index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
6,642
|
Tasha-Carty-220/asvs
|
refs/heads/master
|
/help/urls.py
|
from django.conf.urls import url
from .views import helping
urlpatterns = [
url(r'(?P<category>\d+)', helping, name="help"),
]
|
{"/projects/urls.py": ["/projects/views.py"]}
|
6,643
|
Tasha-Carty-220/asvs
|
refs/heads/master
|
/home/urls.py
|
from django.conf.urls import url
from .views import home_page
urlpatterns = [
url(r'^$', home_page, name="home"),
]
|
{"/projects/urls.py": ["/projects/views.py"]}
|
6,653
|
samueloh17/Segementacion-de-area-especifica-en-cerebro-
|
refs/heads/main
|
/kmenas.py
|
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 11 09:51:41 2021
@author: PC
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage import morphology, feature,io,color
from crecimiento_de_regiones import crecimiento
plt.close('all')
im = cv2.imread('Brain.png')
gris_o = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
im2 = im.reshape((-1,3))
im2 = np.float32(im2)
criterio = (cv2.TermCriteria_EPS + cv2.TERM_CRITERIA_MAX_ITER,10,1 )
k = 4
intentos = 10
ret, label, center = cv2.kmeans(im2, k, None, criterio, intentos, cv2.KMEANS_PP_CENTERS)
center = np.uint8(center)
rescale = center[label.flatten()]
rescaleF = rescale.reshape((im.shape))
gray = cv2.cvtColor(rescaleF, cv2.COLOR_BGR2GRAY)
plt.figure(1)
plt.imshow(gray, cmap = 'gray')
plt.axis('off')
estructure = morphology.disk(4.5)
open_image = morphology.opening(gray,estructure)
segmento = crecimiento(open_image)
imagen_f = segmento * gris_o
plt.figure('f')
plt.axis('off')
plt.imshow(imagen_f , cmap = 'gray')
'''
plt.figure(2)
plt.imshow(open_image, cmap = 'gray')
plt.axis('off')
binario = (open_image > 183)
binario2 = binario * gris_o
edge = feature.canny(binario2,sigma = 2)
plt.figure(3)
plt.imshow(binario2, cmap = 'gray')
plt.axis('off')
salida = (edge * 255) + gris_o
plt.figure(4)
plt.imshow(salida, cmap = 'gray')
plt.axis('off')
'''
|
{"/kmenas.py": ["/crecimiento_de_regiones.py"]}
|
6,654
|
samueloh17/Segementacion-de-area-especifica-en-cerebro-
|
refs/heads/main
|
/crecimiento_de_regiones.py
|
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 6 15:05:43 2021
@author: Samuel OH
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import color, io, morphology
#CRECIMIENTO DE REGIÓN
#MORFOLOGÍA SE REFIERE A LA DILATACIÓN, EROCIÓN DE UNA IMAGEN
#####################CARGAR__LAS__IMAGENES###############
'''imagen = io.imread('29.jpg')
gris = color.rgb2gray(imagen)*255
#########################MOSTRAR___IMAGENES#################
plt.figure(1)
plt.title('IMAGEN ORIGINAL')
plt.axis('off')
plt.imshow(imagen)
plt.figure(2)
plt.title('IMAGEN ESCALA DE GRISES')
plt.axis('off')
plt.imshow(gris, cmap = 'gray')
plt.ion() #LA FUNCIÓN ION REFIERE A INTERACTIVE ON
#####################INICIO__DEL__METODO################
tolerancia = 15 #ESTE VALOR NO DICE QUE SI EL PIXEL VECINO CON UNA VALOR +- 15, EL PIXEL SE PARECE AL PIXEL DEL CENTRO
posicion = np.int32(plt.ginput(0,0)) #SE SOLICITARIA AL USUARIO DONDE COLOCAR LA SEMILLA DE LA IMAGEN
filas , columnas = gris.shape
phi = np.zeros((filas,columnas ),dtype = np.byte) #ESTA VARIABLE NOS SIRVE COMO UNA GUÍA PARA DETENER LA EXPANCIÓN, DE MODO QUE EL PHI NUEVO Y EL PHI OLD SEAN IGUALES ESTA DEBERA PARAR
phiOld = np.zeros ((filas,columnas ), dtype = np.byte)
phi[posicion[:,1], posicion[:,0]] = 1
pixeles = gris[posicion[:,1], posicion[:,0]]
promedio = np.mean(pixeles)
while( np.sum(phiOld) != np.sum(phi) ):
plt.cla()
phiOld = np.copy(phi)
bordes = morphology.binary_dilation(phi) - phi #SOLO SE QUEDAN LOS PIXELES QUE FUERON AUMENTADOS
newPos = np.argwhere(bordes)#EL ARGUMENTO DE LOS BORDES
newPix = gris[newPos[:,0], newPos[:,1]] #SE GUARDAN LOS VALORES DE LOS PIXELES EXPANDIDOS
compara = list(np.logical_and([newPix > promedio - tolerancia], [newPix < promedio + tolerancia])) #SE REALIZA UNA COMPARACIÓN CON LOS VALORES EXPANDIDOS CON EL USO DEL PRIMEDIO Y LA TOLERANCIA
datos = newPos[compara] #AHORA SE GUARDAN LOS VALORES QUE CUMPLIERON LA COMPARATIVA
phi[ datos[:,0], datos[:,1] ] = 1 #AQUI EN PHI SE COLOCA UN 1 EN LAS POSICIONES QUE FUERON GUARDADAS
plt.imshow(phi, cmap = 'gray')
plt.pause(0.01)
plt.figure(2)
plt.axis('off')
plt.imshow(gris, cmap = 'gray')
plt.show()
plt.figure(3)
plt.axis('off')
plt.imshow(phi, cmap = 'gray')
plt.show()
im3D = np.zeros((filas,columnas,10))
im3D[:,:,0] = phi
plt.figure(4)
plt.imshow(im3D[:,:,0],cmap = 'gray' )
plt.imshow()'''
def crecimiento (gris):
plt.figure(2)
plt.title('IMAGEN ESCALA DE GRISES')
plt.axis('off')
plt.imshow(gris, cmap = 'gray')
plt.ion() #LA FUNCIÓN ION REFIERE A INTERACTIVE ON
tolerancia = 15 #ESTE VALOR NO DICE QUE SI EL PIXEL VECINO CON UNA VALOR +- 15, EL PIXEL SE PARECE AL PIXEL DEL CENTRO
posicion = np.int32(plt.ginput(0,0)) #SE SOLICITARIA AL USUARIO DONDE COLOCAR LA SEMILLA DE LA IMAGEN
filas , columnas = gris.shape
phi = np.zeros((filas,columnas ),dtype = np.byte) #ESTA VARIABLE NOS SIRVE COMO UNA GUÍA PARA DETENER LA EXPANCIÓN, DE MODO QUE EL PHI NUEVO Y EL PHI OLD SEAN IGUALES ESTA DEBERA PARAR
phiOld = np.zeros ((filas,columnas ), dtype = np.byte)
phi[posicion[:,1], posicion[:,0]] = 1
pixeles = gris[posicion[:,1], posicion[:,0]]
promedio = np.mean(pixeles)
while( np.sum(phiOld) != np.sum(phi) ):
plt.cla()
phiOld = np.copy(phi)
bordes = morphology.binary_dilation(phi) - phi #SOLO SE QUEDAN LOS PIXELES QUE FUERON AUMENTADOS
newPos = np.argwhere(bordes)#EL ARGUMENTO DE LOS BORDES
newPix = gris[newPos[:,0], newPos[:,1]] #SE GUARDAN LOS VALORES DE LOS PIXELES EXPANDIDOS
compara = list(np.logical_and([newPix > promedio - tolerancia], [newPix < promedio + tolerancia])) #SE REALIZA UNA COMPARACIÓN CON LOS VALORES EXPANDIDOS CON EL USO DEL PRIMEDIO Y LA TOLERANCIA
datos = newPos[compara] #AHORA SE GUARDAN LOS VALORES QUE CUMPLIERON LA COMPARATIVA
phi[ datos[:,0], datos[:,1] ] = 1 #AQUI EN PHI SE COLOCA UN 1 EN LAS POSICIONES QUE FUERON GUARDADAS
plt.imshow(phi, cmap = 'gray')
plt.pause(0.01)
return phi
'''
imagen = io.imread('27.jpg')
gris = color.rgb2gray(imagen)*255
imagen_procesada = crecimiento(gris)'''
|
{"/kmenas.py": ["/crecimiento_de_regiones.py"]}
|
6,655
|
Abhinav-Git19/FiniteStateMachine
|
refs/heads/main
|
/models/intermeidate_state.py
|
from models.state import State
class IntermediateState(State):
def __init__(self,name):
super(IntermediateState, self).__init__(name)
self.transitions=[]
|
{"/models/intermeidate_state.py": ["/models/state.py"], "/models/start_state.py": ["/models/state.py"], "/models/transition.py": ["/models/state.py"], "/models/end_state.py": ["/models/state.py"], "/fsm.py": ["/services/fsm_service.py", "/services/state_trans_service.py"], "/services/state_trans_service.py": ["/models/end_state.py", "/models/start_state.py", "/models/state.py", "/models/transition.py", "/repository/state_repository.py", "/models/intermeidate_state.py"], "/repository/state_repository.py": ["/models/start_state.py", "/models/state.py"], "/services/fsm_service.py": ["/models/current_state.py", "/models/end_state.py", "/repository/state_repository.py"]}
|
6,656
|
Abhinav-Git19/FiniteStateMachine
|
refs/heads/main
|
/models/current_state.py
|
class CurrentState:
def __init__(self):
self.cur_state=None
|
{"/models/intermeidate_state.py": ["/models/state.py"], "/models/start_state.py": ["/models/state.py"], "/models/transition.py": ["/models/state.py"], "/models/end_state.py": ["/models/state.py"], "/fsm.py": ["/services/fsm_service.py", "/services/state_trans_service.py"], "/services/state_trans_service.py": ["/models/end_state.py", "/models/start_state.py", "/models/state.py", "/models/transition.py", "/repository/state_repository.py", "/models/intermeidate_state.py"], "/repository/state_repository.py": ["/models/start_state.py", "/models/state.py"], "/services/fsm_service.py": ["/models/current_state.py", "/models/end_state.py", "/repository/state_repository.py"]}
|
6,657
|
Abhinav-Git19/FiniteStateMachine
|
refs/heads/main
|
/models/start_state.py
|
from models.state import State
class StartState(State):
def __init__(self,name):
super(StartState, self).__init__(name)
self.transitions=[]
|
{"/models/intermeidate_state.py": ["/models/state.py"], "/models/start_state.py": ["/models/state.py"], "/models/transition.py": ["/models/state.py"], "/models/end_state.py": ["/models/state.py"], "/fsm.py": ["/services/fsm_service.py", "/services/state_trans_service.py"], "/services/state_trans_service.py": ["/models/end_state.py", "/models/start_state.py", "/models/state.py", "/models/transition.py", "/repository/state_repository.py", "/models/intermeidate_state.py"], "/repository/state_repository.py": ["/models/start_state.py", "/models/state.py"], "/services/fsm_service.py": ["/models/current_state.py", "/models/end_state.py", "/repository/state_repository.py"]}
|
6,658
|
Abhinav-Git19/FiniteStateMachine
|
refs/heads/main
|
/models/transition.py
|
import uuid
from models.state import State
class Transition:
def __init__(self,name,state):
self.id=uuid.uuid1().hex
self.name=name
self.next_state : State=state
|
{"/models/intermeidate_state.py": ["/models/state.py"], "/models/start_state.py": ["/models/state.py"], "/models/transition.py": ["/models/state.py"], "/models/end_state.py": ["/models/state.py"], "/fsm.py": ["/services/fsm_service.py", "/services/state_trans_service.py"], "/services/state_trans_service.py": ["/models/end_state.py", "/models/start_state.py", "/models/state.py", "/models/transition.py", "/repository/state_repository.py", "/models/intermeidate_state.py"], "/repository/state_repository.py": ["/models/start_state.py", "/models/state.py"], "/services/fsm_service.py": ["/models/current_state.py", "/models/end_state.py", "/repository/state_repository.py"]}
|
6,659
|
Abhinav-Git19/FiniteStateMachine
|
refs/heads/main
|
/models/end_state.py
|
from models.state import State
class EndState(State):
def __init__(self,name):
super(EndState, self).__init__(name)
# End state will have no transitions
|
{"/models/intermeidate_state.py": ["/models/state.py"], "/models/start_state.py": ["/models/state.py"], "/models/transition.py": ["/models/state.py"], "/models/end_state.py": ["/models/state.py"], "/fsm.py": ["/services/fsm_service.py", "/services/state_trans_service.py"], "/services/state_trans_service.py": ["/models/end_state.py", "/models/start_state.py", "/models/state.py", "/models/transition.py", "/repository/state_repository.py", "/models/intermeidate_state.py"], "/repository/state_repository.py": ["/models/start_state.py", "/models/state.py"], "/services/fsm_service.py": ["/models/current_state.py", "/models/end_state.py", "/repository/state_repository.py"]}
|
6,660
|
Abhinav-Git19/FiniteStateMachine
|
refs/heads/main
|
/fsm.py
|
from services.fsm_service import FSMService
from services.state_trans_service import StateTransService
def main():
state_trans_service = StateTransService()
fsm_service = FSMService()
fsm_commands =['begin_fsm','next_state','enable_notification_by_state','enable_all_notifications','curent_state']
state_commands =['add_start_state','add_state','end_state','add_transition']
while True:
cmdargs = input('\nEnter Command\n')
if cmdargs=='EXIT':
print('Exiting FSM...')
exit()
base_cmd = cmdargs.split()[0]
if base_cmd in fsm_commands:
getattr(fsm_service,base_cmd)(cmdargs)
elif base_cmd in state_commands:
getattr(state_trans_service,base_cmd)(cmdargs)
else:
print('Invalid Command')
if __name__ == '__main__':
main()
|
{"/models/intermeidate_state.py": ["/models/state.py"], "/models/start_state.py": ["/models/state.py"], "/models/transition.py": ["/models/state.py"], "/models/end_state.py": ["/models/state.py"], "/fsm.py": ["/services/fsm_service.py", "/services/state_trans_service.py"], "/services/state_trans_service.py": ["/models/end_state.py", "/models/start_state.py", "/models/state.py", "/models/transition.py", "/repository/state_repository.py", "/models/intermeidate_state.py"], "/repository/state_repository.py": ["/models/start_state.py", "/models/state.py"], "/services/fsm_service.py": ["/models/current_state.py", "/models/end_state.py", "/repository/state_repository.py"]}
|
6,661
|
Abhinav-Git19/FiniteStateMachine
|
refs/heads/main
|
/services/state_trans_service.py
|
from typing import List
from models.end_state import EndState
from models.start_state import StartState
from models.state import State
from models.transition import Transition
from repository.state_repository import StateRepository
from models.intermeidate_state import IntermediateState
class StateTransService:
state_repository = StateRepository()
def add_start_state(self,cmdargs):
cmdlist = cmdargs.split()
if len(cmdlist)!=2:
print('Invalid Command')
return
name = cmdlist[1]
state_list : List[State] = self.state_repository.get_all_states()
for state in state_list:
if isinstance(state,StartState):
print('Start State already present cannot add multiple start state')
return
start_state = StartState(name)
self.state_repository.add_state(start_state)
print('Start State added')
def add_state(self, cmdargs):
cmdlist = cmdargs.split()
if len(cmdlist) != 2:
print('Invalid Add State Command')
return
name: str = cmdlist[1]
state_obj = self.state_repository.get_state_by_name(name)
if state_obj is not None:
print('State already present')
return
new_state = IntermediateState(name)
self.state_repository.add_state(new_state)
print('Added State {}'.format(new_state.id))
def end_state(self,cmdargs):
cmdlist = cmdargs.split()
if len(cmdlist) != 2:
print('Invalid End State Command')
return
name = cmdlist[1]
state_obj = self.state_repository.get_state_by_name(name)
if state_obj is not None:
print('State already present')
return
end_state = EndState(name)
self.state_repository.add_state(end_state)
print('End State {} Added'.format(end_state.id))
def add_transition(self,cmdargs):
cmdlist = cmdargs.split()
if len(cmdlist) != 4:
print('Invalid Transition State Command')
return
trans_name,first_state_name,next_state_name = cmdlist[1:]
first_state= self.state_repository.get_state_by_name(first_state_name)
second_state = self.state_repository.get_state_by_name(next_state_name)
if first_state is None or second_state is None:
print('Invalid Transition')
return
if isinstance(first_state,EndState):
print('First state cannot be end state')
return
transition = Transition(trans_name,second_state)
first_state.transitions.append(transition)
print('Transtion {} added'.format(transition))
|
{"/models/intermeidate_state.py": ["/models/state.py"], "/models/start_state.py": ["/models/state.py"], "/models/transition.py": ["/models/state.py"], "/models/end_state.py": ["/models/state.py"], "/fsm.py": ["/services/fsm_service.py", "/services/state_trans_service.py"], "/services/state_trans_service.py": ["/models/end_state.py", "/models/start_state.py", "/models/state.py", "/models/transition.py", "/repository/state_repository.py", "/models/intermeidate_state.py"], "/repository/state_repository.py": ["/models/start_state.py", "/models/state.py"], "/services/fsm_service.py": ["/models/current_state.py", "/models/end_state.py", "/repository/state_repository.py"]}
|
6,662
|
Abhinav-Git19/FiniteStateMachine
|
refs/heads/main
|
/models/state.py
|
import uuid
class State:
def __init__(self,name):
self.id=uuid.uuid1().hex
self.name=name
self.notification : bool =False
|
{"/models/intermeidate_state.py": ["/models/state.py"], "/models/start_state.py": ["/models/state.py"], "/models/transition.py": ["/models/state.py"], "/models/end_state.py": ["/models/state.py"], "/fsm.py": ["/services/fsm_service.py", "/services/state_trans_service.py"], "/services/state_trans_service.py": ["/models/end_state.py", "/models/start_state.py", "/models/state.py", "/models/transition.py", "/repository/state_repository.py", "/models/intermeidate_state.py"], "/repository/state_repository.py": ["/models/start_state.py", "/models/state.py"], "/services/fsm_service.py": ["/models/current_state.py", "/models/end_state.py", "/repository/state_repository.py"]}
|
6,663
|
Abhinav-Git19/FiniteStateMachine
|
refs/heads/main
|
/repository/state_repository.py
|
from typing import Dict, List
from models.start_state import StartState
from models.state import State
class StateRepository:
state_repo: Dict[str, State] = {}
def get_state_by_name(self, name) -> State:
return self.state_repo.setdefault(name, None)
def add_state(self, state_obj: State):
self.state_repo[state_obj.name] = state_obj
def get_all_states(self) -> List[State]:
return list(self.state_repo.values())
def get_start_state(self) ->StartState:
for key,val in self.state_repo.items():
if isinstance(val,StartState):
return val
return None
|
{"/models/intermeidate_state.py": ["/models/state.py"], "/models/start_state.py": ["/models/state.py"], "/models/transition.py": ["/models/state.py"], "/models/end_state.py": ["/models/state.py"], "/fsm.py": ["/services/fsm_service.py", "/services/state_trans_service.py"], "/services/state_trans_service.py": ["/models/end_state.py", "/models/start_state.py", "/models/state.py", "/models/transition.py", "/repository/state_repository.py", "/models/intermeidate_state.py"], "/repository/state_repository.py": ["/models/start_state.py", "/models/state.py"], "/services/fsm_service.py": ["/models/current_state.py", "/models/end_state.py", "/repository/state_repository.py"]}
|
6,664
|
Abhinav-Git19/FiniteStateMachine
|
refs/heads/main
|
/services/fsm_service.py
|
from models.current_state import CurrentState
from models.end_state import EndState
from repository.state_repository import StateRepository
class FSMService:
state_repository = StateRepository()
current_state = CurrentState()
def begin_fsm(self,cmdargs):
cmdlist = cmdargs.split()
if len(cmdlist) != 1:
print('invalid begin command')
return
start_state =self.state_repository.get_start_state()
if start_state is None:
print('StartState Not Specified')
return
self.current_state.cur_state=start_state
def curent_state(self,cmdargs):
cmdlist = cmdargs.split()
if len(cmdlist)!=1:
print('Invalid current state command')
return
if self.current_state.cur_state is None:
print('FSM Not begun yet!')
return
print('Current state {}'.format(self.current_state.cur_state))
def next_state(self,cmdargs):
cmdlist = cmdargs.split()
if len(cmdlist)!=2:
print('invalid next_state command')
return
transition_name = cmdlist[1]
for trans in self.current_state.cur_state.transitions:
if trans.name==transition_name:
self.current_state.cur_state=trans.next_state
if isinstance(self.current_state.cur_state, EndState):
print('End State {} reached'.format(self.current_state.cur_state.name))
if self.current_state.cur_state.notification:
print('State Changed to {}'.format(self.current_state.cur_state.name))
return
print('Transition not found')
def enable_notification_by_state(self,cmdargs):
cmdlist = cmdargs.split()
if len(cmdlist) != 2:
print('invalid notification command')
return
state_name = cmdlist[1]
state = self.state_repository.get_state_by_name(state_name)
if state is None:
print('No such state')
return
state.notification=True
def enable_all_notifications(self,cmdargs):
cmdlist = cmdargs.split()
if len(cmdlist) != 1:
print('invalid all_notification command')
return
state_list = self.state_repository.get_all_states()
for state in state_list:
state.notification=True
|
{"/models/intermeidate_state.py": ["/models/state.py"], "/models/start_state.py": ["/models/state.py"], "/models/transition.py": ["/models/state.py"], "/models/end_state.py": ["/models/state.py"], "/fsm.py": ["/services/fsm_service.py", "/services/state_trans_service.py"], "/services/state_trans_service.py": ["/models/end_state.py", "/models/start_state.py", "/models/state.py", "/models/transition.py", "/repository/state_repository.py", "/models/intermeidate_state.py"], "/repository/state_repository.py": ["/models/start_state.py", "/models/state.py"], "/services/fsm_service.py": ["/models/current_state.py", "/models/end_state.py", "/repository/state_repository.py"]}
|
6,667
|
Vinohith/Lane_Segmentation
|
refs/heads/master
|
/train.py
|
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ModelCheckpoint
from keras.optimizers import Adam, Adadelta
from model_train2 import segmentation_model, segmentation_model2, get_unet, FCN8, segmentation_model3
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
import numpy as np
import cv2
import tensorflow as tf
from keras import backend as K
PATH = '/mnt/data/datasets_extracted/mapillary-vistas-dataset_public_v1.1/'
def getSegmentationArr( path , nClasses , width , height ):
seg_labels = np.zeros(( height , width , nClasses ))
img = cv2.imread(path, 1)
img = cv2.resize(img, ( width , height ))
img = img[:, : , 0]
x = 0
for c in [13,24]:
seg_labels[: , : , x ] = (img == c ).astype(int)
x = x+1
seg_labels[: , : , 2 ] = cv2.bitwise_or(seg_labels[: , : , 0 ]*255, seg_labels[: , : , 1 ]*255, None)
seg_labels[: , : , 2 ] = ~np.array(seg_labels[:, :, 2], np.uint8)/255
return seg_labels
def generator(path_frames, path_masks, batch_size):
j = 0
w = 512
h = 512
directory_img = sorted(os.listdir(path_frames))
directory_mask = sorted(os.listdir(path_masks))
while(1):
images = np.zeros((batch_size, w, h, 3))
masks = np.zeros((batch_size, w, h, 3))
for i in range(j, j+batch_size):
img = cv2.imread(path_frames+'/'+directory_img[i])
img = cv2.resize(img, (w, h))
img = img.reshape(w, h, 3)
images[i-j] = img
mask = getSegmentationArr(path_masks+'/'+directory_mask[i], nClasses=3, width=w, height=h)
masks[i-j] = mask
j = j+batch_size
if (j+batch_size>=len(os.listdir(path_frames))):
j=0
yield images, masks
#mask = getSegmentationArr('/mnt/data/datasets_extracted/mapillary-vistas-dataset_public_v1.1/training/instances/_0P04ZWQtMtPMwx3lgLdWA.png', 3, 512, 512)
model = segmentation_model3(input_shape = (512, 512, 3))
model.summary()
NO_OF_TRAINING_IMAGES = len(os.listdir(PATH+'training/images'))
NO_OF_VAL_IMAGES = len(os.listdir(PATH+'validation/images'))
NO_OF_EPOCHS = 50
BATCH_SIZE = 8
n_classes = 3
filepath="final-smaller(large_checkpoint).h5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='auto')
callbacks_list = [checkpoint]
adadelta=Adadelta(lr=1.0, rho=0.95, epsilon=None, decay=0.0)
model.compile(optimizer=adadelta, loss='categorical_crossentropy',metrics=['accuracy'])
#/mnt/data/datasets_extracted/mapillary-vistas-dataset_public_v1.1/training/images
#/mnt/data/datasets_extracted/mapillary-vistas-dataset_public_v1.1/training/instances
#/mnt/data/datasets_extracted/mapillary-vistas-dataset_public_v1.1/validation/images
#/mnt/data/datasets_extracted/mapillary-vistas-dataset_public_v1.1/validation/instances
model.fit_generator(generator(PATH+'training/images', PATH+'training/instances', BATCH_SIZE), epochs=NO_OF_EPOCHS,
steps_per_epoch=(NO_OF_TRAINING_IMAGES//BATCH_SIZE),
validation_data=generator(PATH+'validation/images', PATH+'validation/instances', BATCH_SIZE),
validation_steps=(NO_OF_VAL_IMAGES//BATCH_SIZE),
callbacks=callbacks_list)
model.save('final-smaller(large_3_class_512).h5')
|
{"/train.py": ["/model_train2.py"]}
|
6,668
|
Vinohith/Lane_Segmentation
|
refs/heads/master
|
/model_train2.py
|
from keras.layers import Input, Conv2D, BatchNormalization, MaxPooling2D, Activation, Layer, Conv2DTranspose, Dropout, Add
from keras.models import Model
from keras.activations import relu, softmax
from keras.optimizers import SGD
from keras import backend as K
from keras.callbacks import ModelCheckpoint
from keras.layers.merge import concatenate, add
class MaxPoolingWithArgmax2D(Layer):
def __init__(
self,
pool_size=(2, 2),
strides=(2, 2),
padding='same',
**kwargs):
super(MaxPoolingWithArgmax2D, self).__init__(**kwargs)
self.padding = padding
self.pool_size = pool_size
self.strides = strides
def call(self, inputs, **kwargs):
padding = self.padding
pool_size = self.pool_size
strides = self.strides
if K.backend() == 'tensorflow':
ksize = [1, pool_size[0], pool_size[1], 1]
padding = padding.upper()
strides = [1, strides[0], strides[1], 1]
output, argmax = K.tf.nn.max_pool_with_argmax(
inputs,
ksize=ksize,
strides=strides,
padding=padding)
else:
errmsg = '{} backend is not supported for layer {}'.format(
K.backend(), type(self).__name__)
raise NotImplementedError(errmsg)
argmax = K.cast(argmax, K.floatx())
return [output, argmax]
def compute_output_shape(self, input_shape):
ratio = (1, 2, 2, 1)
output_shape = [
dim//ratio[idx]
if dim is not None else None
for idx, dim in enumerate(input_shape)]
output_shape = tuple(output_shape)
return [output_shape, output_shape]
def compute_mask(self, inputs, mask=None):
return 2 * [None]
class MaxUnpooling2D(Layer):
def __init__(self, size=(2, 2), **kwargs):
super(MaxUnpooling2D, self).__init__(**kwargs)
self.size = size
def call(self, inputs, output_shape=None):
updates, mask = inputs[0], inputs[1]
with K.tf.variable_scope(self.name):
mask = K.cast(mask, 'int32')
input_shape = K.tf.shape(updates, out_type='int32')
# calculation new shape
if output_shape is None:
output_shape = (
input_shape[0],
input_shape[1]*self.size[0],
input_shape[2]*self.size[1],
input_shape[3])
self.output_shape1 = output_shape
# calculation indices for batch, height, width and feature maps
one_like_mask = K.ones_like(mask, dtype='int32')
batch_shape = K.concatenate(
[[input_shape[0]], [1], [1], [1]],
axis=0)
batch_range = K.reshape(
K.tf.range(output_shape[0], dtype='int32'),
shape=batch_shape)
b = one_like_mask * batch_range
y = mask // (output_shape[2] * output_shape[3])
x = (mask // output_shape[3]) % output_shape[2]
feature_range = K.tf.range(output_shape[3], dtype='int32')
f = one_like_mask * feature_range
# transpose indices & reshape update values to one dimension
updates_size = K.tf.size(updates)
indices = K.transpose(K.reshape(
K.stack([b, y, x, f]),
[4, updates_size]))
values = K.reshape(updates, [updates_size])
ret = K.tf.scatter_nd(indices, values, output_shape)
return ret
def compute_output_shape(self, input_shape):
mask_shape = input_shape[1]
return (
mask_shape[0],
mask_shape[1]*self.size[0],
mask_shape[2]*self.size[1],
mask_shape[3]
)
def segmentation_model(input_shape):
#input_shape = (224, 224, 3)
pool_size = (2,2)
inputs = Input(shape=input_shape)
layer1 = BatchNormalization()(inputs)
# Encoder
# 1
conv1 = Conv2D(16, (3,3), padding='same', kernel_initializer='he_normal')(layer1)
conv1 = BatchNormalization()(conv1)
conv1 = Activation('relu')(conv1)
conv2 = Conv2D(16, (3,3), padding='same', kernel_initializer='he_normal')(conv1)
conv2 = BatchNormalization()(conv2)
conv2 = Activation('relu')(conv2)
pool1, mask1 = MaxPoolingWithArgmax2D(pool_size)(conv2)
drop1 = Dropout(0.2)(pool1)
# 2
conv3 = Conv2D(32, (3,3), padding='same', kernel_initializer='he_normal')(drop1)
conv3 = BatchNormalization()(conv3)
conv3 = Activation('relu')(conv3)
conv4 = Conv2D(32, (3,3), padding='same', kernel_initializer='he_normal')(conv3)
conv4 = BatchNormalization()(conv4)
conv4 = Activation('relu')(conv4)
pool2, mask2 = MaxPoolingWithArgmax2D(pool_size)(conv4)
drop2 = Dropout(0.2)(pool2)
# 3
conv5 = Conv2D(64, (3,3), padding='same', kernel_initializer='he_normal')(drop2)
conv5 = BatchNormalization()(conv5)
conv5 = Activation('relu')(conv5)
conv6 = Conv2D(64, (3,3), padding='same', kernel_initializer='he_normal')(conv5)
conv6 = BatchNormalization()(conv6)
conv6 = Activation('relu')(conv6)
conv7 = Conv2D(64, (3,3), padding='same', kernel_initializer='he_normal')(conv6)
conv7 = BatchNormalization()(conv7)
conv7 = Activation('relu')(conv7)
pool3, mask3 = MaxPoolingWithArgmax2D(pool_size)(conv7)
drop3 = Dropout(0.2)(pool3)
# 4
conv8 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(drop3)
conv8 = BatchNormalization()(conv8)
conv8 = Activation('relu')(conv8)
conv9 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(conv8)
conv9 = BatchNormalization()(conv9)
conv9 = Activation('relu')(conv9)
conv10 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(conv9)
conv10 = BatchNormalization()(conv10)
conv10 = Activation('relu')(conv10)
pool4, mask4 = MaxPoolingWithArgmax2D(pool_size)(conv10)
drop4 = Dropout(0.2)(pool4)
# 5
conv11 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(drop4)
conv11 = BatchNormalization()(conv11)
conv11 = Activation('relu')(conv11)
conv12 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(conv11)
conv12 = BatchNormalization()(conv12)
conv12 = Activation('relu')(conv12)
conv13 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(conv12)
conv13 = BatchNormalization()(conv13)
conv13 = Activation('relu')(conv13)
pool5, mask5 = MaxPoolingWithArgmax2D(pool_size)(conv13)
drop5 = Dropout(0.2)(pool5)
# Decoder
# 5
unpool5 = MaxUnpooling2D(pool_size)([drop5, mask5])
unconv13 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(unpool5)
unconv13 = BatchNormalization()(unconv13)
unconv13 = Activation('relu')(unconv13)
unconv12 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(unconv13)
unconv12 = BatchNormalization()(unconv12)
unconv12 = Activation('relu')(unconv12)
unconv11 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(unconv12)
unconv11 = BatchNormalization()(unconv11)
unconv11 = Activation('relu')(unconv11)
drop6 = Dropout(0.2)(unconv11)
# 4
unpool4 = MaxUnpooling2D(pool_size)([drop6, mask4])
unconv10 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(unpool4)
unconv10 = BatchNormalization()(unconv10)
unconv10 = Activation('relu')(unconv10)
unconv9 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(unconv10)
unconv9 = BatchNormalization()(unconv9)
unconv9 = Activation('relu')(unconv9)
unconv8 = Conv2D(64, (3,3), padding='same', kernel_initializer='he_normal')(unconv9)
unconv8 = BatchNormalization()(unconv8)
unconv8 = Activation('relu')(unconv8)
drop7 = Dropout(0.2)(unconv8)
# 3
unpool3 = MaxUnpooling2D(pool_size)([drop7, mask3])
unconv7 = Conv2D(64, (3,3), padding='same', kernel_initializer='he_normal')(unpool3)
unconv7 = BatchNormalization()(unconv7)
unconv7 = Activation('relu')(unconv7)
unconv6 = Conv2D(64, (3,3), padding='same', kernel_initializer='he_normal')(unconv7)
unconv6 = BatchNormalization()(unconv6)
unconv6 = Activation('relu')(unconv6)
unconv5 = Conv2D(32, (3,3), padding='same', kernel_initializer='he_normal')(unconv6)
unconv5 = BatchNormalization()(unconv5)
unconv5 = Activation('relu')(unconv5)
drop8 = Dropout(0.2)(unconv5)
# 2
unpool2 = MaxUnpooling2D(pool_size)([drop8, mask2])
unconv4 = Conv2D(32, (3,3), padding='same', kernel_initializer='he_normal')(unpool2)
unconv4 = BatchNormalization()(unconv4)
unconv4 = Activation('relu')(unconv4)
unconv3 = Conv2D(16, (3,3), padding='same', kernel_initializer='he_normal')(unconv4)
unconv3 = BatchNormalization()(unconv3)
unconv3 = Activation('relu')(unconv3)
drop9 = Dropout(0.2)(unconv3)
# 1
unpool1 = MaxUnpooling2D(pool_size)([drop9, mask1])
unconv2 = Conv2D(16, (3,3), padding='same', kernel_initializer='he_normal')(unpool1)
unconv2 = BatchNormalization()(unconv2)
unconv2 = Activation('relu')(unconv2)
unconv1 = Conv2D(1, (3,3), padding='same', kernel_initializer='he_normal')(unconv2)
unconv1 = BatchNormalization()(unconv1)
unconv1 = Activation('sigmoid')(unconv1)
model = Model(input=inputs, output=unconv1)
return model
def segmentation_model2(input_shape):
#input_shape = (224, 224, 3)
pool_size = (2,2)
inputs = Input(shape=input_shape)
layer1 = BatchNormalization()(inputs)
# Encoder
# 1
conv1 = Conv2D(32, (3,3), padding='same')(layer1)
conv1 = BatchNormalization()(conv1)
conv1 = Activation('relu')(conv1)
conv2 = Conv2D(32, (3,3), padding='same')(conv1)
conv2 = BatchNormalization()(conv2)
conv2 = Activation('relu')(conv2)
pool1, mask1 = MaxPoolingWithArgmax2D(pool_size)(conv2)
drop1 = Dropout(0.2)(pool1)
# 2
conv3 = Conv2D(64, (3,3), padding='same')(drop1)
conv3 = BatchNormalization()(conv3)
conv3 = Activation('relu')(conv3)
conv4 = Conv2D(64, (3,3), padding='same')(conv3)
conv4 = BatchNormalization()(conv4)
conv4 = Activation('relu')(conv4)
pool2, mask2 = MaxPoolingWithArgmax2D(pool_size)(conv4)
drop2 = Dropout(0.2)(pool2)
# 3
conv5 = Conv2D(128, (3,3), padding='same')(drop2)
conv5 = BatchNormalization()(conv5)
conv5 = Activation('relu')(conv5)
conv6 = Conv2D(128, (3,3), padding='same')(conv5)
conv6 = BatchNormalization()(conv6)
conv6 = Activation('relu')(conv6)
conv7 = Conv2D(128, (3,3), padding='same')(conv6)
conv7 = BatchNormalization()(conv7)
conv7 = Activation('relu')(conv7)
pool3, mask3 = MaxPoolingWithArgmax2D(pool_size)(conv7)
drop3 = Dropout(0.2)(pool3)
# 4
conv8 = Conv2D(256, (3,3), padding='same')(drop3)
conv8 = BatchNormalization()(conv8)
conv8 = Activation('relu')(conv8)
conv9 = Conv2D(256, (3,3), padding='same')(conv8)
conv9 = BatchNormalization()(conv9)
conv9 = Activation('relu')(conv9)
conv10 = Conv2D(256, (3,3), padding='same')(conv9)
conv10 = BatchNormalization()(conv10)
conv10 = Activation('relu')(conv10)
pool4, mask4 = MaxPoolingWithArgmax2D(pool_size)(conv10)
drop4 = Dropout(0.2)(pool4)
# 5
conv11 = Conv2D(256, (3,3), padding='same')(drop4)
conv11 = BatchNormalization()(conv11)
conv11 = Activation('relu')(conv11)
conv12 = Conv2D(256, (3,3), padding='same')(conv11)
conv12 = BatchNormalization()(conv12)
conv12 = Activation('relu')(conv12)
conv13 = Conv2D(256, (3,3), padding='same')(conv12)
conv13 = BatchNormalization()(conv13)
conv13 = Activation('relu')(conv13)
pool5, mask5 = MaxPoolingWithArgmax2D(pool_size)(conv13)
drop5 = Dropout(0.2)(pool5)
# Decoder
# 5
unpool5 = MaxUnpooling2D(pool_size)([drop5, mask5])
con1 = concatenate([unpool5, conv13])
unconv13 = Conv2D(256, (3,3), padding='same')(con1)
unconv13 = BatchNormalization()(unconv13)
unconv13 = Activation('relu')(unconv13)
unconv12 = Conv2D(256, (3,3), padding='same')(unconv13)
unconv12 = BatchNormalization()(unconv12)
unconv12 = Activation('relu')(unconv12)
unconv11 = Conv2D(256, (3,3), padding='same')(unconv12)
unconv11 = BatchNormalization()(unconv11)
unconv11 = Activation('relu')(unconv11)
drop6 = Dropout(0.2)(unconv11)
# 4
unpool4 = MaxUnpooling2D(pool_size)([drop6, mask4])
con2 = concatenate([unpool4, conv10])
unconv10 = Conv2D(256, (3,3), padding='same')(con2)
unconv10 = BatchNormalization()(unconv10)
unconv10 = Activation('relu')(unconv10)
unconv9 = Conv2D(256, (3,3), padding='same')(unconv10)
unconv9 = BatchNormalization()(unconv9)
unconv9 = Activation('relu')(unconv9)
unconv8 = Conv2D(128, (3,3), padding='same')(unconv9)
unconv8 = BatchNormalization()(unconv8)
unconv8 = Activation('relu')(unconv8)
drop7 = Dropout(0.2)(unconv8)
# 3
unpool3 = MaxUnpooling2D(pool_size)([drop7, mask3])
con3 = concatenate([unpool3, conv7])
unconv7 = Conv2D(128, (3,3), padding='same')(con3)
unconv7 = BatchNormalization()(unconv7)
unconv7 = Activation('relu')(unconv7)
unconv6 = Conv2D(128, (3,3), padding='same')(unconv7)
unconv6 = BatchNormalization()(unconv6)
unconv6 = Activation('relu')(unconv6)
unconv5 = Conv2D(64, (3,3), padding='same')(unconv6)
unconv5 = BatchNormalization()(unconv5)
unconv5 = Activation('relu')(unconv5)
drop8 = Dropout(0.2)(unconv5)
# 2
unpool2 = MaxUnpooling2D(pool_size)([drop8, mask2])
con4 = concatenate([unpool2, conv4])
unconv4 = Conv2D(64, (3,3), padding='same')(con4)
unconv4 = BatchNormalization()(unconv4)
unconv4 = Activation('relu')(unconv4)
unconv3 = Conv2D(32, (3,3), padding='same')(unconv4)
unconv3 = BatchNormalization()(unconv3)
unconv3 = Activation('relu')(unconv3)
drop9 = Dropout(0.2)(unconv3)
# 1
unpool1 = MaxUnpooling2D(pool_size)([drop9, mask1])
con5 = concatenate([unpool1, conv2])
unconv2 = Conv2D(32, (3,3), padding='same')(unpool1)
unconv2 = BatchNormalization()(unconv2)
unconv2 = Activation('relu')(unconv2)
unconv1 = Conv2D(1, (3,3), padding='same')(unconv2)
unconv1 = BatchNormalization()(unconv1)
unconv1 = Activation('sigmoid')(unconv1)
model = Model(input=inputs, output=unconv1)
return model
def conv2d_block(input_tensor, n_filters, kernel_size = 3, batchnorm = True):
"""Function to add 2 convolutional layers with the parameters passed to it"""
# first layer
x = Conv2D(filters = n_filters, kernel_size = (kernel_size, kernel_size),\
kernel_initializer = 'he_normal', padding = 'same')(input_tensor)
if batchnorm:
x = BatchNormalization()(x)
x = Activation('relu')(x)
# second layer
x = Conv2D(filters = n_filters, kernel_size = (kernel_size, kernel_size),\
kernel_initializer = 'he_normal', padding = 'same')(input_tensor)
if batchnorm:
x = BatchNormalization()(x)
x = Activation('relu')(x)
return x
def get_unet(input_img_shape, n_filters = 32, dropout = 0.2, batchnorm = True):
"""Function to define the UNET Model"""
input_img = Input(shape=input_img_shape)
# Contracting Path
c1 = conv2d_block(input_img, n_filters * 1, kernel_size = 3, batchnorm = batchnorm)
p1 = MaxPooling2D((2, 2))(c1)
p1 = Dropout(dropout)(p1)
c2 = conv2d_block(p1, n_filters * 2, kernel_size = 3, batchnorm = batchnorm)
p2 = MaxPooling2D((2, 2))(c2)
p2 = Dropout(dropout)(p2)
c3 = conv2d_block(p2, n_filters * 4, kernel_size = 3, batchnorm = batchnorm)
p3 = MaxPooling2D((2, 2))(c3)
p3 = Dropout(dropout)(p3)
c4 = conv2d_block(p3, n_filters * 8, kernel_size = 3, batchnorm = batchnorm)
p4 = MaxPooling2D((2, 2))(c4)
p4 = Dropout(dropout)(p4)
c5 = conv2d_block(p4, n_filters = n_filters * 16, kernel_size = 3, batchnorm = batchnorm)
# Expansive Path
u6 = Conv2DTranspose(n_filters * 8, (3, 3), strides = (2, 2), padding = 'same')(c5)
u6 = concatenate([u6, c4])
u6 = BatchNormalization()(u6)
u6 = Activation('relu')(u6)
u6 = Dropout(dropout)(u6)
c6 = conv2d_block(u6, n_filters * 8, kernel_size = 3, batchnorm = batchnorm)
u7 = Conv2DTranspose(n_filters * 4, (3, 3), strides = (2, 2), padding = 'same')(c6)
u7 = concatenate([u7, c3])
u7 = BatchNormalization()(u7)
u7 = Dropout(dropout)(u7)
c7 = conv2d_block(u7, n_filters * 4, kernel_size = 3, batchnorm = batchnorm)
u8 = Conv2DTranspose(n_filters * 2, (3, 3), strides = (2, 2), padding = 'same')(c7)
u8 = concatenate([u8, c2])
u8 = BatchNormalization()(u8)
u8 = Dropout(dropout)(u8)
c8 = conv2d_block(u8, n_filters * 2, kernel_size = 3, batchnorm = batchnorm)
u9 = Conv2DTranspose(n_filters * 1, (3, 3), strides = (2, 2), padding = 'same')(c8)
u9 = concatenate([u9, c1])
u9 = BatchNormalization()(u9)
u9 = Dropout(dropout)(u9)
c9 = conv2d_block(u9, n_filters * 1, kernel_size = 3, batchnorm = batchnorm)
outputs = Conv2D(1, (1, 1), activation='sigmoid')(c9)
model = Model(inputs=[input_img], outputs=[outputs])
return model
VGG_Weights_path = "/home/beast/Desktop/inthiyaz_segmentation/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5"
def FCN8(nClasses, input_height=224, input_width=224):
## input_height and width must be devisible by 32 because maxpooling with filter size = (2,2) is operated 5 times,
## which makes the input_height and width 2^5 = 32 times smaller
assert input_height % 32 == 0
assert input_width % 32 == 0
IMAGE_ORDERING = "channels_last"
img_input = Input(shape=(input_height, input_width, 3)) ## Assume 224,224,3
## Block 1
x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1', data_format=IMAGE_ORDERING)(
img_input)
x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2', data_format=IMAGE_ORDERING)(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool', data_format=IMAGE_ORDERING)(x)
f1 = x
# Block 2
x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1', data_format=IMAGE_ORDERING)(x)
x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2', data_format=IMAGE_ORDERING)(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool', data_format=IMAGE_ORDERING)(x)
f2 = x
# Block 3
x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1', data_format=IMAGE_ORDERING)(x)
x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2', data_format=IMAGE_ORDERING)(x)
x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3', data_format=IMAGE_ORDERING)(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool', data_format=IMAGE_ORDERING)(x)
pool3 = x
# Block 4
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1', data_format=IMAGE_ORDERING)(x)
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2', data_format=IMAGE_ORDERING)(x)
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3', data_format=IMAGE_ORDERING)(x)
pool4 = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool', data_format=IMAGE_ORDERING)(
x) ## (None, 14, 14, 512)
# Block 5
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1', data_format=IMAGE_ORDERING)(pool4)
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2', data_format=IMAGE_ORDERING)(x)
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3', data_format=IMAGE_ORDERING)(x)
pool5 = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool', data_format=IMAGE_ORDERING)(
x) ## (None, 7, 7, 512)
# x = Flatten(name='flatten')(x)
# x = Dense(4096, activation='relu', name='fc1')(x)
# <--> o = ( Conv2D( 4096 , ( 7 , 7 ) , activation='relu' , padding='same', data_format=IMAGE_ORDERING))(o)
# assuming that the input_height = input_width = 224 as in VGG data
# x = Dense(4096, activation='relu', name='fc2')(x)
# <--> o = ( Conv2D( 4096 , ( 1 , 1 ) , activation='relu' , padding='same', data_format=IMAGE_ORDERING))(o)
# assuming that the input_height = input_width = 224 as in VGG data
# x = Dense(1000 , activation='softmax', name='predictions')(x)
# <--> o = ( Conv2D( nClasses , ( 1 , 1 ) ,kernel_initializer='he_normal' , data_format=IMAGE_ORDERING))(o)
# assuming that the input_height = input_width = 224 as in VGG data
vgg = Model(img_input, pool5)
vgg.load_weights(VGG_Weights_path) ## loading VGG weights for the encoder parts of FCN8
n = 32
o = (Conv2D(n, (7, 7), activation='relu', padding='same', name="conv6", data_format=IMAGE_ORDERING))(pool5)
conv7 = (Conv2D(n, (1, 1), activation='relu', padding='same', name="conv7", data_format=IMAGE_ORDERING))(o)
## 4 times upsamping for pool4 layer
conv7_4 = Conv2DTranspose(nClasses, kernel_size=(4, 4), strides=(4, 4), use_bias=False, data_format=IMAGE_ORDERING)(
conv7)
## (None, 224, 224, 10)
## 2 times upsampling for pool411
pool411 = (
Conv2D(nClasses, (1, 1), activation='relu', padding='same', name="pool4_11", data_format=IMAGE_ORDERING))(pool4)
pool411_2 = (
Conv2DTranspose(nClasses, kernel_size=(2, 2), strides=(2, 2), use_bias=False, data_format=IMAGE_ORDERING))(
pool411)
pool311 = (
Conv2D(nClasses, (1, 1), activation='relu', padding='same', name="pool3_11", data_format=IMAGE_ORDERING))(pool3)
o = Add(name="add")([pool411_2, pool311, conv7_4])
o = Conv2DTranspose(nClasses, kernel_size=(8, 8), strides=(8, 8), use_bias=False, data_format=IMAGE_ORDERING)(o)
o = (Activation('sigmoid'))(o)
model = Model(img_input, o)
return model
def segmentation_model3(input_shape):
#input_shape = (224, 224, 3)
pool_size = (2,2)
inputs = Input(shape=input_shape)
layer1 = BatchNormalization()(inputs)
# Encoder
# 1
conv1 = Conv2D(16, (3,3), padding='same', kernel_initializer='he_normal')(layer1)
conv1 = BatchNormalization()(conv1)
conv1 = Activation('relu')(conv1)
conv2 = Conv2D(16, (3,3), padding='same', kernel_initializer='he_normal')(conv1)
conv2 = BatchNormalization()(conv2)
conv2 = Activation('relu')(conv2)
pool1, mask1 = MaxPoolingWithArgmax2D(pool_size)(conv2)
drop1 = Dropout(0.2)(pool1)
# 2
conv3 = Conv2D(32, (3,3), padding='same', kernel_initializer='he_normal')(drop1)
conv3 = BatchNormalization()(conv3)
conv3 = Activation('relu')(conv3)
conv4 = Conv2D(32, (3,3), padding='same', kernel_initializer='he_normal')(conv3)
conv4 = BatchNormalization()(conv4)
conv4 = Activation('relu')(conv4)
pool2, mask2 = MaxPoolingWithArgmax2D(pool_size)(conv4)
drop2 = Dropout(0.2)(pool2)
# 3
conv5 = Conv2D(64, (3,3), padding='same', kernel_initializer='he_normal')(drop2)
conv5 = BatchNormalization()(conv5)
conv5 = Activation('relu')(conv5)
conv6 = Conv2D(64, (3,3), padding='same', kernel_initializer='he_normal')(conv5)
conv6 = BatchNormalization()(conv6)
conv6 = Activation('relu')(conv6)
conv7 = Conv2D(64, (3,3), padding='same', kernel_initializer='he_normal')(conv6)
conv7 = BatchNormalization()(conv7)
conv7 = Activation('relu')(conv7)
pool3, mask3 = MaxPoolingWithArgmax2D(pool_size)(conv7)
drop3 = Dropout(0.2)(pool3)
# 4
conv8 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(drop3)
conv8 = BatchNormalization()(conv8)
conv8 = Activation('relu')(conv8)
conv9 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(conv8)
conv9 = BatchNormalization()(conv9)
conv9 = Activation('relu')(conv9)
conv10 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(conv9)
conv10 = BatchNormalization()(conv10)
conv10 = Activation('relu')(conv10)
pool4, mask4 = MaxPoolingWithArgmax2D(pool_size)(conv10)
drop4 = Dropout(0.2)(pool4)
# 5
conv11 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(drop4)
conv11 = BatchNormalization()(conv11)
conv11 = Activation('relu')(conv11)
conv12 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(conv11)
conv12 = BatchNormalization()(conv12)
conv12 = Activation('relu')(conv12)
conv13 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(conv12)
conv13 = BatchNormalization()(conv13)
conv13 = Activation('relu')(conv13)
pool5, mask5 = MaxPoolingWithArgmax2D(pool_size)(conv13)
drop5 = Dropout(0.2)(pool5)
# Decoder
# 5
unpool5 = MaxUnpooling2D(pool_size)([drop5, mask5])
con1 = concatenate([unpool5, conv13])
unconv13 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(con1)
unconv13 = BatchNormalization()(unconv13)
unconv13 = Activation('relu')(unconv13)
unconv12 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(unconv13)
unconv12 = BatchNormalization()(unconv12)
unconv12 = Activation('relu')(unconv12)
unconv11 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(unconv12)
unconv11 = BatchNormalization()(unconv11)
unconv11 = Activation('relu')(unconv11)
drop6 = Dropout(0.2)(unconv11)
# 4
unpool4 = MaxUnpooling2D(pool_size)([drop6, mask4])
con2 = concatenate([unpool4, conv10])
unconv10 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(con2)
unconv10 = BatchNormalization()(unconv10)
unconv10 = Activation('relu')(unconv10)
unconv9 = Conv2D(128, (3,3), padding='same', kernel_initializer='he_normal')(unconv10)
unconv9 = BatchNormalization()(unconv9)
unconv9 = Activation('relu')(unconv9)
unconv8 = Conv2D(64, (3,3), padding='same', kernel_initializer='he_normal')(unconv9)
unconv8 = BatchNormalization()(unconv8)
unconv8 = Activation('relu')(unconv8)
drop7 = Dropout(0.2)(unconv8)
# 3
unpool3 = MaxUnpooling2D(pool_size)([drop7, mask3])
con3 = concatenate([unpool3, conv7])
unconv7 = Conv2D(64, (3,3), padding='same', kernel_initializer='he_normal')(con3)
unconv7 = BatchNormalization()(unconv7)
unconv7 = Activation('relu')(unconv7)
unconv6 = Conv2D(64, (3,3), padding='same', kernel_initializer='he_normal')(unconv7)
unconv6 = BatchNormalization()(unconv6)
unconv6 = Activation('relu')(unconv6)
unconv5 = Conv2D(32, (3,3), padding='same', kernel_initializer='he_normal')(unconv6)
unconv5 = BatchNormalization()(unconv5)
unconv5 = Activation('relu')(unconv5)
drop8 = Dropout(0.2)(unconv5)
# 2
unpool2 = MaxUnpooling2D(pool_size)([drop8, mask2])
con4 = concatenate([unpool2, conv4])
unconv4 = Conv2D(32, (3,3), padding='same', kernel_initializer='he_normal')(con4)
unconv4 = BatchNormalization()(unconv4)
unconv4 = Activation('relu')(unconv4)
unconv3 = Conv2D(16, (3,3), padding='same', kernel_initializer='he_normal')(unconv4)
unconv3 = BatchNormalization()(unconv3)
unconv3 = Activation('relu')(unconv3)
drop9 = Dropout(0.2)(unconv3)
# 1
unpool1 = MaxUnpooling2D(pool_size)([drop9, mask1])
con5 = concatenate([unpool1, conv2])
unconv2 = Conv2D(16, (3,3), padding='same', kernel_initializer='he_normal')(unpool1)
unconv2 = BatchNormalization()(unconv2)
unconv2 = Activation('relu')(unconv2)
unconv1 = Conv2D(3, (3,3), padding='same', kernel_initializer='he_normal')(unconv2)
unconv1 = BatchNormalization()(unconv1)
unconv1 = Activation('softmax')(unconv1)
model = Model(input=inputs, output=unconv1)
return model
|
{"/train.py": ["/model_train2.py"]}
|
6,681
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busempresa/models.py
|
from django.db import models
class BusEmpresa(models.Model):
nombre = models.CharField(default = "", max_length=255)
descripcion = models.CharField(default = "", max_length=255)
choferes = models.ManyToManyField ('busdriver.BusDriver')
def __str__(self):
return self.nombre
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,682
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/bususer/migrations/0003_remove_bususer_is_driver.py
|
# Generated by Django 2.0.4 on 2018-04-18 19:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('bususer', '0002_bususer_is_driver'),
]
operations = [
migrations.RemoveField(
model_name='bususer',
name='is_driver',
),
]
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,683
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busdriver/migrations/0004_auto_20180419_1602.py
|
# Generated by Django 2.0.3 on 2018-04-19 22:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('busdriver', '0003_auto_20180419_1521'),
]
operations = [
migrations.AlterField(
model_name='busdriver',
name='placa',
field=models.CharField(default='', max_length=255, unique=True),
),
]
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,684
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busparada/admin.py
|
from django.contrib import admin
from .models import BusParada
admin.site.register(BusParada)
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,685
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busempresa/migrations/0002_busempresa_choferes.py
|
# Generated by Django 2.0.3 on 2018-04-19 21:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('busdriver', '0002_busdriver_empresa'),
('busempresa', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='busempresa',
name='choferes',
field=models.ManyToManyField(to='busdriver.BusDriver'),
),
]
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,686
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busruta/migrations/0003_auto_20180419_1521.py
|
# Generated by Django 2.0.3 on 2018-04-19 21:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('busparada', '0005_remove_busparada_ruta'),
('busruta', '0002_auto_20180419_0228'),
]
operations = [
migrations.RemoveField(
model_name='busruta',
name='empresa',
),
migrations.AddField(
model_name='busruta',
name='paradas',
field=models.ManyToManyField(to='busparada.BusParada'),
),
]
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,687
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busruta/models.py
|
from django.db import models
class BusRuta(models.Model):
nombre = models.CharField(default = "", max_length=255)
latitud_final = models.CharField(default = "", max_length=255)
longitud_final = models.CharField(default = "", max_length=255)
costo = models.FloatField(null=True, blank=True, default=None)
latitud = models.FloatField(null=True, blank=True, default=None)
longitud = models.FloatField(null=True, blank=True, default=None)
paradas = models.ManyToManyField('busparada.BusParada')
def __str__(self):
return self.nombre
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,688
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busdriver/views.py
|
from busdriver.models import BusDriver
from rest_framework import viewsets
from busdriver.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = BusDriver.objects.all().order_by('-id')
serializer_class = UserSerializer
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,689
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busruta/apps.py
|
from django.apps import AppConfig
class BusrutaConfig(AppConfig):
name = 'busruta'
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,690
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busempresa/admin.py
|
from django.contrib import admin
from .models import BusEmpresa
admin.site.register(BusEmpresa)
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,691
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busruta/migrations/0004_auto_20180419_1526.py
|
# Generated by Django 2.0.3 on 2018-04-19 21:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('busruta', '0003_auto_20180419_1521'),
]
operations = [
migrations.RenameField(
model_name='busruta',
old_name='final',
new_name='latitud_final',
),
migrations.RenameField(
model_name='busruta',
old_name='inicio',
new_name='longitud_final',
),
]
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,692
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busdriver/models.py
|
from django.db import models
class BusDriver(models.Model):
placa = models.CharField(default = "", max_length=255, unique = True)
rating = models.SmallIntegerField(default=0)
latitud = models.FloatField(null=True, blank=True, default=None)
longitud = models.FloatField(null=True, blank=True, default=None)
rutas = models.ManyToManyField('busruta.BusRuta')
def __str__(self):
return self.placa
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,693
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busdriver/resources.py
|
from tastypie.resources import ModelResource
from busdriver.models import BusDriver
from tastypie.authorization import Authorization
from tastypie import fields
class BusDriverResource(ModelResource):
rutas = fields.ManyToManyField("busruta.resources.BusRutaResource", 'rutas',
null=True, full=True, related_name='ruta')
class Meta:
queryset = BusDriver.objects.all()
resource_name = 'driver'
authorization = Authorization()
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,694
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/bususer/resources.py
|
from tastypie.resources import ModelResource
from bususer.models import BusUser
from tastypie.authorization import Authorization
class BusUserResource(ModelResource):
class Meta:
queryset = BusUser.objects.all()
resource_name = 'user'
authorization = Authorization()
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,695
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busempresa/resources.py
|
from tastypie.resources import ModelResource
from busempresa.models import BusEmpresa
from tastypie.authorization import Authorization
from tastypie import fields
class BusEmpresaResource(ModelResource):
choferes = fields.ManyToManyField("busdriver.resources.BusDriverResource", 'choferes',
null=True, full=True, related_name='chofer')
class Meta:
queryset = BusEmpresa.objects.all()
resource_name = 'empresa'
authorization = Authorization()
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,696
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busdriver/migrations/0003_auto_20180419_1521.py
|
# Generated by Django 2.0.3 on 2018-04-19 21:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('busruta', '0003_auto_20180419_1521'),
('busdriver', '0002_busdriver_empresa'),
]
operations = [
migrations.RemoveField(
model_name='busdriver',
name='empresa',
),
migrations.AddField(
model_name='busdriver',
name='rutas',
field=models.ManyToManyField(to='busruta.BusRuta'),
),
]
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,697
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busdriver/admin.py
|
from django.contrib import admin
from .models import BusDriver
admin.site.register(BusDriver)
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,698
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/bususer/migrations/0002_bususer_is_driver.py
|
# Generated by Django 2.0.4 on 2018-04-18 19:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bususer', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='bususer',
name='is_driver',
field=models.BooleanField(default=False),
),
]
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,699
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busparada/urls.py
|
from django.conf.urls import re_path
from djoser import views as djoser_views
from rest_framework_jwt import views as jwt_views
from busparada import views
urlpatterns = [
# Views are defined in Djoser, but we're assigning custom paths.
#re_path(r'^parada/view/$', djoser_views.UserView.as_view(), name='parada-view'),
#re_path(r'^parada/delete/$', djoser_views.UserDeleteView.as_view(), name='parada-delete'),
#re_path(r'^parada/create/$', djoser_views.UserCreateView.as_view(), name='parada-create'),
]
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,700
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/BUS/urls.py
|
"""BUS URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, re_path
from busparada.resources import BusParadaResource
from busruta.resources import BusRutaResource
from busempresa.resources import BusEmpresaResource
from busdriver.resources import BusDriverResource
#from bususer.resources import BusUserResource
parada = BusParadaResource()
ruta = BusRutaResource()
empresa = BusEmpresaResource()
driver = BusDriverResource()
#user = BusUserResource()
urlpatterns = [
re_path(r'^', admin.site.urls),
re_path(r'^admin/', admin.site.urls),
re_path(r'^api/', include('bususer.urls')),
re_path(r'^api/', include(parada.urls)),
re_path(r'^api/', include(ruta.urls)),
re_path(r'^api/', include(empresa.urls)),
re_path(r'^api/', include(driver.urls)),
#re_path(r'^api/', include(user.urls)),
]
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,701
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busruta/resources.py
|
from tastypie.resources import ModelResource
from busruta.models import BusRuta
from tastypie.authorization import Authorization
from tastypie import fields
class BusRutaResource(ModelResource):
paradas = fields.ManyToManyField("busparada.resources.BusParadaResource", 'paradas',
null=True, full=True, related_name='parada')
class Meta:
queryset = BusRuta.objects.all()
resource_name = 'ruta'
authorization = Authorization()
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,702
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busempresa/apps.py
|
from django.apps import AppConfig
class BusempresaConfig(AppConfig):
name = 'busempresa'
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,703
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busparada/views.py
|
from django.shortcuts import render
import uuid
from rest_framework import views, permissions, status
from rest_framework.response import Response
# Create your views here.
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,704
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busruta/admin.py
|
from django.contrib import admin
from .models import BusRuta
admin.site.register(BusRuta)
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,705
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busparada/resources.py
|
from tastypie.resources import ModelResource
from busparada.models import BusParada
from tastypie.authorization import Authorization
class BusParadaResource(ModelResource):
class Meta:
queryset = BusParada.objects.all()
resource_name = 'parada'
authorization = Authorization()
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,706
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/bususer/views.py
|
from bususer.models import BusUser
from rest_framework import viewsets
from bususer.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = BusUser.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,707
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busdriver/migrations/0002_busdriver_empresa.py
|
# Generated by Django 2.0.3 on 2018-04-19 18:36
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('busempresa', '0001_initial'),
('busdriver', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='busdriver',
name='empresa',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='busempresa.BusEmpresa'),
),
]
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,708
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busparada/apps.py
|
from django.apps import AppConfig
class BusparadaConfig(AppConfig):
name = 'busparada'
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,709
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/bususer/serializers.py
|
from bususer.models import BusUser
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = BusUser
fields = ('id','url','is_admin','email','first_name','last_name','chofer')
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,710
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/bususer/admin.py
|
from django.contrib import admin
from .models import BusUser
admin.site.register(BusUser)
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,711
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busparada/models.py
|
from django.db import models
class BusParada(models.Model):
nombre = models.CharField(default = "", max_length=255)
latitud = models.FloatField(null=True, blank=True, default=None)
longitud = models.FloatField(null=True, blank=True, default=None)
def __str__(self):
return self.nombre
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,712
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/bususer/apps.py
|
from django.apps import AppConfig
class BususerConfig(AppConfig):
name = 'bususer'
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,713
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/bususer/urls.py
|
from django.conf.urls import re_path, include
from djoser import views as djoser_views
from rest_framework_jwt import views as jwt_views
from bususer import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
urlpatterns = [
# Views are defined in Djoser, but we're assigning custom paths.
re_path(r'^user/view/$', djoser_views.UserView.as_view(), name='user-view'),
re_path(r'^user/delete/$', djoser_views.UserDeleteView.as_view(), name='user-delete'),
re_path(r'^user/create/$', djoser_views.UserCreateView.as_view(), name='user-create'),
# Views are defined in Rest Framework JWT, but we're assigning custom paths.
re_path(r'^user/login/$', jwt_views.ObtainJSONWebToken.as_view(), name='user-login'),
re_path(r'^user/login/refresh/$', jwt_views.RefreshJSONWebToken.as_view(), name='user-login-refresh'),
re_path(r'^', include(router.urls)),
re_path(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,714
|
SpiritHunt3r/API_Proyecto1
|
refs/heads/master
|
/busparada/migrations/0005_remove_busparada_ruta.py
|
# Generated by Django 2.0.3 on 2018-04-19 21:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('busparada', '0004_auto_20180419_0228'),
]
operations = [
migrations.RemoveField(
model_name='busparada',
name='ruta',
),
]
|
{"/busparada/admin.py": ["/busparada/models.py"], "/busdriver/views.py": ["/busdriver/models.py"], "/busempresa/admin.py": ["/busempresa/models.py"], "/busdriver/resources.py": ["/busdriver/models.py"], "/busempresa/resources.py": ["/busempresa/models.py"], "/busdriver/admin.py": ["/busdriver/models.py"], "/BUS/urls.py": ["/busparada/resources.py", "/busruta/resources.py", "/busempresa/resources.py", "/busdriver/resources.py"], "/busruta/resources.py": ["/busruta/models.py"], "/busruta/admin.py": ["/busruta/models.py"], "/busparada/resources.py": ["/busparada/models.py"], "/bususer/views.py": ["/bususer/serializers.py"]}
|
6,716
|
hongsam14/django_practice
|
refs/heads/master
|
/article/views.py
|
import django
from django.shortcuts import render
from django.views import generic
from django.views.generic import ListView, FormView, RedirectView, CreateView
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.urls import reverse_lazy
from django.contrib import messages
from .models import Article, UserFavouriteArticle
from .forms import ArticleForm
# Create your views here.
class ArticleView(ListView):
model = Article
template_name = 'article.html'
class HomeView(RedirectView):
pattern_name = 'article'
class LoginView(FormView):
form_class = AuthenticationForm
template_name = 'login.html'
success_url = reverse_lazy('home')
class SignUp(CreateView):
form_class = UserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
class Publications(FormView):
form_class = ArticleForm
template_name = 'publish.html'
success_url = '/'
def form_valid(self, form:ArticleForm):
# post = form(self.request.POST)
post = form.save(commit=False)
post.author = self.request.user
post.save()
return super().form_valid(form)
def form_invalid(self, form):
messages.error(self.request, "Invalid information.")
return super().form_invalid(form)
|
{"/article/views.py": ["/article/forms.py"]}
|
6,717
|
hongsam14/django_practice
|
refs/heads/master
|
/article/urls.py
|
from django.urls import path
from . import views
from django.contrib.auth.decorators import login_required
urlpatterns = [
path('', views.HomeView.as_view(), name='home'),
path('article/', views.ArticleView.as_view(), name='article'),
path('login/', views.LoginView.as_view(), name='login'),
path('resister/', views.SignUp.as_view(), name='signup'),
path('publish/', login_required(views.Publications.as_view()), name='publish'),
]
|
{"/article/views.py": ["/article/forms.py"]}
|
6,718
|
hongsam14/django_practice
|
refs/heads/master
|
/article/forms.py
|
from django.forms import ModelForm
from .models import Article
# https://docs.djangoproject.com/en/3.2/topics/forms/modelforms/
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = ['title', 'synopsis', 'content']
|
{"/article/views.py": ["/article/forms.py"]}
|
6,754
|
brleinad/pygame-menu
|
refs/heads/master
|
/pygameMenu/utils.py
|
# coding=utf-8
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
UTILS
Utilitary functions.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2020 Pablo Pizarro R. @ppizarror
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-------------------------------------------------------------------------------
"""
import pygame
import pygameMenu.locals as _locals
def assert_alignment(align):
"""
Assert alignment local.
:param align: Align value
:type align: basestring
:return: None
"""
assert isinstance(align, str), 'alignment "{0}" must be a string'.format(align)
assert align in [_locals.ALIGN_LEFT,
_locals.ALIGN_CENTER,
_locals.ALIGN_RIGHT,
_locals.ALIGN_TOP,
_locals.ALIGN_BOTTOM], \
'incorrect alignment value "{0}"'.format(align)
def assert_color(color):
"""
Assert that a certain color is valid.
:param color: Object color
:type color: list, tuple
:return: None
"""
assert isinstance(color, (list, tuple))
assert len(color) == 3, 'color must be a tuple or list of 3 numbers'
for i in color:
assert isinstance(i, int), '"{0}" in element color {1} must be an integer'.format(i, color)
def assert_orientation(orientation):
"""
Assert that a certain widget orientation is valid.
:param orientation: Object orientation
:type orientation: basestring
:return: None
"""
assert isinstance(orientation, str)
assert orientation in [_locals.ORIENTATION_HORIZONTAL, _locals.ORIENTATION_VERTICAL], \
'invalid orientation value "{0}"'.format(orientation)
def assert_position(position):
"""
Assert that a certain widget position is valid.
:param position: Object position
:type position: basestring
:return: None
"""
assert isinstance(position, str)
assert position in [_locals.POSITION_WEST, _locals.POSITION_SOUTHWEST,
_locals.POSITION_SOUTH, _locals.POSITION_SOUTHEAST,
_locals.POSITION_EAST, _locals.POSITION_NORTH,
_locals.POSITION_NORTHWEST, _locals.POSITION_NORTHEAST], \
'invalid position value "{0}"'.format(position)
def check_key_pressed_valid(event):
"""
Checks if the pressed key is valid.
:param event: Key press event
:type event: pygame.event.EventType
:return: True if a key is pressed
:rtype: bool
"""
# If the system detects that any key event has been pressed but
# there's not any key pressed then this method raises a KEYUP
# flag
bad_event = not (True in pygame.key.get_pressed())
if bad_event:
if 'test' in event.dict and event.dict['test']:
return True
ev = pygame.event.Event(pygame.KEYUP, {'key': event.key})
pygame.event.post(ev)
return not bad_event
def dummy_function():
"""
Dummy function, this can be archieved with lambda but it's against
PEP-8.
:return: None
"""
return
def make_surface(width, height, alpha=False):
"""
Creates a pygame surface object.
:param width: Surface width
:type width: int, float
:param height: Surface height
:type height: int, float
:param alpha: Enable alpha channel on surface
:type alpha: bool
:return: Pygame surface
:rtype: _pygame.Surface
"""
assert width > 0 and height > 0, 'surface width and height must be greater than zero'
assert isinstance(alpha, bool)
surface = pygame.Surface((width, height), pygame.SRCALPHA, 32) # lgtm [py/call/wrong-arguments]
if alpha:
surface = pygame.Surface.convert_alpha(surface)
return surface
|
{"/pygameMenu/themes.py": ["/pygameMenu/utils.py"], "/pygameMenu/menu.py": ["/pygameMenu/utils.py", "/pygameMenu/widgets/__init__.py"], "/pygameMenu/widgets/__init__.py": ["/pygameMenu/widgets/selection/highlight.py", "/pygameMenu/widgets/selection/none.py"]}
|
6,755
|
brleinad/pygame-menu
|
refs/heads/master
|
/pygameMenu/themes.py
|
# coding=utf-8
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
THEMES
Theme class and predefined themes.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2020 Pablo Pizarro R. @ppizarror
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-------------------------------------------------------------------------------
"""
import pygame
import pygameMenu
import pygameMenu.utils
class Theme(object):
"""
Class defining the visual rendering of menus and widgets.
:param background_color: Menu background color
:type background_color: tuple, list
:param selection_border_width: Border width of the highlight box
:type selection_border_width: int
:param selection_margin_x: X margin of selected highlight box
:type selection_margin_x: int, float
:param selection_margin_y: X margin of selected highlight box
:type selection_margin_y: int, float
:param selection_color: Color of the selecter widget
:type selection_color: tuple
:param scrollbar_color: Scrollbars color
:type scrollbar_color: tuple, list
:param scrollbar_shadow: Indicate if a shadow is drawn on each scrollbar
:type scrollbar_shadow: bool
:param scrollbar_shadow_color: Color of the shadow
:type scrollbar_shadow_color: tuple, list
:param scrollbar_shadow_offset: Offset of shadow
:type scrollbar_shadow_offset: int, float
:param scrollbar_shadow_position: Position of shadow
:type scrollbar_shadow_position: basestring
:param scrollbar_slider_color: Color of the sliders
:type scrollbar_slider_color: tuple, list
:param scrollbar_slider_pad: Space between slider and scrollbars borders
:type scrollbar_slider_pad: int, float
:param scrollbar_thick: Scrollbars thickness
:type scrollbar_thick: int, float
:param title_background_color: Title background color
:type title_background_color: tuple, list
:param title_font: Optional title font, if None use the Menu default font
:type title_font: basestring, NoneType
:param title_font_color: Title font color, if None use the widget font color
:type title_font_color: list, tuple, NoneType
:param title_font_size: Font size of the title
:type title_font_size: int
:param title_shadow: Enable shadow on title
:type title_shadow: bool
:param title_shadow_color: Title shadow color
:type title_shadow_color: list, tuple
:param title_shadow_offset: Offset of shadow on title
:type title_shadow_offset: int, float
:param title_shadow_position: Position of the shadow on title
:type title_shadow_position: basestring
:param widget_font: Menu font file path or name
:type widget_font: basestring
:param widget_alignment: Widget default alignment
:type widget_alignment: basestring
:param widget_font_color: Color of the font
:type widget_font_color: tuple, list
:param widget_font_size: Font size
:type widget_font_size: int
:param widget_shadow: Indicate if a shadow is drawn on each widget
:type widget_shadow: bool
:param widget_shadow_color: Color of the shadow
:type widget_shadow_color: tuple, list
:param widget_shadow_offset: Offset of shadow
:type widget_shadow_offset: int, float
:param widget_shadow_position: Position of shadow
:type widget_shadow_position: basestring
"""
def __init__(self, **kwargs):
self.background_color = self._get(kwargs, 'background_color',
'color', (220, 220, 220))
self.selection_border_width = self._get(kwargs, 'selection_border_width',
int, 1)
self.selection_margin_x = self._get(kwargs, 'selection_margin_x',
float, 16.0)
self.selection_margin_y = self._get(kwargs, 'selection_margin_y',
float, 8.0)
self.selection_color = self._get(kwargs, 'selection_color',
'color', (0, 0, 0))
self.scrollbar_color = self._get(kwargs, 'scrollbar_color',
'color', (235, 235, 235))
self.scrollbar_shadow = self._get(kwargs, 'scrollbar_shadow',
bool, False)
self.scrollbar_shadow_color = self._get(kwargs, 'scrollbar_shadow_color',
'color', False)
self.scrollbar_shadow_offset = self._get(kwargs, 'scrollbar_shadow_offset',
(int, float), False)
self.scrollbar_shadow_position = self._get(kwargs, 'scrollbar_shadow_position',
'position', pygameMenu.locals.POSITION_NORTHWEST)
self.scrollbar_slider_color = self._get(kwargs, 'scrollbar_slider_color',
'color', (200, 200, 200))
self.scrollbar_slider_pad = self._get(kwargs, 'scrollbar_slider_pad',
(int, float), 0)
self.scrollbar_thick = self._get(kwargs, 'scrollbar_thick',
(int, float), 20)
self.title_background_color = self._get(kwargs, 'title_background_color',
'color', (70, 70, 70))
self.title_font = self._get(kwargs, 'title_font',
(str, type(None)))
self.title_font_color = self._get(kwargs, 'title_font_color',
'color', (220, 220, 220))
self.title_font_size = self._get(kwargs, 'title_font_size',
int, 45)
self.title_shadow = self._get(kwargs, 'title_shadow',
bool, False)
self.title_shadow_color = self._get(kwargs, 'title_shadow_color',
'color', (0, 0, 0))
self.title_shadow_offset = self._get(kwargs, 'title_shadow_offset',
(int, float), 2)
self.title_shadow_position = self._get(kwargs, 'title_shadow_position',
'position', pygameMenu.locals.POSITION_NORTHWEST)
self.widget_font = self._get(kwargs, 'widget_font',
str, pygameMenu.font.FONT_BEBAS)
self.widget_alignment = self._get(kwargs, 'widget_alignment',
'alignment', pygameMenu.locals.ALIGN_CENTER)
self.widget_font_color = self._get(kwargs, 'widget_font_color',
'color', (70, 70, 70))
self.widget_font_size = self._get(kwargs, 'widget_font_size',
int, 35)
self.widget_shadow = self._get(kwargs, 'widget_shadow',
bool, False)
self.widget_shadow_color = self._get(kwargs, 'widget_shadow_color',
'color', (0, 0, 0))
self.widget_shadow_offset = self._get(kwargs, 'widget_shadow_offset',
(int, float), 2)
self.widget_shadow_position = self._get(kwargs, 'widget_shadow_position',
'position', pygameMenu.locals.POSITION_NORTHWEST)
@staticmethod
def _get(params, key, allowed_types=None, default=None):
"""
Return a value from a dictionary.
:param params: parameters dictionnary
:type params: dict
:param key: key to look for
:type key: basestring
:param allowed_types: list of allowed types
:type allowed_types: any
:param default: default value to return
:type default: any
:return: the value associated to the key
"""
if key not in params:
return default
value = params.pop(key)
if allowed_types:
if not isinstance(allowed_types, (tuple, list)):
allowed_types = (allowed_types,)
for valtype in allowed_types:
if valtype == 'color':
pygameMenu.utils.assert_color(value)
elif valtype == 'position':
pygameMenu.utils.assert_position(value)
elif valtype == 'alignment':
pygameMenu.utils.assert_alignment(value)
others = [t for t in allowed_types if t not in ('color', 'position', 'alignment')]
if others:
msg = 'Theme.{} type shall be {} (got {})'.format(key, others, type(value))
# noinspection PyTypeChecker
assert isinstance(value, others), msg
return value
def apply_selected(self, surface, widget):
"""
Draw the selection.
:param surface: Surface to draw
:type surface: pygame.surface.SurfaceType
:param widget: Widget object
:type widget: pygameMenu.widgets.core.widget.Widget
:return: None
"""
# noinspection PyProtectedMember
rect = widget._rect.copy().inflate(self.selection_margin_x,
self.selection_margin_y).move(0, -1)
pygame.draw.rect(surface, self.selection_color, rect, self.selection_border_width)
THEME_DEFAULT = Theme()
THEME_BLUE = Theme(widget_font_color=(61, 170, 220),
selection_color=(100, 62, 132),
title_font_color=(228, 230, 246),
title_background_color=(62, 149, 195),
background_color=(228, 230, 246))
THEME_GREEN = Theme(widget_font_color=(255, 255, 255),
selection_color=(125, 121, 114),
title_font_color=(228, 230, 246),
title_background_color=(125, 121, 114),
background_color=(186, 214, 177))
THEME_SOLARIZED = Theme(widget_font_color=(102, 122, 130),
selection_color=(207, 62, 132),
title_font_color=(38, 158, 151),
title_background_color=(4, 47, 58),
background_color=(239, 231, 211))
|
{"/pygameMenu/themes.py": ["/pygameMenu/utils.py"], "/pygameMenu/menu.py": ["/pygameMenu/utils.py", "/pygameMenu/widgets/__init__.py"], "/pygameMenu/widgets/__init__.py": ["/pygameMenu/widgets/selection/highlight.py", "/pygameMenu/widgets/selection/none.py"]}
|
6,756
|
brleinad/pygame-menu
|
refs/heads/master
|
/pygameMenu/widgets/selection/highlight.py
|
# coding=utf-8
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
HIGHLIGHT
Widget selection highlight box effect.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2020 Pablo Pizarro R. @ppizarror
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-------------------------------------------------------------------------------
"""
import pygame
from pygameMenu.widgets.core.selection import Selection
class HighlightSelection(Selection):
"""
Widget selection highlight class.
:param border_width: Border width of the highlight box
:type border_width: int
:param margin_x: X margin of selected highlight box
:type margin_x: int, float
:param margin_y: X margin of selected highlight box
:type margin_y: int, float
"""
def __init__(self,
border_width=1,
margin_x=16.0,
margin_y=8.0,
):
assert isinstance(border_width, int)
assert margin_x >= 0 and margin_y >= 0
assert border_width >= 0
margin_x = float(margin_x)
margin_y = float(margin_y)
super(HighlightSelection, self).__init__(margin_left=margin_x / 2, margin_right=margin_x / 2,
margin_top=margin_y / 2, margin_bottom=margin_y / 2)
self.border_width = border_width
self.margin_x = margin_x
self.margin_y = margin_y
def get_margin(self):
"""
Return top, left, bottom and right margins of the selection.
:return: Tuple of (t,l,b,r) margins in px
:rtype: tuple
"""
return self.margin_top + self.border_width, self.margin_left + self.border_width, \
self.margin_bottom + self.border_width, self.margin_right + self.border_width
def draw(self, surface, widget):
"""
Draw the selection.
:param surface: Surface to draw
:type surface: pygame.surface.SurfaceType
:param widget: Widget object
:type widget: pygameMenu.widgets.core.widget.Widget
:return: None
"""
# noinspection PyProtectedMember
rect = widget.get_rect().inflate(self.margin_x, self.margin_y).move(0, -1)
pygame.draw.rect(surface,
self.color,
rect,
self.border_width)
|
{"/pygameMenu/themes.py": ["/pygameMenu/utils.py"], "/pygameMenu/menu.py": ["/pygameMenu/utils.py", "/pygameMenu/widgets/__init__.py"], "/pygameMenu/widgets/__init__.py": ["/pygameMenu/widgets/selection/highlight.py", "/pygameMenu/widgets/selection/none.py"]}
|
6,757
|
brleinad/pygame-menu
|
refs/heads/master
|
/pygameMenu/menu.py
|
# coding=utf-8
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
MENU
Menu class.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2020 Pablo Pizarro R. @ppizarror
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-------------------------------------------------------------------------------
"""
import sys
import types
import textwrap
from uuid import uuid4
import pygame
import pygameMenu.controls as _controls
import pygameMenu.events as _events
import pygameMenu.locals as _locals
import pygameMenu.utils as _utils
import pygameMenu.widgets as _widgets
from pygameMenu.scrollarea import ScrollArea
from pygameMenu.sound import Sound
# Joy events
_JOY_EVENT_LEFT = 1
_JOY_EVENT_RIGHT = 2
_JOY_EVENT_UP = 4
_JOY_EVENT_DOWN = 8
_JOY_EVENT_REPEAT = pygame.NUMEVENTS - 1
class Menu(object):
"""
Menu object.
:param menu_height: Height of the Menu (px)
:type menu_height: int, float
:param menu_width: Width of the Menu (px)
:type menu_width: int, float
:param font: Menu font file path or name
:type font: basestring
:param title: Title of the Menu (main title)
:type title: basestring
:param back_box: Draw a back-box button on header
:type back_box: bool
:param column_force_fit_text: Force text fitting of widgets if the width exceeds the column max width
:type column_force_fit_text: bool
:param column_max_width: List/Tuple representing the max width of each column in px, None equals no limit
:type column_max_width: tuple, NoneType
:param columns: Number of columns, by default it's 1
:type columns: int
:param enabled: Menu is enabled by default or not
:type enabled: bool
:param joystick_enabled: Enable/disable joystick on the Menu
:type joystick_enabled: bool
:param menu_background_color: Menu background color
:type menu_background_color: tuple, list
:param mouse_enabled: Enable/disable mouse click inside the Menu
:type mouse_enabled: bool
:param menu_id: ID of the Menu
:type menu_id: basestring
:param menu_opacity: Opacity of background (0=transparent, 100=opaque)
:type menu_opacity: int, float
:param menu_position_x: Left position of the Menu respect to the window (%), if 50 the Menu is horizontally centered
:type menu_position_x: int, float
:param menu_position_y: Top position of the Menu respect to the window (%), if 50 the Menu is vertically centered
:type menu_position_y: int, float
:param mouse_visible: Set mouse visible on Menu
:type mouse_visible: bool
:param onclose: Function applied when closing the Menu
:type onclose: callable, NoneType
:param rows: Number of rows of each column, None if there's only 1 column
:type rows: int, NoneType
:param scrollbar_color: Scrollbars color
:type scrollbar_color: tuple, list
:param scrollbar_shadow: Indicate if a shadow is drawn on each scrollbar
:type scrollbar_shadow: bool
:param scrollbar_shadow_color: Color of the shadow
:type scrollbar_shadow_color: tuple, list
:param scrollbar_shadow_offset: Offset of shadow
:type scrollbar_shadow_offset: int, float
:param scrollbar_shadow_position: Position of shadow
:type scrollbar_shadow_position: basestring
:param scrollbar_slider_color: Color of the sliders
:type scrollbar_slider_color: tuple, list
:param scrollbar_slider_pad: Space between slider and scrollbars borders
:type scrollbar_slider_pad: int, float
:param scrollbar_thick: Scrollbars thickness
:type scrollbar_thick: int, float
:param selection_color: Color of the selecter widget
:type selection_color: tuple
:param title_background_color: Title background color
:type title_background_color: tuple, list
:param title_font: Optional title font, if None use the Menu default font
:type title_font: basestring, NoneType
:param title_font_color: Title font color, if None use the widget font color
:type title_font_color: list, tuple, NoneType
:param title_font_size: Font size of the title
:type title_font_size: int
:param title_offset_x: Offset x-position of title (px)
:type title_offset_x: int, float
:param title_offset_y: Offset y-position of title (px)
:type title_offset_y: int, float
:param title_shadow: Enable shadow on title
:type title_shadow: bool
:param title_shadow_color: Title shadow color
:type title_shadow_color: list, tuple
:param title_shadow_offset: Offset of shadow on title
:type title_shadow_offset: int, float
:param title_shadow_position: Position of the shadow on title
:type title_shadow_position: basestring
:param widget_alignment: Widget default alignment
:type widget_alignment: basestring
:param widget_font_color: Color of the font
:type widget_font_color: tuple, list
:param widget_font_size: Font size
:type widget_font_size: int
:param widget_margin_x: Horizontal margin of each element in Menu (px)
:type widget_margin_x: int, float
:param widget_margin_y: Vertical margin of each element in Menu (px)
:type widget_margin_y: int, float
:param widget_offset_x: X axis offset of widgets inside Menu (px). If value less than 1 use percentage of width
:type widget_offset_x: int, float
:param widget_offset_y: Y axis offset of widgets inside Menu (px). If value less than 1 use percentage of height
:type widget_offset_y: int, float
:param widget_selection: Widget selection effect object
:type widget_selection: pygameMenu.widgets.core.selection.Selection
:param widget_shadow: Indicate if a shadow is drawn on each widget
:type widget_shadow: bool
:param widget_shadow_color: Color of the shadow
:type widget_shadow_color: tuple, list
:param widget_shadow_offset: Offset of shadow
:type widget_shadow_offset: int, float
:param widget_shadow_position: Position of shadow
:type widget_shadow_position: basestring
"""
def __init__(self,
menu_height,
menu_width,
font,
title,
back_box=True,
column_force_fit_text=False,
column_max_width=None,
columns=1,
enabled=True,
joystick_enabled=True,
menu_opacity=100,
menu_background_color=(0, 0, 0),
menu_id='',
menu_position_x=50,
menu_position_y=50,
mouse_enabled=True,
mouse_visible=True,
onclose=None,
rows=None,
scrollbar_color=(235, 235, 235),
scrollbar_shadow=False,
scrollbar_shadow_color=(0, 0, 0),
scrollbar_shadow_offset=2,
scrollbar_shadow_position=_locals.POSITION_SOUTHEAST,
scrollbar_slider_color=(200, 200, 200),
scrollbar_slider_pad=0,
scrollbar_thick=20,
selection_color=(255, 255, 255),
title_background_color=None,
title_font=None,
title_font_color=None,
title_font_size=45,
title_offset_x=0,
title_offset_y=0,
title_shadow=False,
title_shadow_color=(0, 0, 0),
title_shadow_offset=2,
title_shadow_position=_locals.POSITION_NORTHWEST,
widget_alignment=_locals.ALIGN_CENTER,
widget_font_color=(255, 255, 255),
widget_font_size=35,
widget_margin_x=0,
widget_margin_y=10,
widget_offset_x=0,
widget_offset_y=0,
widget_selection=_widgets.HighlightSelection(),
widget_shadow=False,
widget_shadow_color=(0, 0, 0),
widget_shadow_offset=2,
widget_shadow_position=_locals.POSITION_NORTHWEST,
):
assert isinstance(menu_height, (int, float))
assert isinstance(menu_width, (int, float))
assert isinstance(font, str)
assert isinstance(back_box, bool)
assert isinstance(column_force_fit_text, bool)
assert isinstance(column_max_width, (tuple, type(None), (int, float), list))
assert isinstance(columns, int)
assert isinstance(enabled, bool)
assert isinstance(joystick_enabled, bool)
assert isinstance(menu_opacity, (int, float))
assert isinstance(menu_id, str)
assert isinstance(mouse_enabled, bool)
assert isinstance(mouse_visible, bool)
assert isinstance(rows, (int, type(None)))
assert isinstance(scrollbar_shadow, bool)
assert isinstance(scrollbar_shadow_offset, (int, float))
assert isinstance(scrollbar_slider_pad, (int, float))
assert isinstance(scrollbar_thick, (int, float))
assert isinstance(title, str)
assert isinstance(title_font, (str, type(None)))
assert isinstance(title_font_size, int)
assert isinstance(title_offset_x, (int, float))
assert isinstance(title_offset_y, (int, float))
assert isinstance(title_shadow, bool)
assert isinstance(title_shadow_offset, (int, float))
assert isinstance(widget_alignment, str)
assert isinstance(widget_font_size, int)
assert isinstance(widget_margin_x, (int, float))
assert isinstance(widget_margin_y, (int, float))
assert isinstance(widget_offset_x, (int, float))
assert isinstance(widget_offset_y, (int, float))
assert isinstance(widget_selection, _widgets.Selection)
assert isinstance(widget_shadow, bool)
assert isinstance(widget_shadow_offset, (int, float))
# Assert colors
if title_background_color is None:
title_background_color = menu_background_color
if title_font_color is None:
title_font_color = widget_font_color
_utils.assert_color(menu_background_color)
_utils.assert_color(scrollbar_color)
_utils.assert_color(scrollbar_shadow_color)
_utils.assert_color(scrollbar_slider_color)
_utils.assert_color(selection_color)
_utils.assert_color(title_background_color)
_utils.assert_color(title_font_color)
_utils.assert_color(title_shadow_color)
_utils.assert_color(widget_font_color)
_utils.assert_color(widget_shadow_color)
# Assert positions
_utils.assert_position(scrollbar_shadow_position)
_utils.assert_position(title_shadow_position)
_utils.assert_position(widget_shadow_position)
# Column/row asserts
assert columns >= 1, 'number of columns must be greater or equal than 1'
if columns > 1:
assert rows is not None and rows >= 1, 'if columns greater than 1 then rows must be equal or greater than 1'
else:
if columns == 1:
if rows is None:
rows = 1e6 # Set rows as a big number
else:
assert rows > 0, 'number of rows must be greater than 1'
if column_max_width is not None:
if isinstance(column_max_width, (int, float)):
assert columns == 1, 'column_max_width can be a single number if there is only 1 column'
column_max_width = [column_max_width]
assert len(column_max_width) == columns, 'column_max_width length must be the same as the number of columns'
for i in column_max_width:
assert isinstance(i, type(None)) or isinstance(i, (int, float)), \
'each column max width can be None (no limit) or an integer/float'
assert i > 0 or i is None, 'each column max width must be greater than zero or None'
else:
column_max_width = [None for _ in range(columns)]
# Element size and position asserts
assert menu_width > 0 and menu_height > 0, \
'menu width and height must be greater than zero'
assert scrollbar_thick > 0, 'scrollbar thickness must be greater than zero'
assert widget_font_size > 0 and title_font_size > 0, \
'widget font size and title font size must be greater than zero'
assert widget_offset_x >= 0 and widget_offset_y >= 0, 'widget offset must be greater or equal than zero'
# Other asserts
assert 0 <= menu_opacity <= 100, \
'menu opacity must be between 0 and 100 (both values included)'
_utils.assert_alignment(widget_alignment)
# Get window size
window_width, window_height = pygame.display.get_surface().get_size()
assert menu_width <= window_width and menu_height <= window_height, \
'menu size must be lower than the size of the window'
# Generate ID if empty
if len(menu_id) == 0:
menu_id = str(uuid4())
# Update background color
menu_opacity = int(255.0 * (1.0 - (100.0 - menu_opacity) / 100.0))
menu_background_color = (menu_background_color[0],
menu_background_color[1],
menu_background_color[2],
menu_opacity)
# General properties of the Menu
self._background_function = None # type: (None,callable)
self._clock = pygame.time.Clock() # Inner clock
self._height = float(menu_height)
self._id = menu_id
self._index = -1 # Selected index, if -1 the widget does not have been selected yet
self._joy_event = 0 # type: int
self._onclose = onclose # Function that calls after closing Menu
self._sounds = Sound() # type: Sound
self._submenus = [] # type: list
self._width = float(menu_width)
# Menu links (pointer to previous and next menus in nested submenus), for public methods
# accesing self should be through "_current", because user can move through submenus
# and self pointer should target the current Menu object. Private methods access
# through self (not _current) because these methods are called by public (_current) or
# by themselves. _top is only used when moving through menus (open,reset)
self._current = self # Current Menu
# Prev stores a list of Menu pointers, when accesing a submenu, prev grows as
# prev = [prev, new_pointer]
self._prev = None # type: (list,None)
# Top is the same for the menus and submenus if the user moves through them
self._top = self # type: Menu
# Enabled and closed belongs to top, closing a submenu is equal as closing the root
# Menu
self._enabled = enabled # Menu is enabled or not
# Position of Menu
self._pos_x = 0 # type: int
self._pos_y = 0 # type: int
self.set_relative_position(menu_position_x, menu_position_y, current=False)
# Menu widgets
if abs(widget_offset_x) < 1:
widget_offset_x *= self._width
if abs(widget_offset_y) < 1:
widget_offset_y *= self._height
self._widgets = [] # type: list
self._widget_default_alignment = widget_alignment
self._widget_default_font_color = widget_font_color
self._widget_default_font_name = font
self._widget_default_font_size = widget_font_size
self._widget_default_margin = (widget_margin_x, widget_margin_y)
self._widget_default_selection = widget_selection
self._widget_default_selection_color = selection_color
self._widget_default_shadow = widget_shadow
self._widget_default_shadow_color = widget_shadow_color
self._widget_default_shadow_offset = widget_shadow_offset
self._widget_default_shadow_position = widget_shadow_position
self._widget_offset_x = widget_offset_x
self._widget_offset_y = widget_offset_y
# Configure the selection widget effect
self._widget_default_selection.set_color(selection_color)
# Columns and rows
self._column_max_width = column_max_width
self._column_pos_x = []
self._column_widths = None # type: (list,None)
self._columns = columns
self._force_fit_text = column_force_fit_text
self._rows = rows
# Init joystick
self._joystick = joystick_enabled
if self._joystick:
if not pygame.joystick.get_init():
pygame.joystick.init()
for i in range(pygame.joystick.get_count()):
pygame.joystick.Joystick(i).init()
# Init mouse
self._mouse = mouse_enabled and mouse_visible
self._mouse_visible = mouse_visible
self._mouse_visible_default = mouse_visible
# Create Menu bar (title)
self._menubar = _widgets.MenuBar(label=title,
width=self._width,
back_box=back_box,
bgcolor=menu_background_color, # bg_color_title is only used behind text
onreturn=self._back)
self._menubar.set_menu(self)
self._menubar.set_title(title=title,
offsetx=title_offset_x,
offsety=title_offset_y)
self._menubar.set_font(font=title_font or font,
font_size=title_font_size,
color=(title_background_color[0],
title_background_color[1],
title_background_color[2],
menu_opacity),
selected_color=title_font_color)
self._menubar.set_shadow(enabled=title_shadow,
color=title_shadow_color,
position=title_shadow_position,
offset=title_shadow_offset)
self._menubar.set_controls(self._joystick, self._mouse)
# Scrolling area
self._widgets_surface = None
self._scroll = ScrollArea(area_width=self._width,
area_height=self._height - self._menubar.get_rect().height,
area_color=menu_background_color,
scrollbar_color=scrollbar_color,
scrollbar_slider_color=scrollbar_slider_color,
scrollbar_slider_pad=scrollbar_slider_pad,
scrollbar_thick=scrollbar_thick,
shadow=scrollbar_shadow,
shadow_color=scrollbar_shadow_color,
shadow_offset=scrollbar_shadow_offset,
shadow_position=scrollbar_shadow_position)
def add_button(self,
title,
action,
*args,
**kwargs):
"""
Adds a button to the current Menu.
kwargs (Optional):
- align Widget alignment (str)
- button_id Widget ID (str)
- font_color Widget font color (tuple)
- font_name Widget font (str)
- font_size Font size of the widget (int)
- margin Tuple of (x,y) margin (int, float)
- selection_color Widget selection color
- selection_effect Widget selector effect :py:class:`pygameMenu.widgets.Selection`
:param title: Title of the button
:type title: basestring
:param action: Action of the button, can be a Menu, an event or a function
:type action: Menu, PymenuAction, function
:param args: Additional arguments used by a function
:param kwargs: Additional keyword arguments
:type kwargs: any
:return: Widget object
:rtype: :py:class:`pygameMenu.widgets.Button`
"""
assert isinstance(title, str)
# Get ID
button_id = kwargs.pop('button_id', '')
assert isinstance(button_id, str), 'ID must be a string'
# If element is a Menu
onchange = None
if isinstance(action, Menu):
self._current._submenus.append(action)
widget = _widgets.Button(title, button_id, onchange, self._current._open, action)
# If element is a PyMenuAction
elif action == _events.BACK: # Back to Menu
widget = _widgets.Button(title, button_id, onchange, self.reset,
1) # reset is public, so no _current
elif action == _events.RESET: # Back to Top Menu
widget = _widgets.Button(title, button_id, onchange, self.full_reset)
elif action == _events.CLOSE: # Close Menu
widget = _widgets.Button(title, button_id, onchange, self._current._close)
elif action == _events.EXIT: # Exit program
widget = _widgets.Button(title, button_id, onchange, self._current._exit)
elif action == _events.NONE: # None action
widget = _widgets.Button(title, button_id)
# If element is a function
elif isinstance(action, (types.FunctionType, types.MethodType)) or callable(action):
widget = _widgets.Button(title, button_id, onchange, action, *args)
else:
raise ValueError('Element must be a Menu, a PymenuAction or a function')
# Configure and add the button
self._current._configure_widget(widget=widget, **kwargs)
self._current._append_widget(widget)
return widget
def add_color_input(self,
title,
color_type,
color_id='',
default='',
input_separator=',',
input_underline='_',
onchange=None,
onreturn=None,
previsualization_width=3,
**kwargs):
"""
Add a color widget with RGB or Hex format to the current Menu.
Includes a preview box that renders the given color.
And functions onchange and onreturn does
onchange(current_text, \*\*kwargs)
onreturn(current_text, \*\*kwargs)
kwargs (Optional):
- align Widget alignment (str)
- font_color Widget font color (tuple)
- font_name Widget font (str)
- font_size Font size of the widget (int)
- margin Tuple of (x,y) margin (int, float)
- selection_color Widget selection color
- selection_effect Widget selector effect :py:class:`pygameMenu.widgets.Selection`
:param title: Title of the color input
:type title: basestring
:param color_type: Type of the color input, can be "rgb" or "hex"
:type color_type: basestring
:param color_id: ID of the color input
:type color_id: basestring
:param default: Default value to display, if RGB must be a tuple (r,g,b), if HEX must be a string "#XXXXXX"
:type default: basestring, tuple
:param input_separator: Divisor between RGB channels, not valid in HEX format
:type input_separator: basestring
:param input_underline: Underline character
:type input_underline: basestring
:param onchange: Function when changing the selector
:type onchange: callable, NoneType
:param onreturn: Function when pressing return button
:type onreturn: callable, NoneType
:param previsualization_width: Previsualization width as a factor of the height
:type previsualization_width: int, float
:param kwargs: Additional keyword-parameters
:type kwargs: any
:return: Widget object
:rtype: :py:class:`pygameMenu.widgets.ColorInput`
"""
assert isinstance(default, (str, tuple))
widget = _widgets.ColorInput(label=title,
colorinput_id=color_id,
color_type=color_type,
input_separator=input_separator,
input_underline=input_underline,
onchange=onchange,
onreturn=onreturn,
prev_size=previsualization_width,
**kwargs)
self._current._configure_widget(widget=widget, **kwargs)
widget.set_value(default)
self._current._append_widget(widget)
return widget
def add_image(self,
image_path,
angle=0,
image_id='',
scale=(1, 1),
scale_smooth=False,
selectable=False,
**kwargs):
"""
Add a simple image to the current Menu.
kwargs (Optional):
- align Widget alignment (str)
- margin Tuple of (x,y) margin (int, float)
- selection_color Widget selection color
- selection_effect Widget selector effect :py:class:`pygameMenu.widgets.Selection`
:param image_path: Path of the image of the widget
:type image_path: basestring
:param image_id: ID of the label
:type image_id: basestring
:param angle: Angle of the image in degrees (clockwise)
:type angle: int, float
:param scale: Scale of the image (x,y), float or int
:type scale: tuple, list
:param scale_smooth: Scale is smoothed
:type scale_smooth: bool
:param selectable: Image accepts user selection
:type selectable: bool
:param kwargs: Optional keywords arguments
:type kwargs: any
:return: Widget object
:rtype: :py:class:`pygameMenu.widgets.Image`
"""
assert isinstance(selectable, bool)
widget = _widgets.Image(image_path=image_path,
image_id=image_id,
angle=angle,
scale=scale,
scale_smooth=scale_smooth)
widget.is_selectable = selectable
self._current._configure_widget(widget=widget, **kwargs)
self._current._append_widget(widget)
return widget
def add_label(self,
title,
label_id='',
max_char=0,
selectable=False,
**kwargs):
"""
Add a simple text to the current Menu.
kwargs (Optional):
- align Widget alignment (str)
- font_color Widget font color (tuple)
- font_name Widget font (str)
- font_size Font size of the widget (int)
- margin Tuple of (x,y) margin (int, float)
- selection_color Widget selection color
- selection_effect Widget selector effect :py:class:`pygameMenu.widgets.Selection`
:param title: Text to be displayed
:type title: basestring
:param label_id: ID of the label
:type label_id: basestring
:param max_char: If text length exeeds this limit then split the text and add another label, if 0 there's no limit
:type max_char: int
:param selectable: Label accepts user selection
:type selectable: bool
:param kwargs: Optional keywords arguments
:type kwargs: any
:return: Widget object or List of widgets if the text overflows
:rtype: :py:class:`pygameMenu.widgets.Label`, list[:py:class:`pygameMenu.widgets.Label`]
"""
assert isinstance(label_id, str)
assert isinstance(max_char, int)
assert isinstance(selectable, bool)
assert max_char >= 0, 'max characters cannot be negative'
if len(label_id) == 0:
label_id = str(uuid4()) # If wrap
# If no overflow
if len(title) <= max_char or max_char == 0:
widget = _widgets.Label(label=title, label_id=label_id)
widget.is_selectable = selectable
self._current._configure_widget(widget=widget, **kwargs)
self._current._append_widget(widget)
else:
self._current._check_id_duplicated(label_id) # Before adding + LEN
widget = []
for line in textwrap.wrap(title, max_char):
widget.append(self.add_label(title=line,
label_id=label_id + '+' + str(len(widget) + 1),
max_char=max_char,
selectable=selectable,
**kwargs))
return widget
def add_selector(self,
title,
items,
default=0,
onchange=None,
onreturn=None,
selector_id='',
**kwargs):
"""
Add a selector to the current Menu: several items with values and
two functions that are executed when changing the selector (left/right)
and pressing return button on the selected item.
Values of the selector are like:
values = [('Item1', a, b, c...), ('Item2', a, b, c..)]
And functions onchange and onreturn does
onchange(a, b, c..., \*\*kwargs)
onreturn(a, b, c..., \*\*kwargs)
kwargs (Optional):
- align Widget alignment (str)
- font_color Widget font color (tuple)
- font_name Widget font (str)
- font_size Font size of the widget (int)
- margin Tuple of (x,y) margin (int, float)
- selection_color Widget selection color
- selection_effect Widget selector effect :py:class:`pygameMenu.widgets.Selection`
:param title: Title of the selector
:type title: basestring
:param items: Elements of the selector [('Item1', var1..), ('Item2'...)]
:type items: list
:param default: Index of default value to display
:type default: int
:param onchange: Function when changing the selector
:type onchange: callable, NoneType
:param onreturn: Function when pressing return button
:type onreturn: callable, NoneType
:param selector_id: ID of the selector
:type selector_id: basestring
:param kwargs: Additional parameters
:type kwargs: any
:return: Widget object
:rtype: :py:class:`pygameMenu.widgets.Selector`
"""
widget = _widgets.Selector(label=title,
elements=items,
selector_id=selector_id,
default=default,
onchange=onchange,
onreturn=onreturn,
**kwargs)
self._current._configure_widget(widget=widget, **kwargs)
self._current._append_widget(widget)
return widget
def add_text_input(self,
title,
default='',
enable_copy_paste=True,
enable_selection=True,
input_type=_locals.INPUT_TEXT,
input_underline='',
maxchar=0,
maxwidth=0,
onchange=None,
onreturn=None,
password=False,
textinput_id='',
valid_chars=None,
**kwargs):
"""
Add a text input to the current Menu: free text area and two functions
that execute when changing the text and pressing return button
on the element.
And functions onchange and onreturn does
onchange(current_text, \*\*kwargs)
onreturn(current_text, \*\*kwargs)
kwargs (Optional):
- align Widget alignment (str)
- font_color Widget font color (tuple)
- font_name Widget font (str)
- font_size Font size of the widget (int)
- margin Tuple of (x,y) margin (int, float)
- selection_color Widget selection color
- selection_effect Widget selector effect :py:class:`pygameMenu.widgets.Selection`
:param title: Title of the text input
:type title: basestring
:param default: Default value to display
:type default: basestring, int, float
:param enable_copy_paste: Enable text copy, paste and cut
:type enable_copy_paste: bool
:param enable_selection: Enable text selection on input
:type enable_selection: bool
:param input_type: Data type of the input
:type input_type: basestring
:param input_underline: Underline character
:type input_underline: basestring
:param maxchar: Maximum length of string, if 0 there's no limit
:type maxchar: int
:param maxwidth: Maximum size of the text widget, if 0 there's no limit
:type maxwidth: int
:param onchange: Function when changing the selector
:type onchange: callable, NoneType
:param onreturn: Function when pressing return button
:type onreturn: callable, NoneType
:param password: Text input is a password
:type password: bool
:param textinput_id: ID of the text input
:type textinput_id: basestring
:param valid_chars: List of chars to be ignored, None if no chars are invalid
:type valid_chars: list
:param kwargs: Additional keyword-parameters
:type kwargs: any
:return: Widget object
:rtype: :py:class:`pygameMenu.widgets.TextInput`
"""
assert isinstance(default, (str, int, float))
# If password is active no default value should exist
if password and default != '':
raise ValueError('default value must be empty if the input is a password')
widget = _widgets.TextInput(label=title,
textinput_id=textinput_id,
maxchar=maxchar,
maxwidth=maxwidth,
input_type=input_type,
input_underline=input_underline,
enable_copy_paste=enable_copy_paste,
enable_selection=enable_selection,
valid_chars=valid_chars,
password=password,
onchange=onchange,
onreturn=onreturn,
**kwargs)
self._current._configure_widget(widget=widget, **kwargs)
widget.set_value(default)
self._current._append_widget(widget)
return widget
def add_vertical_margin(self, margin):
"""
Adds a vertical margin to the current Menu.
:param margin: Margin in px
:type margin: int, float
:return: Widget object
:rtype: :py:class:`pygameMenu.widgets.VMargin`
"""
widget = _widgets.VMargin()
self._current._configure_widget(widget=widget, margin=(0, margin))
self._current._append_widget(widget)
return widget
def _configure_widget(self, widget, **kwargs):
"""
Update the given widget with the parameters defined at
the Menu level.
kwargs (Optional):
- align Widget alignment (str)
- font_color Widget font color (tuple)
- font_name Widget font (str)
- font_size Font size of the widget (int)
- margin Tuple of (x,y) margin (int, float)
- selection_color Widget selection color (tuple)
- selection_effect Widget selector effect (:py:class:`pygameMenu.widgets.Selection`)
- shadow_enabled Shadow is enabled or disabled (bool)
- shadow_color Text shadow color (tuple)
- shadow_position Text shadow position, see locals for position (str)
- shadow_offset Text shadow offset (int, float, NoneType)
:param widget: Widget object
:type widget: :py:class:`pygameMenu.widgets.core.widget.Widget`
:param kwargs: Optional keywords arguments
:type kwargs: any
:return: None
"""
align = kwargs.pop('align', self._widget_default_alignment)
assert isinstance(align, str)
font_color = kwargs.pop('font_folor', self._widget_default_font_color)
_utils.assert_color(font_color)
font_name = kwargs.pop('font_name', self._widget_default_font_name)
assert isinstance(font_name, str)
font_size = kwargs.pop('font_size', self._widget_default_font_size)
assert isinstance(font_size, int)
assert font_size > 0, 'font_size must be greater than zero'
margin = kwargs.pop('margin', self._widget_default_margin)
assert isinstance(margin, (tuple, list))
assert len(margin) == 2, 'margin must be a tuple or list of 2 numbers'
selection_color = kwargs.pop('selection_color', self._widget_default_selection_color)
_utils.assert_color(selection_color)
selection_effect = kwargs.pop('selection_effect', self._widget_default_selection)
assert isinstance(selection_effect, _widgets.Selection)
shadow_enabled = kwargs.pop('shadow', self._widget_default_shadow)
assert isinstance(shadow_enabled, bool)
shadow_color = kwargs.pop('shadow_color', self._widget_default_shadow_color)
_utils.assert_color(shadow_color)
shadow_position = kwargs.pop('shadow_position', self._widget_default_shadow_position)
assert isinstance(shadow_position, str)
shadow_offset = kwargs.pop('shadow_offset', self._widget_default_shadow_offset)
assert isinstance(shadow_offset, (int, float, type(None)))
_col = int((len(self._widgets) - 1) // self._rows) # Column position
# Configure the widget
widget.set_menu(self)
self._check_id_duplicated(widget.get_id())
widget.set_font(font=font_name,
font_size=font_size,
color=font_color,
selected_color=selection_color)
if self._force_fit_text and self._column_max_width[_col] is not None:
widget.set_max_width(self._column_max_width[_col] - selection_effect.get_width())
widget.set_shadow(enabled=shadow_enabled,
color=shadow_color,
position=shadow_position,
offset=shadow_offset)
widget.set_controls(self._joystick, self._mouse)
widget.set_alignment(align)
widget.set_margin(margin[0], margin[1])
widget.set_selection_effect(selection_effect)
def _append_widget(self, widget):
"""
Add a widget to the list.
:param widget: Widget object
:type widget: :py:class:`pygameMenu.widgets.core.widget.Widget`
"""
assert isinstance(widget, _widgets.Widget)
if self._columns > 1:
max_elements = self._columns * self._rows
assert len(self._widgets) + 1 <= max_elements, \
'total widgets cannot be greater than columns*rows ({0} elements)'.format(max_elements)
self._widgets.append(widget)
if self._index < 0 and widget.is_selectable:
widget.set_selected()
self._index = len(self._widgets) - 1
self._widgets_surface = None # If added on execution time forces the update of the surface
def _back(self):
"""
Go to previous Menu or close if top Menu is currently displayed.
:return: None
"""
if self._top._prev is not None:
self.reset(1)
else:
self._close()
def _update_column_width(self):
"""
Update the width of each column (self._column_widths). If the max column width is not set
the width of the column will be the maximum widget in the column.
:return: Total width of the columns
:rtype: int
"""
# Compute the available width, that is the surface width minus the max width columns
self._column_widths = [0 for _ in range(self._columns)]
for i in range(self._columns):
if self._column_max_width[i] is not None:
self._column_widths[i] = self._column_max_width[i]
# Update None columns (max width not set)
for index in range(len(self._widgets)):
widget = self._widgets[index]
rect = widget.get_rect() # type: pygame.Rect
col_index = int(index // self._rows)
selection = widget.get_selection_effect()
if self._column_max_width[col_index] is None: # No limit
self._column_widths[col_index] = max(self._column_widths[col_index],
rect.width + selection.get_width())
# If the total weight is less than the window width (so there's no horizontal scroll), scale the columns
if 0 < sum(self._column_widths) < self._width:
scale = float(self._width) / sum(self._column_widths)
for index in range(self._columns):
self._column_widths[index] *= scale
# Final column width
total_col_width = float(sum(self._column_widths))
if self._columns > 1:
# Calculate column width scale (weights)
column_weights = tuple(
float(self._column_widths[i]) / max(total_col_width, 1) for i in range(self._columns))
# Calculate the position of each column
self._column_pos_x = []
cumulative = 0
for i in range(self._columns):
w = column_weights[i]
self._column_pos_x.append(total_col_width * (cumulative + 0.5 * w))
cumulative += w
else:
self._column_pos_x = [total_col_width * 0.5]
self._column_widths = [total_col_width]
return total_col_width
def _update_widget_position(self):
"""
Update the position dict for each widget.
:return: None
"""
if self._column_widths is None:
self._update_column_width()
# Update title position
self._menubar.set_position(self._pos_x, self._pos_y)
# Store widget rects
widget_rects = {}
for widget in self._widgets: # type: _widgets.Widget
widget_rects[widget.get_id()] = widget.get_rect()
# Update appended widgets
for index in range(len(self._widgets)):
widget = self._widgets[index] # type: _widgets.Widget
rect = widget_rects[widget.get_id()] # type: pygame.Rect
selection = widget.get_selection_effect()
# Get column and row position
col = int(index // self._rows)
row = int(index % self._rows)
# Calculate X position
column_width = self._column_widths[col]
_, sel_left, sel_bottom, sel_right = selection.get_margin()
selection_margin = 0
align = widget.get_alignment()
if align == _locals.ALIGN_CENTER:
dx = -float(rect.width) / 2
elif align == _locals.ALIGN_LEFT:
selection_margin = sel_left
dx = -column_width / 2 + selection_margin
elif align == _locals.ALIGN_RIGHT:
selection_margin = sel_right
dx = column_width / 2 - rect.width - selection_margin
else:
dx = 0
x_coord = self._column_pos_x[col] + dx + widget.get_margin()[0]
x_coord = max(selection_margin, x_coord)
x_coord += self._widget_offset_x
# Calculate Y position
ysum = 0 # Compute the total height from the current row position to the top of the column
for r in range(row):
rwidget = self._widgets[int(self._rows * col + r)] # type: _widgets.Widget
ysum += widget_rects[rwidget.get_id()].height + rwidget.get_margin()[1]
y_coord = self._widget_offset_y + ysum + sel_bottom
# Update the position of the widget
widget.set_position(x_coord, y_coord)
def _get_widget_max_position(self):
"""
:return: Returns the lower rightmost position of each widgets in Menu.
:rtype: tuple
"""
max_x = -1e6
max_y = -1e6
for widget in self._widgets: # type: _widgets.Widget
_, _, x, y = widget.get_position() # Use only bottom right position
max_x = max(max_x, x)
max_y = max(max_y, y)
return max_x, max_y
def _build_widget_surface(self):
"""
Create the surface used to draw widgets according the
required width and height.
:return: None
"""
self._update_widget_position()
menubar_height = self._menubar.get_rect().height
max_x, max_y = self._get_widget_max_position()
if max_x > self._width and max_y > self._height - menubar_height:
width, height = max_x + 20, max_y + 20
if not self._mouse_visible:
self._mouse_visible = True
elif max_x > self._width:
# Remove the thick of the scrollbar
# to avoid displaying an vertical one
width, height = max_x + 20, self._height - menubar_height - 20
self._mouse_visible = self._mouse_visible_default
elif max_y > self._height - menubar_height:
# Remove the thick of the scrollbar
# to avoid displaying an horizontal one
width, height = self._width - 20, max_y + 20
if not self._mouse_visible:
self._mouse_visible = True
else:
width, height = self._width, self._height - menubar_height
self._mouse_visible = self._mouse_visible_default
self._widgets_surface = _utils.make_surface(width, height)
self._scroll.set_world(self._widgets_surface)
self._scroll.set_position(self._pos_x, self._pos_y + menubar_height + 5)
def _check_id_duplicated(self, widget_id):
"""
Check if widget ID is duplicated.
:param widget_id: New widget ID
:type widget_id: basestring
:return: None
"""
for widget in self._widgets: # type: _widgets.Widget
if widget.get_id() == widget_id:
raise ValueError('The widget ID="{0}" is duplicated'.format(widget_id))
def _close(self):
"""
Execute close callbacks and disable the Menu.
:return: True if Menu has been disabled
:rtype: bool
"""
onclose = self._onclose
if onclose is None:
close = False
else:
close = True
a = isinstance(onclose, _events.PymenuAction)
b = str(type(onclose)) == "<class 'pygameMenu.events.PymenuAction'>" # python compatibility
if a or b:
if onclose == _events.DISABLE_CLOSE:
close = False
else:
self.disable() # Closing disables the Menu
# Sort through events
if onclose == _events.RESET:
self.full_reset()
elif onclose == _events.BACK:
self.reset(1)
elif onclose == _events.EXIT:
self._exit()
elif isinstance(onclose, (types.FunctionType, types.MethodType)):
onclose()
return close
def _get_depth(self):
"""
Find Menu depth.
:return: Depth
:rtype: int
"""
if self._top is None:
return 0
prev = self._top._prev # type: list
depth = 0
while True:
if prev is not None:
prev = prev[0]
depth += 1
else:
break
return depth
def disable(self):
"""
Disables the Menu (doesn't check events and draw on the surface).
:return: None
"""
self._top._enabled = False
def set_relative_position(self, position_x, position_y, current=True):
"""
Set the menu position relative to the window.
- Menu left position (x) must be between 0 and 100, if 0 the margin
is at the left of the window, if 100 the menu is at the right
of the window.
- Menu top position (y) must be between 0 and 100, if 0 the margin is
at the top of the window, if 100 the margin is at the bottom of
the window.
:param position_x: Left position of the window
:type position_x: int, float
:param position_y: Top position of the window
:type position_y: int, float
:param current: If true, centers the current active Menu, otherwise center the base Menu
:type current: bool
:return: None
"""
assert isinstance(position_x, (int, float))
assert isinstance(position_y, (int, float))
assert 0 <= position_x <= 100
assert 0 <= position_y <= 100
isinstance(current, bool)
position_x = float(position_x) / 100
position_y = float(position_y) / 100
window_width, window_height = pygame.display.get_surface().get_size()
if current:
self._current._pos_x = (window_width - self._current._width) * position_x
self._current._pos_y = (window_height - self._current._height) * position_y
else:
self._pos_x = (window_width - self._width) * position_x
self._pos_y = (window_height - self._height) * position_y
self._widgets_surface = None # This forces an update of the widgets
def center_content(self, current=True):
"""
Update draw_region_y based on the current widgets, centering the content
of the window.
If the height of the widgets is greater than the height of the Menu,
the drawing region will start at zero, using all the height for the scrollbar.
:param current: If true, centers the current active Menu, otherwise center the base Menu
:type current: bool
:return: None
"""
isinstance(current, bool)
if current:
self._current._center_content()
else:
self._center_content()
def _center_content(self):
"""
Update draw_region_y based on the current widgets.
If the height of the widgets is greater than the height of the Menu,
the drawing region will start at zero.
:return: None
"""
self._build_widget_surface()
horizontal_scroll = self._scroll.get_scrollbar_thickness(_locals.ORIENTATION_HORIZONTAL)
_, max_y = self._get_widget_max_position()
max_y -= self._widget_offset_y # Only use total height
available = self._height - self._menubar.get_rect().height - horizontal_scroll
new_pos = max((available - max_y) / (2.0 * self._height), 0) # Percentage of height
self._widget_offset_y = self._height * new_pos
self._build_widget_surface() # Rebuild
def draw(self, surface):
"""
Draw the current Menu into the given surface.
:param surface: Pygame surface to draw the Menu
:type surface: pygame.surface.SurfaceType
:return: None
"""
if not self.is_enabled():
raise RuntimeError('Menu is not enabled, it cannot be drawn')
# The surface may has been erased because the number
# of widgets has changed and thus size shall be calculated.
if not self._current._widgets_surface:
self._current._build_widget_surface()
# Fill the surface with background function (setted from mainloop)
if self._top._background_function is not None:
self._top._background_function()
# Fill the scrolling surface
self._current._widgets_surface.fill((255, 255, 255, 0))
# Draw widgets
for widget in self._current._widgets: # type: _widgets.Widget
widget.draw(self._current._widgets_surface)
if widget.selected:
widget.draw_selected_rect(self._current._widgets_surface)
self._current._scroll.draw(surface)
self._current._menubar.draw(surface)
def enable(self):
"""
Enables Menu (can check events and draw).
:return: None
"""
self._top._enabled = True
def toggle(self):
"""
Switch between enable and disable.
:return: None
"""
self._top._enabled = not self._top._enabled
@staticmethod
def _exit():
"""
Internal exit function.
:return: None
"""
pygame.quit()
sys.exit()
def is_enabled(self):
"""
Returns True if Menu is enabled else False is returned.
:return: True if the Menu is enabled
:rtype: bool
"""
return self._top._enabled
def _left(self):
"""
Left event (column support).
"""
if self._index >= self._rows:
self._select(self._index - self._rows)
else:
self._select(0, 1)
def _right(self):
"""
Right event (column support).
"""
if self._index + self._rows < len(self._widgets):
self._select(self._index + self._rows)
else:
self._select(len(self._widgets) - 1)
def _handle_joy_event(self):
"""
Handle joy events.
"""
if self._joy_event & _JOY_EVENT_UP:
self._select(self._index - 1)
if self._joy_event & _JOY_EVENT_DOWN:
self._select(self._index + 1)
if self._joy_event & _JOY_EVENT_LEFT:
self._left()
if self._joy_event & _JOY_EVENT_RIGHT:
self._right()
def update(self, events):
"""
Update the status of the Menu using external events.
The update event is applied only on the current Menu.
:param events: Pygame events as a list
:type events: list
:return: True if mainloop must be stopped
:rtype: bool
"""
assert isinstance(events, list)
# If any widget status changes, set the status as True
updated = False
# Update mouse
pygame.mouse.set_visible(self._current._mouse_visible)
# Surface needs an update
menu_surface_needs_update = False
# Update scroll bars
if self._current._scroll.update(events):
updated = True
# Update the menubar, it may change the status of the widget because
# of the button back/close
elif self._current._menubar.update(events):
updated = True
# Check selected widget
elif len(self._current._widgets) > 0 and self._current._widgets[self._current._index].update(events):
updated = True
# Check others
else:
for event in events: # type: pygame.event.EventType
# noinspection PyUnresolvedReferences
if event.type == pygame.locals.QUIT or (
event.type == pygame.KEYDOWN and event.key == pygame.K_F4 and (
event.mod == pygame.KMOD_LALT or event.mod == pygame.KMOD_RALT)):
self._current._exit()
updated = True
elif event.type == pygame.locals.KEYDOWN:
# Check key event is valid
if not _utils.check_key_pressed_valid(event):
continue
if event.key == _controls.KEY_MOVE_DOWN:
self._current._select(self._current._index - 1)
self._current._sounds.play_key_add()
elif event.key == _controls.KEY_MOVE_UP:
self._current._select(self._current._index + 1)
self._current._sounds.play_key_add()
elif event.key == _controls.KEY_LEFT and self._current._columns > 1:
self._current._left()
self._current._sounds.play_key_add()
elif event.key == _controls.KEY_RIGHT and self._current._columns > 1:
self._current._right()
self._current._sounds.play_key_add()
elif event.key == _controls.KEY_BACK and self._top._prev is not None:
self._current._sounds.play_close_menu()
self.reset(1) # public, do not use _current
elif event.key == _controls.KEY_CLOSE_MENU:
self._current._sounds.play_close_menu()
if self._current._close():
updated = True
elif self._current._joystick and event.type == pygame.JOYHATMOTION:
if event.value == _controls.JOY_UP:
self._current._select(self._current._index - 1)
elif event.value == _controls.JOY_DOWN:
self._current._select(self._current._index + 1)
elif event.value == _controls.JOY_LEFT and self._columns > 1:
self._current._select(self._current._index - 1)
elif event.value == _controls.JOY_RIGHT and self._columns > 1:
self._current._select(self._current._index + 1)
elif self._current._joystick and event.type == pygame.JOYAXISMOTION:
prev = self._current._joy_event
self._current._joy_event = 0
if event.axis == _controls.JOY_AXIS_Y and event.value < -_controls.JOY_DEADZONE:
self._current._joy_event |= _JOY_EVENT_UP
if event.axis == _controls.JOY_AXIS_Y and event.value > _controls.JOY_DEADZONE:
self._current._joy_event |= _JOY_EVENT_DOWN
if event.axis == _controls.JOY_AXIS_X and event.value < -_controls.JOY_DEADZONE and self._columns > 1:
self._current._joy_event |= _JOY_EVENT_LEFT
if event.axis == _controls.JOY_AXIS_X and event.value > _controls.JOY_DEADZONE and self._columns > 1:
self._current._joy_event |= _JOY_EVENT_RIGHT
if self._current._joy_event:
self._current._handle_joy_event()
if self._current._joy_event == prev:
pygame.time.set_timer(_JOY_EVENT_REPEAT, _controls.JOY_REPEAT)
else:
pygame.time.set_timer(_JOY_EVENT_REPEAT, _controls.JOY_DELAY)
else:
pygame.time.set_timer(_JOY_EVENT_REPEAT, 0)
elif event.type == _JOY_EVENT_REPEAT:
if self._current._joy_event:
self._current._handle_joy_event()
pygame.time.set_timer(_JOY_EVENT_REPEAT, _controls.JOY_REPEAT)
else:
pygame.time.set_timer(_JOY_EVENT_REPEAT, 0)
elif self._current._mouse and event.type == pygame.MOUSEBUTTONDOWN:
for index in range(len(self._current._widgets)):
widget = self._current._widgets[index]
# Don't considere the mouse wheel (button 4 & 5)
if event.button in (1, 2, 3) and \
self._current._scroll.to_real_position(widget.get_rect()).collidepoint(*event.pos):
self._current._select(index)
elif self._current._mouse and event.type == pygame.MOUSEBUTTONUP:
self._current._sounds.play_click_mouse()
widget = self._current._widgets[self._current._index]
# Don't considere the mouse wheel (button 4 & 5)
if event.button in (1, 2, 3) and \
self._current._scroll.to_real_position(widget.get_rect()).collidepoint(*event.pos):
new_event = pygame.event.Event(event.type, **event.dict)
new_event.dict['origin'] = self._current._scroll.to_real_position((0, 0))
new_event.pos = self._current._scroll.to_world_position(event.pos)
widget.update((new_event,)) # This widget can change the current Menu to a submenu
menu_surface_needs_update = menu_surface_needs_update or widget.surface_needs_update()
updated = True # It is updated
break
# Check if the position has changed
if len(self._current._widgets) > 0:
menu_surface_needs_update = menu_surface_needs_update or self._current._widgets[
self._current._index].surface_needs_update()
# This forces the rendering of all widgets
if menu_surface_needs_update:
self._current._widgets_surface = None
# A widget has closed the Menu
if not self.is_enabled():
updated = True
return updated
def mainloop(self, surface, bgfun=None, disable_loop=False, fps_limit=30):
"""
Main loop of Menu. In this function, the Menu handle exceptions and draw.
The Menu pauses the application and checks :py:mod:`pygame` events itself.
This method returns until the menu is updated (a widget status has changed).
The execution of the mainloop is at the current Menu level.
.. code-block:: python
menu = pygameMenu.Menu(...)
menu.mainloop(surface)
:param surface: Pygame surface to draw the Menu
:type surface: pygame.surface.SurfaceType
:param bgfun: Background function called on each loop iteration before drawing the Menu
:type bgfun: callable
:param disable_loop: If true run this method for only 1 loop
:type disable_loop: bool
:param fps_limit: Limit frame per second of the loop, if 0 there's no limit
:type fps_limit: int, float
:return: None
"""
assert isinstance(surface, pygame.Surface)
if bgfun:
assert callable(bgfun), 'background function must be callable (a function)'
assert isinstance(disable_loop, bool)
assert isinstance(fps_limit, (int, float))
assert fps_limit >= 0, 'fps limit cannot be negative'
# NOTE: For Menu accesor, use only _current, as the Menu pointer can change through the execution
if not self.is_enabled():
return
self._background_function = bgfun
while True:
self._current._clock.tick(fps_limit)
# If loop, gather events by Menu and draw the background function, if this method
# returns true then the mainloop will break
self.update(pygame.event.get())
# As event can change the status of the Menu, this has to be checked twice
if self.is_enabled():
self.draw(surface=surface)
pygame.display.flip()
if not self.is_enabled() or disable_loop:
self._background_function = None
return
def get_input_data(self, recursive=False, current=True):
"""
Return input data from a Menu. The results are given as a dict object.
The keys are the ID of each element.
With ``recursive=True``: it collect also data inside the all sub-menus.
:param recursive: Look in Menu and sub-menus
:type recursive: bool
:param current: If True, returns the value from the current active Menu, otherwise from the base Menu
:type current: bool
:return: Input dict e.g.: {'id1': value, 'id2': value, ...}
:rtype: dict
"""
assert isinstance(recursive, bool)
assert isinstance(current, bool)
if current:
return self._current._get_input_data(recursive, depth=0)
return self._get_input_data(recursive, depth=0)
def _get_input_data(self, recursive, depth):
"""
Return input data from a Menu. The results are given as a dict object.
The keys are the ID of each element.
With ``recursive=True``: it collect also data inside the all sub-menus.
:param recursive: Look in Menu and sub-menus
:type recursive: bool
:param depth: Depth of the input data
:type depth: int
:return: Input dict e.g.: {'id1': value, 'id2': value, ...}
:rtype: dict
"""
data = {}
for widget in self._widgets: # type: _widgets.Widget
try:
data[widget.get_id()] = widget.get_value()
except ValueError: # Widget does not return data
pass
if recursive:
depth += 1
for menu in self._submenus: # type: Menu
data_submenu = menu._get_input_data(recursive=recursive, depth=depth)
# Check if there is a collision between keys
data_keys = data.keys()
subdata_keys = data_submenu.keys()
for key in subdata_keys: # type: str
if key in data_keys:
msg = 'Collision between widget data ID="{0}" at depth={1}'.format(key, depth)
raise ValueError(msg)
# Update data
data.update(data_submenu)
return data
def get_rect(self, current=True):
"""
Return Menu pygame Rect.
:param current: If True, returns the value from the current active Menu, otherwise from the base Menu
:type current: bool
:return: Rect
:rtype: pygame.rect.RectType
"""
if current:
return pygame.Rect(self._current._pos_x, self._current._pos_y,
self._current._width, self._current._height)
return pygame.Rect(self._pos_x, self._pos_y, self._width, self._height)
def set_sound(self, sound, recursive=False):
"""
Add a sound engine to the Menu. If ``recursive=True``, the sound is
applied to all submenus.
The sound is applied only to the base Menu (not the currently displayed).
:param sound: Sound object
:type sound: :py:class:`pygameMenu.sound.Sound`, NoneType
:param recursive: Set the sound engine to all submenus
:type recursive: bool
:return: None
"""
assert isinstance(sound, (type(self._sounds), type(None)))
if sound is None:
sound = Sound()
self._sounds = sound
for widget in self._widgets: # type: _widgets.Widget
widget.set_sound(sound)
if recursive:
for menu in self._submenus: # type: Menu
menu.set_sound(sound, recursive=True)
def get_title(self, current=True):
"""
Return title of the Menu.
:param current: If True, return the title of currently displayed Menu
:type current: bool
:return: Title
:rtype: basestring
"""
if current:
return self._current._menubar.get_title()
return self._menubar.get_title()
def full_reset(self, current=True):
"""
Reset the Menu back to the first opened Menu.
:param current: If True, reset from current Menu, otherwise reset from base Menu
:type current: bool
:return: None
"""
if current:
depth = self._current._get_depth()
else:
depth = self._get_depth()
if depth > 0:
self.reset(depth) # public, do not use _current
def clear(self, current=True):
"""
Full reset Menu and clear all widgets.
:param current: If True, clear from current active Menu, otherwise clears base Menu
:type current: bool
:return: None
"""
assert isinstance(current, bool)
self.full_reset(current=current) # public, do not use _current
if current:
del self._current._widgets[:]
del self._current._submenus[:]
else:
del self._widgets[:]
del self._submenus[:]
def _open(self, menu):
"""
Open the given Menu.
:param menu: Menu object
:type menu: Menu
:return: None
"""
current = self
# Update pointers
menu._top = self._top
self._top._current = menu._current
self._top._prev = [self._top._prev, current]
# Select the first widget
self._select(0, 1)
def reset(self, total):
"""
Go back in Menu history a certain number of times from the current Menu.
:param total: How many menus to go back
:type total: int
:return: None
"""
assert isinstance(total, int)
assert total > 0, 'total must be greater than zero'
i = 0
while True:
if self._top._prev is not None:
prev = self._top._prev
self._top._current = prev[1] # This changes the "current" pointer
self._top._prev = prev[0] # Eventually will reach None
i += 1
if i == total:
break
else:
break
self._current._select(self._top._current._index)
def _select(self, new_index, dwidget=0):
"""
Select the widget at the given index and unselect others.
Selection forces rendering of the widget.
:param new_index: Widget index
:type new_index: int
:param dwidget: Direction to search if the new_index widget is non selectable
:type dwidget: int
:return: None
"""
current = self._top._current
if len(current._widgets) == 0:
return
# This stores +/-1 if the index increases or decreases
# Used by non-selectable selection
if dwidget == 0:
if new_index < current._index:
dwidget = -1
else:
dwidget = 1
# Limit the index to the length
new_index %= len(current._widgets)
if new_index == current._index: # Index has not changed
return
# Get both widgets
old_widget = current._widgets[current._index] # type: _widgets.Widget
new_widget = current._widgets[new_index] # type:_widgets.Widget
# If new widget is not selectable
if not new_widget.is_selectable:
if current._index >= 0: # There's at least 1 selectable option (if only text this would be false)
current._select(new_index + dwidget)
return
else: # No selectable options, quit
return
# Selecting widgets forces rendering
old_widget.set_selected(False)
current._index = new_index # Update selected index
new_widget.set_selected()
# Scroll to rect
rect = new_widget.get_rect()
if current._index == 0: # Scroll to the top of the Menu
rect = pygame.Rect(rect.x, 0, rect.width, rect.height)
current._scroll.scroll_to_rect(rect)
def get_id(self, current=True):
"""
Returns the ID of the Menu.
:param current: If True, returns the value from the current active Menu, otherwise returns from the base Menu
:type current: bool
:return: Menu ID
:rtype: basestring
"""
assert isinstance(current, bool)
if current:
return self._current._id
return self._id
def get_widget(self, widget_id, recursive=False, current=True):
"""
Return a widget by a given ID.
With ``recursive=True``: it looks for a widget in the Menu
and all sub-menus. Use ``current`` for getting from current and
base Menu.
None is returned if no widget found.
:param widget_id: Widget ID
:type widget_id: basestring
:param recursive: Look in Menu and submenus
:type recursive: bool
:param current: If True, returns the value from the current active Menu, otherwise from the base Menu
:type current: bool
:return: Widget object
:rtype: :py:class:`pygameMenu.widgets.core.widget.Widget`
"""
assert isinstance(widget_id, str)
assert isinstance(recursive, bool)
assert isinstance(current, bool)
if current:
return self._current._get_widget(widget_id, recursive)
return self._get_widget(widget_id, recursive)
def _get_widget(self, widget_id, recursive):
"""
Return a widget by a given ID.
With ``recursive=True``: it looks for a widget in the Menu
and all sub-menus. Use ``current`` for getting from current and
base Menu.
None is returned if no widget found.
:param widget_id: Widget ID
:type widget_id: basestring
:param recursive: Look in Menu and submenus
:type recursive: bool
:return: Widget object
:rtype: :py:class:`pygameMenu.widgets.core.widget.Widget`
"""
for widget in self._widgets: # type: _widgets.Widget
if widget.get_id() == widget_id:
return widget
if recursive:
for menu in self._submenus: # type: Menu
widget = menu.get_widget(widget_id, recursive)
if widget:
return widget
return None
def get_index(self, current=True):
"""
Get selected widget from the current Menu.
:param current: If True, returns the value from the current active Menu, otherwise returns from the base Menu
:type current: bool
:return: Selected widget index
:rtype: int
"""
assert isinstance(current, bool)
if current:
return self._current._index
return self._index
def get_selected_widget(self, current=True):
"""
Return the currently selected widget.
:param current: If True, returns the value from the current active Menu, otherwise from the base Menu
:type current: bool
:return: Widget object
:rtype: :py:class:`pygameMenu.widgets.core.widget.Widget`
"""
assert isinstance(current, bool)
if current:
return self._current._widgets[self._current._index]
return self._widgets[self._index]
|
{"/pygameMenu/themes.py": ["/pygameMenu/utils.py"], "/pygameMenu/menu.py": ["/pygameMenu/utils.py", "/pygameMenu/widgets/__init__.py"], "/pygameMenu/widgets/__init__.py": ["/pygameMenu/widgets/selection/highlight.py", "/pygameMenu/widgets/selection/none.py"]}
|
6,758
|
brleinad/pygame-menu
|
refs/heads/master
|
/pygameMenu/widgets/selection/none.py
|
# coding=utf-8
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
HIGHLIGHT
Widget selection highlight box effect.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2020 Pablo Pizarro R. @ppizarror
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-------------------------------------------------------------------------------
"""
from pygameMenu.widgets.core.selection import Selection
class NoneSelection(Selection):
"""
No selection.
"""
def __init__(self):
super(NoneSelection, self).__init__(margin_left=0, margin_right=0,
margin_top=0, margin_bottom=0)
def get_margin(self):
"""
Return top, left, bottom and right margins of the selection.
:return: Tuple of (t,l,b,r) margins in px
:rtype: tuple
"""
return 0, 0, 0, 0
def draw(self, surface, widget):
"""
Draw the selection.
:param surface: Surface to draw
:type surface: pygame.surface.SurfaceType
:param widget: Widget object
:type widget: pygameMenu.widgets.core.widget.Widget
:return: None
"""
pass
|
{"/pygameMenu/themes.py": ["/pygameMenu/utils.py"], "/pygameMenu/menu.py": ["/pygameMenu/utils.py", "/pygameMenu/widgets/__init__.py"], "/pygameMenu/widgets/__init__.py": ["/pygameMenu/widgets/selection/highlight.py", "/pygameMenu/widgets/selection/none.py"]}
|
6,759
|
brleinad/pygame-menu
|
refs/heads/master
|
/pygameMenu/examples/multi_input.py
|
# coding=utf-8
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
EXAMPLE - MULTI-INPUT
Shows different inputs (widgets).
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2020 Pablo Pizarro R. @ppizarror
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-------------------------------------------------------------------------------
"""
# Import libraries
import sys
sys.path.insert(0, '../../')
import os
import pygame
import pygameMenu
# -----------------------------------------------------------------------------
# Constants and global variables
# -----------------------------------------------------------------------------
COLOR_BLACK = (0, 0, 0)
COLOR_WHITE = (255, 255, 255)
FPS = 60.0
MENU_BACKGROUND_COLOR = (228, 100, 36)
TITLE_BACKGROUND_COLOR = (170, 65, 50)
WINDOW_SIZE = (640, 480)
# noinspection PyTypeChecker
sound = None # type: pygameMenu.sound.Sound
# noinspection PyTypeChecker
surface = None # type: pygame.Surface
# noinspection PyTypeChecker
main_menu = None # type: pygameMenu.Menu
# -----------------------------------------------------------------------------
# Methods
# -----------------------------------------------------------------------------
def main_background():
"""
Background color of the main menu, on this function user can plot
images, play sounds, etc.
:return: None
"""
global surface
surface.fill((40, 40, 40))
def check_name_test(value):
"""
This function tests the text input widget.
:param value: The widget value
:type value: basestring
:return: None
"""
print('User name: {0}'.format(value))
# noinspection PyUnusedLocal
def update_menu_sound(value, enabled):
"""
Update menu sound.
:param value: Value of the selector (Label and index)
:type value: tuple
:param enabled: Parameter of the selector, (True/False)
:type enabled: bool
:return: None
"""
global main_menu
global sound
if enabled:
main_menu.set_sound(sound, recursive=True)
print('Menu sounds were enabled')
else:
main_menu.set_sound(None, recursive=True)
print('Menu sounds were disabled')
def main(test=False):
"""
Main program.
:param test: Indicate function is being tested
:type test: bool
:return: None
"""
# -------------------------------------------------------------------------
# Globals
# -------------------------------------------------------------------------
global main_menu
global sound
global surface
# -------------------------------------------------------------------------
# Init pygame
# -------------------------------------------------------------------------
pygame.init()
os.environ['SDL_VIDEO_CENTERED'] = '1'
# Create pygame screen and objects
surface = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption('Example - Multi Input')
clock = pygame.time.Clock()
# -------------------------------------------------------------------------
# Set sounds
# -------------------------------------------------------------------------
sound = pygameMenu.sound.Sound()
# Load example sounds
sound.load_example_sounds()
# Disable a sound
sound.set_sound(pygameMenu.sound.SOUND_TYPE_ERROR, None)
# -------------------------------------------------------------------------
# Create menus: Settings
# -------------------------------------------------------------------------
settings_menu = pygameMenu.Menu(font=pygameMenu.font.FONT_HELVETICA,
menu_background_color=MENU_BACKGROUND_COLOR,
menu_height=WINDOW_SIZE[1] * 0.85,
menu_width=WINDOW_SIZE[0] * 0.9,
onclose=pygameMenu.events.DISABLE_CLOSE,
title='Settings',
title_background_color=TITLE_BACKGROUND_COLOR,
widget_alignment=pygameMenu.locals.ALIGN_LEFT,
widget_font_color=COLOR_BLACK,
widget_font_size=25,
widget_margin_x=10,
)
# Add text inputs with different configurations
wid1 = settings_menu.add_text_input('First name: ',
default='John',
onreturn=check_name_test,
textinput_id='first_name')
wid2 = settings_menu.add_text_input('Last name: ',
default='Rambo',
maxchar=10,
textinput_id='last_name',
input_underline='.')
settings_menu.add_text_input('Your age: ',
default=25,
maxchar=3,
maxwidth=3,
textinput_id='age',
input_type=pygameMenu.locals.INPUT_INT,
enable_selection=False)
settings_menu.add_text_input('Some long text: ',
maxwidth=19,
textinput_id='long_text',
input_underline='_')
settings_menu.add_text_input('Password: ',
maxchar=6,
password=True,
textinput_id='pass',
input_underline='_')
# Create selector with 3 difficulty options
settings_menu.add_selector('Select difficulty ',
[('Easy', 'EASY'),
('Medium', 'MEDIUM'),
('Hard', 'HARD')],
selector_id='difficulty',
default=1)
def data_fun():
"""
Print data of the menu.
:return: None
"""
print('Settings data:')
data = settings_menu.get_input_data()
for k in data.keys():
print(u'\t{0}\t=>\t{1}'.format(k, data[k]))
settings_menu.add_button('Store data', data_fun) # Call function
settings_menu.add_button('Return to main menu', pygameMenu.events.BACK,
align=pygameMenu.locals.ALIGN_CENTER)
settings_menu.center_content() # After all widgets added
# -------------------------------------------------------------------------
# Create menus: More settings
# -------------------------------------------------------------------------
more_settings_menu = pygameMenu.Menu(font=pygameMenu.font.FONT_COMIC_NEUE,
menu_background_color=MENU_BACKGROUND_COLOR,
menu_height=WINDOW_SIZE[1] * 0.85,
menu_width=WINDOW_SIZE[0] * 0.9,
onclose=pygameMenu.events.DISABLE_CLOSE,
selection_color=COLOR_WHITE,
title='More Settings',
title_background_color=TITLE_BACKGROUND_COLOR,
widget_alignment=pygameMenu.locals.ALIGN_LEFT,
widget_font_color=COLOR_BLACK,
widget_font_size=25,
widget_offset_x=5, # px
widget_offset_y=10, # px
)
more_settings_menu.add_image(pygameMenu.baseimage.IMAGE_PYGAME_MENU,
scale=(0.25, 0.25),
align=pygameMenu.locals.ALIGN_CENTER)
more_settings_menu.add_color_input('Color 1 RGB: ', color_type='rgb')
more_settings_menu.add_color_input('Color 2 RGB: ', color_type='rgb', default=(255, 0, 0), input_separator='-')
def print_color(color):
"""
Test onchange/onreturn.
:param color: Color tuple
:type color: tuple
:return: None
"""
print('Returned color: ', color)
more_settings_menu.add_color_input('Color in Hex: ', color_type='hex', onreturn=print_color)
more_settings_menu.add_vertical_margin(25)
more_settings_menu.add_button('Return to main menu', pygameMenu.events.BACK,
align=pygameMenu.locals.ALIGN_CENTER)
# -------------------------------------------------------------------------
# Create menus: Column buttons
# -------------------------------------------------------------------------
button_column_menu = pygameMenu.Menu(columns=2,
font=pygameMenu.font.FONT_COMIC_NEUE,
menu_background_color=MENU_BACKGROUND_COLOR,
menu_height=WINDOW_SIZE[1] * 0.45,
menu_width=WINDOW_SIZE[0] * 0.9,
onclose=pygameMenu.events.DISABLE_CLOSE,
rows=3,
selection_color=COLOR_WHITE,
title='Columns',
title_background_color=TITLE_BACKGROUND_COLOR,
widget_font_color=COLOR_BLACK,
widget_font_size=25,
)
for i in range(4):
button_column_menu.add_button('Button {0}'.format(i), pygameMenu.events.BACK)
button_column_menu.add_button('Return to main menu', pygameMenu.events.BACK)
button_column_menu.center_content()
# -------------------------------------------------------------------------
# Create menus: Main menu
# -------------------------------------------------------------------------
main_menu = pygameMenu.Menu(font=pygameMenu.font.FONT_COMIC_NEUE,
menu_background_color=MENU_BACKGROUND_COLOR,
menu_height=WINDOW_SIZE[1] * 0.7,
menu_width=WINDOW_SIZE[0] * 0.8,
onclose=pygameMenu.events.EXIT, # User press ESC button
selection_color=COLOR_WHITE,
title='Main menu',
title_background_color=TITLE_BACKGROUND_COLOR,
widget_font_color=COLOR_BLACK,
widget_font_size=30,
widget_offset_y=0.09,
)
main_menu.add_button('Settings', settings_menu)
main_menu.add_button('More Settings', more_settings_menu)
main_menu.add_button('Menu in columns!', button_column_menu)
main_menu.add_selector('Menu sounds ',
[('Off', False), ('On', True)],
onchange=update_menu_sound)
main_menu.add_button('Quit', pygameMenu.events.EXIT)
assert main_menu.get_widget('first_name', recursive=True) is wid1
assert main_menu.get_widget('last_name', recursive=True) is wid2
assert main_menu.get_widget('last_name') is None
# -------------------------------------------------------------------------
# Main loop
# -------------------------------------------------------------------------
while True:
# Tick
clock.tick(FPS)
# Paint background
main_background()
# Main menu
main_menu.mainloop(surface, main_background, disable_loop=test, fps_limit=FPS)
# Flip surface
pygame.display.flip()
# At first loop returns
if test:
break
if __name__ == '__main__':
main()
|
{"/pygameMenu/themes.py": ["/pygameMenu/utils.py"], "/pygameMenu/menu.py": ["/pygameMenu/utils.py", "/pygameMenu/widgets/__init__.py"], "/pygameMenu/widgets/__init__.py": ["/pygameMenu/widgets/selection/highlight.py", "/pygameMenu/widgets/selection/none.py"]}
|
6,760
|
brleinad/pygame-menu
|
refs/heads/master
|
/pygameMenu/examples/simple.py
|
# coding=utf-8
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
EXAMPLE - SIMPLE
Super simple example of pygame-menu usage, featuring a selector and a button.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2020 Pablo Pizarro R. @ppizarror
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-------------------------------------------------------------------------------
"""
import os
import pygame
import pygameMenu
pygame.init()
os.environ['SDL_VIDEO_CENTERED'] = '1'
surface = pygame.display.set_mode((600, 500))
def set_difficulty(selected, value):
"""
Set the difficulty of the game.
:return: None
"""
print('Set difficulty to {} ({})'.format(selected[0], value))
def start_the_game():
"""
Function that starts a game. This is raised by the menu button,
here menu can be disabled, etc.
:return: None
"""
print('Do the job here !')
menu = pygameMenu.Menu(300, 400, pygameMenu.font.FONT_BEBAS, 'Welcome',
widget_font_color=(102, 122, 130),
selection_color=(207, 62, 132),
title_font_color=(38, 158, 151),
title_background_color=(4, 47, 58),
menu_background_color=(239, 231, 211))
menu.add_text_input('Name: ')
menu.add_selector('Difficulty: ', [('Hard', 1), ('Easy', 2)], onchange=set_difficulty)
menu.add_button('Play', start_the_game)
menu.add_button('Quit', pygameMenu.events.EXIT)
menu.center_content()
if __name__ == '__main__':
menu.mainloop(surface)
|
{"/pygameMenu/themes.py": ["/pygameMenu/utils.py"], "/pygameMenu/menu.py": ["/pygameMenu/utils.py", "/pygameMenu/widgets/__init__.py"], "/pygameMenu/widgets/__init__.py": ["/pygameMenu/widgets/selection/highlight.py", "/pygameMenu/widgets/selection/none.py"]}
|
6,761
|
brleinad/pygame-menu
|
refs/heads/master
|
/pygameMenu/widgets/__init__.py
|
# coding=utf-8
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
WIDGETS
Widgets elements that can be added to the menu.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2020 Pablo Pizarro R. @ppizarror
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-------------------------------------------------------------------------------
"""
# Core
from pygameMenu.widgets.core.widget import Widget
from pygameMenu.widgets.core.selection import Selection
# Selection
from pygameMenu.widgets.selection.highlight import HighlightSelection
from pygameMenu.widgets.selection.none import NoneSelection
# Widgets
from pygameMenu.widgets.widget.button import Button
from pygameMenu.widgets.widget.colorinput import ColorInput
from pygameMenu.widgets.widget.image import Image
from pygameMenu.widgets.widget.label import Label
from pygameMenu.widgets.widget.menubar import MenuBar
from pygameMenu.widgets.widget.scrollbar import ScrollBar
from pygameMenu.widgets.widget.selector import Selector
from pygameMenu.widgets.widget.textinput import TextInput
from pygameMenu.widgets.widget.vmargin import VMargin
|
{"/pygameMenu/themes.py": ["/pygameMenu/utils.py"], "/pygameMenu/menu.py": ["/pygameMenu/utils.py", "/pygameMenu/widgets/__init__.py"], "/pygameMenu/widgets/__init__.py": ["/pygameMenu/widgets/selection/highlight.py", "/pygameMenu/widgets/selection/none.py"]}
|
6,773
|
adiljumak/MultiPlayer_Tank_Game_RabbitMQ_MongoDB
|
refs/heads/main
|
/menu.py
|
import pygame
import os
from button import Button
pygame.init()
WHICH_ROOM = 1
size_w = 800
size_h = 600
screen = pygame.display.set_mode((size_w, size_h))
menu_background = pygame.image.load("menu_background.png").convert()
menu_background = pygame.transform.scale(menu_background, (size_w, size_h))
run = True
MAIN_MENU = True
SINGLE_PLAY = False
MULTI_PLAY = False
MULTI_AI_PLAY = False
def click_button_single():
global MAIN_MENU, SINGLE_PLAY, MULTI_PLAY, MULTI_AI_PLAY
#os.startfile('main.py')
SINGLE_PLAY = True
MAIN_MENU = False
def click_button_multi():
global MAIN_MENU, SINGLE_PLAY, MULTI_PLAY, MULTI_AI_PLAY
#os.startfile('multi_main.py')
MULTI_PLAY = True
MAIN_MENU = False
def click_button_multi_AI():
global MAIN_MENU, SINGLE_PLAY, MULTI_PLAY, MULTI_AI_PLAY
#print('ok good MULTI AI')
MULTI_AI_PLAY = True
MAIN_MENU = False
button_single = Button(410, 350, "Одиночная игра", click_button_single)
button_multi = Button(130, 350,"Мультиплеер", click_button_multi)
button_multi_AI = Button(670, 350,"Мультиплеер ИИ", click_button_multi_AI)
buttons = [button_single, button_multi, button_multi_AI]
rooms = []
room_num = 1
for i in range(1, 7):
for j in range(1,6):
text = 'room: {}'.format(room_num)
rooms.append(Button(j * 160 - 80, i * 100 - 50, text, room_num))
room_num += 1
while run:
if MAIN_MENU:
pos = pygame.mouse.get_pos()
screen.blit(menu_background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
for button in buttons:
if button.x - 100 <= pos[0] <= button.x + 100 and button.y - 20 <= pos[1] <= button.y + 20:
button.func()
for button in buttons:
button.draw(screen)
pygame.display.flip()
elif SINGLE_PLAY:
os.startfile('main.py')
run = False
else:
pos = pygame.mouse.get_pos()
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
for room in rooms:
if room.x - 50 <= pos[0] <= room.x + 50 and room.y - 20 <= pos[1] <= room.y + 20:
WHICH_ROOM = room.func
run = False
if MULTI_PLAY:
os.startfile('multi_main.py')
run = False
if MULTI_AI_PLAY:
print("OK")
run = False
#print(room.func)
for room in rooms:
room.draw(screen)
pygame.display.flip()
|
{"/menu.py": ["/button.py"], "/main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/multi_main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/bullet.py": ["/tank.py"], "/wall.py": ["/tank.py"]}
|
6,774
|
adiljumak/MultiPlayer_Tank_Game_RabbitMQ_MongoDB
|
refs/heads/main
|
/main.py
|
import pygame
import random
from enum import Enum
from tank import Tank
from direction import Direction
from bullet import Bullet
from wall import Wall
from buff import Buff
pygame.init()
pygame.mixer.init()
size_w = 800
size_h = 600
screen = pygame.display.set_mode((size_w, size_h))
background = pygame.image.load("background.jpg").convert()
background = pygame.transform.scale(background, (size_w, size_h))
FPS = 60
clock = pygame.time.Clock()
sound_hit = pygame.mixer.Sound('sound_hit.wav')
tank1_sprite = pygame.image.load("tank1_sprite.png").convert()
tank1_sprite = pygame.transform.scale(tank1_sprite, (35, 35))
tank1_sprite.set_colorkey((255, 255, 255))
tank2_sprite = pygame.image.load("tank2_sprite.png").convert()
tank2_sprite = pygame.transform.scale(tank2_sprite, (35, 35))
tank2_sprite.set_colorkey((255, 255, 255))
bullet1_sprite = pygame.image.load("bullet1_sprite.png").convert()
bullet1_sprite = pygame.transform.scale(bullet1_sprite, (15, 5))
bullet1_sprite.set_colorkey((255, 255, 255))
bullet2_sprite = pygame.image.load("bullet2_sprite.png").convert()
bullet2_sprite = pygame.transform.scale(bullet2_sprite, (15, 5))
bullet2_sprite.set_colorkey((255, 255, 255))
run = True
tank_1 = Tank(300, 300, 200, tank1_sprite, bullet1_sprite)
tank_2 = Tank(100, 100, 200, tank2_sprite, bullet2_sprite, pygame.K_d, pygame.K_a, pygame.K_w, pygame.K_s, pygame.K_SPACE)
tanks = [tank_1, tank_2]
bullets = []
def hit_check(bullet, which_bullet):
global tanks
shadow_x1 = []
shadow_x2 = []
shadow_y1 = []
shadow_y2 = []
i = 0
for tank in tanks:
shadow_x1.append(tank.x)
shadow_x2.append(tank.x + tank.width)
shadow_y1.append(tank.y)
shadow_y2.append(tank.y + tank.height)
if shadow_x1[i] <= bullet.x <= shadow_x2[i] and shadow_y1[i] <= bullet.y <= shadow_y2[i]:
sound_hit.play()
tank.lifes -= 1
if tank.lifes <= 0: del tanks[i]
del bullets[which_bullet]
i += 1
#tank1_sprite = pygame.transform.rotate(tank1_sprite, 270)
wallprob = Wall(1000,1000)
walls = []
for i in range(0, size_h, wallprob.size):
for j in range(0, size_w, wallprob.size):
rand = random.randint(1,100)
if rand <= 10:
walls.append(Wall(j, i))
buffs = []
buff_time = 0
buff_time_when = random.randint(1, 10)
while run:
millis = clock.tick(FPS)
seconds = millis / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
for tank in tanks:
if event.key in tank.KEY.keys():
tank.change_direction(tank.KEY[event.key])
if event.key == tank.fire_key:
if tank.recharge != True:
if tank.buff == False:
bullets.append(Bullet(tank,500, screen))
else:
bullets.append(Bullet(tank, 1000, screen))
tank.recharge = True
screen.blit(background, (0, 0))
for tank in tanks:
i = 0
for wall in walls:
x1 = wall.x
y1 = wall.y
x2 = wall.x + wall.size
y2 = wall.y + wall.size
if ( ( (tank.x <= x2 and tank.x >= x1) or (tank.x + tank.width <= x2 and tank.x + tank.width >= x1) ) and (tank.y <= y2 and tank.y >= y1)) or (((tank.x <= x2 and tank.x >= x1) or (tank.x + tank.width <= x2 and tank.x + tank.width >= x1)) and (tank.y + tank.width <= y2 and tank.y + tank.width >= y1)) :
tank.lifes -= 1
del walls[i]
i += 1
i = 0
for buff in buffs:
x1 = buff.x
y1 = buff.y
x2 = buff.x + buff.size
y2 = buff.y + buff.size
if ( ( (tank.x <= x2 and tank.x >= x1) or (tank.x + tank.width <= x2 and tank.x + tank.width >= x1) ) and (tank.y <= y2 and tank.y >= y1)) or (((tank.x <= x2 and tank.x >= x1) or (tank.x + tank.width <= x2 and tank.x + tank.width >= x1)) and (tank.y + tank.width <= y2 and tank.y + tank.width >= y1)):
tank.buff = True
del buffs[i]
tank.move(seconds)
tank.draw(screen, size_w, size_h)
i = 0
for bullet in bullets:
hit_check(bullet, i)
bullet.move(seconds)
bullet.draw()
if bullet.life_time >= bullet.del_time: del bullets[i]
i += 1
k = 0
for wall in walls:
x1 = wall.x
y1 = wall.y
x2 = wall.x + wall.size
y2 = wall.y + wall.size
ktmp = 0
for bullet in bullets:
if (((bullet.x <= x2 and bullet.x >= x1) or (bullet.x + bullet.bullet_h <= x2 and bullet.x + bullet.bullet_h >= x1)) and (
bullet.y <= y2 and bullet.y >= y1)) or (
((bullet.x <= x2 and bullet.x >= x1) or (bullet.x + bullet.bullet_h <= x2 and bullet.x + bullet.bullet_h >= x1)) and (
bullet.y + bullet.bullet_h <= y2 and bullet.y + bullet.bullet_h >= y1)):
del walls[k]
del bullets[ktmp]
ktmp += 1
k += 1
wall.draw(screen)
buff_time += seconds
if buff_time >= buff_time_when:
buff_time = 0
buff_time_when = random.randint(1, 10)
buff_x, buff_y = 0, 0
wrong = False
while not wrong:
buff_x = random.randint(0, size_w / wallprob.size)
buff_y = random.randint(0, size_h / wallprob.size)
for wall in walls:
if wall.x != buff_x * wallprob.size and wall.y != buff_y * wallprob.size:
wrong = True
buffs.append(Buff(buff_x * wallprob.size, buff_y * wallprob.size))
for buff in buffs:
buff.draw(screen)
for tank in tanks:
if tank.buff == True and tank.buff_time <= 5:
tank.speed = 400
tank.buff_time += seconds
else:
tank.buff = False
tank.buff_time = 0
tank.speed = 200
######tests######
screen.blit(tank1_sprite, (0, 0))
#wall.draw(screen)
################
#print(seconds)
pygame.display.flip()
pygame.quit()
|
{"/menu.py": ["/button.py"], "/main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/multi_main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/bullet.py": ["/tank.py"], "/wall.py": ["/tank.py"]}
|
6,775
|
adiljumak/MultiPlayer_Tank_Game_RabbitMQ_MongoDB
|
refs/heads/main
|
/multi_main.py
|
import pygame
import os
import random
from enum import Enum
from tank import Tank
from direction import Direction
from bullet import Bullet
from wall import Wall
from buff import Buff
#from menu import WHICH_ROOM
font = pygame.font.Font('freesansbold.ttf', 32)
font2 = pygame.font.Font('freesansbold.ttf', 15)
pygame.init()
SCREEN_W = 1000
SCREEN_H = 600
screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
background = pygame.image.load("background.jpg").convert()
background = pygame.transform.scale(background, (SCREEN_W - 200, SCREEN_H))
FPS = 60
clock = pygame.time.Clock()
my_tank_sprite = pygame.image.load("tank1_sprite.png")#.convert()
my_tank_sprite = pygame.transform.scale(my_tank_sprite, (35, 35))
my_tank_sprite.set_colorkey((255, 255, 255))
my_tank_sprite_UP = pygame.transform.rotate(my_tank_sprite, 90)
my_tank_sprite_LEFT = pygame.transform.rotate(my_tank_sprite, 180)
my_tank_sprite_DOWN = pygame.transform.rotate(my_tank_sprite, 270)
tank_sprite = pygame.image.load("tank2_sprite.png")#.convert()
tank_sprite = pygame.transform.scale(tank_sprite, (35, 35))
tank_sprite.set_colorkey((255, 255, 255))
tank_sprite_UP = pygame.transform.rotate(tank_sprite, 90)
tank_sprite_LEFT = pygame.transform.rotate(tank_sprite, 180)
tank_sprite_DOWN = pygame.transform.rotate(tank_sprite, 270)
my_bullet_sprite = pygame.image.load("bullet1_sprite.png").convert()
my_bullet_sprite = pygame.transform.scale(my_bullet_sprite, (15, 5))
my_bullet_sprite.set_colorkey((255, 255, 255))
my_bullet_sprite_UP = pygame.transform.rotate(my_bullet_sprite, 90)
my_bullet_sprite_LEFT = pygame.transform.rotate(my_bullet_sprite, 180)
my_bullet_sprite_DOWN = pygame.transform.rotate(my_bullet_sprite, 270)
bullet1_sprite = pygame.image.load("bullet2_sprite.png").convert()
bullet1_sprite = pygame.transform.scale(bullet1_sprite, (15, 5))
bullet1_sprite.set_colorkey((255, 255, 255))
bullet1_sprite_UP = pygame.transform.rotate(bullet1_sprite, 90)
bullet1_sprite_LEFT = pygame.transform.rotate(bullet1_sprite, 180)
bullet1_sprite_DOWN = pygame.transform.rotate(bullet1_sprite, 270)
import json
import uuid
from threading import Thread
import pika
import pygame
IP = '34.254.177.17'
PORT = '5672'
VIRTUAL_HOST = 'dar-tanks'
USERNAME = 'dar-tanks'
PASSWORD = '5orPLExUYnyVYZg48caMpX'
MY_TANK_ID = ''
MY_SCORE = ''
class TankRpcClient:
global MY_TANK_ID
def __init__(self):
self.connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=IP,
port=PORT,
virtual_host=VIRTUAL_HOST,
credentials=pika.PlainCredentials(
username=USERNAME,
password=PASSWORD
)
)
)
self.channel = self.connection.channel()
queue = self.channel.queue_declare(queue='',
auto_delete=True,
exclusive=True
)
self.callback_queue = queue.method.queue
self.channel.queue_bind(
exchange='X:routing.topic',
queue=self.callback_queue
)
self.channel.basic_consume(
queue=self.callback_queue,
on_message_callback=self.on_response,
auto_ack=True
)
self.response = None
self.corr_id = None
self.token = None
self.tank_id = None
self.room_id = None
def on_response(self, ch, method, props, body):
if self.corr_id == props.correlation_id:
self.response = json.loads(body)
print(self.response)
def call(self, key, message={}):
self.response = None
self.corr_id = str(uuid.uuid4())
self.channel.basic_publish(
exchange='X:routing.topic',
routing_key=key,
properties=pika.BasicProperties(
reply_to=self.callback_queue,
correlation_id=self.corr_id,
),
body=json.dumps(message)
)
while self.response is None:
self.connection.process_data_events()
def check_server_status(self):
self.call('tank.request.healthcheck')
return self.response['status'] == '200'
def obtain_token(self, room_id):
global MY_TANK_ID
message = {
'roomId': room_id
}
self.call('tank.request.register', message)
if 'token' in self.response:
self.token = self.response['token']
self.tank_id = self.response['tankId']
MY_TANK_ID = self.tank_id
self.room_id = self.response['roomId']
return True
return False
def turn_tank(self, token, direction):
message = {
'token': token,
'direction': direction
}
self.call('tank.request.turn', message)
def fire_bullet(self, token):
message = {
'token': token
}
self.call('tank.request.fire', message)
class TankConsumerClient(Thread):
def __init__(self, room_id):
super().__init__()
self.connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=IP,
port=PORT,
virtual_host=VIRTUAL_HOST,
credentials=pika.PlainCredentials(
username=USERNAME,
password=PASSWORD
)
)
)
self.channel = self.connection.channel()
queue = self.channel.queue_declare(queue='',
auto_delete=True,
exclusive=True
)
#self.listener = queue.method.queue
event_listener = queue.method.queue
self.channel.queue_bind(exchange='X:routing.topic',
queue=event_listener,
routing_key='event.state.'+room_id)
self.channel.basic_consume(
queue=event_listener,
on_message_callback=self.on_response,
auto_ack=True
)
self.response = None
def on_response(self, ch, method, props, body):
self.response = json.loads(body)
def run(self):
self.channel.start_consuming()
UP = 'UP'
DOWN = 'DOWN'
LEFT = 'LEFT'
RIGHT = 'RIGHT'
MOVE_KEYS = {
pygame.K_w: UP,
pygame.K_a: LEFT,
pygame.K_s: DOWN,
pygame.K_d: RIGHT
}
def draw_tank(x, y, width, height, direction, tank_id, tank_health):
global MY_TANK_ID, font2, screen
if tank_id == MY_TANK_ID:
if direction == 'RIGHT':
screen.blit(my_tank_sprite, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + x + i * 3 * r, y + r - 2), r)
if direction == 'LEFT':
screen.blit(my_tank_sprite_LEFT, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + x + i * 3 * r + 4, y + r - 4), r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'UP':
screen.blit(my_tank_sprite_UP, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + x + i * 3 * r + 3, y + r + width),
r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'DOWN':
screen.blit(my_tank_sprite_DOWN, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + x + i * 3 * r + 1, y + r - 4), r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
else:
if direction == 'RIGHT':
screen.blit(tank_sprite, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + x + i * 3 * r, y + r - 2), r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'LEFT':
screen.blit(tank_sprite_LEFT, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + x + i * 3 * r + 4, y + r - 4), r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'UP':
screen.blit(tank_sprite_UP, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + x + i * 3 * r + 3, y + r + width),
r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'DOWN':
screen.blit(tank_sprite_DOWN, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + x + i * 3 * r + 1, y + r - 4), r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
def draw_bullet(x, y, width, height, direction, bullet_owner):
if bullet_owner == MY_TANK_ID:
if direction == 'RIGHT':
screen.blit(my_bullet_sprite, (x, y))
if direction == 'LEFT':
screen.blit(my_bullet_sprite_LEFT, (x, y))
if direction == 'UP':
screen.blit(my_bullet_sprite_UP, (x, y))
if direction == 'DOWN':
screen.blit(my_bullet_sprite_DOWN, (x, y))
else:
if direction == 'RIGHT':
screen.blit(bullet1_sprite, (x, y))
if direction == 'LEFT':
screen.blit(bullet1_sprite_LEFT, (x, y))
if direction == 'UP':
screen.blit(bullet1_sprite_UP, (x, y))
if direction == 'DOWN':
screen.blit(bullet1_sprite_DOWN, (x, y))
def draw_panel(tanks):
global screen
pygame.draw.rect(screen, (0, 0, 0), ((800, 0), (200, 600)))
k = 0
max = 0
for tank in tanks:
if tank['score'] > max:
max = tank['score']
texttmp = font2.render('ID LIFE SCORE', True, (255, 255, 255))
texttmpRect = texttmp.get_rect()
texttmpRect.center = (900 + 15, 10)
screen.blit(texttmp, texttmpRect)
y = 30
while(max >= 0):
for tank in tanks:
if tank['score'] == max:
if tank['id'] != MY_TANK_ID:
text = font2.render('{}'.format(tank['id']), True, (255, 0, 0))
else:
text = font2.render('i', True, (0, 255, 0))
textRect = text.get_rect()
textRect.center = (825 + 15, y)
screen.blit(text, textRect)
if tank['id'] != MY_TANK_ID:
text = font2.render('{}'.format(tank['health']), True, (255, 0, 0))
else:
text = font2.render('{}'.format(tank['health']), True, (0, 255, 0))
textRect = text.get_rect()
textRect.center = (825 + 90, y)
screen.blit(text, textRect)
if tank['id'] != MY_TANK_ID:
text = font2.render('{}'.format(tank['score']), True, (255, 0, 0))
else:
text = font2.render('{}'.format(tank['score']), True, (0, 255, 0))
textRect = text.get_rect()
textRect.center = (825 + 160, y)
screen.blit(text, textRect)
y += 30
# print(tank['id'])
# print(tank['health'])
# print(tank['score'])
max -= 1
def loserr():
global screen, MY_SCORE
pygame.draw.rect(screen, (0, 0, 0), ((0, 0), (1000, 600)))
text = font.render('Неудача!', True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 40)
screen.blit(text, textRect)
text = font.render('Ваш итоговый счет: {}'.format(MY_SCORE), True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 150)
screen.blit(text, textRect)
def winerr():
global screen, MY_SCORE
pygame.draw.rect(screen, (0, 0, 0), ((0, 0), (1000, 600)))
text = font.render('Победа!', True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 40)
screen.blit(text, textRect)
text = font.render('Ваш итоговый счет: {}'.format(MY_SCORE), True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 150)
screen.blit(text, textRect)
def game_start():
global MY_SCORE
run = True
global font
global screen
los = False
won = False
while run:
millis = clock.tick(FPS)
seconds = millis / 1000
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
if event.key in MOVE_KEYS:
client.turn_tank(client.token, MOVE_KEYS[event.key])
if event.key == pygame.K_SPACE:
client.fire_bullet(client.token)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
los = False
won = False
try:
remaining_time = event_client.response['remainingTime']
text = font.render('Remaining Time: {}'.format(remaining_time), True, (0, 0, 0))
textRect = text.get_rect()
screen.blit(text, textRect)
if remaining_time == 0:
run = False
hits = event_client.response['hits']
winners = event_client.response['winners']
losers = event_client.response['losers']
tanks = event_client.response['gameField']['tanks']
bullets = event_client.response['gameField']['bullets']
draw_panel(tanks)
for loser in losers:
if loser['tankId'] == MY_TANK_ID:
#print("")
los = True
for win in winners:
if win['tankId'] == MY_TANK_ID:
won = True
# run2 = True
# while run2:
# screen.fill((255, 255, 255))
#
# # for event in pygame.event.get():
# # if event.type == pygame.KEYDOWN:
# # if event.key == pygame.K_ESCAPE:
# # run2 = False
#
# text = font.render('self.text', True, (0, 0, 0))
# textRect = text.get_rect()
# textRect.center = (500, 500)
# screen.blit(text, textRect)
#
# screen.flip()
for tank in tanks:
tank_x = tank['x']
tank_y = tank['y']
tank_width = tank['width']
tank_height = tank['height']
tank_direction = tank['direction']
tank_id = tank['id']
tank_health = tank['health']
if tank['id'] == MY_TANK_ID:
MY_SCORE = tank['score']
#txt_losers = ','.join(i['tankId'] for i in losers)
#print(txt_losers)
# if tank['id'] == MY_TANK_ID: #and tank['health'] == 0:
# for lose in losers:
#
# print(','.join(lose['tankId']))
# print(tank['health'])
#for lose in losers:
#print(lose['tankid'])
# lose(tank['score'])
#print(losers)
# txt_losers = ','.join(i['tankId'] for i in losers)
# print(txt_losers)
draw_tank(tank_x, tank_y, tank_width, tank_height, tank_direction, tank_id, tank_health)
for bullet in bullets:
bullet_x = bullet['x']
bullet_y = bullet['y']
bullet_owner = bullet['owner']
bullet_width = bullet['width']
bullet_height = bullet['height']
bullet_direction = bullet['direction']
draw_bullet(bullet_x, bullet_y, bullet_width, bullet_height, bullet_direction, bullet_owner) # if bullet_owner == my_tank_id
except:
pass
if los:
loserr()
if won:
winerr()
pygame.display.flip()
client.connection.close()
#pygame.quit()
client = TankRpcClient()
client.check_server_status()
client.obtain_token('room-1')
event_client = TankConsumerClient('room-1')
event_client.start()
game_start()
runtmp = True
while runtmp:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
runtmp = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
runtmp = False
pygame.draw.rect(screen, (0, 0, 0), ((0, 0), (1000, 600)))
text = font.render('Игра закончена!', True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 40)
screen.blit(text, textRect)
text = font.render('Ваш итоговый счет: {}'.format(MY_SCORE), True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 150)
screen.blit(text, textRect)
text = font.render('Нажмите R чтобы сыграть заново!', True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 350)
screen.blit(text, textRect)
pygame.display.flip()
os.startfile('menu.py')
pygame.quit()
# client.turn_tank(client.token, 'UP')
|
{"/menu.py": ["/button.py"], "/main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/multi_main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/bullet.py": ["/tank.py"], "/wall.py": ["/tank.py"]}
|
6,776
|
adiljumak/MultiPlayer_Tank_Game_RabbitMQ_MongoDB
|
refs/heads/main
|
/button.py
|
import pygame
pygame.init()
class Button:
def __init__(self, x, y, text, func):
self.x = x
self.y = y
self.text = text
self.func = func
def draw(self, screen):
font = pygame.font.Font('freesansbold.ttf', 28)
text = font.render(self.text, True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (self.x, self.y)
screen.blit(text, textRect)
|
{"/menu.py": ["/button.py"], "/main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/multi_main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/bullet.py": ["/tank.py"], "/wall.py": ["/tank.py"]}
|
6,777
|
adiljumak/MultiPlayer_Tank_Game_RabbitMQ_MongoDB
|
refs/heads/main
|
/all_in_one.py
|
import pygame
import os
import random
from enum import Enum
import json
import uuid
from threading import Thread
import pika
pygame.init()
pygame.mixer.init()
SCREEN_W = 800
SCREEN_H = 600
my_bullet_sprite = pygame.image.load("bullet1_sprite.png")#.convert()
my_bullet_sprite = pygame.transform.scale(my_bullet_sprite, (15, 5))
my_bullet_sprite.set_colorkey((255, 255, 255))
my_bullet_sprite_UP = pygame.transform.rotate(my_bullet_sprite, 90)
my_bullet_sprite_LEFT = pygame.transform.rotate(my_bullet_sprite, 180)
my_bullet_sprite_DOWN = pygame.transform.rotate(my_bullet_sprite, 270)
bullet1_sprite = pygame.image.load("bullet2_sprite.png")#.convert()
bullet1_sprite = pygame.transform.scale(bullet1_sprite, (15, 5))
bullet1_sprite.set_colorkey((255, 255, 255))
bullet1_sprite_UP = pygame.transform.rotate(bullet1_sprite, 90)
bullet1_sprite_LEFT = pygame.transform.rotate(bullet1_sprite, 180)
bullet1_sprite_DOWN = pygame.transform.rotate(bullet1_sprite, 270)
my_tank_sprite = pygame.image.load("tank1_sprite.png")#.convert()
my_tank_sprite = pygame.transform.scale(my_tank_sprite, (35, 35))
my_tank_sprite.set_colorkey((255, 255, 255))
my_tank_sprite_UP = pygame.transform.rotate(my_tank_sprite, 90)
my_tank_sprite_LEFT = pygame.transform.rotate(my_tank_sprite, 180)
my_tank_sprite_DOWN = pygame.transform.rotate(my_tank_sprite, 270)
tank_sprite = pygame.image.load("tank2_sprite.png")#.convert()
tank_sprite = pygame.transform.scale(tank_sprite, (35, 35))
tank_sprite.set_colorkey((255, 255, 255))
tank_sprite_UP = pygame.transform.rotate(tank_sprite, 90)
tank_sprite_LEFT = pygame.transform.rotate(tank_sprite, 180)
tank_sprite_DOWN = pygame.transform.rotate(tank_sprite, 270)
class TankRpcClient:
global MY_TANK_ID
def __init__(self):
self.connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=IP,
port=PORT,
virtual_host=VIRTUAL_HOST,
credentials=pika.PlainCredentials(
username=USERNAME,
password=PASSWORD
)
)
)
self.channel = self.connection.channel()
queue = self.channel.queue_declare(queue='',
auto_delete=True,
exclusive=True
)
self.callback_queue = queue.method.queue
self.channel.queue_bind(
exchange='X:routing.topic',
queue=self.callback_queue
)
self.channel.basic_consume(
queue=self.callback_queue,
on_message_callback=self.on_response,
auto_ack=True
)
self.response = None
self.corr_id = None
self.token = None
self.tank_id = None
self.room_id = None
def on_response(self, ch, method, props, body):
if self.corr_id == props.correlation_id:
self.response = json.loads(body)
print(self.response)
def call(self, key, message={}):
self.response = None
self.corr_id = str(uuid.uuid4())
self.channel.basic_publish(
exchange='X:routing.topic',
routing_key=key,
properties=pika.BasicProperties(
reply_to=self.callback_queue,
correlation_id=self.corr_id,
),
body=json.dumps(message)
)
while self.response is None:
self.connection.process_data_events()
def check_server_status(self):
self.call('tank.request.healthcheck')
return self.response['status'] == '200'
def obtain_token(self, room_id):
global MY_TANK_ID
message = {
'roomId': room_id
}
self.call('tank.request.register', message)
if 'token' in self.response:
self.token = self.response['token']
self.tank_id = self.response['tankId']
MY_TANK_ID = self.tank_id
self.room_id = self.response['roomId']
return True
return False
def turn_tank(self, token, direction):
message = {
'token': token,
'direction': direction
}
self.call('tank.request.turn', message)
def fire_bullet(self, token):
message = {
'token': token
}
self.call('tank.request.fire', message)
class TankConsumerClient(Thread):
def __init__(self, room_id):
super().__init__()
self.connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=IP,
port=PORT,
virtual_host=VIRTUAL_HOST,
credentials=pika.PlainCredentials(
username=USERNAME,
password=PASSWORD
)
)
)
self.channel = self.connection.channel()
queue = self.channel.queue_declare(queue='',
auto_delete=True,
exclusive=True
)
#self.listener = queue.method.queue
event_listener = queue.method.queue
self.channel.queue_bind(exchange='X:routing.topic',
queue=event_listener,
routing_key='event.state.'+room_id)
self.channel.basic_consume(
queue=event_listener,
on_message_callback=self.on_response,
auto_ack=True
)
self.response = None
def on_response(self, ch, method, props, body):
self.response = json.loads(body)
def run(self):
self.channel.start_consuming()
UP = 'UP'
DOWN = 'DOWN'
LEFT = 'LEFT'
RIGHT = 'RIGHT'
MOVE_KEYS = {
pygame.K_w: UP,
pygame.K_a: LEFT,
pygame.K_s: DOWN,
pygame.K_d: RIGHT
}
font = pygame.font.Font('freesansbold.ttf', 32)
font2 = pygame.font.Font('freesansbold.ttf', 15)
background = pygame.image.load("background.jpg")#.convert()
background = pygame.transform.scale(background, (SCREEN_W - 200, SCREEN_H))
FPS = 60
clock = pygame.time.Clock()
IP = '34.254.177.17'
PORT = '5672'
VIRTUAL_HOST = 'dar-tanks'
USERNAME = 'dar-tanks'
PASSWORD = '5orPLExUYnyVYZg48caMpX'
MY_TANK_ID = ''
MY_SCORE = ''
wall_sprite = pygame.image.load("wall_sprite.png")#.convert()
wall_sprite.set_colorkey((255, 255, 255))
sound_shoot = pygame.mixer.Sound('sound_shoot.wav')
buff_sprite = pygame.image.load("buff_sprite.png")#.convert()
buff_sprite.set_colorkey((255, 255, 255))
class Buff:
def __init__(self, x, y):
self.size = 40 # in px
self.x = x
self.y = y
self.sprite = buff_sprite
self.sprite = pygame.transform.scale(self.sprite, (self.size, self.size))
def draw(self, screen):
screen.blit(self.sprite, (self.x, self.y))
class Bullet:
def __init__(self, tank, speed, screen):
sound_shoot.play()
self.screen = screen
self.size = 2
self.tank = tank
self.sprite = tank.bullet_sprite
self.direction = tank.direction
self.speed = speed
self.life_time = 0
self.del_time = 1.5 # in sec
self.bullet_w = 15
self.bullet_h = 5
self.sprite_RIGHT = self.sprite
self.sprite_UP = pygame.transform.rotate(self.sprite, 90)
self.sprite_LEFT = pygame.transform.rotate(self.sprite, 180)
self.sprite_DOWN = pygame.transform.rotate(self.sprite, 270)
if tank.direction == Direction.RIGHT:
self.sprite = tank.bullet_sprite
self.x = tank.x + tank.height + int(tank.height / 2)
self.y = int(tank.y + tank.width / 2)
if self.direction == Direction.LEFT:
self.sprite = pygame.transform.rotate(self.sprite, 180)
self.x = tank.x - tank.height + int(tank.height / 2)
self.y = tank.y + int(tank.width / 2)
if self.direction == Direction.UP:
self.sprite = pygame.transform.rotate(self.sprite, 90)
self.x = tank.x + int(tank.height / 2)
self.y = tank.y - int(tank.width / 2)
if self.direction == Direction.DOWN:
self.sprite = pygame.transform.rotate(self.sprite, 270)
self.x = tank.x + int(tank.height / 2)
self.y = tank.y + tank.width + int(tank.width / 2)
def draw(self):
#pygame.draw.circle(self.screen, self.color, (self.x, self.y), self.size)
self.screen.blit(self.sprite, (self.x , self.y))
def move(self, seconds):
self.life_time += seconds
if self.direction == Direction.RIGHT:
self.x += int(self.speed * seconds)
if self.direction == Direction.LEFT:
self.x -= int(self.speed * seconds)
if self.direction == Direction.UP:
self.y -= int(self.speed * seconds)
if self.direction == Direction.DOWN:
self.y += int(self.speed * seconds)
class Wall:
def __init__(self, x, y):
self.size = 40 # in px
self.x = x
self.y = y
self.sprite = wall_sprite
self.sprite = pygame.transform.scale(self.sprite, (self.size, self.size))
def draw(self, screen):
screen.blit(self.sprite, (self.x, self.y))
class Tank:
def __init__(self, x, y, speed, sprite, bullet_sprite, d_right=pygame.K_RIGHT, d_left=pygame.K_LEFT, d_up=pygame.K_UP,
d_down=pygame.K_DOWN, fire_key=pygame.K_RETURN):
self.buff = False
self.buff_time = 0
self.num_of_bullet = 3
self.fire_key = fire_key
self.recharge = False
self.recharge_duration = 2 # in sec
self.recharge_time = 0 # in sec
self.lifes = 3
self.x = x
self.y = y
self.speed = speed
#self.color = color
self.bullet_sprite = bullet_sprite
self.sprite = sprite
self.sprite_RIGHT = self.sprite
self.sprite_UP = pygame.transform.rotate(self.sprite, 90)
self.sprite_LEFT = pygame.transform.rotate(self.sprite, 180)
self.sprite_DOWN = pygame.transform.rotate(self.sprite, 270)
self.width = 35
self.height = 35
self.direction = Direction.RIGHT
self.KEY = {
d_right: Direction.RIGHT,
d_left: Direction.LEFT,
d_up: Direction.UP,
d_down: Direction.DOWN
}
def draw(self, screen, size_w, size_h):
tank_c = (self.x + int(self.width / 2), self.y + int(self.height / 2))
if self.x <= 0:
self.x = size_w - self.width
if self.y <= 0:
self.y = size_h - self.height
if self.x + self.width > size_w:
self.x = 0
if self.y >= size_h:
self.y = 0
#screen.blit(self.sprite, (self.x, self.y))
# pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height), 2)
# pygame.draw.circle(screen, self.color, tank_c, int(self.width / 2))
if self.direction == Direction.RIGHT:
screen.blit(self.sprite_RIGHT, (self.x, self.y))
for i in range(0, self.lifes):
r = int(((self.width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + self.x + i * 3 * r, self.y + r - 2), r)
# pygame.draw.line(screen, self.color, tank_c,
# (self.x + self.height + int(self.height / 2), int(self.y + self.width / 2)), 4)
if self.direction == Direction.LEFT:
screen.blit(self.sprite_LEFT, (self.x, self.y))
for i in range(0, self.lifes):
r = int(((self.width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + self.x + i * 3 * r + 4, self.y + r - 4), r)
# pygame.draw.line(screen, self.color, tank_c,
# (self.x - self.height + int(self.height / 2), self.y + int(self.width / 2)), 4)
if self.direction == Direction.UP:
screen.blit(self.sprite_UP, (self.x, self.y))
for i in range(0, self.lifes):
r = int(((self.width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + self.x + i * 3 * r + 3, self.y + r + self.width - 2), r)
# pygame.draw.line(screen, self.color, tank_c, (self.x + int(self.height / 2), self.y - int(self.width / 2)),
# 4)
if self.direction == Direction.DOWN:
screen.blit(self.sprite_DOWN, (self.x, self.y))
for i in range(0, self.lifes):
r = int(((self.width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + self.x + i * 3 * r + 1, self.y + r - 4), r)
# pygame.draw.line(screen, self.color, tank_c,
# (self.x + int(self.height / 2), self.y + self.width + int(self.width / 2)), 4)
def change_direction(self, direction):
self.direction = direction
def move(self, seconds):
if self.direction == Direction.LEFT:
self.x -= int(self.speed * seconds)
if self.direction == Direction.RIGHT:
self.x += int(self.speed * seconds)
if self.direction == Direction.UP:
self.y -= int(self.speed * seconds)
if self.direction == Direction.DOWN:
self.y += int(self.speed * seconds)
self.recharge_time += seconds
if self.recharge_time >= self.recharge_duration:
self.recharge = False
self.recharge_time = 0
class Direction(Enum):
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
class Button:
def __init__(self, x, y, text, func):
self.x = x
self.y = y
self.text = text
self.func = func
def draw(self, screen):
font = pygame.font.Font('freesansbold.ttf', 28)
text = font.render(self.text, True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (self.x, self.y)
screen.blit(text, textRect)
WHICH_ROOM = 1
screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
menu_background = pygame.image.load("menu_background.png").convert()
menu_background = pygame.transform.scale(menu_background, (SCREEN_W, SCREEN_H))
MAIN_MENU = True
SINGLE_PLAY = False
MULTI_PLAY = False
MULTI_AI_PLAY = False
def click_button_single():
global MAIN_MENU, SINGLE_PLAY, MULTI_PLAY, MULTI_AI_PLAY
#os.startfile('main.py')
SINGLE_PLAY = True
MAIN_MENU = False
def click_button_multi():
global MAIN_MENU, SINGLE_PLAY, MULTI_PLAY, MULTI_AI_PLAY
#os.startfile('multi_main.py')
MULTI_PLAY = True
MAIN_MENU = False
def click_button_multi_AI():
global MAIN_MENU, SINGLE_PLAY, MULTI_PLAY, MULTI_AI_PLAY
#print('ok good MULTI AI')
MULTI_AI_PLAY = True
MAIN_MENU = False
button_single = Button(410, 350, "Одиночная игра", click_button_single)
button_multi = Button(130, 350,"Мультиплеер", click_button_multi)
button_multi_AI = Button(670, 350,"Мультиплеер ИИ", click_button_multi_AI)
buttons = [button_single, button_multi, button_multi_AI]
rooms = []
room_num = 1
for i in range(1, 7):
for j in range(1,6):
text = 'room: {}'.format(room_num)
rooms.append(Button(j * 160 - 80, i * 100 - 50, text, room_num))
room_num += 1
run = True
while run:
if MAIN_MENU:
pos = pygame.mouse.get_pos()
screen.blit(menu_background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
for button in buttons:
if button.x - 100 <= pos[0] <= button.x + 100 and button.y - 20 <= pos[1] <= button.y + 20:
button.func()
for button in buttons:
button.draw(screen)
pygame.display.flip()
elif SINGLE_PLAY:
background = pygame.image.load("background.jpg").convert()
background = pygame.transform.scale(background, (SCREEN_W, SCREEN_H))
FPS = 60
clock = pygame.time.Clock()
sound_hit = pygame.mixer.Sound('sound_hit.wav')
tank1_sprite = pygame.image.load("tank1_sprite.png").convert()
tank1_sprite = pygame.transform.scale(tank1_sprite, (35, 35))
tank1_sprite.set_colorkey((255, 255, 255))
tank2_sprite = pygame.image.load("tank2_sprite.png").convert()
tank2_sprite = pygame.transform.scale(tank2_sprite, (35, 35))
tank2_sprite.set_colorkey((255, 255, 255))
bullet1_sprite = pygame.image.load("bullet1_sprite.png").convert()
bullet1_sprite = pygame.transform.scale(bullet1_sprite, (15, 5))
bullet1_sprite.set_colorkey((255, 255, 255))
bullet2_sprite = pygame.image.load("bullet2_sprite.png").convert()
bullet2_sprite = pygame.transform.scale(bullet2_sprite, (15, 5))
bullet2_sprite.set_colorkey((255, 255, 255))
running = True
tank_1 = Tank(300, 300, 200, tank1_sprite, bullet1_sprite)
tank_2 = Tank(100, 100, 200, tank2_sprite, bullet2_sprite, pygame.K_d, pygame.K_a, pygame.K_w, pygame.K_s,
pygame.K_SPACE)
tanks = [tank_1, tank_2]
bullets = []
def hit_check(bullet, which_bullet):
global tanks
shadow_x1 = []
shadow_x2 = []
shadow_y1 = []
shadow_y2 = []
i = 0
for tank in tanks:
shadow_x1.append(tank.x)
shadow_x2.append(tank.x + tank.width)
shadow_y1.append(tank.y)
shadow_y2.append(tank.y + tank.height)
if shadow_x1[i] <= bullet.x <= shadow_x2[i] and shadow_y1[i] <= bullet.y <= shadow_y2[i]:
sound_hit.play()
tank.lifes -= 1
if tank.lifes <= 0: del tanks[i]
del bullets[which_bullet]
i += 1
wallprob = Wall(1000, 1000)
walls = []
for i in range(0, SCREEN_H, wallprob.size):
for j in range(0, SCREEN_W, wallprob.size):
rand = random.randint(1, 100)
if rand <= 10:
walls.append(Wall(j, i))
buffs = []
buff_time = 0
buff_time_when = random.randint(1, 10)
while running:
millis = clock.tick(FPS)
seconds = millis / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
for tank in tanks:
if event.key in tank.KEY.keys():
tank.change_direction(tank.KEY[event.key])
if event.key == tank.fire_key:
if tank.recharge != True:
if tank.buff == False:
bullets.append(Bullet(tank, 500, screen))
else:
bullets.append(Bullet(tank, 1000, screen))
tank.recharge = True
screen.blit(background, (0, 0))
for tank in tanks:
i = 0
for wall in walls:
x1 = wall.x
y1 = wall.y
x2 = wall.x + wall.size
y2 = wall.y + wall.size
if (((tank.x <= x2 and tank.x >= x1) or (
tank.x + tank.width <= x2 and tank.x + tank.width >= x1)) and (
tank.y <= y2 and tank.y >= y1)) or (((tank.x <= x2 and tank.x >= x1) or (
tank.x + tank.width <= x2 and tank.x + tank.width >= x1)) and (
tank.y + tank.width <= y2 and tank.y + tank.width >= y1)):
tank.lifes -= 1
del walls[i]
i += 1
i = 0
for buff in buffs:
x1 = buff.x
y1 = buff.y
x2 = buff.x + buff.size
y2 = buff.y + buff.size
if (((tank.x <= x2 and tank.x >= x1) or (
tank.x + tank.width <= x2 and tank.x + tank.width >= x1)) and (
tank.y <= y2 and tank.y >= y1)) or (((tank.x <= x2 and tank.x >= x1) or (
tank.x + tank.width <= x2 and tank.x + tank.width >= x1)) and (
tank.y + tank.width <= y2 and tank.y + tank.width >= y1)):
tank.buff = True
del buffs[i]
tank.move(seconds)
tank.draw(screen, SCREEN_W, SCREEN_H)
i = 0
for bullet in bullets:
hit_check(bullet, i)
bullet.move(seconds)
bullet.draw()
if bullet.life_time >= bullet.del_time: del bullets[i]
i += 1
k = 0
for wall in walls:
x1 = wall.x
y1 = wall.y
x2 = wall.x + wall.size
y2 = wall.y + wall.size
ktmp = 0
for bullet in bullets:
if (((bullet.x <= x2 and bullet.x >= x1) or (
bullet.x + bullet.bullet_h <= x2 and bullet.x + bullet.bullet_h >= x1)) and (
bullet.y <= y2 and bullet.y >= y1)) or (
((bullet.x <= x2 and bullet.x >= x1) or (
bullet.x + bullet.bullet_h <= x2 and bullet.x + bullet.bullet_h >= x1)) and (
bullet.y + bullet.bullet_h <= y2 and bullet.y + bullet.bullet_h >= y1)):
del walls[k]
del bullets[ktmp]
ktmp += 1
k += 1
wall.draw(screen)
buff_time += seconds
if buff_time >= buff_time_when:
buff_time = 0
buff_time_when = random.randint(1, 10)
buff_x, buff_y = 0, 0
wrong = False
while not wrong:
buff_x = random.randint(0, SCREEN_W / wallprob.size)
buff_y = random.randint(0, SCREEN_H / wallprob.size)
for wall in walls:
if wall.x != buff_x * wallprob.size and wall.y != buff_y * wallprob.size:
wrong = True
buffs.append(Buff(buff_x * wallprob.size, buff_y * wallprob.size))
for buff in buffs:
buff.draw(screen)
for tank in tanks:
if tank.buff == True and tank.buff_time <= 5:
tank.speed = 400
tank.buff_time += seconds
else:
tank.buff = False
tank.buff_time = 0
tank.speed = 200
######tests######
screen.blit(tank1_sprite, (0, 0))
# wall.draw(screen)
################
# print(seconds)
pygame.display.flip()
#os.startfile('main.py')
SINGLE_PLAY = False
MAIN_MENU = True
#run = False
else:
pos = pygame.mouse.get_pos()
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
MAIN_MENU = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
MAIN_MENU = True
if event.type == pygame.MOUSEBUTTONDOWN:
for room in rooms:
if room.x - 50 <= pos[0] <= room.x + 50 and room.y - 20 <= pos[1] <= room.y + 20:
WHICH_ROOM = room.func
#run = False
if MULTI_PLAY:
SCREEN_W = 1000
background = pygame.transform.scale(background, (SCREEN_W, SCREEN_H))
screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
def draw_tank(x, y, width, height, direction, tank_id, tank_health):
global MY_TANK_ID, font2, screen, my_tank_sprite, my_tank_sprite_DOWN, my_tank_sprite_LEFT, my_tank_sprite_UP
if tank_id == MY_TANK_ID:
if direction == 'RIGHT':
screen.blit(my_tank_sprite, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + x + i * 3 * r, y + r - 2),
r)
if direction == 'LEFT':
screen.blit(my_tank_sprite_LEFT, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0),
(2 * r + x + i * 3 * r + 4, y + r - 4), r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'UP':
screen.blit(my_tank_sprite_UP, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0),
(2 * r + x + i * 3 * r + 3, y + r + width),
r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'DOWN':
screen.blit(my_tank_sprite_DOWN, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0),
(2 * r + x + i * 3 * r + 1, y + r - 4), r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
else:
if direction == 'RIGHT':
screen.blit(tank_sprite, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + x + i * 3 * r, y + r - 2),
r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'LEFT':
screen.blit(tank_sprite_LEFT, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0),
(2 * r + x + i * 3 * r + 4, y + r - 4), r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'UP':
screen.blit(tank_sprite_UP, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0),
(2 * r + x + i * 3 * r + 3, y + r + width),
r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'DOWN':
screen.blit(tank_sprite_DOWN, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0),
(2 * r + x + i * 3 * r + 1, y + r - 4), r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
def draw_bullet(x, y, width, height, direction, bullet_owner):
if bullet_owner == MY_TANK_ID:
if direction == 'RIGHT':
screen.blit(my_bullet_sprite, (x, y))
if direction == 'LEFT':
screen.blit(my_bullet_sprite_LEFT, (x, y))
if direction == 'UP':
screen.blit(my_bullet_sprite_UP, (x, y))
if direction == 'DOWN':
screen.blit(my_bullet_sprite_DOWN, (x, y))
else:
if direction == 'RIGHT':
screen.blit(bullet1_sprite, (x, y))
if direction == 'LEFT':
screen.blit(bullet1_sprite_LEFT, (x, y))
if direction == 'UP':
screen.blit(bullet1_sprite_UP, (x, y))
if direction == 'DOWN':
screen.blit(bullet1_sprite_DOWN, (x, y))
def draw_panel(tanks):
global screen
pygame.draw.rect(screen, (0, 0, 0), ((800, 0), (200, 600)))
k = 0
max = 0
for tank in tanks:
if tank['score'] > max:
max = tank['score']
texttmp = font2.render('ID LIFE SCORE', True, (255, 255, 255))
texttmpRect = texttmp.get_rect()
texttmpRect.center = (900 + 15, 10)
screen.blit(texttmp, texttmpRect)
y = 30
while (max >= 0):
for tank in tanks:
if tank['score'] == max:
if tank['id'] != MY_TANK_ID:
text = font2.render('{}'.format(tank['id']), True, (255, 0, 0))
else:
text = font2.render('i', True, (0, 255, 0))
textRect = text.get_rect()
textRect.center = (825 + 15, y)
screen.blit(text, textRect)
if tank['id'] != MY_TANK_ID:
text = font2.render('{}'.format(tank['health']), True, (255, 0, 0))
else:
text = font2.render('{}'.format(tank['health']), True, (0, 255, 0))
textRect = text.get_rect()
textRect.center = (825 + 90, y)
screen.blit(text, textRect)
if tank['id'] != MY_TANK_ID:
text = font2.render('{}'.format(tank['score']), True, (255, 0, 0))
else:
text = font2.render('{}'.format(tank['score']), True, (0, 255, 0))
textRect = text.get_rect()
textRect.center = (825 + 160, y)
screen.blit(text, textRect)
y += 30
# print(tank['id'])
# print(tank['health'])
# print(tank['score'])
max -= 1
def loserr():
global screen, MY_SCORE
pygame.draw.rect(screen, (0, 0, 0), ((0, 0), (1000, 600)))
text = font.render('Неудача!', True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 40)
screen.blit(text, textRect)
text = font.render('Ваш итоговый счет: {}'.format(MY_SCORE), True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 150)
screen.blit(text, textRect)
def winerr():
global screen, MY_SCORE
pygame.draw.rect(screen, (0, 0, 0), ((0, 0), (1000, 600)))
text = font.render('Победа!', True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 40)
screen.blit(text, textRect)
text = font.render('Ваш итоговый счет: {}'.format(MY_SCORE), True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 150)
screen.blit(text, textRect)
def game_start():
global MY_SCORE
run = True
global font
global screen
los = False
won = False
global MOVE_KEYS
while run:
millis = clock.tick(FPS)
seconds = millis / 1000
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
if event.key in MOVE_KEYS:
client.turn_tank(client.token, MOVE_KEYS[event.key])
if event.key == pygame.K_SPACE:
client.fire_bullet(client.token)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
los = False
won = False
try:
remaining_time = event_client.response['remainingTime']
text = font.render('Remaining Time: {}'.format(remaining_time), True, (0, 0, 0))
textRect = text.get_rect()
screen.blit(text, textRect)
if remaining_time == 0:
run = False
hits = event_client.response['hits']
winners = event_client.response['winners']
losers = event_client.response['losers']
tanks = event_client.response['gameField']['tanks']
bullets = event_client.response['gameField']['bullets']
draw_panel(tanks)
for loser in losers:
if loser['tankId'] == MY_TANK_ID:
# print("")
los = True
for win in winners:
if win['tankId'] == MY_TANK_ID:
won = True
# run2 = True
# while run2:
# screen.fill((255, 255, 255))
#
# # for event in pygame.event.get():
# # if event.type == pygame.KEYDOWN:
# # if event.key == pygame.K_ESCAPE:
# # run2 = False
#
# text = font.render('self.text', True, (0, 0, 0))
# textRect = text.get_rect()
# textRect.center = (500, 500)
# screen.blit(text, textRect)
#
# screen.flip()
for tank in tanks:
tank_x = tank['x']
tank_y = tank['y']
tank_width = tank['width']
tank_height = tank['height']
tank_direction = tank['direction']
tank_id = tank['id']
tank_health = tank['health']
if tank['id'] == MY_TANK_ID:
MY_SCORE = tank['score']
# txt_losers = ','.join(i['tankId'] for i in losers)
# print(txt_losers)
# if tank['id'] == MY_TANK_ID: #and tank['health'] == 0:
# for lose in losers:
#
# print(','.join(lose['tankId']))
# print(tank['health'])
# for lose in losers:
# print(lose['tankid'])
# lose(tank['score'])
# print(losers)
# txt_losers = ','.join(i['tankId'] for i in losers)
# print(txt_losers)
draw_tank(tank_x, tank_y, tank_width, tank_height, tank_direction, tank_id,
tank_health)
for bullet in bullets:
bullet_x = bullet['x']
bullet_y = bullet['y']
bullet_owner = bullet['owner']
bullet_width = bullet['width']
bullet_height = bullet['height']
bullet_direction = bullet['direction']
draw_bullet(bullet_x, bullet_y, bullet_width, bullet_height,
bullet_direction, bullet_owner) # if bullet_owner == my_tank_id
except:
pass
if los:
loserr()
if won:
winerr()
pygame.display.flip()
client.connection.close()
# pygame.quit()
client = TankRpcClient()
client.check_server_status()
which_room = 'room-' + str(WHICH_ROOM)
client.obtain_token(which_room)
event_client = TankConsumerClient(which_room)
event_client.start()
game_start()
runtmp = True
while runtmp:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
runtmp = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
runtmp = False
pygame.draw.rect(screen, (0, 0, 0), ((0, 0), (1000, 600)))
text = font.render('Игра закончена!', True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 40)
screen.blit(text, textRect)
text = font.render('Ваш итоговый счет: {}'.format(MY_SCORE), True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 150)
screen.blit(text, textRect)
text = font.render('Нажмите R чтобы сыграть заново!', True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 350)
screen.blit(text, textRect)
pygame.display.flip()
#os.startfile('multi_main.py')
#MULTI_PLAY = False
#run = False
if MULTI_AI_PLAY:
SCREEN_W = 1000
background = pygame.transform.scale(background, (SCREEN_W, SCREEN_H))
screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
def draw_tank(x, y, width, height, direction, tank_id, tank_health):
global MY_TANK_ID, font2, screen, my_tank_sprite, my_tank_sprite_DOWN, my_tank_sprite_LEFT, my_tank_sprite_UP
if tank_id == MY_TANK_ID:
if direction == 'RIGHT':
screen.blit(my_tank_sprite, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + x + i * 3 * r, y + r - 2),
r)
if direction == 'LEFT':
screen.blit(my_tank_sprite_LEFT, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0),
(2 * r + x + i * 3 * r + 4, y + r - 4), r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'UP':
screen.blit(my_tank_sprite_UP, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0),
(2 * r + x + i * 3 * r + 3, y + r + width),
r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'DOWN':
screen.blit(my_tank_sprite_DOWN, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0),
(2 * r + x + i * 3 * r + 1, y + r - 4), r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
else:
if direction == 'RIGHT':
screen.blit(tank_sprite, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + x + i * 3 * r, y + r - 2),
r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'LEFT':
screen.blit(tank_sprite_LEFT, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0),
(2 * r + x + i * 3 * r + 4, y + r - 4), r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'UP':
screen.blit(tank_sprite_UP, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0),
(2 * r + x + i * 3 * r + 3, y + r + width),
r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
if direction == 'DOWN':
screen.blit(tank_sprite_DOWN, (x, y))
tank_id_text = font2.render('{}'.format(tank_id), True, (255, 255, 255))
tank_id_textRect = tank_id_text.get_rect()
tank_id_textRect.center = (x + 15, y + width + 10)
screen.blit(tank_id_text, tank_id_textRect)
for i in range(0, tank_health):
r = int(((width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0),
(2 * r + x + i * 3 * r + 1, y + r - 4), r)
# tank_id_textRect.center = (x, y)
# screen.blit(tank_id_text, tank_id_textRect)
def draw_bullet(x, y, width, height, direction, bullet_owner):
if bullet_owner == MY_TANK_ID:
if direction == 'RIGHT':
screen.blit(my_bullet_sprite, (x, y))
if direction == 'LEFT':
screen.blit(my_bullet_sprite_LEFT, (x, y))
if direction == 'UP':
screen.blit(my_bullet_sprite_UP, (x, y))
if direction == 'DOWN':
screen.blit(my_bullet_sprite_DOWN, (x, y))
else:
if direction == 'RIGHT':
screen.blit(bullet1_sprite, (x, y))
if direction == 'LEFT':
screen.blit(bullet1_sprite_LEFT, (x, y))
if direction == 'UP':
screen.blit(bullet1_sprite_UP, (x, y))
if direction == 'DOWN':
screen.blit(bullet1_sprite_DOWN, (x, y))
def draw_panel(tanks):
global screen
pygame.draw.rect(screen, (0, 0, 0), ((800, 0), (200, 600)))
k = 0
max = 0
for tank in tanks:
if tank['score'] > max:
max = tank['score']
texttmp = font2.render('ID LIFE SCORE', True, (255, 255, 255))
texttmpRect = texttmp.get_rect()
texttmpRect.center = (900 + 15, 10)
screen.blit(texttmp, texttmpRect)
y = 30
while (max >= 0):
for tank in tanks:
if tank['score'] == max:
if tank['id'] != MY_TANK_ID:
text = font2.render('{}'.format(tank['id']), True, (255, 0, 0))
else:
text = font2.render('i', True, (0, 255, 0))
textRect = text.get_rect()
textRect.center = (825 + 15, y)
screen.blit(text, textRect)
if tank['id'] != MY_TANK_ID:
text = font2.render('{}'.format(tank['health']), True, (255, 0, 0))
else:
text = font2.render('{}'.format(tank['health']), True, (0, 255, 0))
textRect = text.get_rect()
textRect.center = (825 + 90, y)
screen.blit(text, textRect)
if tank['id'] != MY_TANK_ID:
text = font2.render('{}'.format(tank['score']), True, (255, 0, 0))
else:
text = font2.render('{}'.format(tank['score']), True, (0, 255, 0))
textRect = text.get_rect()
textRect.center = (825 + 160, y)
screen.blit(text, textRect)
y += 30
# print(tank['id'])
# print(tank['health'])
# print(tank['score'])
max -= 1
def loserr():
global screen, MY_SCORE
pygame.draw.rect(screen, (0, 0, 0), ((0, 0), (1000, 600)))
text = font.render('Неудача!', True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 40)
screen.blit(text, textRect)
text = font.render('Ваш итоговый счет: {}'.format(MY_SCORE), True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 150)
screen.blit(text, textRect)
def winerr():
global screen, MY_SCORE
pygame.draw.rect(screen, (0, 0, 0), ((0, 0), (1000, 600)))
text = font.render('Победа!', True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 40)
screen.blit(text, textRect)
text = font.render('Ваш итоговый счет: {}'.format(MY_SCORE), True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 150)
screen.blit(text, textRect)
def game_start():
global MY_SCORE
run = True
global font
global screen
los = False
won = False
global MOVE_KEYS
while run:
millis = clock.tick(FPS)
seconds = millis / 1000
screen.blit(background, (0, 0))
try:
remaining_time = event_client.response['remainingTime']
text = font.render('Remaining Time: {}'.format(remaining_time), True, (0, 0, 0))
textRect = text.get_rect()
screen.blit(text, textRect)
if remaining_time == 0:
run = False
hits = event_client.response['hits']
winners = event_client.response['winners']
losers = event_client.response['losers']
tanks = event_client.response['gameField']['tanks']
bullets = event_client.response['gameField']['bullets']
draw_panel(tanks)
for loser in losers:
if loser['tankId'] == MY_TANK_ID:
# print("")
los = True
for win in winners:
if win['tankId'] == MY_TANK_ID:
won = True
# run2 = True
# while run2:
# screen.fill((255, 255, 255))
#
# # for event in pygame.event.get():
# # if event.type == pygame.KEYDOWN:
# # if event.key == pygame.K_ESCAPE:
# # run2 = False
#
# text = font.render('self.text', True, (0, 0, 0))
# textRect = text.get_rect()
# textRect.center = (500, 500)
# screen.blit(text, textRect)
#
# screen.flip()
MY_X = 0
MY_Y = 0
for tank in tanks:
tank_x = tank['x']
tank_y = tank['y']
tank_width = tank['width']
tank_height = tank['height']
tank_direction = tank['direction']
tank_id = tank['id']
tank_health = tank['health']
if tank['id'] == MY_TANK_ID:
MY_SCORE = tank['score']
MY_X = tank['x']
MY_Y = tank['y']
# txt_losers = ','.join(i['tankId'] for i in losers)
# print(txt_losers)
# if tank['id'] == MY_TANK_ID: #and tank['health'] == 0:
# for lose in losers:
#
# print(','.join(lose['tankId']))
# print(tank['health'])
# for lose in losers:
# print(lose['tankid'])
# lose(tank['score'])
# print(losers)
# txt_losers = ','.join(i['tankId'] for i in losers)
# print(txt_losers)
draw_tank(tank_x, tank_y, tank_width, tank_height, tank_direction, tank_id,
tank_health)
for bullet in bullets:
bullet_x = bullet['x']
bullet_y = bullet['y']
bullet_owner = bullet['owner']
bullet_width = bullet['width']
bullet_height = bullet['height']
bullet_direction = bullet['direction']
draw_bullet(bullet_x, bullet_y, bullet_width, bullet_height,
bullet_direction, bullet_owner) # if bullet_owner == my_tank_id
except:
pass
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
los = False
won = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
# if event.key in MOVE_KEYS:
# client.turn_tank(client.token, MOVE_KEYS[event.key])
# if event.key == pygame.K_SPACE:
# client.fire_bullet(client.token)
# so_close_x = MY_X
# so_close_y = MY_Y
# so_close_x_tmp = 0
# so_close_y_tmp = 0
#
# so_close_tank_id = ''
# for tank in tanks:
# if tank['id'] != MY_TANK_ID:
# if abs(tank['x'] - MY_X) < so_close_x:
# so_close_x = abs(tank['x'] - MY_X)
# so_close_x_tmp = tank['x']
# if abs(tank['y'] - MY_Y) < so_close_y:
# so_close_y = abs(tank['y'] - MY_Y)
# so_close_y_tmp = tank['y']
# for tank in tanks:
# if tank['id'] != MY_TANK_ID:
# if tank['x'] == so_close_x_tmp and tank['y'] == so_close_y_tmp:
# so_close_tank_id = tank['id']
# else:
# so_close_tank_id = ''
my_direction = ''
for tank in tanks:
if tank['id'] == MY_TANK_ID:
my_direction = tank['direction']
for tank in tanks:
if tank['id'] != MY_TANK_ID:
if tank['y'] >= MY_Y and tank['y'] <= MY_Y + 35:
if tank['direction'] == 'DOWN' and my_direction == 'UP':
client.fire_bullet(client.token)
client.turn_tank(client.token, 'RIGHT')
if tank['direction'] == 'UP' and my_direction == 'DOWN':
client.fire_bullet(client.token)
client.turn_tank(client.token, 'LEFT')
if tank['x'] >= MY_X and tank['x'] <= MY_X + 35:
if tank['direction'] == 'LEFT' and my_direction == 'RIGHT':
client.fire_bullet(client.token)
client.turn_tank(client.token, 'UP')
if tank['direction'] == 'RIGHT' and my_direction == 'LEFT':
client.fire_bullet(client.token)
client.turn_tank(client.token, 'DOWN')
# print(so_close_x)
# print(so_close_y)
# print(so_close_tank_id)
# distance = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
#
# itmp = 0
# for tank in tanks:
# if tank['id'] != MY_TANK_ID:
# distance[itmp].append(tank['id'])
# distance[itmp].append( ((tank['x'] - MY_X)**2 + (tank['y'] - MY_Y)**2)**0.5)
# itmp += 1
#
# print(distance)
if los:
loserr()
if won:
winerr()
pygame.display.flip()
client.connection.close()
# pygame.quit()
client = TankRpcClient()
client.check_server_status()
which_room = 'room-' + str(WHICH_ROOM)
client.obtain_token(which_room)
event_client = TankConsumerClient(which_room)
event_client.start()
client.turn_tank(client.token, 'UP')
game_start()
runtmp = True
while runtmp:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
runtmp = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
runtmp = False
pygame.draw.rect(screen, (0, 0, 0), ((0, 0), (1000, 600)))
text = font.render('Игра закончена!', True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 40)
screen.blit(text, textRect)
text = font.render('Ваш итоговый счет: {}'.format(MY_SCORE), True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 150)
screen.blit(text, textRect)
text = font.render('Нажмите R чтобы сыграть заново!', True, (255, 255, 255))
textRect = text.get_rect()
textRect.center = (400, 350)
screen.blit(text, textRect)
pygame.display.flip()
#run = False
#print(room.func)
SCREEN_W = 800
screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
for room in rooms:
room.draw(screen)
pygame.display.flip()
|
{"/menu.py": ["/button.py"], "/main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/multi_main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/bullet.py": ["/tank.py"], "/wall.py": ["/tank.py"]}
|
6,778
|
adiljumak/MultiPlayer_Tank_Game_RabbitMQ_MongoDB
|
refs/heads/main
|
/bullet.py
|
import pygame
import random
from enum import Enum
from tank import Tank
from direction import Direction
pygame.init()
pygame.mixer.init()
sound_shoot = pygame.mixer.Sound('sound_shoot.wav')
class Bullet:
def __init__(self, tank, speed, screen):
sound_shoot.play()
self.screen = screen
self.size = 2
self.tank = tank
self.sprite = tank.bullet_sprite
self.direction = tank.direction
self.speed = speed
self.life_time = 0
self.del_time = 1.5 # in sec
self.bullet_w = 15
self.bullet_h = 5
self.sprite_RIGHT = self.sprite
self.sprite_UP = pygame.transform.rotate(self.sprite, 90)
self.sprite_LEFT = pygame.transform.rotate(self.sprite, 180)
self.sprite_DOWN = pygame.transform.rotate(self.sprite, 270)
if tank.direction == Direction.RIGHT:
self.sprite = tank.bullet_sprite
self.x = tank.x + tank.height + int(tank.height / 2)
self.y = int(tank.y + tank.width / 2)
if self.direction == Direction.LEFT:
self.sprite = pygame.transform.rotate(self.sprite, 180)
self.x = tank.x - tank.height + int(tank.height / 2)
self.y = tank.y + int(tank.width / 2)
if self.direction == Direction.UP:
self.sprite = pygame.transform.rotate(self.sprite, 90)
self.x = tank.x + int(tank.height / 2)
self.y = tank.y - int(tank.width / 2)
if self.direction == Direction.DOWN:
self.sprite = pygame.transform.rotate(self.sprite, 270)
self.x = tank.x + int(tank.height / 2)
self.y = tank.y + tank.width + int(tank.width / 2)
def draw(self):
#pygame.draw.circle(self.screen, self.color, (self.x, self.y), self.size)
self.screen.blit(self.sprite, (self.x , self.y))
def move(self, seconds):
self.life_time += seconds
if self.direction == Direction.RIGHT:
self.x += int(self.speed * seconds)
if self.direction == Direction.LEFT:
self.x -= int(self.speed * seconds)
if self.direction == Direction.UP:
self.y -= int(self.speed * seconds)
if self.direction == Direction.DOWN:
self.y += int(self.speed * seconds)
|
{"/menu.py": ["/button.py"], "/main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/multi_main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/bullet.py": ["/tank.py"], "/wall.py": ["/tank.py"]}
|
6,779
|
adiljumak/MultiPlayer_Tank_Game_RabbitMQ_MongoDB
|
refs/heads/main
|
/tank.py
|
import pygame
import random
from enum import Enum
from direction import Direction
pygame.init()
pygame.mixer.init()
class Tank:
def __init__(self, x, y, speed, sprite, bullet_sprite, d_right=pygame.K_RIGHT, d_left=pygame.K_LEFT, d_up=pygame.K_UP,
d_down=pygame.K_DOWN, fire_key=pygame.K_RETURN):
self.buff = False
self.buff_time = 0
self.num_of_bullet = 3
self.fire_key = fire_key
self.recharge = False
self.recharge_duration = 2 # in sec
self.recharge_time = 0 # in sec
self.lifes = 3
self.x = x
self.y = y
self.speed = speed
#self.color = color
self.bullet_sprite = bullet_sprite
self.sprite = sprite
self.sprite_RIGHT = self.sprite
self.sprite_UP = pygame.transform.rotate(self.sprite, 90)
self.sprite_LEFT = pygame.transform.rotate(self.sprite, 180)
self.sprite_DOWN = pygame.transform.rotate(self.sprite, 270)
self.width = 35
self.height = 35
self.direction = Direction.RIGHT
self.KEY = {
d_right: Direction.RIGHT,
d_left: Direction.LEFT,
d_up: Direction.UP,
d_down: Direction.DOWN
}
def draw(self, screen, size_w, size_h):
tank_c = (self.x + int(self.width / 2), self.y + int(self.height / 2))
if self.x <= 0:
self.x = size_w - self.width
if self.y <= 0:
self.y = size_h - self.height
if self.x + self.width > size_w:
self.x = 0
if self.y >= size_h:
self.y = 0
#screen.blit(self.sprite, (self.x, self.y))
# pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height), 2)
# pygame.draw.circle(screen, self.color, tank_c, int(self.width / 2))
if self.direction == Direction.RIGHT:
screen.blit(self.sprite_RIGHT, (self.x, self.y))
for i in range(0, self.lifes):
r = int(((self.width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + self.x + i * 3 * r, self.y + r - 2), r)
# pygame.draw.line(screen, self.color, tank_c,
# (self.x + self.height + int(self.height / 2), int(self.y + self.width / 2)), 4)
if self.direction == Direction.LEFT:
screen.blit(self.sprite_LEFT, (self.x, self.y))
for i in range(0, self.lifes):
r = int(((self.width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + self.x + i * 3 * r + 4, self.y + r - 4), r)
# pygame.draw.line(screen, self.color, tank_c,
# (self.x - self.height + int(self.height / 2), self.y + int(self.width / 2)), 4)
if self.direction == Direction.UP:
screen.blit(self.sprite_UP, (self.x, self.y))
for i in range(0, self.lifes):
r = int(((self.width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + self.x + i * 3 * r + 3, self.y + r + self.width - 2), r)
# pygame.draw.line(screen, self.color, tank_c, (self.x + int(self.height / 2), self.y - int(self.width / 2)),
# 4)
if self.direction == Direction.DOWN:
screen.blit(self.sprite_DOWN, (self.x, self.y))
for i in range(0, self.lifes):
r = int(((self.width / 3) / 2) - 2)
pygame.draw.circle(screen, (0, 255, 0), (2 * r + self.x + i * 3 * r + 1, self.y + r - 4), r)
# pygame.draw.line(screen, self.color, tank_c,
# (self.x + int(self.height / 2), self.y + self.width + int(self.width / 2)), 4)
def change_direction(self, direction):
self.direction = direction
def move(self, seconds):
if self.direction == Direction.LEFT:
self.x -= int(self.speed * seconds)
if self.direction == Direction.RIGHT:
self.x += int(self.speed * seconds)
if self.direction == Direction.UP:
self.y -= int(self.speed * seconds)
if self.direction == Direction.DOWN:
self.y += int(self.speed * seconds)
self.recharge_time += seconds
if self.recharge_time >= self.recharge_duration:
self.recharge = False
self.recharge_time = 0
|
{"/menu.py": ["/button.py"], "/main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/multi_main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/bullet.py": ["/tank.py"], "/wall.py": ["/tank.py"]}
|
6,780
|
adiljumak/MultiPlayer_Tank_Game_RabbitMQ_MongoDB
|
refs/heads/main
|
/wall.py
|
import pygame
import random
from enum import Enum
from tank import Tank
from direction import Direction
pygame.init()
pygame.mixer.init()
wall_sprite = pygame.image.load("wall_sprite.png")#.convert()
wall_sprite.set_colorkey((255, 255, 255))
class Wall:
def __init__(self, x, y):
self.size = 40 # in px
self.x = x
self.y = y
self.sprite = wall_sprite
self.sprite = pygame.transform.scale(self.sprite, (self.size, self.size))
def draw(self, screen):
screen.blit(self.sprite, (self.x, self.y))
|
{"/menu.py": ["/button.py"], "/main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/multi_main.py": ["/tank.py", "/bullet.py", "/wall.py"], "/bullet.py": ["/tank.py"], "/wall.py": ["/tank.py"]}
|
6,819
|
robertutterback/flask-celery-toy
|
refs/heads/master
|
/app/all.py
|
import os, uuid
from pathlib import Path
from flask import (
Blueprint,
request, render_template, redirect, url_for,
jsonify, session, flash, current_app
)
from flask_socketio import emit, disconnect, join_room, leave_room
from werkzeug.datastructures import MultiDict as FormDataStructure
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
from .tasks import long_task
from . import socketio
bp = Blueprint("all", __name__)
class MyForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()],
render_kw = {"placeholder": 'Enter your name'})
# ignore dataset, for now
def get_output_path(dataset, room):
return Path(current_app.instance_path) / 'outputs' / room
@bp.route('/', methods=['GET'])
@bp.route('/<dataset>/', methods=['GET'])
@bp.route('/<dataset>/<room>', methods=['GET'])
def index(dataset='default', room=None):
form = MyForm()
done = False
output = None
if room:
outfile = get_output_path(dataset, room)
tmpfile = Path(f"{outfile}.tmp")
if not outfile.exists():
if tmpfile.exists(): # still in progress
output = 'Task still in progress.'
# keep room, then the javascript will join and check for output
else:
output = f'Room "{room}" does not exist!'
room = None
else: # outfile exists, we're done
with open(outfile, 'r') as f:
output = f.read()
done = True
return render_template('index.html', dataset=dataset, room=room,
result=output, done=done, form=form)
@bp.route('/longtask', methods=['POST'])
def longtask():
data = request.json
form = MyForm()
if 'formdata' in data:
form_data = FormDataStructure(data['formdata'])
form = MyForm(formdata=form_data)
if not form.validate():
return jsonify(data={'form error': form.errors}), 400
name = form.name.data
dataset = request.json['dataset']
roomid = str(uuid.uuid4())
outfile = Path(current_app.instance_path) / 'outputs' / roomid
# Let others know this is in progress
Path(f"{outfile}.tmp").touch()
details = [dataset, roomid]
# print("Long task would be started")
task = long_task.delay(dataset, os.fspath(outfile), roomid,
url_for('all.task_event', _external=True))
# Socket not connected yet, (and room not joined yet), so can't emit here.
# socketio.emit('status', {'status': f'Task started: {details}'}, to=roomid)
return jsonify({'roomid': roomid, 'name': name}), 202
@bp.route('/task_event/', methods=['POST'])
def task_event():
data = request.json
if not data or 'taskid' not in data:
print("Incorrect task event data from celery!")
return 'error', 404
roomid = request.json['taskid']
print(f"Trying to emit to {roomid}")
socketio.emit('taskprogress', data, to=roomid)
if data['done']:
outfile = Path(current_app.instance_path) / 'outputs' / data['taskid']
with open(outfile, 'r') as f:
result = f.read()
print(f"Done; emitting '{result}' to {roomid}")
socketio.emit('taskdone', result, to=roomid)
return 'ok'
@socketio.on('status')
def bounce_status(message):
emit('status', {'status': message['status']}, to=request.sid)
@socketio.on('connect')
def connect(data=None):
print(f'Client connected.')
@socketio.on('join_room')
def join_task_room(data):
assert 'roomid' in data
join_room(data['roomid'])
socketio.emit('status', {'status': f'Joined room: {data["roomid"]}'}, to=request.sid)
## @TODO: what is this?
@socketio.on('disconnect request')
def disconnect_request():
emit('status', {'status': 'Disconnected!'}, to=request.sid)
disconnect()
@socketio.on('disconnect')
def events_disconnect():
# del current_app.clients[session['userid']]
print(f"Client disconnected")
|
{"/app/all.py": ["/app/__init__.py"], "/run.py": ["/app/__init__.py"], "/celery_worker.py": ["/app/__init__.py"], "/app/__init__.py": ["/app/all.py"]}
|
6,820
|
robertutterback/flask-celery-toy
|
refs/heads/master
|
/run.py
|
from app import create_app, socketio
import app
if __name__ == '__main__':
app = create_app(celery=app.celery)
socketio.run(app, debug=True, host='0.0.0.0')
|
{"/app/all.py": ["/app/__init__.py"], "/run.py": ["/app/__init__.py"], "/celery_worker.py": ["/app/__init__.py"], "/app/__init__.py": ["/app/all.py"]}
|
6,821
|
robertutterback/flask-celery-toy
|
refs/heads/master
|
/celery_worker.py
|
from app import celery, create_app, init_celery
#app = create_app(os.getenv('FLASK_CONFIG') or 'default')
#app.app_context().push()
app = create_app()
init_celery(celery, app)
|
{"/app/all.py": ["/app/__init__.py"], "/run.py": ["/app/__init__.py"], "/celery_worker.py": ["/app/__init__.py"], "/app/__init__.py": ["/app/all.py"]}
|
6,822
|
robertutterback/flask-celery-toy
|
refs/heads/master
|
/app/__init__.py
|
from pathlib import Path
from flask import Flask
from celery import Celery
from flask_socketio import SocketIO
from flask_wtf.csrf import CSRFProtect
def init_celery(celery, app):
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
def make_celery(app_name=__name__):
backend = 'redis://localhost:6379/0'
broker = backend.replace('0', '1')
return Celery(app_name, backend=backend, broker=broker,
include=['app.tasks'])
celery = make_celery()
socketio = SocketIO()
csrf = CSRFProtect()
def create_app(app_name=__name__, **kwargs):
app = Flask(app_name)
app.secret_key = 'toydev'
if kwargs.get("celery"):
init_celery(kwargs.get("celery"), app)
csrf.init_app(app)
from app.all import bp
app.register_blueprint(bp)
(Path(app.instance_path) / 'outputs').mkdir(parents=True, exist_ok=True)
socketio.init_app(app, message_queue='redis://localhost:6379/0')
return app
|
{"/app/all.py": ["/app/__init__.py"], "/run.py": ["/app/__init__.py"], "/celery_worker.py": ["/app/__init__.py"], "/app/__init__.py": ["/app/all.py"]}
|
6,832
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/object_detection_service/object_detection_service/handlers/object_detection.py
|
import logging
from typing import Tuple
import torch
from flask import Response, request, make_response
from flask_restful import Resource
import numpy as np
import cv2 as cv
from torchvision.models.detection.retinanet import RetinaNet
from ..config import \
CLASS_MAPPING
from ..entities import \
DetectedObjects, BoundingBox, DetectedObject
from ..utils import \
image_from_str, to_chw_tensor
STANDARDIZATION_CONST = 255.0
RawPrediction = dict
logging.getLogger().setLevel(logging.INFO)
class ObjectDetection(Resource):
def __init__(
self,
model: RetinaNet,
confidence_threshold: float,
max_image_dim: int
):
self.__model = model
self.__confidence_threshold = confidence_threshold
self.__max_image_dim = max_image_dim
def post(self) -> Response:
if 'image' not in request.files:
return make_response({'msg': 'Field named "image" required.'}, 400)
image = image_from_str(raw_image=request.files['image'].read())
results = self.__infer_from_image(image=image)
return make_response(results.to_dict(), 200)
def __infer_from_image(
self,
image: np.ndarray
) -> DetectedObjects:
image, scale = self.__standardize_image(image=image)
logging.info(f"Standardized image shape: {image.shape}. scale: {scale}")
prediction = self.__model(image)[0]
return self.__post_process_inference(prediction=prediction, scale=scale)
def __standardize_image(
self,
image: np.ndarray
) -> Tuple[torch.Tensor, float]:
max_shape = max(image.shape[:2])
if max_shape <= self.__max_image_dim:
return to_chw_tensor(image / STANDARDIZATION_CONST), 1.0
scale = self.__max_image_dim / max_shape
resized_image = cv.resize(image, dsize=None, fx=scale, fy=scale)
return to_chw_tensor(resized_image / STANDARDIZATION_CONST), scale
def __post_process_inference(
self,
prediction: RawPrediction,
scale: float
) -> DetectedObjects:
boxes, scores, labels = \
prediction["boxes"].detach().numpy() / scale, \
prediction["scores"].detach().numpy(), \
prediction["labels"].detach().numpy()
detected_objects = []
for bbox, score, label in zip(boxes, scores, labels):
if score < self.__confidence_threshold:
continue
bbox = BoundingBox(
left_top=(int(round(bbox[0])), int(round(bbox[1]))),
right_bottom=(int(round(bbox[2])), int(round(bbox[3])))
)
detected_object = DetectedObject(
bbox=bbox,
confidence=score.astype(float).item(),
label=label.item(),
class_name=CLASS_MAPPING.get(label, "N/A")
)
detected_objects.append(detected_object)
return DetectedObjects(detected_objects=detected_objects)
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,833
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/resources_manager_service/resources_manager_service/handlers/input_image_register.py
|
import os
from uuid import uuid4
from flask import request, Response, make_response, send_from_directory
from flask_restful import Resource
from .utils import initialize_request_parser, build_base_resource_path
from .config import RESOURCE_IDENTIFIER_FIELD_NAME, LOGIN_FIELD_NAME
from ..config import INPUT_IMAGE_NAME
class InputImageRegister(Resource):
def __init__(self):
self.__get_request_parser = initialize_request_parser()
self.__post_request_parser = initialize_request_parser(
include_resource_identifier=False
)
def post(self) -> Response:
if 'image' not in request.files:
return make_response(
{'msg': 'Field called "image" must be specified'}, 400
)
data = self.__post_request_parser.parse_args()
requester_login = data[LOGIN_FIELD_NAME]
resource_identifier = f'{uuid4()}'
target_path = os.path.join(
build_base_resource_path(
requester_login=requester_login,
resource_identifier=resource_identifier
),
INPUT_IMAGE_NAME
)
os.makedirs(os.path.dirname(target_path), exist_ok=True)
request.files['image'].save(target_path)
return make_response(
{
LOGIN_FIELD_NAME: requester_login,
RESOURCE_IDENTIFIER_FIELD_NAME: resource_identifier
},
200
)
def get(self) -> Response:
data = self.__get_request_parser.parse_args()
requester_login = data[LOGIN_FIELD_NAME]
resource_identifier = data[RESOURCE_IDENTIFIER_FIELD_NAME]
resources_dir = build_base_resource_path(
requester_login=requester_login,
resource_identifier=resource_identifier
)
if not os.path.isdir(resources_dir):
return make_response(
{'msg': 'Incorrect resource identifiers.'}, 500
)
try:
return send_from_directory(
directory=resources_dir,
filename=INPUT_IMAGE_NAME,
as_attachment=True
)
except FileNotFoundError:
return make_response(
{'msg': 'There is no input file detected.'}, 500
)
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,834
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/face_detection_service/face_detection_service/app.py
|
import json
import logging
from functools import partial
from threading import Thread
from typing import List, Any
import pika
from pika import spec
from pika.channel import Channel
from retina_face_net import RetinaFaceNet, RetinaFaceNetPrediction
from .communication import fetch_processing_input, register_results, \
LOGIN_FIELD, RESOURCE_IDENTIFIER_FIELD
from .config import RABBIT_HOST, RABBIT_PORT, RABBIT_USER, RABBIT_PASSWORD, \
FACE_DETECTION_CHANNEL, WEIGHTS_PATH, TOP_K, CONFIDENCE_THRESHOLD
logging.getLogger().setLevel(logging.INFO)
def start_app() -> None:
connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=RABBIT_HOST,
port=RABBIT_PORT,
credentials=pika.PlainCredentials(
username=RABBIT_USER,
password=RABBIT_PASSWORD
)
)
)
channel = connection.channel()
channel.queue_declare(queue=FACE_DETECTION_CHANNEL)
channel.basic_qos(prefetch_count=1)
model = RetinaFaceNet.initialize(
weights_path=WEIGHTS_PATH,
top_k=TOP_K,
confidence_threshold=CONFIDENCE_THRESHOLD
)
channel.basic_consume(
queue=FACE_DETECTION_CHANNEL,
on_message_callback=partial(on_face_detection, model=model)
)
channel.start_consuming()
def on_face_detection(
channel: Channel,
method: spec.Basic.Deliver,
properties: spec.BasicProperties,
body: str,
model: RetinaFaceNet
) -> None:
logging.info("Starting worker thread.")
worker_thread = Thread(
target=start_face_detection,
args=(channel, method, properties, body, model,)
)
worker_thread.daemon = True
worker_thread.start()
logging.info("Working thread started.")
def start_face_detection(
channel: Channel,
method: spec.Basic.Deliver,
properties: spec.BasicProperties,
body: str,
model: RetinaFaceNet
) -> None:
# https://stackoverflow.com/questions/51752890/how-to-disable-heartbeats-with-pika-and-rabbitmq
try:
message_content = json.loads(body)
logging.info(f"Processing request: {message_content}")
image = fetch_processing_input(
requester_login=message_content[LOGIN_FIELD],
request_identifier=message_content[RESOURCE_IDENTIFIER_FIELD]
)
inference_results = model.infer(image=image)
logging.info(f"Inference done: {message_content}")
serialized_results = _inference_results_to_dict(
inference_results=inference_results
)
register_results(
requester_login=message_content[LOGIN_FIELD],
request_identifier=message_content[RESOURCE_IDENTIFIER_FIELD],
results=serialized_results
)
send_ack = partial(ack_message, channel=channel, delivery_tag=method.delivery_tag)
channel.connection.add_callback_threadsafe(send_ack)
logging.info(f"Results registered: {message_content}")
except Exception as e:
logging.error(f"Could not process image: {e}")
def ack_message(channel: Channel, delivery_tag: Any):
"""Note that `channel` must be the same pika channel instance via which
the message being ACKed was retrieved (AMQP protocol constraint).
"""
if channel.is_open:
channel.basic_ack(delivery_tag)
else:
# Channel is already closed, so we can't ACK this message;
# log and/or do something that makes sense for your app in this case.
pass
def _inference_results_to_dict(
inference_results: List[RetinaFaceNetPrediction]
) -> dict:
return {
"inference_results": [
{
"bounding_box": {
"left_top": list(r.bbox.left_top.compact_form),
"right_bottom": list(r.bbox.right_bottom.compact_form)
},
"confidence": r.confidence.astype(float).item(),
"landmarks": [
list(l.compact_form) for l in r.landmarks
]
} for r in inference_results
]
}
if __name__ == '__main__':
start_app()
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,835
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/gateway_service/gateway_service/app.py
|
import logging
import time
from threading import Thread
from typing import Tuple
import pika
from flask import Flask
from flask_restful import Api
from .handlers.face_detection import FaceDetection
from .handlers.object_detection import ObjectDetection
from .config import RABBIT_PASSWORD, RABBIT_USER, RABBIT_PORT, RABBIT_HOST, \
PORT, FACE_DETECTION_CHANNEL, GATEWAY_API_BASE_PATH
logging.getLogger().setLevel(logging.INFO)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
STOP_HEARTBEAT = False
def keep_rabbit_connection_online(connection: pika.BlockingConnection) -> None:
while not STOP_HEARTBEAT:
logging.info("RabbitMQ heartbeat.")
connection.process_data_events()
time.sleep(30)
def create_api() -> Tuple[Api, Thread]:
api = Api(app)
connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=RABBIT_HOST,
port=RABBIT_PORT,
credentials=pika.PlainCredentials(
username=RABBIT_USER,
password=RABBIT_PASSWORD
),
heartbeat=60
)
)
channel = connection.channel()
channel.queue_declare(queue=FACE_DETECTION_CHANNEL)
api.add_resource(
FaceDetection,
construct_api_url('detect_faces'),
resource_class_kwargs={
'rabbit_channel': channel
}
)
api.add_resource(
ObjectDetection,
construct_api_url('detect_objects')
)
heartbeat = Thread(target=keep_rabbit_connection_online, args=(connection, ))
heartbeat.start()
return api, heartbeat
def construct_api_url(url_postfix: str) -> str:
return f"{GATEWAY_API_BASE_PATH}/{url_postfix}"
if __name__ == '__main__':
api, heartbeat = create_api()
try:
app.run(host='0.0.0.0', port=PORT)
except KeyboardInterrupt:
STOP_HEARTBEAT = True
heartbeat.join()
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,836
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/gateway_service/gateway_service/config.py
|
import os
PORT = 50000
FACE_DETECTION_CHANNEL = "face_detection_channel"
RABBIT_HOST = os.getenv("RABBIT_HOST", "127.0.0.1")
RABBIT_PORT = 5672
RABBIT_USER = os.getenv("RABBIT_USER", "guest")
RABBIT_PASSWORD = os.getenv("RABBIT_PASSWORD", "guest")
OBJECT_DETECTION_URL = "http://127.0.0.1:50001/maas_workshop/v2/object_detection/detect"
INPUT_IMAGE_INGEST_URL = "http://127.0.0.1:50002/maas_workshop/v2/resources_manager/input_image_register"
FETCH_RESULTS_URL = "http://127.0.0.1:50002/maas_workshop/v2/resources_manager/face_detection_register"
GATEWAY_API_BASE_PATH = "/maas_workshop/v2/gateway"
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,837
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/object_detection_service/object_detection_service/entities.py
|
from dataclasses import dataclass
from typing import Tuple, List
from dataclasses_json import DataClassJsonMixin
@dataclass(frozen=True)
class BoundingBox(DataClassJsonMixin):
left_top: Tuple[int, int]
right_bottom: Tuple[int, int]
@dataclass
class DetectedObject(DataClassJsonMixin):
bbox: BoundingBox
confidence: float
label: int
class_name: str
@dataclass
class DetectedObjects(DataClassJsonMixin):
detected_objects: List[DetectedObject]
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,838
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/resources_manager_service/resources_manager_service/handlers/face_detection_register.py
|
import json
import os
from json.decoder import JSONDecodeError
from flask import Response, make_response
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from .utils import safe_load_json, initialize_request_parser, \
build_base_resource_path, persist_json_result
from .config import LOGIN_FIELD_NAME, RESOURCE_IDENTIFIER_FIELD_NAME
from ..config import PERSISTENCE_DIR
FACE_DETECTION_FILE_NAME = "face_detection.json"
FACE_DETECTION_RESULTS_FIELD = "face_detection_results"
class FaceDetectionRegister(Resource):
def __init__(self):
self.__get_request_parser = initialize_request_parser()
self.__post_request_parser = self.__initialize_post_request_parser()
def get(self) -> Response:
data = self.__get_request_parser.parse_args()
requester_login = data[LOGIN_FIELD_NAME]
resource_identifier = data[RESOURCE_IDENTIFIER_FIELD_NAME]
resource_path = os.path.join(
PERSISTENCE_DIR, requester_login, resource_identifier, FACE_DETECTION_FILE_NAME
)
if not os.path.isdir(os.path.dirname(resource_path)):
return make_response(
{'msg': 'Incorrect resource identifiers.'}, 500
)
if not os.path.isfile(resource_path):
return make_response({"status": "in_progress"}, 200)
resource = safe_load_json(resource_path)
return make_response(resource, 200)
def post(self) -> Response:
data = self.__post_request_parser.parse_args()
requester_login = data[LOGIN_FIELD_NAME]
resource_identifier = data[RESOURCE_IDENTIFIER_FIELD_NAME]
target_path = os.path.join(
build_base_resource_path(
requester_login=requester_login,
resource_identifier=resource_identifier
),
FACE_DETECTION_FILE_NAME
)
if not os.path.isdir(os.path.dirname(target_path)):
return make_response(
{'msg': 'Wrong resource identifier or requester login'}, 500
)
try:
content = json.loads(data[FACE_DETECTION_RESULTS_FIELD])
persist_json_result(target_path=target_path, content=content)
return make_response({"msg": "OK"}, 200)
except (JSONDecodeError, KeyError):
return make_response(
{'msg': f'Input in {FACE_DETECTION_RESULTS_FIELD} is not JSON'},
400
)
def __initialize_post_request_parser(self) -> RequestParser:
parser = initialize_request_parser()
parser.add_argument(
FACE_DETECTION_RESULTS_FIELD,
help=f'Field "{FACE_DETECTION_RESULTS_FIELD}" must '
'be specified in this request.',
required=True
)
return parser
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,839
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/gateway_service/gateway_service/handlers/proxy.py
|
import requests
from flask import request, Response, make_response
from flask_restful import Resource
class Proxy(Resource):
def __init__(self):
super().__init__()
self.__excluded_headers = [
'content-encoding', 'content-length',
'transfer-encoding', 'connection'
]
def _forward_message(self, target_url: str) -> Response:
headers = {
key: value for (key, value) in request.headers if key != 'Host'
}
try:
resp = requests.request(
method=request.method,
url=target_url,
headers=headers,
data=request.get_data(),
allow_redirects=False,
verify=False
)
except Exception:
return make_response({'msg': 'Internal error'}, 500)
headers = [
(name, value) for (name, value) in resp.raw.headers.items()
if name.lower() not in self.__excluded_headers
]
response = Response(resp.content, resp.status_code, headers)
return response
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,840
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/gateway_service/gateway_service/handlers/face_detection.py
|
import json
from flask import Response, make_response
from pika.channel import Channel
from ..config import INPUT_IMAGE_INGEST_URL, FACE_DETECTION_CHANNEL, \
FETCH_RESULTS_URL
from .proxy import Proxy
class FaceDetection(Proxy):
def __init__(self, rabbit_channel: Channel):
super().__init__()
self.__rabbit_channel = rabbit_channel
def post(self) -> Response:
registration_response = self._forward_message(target_url=INPUT_IMAGE_INGEST_URL)
if registration_response.status_code != 200:
return registration_response
try:
self.__rabbit_channel.basic_publish(
exchange="",
routing_key=FACE_DETECTION_CHANNEL,
body=json.dumps(registration_response.json)
)
except Exception as e:
return make_response({"msg": f"Internal error, {e}"}, 500)
return registration_response
def get(self) -> Response:
return self._forward_message(target_url=FETCH_RESULTS_URL)
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,841
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/resources_manager_service/resources_manager_service/config.py
|
import os
BASE_RESOURCE_PATH = '/maas_workshop/v2/resources_manager'
PORT = 50002
PERSISTENCE_DIR = os.path.abspath(os.path.join(
os.path.dirname(__file__), "..", "storage"
))
INPUT_IMAGE_NAME = "input_image.jpeg"
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,842
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/face_detection_service/face_detection_service/config.py
|
import os
FACE_DETECTION_CHANNEL = "face_detection_channel"
RABBIT_HOST = os.getenv("RABBIT_HOST", "127.0.0.1")
RABBIT_PORT = 5672
RABBIT_USER = os.getenv("RABBIT_USER", "guest")
RABBIT_PASSWORD = os.getenv("RABBIT_PASSWORD", "guest")
RESOURCE_MANAGER_BASE_URI = "http://127.0.0.1:50002/maas_workshop/v2/resources_manager/"
INPUT_IMAGE_FETCHING_URI = f"{RESOURCE_MANAGER_BASE_URI}input_image_register"
RESULT_POSTING_URI = f"{RESOURCE_MANAGER_BASE_URI}face_detection_register"
WEIGHTS_PATH = os.path.join("/weights", "weights.pth")
TOP_K = 50
CONFIDENCE_THRESHOLD = 0.2
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,843
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/object_detection_service/object_detection_service/utils.py
|
from typing import Union, List
import numpy as np
import cv2 as cv
import torch
def image_from_str(raw_image: str) -> np.ndarray:
data = np.fromstring(raw_image, dtype=np.uint8)
return cv.imdecode(data, cv.IMREAD_COLOR)
def to_chw_tensor(x: Union[np.ndarray, List[np.ndarray]]) -> torch.Tensor:
if type(x) is not list:
x = [x]
return torch.Tensor([e.transpose(2, 0, 1).copy() for e in x])
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,844
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/object_detection_service/object_detection_service/app.py
|
import torchvision
from flask import Flask
from flask_restful import Api
from .config import \
OBJECT_DETECTION_PATH, CONFIDENCE_THRESHOLD, MAX_IMAGE_DIM, PORT
from .handlers.object_detection import \
ObjectDetection
app = Flask(__name__)
def create_api() -> Api:
api = Api(app)
model = torchvision.models.detection.retinanet_resnet50_fpn(pretrained=True)
model.eval()
api.add_resource(
ObjectDetection,
OBJECT_DETECTION_PATH,
resource_class_kwargs={
'model': model,
'confidence_threshold': CONFIDENCE_THRESHOLD,
'max_image_dim': MAX_IMAGE_DIM
}
)
return api
api = create_api()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=PORT)
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,845
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/resources_manager_service/resources_manager_service/app.py
|
from flask import Flask
from flask_restful import Api
from .handlers.input_image_register import InputImageRegister
from .handlers.face_detection_register import FaceDetectionRegister
from .config import BASE_RESOURCE_PATH, PORT
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
def create_api() -> Api:
api = Api(app)
api.add_resource(
InputImageRegister,
construct_api_url('input_image_register')
)
api.add_resource(
FaceDetectionRegister,
construct_api_url('face_detection_register')
)
return api
def construct_api_url(resource_postfix: str) -> str:
return f'{BASE_RESOURCE_PATH}/{resource_postfix}'
if __name__ == '__main__':
api = create_api()
app.run(host='0.0.0.0', port=PORT)
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,846
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/resources_manager_service/resources_manager_service/handlers/config.py
|
LOGIN_FIELD_NAME = "login"
RESOURCE_IDENTIFIER_FIELD_NAME = "resource_identifier"
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,847
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/resources_manager_service/resources_manager_service/handlers/utils.py
|
import json
import os
from typing import Optional
from flask_restful import reqparse
from .config import LOGIN_FIELD_NAME, RESOURCE_IDENTIFIER_FIELD_NAME
from ..config import PERSISTENCE_DIR
def persist_json_result(target_path: str, content: dict) -> None:
with open(target_path, "w") as f:
json.dump(content, f)
def safe_load_json(path: str) -> Optional[dict]:
try:
with open(path, "r") as f:
return json.load(f)
except Exception:
return None
def initialize_request_parser(
include_resource_identifier: bool = True
) -> reqparse.RequestParser:
parser = reqparse.RequestParser()
parser.add_argument(
LOGIN_FIELD_NAME,
help='Field "login" must be specified in this request.',
required=True
)
if include_resource_identifier:
parser.add_argument(
RESOURCE_IDENTIFIER_FIELD_NAME,
help='Field "resource_identifier" must '
'be specified in this request.',
required=True
)
return parser
def build_base_resource_path(
requester_login: str,
resource_identifier: str
) -> str:
return os.path.join(
PERSISTENCE_DIR, requester_login, resource_identifier
)
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,848
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/object_detection_service/cache_weights.py
|
import torchvision
if __name__ == '__main__':
print("Model weights fetching...")
_ = torchvision.models.detection.retinanet_resnet50_fpn(pretrained=True)
print("Done.")
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,849
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/face_detection_service/face_detection_service/communication.py
|
import json
import numpy as np
import cv2 as cv
import requests
from .config import INPUT_IMAGE_FETCHING_URI, RESULT_POSTING_URI
LOGIN_FIELD = "login"
RESOURCE_IDENTIFIER_FIELD = "resource_identifier"
FACE_DETECTION_RESULTS_FIELD = "face_detection_results"
def fetch_processing_input(
requester_login: str,
request_identifier: str
) -> np.ndarray:
payload = {
LOGIN_FIELD: requester_login,
RESOURCE_IDENTIFIER_FIELD: request_identifier
}
response = requests.get(INPUT_IMAGE_FETCHING_URI, data=payload)
if response.status_code != 200:
raise RuntimeError("Could not process request")
data = np.fromstring(response.content, dtype=np.uint8)
return cv.imdecode(data, cv.IMREAD_COLOR)
def register_results(
requester_login: str,
request_identifier: str,
results: dict
) -> None:
payload = {
LOGIN_FIELD: requester_login,
RESOURCE_IDENTIFIER_FIELD: request_identifier,
FACE_DETECTION_RESULTS_FIELD: json.dumps(results)
}
response = requests.post(RESULT_POSTING_URI, data=payload)
if response.status_code != 200:
raise RuntimeError("Could not send back results.")
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,850
|
PawelPeczek/ModelAsAServiceV2
|
refs/heads/master
|
/gateway_service/gateway_service/handlers/object_detection.py
|
from flask import Response
from ..config import OBJECT_DETECTION_URL
from .proxy import Proxy
class ObjectDetection(Proxy):
def post(self) -> Response:
return self._forward_message(target_url=OBJECT_DETECTION_URL)
|
{"/object_detection_service/object_detection_service/handlers/object_detection.py": ["/object_detection_service/object_detection_service/entities.py", "/object_detection_service/object_detection_service/utils.py"], "/resources_manager_service/resources_manager_service/handlers/input_image_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/app.py": ["/face_detection_service/face_detection_service/communication.py", "/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/app.py": ["/gateway_service/gateway_service/handlers/face_detection.py", "/gateway_service/gateway_service/handlers/object_detection.py", "/gateway_service/gateway_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py": ["/resources_manager_service/resources_manager_service/handlers/utils.py", "/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/gateway_service/gateway_service/handlers/face_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"], "/object_detection_service/object_detection_service/app.py": ["/object_detection_service/object_detection_service/handlers/object_detection.py"], "/resources_manager_service/resources_manager_service/app.py": ["/resources_manager_service/resources_manager_service/handlers/input_image_register.py", "/resources_manager_service/resources_manager_service/handlers/face_detection_register.py", "/resources_manager_service/resources_manager_service/config.py"], "/resources_manager_service/resources_manager_service/handlers/utils.py": ["/resources_manager_service/resources_manager_service/handlers/config.py", "/resources_manager_service/resources_manager_service/config.py"], "/face_detection_service/face_detection_service/communication.py": ["/face_detection_service/face_detection_service/config.py"], "/gateway_service/gateway_service/handlers/object_detection.py": ["/gateway_service/gateway_service/config.py", "/gateway_service/gateway_service/handlers/proxy.py"]}
|
6,865
|
Sandip123456789/selenium-end-to-end-automation-demo
|
refs/heads/master
|
/pageObjects/ConfirmPage.py
|
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from utilities.BaseClass import BaseClass
class ConfirmPage(BaseClass):
def __init__(self, driver):
self.driver = driver
def getCountryName(self):
#for logger
log = self.getLogger()
log.info("Entering country name as Ge")
self.driver.find_element_by_id("country").send_keys("Ge")
# Explicit wait from custom utilities, imported from BaseClass
self.verifyLinkPresence("Germany")
self.driver.find_element_by_link_text("Germany").click()
def getCheckBox(self):
return self.driver.find_element_by_xpath("//div[@class='checkbox checkbox-primary']")
# checkBox = self.driver.find_element_by_xpath("//div[@class='checkbox checkbox-primary']")
# checkBox.click()
# assert not checkBox.is_selected()
def getPurchaseBtn(self):
return self.driver.find_element_by_css_selector("input[type='submit']")
|
{"/pytests/test_homePage.py": ["/pageObjects/HomePage.py", "/TestData/HomePageData.py"], "/pytests/test_e2e.py": ["/pageObjects/HomePage.py", "/pageObjects/CheckoutPage.py", "/pageObjects/ConfirmPage.py"]}
|
6,866
|
Sandip123456789/selenium-end-to-end-automation-demo
|
refs/heads/master
|
/pageObjects/CheckoutPage.py
|
class CheckoutPage:
def __init__(self, driver):
self.driver = driver
def getCardTitle(self):
return self.driver.find_elements_by_xpath("//div[@class='card h-100']")
def getCheckoutList(self):
# To click on checkout button
return self.driver.find_element_by_css_selector("a[class*='btn-primary']")
def getQuantity(self):
# enter quantity no
return self.driver.find_element_by_id("exampleInputEmail1")
def getCheckOut(self):
#This is last checkout btn or success btn
return self.driver.find_element_by_css_selector("button[class*='btn-success']")
|
{"/pytests/test_homePage.py": ["/pageObjects/HomePage.py", "/TestData/HomePageData.py"], "/pytests/test_e2e.py": ["/pageObjects/HomePage.py", "/pageObjects/CheckoutPage.py", "/pageObjects/ConfirmPage.py"]}
|
6,867
|
Sandip123456789/selenium-end-to-end-automation-demo
|
refs/heads/master
|
/pytests/test_homePage.py
|
import pytest
from selenium import webdriver
from selenium.webdriver.support.select import Select
from utilities.BaseClass import BaseClass
from pageObjects.HomePage import HomePage
from TestData.HomePageData import HomePageData
class TestHomePage(BaseClass):
def test_homePage(self, getData):
driver = self.driver
#for logger
log = self.getLogger()
driver.implicitly_wait(10)
#object of class HomePage
homePage = HomePage(driver)
log.info("Entered name is "+getData["Name"]+" and Email is "+getData["Email"])
homePage.getName().send_keys(getData["Name"])
homePage.getEmail().send_keys(getData["Email"])
homePage.getPassword().send_keys(getData["Password"])
homePage.getCheckbox().click()
# homePage.getGender() #imported from HomePage
# imported from BaseClass, for reusable purpose
self.selectDropdownByText(homePage.getGender(), getData["Gender"])
homePage.getRadioBtnStudent().click()
homePage.getDOB().send_keys(getData["DOB"])
homePage.getSubmitBtn().click()
# validating and printing success message
message = driver.find_element_by_class_name('alert-success').text
print(message)
log.info(message)
assert "Success!" in message
#refresh before second test inputs
self.driver.refresh()
#Using another file to store data, imported from TestData.HomePageData
@pytest.fixture(params=HomePageData.test_homePage_data)
def getData(self, request):
return request.param
# we can also use dictionary inside list of params
# @pytest.fixture(params=[("Killerbee", "killer@gmail.com", "killer99", "04/11/2000"),
# ("Rusty", "rustyboi@gmail.com", "rusty99", "05/12/2001")
# ])
# def getData(self, request):
# return request.param
|
{"/pytests/test_homePage.py": ["/pageObjects/HomePage.py", "/TestData/HomePageData.py"], "/pytests/test_e2e.py": ["/pageObjects/HomePage.py", "/pageObjects/CheckoutPage.py", "/pageObjects/ConfirmPage.py"]}
|
6,868
|
Sandip123456789/selenium-end-to-end-automation-demo
|
refs/heads/master
|
/end2endAutomation/end2endTest.py
|
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--ignore-certificate-errors")
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
driver.get('https://rahulshettyacademy.com/angularpractice/')
#Clicking without using selenium .click() method
shopBtn = driver.find_element_by_link_text("Shop")
driver.execute_script("arguments[0].click();",shopBtn)
#to scroll down top to bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
#Steps to Click on Add to cart button
# driver.find_element_by_xpath("//body/app-root[1]/app-shop[1]/div[1]/div[1]/div[2]/app-card-list[1]/app-card[1]/div[1]/div[2]/button[1]").click()
products = driver.find_elements_by_xpath("//div[@class='card h-100']")
# //div[@class='card h-100']/div/h4/a
# //div[@class='card h-100']/div[2]/button
# //div[@class='card h-100']/div/button
for product in products:
productName = product.find_element_by_xpath("div/h4/a").text
print(productName)
if productName == "iphone X":
#Add item into cart
product.find_element_by_xpath("div[2]/button").click()
#to scroll down bottom to top
driver.execute_script("window.scrollTo(document.body.scrollHeight, 0)")
#To click on checkout button
driver.find_element_by_css_selector("a[class*='btn-primary']").click()
#enter quantity no
driver.find_element_by_id("exampleInputEmail1").clear()
driver.find_element_by_id("exampleInputEmail1").send_keys("2")
driver.find_element_by_css_selector("button[class*='btn-success']").click()
driver.find_element_by_id("country").send_keys("Ge")
#Explicit wait
wait = WebDriverWait(driver, 8)
wait.until(expected_conditions.presence_of_element_located((By.LINK_TEXT, "Germany")))
# wait.until(expected_conditions.presence_of_element_located((By.XPATH, "//div[@class='suggestions']/ul/li/a")))
driver.find_element_by_link_text("Germany").click()
checkBox = driver.find_element_by_xpath("//div[@class='checkbox checkbox-primary']")
checkBox.click()
assert not checkBox.is_selected()
driver.find_element_by_css_selector("input[type='submit']").click()
successText = driver.find_element_by_class_name("alert-success").text
assert "Success!" in successText
print(successText)
#Taking screenshot
driver.get_screenshot_as_file("../Screenshots/successScreen.png")
time.sleep(4)
driver.close()
driver.quit()
|
{"/pytests/test_homePage.py": ["/pageObjects/HomePage.py", "/TestData/HomePageData.py"], "/pytests/test_e2e.py": ["/pageObjects/HomePage.py", "/pageObjects/CheckoutPage.py", "/pageObjects/ConfirmPage.py"]}
|
6,869
|
Sandip123456789/selenium-end-to-end-automation-demo
|
refs/heads/master
|
/TestData/HomePageData.py
|
class HomePageData:
test_homePage_data = [
{"Name":"Killerbee", "Email":"killer@gmail.com", "Password":"killer99", "Gender":"Female", "DOB":"04/11/2000"},
{"Name":"Rusty", "Email":"rustyboi@gmail.com", "Password":"rusty99", "Gender":"Male", "DOB":"05/12/2001"}
]
|
{"/pytests/test_homePage.py": ["/pageObjects/HomePage.py", "/TestData/HomePageData.py"], "/pytests/test_e2e.py": ["/pageObjects/HomePage.py", "/pageObjects/CheckoutPage.py", "/pageObjects/ConfirmPage.py"]}
|
6,870
|
Sandip123456789/selenium-end-to-end-automation-demo
|
refs/heads/master
|
/pageObjects/HomePage.py
|
import pytest
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.by import By
from utilities.BaseClass import BaseClass
class HomePage:
def __init__(self, driver):
self.driver = driver
#creating tuples
name = (By.NAME, "name")
email = (By.NAME, "email")
password = (By.ID, "exampleInputPassword1")
checkbox = (By.ID, "exampleCheck1")
gender = (By.ID, "exampleFormControlSelect1")
radioBtn = (By.ID, "inlineRadio1")
dob = (By.NAME, "bday")
submit = (By.XPATH, "//input[@type='submit']")
def getShopBtn(self):
# Clicking without using selenium .click() method
shop = self.driver.find_element_by_link_text("Shop")
# shop.click()
self.driver.execute_script("arguments[0].click();", shop)
def getName(self):
return self.driver.find_element(*HomePage.name) # put * to say it is tuple
# self.driver.find_element_by_name('name').send_keys("Killerbee")
def getEmail(self):
return self.driver.find_element(*HomePage.email)
def getPassword(self):
return self.driver.find_element(*HomePage.password)
def getCheckbox(self):
return self.driver.find_element(*HomePage.checkbox)
def getGender(self):
#select class provide the methods to handle the options in dropdown (static)
return self.driver.find_element(*HomePage.gender)
def getRadioBtnStudent(self):
return self.driver.find_element(*HomePage.radioBtn)
def getDOB(self):
return self.driver.find_element(*HomePage.dob)
def getSubmitBtn(self):
return self.driver.find_element(*HomePage.submit)
|
{"/pytests/test_homePage.py": ["/pageObjects/HomePage.py", "/TestData/HomePageData.py"], "/pytests/test_e2e.py": ["/pageObjects/HomePage.py", "/pageObjects/CheckoutPage.py", "/pageObjects/ConfirmPage.py"]}
|
6,871
|
Sandip123456789/selenium-end-to-end-automation-demo
|
refs/heads/master
|
/pytests/conftest.py
|
from selenium import webdriver
import pytest
import time
driver = None
@pytest.fixture(scope="class")
def setup(request):
global driver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--ignore-certificate-errors")
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
driver.get('https://rahulshettyacademy.com/angularpractice/')
request.cls.driver = driver
yield
time.sleep(4)
driver.close()
driver.quit()
#Logic to Take Screenshot only when there is failure
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
"""
Extends the PyTest Plugin to take and embed screenshot in html report, whenever test fails.
:param item:
"""
pytest_html = item.config.pluginmanager.getplugin('html')
outcome = yield
report = outcome.get_result()
extra = getattr(report, 'extra', [])
if report.when == 'call' or report.when == "setup":
xfail = hasattr(report, 'wasxfail')
if (report.skipped and xfail) or (report.failed and not xfail):
file_name = report.nodeid.replace("::", "_") + ".png"
_capture_screenshot(file_name)
if file_name:
html = '<div><img src="%s" alt="screenshot" style="width:304px;height:228px;" ' \
'onclick="window.open(this.src)" align="right"/></div>' % file_name
extra.append(pytest_html.extras.html(html))
report.extra = extra
def _capture_screenshot(name):
driver.get_screenshot_as_file(name)
|
{"/pytests/test_homePage.py": ["/pageObjects/HomePage.py", "/TestData/HomePageData.py"], "/pytests/test_e2e.py": ["/pageObjects/HomePage.py", "/pageObjects/CheckoutPage.py", "/pageObjects/ConfirmPage.py"]}
|
6,872
|
Sandip123456789/selenium-end-to-end-automation-demo
|
refs/heads/master
|
/pytests/test_e2e.py
|
import pytest
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from pageObjects.HomePage import HomePage
from pageObjects.CheckoutPage import CheckoutPage
from pageObjects.ConfirmPage import ConfirmPage
from utilities.BaseClass import BaseClass
# @pytest.mark.usefixtures("setup")
class TestOne(BaseClass):
def test_e2e(self):
driver = self.driver
#for logger
log = self.getLogger()
#Creating Objects of from Classes
homePage = HomePage(driver)
checkoutPage = CheckoutPage(driver)
confirmPage = ConfirmPage(driver)
#click shop, imported from HomePage
homePage.getShopBtn()
# to scroll down top to bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
#click add item button, imported from CheckoutPage
# Steps to Click on Add to cart button
log.info("Getting all the product titles")
products = checkoutPage.getCardTitle()
for product in products:
productName = product.find_element_by_xpath("div/h4/a").text
print(productName)
log.info(productName)
if productName == "iphone X":
# Add item into cart
product.find_element_by_xpath("div[2]/button").click()
# to scroll down bottom to top
driver.execute_script("window.scrollTo(document.body.scrollHeight, 0)")
# To click on checkout button, imported from CheckoutPage
checkoutPage.getCheckoutList().click()
# enter quantity no
checkoutPage.getQuantity().clear()
checkoutPage.getQuantity().send_keys("2")
checkoutPage.getCheckOut().click()
#enter country name
confirmPage.getCountryName()
#Click checkBox, imported from ConfirmPage
checkbox = confirmPage.getCheckBox()
checkbox.click()
assert not checkbox.is_selected()
#Click purchase button, imported from ConfirmPage
confirmPage.getPurchaseBtn().click()
#validating success message
successText = driver.find_element_by_class_name("alert-success").text
assert "Success!" in successText
print(successText)
log.info("Received success text is "+successText)
# Taking screenshot
# driver.get_screenshot_as_file("../Screenshots/successScreen.png")
|
{"/pytests/test_homePage.py": ["/pageObjects/HomePage.py", "/TestData/HomePageData.py"], "/pytests/test_e2e.py": ["/pageObjects/HomePage.py", "/pageObjects/CheckoutPage.py", "/pageObjects/ConfirmPage.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.