index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
33,987
AlenaDos/openeo-python-client
refs/heads/master
/openeo/__init__.py
""" Python Client API for OpenEO backends. This client is a lightweight implementation with limited dependencies on other modules. The aim of OpenEO is to process remote sensing data on dedicated processing resources close to the source data. This client allows users to communicate with OpenEO backends, in a way that feels familiar for Python programmers. .. literalinclude:: ../examples/download_composite.py :caption: Basic example :name: basic_example """ __title__ = 'openeo' __version__ = '0.0.3' __author__ = 'Jeroen Dries' from .catalog import EOProduct from .imagecollection import ImageCollection from .rest.rest_session import session from .job import Job from .auth.auth import Auth from .process.process import *
{"/tests/test_usecase1.py": ["/openeo/__init__.py"], "/tests/test_rest_session.py": ["/openeo/__init__.py"], "/openeo/rest/job.py": ["/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/rest/rest_session.py": ["/openeo/sessions.py"], "/openeo/imagecollection.py": ["/openeo/job.py"], "/examples/gee_example.py": ["/openeo/__init__.py"], "/openeo/__init__.py": ["/openeo/imagecollection.py", "/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/sessions.py": ["/openeo/imagecollection.py"]}
33,988
AlenaDos/openeo-python-client
refs/heads/master
/openeo/sessions.py
from abc import ABC, abstractmethod from .auth import Auth from .imagecollection import ImageCollection """ openeo.sessions ~~~~~~~~~~~~~~~~ This module provides a Session object to manage and persist settings when interacting with the OpenEO API. """ class Session(ABC): """ A `Session` class represents a connection with an OpenEO service. It is your entry point to create new Image Collections. """ @property @abstractmethod def auth(self, username, password, auth:Auth) -> bool: """ Authenticates a user to the backend using auth class. :param username: String Username credential of the user :param password: String Password credential of the user :param auth_class: Auth instance of the abstract Auth class :return: token: String Bearer token """ pass @abstractmethod def list_capabilities(self) -> dict: """ Loads all available capabilities. :return: data_dict: Dict All available data types """ @abstractmethod def list_collections(self) -> dict: """ Retrieve all products available in the backend. :return: a dict containing product information. The 'product_id' corresponds to an image collection id. """ pass @abstractmethod def get_collection(self, col_id) -> dict: # TODO: Maybe create some kind of Data class. """ Loads detailed information of a specific image collection. :param col_id: String Id of the collection :return: data_dict: Dict Detailed information about the collection """ @abstractmethod def get_all_processes(self) -> dict: # TODO: Maybe format the result dictionary so that the process_id is the key of the dictionary. """ Loads all available processes of the back end. :return: processes_dict: Dict All available processes of the back end. """ @abstractmethod def get_process(self, process_id) -> dict: # TODO: Maybe create some kind of Process class. """ Get detailed information about a specifig process. :param process_id: String Process identifier :return: processes_dict: Dict with the detail information about the process """ @abstractmethod def create_job(self, post_data, evaluation="lazy") -> str: # TODO: Create a Job class or something for the creation of a nested process execution... """ Posts a job to the back end including the evaluation information. :param post_data: String data of the job (e.g. process graph) :param evaluation: String Option for the evaluation of the job :return: job_id: String Job id of the new created job """ @abstractmethod def imagecollection(self, image_collection_id:str) -> ImageCollection: """ Retrieves an Image Collection object based on the id of a given layer. A list of available collections can be retrieved with :meth:`openeo.sessions.Session.list_collections`. :param image_collection_id: The id of the image collection to retrieve. :rtype: openeo.imagecollection.ImageCollection """ pass @abstractmethod def image(self, image_product_id) -> 'ImageCollection': """ Get imagery by id. :param image_collection_id: String image collection identifier :return: collection: RestImagery the imagery with the id """ @abstractmethod def user_jobs(self) -> dict: #TODO: Create a kind of User class to abstract the information (e.g. userid, username, password from the session. """ Loads all jobs of the current user. :return: jobs: Dict All jobs of the user """ @abstractmethod def user_download_file(self, file_path, output_file): """ Downloads a user file to the back end. :param file_path: remote path to the file that should be downloaded. :param output_file: local path, where the file should be saved. :return: status: True if it was successful, False otherwise """ @abstractmethod def user_upload_file(self, file_path, remote_path=None): """ Uploads a user file to the back end. :param file_path: Local path to the file that should be uploaded. :param remote_path: Remote path of the file where it should be uploaded. :return: status: True if it was successful, False otherwise """ @abstractmethod def user_list_files(self): """ Lists all files that the logged in user uploaded. :return: file_list: List of the user uploaded files. """ @abstractmethod def download(self, graph, time, outputfile, format_options): """ Downloads a result of a process graph synchronously. :param graph: Dict representing a process graph :param time: dba :param outputfile: output file :param format_options: formating options :return: job_id: String """ @abstractmethod def get_outputformats(self) -> dict: """ Loads all available output formats. :return: data_dict: Dict All available output formats """ pass
{"/tests/test_usecase1.py": ["/openeo/__init__.py"], "/tests/test_rest_session.py": ["/openeo/__init__.py"], "/openeo/rest/job.py": ["/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/rest/rest_session.py": ["/openeo/sessions.py"], "/openeo/imagecollection.py": ["/openeo/job.py"], "/examples/gee_example.py": ["/openeo/__init__.py"], "/openeo/__init__.py": ["/openeo/imagecollection.py", "/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/sessions.py": ["/openeo/imagecollection.py"]}
33,990
tienqpham/final-super-dodgeball-64
refs/heads/master
/manualtest_control_select.py
import pygame import constants from art import * from control_select import * SCREEN_WIDTH = 400 SCREEN_HEIGHT = 900 WHITE = (255,255,255) BLACK = (0,0,0) pygame.init() screen = pygame.display.set_mode([constants.SCREEN_WIDTH,constants.SCREEN_HEIGHT]) art = Art() clock = pygame.time.Clock() done = False my_selector = ControlSelect(1) while not done: clock.tick(60) screen.fill(WHITE) for event in pygame.event.get(): my_selector.handle_event(event) if event.type == pygame.QUIT: done = True break if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: done = True break elif event.key == pygame.K_SPACE: if my_selector.get_player1_control() < -1: print("no player 1 peripheral selected") if my_selector.get_player1_control() == -1: print("player 1 uses keyboard") if my_selector.get_player1_control() == 0: print("player 1 uses joystick 0") if my_selector.get_player1_control() == 1: print("player 1 uses joystick 1") if my_selector.get_player2_control() < -1: print("no player 2 peripheral selected") if my_selector.get_player2_control() == -1: print("player 2 uses keyboard") if my_selector.get_player2_control() == 0: print("player 2 uses joystick 0") if my_selector.get_player2_control() == 1: print("player 2 uses joystick 1") if my_selector.is_everyone_ready(): print("READY!") else: print("NOT READY!") elif event.type == pygame.JOYBUTTONDOWN: for i in range(0, pygame.joystick.get_count()): if pygame.joystick.Joystick(i).get_button(0): if my_selector.get_player1_control() < -1: print("no player 1 peripheral selected") if my_selector.get_player1_control() == -1: print("player 1 uses keyboard") if my_selector.get_player1_control() == 0: print("player 1 uses joystick 0") if my_selector.get_player1_control() == 1: print("player 1 uses joystick 1") if my_selector.get_player2_control() < -1: print("no player 2 peripheral selected") if my_selector.get_player2_control() == -1: print("player 2 uses keyboard") if my_selector.get_player2_control() == 0: print("player 2 uses joystick 0") if my_selector.get_player2_control() == 1: print("player 2 uses joystick 1") if my_selector.is_everyone_ready(): print("READY!") else: print("NOT READY!") print('') print('') my_selector.draw(screen) pygame.display.flip() pygame.quit()
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
33,991
tienqpham/final-super-dodgeball-64
refs/heads/master
/music.py
import pygame from file import * class Music(): class __Music(): def __init__(self): # needs songs self.songlist = {"title_music": File().load("titlemusic"), "new_title_music": File().load("newtitlemusic"), "game_music": File().load("gamemusic")} self.isPaused = False def play_once(self, id): pygame.mixer.music.load(self.songlist.get(id)) pygame.mixer.music.play() self.isPaused = False def play_repeat(self, id): file_location = self.songlist.get(id) print(file_location) pygame.mixer.music.load(self.songlist.get(id)) pygame.mixer.music.set_volume(0.15) pygame.mixer.music.play(-1) self.isPaused = False def stop(self): pygame.mixer.music.stop() def toggle_pause(self): if self.isPaused == False: pygame.mixer.music.pause() self.isPaused = True else: pygame.mixer.music.unpause() self.isPaused = False instance = None def __init__(self): if not Music.instance: Music.instance = Music.__Music() def __getattr__(self, name): return getattr(self.instance, name)
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
33,992
tienqpham/final-super-dodgeball-64
refs/heads/master
/test/test_keyboard_player.py
import unittest import sys sys.path.append('..') import constants from keyboard_player import * from art import * pygame.init() pygame.display.init() screen = pygame.display.set_mode([ constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT ]) class test_KeyboardPlayer(unittest.TestCase): def test_init(self): player1 = KeyboardPlayer(1) self.assertTrue(True) if __name__ == '__main__': unittest.main()
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
33,993
tienqpham/final-super-dodgeball-64
refs/heads/master
/soccer_goal.py
import pygame import constants from art import * from actor import * class SoccerGoal(Actor): def __init__(self, goalNumber): self.imgg = Art().get_image('tempGoal') if goalNumber == 1: spawn_place = [0, constants.SCREEN_HEIGHT/2] elif goalNumber == 2: spawn_place = [constants.SCREEN_HEIGHT * 3 / 4, constants.SCREEN_HEIGHT/2] else: raise ValueError('invaid player number') self.goalNumber = goalNumber super().__init__(self.imgg, spawn_place[0], spawn_place[1]) def get_goal_number(self): return self.goalNumber
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
33,994
tienqpham/final-super-dodgeball-64
refs/heads/master
/soccer_screen.py
import pygame import random import math import constants from level_manager import * from art import * from music import * from sound import * from keyboard_player import * from joystick_player import * from reticle import * from ball import * from game_screen import* from math import * class SoccerScreen(GameScreen): def __init__(self, player1_control=-1, player2_control=0): super().__init__(player1_control=-1, player2_control=0) self.soccerBall = NeutralBall(800, 800, 0, 0, 1) self.speed = 10 self.hitScale = 1.5 self.soccerBalls = pygame.sprite.Group() self.soccerBalls.add(soccerBall) self.goals1 = pygame.sprite.Group() goals1.add(SoccerGoal().__init__(1)) self.goals2 = pygame.sprite.Group() goals2.add(SoccerGoal().__init__(2)) #should be updated along with game_screen def handle_keyboard_event(self, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.joystick.quit() pygame.joystick.init() for i in range(pygame.joystick.get_count()): pygame.joystick.Joystick(i).init() Music().stop() Music().play_repeat("title_music") LevelManager().leave_level() elif event.key == pygame.K_SPACE and not self.game_over: self.toggle_pause() elif event.type == pygame.JOYBUTTONDOWN: if self.player2.get_joystick().get_button(7) and not self.game_over: self.toggle_pause() #elif self.player2.get_joystick().get_button(5) or self.player2.get_joystick().get_button(4): #if not self.game_over and not self.paused: #self.shoot(2) #print("player 2 shoots") #elif event.type == pygame.MOUSEBUTTONDOWN: #if not self.game_over and not self.paused: #self.shoot(1) #print("player 1 shoots") #if not self.paused: self.player1.handle_control_event(event) def update(self) : self.check_collisions() def check_collisions(self): self.check_player1() self.check_player2() self.check_goal1() self.check_goal2() def check_player1(self): if not self.game_over: ball_hits = pygame.sprite.spritecollide(self.player1, self.soccerBalls, True) if len(ball_hits) > 0: shoot(1) def check_player2(self): if not self.game_over: ball_hits = pygame.sprite.spritecollide(self.player1, self.soccerBalls, True) if len(ball_hits) > 0: shoot(2) def check_goal1(self): if not self.game_over: goalHits = pygame.sprite.spritecollide(self.goals1, self.soccer_balls, True) self.game_over = True self.player2_wins = True self.all_sprites.remove(self.player1) self.players.remove(self.player1) self.reticles.remove(self.reticle1) self.reticles.remove(self.reticle2) def check_goal2(self): if not self.game_over: goalHits = pygame.sprite.spritecollide(self.goals2, self.soccer_balls, True) self.game_over = True self.player1_wins = True self.all_sprites.remove(self.player2) self.players.remove(self.player2) self.reticles.remove(self.reticle1) self.reticles.remove(self.reticle2) def shoot(self, player_number): if player_number == 1: d = [0,0] d[0] = self.reticle1.get_center()[0] - self.player1.get_center()[0] d[1] = self.reticle1.get_center()[1] - self.player1.get_center()[1] hypo = math.sqrt( math.pow(d[0],2) + math.pow(d[1],2) ) speed = [ d[0]/hypo * constants.SHOT_SPEED, d[1]/hypo * constants.SHOT_SPEED] soccerBall.speed_x += speed[0] * hitScale soccerBall.x += soccerBall.speed_x soccerBall.y += soccerBall.speed_y Sound().play_sound("player_shooting") elif player_number == 2: d = [0,0] d[0] = self.reticle2.get_center()[0] - self.player2.get_center()[0] d[1] = self.reticle2.get_center()[1] - self.player2.get_center()[1] hypo = math.sqrt( math.pow(d[0],2) + math.pow(d[1],2) ) speed = [ d[0]/hypo * constants.SHOT_SPEED, d[1]/hypo * constants.SHOT_SPEED] soccerBall.speed_x += speed[0] * hitScale soccerBall.x += soccerBall.speed_x soccerBall.y += soccerBall.speed_y Sound().play_sound("player_shooting")
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
33,995
tienqpham/final-super-dodgeball-64
refs/heads/master
/control_select.py
import pygame import constants from level_manager import * from art import * class ControlSelect(): def __init__(self, player_count=2): self.keyboard_img = Art().get_image("keyboard_select") self.gamepad_img = Art().get_image("gamepad_select") self.ready1_on = Art().get_image("ready1_on") self.ready1_off = Art().get_image("ready1_off") self.ready2_on = Art().get_image("ready2_on") self.ready2_off = Art().get_image("ready2_off") self.keyboard_height = self.keyboard_img.get_rect().size[1] self.gamepad_height = self.gamepad_img.get_rect().size[1] self.gap_y = 30 self.player_count = player_count self.player1_fill = False self.player2_fill = False self.player1_ready = False self.player2_ready = False self.player1_control = -2 self.player2_control = -2 self.joystick_count = pygame.joystick.get_count() self.total_count = self.joystick_count + 1 self.joysticks = [] self.is_joystick_in_use = [] for i in range(0, self.joystick_count): self.is_joystick_in_use.append(False) self.joysticks.append(pygame.joystick.Joystick(i)) self.joysticks[i].init() self.is_keyboard_in_use = False # returns True if all player(s) are ready # returns False if any player is not ready def is_everyone_ready(self): if self.player_count == 1: return self.player1_ready elif self.player_count == 2: return self.player1_ready and self.player2_ready def is_anyone_ready(self): return self.player1_ready or self.player2_ready # returns the ID of player1's assigned joystick # returns -1 if player1 is assigned keyboard def get_player1_control(self): return self.player1_control # returns the ID of player2's assigned joystick # returns -1 if player2 is assigned keyboard def get_player2_control(self): return self.player2_control # resets menu to initial state def reset(self): self.player1_fill = False self.player2_fill = False self.player1_ready = False self.player2_ready = False self.player1_control = -2 self.player2_control = -2 self.is_keyboard_in_use = False for i in range(0, self.joystick_count): self.is_joystick_in_use[i] = False def update(self): pass def draw(self, screen): self.draw_controllers(screen) self.draw_players(screen) def draw_controllers(self, screen): if not self.is_keyboard_in_use: # blit keyboard sprite centered at screen_width/2, gap_y + imgHeight/2 rect = self.keyboard_img.get_rect(center=[constants.SCREEN_WIDTH/2, self.keyboard_height/2 + self.gap_y]) screen.blit(self.keyboard_img, rect) for i in range(0, self.joystick_count): if not self.is_joystick_in_use[i]: # blit gamepad sprite centered at # screen_width/2, gap_y*(i+2) + joystick_sprite_height*i + keyboard_sprite_height rect = self.gamepad_img.get_rect(center=[constants.SCREEN_WIDTH/2,0]) rect.y = self.gap_y*(i+2) + self.gamepad_height*i + self.keyboard_height screen.blit(self.gamepad_img, rect) def draw_players(self, screen): if not self.player1_ready: # blit ready_red_off centered at constants.SCREEN_WIDTH/4, constants.SCREEN_HEIGHT/2 + gamepad_height rect = self.ready1_off.get_rect(center=[constants.SCREEN_WIDTH/4, constants.SCREEN_HEIGHT/2 + self.gamepad_height]) screen.blit(self.ready1_off, rect) if self.player_count ==2 and \ not self.player2_ready: # blit ready_bleu_off centered at constants.SCREEN_WIDTH*3/4, constants.SCREEN_HEIGHT/2 + gamepad_height rect = self.ready2_off.get_rect(center=[constants.SCREEN_WIDTH*3/4, constants.SCREEN_HEIGHT/2 + self.gamepad_height]) screen.blit(self.ready2_off, rect) if self.player1_fill: if self.player1_control == -1: # blit keyboard sprite centered at # screen_width/4, screen_height/2 rect = self.keyboard_img.get_rect(center=[constants.SCREEN_WIDTH/4, constants.SCREEN_HEIGHT/2]) screen.blit(self.keyboard_img, rect) elif self.player1_control >= 0: # blit gamepad sprite centered at # screen_width/4, screen_height/2 rect = self.gamepad_img.get_rect(center=[constants.SCREEN_WIDTH/4, constants.SCREEN_HEIGHT/2]) screen.blit(self.gamepad_img, rect) if self.player1_ready: #blit ready_red_on centered at constants.SCREEN_WIDTH/4, constants.SCREEN_HEIGHT/2 + gamepad_height rect = self.ready1_on.get_rect(center=[constants.SCREEN_WIDTH/4, constants.SCREEN_HEIGHT/2 + self.gamepad_height]) screen.blit(self.ready1_on, rect) if self.player2_fill: if self.player2_control == -1: # blit keyboard sprite centered # at screen_width*3/4, screen_height/2 rect = self.keyboard_img.get_rect(center=[constants.SCREEN_WIDTH*3/4, constants.SCREEN_HEIGHT/2]) screen.blit(self.keyboard_img, rect) elif self.player2_control >= 0: # blit gamepad sprite centered at # screen_width*3/4, screen_height/2 rect = self.gamepad_img.get_rect(center=[constants.SCREEN_WIDTH*3/4, constants.SCREEN_HEIGHT/2]) screen.blit(self.gamepad_img, rect) if self.player2_ready: #blit ready_blue_on centered at constants.SCREEN_WIDTH*3/4, constants.SCREEN_HEIGHT/2 + gamepad_height rect = self.ready2_on.get_rect(center=[constants.SCREEN_WIDTH*3/4, constants.SCREEN_HEIGHT/2 + self.gamepad_height]) screen.blit(self.ready2_on, rect) def handle_event(self, event): # keypress if event.type == pygame.KEYDOWN: self.handle_keydown(event) # joybutton press if event.type == pygame.JOYBUTTONDOWN: self.handle_joybuttondown(event) # joyhat press if event.type == pygame.JOYHATMOTION: self.handle_joyhatmotion(event) def handle_joyhatmotion(self,event): for i in range(0,self.joystick_count): # left hat press if self.joysticks[i].get_hat(0)[0] == -1: # player 1 assigns controller if not self.is_joystick_in_use[i] and not self.player1_fill and self.player1_control == -2: self.is_joystick_in_use[i] = True self.player1_fill = True self.player1_control = self.joysticks[i].get_id() print("player 1 selected joystick " + str(self.joysticks[i].get_id())) print('') # player 2 unassigns controller elif self.is_joystick_in_use[i] and self.player2_fill and self.player2_control == self.joysticks[i].get_id() and not self.player2_ready: self.is_joystick_in_use[i] = False self.player2_fill = False self.player2_control = -2 print("player 2 unselected joystick " + str(self.joysticks[i].get_id())) print('') # right hat press elif self.joysticks[i].get_hat(0)[0] == 1: # player 2 assigns controller if self.player_count ==2 and not self.is_joystick_in_use[i] and \ not self.player2_fill and self.player2_control == -2: self.is_joystick_in_use[i] = True self.player2_fill = True self.player2_control = self.joysticks[i].get_id() print("player 2 selected joystick " + str(self.joysticks[i].get_id())) print('') # player 1 unassigns controller elif self.is_joystick_in_use[i] and self.player1_fill and self.player1_control == self.joysticks[i].get_id() and not self.player1_ready: self.is_joystick_in_use[i] = False self.player1_fill = False self.player1_control = -2 print("player 1 unselected joystick " + str(self.joysticks[i].get_id())) print('') def handle_joybuttondown(self,event): for i in range(0,self.joystick_count): # X/A button press if self.joysticks[i].get_button(0): if self.player1_control == i: if self.player1_fill: self.player1_ready = True elif self.player2_control == i: if self.player2_fill: self.player2_ready = True # Circle/B button press elif self.joysticks[i].get_button(1): if self.player1_control == i: if self.player1_ready: self.player1_ready = False elif self.player2_control == i: if self.player2_ready: self.player2_ready = False def handle_keydown(self,event): # left keypress if event.key == pygame.K_a or event.key == pygame.K_LEFT: # player 1 assigns keyboard if not self.player1_fill and self.player1_control == -2 and not self.is_keyboard_in_use: self.player1_fill = True self.player1_control = -1 self.is_keyboard_in_use = True print("player 1 selected keyboard") print('') # player 2 unassigns keyboard elif self.player2_fill and self.player2_control == -1 and self.is_keyboard_in_use and not self.player2_ready: self.player2_fill = False self.player2_control = -2 self.is_keyboard_in_use = False print("player 2 unselected keyboard") print('') # right keypress elif event.key == pygame.K_d or event.key == pygame.K_RIGHT: # player 2 assigns keyboard if self.player_count ==2 and not self.player2_fill and \ self.player2_control == -2 and not self.is_keyboard_in_use: self.player2_fill = True self.player2_control = -1 self.is_keyboard_in_use = True print("player 2 selected keyboard") print('') # player 1 unassigns keyboard elif self.player1_fill and self.player1_control == -1 and self.is_keyboard_in_use and not self.player1_ready: self.player1_fill = False self.player1_control = -2 self.is_keyboard_in_use = False print("player 1 unselected keyboard") print('') # spacebar press elif event.key == pygame.K_SPACE: if self.player1_control == -1: if self.player1_fill: self.player1_ready = True elif self.player2_control == -1: if self.player2_fill: self.player2_ready = True # escape/tab/backspace press elif event.key == pygame.K_ESCAPE or \ event.key == pygame.K_TAB or \ event.key == pygame.K_BACKSPACE: if self.player1_control == -1: if self.player1_ready: self.player1_ready = False elif self.player2_control == -1: if self.player2_ready: self.player2_ready = False
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
33,996
tienqpham/final-super-dodgeball-64
refs/heads/master
/player.py
import pygame import constants from art import * from actor import * class Player(Actor): def __init__(self, playerNumber, hit_points = 5): self.hitpoint = hit_points self.control_index = -2 left_bound = 0 right_bound = constants.SCREEN_WIDTH/2 spawn_place = [0,0] if playerNumber == 1: self.imgg = Art().get_image('player1') left_bound = 0 right_bound = constants.SCREEN_WIDTH/2 spawn_place = [ constants.SCREEN_WIDTH/4, constants.SCREEN_HEIGHT/2 ] elif playerNumber == 2: self.imgg = Art().get_image('player2') left_bound = constants.SCREEN_WIDTH/2 right_bound = constants.SCREEN_WIDTH spawn_place = [ ( constants.SCREEN_WIDTH/4 ) * 3, constants.SCREEN_HEIGHT/2 ] else: raise ValueError('invalid player number') self.playerNumber = playerNumber super().__init__(self.imgg, spawn_place[0], spawn_place[1]) self.left_bound = left_bound self.right_bound = right_bound def get_player_number(self): return self.playerNumber def get_control(self): return self.control_index def damage(self, amount = 1): if amount <= 0: pygame.error("can not take negative damage") self.hitpoint -= amount def get_hit_points(self): return self.hitpoint # does nothing unless overridden def handle_event(self, event): pass
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
33,997
tienqpham/final-super-dodgeball-64
refs/heads/master
/shield.py
import pygame import constants import sys sys.path.append('..') from art import * from actor import * class Shield(Actor): def __init__(self,x,y,playerNumber): img = Art().get_image('shield1') if playerNumber == 2: img = Art().get_image('shield2') if playerNumber != 1 and playerNumber != 2: raise ValueError("Invalid player number for shield") super().__init__(img,x,y) def update(self): self.rect.x += self.speed_x self.rect.y += self.speed_y self.check_out_of_bounds() # shield can pass halfway off screen in either direction # shield center cannot pass off screen def check_out_of_bounds(self): # x # left edge if self.get_center()[0] < 0: self.stop_x() self.rect.x = 0 - (self.rect.size[0]/2) # right edge if self.get_center()[0] > constants.SCREEN_WIDTH: self.stop_x() self.rect.x = constants.SCREEN_WIDTH - (self.rect.size[0]/2) # y # top edge if self.get_center()[1] < 0: self.stop_y() self.rect.y = 0 - (self.rect.size[1]/2) # bottom edge if self.get_center()[1] > constants.SCREEN_HEIGHT: self.stop_y() self.rect.y = constants.SCREEN_HEIGHT - (self.rect.size[1]/2)
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
33,998
tienqpham/final-super-dodgeball-64
refs/heads/master
/gameover_screen.py
import pygame import constants from level_manager import * from art import * pygame.init() class GameoverScreen(): def __init__(self): font = pygame.font.SysFont('Calibri', 60, True, False) self.gameover = font.render("Gameover",True,constants.RED) def handle_keyboard_event(self, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: Music().stop() Music().play_repeat("title_music") LevelManager().load_level(TitleScreen()) def update(self): pass def draw(self, screen): screen.fill(constants.WHITE) screen.blit(self.gameover, [(constants.SCREEN_WIDTH/2 - self.gameover.get_width()/2), constants.SCREEN_HEIGHT/2])
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
33,999
tienqpham/final-super-dodgeball-64
refs/heads/master
/credit_screen.py
import pygame import constants from level_manager import * from art import * pygame.init() class CreditsScreen(): def __init__(self): self.joysticks = [] for i in range(0,pygame.joystick.get_count()): pygame.joystick.Joystick(i).init() self.joysticks.append(pygame.joystick.Joystick(i)) font = pygame.font.SysFont('Calibri', 40, True, False) font2 = pygame.font.SysFont('Calibri', 30, True, False) self.background_image = Art().get_image("basketBallCourt_dark") Credits = font.render("Credits:",True,constants.WHITE) programming = font2.render("Programming: Harrison Malloy, Tien Pham, Austin Tauer, Nicholas Riebel",True,constants.WHITE) art = font2.render("Art: Harrison Malloy",True,constants.WHITE) announcer = font2.render("Announcer: Harrison Malloy",True,constants.WHITE) music_sound = font2.render("Music and Sound Effects:",True,constants.WHITE) title_song = font2.render("Title song: 'Clicky' from Electronic (2018) by Manuel Senfft (www.tagirijus.de)",True,constants.WHITE) game_song = font2.render("Game song: 'Hard Fight' from Hard (2018) by Manuel Senfft (www.tagirijus.de)",True,constants.WHITE) colliding = font2.render("Balls colliding: https://opengameart.org/content/bombexplosion8bit",True,constants.WHITE) throwing = font2.render("Throwing ball: https://opengameart.org/content/sfxthrow - copyright Blender Foundation : apricot.blender.org",True,constants.WHITE) throwing2 = font2.render("Throwing sound effect from Yo Frankie! game",True,constants.WHITE) border = font2.render("Hitting Border: https://opengameart.org/content/short-alarm",True,constants.WHITE) hitting = font2.render("Getting hit by ball: https://opengameart.org/content/grunt author: n3b",True,constants.WHITE) self.text = [] self.text.append(Credits) self.text.append(programming) self.text.append(art) self.text.append(announcer) self.text.append(music_sound) self.text.append(title_song) self.text.append(game_song) self.text.append(colliding) self.text.append(throwing) self.text.append(throwing2) self.text.append(hitting) def handle_keyboard_event(self, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE or \ event.key == pygame.K_TAB or \ event.key == pygame.K_BACKSPACE: LevelManager().leave_level() elif event.type == pygame.JOYBUTTONDOWN: for joystick in self.joysticks: if joystick.get_button(1): LevelManager().leave_level() def update(self): pass def draw(self, screen): screen.fill(constants.WHITE) screen.blit(self.background_image, [0, 0]) for i in range(0,len(self.text)): rect = self.text[i].get_rect(center=(constants.SCREEN_WIDTH/2, (i+1)*50)) screen.blit(self.text[i],rect) ''' screen.blit(self.credits, [(constants.SCREEN_WIDTH/2 - self.credits.get_width()/2), 50]) screen.blit(self.programming, [(constants.SCREEN_WIDTH/2 - self.programming.get_width()/2), 150]) screen.blit(self.art, [(constants.SCREEN_WIDTH/2 - self.art.get_width()/2), 200]) screen.blit(self.music_sound, [(constants.SCREEN_WIDTH/2 - self.music_sound.get_width()/2), 300]) screen.blit(self.title_song, [(constants.SCREEN_WIDTH/2 - self.title_song.get_width()/2), 350]) screen.blit(self.game_song, [(constants.SCREEN_WIDTH/2 - self.game_song.get_width()/2), 400]) screen.blit(self.colliding, [(constants.SCREEN_WIDTH/2 - self.colliding.get_width()/2), 450]) screen.blit(self.throwing, [(constants.SCREEN_WIDTH/2 - self.throwing.get_width()/2), 500]) screen.blit(self.throwing2, [(constants.SCREEN_WIDTH/2 - self.throwing2.get_width()/2), 550]) screen.blit(self.border, [(constants.SCREEN_WIDTH/2 - self.border.get_width()/2), 600]) screen.blit(self.hitting, [(constants.SCREEN_WIDTH/2 - self.hitting.get_width()/2), 650]) '''
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,000
tienqpham/final-super-dodgeball-64
refs/heads/master
/vertical_menu.py
import pygame # an external event handler is required to activate selected menu item # use VerticalMenu.get_selected() to retrieve selected item # use VerticalMenu.get_joystick() to retrieve supported joystick class VerticalMenu(): # PARAMETERS: # rect: # a pygame.Rect defining the position and boundaries of the menu # items_off: # a list of images for each item's unselected state # items_on: # a list of images for each item's selected state # center_spacing: # TRUE: the distance bewteen adjacent items' centers is fixed; # this setting is default and advisable for images of # different sizes # FALSE: the distance between an item's bottom edge and the # next item's top edge is fixed # joystick: represents the ID of a joystick used to navigate this menu; # -2 to negative infinity uses all joysticks # -1 uses no joysticks # 0 to infinity uses the joystick of that ID # uses_keyboard: # TRUE: the menu can be navigated with the keyboard # FALSE: the menu cannot be navigated with the keyboard # uses_mouse: # TRUE: the menu can be navigated with the mouse # FALSE: the menu cannot be navigated with the mouse # PRECONDITIONS: # items_off and items_on must be of the same length def __init__(self, rect, items_off, items_on, joystick=-2, uses_keyboard=True, uses_mouse=True, center_spacing = True): self.joysticks = [] if joystick <= -2: for i in range(0,pygame.joystick.get_count()): pygame.joystick.Joystick(i).init() self.joysticks.append(pygame.joystick.Joystick(i)) elif joystick >= 0: if joysticks >= pygame.joystick.get_count(): raise ValueError("joystick of ID does not exist") pygame.joystick.Joystick(i).init() self.joysticks.append(pygame.joystick.Joystick(i)) self.center_spacing = center_spacing if len(items_off) != len(items_on): #throw an error raise ValueError("Unequal length of items_off and items_on") self.items_on = items_on self.items_off = items_off self.rect = rect self.height = rect.size[1] self.width = rect.size[0] self.top = rect.y self.bottom = self.top + self.height self.left = rect.x self.right = self.left + self.width self.item_width = items_on[0].get_rect().size[0] self.item_height = items_on[0].get_rect().size[1] for item in items_on: if item.get_rect().size[0] > self.item_width: self.item_width = item.get_rect().size[0] if item.get_rect().size[1] > self.item_height: self.item_height = item.get_rect().size[1] self.length = len(items_off) if self.center_spacing: self.positions = [] vertical_gap = self.height / (self.length+1) for i in range (0,self.length): self.positions.append( (self.width/2+self.left, self.top+vertical_gap*(i+1)) ) self.gap_x = ( self.width - self.item_width ) /2 self.gap_y = ( self.height - self.item_height * self.length) / (self.length + 1) self.selected_item = -1 self.uses_keyboard = uses_keyboard self.uses_mouse = uses_mouse self.mouse_is_visible = False if self.uses_mouse: self.mouse_is_visible = True # resets menu so no item is selected def reset(self, reset_point = -1): self.selected_item = reset_point # retrieves index of currently selected item # returns between 0 and length-1 if an item is selected # returns -1 if no item is selected def get_selected(self): return self.selected_item # returns the number of items in the menu def get_length(self): return self.length # moves item selection up one item in the list def cursor_up(self): if self.selected_item > 0: self.selected_item -= 1 elif self.selected_item == -1: self.selected_item = 0 # moves item selection down one item in the list def cursor_down(self): if self.selected_item < self.length - 1: self.selected_item += 1 def update(self): self.check_mouse() self.set_mouse_visibility() if self.center_spacing: for i in range (0,self.length): rect = self.items_off[i].get_rect(center=self.positions[i]) if rect.collidepoint(pygame.mouse.get_pos()) and self.mouse_is_visible: self.selected_item = i elif not self.center_spacing: for i in range (0,self.length): item_width = self.items_on[i].get_rect().size[0] item_height = self.items_on[i].get_rect().size[1] gap_x = ( self.width - item_width ) /2 gap_y = ( self.height - item_height * self.length) / (self.length + 1) rect = pygame.Rect(gap_x + self.left, gap_y * (i+1) + item_height * i + self.top, item_width, item_height) if rect.collidepoint(pygame.mouse.get_pos()) and self.mouse_is_visible: self.selected_item = i def draw(self, screen): if self.center_spacing: for i in range (0, self.length): rect = self.items_off[i].get_rect(center=self.positions[i]) if self.selected_item == i: screen.blit(self.items_on[i], (rect.x,rect.y) ) else: screen.blit(self.items_off[i], (rect.x,rect.y) ) elif not self.center_spacing: for i in range (0,self.length): item_width = self.items_on[i].get_rect().size[0] item_height = self.items_on[i].get_rect().size[1] gap_x = ( self.width - item_width ) /2 gap_y = ( self.height - item_height * self.length) / (self.length + 1) coord = [gap_x + self.left, gap_y * (i+1) + item_height * i + self.top] if self.selected_item == i: screen.blit(self.items_on[i], coord) else: screen.blit(self.items_off[i], coord) def check_mouse(self): if pygame.mouse.get_rel() != (0,0) and self.uses_mouse: self.mouse_is_visible = True def set_mouse_visibility(self): if self.mouse_is_visible: pygame.mouse.set_visible(True) else: pygame.mouse.set_visible(False) def handle_event(self, event): if event.type == pygame.KEYDOWN and self.uses_keyboard: self.mouse_is_visible = False if event.key == pygame.K_w or event.key==pygame.K_UP: self.cursor_up() elif event.key == pygame.K_s or event.key==pygame.K_DOWN: self.cursor_down() elif event.key == pygame.K_SPACE: print("button " + str(self.selected_item + 1) + " pressed") if event.type == pygame.JOYHATMOTION: for joystick in self.joysticks: if joystick.get_hat(0)[1] == 1: self.cursor_up() if joystick.get_hat(0)[1] == -1: self.cursor_down() if event.type == pygame.MOUSEBUTTONDOWN and self.mouse_is_visible: if pygame.mouse.get_pressed()[0]: print("button " + str(self.selected_item + 1) + " pressed")
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,001
tienqpham/final-super-dodgeball-64
refs/heads/master
/sound.py
import pygame import random from file import * class Sound(): class __Sound: def __init__(self): self.announcer_volume = 1 # needs sfx self.soundlist = {"balls_colliding": File().load("colliding"), "hitting_border": File().load("border"), "player_shooting": File().load("shooting"), "hit_by_ball": File().load("hitting"), "finalround": File().load("normal_finalround"), "heycomeon": File().load("normal_heycomeon"), "heystepitup": File().load("normal_heystepitup"), "itsnotover": File().load("normal_itsnotover"), "neverseenabattle": File().load("normal_neverseenabattle"), "player1wins": File().load("normal_player1wins"), "player2wins": File().load("normal_player2wins"), "round1": File().load("normal_round1"), "round2": File().load("normal_round2"), "round3": File().load("normal_round3"), "round4": File().load("normal_round4"), "straight": File().load("normal_straight"), "vs": File().load("normal_vs"), "soccer": File().load("normal_soccer"), "practice": File().load("normal_practice"), "draw_game": File().load("normal_drawgame"), "time": File().load("normal_time"), "timeup":File().load("normal_timeup")} # load sfx from file self.roundreadylist = {"1": File().load("normal_fightfortheages"), "2": File().load("normal_areyouready"), "3": File().load("normal_areyouready2"), "4": File().load("normal_faceitstraight"), "5": File().load("normal_getready"), "6": File().load("normal_goforbroke")} self.round2readylist = {"1": File().load("normal_heycomeon"), "2": File().load("normal_heystepitup"), "3": File().load("normal_warmingup"), "4": File().load("normal_youcantgiveitup"), "5": File().load("normal_itsnotover")} self.finalroundreadylist = {"1": File().load("normal_dodgeorbedodge"), "2": File().load("normal_doordodge"), "3": File().load("normal_battleofthecentury"), "4": File().load("normal_noholdbard"), "5": File().load("normal_nosecondchance"), "6": File().load("normal_letloose")} self.golist= {"1": File().load("normal_goforit"), "2": File().load("normal_goforitman"), "3": File().load("normal_letsparty")} self.winlist= {"1": File().load("normal_Icantbelievemyeyes"), "2": File().load("normal_knockout"), "3": File().load("normal_leaveamark"), "4": File().load("normal_leaveamark2")} self.knowledgelist = {"1": File().load("normal_knowledgeispower"), "2": File().load("normal_readup"), "3": File().load("normal_checkitout")} self.quitlist= {"1": File().load("normal_solong"), "2": File().load("normal_seeyoulater"), "3": File().load("normal_comebacksoon")} def play_round(self,num): if num == 0: sound = pygame.mixer.Sound(self.soundlist.get('finalround')) sound.set_volume(self.announcer_volume) sound.play() elif num == 1: sound = pygame.mixer.Sound(self.soundlist.get('round1')) sound.set_volume(self.announcer_volume) sound.play() elif num == 2: sound = pygame.mixer.Sound(self.soundlist.get('round2')) sound.set_volume(self.announcer_volume) sound.play() def play_time(self): num = random.randint(1,2) if num == 1: sound = pygame.mixer.Sound(self.soundlist.get('time')) sound.play() if num == 2: sound = pygame.mixer.Sound(self.soundlist.get('timeup')) sound.play() def play_sound(self, id): sound = pygame.mixer.Sound(self.soundlist.get(id)) sound.play() def play_ready_round(self): string = str(random.randint(1,len(self.roundreadylist))) print(string) sound = pygame.mixer.Sound(self.roundreadylist.get(string)) sound.set_volume(self.announcer_volume) sound.play() def play_ready_round2(self): sound = pygame.mixer.Sound(self.round2readylist.get(str(random.randint(1,len(self.round2readylist))))) sound.set_volume(self.announcer_volume) sound.play() def play_ready_finalround(self): sound = pygame.mixer.Sound(self.finalroundreadylist.get(str(random.randint(1,len(self.finalroundreadylist))))) sound.set_volume(self.announcer_volume) sound.play() def play_go(self): sound = pygame.mixer.Sound(self.golist.get(str(random.randint(1,len(self.golist))))) sound.set_volume(self.announcer_volume) sound.play() def play_win(self): sound = pygame.mixer.Sound(self.winlist.get(str(random.randint(1,len(self.winlist))))) sound.set_volume(self.announcer_volume) sound.play() def play_knowledge(self): sound = pygame.mixer.Sound(self.knowledgelist.get(str(random.randint(1,len(self.knowledgelist))))) sound.set_volume(self.announcer_volume) sound.play() def play_quit(self): sound = pygame.mixer.Sound(self.quitlist.get(str(random.randint(1,len(self.quitlist))))) sound.set_volume(self.announcer_volume) sound.play() instance = None def __init__(self): if not Sound.instance: Sound.instance = Sound.__Sound() def __getattr__(self, name): return getattr(self.instance, name)
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,002
tienqpham/final-super-dodgeball-64
refs/heads/master
/test/test_ball.py
import unittest import sys sys.path.append('..') import constants from actor import * from ball import * class test_Ball(unittest.TestCase): # can be created def test_init(self): ball = Ball(pygame.image.load('missing.png'),0,0,1,1,1) self.assertTrue(True) # can be updated automatically def test_update(self): ball = Ball(pygame.image.load('missing.png'),0,0,1,1,1) ball.update() self.assertTrue(True) # left edge def test_out_of_bounds_left(self): ball = Ball(pygame.image.load('missing.png'),0,0,-10,5,1) ball.set_speed_x(-10) ball.update() #self.assertEqual(ball.set_speed_x(10)) if __name__ == '__main__': unittest.main()
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,003
tienqpham/final-super-dodgeball-64
refs/heads/master
/art.py
import pygame import constants from file import * class Art(): class __Art: def __init__(self): # needs images self.imgList = {'missing': File().load("missing"), 'targetBlue': File().load("targetBlue"), 'ball': File().load("ball"), 'player1': File().load("player1"), 'player2': File().load("player2"), 'reticle1': File().load("reticle1"), 'reticle2': File().load("reticle2"), 'shield1': File().load("shield_red"), 'shield2': File().load("shield_blue"), 'ball1': File().load("ball1"), 'ball2': File().load("ball2"), 'gamepad_select': File().load("gamepad_select"), 'keyboard_select': File().load("keyboard_select"), 'howtoplay':File().load("howtoplay"), 'ready1_off': File().load("ready1_off"), 'ready1_on': File().load("ready1_on"), 'ready2_off': File().load("ready2_off"), 'ready2_on': File().load("ready2_on"), 'title': File().load("title"), 'quit_off': File().load("quit_green_off"), 'quit_on': File().load("quit_green_on"), 'resume_off': File().load("resume_green_off"), 'resume_on': File().load("resume_green_on"), 'quit_red_off': File().load("quit_red_off"), 'quit_red_on': File().load("quit_red_on"), 'practice_red_off': File().load("practice_red_off"), 'practice_red_on': File().load("practice_red_on"), 'versus_split_off': File().load("versus_split_off"), 'versus_split_on': File().load("versus_split_on"), 'howToPlay_red_off': File().load("howToPlay_red_off"), 'howToPlay_red_on': File().load("howToPlay_red_on"), 'soccer_split_off': File().load("soccer_split_off"), 'soccer_split_on': File().load("soccer_split_on"), 'credits_red_off': File().load("credits_red_off"), 'credits_red_on': File().load("credits_red_on"), 'timerFrame': File().load("timerFrame"), 'round1': File().load("round1"), 'round2': File().load("round2"), 'finalRound': File().load("finalRound"), 'ready': File().load("ready"), 'go': File().load("go"), 'player1_wins': File().load("player1_wins"), 'player2_wins': File().load("player2_wins"), 'draw_game': File().load("draw_game"), 'time': File().load("time"), 'knockout': File().load("knockout"), 'paused': File().load("paused"), 'basketBallCourt': File().load("basketBallCourt"), 'basketBallCourt_dark': File().load("basketBallCourt_dark"), 'paused': File().load("paused"), 'soccerBall': File().load("soccerBall"), 'soccerField': File().load("soccerField"), 'tempGoal': File().load("tempGoal")} self.P1healthBarsList = {'5': File().load("health_red_5of5"), '4': File().load("health_red_4of5"), '3': File().load("health_red_3of5"), '2': File().load("health_red_2of5"), '1': File().load("health_red_1of5"), '0': File().load("health_red_0of5")} self.P2healthBarsList = {'5': File().load("health_blue_5of5"), '4': File().load("health_blue_4of5"), '3': File().load("health_blue_3of5"), '2': File().load("health_blue_2of5"), '1': File().load("health_blue_1of5"), '0': File().load("health_blue_0of5")} self.digit_list = {'0': File().load("digital0"), '1': File().load("digital1"), '2': File().load("digital2"), '3': File().load("digital3"), '4': File().load("digital4"), '5': File().load("digital5"), '6': File().load("digital6"), '7': File().load("digital7"), '8': File().load("digital8"), '9': File().load("digital9")} self.round_list = {'1': File().load("round1"), '2': File().load("round2"), '0': File().load("finalRound")} # class methods def get_image(self, id): img = self.imgList.get(id) image = pygame.image.load(str(img)).convert() image.set_colorkey(constants.TRANSPARENT_COLOR) return image def get_round(self, id): img = self.round_list.get(id) image = pygame.image.load(str(img)).convert() image.set_colorkey(constants.TRANSPARENT_COLOR) return image def get_digit(self,id): img = self.digit_list.get(id) image = pygame.image.load(str(img)).convert() image.set_colorkey(constants.BLACK) return image def get_health_bar_image(self,player_number,id): if player_number == 1: img = self.P1healthBarsList.get(id) elif player_number == 2: img = self.P2healthBarsList.get(id) image = pygame.image.load(str(img)).convert() image.set_colorkey(constants.TRANSPARENT_COLOR) return image instance = None def __init__(self): if not Art.instance: Art.instance = Art.__Art() def __getattr__(self, name): return getattr(self.instance, name)
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,004
tienqpham/final-super-dodgeball-64
refs/heads/master
/test_timer.py
import pygame from timer import * SCREEN_WIDTH = 400 SCREEN_HEIGHT = 300 WHITE = (255,255,255) BLACK = (0,0,0) pygame.init() screen = pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT]) clock = pygame.time.Clock() done = False rect = pygame.Rect(0,0, 200, 200) my_timer = Timer(rect,60) while not done: clock.tick(60) screen.fill(BLACK) for event in pygame.event.get(): if event.type == pygame.QUIT: done = True break if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: done = True break elif event.key == pygame.K_SPACE: my_timer.toggle_pause() my_timer.update() screen.blit(Art().get_image('timerFrame'),[0,0]) my_timer.draw(screen) pygame.display.flip() pygame.quit()
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,005
tienqpham/final-super-dodgeball-64
refs/heads/master
/controller_screen.py
import pygame import constants from level_manager import * from art import * from control_select import * from game_screen import * from soccer_screen import * #from single_player import * pygame.init() pygame.joystick.init() class ControllerScreen(): # game_mode: # 0: standard versus # 1: soccer # 2: practice def __init__(self,game_mode=0): self.game_mode = game_mode if game_mode == 2: self.control_menu = ControlSelect(1) else: self.control_menu = ControlSelect() self.background_image = Art().get_image("basketBallCourt_dark") font = pygame.font.SysFont('Calibri', 25, True, False) self.ready_time = 0 self.current_time = 0 self.ready = False self.controller = font.render("Controller not detected!",True,constants.RED) def return_to_title(self): pygame.joystick.quit() pygame.joystick.init() for i in range(pygame.joystick.get_count()): pygame.joystick.Joystick(i).init() LevelManager().leave_level() def handle_keyboard_event(self, event): if event.type == pygame.KEYDOWN: if (event.key == pygame.K_ESCAPE or \ event.key == pygame.K_TAB or \ event.key == pygame.K_BACKSPACE) and \ not self.control_menu.is_anyone_ready(): self.return_to_title() if event.type == pygame.JOYBUTTONDOWN: for i in range(0,pygame.joystick.get_count()): if pygame.joystick.Joystick(i).get_button(1) and\ not self.control_menu.is_anyone_ready(): self.return_to_title() break self.control_menu.handle_event(event) def update(self): self.current_time = pygame.time.get_ticks() self.control_menu.update() if self.control_menu.is_everyone_ready(): if not self.ready: self.ready = True self.ready_time = self.current_time else: if self.current_time >= self.ready_time + constants.PROMPT_DELAY: if self.game_mode == 0: LevelManager().load_level(GameScreen(self.control_menu.get_player1_control(), self.control_menu.get_player2_control())) if self.game_mode == 1: # load soccer pass if self.game_mode == 2: LevelManager().load_level(SinglePlayer(self.control_menu.get_player1_control())) pass self.control_menu.reset() self.ready = False def draw(self, screen): screen.fill(constants.WHITE) screen.blit(self.background_image, [0, 0]) self.control_menu.draw(screen) #screen.blit(self.controller, [(constants.SCREEN_WIDTH/2 - self.controller.get_width()/2), (constants.SCREEN_HEIGHT/4)])
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,006
tienqpham/final-super-dodgeball-64
refs/heads/master
/test/test_actor.py
import unittest import sys from unittest.mock import patch sys.path.append('..') import constants from actor import * class test_Actor(unittest.TestCase): # can be created @patch('actor.pygame') def test_init(self,mock_pygame): actor = mock_pygame self.assertTrue(True) # can be created at a specific position def test_init_pos(self): actor = Actor(pygame.image.load('missing.png'),5,10) self.assertEqual(actor.rect.x, 5) self.assertEqual(actor.rect.y, 10) # if created out of bounds, resets back within bounds def test_init_bounds(self): actor = Actor(pygame.image.load('missing.png'),-5,-3) self.assertEqual(actor.get_x(), 0) self.assertEqual(actor.get_y(), 0) # can be updated automatically def test_update(self): actor = Actor(pygame.image.load('missing.png')) actor.update() self.assertTrue(True) # speed can be modified directly def test_set_speed(self): actor = Actor(pygame.image.load('missing.png')) self.assertEqual(actor.speed_x, 0) self.assertEqual(actor.speed_y, 0) actor.set_speed_x(5) actor.set_speed_y(4) self.assertEqual(actor.speed_x, 5) self.assertEqual(actor.speed_y, 4) # speed can be modified via acceleration def test_acceleration(self): actor = Actor(pygame.image.load('missing.png')) self.assertEqual(actor.speed_x, 0) self.assertEqual(actor.speed_y, 0) actor.accelerate(2,3) actor.accelerate(2,3) self.assertEqual(actor.speed_x, 4) self.assertEqual(actor.speed_y, 6) # can be stopped in x direction without affecting y speed def test_stop_x(self): actor = Actor(pygame.image.load('missing.png')) self.assertEqual(actor.speed_x, 0) self.assertEqual(actor.speed_y, 0) actor.accelerate(5,3) self.assertEqual(actor.speed_x, 5) self.assertEqual(actor.speed_y, 3) actor.stop_x() self.assertEqual(actor.speed_x, 0) self.assertEqual(actor.speed_y, 3) # can be stopped in y direction without affecting x speed def test_stop_y(self): actor = Actor(pygame.image.load('missing.png')) self.assertEqual(actor.speed_x, 0) self.assertEqual(actor.speed_y, 0) actor.accelerate(5,3) self.assertEqual(actor.speed_x, 5) self.assertEqual(actor.speed_y, 3) actor.stop_y() self.assertEqual(actor.speed_x, 5) self.assertEqual(actor.speed_y, 0) # can be stopped abruptly def test_stop(self): actor = Actor(pygame.image.load('missing.png')) self.assertEqual(actor.speed_x, 0) self.assertEqual(actor.speed_y, 0) actor.accelerate(5,5) self.assertEqual(actor.speed_x, 5) self.assertEqual(actor.speed_y, 5) actor.stop() self.assertEqual(actor.speed_x, 0) self.assertEqual(actor.speed_y, 0) # speed affects position after update def test_update_with_speed(self): actor = Actor(pygame.image.load('missing.png')) self.assertEqual(actor.rect.x, 0) self.assertEqual(actor.rect.y, 0) actor.set_speed_x(5) actor.set_speed_y(4) actor.update() actor.update() self.assertEqual(actor.rect.x, 10) self.assertEqual(actor.rect.y, 8) # cannot move out of bounds # left edge def test_out_of_bounds_left(self): actor = Actor(pygame.image.load('missing.png'),5,5) self.assertEqual(actor.get_pos()[0], 5) actor.set_speed_x(-10) actor.update() self.assertEqual(actor.get_pos()[0], 0) actor.update() self.assertEqual(actor.get_pos()[0], 0) # top edge def test_out_of_bounds_top(self): actor = Actor(pygame.image.load('missing.png'),5,5) self.assertEqual(actor.get_pos()[1], 5) actor.set_speed_y(-10) actor.update() self.assertEqual(actor.get_pos()[1], 0) actor.update() self.assertEqual(actor.get_pos()[1], 0) # right edge # the sprite used, 'missing.png', is 150x150 pixels def test_out_of_bounds_right(self): actor = Actor(pygame.image.load('missing.png'), constants.SCREEN_WIDTH - 180, constants.SCREEN_HEIGHT - 180) self.assertEqual(actor.get_pos()[0], constants.SCREEN_WIDTH - 180) actor.set_speed_x(50) actor.update() self.assertEqual(actor.get_pos()[0], constants.SCREEN_WIDTH - 150) actor.update() self.assertEqual(actor.get_pos()[0], constants.SCREEN_WIDTH - 150) # bottom edge def test_out_of_bounds_bottom(self): actor = Actor(pygame.image.load('missing.png'), constants.SCREEN_WIDTH - 180, constants.SCREEN_HEIGHT - 180) self.assertEqual(actor.get_pos()[1], constants.SCREEN_HEIGHT - 180) actor.set_speed_y(50) actor.update() self.assertEqual(actor.get_pos()[1], constants.SCREEN_HEIGHT - 150) actor.update() self.assertEqual(actor.get_pos()[1], constants.SCREEN_HEIGHT - 150) # position can be set directly def test_set_pos(self): img = pygame.image.load('missing.png') actor = Actor(img,0,0) actor.set_pos(3,4) self.assertEqual(3, actor.get_pos()[0]) self.assertEqual(4, actor.get_pos()[1]) # center position can be set directly def test_set_center(self): img = pygame.image.load('missing.png') actor = Actor(img,0,0) actor.set_center(3,4) self.assertEqual(3, actor.get_center()[0]) self.assertEqual(4, actor.get_center()[1]) self.assertFalse( actor.get_center()[0] == actor.get_pos()[0] ) self.assertFalse( actor.get_center()[1] == actor.get_pos()[1] ) # can be drawn on a screen def test_draw(self): screen = pygame.display.set_mode([constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]) screen.fill(constants.WHITE) sprite_list = pygame.sprite.Group() actor = Actor(pygame.image.load('missing.png')) sprite_list.add(actor) sprite_list.update() sprite_list.draw(screen) pygame.display.flip() pygame.quit() if __name__ == '__main__': unittest.main()
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,007
tienqpham/final-super-dodgeball-64
refs/heads/master
/ball.py
import pygame import constants from actor import * from art import * class Ball(Actor): def __init__(self,img,x,y,speed_x,speed_y, multiplier): super().__init__(img,x,y) self.multiplier = multiplier self.set_speed(speed_x, speed_y) def update(self): self.rect.x += self.speed_x * self.multiplier self.rect.y += self.speed_y * self.multiplier #left edge if self.rect.x < 0: self.speed_x = self.speed_x * -1 #right edge if self.rect.x > constants.SCREEN_WIDTH - self.rect.size[0]: self.speed_x = self.speed_x * -1 #top edge if self.rect.y < 0: self.speed_y = self.speed_y * -1 #bottom edge if self.rect.y > constants.SCREEN_HEIGHT - self.rect.size[1]: self.speed_y = self.speed_y * -1 def get_multiplier(self): return self.multiplier class NeutralBall(Ball): def __init__(self,x,y,speed_x,speed_y, multiplier=1): super().__init__( Art().get_image('ball'), x, y,speed_x,speed_y, multiplier) class RedBall(Ball): def __init__(self,x,y,speed_x,speed_y, multiplier=1): super().__init__( Art().get_image('ball1'), x, y,speed_x,speed_y, multiplier) class BlueBall(Ball): def __init__(self,x,y,speed_x,speed_y, multiplier=1): super().__init__( Art().get_image('ball2'), x, y,speed_x,speed_y, multiplier)
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,008
tienqpham/final-super-dodgeball-64
refs/heads/master
/joystick_player.py
import pygame import constants from player import * class JoystickPlayer(Player): def __init__(self, playerNumber, joystickNumber): super().__init__(playerNumber) self.control_index = joystickNumber self.joystick = pygame.joystick.Joystick(joystickNumber) self.joystick.init() self.top_speed = constants.JOYSTICK_PLAYER_SPEED self.deadzone = constants.DEADZONE def get_joystick(self): return self.joystick def handle_event(self, event): if event.type == pygame.JOYAXISMOTION: if self.joystick.get_axis(0) > self.deadzone or \ self.joystick.get_axis(0) < self.deadzone * -1 : self.speed_x = int(self.top_speed * self.joystick.get_axis(0)) else : self.speed_x = 0 if self.joystick.get_axis(1) > self.deadzone or \ self.joystick.get_axis(1) < self.deadzone * -1 : self.speed_y = int(self.top_speed * self.joystick.get_axis(1)) else : self.speed_y = 0
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,009
tienqpham/final-super-dodgeball-64
refs/heads/master
/timer.py
import pygame import constants from art import * class Timer(): # PARAMETERS: # start_time: # the time, in seconds, at which the clock starts # max_time: # the upper limit of the clock time; # not used when counting down from start_time to 0 # count_by_update_cycle: # TRUE: time is measured by the number of update cycles # FALSE: time is measured using real time # count_down: # TRUE: the timer will count down from start_time to 0 # FALSE: the timer will count up from start_time # start_immediately: # TRUE: calls to update() will immediately affect # the clock time # FALSE: start() must be called before calls to # update() will affect the clock time def __init__(self, rect, start_time, max_time = 999, count_by_update_cycle=False, count_down=True, start_immediately=False): self.count_by_update = count_by_update_cycle self.rect = rect self.left = self.rect.x self.right = self.left + self.rect.size[0] self.top = self.rect.y self.bottom = self.top + self.rect.size[1] if count_down: self.digits = len(str(start_time)) else: self.digits = len(str(max_time)) self.start_time = start_time self.max_time = max_time if count_by_update_cycle: self.current_time = 0 self.last_check = 0 else: self.current_time = pygame.time.get_ticks() self.clock_time = start_time self.count_down = count_down self.is_paused = not start_immediately # returns the time, in seconds, on the clock # PARAMETERS: # as_list: # TRUE: returns time as a list of single-digit integers # FALSE: returns time as a single integer def get_time(self, as_list = False): if not as_list: return self.clock_time else: timeString = str(self.clock_time) timeArr = [] for digit in timeString: timeArr.append(int(digit)) return timeArr # returns TRUE if the timer can no longer advance # returns FALSE if the timer can still advance def is_time_up(self): if self.count_down: return self.clock_time == 0 else: return self.clock_time == self.max_time # resets current time on the clock to the start time def reset(self): self.clock_time = self.start_time # sets current time on the clock to the specified time def set_time(self, time): self.clock_time = time # sets the timer to start counting if either paused # or set not to start immediately; # functionally identical to unpause() def start(self): self.unpause() def pause(self): self.is_paused = True def unpause(self): self.is_paused = False def toggle_pause(self): if self.is_paused: self.is_paused = False else: self.is_paused = True def update(self): if not self.is_paused: if self.has_one_second_passed(): if not self.count_down and self.clock_time < self.max_time: self.clock_time += 1 elif self.count_down and self.clock_time > 0: self.clock_time -= 1 def draw(self, screen): arr = self.get_time(True) imgs = [] for num in arr: imgs.append(Art().get_digit(str(num))) width = imgs[0].get_rect().size[0] gap = 4 for i in range(0, self.digits-len(imgs)): imgs.insert(0,Art().get_digit('0')) for i in range(0, len(imgs)): screen.blit(imgs[i], (self.left + (width+gap)*i, self.top)) def has_one_second_passed(self): if self.count_by_update: self.current_time += 1 if self.current_time >= self.last_check + 60: self.last_check = self.current_time return True else: return False else: if pygame.time.get_ticks() >= self.current_time + 1000: self.current_time = pygame.time.get_ticks() return True else: return False
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,010
tienqpham/final-super-dodgeball-64
refs/heads/master
/test/test_reticle.py
import unittest import pygame import sys sys.path.append('..') import constants from reticle import * from art import * pygame.init() pygame.display.init() art = Art() class test_reticle(unittest.TestCase): # can be created def test_init(self): ret = Reticle(0,0,1) self.assertTrue(True) # can be updated automatically def test_update(self): ret = Reticle(0,0,1) ret.update() self.assertTrue(True) # can be created at coordinates on screen def test_init_pos(self): ret = Reticle(10,20,1) self.assertEqual(ret.get_pos()[0], 10) self.assertEqual(ret.get_pos()[1], 20) # reticle can be partly off screen def test_init_off_screen(self): ret = Reticle(-5,-5,1) # coordinates of upper-left corner should be off screen self.assertEqual(-5, ret.get_pos()[0]) self.assertEqual(-5, ret.get_pos()[1]) # reticle center cannot be off screen def test_out_of_bounds(self): ret = Reticle(0,0,1) ret.set_center(-5, -5) ret.update() self.assertEqual(0, ret.get_center()[0]) self.assertEqual(0, ret.get_center()[1]) ret.set_center(constants.SCREEN_WIDTH+50, constants.SCREEN_HEIGHT+50) ret.update() self.assertEqual(constants.SCREEN_WIDTH, ret.get_center()[0]) self.assertEqual(constants.SCREEN_HEIGHT, ret.get_center()[1]) # can be drawn on a screen def test_draw(self): screen = pygame.display.set_mode([constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]) screen.fill(constants.WHITE) sprite_list = pygame.sprite.Group() ret = Reticle(0,0,1) sprite_list.add(ret) sprite_list.update() sprite_list.draw(screen) pygame.display.flip() if __name__ == '__main__': unittest.main()
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,011
tienqpham/final-super-dodgeball-64
refs/heads/master
/reticle.py
import pygame import constants import sys sys.path.append('..') from art import * from file import * from actor import * class Reticle(Actor): def __init__(self, x, y, playerNumber): img = Art().get_image('reticle1') if playerNumber == 2: img = Art().get_image('reticle2') if playerNumber != 1 and playerNumber != 2: raise ValueError("Invalid player number for reticle") super().__init__(img, x, y) def update(self): self.rect.x += self.speed_x self.rect.y += self.speed_y self.check_out_of_bounds() # reticle can pass halfway off screen in either direction # reticle center cannot pass off screen def check_out_of_bounds(self): # x # left edge if self.get_center()[0] < 0: self.stop_x() self.rect.x = 0 - (self.rect.size[0]/2) # right edge if self.get_center()[0] > constants.SCREEN_WIDTH: self.stop_x() self.rect.x = constants.SCREEN_WIDTH - (self.rect.size[0]/2) # y # top edge if self.get_center()[1] < 0: self.stop_y() self.rect.y = 0 - (self.rect.size[1]/2) # bottom edge if self.get_center()[1] > constants.SCREEN_HEIGHT: self.stop_y() self.rect.y = constants.SCREEN_HEIGHT - (self.rect.size[1]/2)
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,012
tienqpham/final-super-dodgeball-64
refs/heads/master
/keyboard_player.py
import pygame import constants from player import * class KeyboardPlayer(Player): def __init__(self, playerNumber): super().__init__(playerNumber) self.top_speed = constants.KEYBOARD_PLAYER_SPEED self.control_index = -1 def handle_event(self, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_w: # up self.accelerate(0, self.top_speed * -1) elif event.key == pygame.K_a: # left self.accelerate(self.top_speed * -1, 0) elif event.key == pygame.K_s: # down self.accelerate(0, self.top_speed) elif event.key == pygame.K_d: # right self.accelerate(self.top_speed, 0) elif event.type == pygame.KEYUP: if event.key == pygame.K_w: # up self.accelerate(0,self.top_speed) elif event.key == pygame.K_a: # left self.accelerate(self.top_speed,0) elif event.key == pygame.K_s: # down self.accelerate(0,self.top_speed * -1) elif event.key == pygame.K_d: # right self.accelerate(self.top_speed * -1,0)
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,013
tienqpham/final-super-dodgeball-64
refs/heads/master
/test/test_vertical_menu.py
import unittest import pygame import sys sys.path.append('..') import constants from vertical_menu import * from art import * art = Art() pygame.init() pygame.display.init() SCREEN_WIDTH = 400 SCREEN_HEIGHT = 300 screen = pygame.display.set_mode([ SCREEN_WIDTH, SCREEN_HEIGHT ]) class test_VerticalMenu(unittest.TestCase): def test_init(self): rect = pygame.Rect(0,0,SCREEN_WIDTH,SCREEN_HEIGHT) items_off = [] items_on = [] for i in range(0,3): items_off.append(Art().get_image("ball")) items_on.append(Art().get_image("ball1")) myMenu = VerticalMenu(rect,items_off,items_on) self.assertTrue(True) def test_update(self): rect = pygame.Rect(0,0,SCREEN_WIDTH,SCREEN_HEIGHT) items_off = [] items_on = [] for i in range(0,3): items_off.append(Art().get_image("ball")) items_on.append(Art().get_image("ball1")) myMenu = VerticalMenu(rect,items_off,items_on) myMenu.update() self.assertTrue(True) def test_get_selected(self): rect = pygame.Rect(0,0,SCREEN_WIDTH,SCREEN_HEIGHT) items_off = [] items_on = [] for i in range(0,3): items_off.append(Art().get_image("ball")) items_on.append(Art().get_image("ball1")) myMenu = VerticalMenu(rect,items_off,items_on) myMenu.update() self.assertEqual(-1,myMenu.get_selected()) def test_get_length(self): rect = pygame.Rect(0,0,SCREEN_WIDTH,SCREEN_HEIGHT) items_off = [] items_on = [] length = 3 for i in range(0,length): items_off.append(Art().get_image("ball")) items_on.append(Art().get_image("ball1")) myMenu = VerticalMenu(rect,items_off,items_on) self.assertEqual(length,myMenu.get_length()) items_off.clear() items_on.clear() length = 6 for i in range(0,length): items_off.append(Art().get_image("ball")) items_on.append(Art().get_image("ball1")) otherMenu = VerticalMenu(rect,items_off,items_on) self.assertEqual(length,otherMenu.get_length()) def test_cursor_down(self): rect = pygame.Rect(0,0,SCREEN_WIDTH,SCREEN_HEIGHT) items_off = [] items_on = [] for i in range(0,3): items_off.append(Art().get_image("ball")) items_on.append(Art().get_image("ball1")) myMenu = VerticalMenu(rect,items_off,items_on) #myMenu.update() self.assertEqual(-1,myMenu.get_selected()) myMenu.cursor_down() myMenu.update() self.assertEqual(0,myMenu.get_selected()) for i in range(0,3): myMenu.cursor_down() self.assertEqual(myMenu.get_length()-1, myMenu.get_selected()) def test_cursor_up(self): rect = pygame.Rect(0,0,SCREEN_WIDTH,SCREEN_HEIGHT) items_off = [] items_on = [] for i in range(0,3): items_off.append(Art().get_image("ball")) items_on.append(Art().get_image("ball1")) myMenu = VerticalMenu(rect,items_off,items_on) self.assertEqual(-1,myMenu.get_selected()) myMenu.cursor_up() myMenu.update() self.assertEqual(0,myMenu.get_selected()) for i in range(0,3): myMenu.cursor_down() self.assertEqual(myMenu.get_length()-1, myMenu.get_selected()) for i in range(0,3): myMenu.cursor_up() self.assertEqual(0, myMenu.get_selected()) if __name__ == '__main__': unittest.main()
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,014
tienqpham/final-super-dodgeball-64
refs/heads/master
/test/test_player.py
import unittest import pygame import sys sys.path.append('..') import constants from player import * from art import * art = Art() pygame.init() pygame.display.init() screen = pygame.display.set_mode([ constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT ]) class test_player(unittest.TestCase): def test_init(self): player1 = Player(1) player2 = Player(2) self.assertTrue(True) def test_player_default_hit_points(self): player1 = Player(1) self.assertEqual(player1.get_hit_points(), 5) def test_player_input_hit_points(self): player1 = Player(1, 10) self.assertEqual(player1.get_hit_points(), 10) def can_not_be_damage_by_negative_amount(self): player1 = Player(1) player1.damage(-1) self.assertEqual(player1.get_hit_points(), 5) def test_player_can_take_default_damage(self): player1 = Player(1) player1.damage() self.assertEqual(player1.get_hit_points(), 4) def test_player_can_take_input_damage(self): player1 = Player(1) player1.damage(3) self.assertEqual(player1.get_hit_points(), 2) # BEGIN PLAYER 1 SPECIFIC TESTS # cannot move out of bounds # left edge def test_P1_out_of_bounds_left(self): player1 = Player(1) self.assertEqual(player1.get_pos()[0], constants.SCREEN_WIDTH/4) player1.set_speed_x(-1000) self.assertEqual(player1.get_speed()[0], -1000) player1.update() self.assertEqual(player1.get_pos()[0], 0) # top edge def test_P1_out_of_bounds_top(self): player1 = Player(1) self.assertEqual(player1.get_pos()[1], constants.SCREEN_HEIGHT/2) player1.set_speed_y(-1000) self.assertEqual(player1.get_speed()[1], -1000) player1.update() self.assertEqual(player1.get_pos()[1], 0) # right edge def test_P1_out_of_bounds_right(self): player1 = Player(1) self.assertEqual(player1.get_pos()[0], constants.SCREEN_WIDTH/4) player1.set_speed_x(1000) player1.update() self.assertEqual(player1.get_pos()[0], constants.SCREEN_WIDTH/2 - player1.rect.size[0]) # bottom edge def test_P1_out_of_bounds_bottom(self): player1 = Player(1) self.assertEqual(player1.get_pos()[1], constants.SCREEN_HEIGHT/2) player1.set_speed_y(1000) player1.update() self.assertEqual(player1.get_pos()[1], constants.SCREEN_HEIGHT - player1.rect.size[1]) # END PLAYER 1 SPECIFIC TESTS # BEGIN PLAYER 2 SPECIFIC TESTS # cannot move out of bounds # left edge def test_P2_out_of_bounds_left(self): player2 = Player(2) self.assertEqual(player2.get_pos()[0], constants.SCREEN_WIDTH/4*3) player2.set_speed_x(-1000) self.assertEqual(player2.get_speed()[0], -1000) player2.update() self.assertEqual(player2.get_pos()[0], constants.SCREEN_WIDTH/2) # top edge def test_P2_out_of_bounds_top(self): player2 = Player(2) self.assertEqual(player2.get_pos()[1], constants.SCREEN_HEIGHT/2) player2.set_speed_y(-1000) self.assertEqual(player2.get_speed()[1], -1000) player2.update() self.assertEqual(player2.get_pos()[1], 0) # right edge def test_P2_out_of_bounds_right(self): player2 = Player(2) self.assertEqual(player2.get_pos()[0], constants.SCREEN_WIDTH/4*3) player2.set_speed_x(1000) player2.update() self.assertEqual(player2.get_pos()[0], constants.SCREEN_WIDTH - player2.rect.size[0]) # bottom edge def test_P2_out_of_bounds_bottom(self): player2 = Player(2) self.assertEqual(player2.get_pos()[1], constants.SCREEN_HEIGHT/2) player2.set_speed_y(1000) player2.update() self.assertEqual(player2.get_pos()[1], constants.SCREEN_HEIGHT - player2.rect.size[1]) # END PLAYER 2 SPECIFIC TESTS if __name__ == '__main__': unittest.main()
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,015
tienqpham/final-super-dodgeball-64
refs/heads/master
/howtoplay_screen.py
import pygame import constants from level_manager import * from music import * from art import * pygame.init() class HowtoplayScreen(): def __init__(self): self.joysticks = [] for i in range(0,pygame.joystick.get_count()): pygame.joystick.Joystick(i).init() self.joysticks.append(pygame.joystick.Joystick(i)) font = pygame.font.SysFont('Calibri', 50, True, False) font2 = pygame.font.SysFont('Calibri', 30, True, False) self.background_image = Art().get_image("basketBallCourt_dark") self.how = font.render("How to play?",True,constants.BLACK) self.player1 = font2.render("Player 1 Controls",True,constants.BLACK) self.player2 = font2.render("Player 2 Controls",True,constants.BLACK) self.player1_shooting = font2.render("Left or Right mouse to shoot.",True,constants.BLACK) self.player1_moving = font2.render("WASD to move.",True,constants.BLACK) self.player1_aiming = font2.render("Use mouse to aim.",True,constants.BLACK) self.player1_pause = font2.render("Press spacebar to pause",True,constants.BLACK) self.player2_shooting = font2.render("LB/RB to shoot.",True,constants.BLACK) self.player2_moving = font2.render("Left Joystick to move.",True,constants.BLACK) self.player2_aiming = font2.render("Right Joystick to aim.",True,constants.BLACK) self.player2_pause = font2.render("Press start to pause.",True,constants.BLACK) self.gameplay1 = font2.render("When balls of different colors collide, their velocities are added along with their speed multipliers.",True,constants.BLACK) self.gameplay2 = font2.render("The player that survives longer wins.",True,constants.BLACK) self.esc = font2.render("Press ESC on any screen to leave (Pressing ESC on title screen quit the game).",True,constants.BLACK) def handle_keyboard_event(self, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE or \ event.key == pygame.K_TAB or \ event.key == pygame.K_BACKSPACE: LevelManager().leave_level() elif event.type == pygame.JOYBUTTONDOWN: for joystick in self.joysticks: if joystick.get_button(1): LevelManager().leave_level() def update(self): pass def draw(self, screen): screen.fill(constants.WHITE) screen.blit(self.background_image, [0, 0]) screen.blit(Art().get_image('howtoplay'), [0,0]) ''' screen.blit(self.how, [(constants.SCREEN_WIDTH/2 - self.how.get_width()/2), 50]) screen.blit(self.esc, [(constants.SCREEN_WIDTH/2 - self.esc.get_width()/2), 500]) screen.blit(self.player1, [(constants.SCREEN_WIDTH/4 - self.player1.get_width()/2), 150]) screen.blit(self.player1_shooting, [(constants.SCREEN_WIDTH/4 - self.player1_shooting.get_width()/2), 200]) screen.blit(self.player1_moving, [(constants.SCREEN_WIDTH/4 - self.player1_moving.get_width()/2), 250]) screen.blit(self.player1_aiming, [(constants.SCREEN_WIDTH/4 - self.player1_aiming.get_width()/2), 300]) screen.blit(self.player1_pause, [(constants.SCREEN_WIDTH/4 - self.player1_pause.get_width()/2), 350]) screen.blit(self.player2, [(((constants.SCREEN_WIDTH/4) * 3) - self.player2.get_width()/2), 150]) screen.blit(self.player2_shooting, [(((constants.SCREEN_WIDTH/4) * 3) - self.player2_shooting.get_width()/2), 200]) screen.blit(self.player2_moving, [(((constants.SCREEN_WIDTH/4) * 3) - self.player2_moving.get_width()/2), 250]) screen.blit(self.player2_aiming, [(((constants.SCREEN_WIDTH/4) * 3) - self.player2_aiming.get_width()/2), 300]) screen.blit(self.player2_pause, [(((constants.SCREEN_WIDTH/4) * 3) - self.player2_pause.get_width()/2), 350]) screen.blit(self.gameplay1, [(((constants.SCREEN_WIDTH/4)) - self.player2_pause.get_width()/2), 400]) screen.blit(self.gameplay2, [(((constants.SCREEN_WIDTH/4)) - self.player2_pause.get_width()/2), 450]) '''
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,016
tienqpham/final-super-dodgeball-64
refs/heads/master
/actor.py
import pygame import constants class Actor(pygame.sprite.Sprite): def __init__(self, img, x=0, y=0, rebound=0): super().__init__() self.rebound = rebound self.image = img self.image.set_colorkey(constants.TRANSPARENT_COLOR) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.speed_x = 0 self.speed_y = 0 self.left_bound = 0 self.right_bound = constants.SCREEN_WIDTH self.top_bound = 0 self.low_bound = constants.SCREEN_HEIGHT self.check_out_of_bounds() # increments directional speeds by given amounts # positive values accelerate down and right, # negative values accelerate up and left def accelerate(self, x, y): self.speed_x += x self.speed_y += y def set_speed_x(self, x): self.speed_x = x def set_speed_y(self, y): self.speed_y = y def set_speed(self, x, y): self.speed_x = x self.speed_y = y def get_speed(self): return [self.speed_x, self.speed_y] def set_pos(self, x, y): self.rect.x = x self.rect.y = y def set_center(self, x, y): self.rect.x = x - (self.rect.size[0]/2) self.rect.y = y - (self.rect.size[1]/2) # returns an array containing coordinates of the center def get_center(self): return [ self.rect.x + (self.rect.size[0]/2), self.rect.y + (self.rect.size[1]/2) ] # returns an array containing coordinates of upper-left corner def get_pos(self): return [self.rect.x, self.rect.y] def get_x(self): return self.rect.x def get_y(self): return self.rect.y def stop_y(self): self.speed_y = 0 def stop_x(self): self.speed_x = 0 def stop(self): self.stop_y() self.stop_x() def set_rebound(self, rebound): self.rebound = rebound def update(self): self.rect.x += self.speed_x self.rect.y += self.speed_y self.check_out_of_bounds() def check_out_of_bounds(self): # x # left edge if self.rect.x < self.left_bound: self.rect.x = self.left_bound # right edge if self.rect.x > self.right_bound - self.rect.size[0]: self.rect.x = self.right_bound - self.rect.size[0] - self.rebound # y # top edge if self.rect.y < self.top_bound: self.rect.y = self.top_bound # bottom edge if self.rect.y > self.low_bound - self.rect.size[1]: self.rect.y = self.low_bound - self.rect.size[1] - self.rebound
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,017
tienqpham/final-super-dodgeball-64
refs/heads/master
/title_screen.py
import pygame import constants from level_manager import * from credit_screen import * from game_screen import * from soccer_screen import * from controller_screen import * from howtoplay_screen import * from art import * from music import * from vertical_menu import * from sound import * pygame.init() pygame.joystick.init() class TitleScreen(): def __init__(self): self.title = Art().get_image('title') self.title_rect = self.title.get_rect(center=(constants.SCREEN_WIDTH/2,constants.SCREEN_HEIGHT/4)) self.title_speed = 0 self.joysticks = [] for i in range(0,pygame.joystick.get_count()): pygame.joystick.Joystick(i).init() self.joysticks.append(pygame.joystick.Joystick(i)) menu_off = [] menu_off.append(Art().get_image('versus_split_off')) #menu_off.append(Art().get_image('soccer_split_off')) #menu_off.append(Art().get_image('practice_red_off')) menu_off.append(Art().get_image('howToPlay_red_off')) menu_off.append(Art().get_image('credits_red_off')) menu_off.append(Art().get_image('quit_red_off')) menu_on = [] menu_on.append(Art().get_image('versus_split_on')) #menu_on.append(Art().get_image('soccer_split_on')) #menu_on.append(Art().get_image('practice_red_on')) menu_on.append(Art().get_image('howToPlay_red_on')) menu_on.append(Art().get_image('credits_red_on')) menu_on.append(Art().get_image('quit_red_on')), menu_rect = pygame.rect.Rect(0, constants.SCREEN_HEIGHT/2, constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT/2) self.main_menu = VerticalMenu(menu_rect,menu_off,menu_on) Music().play_repeat("title_music") self.background_image = Art().get_image("basketBallCourt_dark") font = pygame.font.SysFont('Calibri', 50, True, False) font2 = pygame.font.SysFont('Calibri', 30, True, False) self.game_title = font.render("Super Dodgeball 64",True,constants.BLACK) self.game_screen = font.render("Press spacebar to start the game.",True,constants.BLACK) self.credit_screen = font.render("Press c to go to the credits.",True,constants.BLACK) self.howtoplay_screen = font.render("How to play? Press v",True,constants.BLACK) def handle_keyboard_event(self, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.load_game_mode() elif event.key == pygame.K_j: Sound().play_ready_round() elif event.type == pygame.JOYBUTTONDOWN: for joystick in self.joysticks: if joystick.get_button(0): self.load_game_mode() elif event.type == pygame.MOUSEBUTTONDOWN: self.load_game_mode() self.main_menu.handle_event(event) def load_game_mode(self): index = self.main_menu.get_selected() if index == 0: # load versus Sound().play_sound("vs") LevelManager().load_level(ControllerScreen(0)) if index == 4: # load soccer #LevelManager.load_level(ControllerScreen(1)) Sound().play_sound("soccer") if pygame.joystick.get_count() == 0: LevelManager().load_level(ControllerScreen()) if pygame.joystick.get_count() >= 1: LevelManager().load_level(SoccerScreen()) if index == 5: # load practice Sound().play_sound("practice") LevelManager().load_level(ControllerScreen(2)) #pass if index == 1: # load howToPlay Sound().play_knowledge() LevelManager().load_level(HowtoplayScreen()) if index == 2: # load credits Sound().play_knowledge() LevelManager().load_level(CreditsScreen()) if index == 3: Sound().play_quit() pygame.time.wait(1200) LevelManager().leave_level() def update(self): #self.update_title_pos() self.main_menu.update() def update_title_pos(self): bound = constants.SCREEN_HEIGHT/4-80 self.title_speed += 1 self.title_rect.y += self.title_speed if self.title_rect.y > bound: self.title_rect.y = bound self.title_speed *= -1 def draw(self, screen): screen.fill(constants.WHITE) screen.blit(self.background_image, [0, 0]) screen.blit(self.title, self.title_rect) self.main_menu.draw(screen) #screen.blit(self.game_title, [(constants.SCREEN_WIDTH/2 - self.game_title.get_width()/2), (constants.SCREEN_HEIGHT/4)]) #screen.blit(self.game_screen, [0, (constants.SCREEN_HEIGHT - 150)]) #screen.blit(self.credit_screen, [0, (constants.SCREEN_HEIGHT - 100)]) #screen.blit(self.howtoplay_screen, [0, (constants.SCREEN_HEIGHT - 50)])
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,018
tienqpham/final-super-dodgeball-64
refs/heads/master
/test/template.py
import unittest import sys sys.path.append('..') from level_manager import * class test_(unittest.TestCase): def test_init(self): level_manager = LevelManager() self.assertTrue(True) if __name__ == '__main__': unittest.main()
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,019
tienqpham/final-super-dodgeball-64
refs/heads/master
/constants.py
SCREEN_WIDTH = 1600 SCREEN_HEIGHT = 900 KEYBOARD_PLAYER_SPEED = 15 JOYSTICK_PLAYER_SPEED = KEYBOARD_PLAYER_SPEED + 2 DEADZONE = .1 JOYSTICK_RETICLE_DISTANCE = 400 SHIELD_DISTANCE = 80 SHOT_SPEED = 30 SHOT_DELAY = 300 PROMPT_DELAY = 1750 WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) BLUE = (54,124,247) GREEN = (0,255,0) TRANSPARENT_COLOR = GREEN
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,020
tienqpham/final-super-dodgeball-64
refs/heads/master
/game_screen.py
import pygame import random import math import constants from level_manager import * from art import * from music import * from sound import * from keyboard_player import * from joystick_player import * from reticle import * from shield import * from ball import * from vertical_menu import * from timer import * class GameScreen(): def __init__(self, player1_control=-1, player2_control=0, round_num=0, rounds_won1=0, rounds_won2=0): self.final_round = 3 self.round_num = round_num self.rounds_won1 = rounds_won1 self.rounds_won2 = rounds_won2 timer_rect = pygame.rect.Rect(constants.SCREEN_WIDTH/2-56,10, 100,100) self.timer = Timer(timer_rect,60) self.timer.start() self.center_screen = [constants.SCREEN_WIDTH/2,constants.SCREEN_HEIGHT/2] self.gap = 100 pygame.mouse.set_visible(False) self.chaos_mode_on = False pause_on = [] pause_off = [] pause_on.append(Art().get_image('resume_on')) pause_on.append(Art().get_image('quit_on')) pause_off.append(Art().get_image('resume_off')) pause_off.append(Art().get_image('quit_off')) pause_rect = pygame.rect.Rect(constants.SCREEN_WIDTH/2 - pause_on[0].get_rect().size[0], constants.SCREEN_HEIGHT/2 - pause_on[1].get_rect().size[0], pause_on[0].get_rect().size[0]*2, pause_on[0].get_rect().size[1]*4) if player1_control == player2_control or \ (player1_control < 0 and player2_control < 0): raise ValueError("two players cannot share the same input device") self.pause_menu = VerticalMenu(pause_rect,pause_off,pause_on) if player1_control < 0: self.player1 = KeyboardPlayer(1) self.player2 = JoystickPlayer(2,player2_control) else: self.player1 = JoystickPlayer(1,player1_control) if player2_control < 0: self.player2 = KeyboardPlayer(2) else: self.player2 = JoystickPlayer(2, player2_control) Music().stop() Music().play_repeat("game_music") self.background_image = Art().get_image("basketBallCourt") self.player1_health_bar = Art().get_health_bar_image(1,"5") self.player2_health_bar = Art().get_health_bar_image(2,"5") self.timer_box = Art().get_image("timerFrame") font = pygame.font.SysFont('Calibri', 20, True, False) font2 = pygame.font.SysFont('Calibri', 40, True, False) self.gameover = font2.render("Gameover",True,constants.BLACK) self.p1_win_text = font2.render("Player 1 Wins!!!!",True,constants.RED) self.p2_win_text = font2.render("Player 2 Wins!!!!",True,constants.BLUE) self.draw_text = font2.render("DRAW GAME",True,constants.BLACK) self.temp = font.render("Work in progress",True,constants.BLACK) # every onscreen sprite must be added to this group self.all_sprites = pygame.sprite.Group() # sprites with distinct functionality # (red balls, neutral balls, etc) # should each have their own group self.blue_balls = pygame.sprite.Group() self.red_balls = pygame.sprite.Group() self.yellow_balls = pygame.sprite.Group() self.players = pygame.sprite.Group() self.reticles = pygame.sprite.Group() self.shields = pygame.sprite.Group() self.players.add(self.player1) self.players.add(self.player2) self.all_sprites.add(self.player1) self.all_sprites.add(self.player2) self.reticle1 = Reticle(0, 0, 1) # x, y, player number self.reticle2 = Reticle(0 ,0, 2) # x, y, player number self.last_shot = [pygame.time.get_ticks(), pygame.time.get_ticks()] self.reticles.add(self.reticle1) self.reticles.add(self.reticle2) self.all_sprites.add(self.reticle1) self.all_sprites.add(self.reticle2) self.shield1 = Shield(0,0,1) self.shield2 = Shield(0,0,2) self.shields.add(self.shield1) self.shields.add(self.shield2) self.all_sprites.add(self.shield1) self.all_sprites.add(self.shield2) self.paused = False self.started = False self.check = False self.time = pygame.time.get_ticks() self.game_over = False self.knockout = False self.player1_wins = False self.player2_wins = False self.draw_game = False self.announcements_over = False #self.generate_test_balls() def quit(self): pygame.joystick.quit() pygame.joystick.init() for i in range(pygame.joystick.get_count()): pygame.joystick.Joystick(i).init() Music().stop() Music().play_repeat("title_music") LevelManager().leave_level() def handle_keyboard_event(self, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: if not self.game_over: self.toggle_pause() else: self.quit() if event.key == pygame.K_SPACE and not self.game_over: if self.paused: if self.pause_menu.get_selected()==0: self.unpause() elif self.pause_menu.get_selected()==1: self.quit() elif event.type == pygame.JOYBUTTONDOWN: if not self.game_over: for player in self.players: if player.get_control() >= 0: if player.get_joystick().get_button(7): self.toggle_pause() elif player.get_joystick().get_button(0): if self.paused: if self.pause_menu.get_selected()==0: self.unpause() elif self.pause_menu.get_selected()==1: self.quit() elif player.get_joystick().get_button(5) or \ player.get_joystick().get_button(4): if not self.game_over and not self.paused: self.shoot(player.get_player_number()) print("player" + str(player.get_player_number()) + "shoots") elif event.type == pygame.MOUSEBUTTONDOWN: if not self.game_over and not self.paused: for player in self.players: if player.get_control() == -1: self.shoot(player.get_player_number()) print("player" + str(player.get_player_number()) + "shoots") self.player1.handle_event(event) self.player2.handle_event(event) if self.paused: self.pause_menu.handle_event(event) def who_is_winning(self): if self.player1.get_hit_points() > self.player2.get_hit_points(): return 1 elif self.player1.get_hit_points() < self.player2.get_hit_points(): return 2 else: return 0 def announce_round_end(self, screen): if pygame.time.get_ticks() > self.time + constants.PROMPT_DELAY*2: self.announcements_over = True if pygame.time.get_ticks() > self.time + constants.PROMPT_DELAY: # player # wins OR draw # player 1 wins if self.player1_wins: if not self.check: Sound().play_sound('player1wins') self.check = True img = Art().get_image('player1_wins') rect = img.get_rect(center = self.center_screen) screen.blit(img, rect) # player 2 wins elif self.player2_wins: if not self.check: Sound().play_sound('player2wins') self.check = True img = Art().get_image('player2_wins') rect = img.get_rect(center = self.center_screen) screen.blit(img, rect) # draw elif self.draw: if not self.check: Sound().play_sound('draw_game') self.check = True img = Art().get_image('draw_game') rect = img.get_rect(center = self.center_screen) screen.blit(img, rect) else: # knockout or time # time if self.timer.is_time_up(): img = Art().get_image('time') rect = img.get_rect(center = self.center_screen) screen.blit(img, rect) if self.check: Sound().play_time() self.check = False self.time = pygame.time.get_ticks() # knockout elif self.knockout: img = Art().get_image('knockout') rect = img.get_rect(center = self.center_screen) screen.blit(img, rect) if self.check: Sound().play_win() self.check = False self.time = pygame.time.get_ticks() def announce_round_start(self, screen): if pygame.time.get_ticks() > self.time + constants.PROMPT_DELAY*3: # round starts self.time = pygame.time.get_ticks() self.started = True elif pygame.time.get_ticks() >= self.time + constants.PROMPT_DELAY*2: # go if not self.check: Sound().play_go() self.check = True img = Art().get_image('go') rect = img.get_rect(center = self.center_screen) screen.blit(img, rect) elif pygame.time.get_ticks() >= self.time + constants.PROMPT_DELAY: # round # if self.check: Sound().play_round(self.round_num) self.check = False img = Art().get_round(str(self.round_num)) rect = img.get_rect(center = self.center_screen) screen.blit(img, rect) else: # ready? if not self.check: Sound().play_ready_round() self.check = True self.time = pygame.time.get_ticks() img = Art().get_image('ready') rect = img.get_rect(center = self.center_screen) screen.blit(img, rect) def update(self): print(str(self.check)) if self.started and not self.game_over and not self.paused: self.timer.update() self.update_reticles() self.update_shields() self.all_sprites.update() self.check_collisions() self.check_health() if self.timer.is_time_up() and not self.game_over: self.end_round() if self.paused: self.pause_menu.update() if self.announcements_over and self.game_over: #self.load_next_round() pass def end_round(self): self.game_over = True self.time = pygame.time.get_ticks() self.reticles.remove(self.reticle1) self.reticles.remove(self.reticle2) # player 1 wins if self.who_is_winning() == 1: self.player1_wins = True self.all_sprites.remove(self.player2) self.players.remove(self.player2) # player 2 wins elif self.who_is_winning() == 2: self.player2_wins = True self.all_sprites.remove(self.player1) self.players.remove(self.player1) # draw game else: self.draw_game = True if self.player1.get_hit_points() == 0 or \ self.player2.get_hit_points() == 0: self.knockout = True def load_next_round(self): if self.round_num == 0: # make the rematch/quit menu pass elif self.round_num >= 1: round_to_load = self.round_num + 1 if round_to_load == self.final_round: round_to_load = 0 LevelManager().leave_level() if self.player1_wins: self.rounds_won1 += 1 elif self.player2_wins: self.rounds_won2 += 1 elif self.draw: self.rounds_won1 += 1 self.rounds_won2 += 1 LevelManager().load(GameScreen(self.player1.get_control(), self.player2.get_control(), round_to_load, self.rounds_won1, self.rounds_won2)) def draw_background(self, screen): screen.fill(constants.WHITE) screen.blit(self.background_image, [0, 0]) screen.blit(self.timer_box, [(constants.SCREEN_WIDTH/2) - (self.timer_box.get_rect().size[0]/2), 0]) screen.blit(self.temp, [0,0]) def draw_health_bars(self, screen): screen.blit(self.player1_health_bar, [(constants.SCREEN_WIDTH/2 - self.player1_health_bar.get_width()) - self.gap, 5]) screen.blit(self.player2_health_bar, [((constants.SCREEN_WIDTH/2) + self.gap), 5]) def draw(self, screen): self.draw_background(screen) self.draw_health_bars(screen) self.timer.draw(screen) self.players.draw(screen) if not self.started: self.announce_round_start(screen) else: self.red_balls.draw(screen) self.blue_balls.draw(screen) self.yellow_balls.draw(screen) self.shields.draw(screen) self.reticles.draw(screen) #self.draw_gameover(screen) if self.paused and not self.game_over: self.pause_menu.draw(screen) if self.game_over: self.announce_round_end(screen) def draw_gameover(self, screen): if self.game_over == True: #screen.blit(self.gameover, [(constants.SCREEN_WIDTH/2 - self.gameover.get_width()/2), constants.SCREEN_HEIGHT/4]) if self.player1_wins == True: img = Art().get_image('player1_wins') rect = img.get_rect(center = self.center_screen) screen.blit(img, rect) #screen.blit(self.p1_win_text, [(constants.SCREEN_WIDTH/4 - self.p1_win_text.get_width()/2), constants.SCREEN_HEIGHT/4]) elif self.player2_wins == True: img = Art().get_image('player2_wins') rect = img.get_rect(center = self.center_screen) screen.blit(img, rect) #screen.blit(self.p2_win_text, [(((constants.SCREEN_WIDTH/4) * 3) - self.p2_win_text.get_width()/2), constants.SCREEN_HEIGHT/4]) elif self.draw_game: img = Art().get_image('draw_game') rect = img.get_rect(center = self.center_screen) screen.blit(img, rect) #draw_rect = self.draw_text.get_rect(center=(constants.SCREEN_WIDTH/2, constants.SCREEN_HEIGHT/2)) #screen.blit(self.draw_text, draw_rect) def print_pause_screen(self, screen): img = Art().get_image('paused') img.set_colorkey(constants.TRANSPARENT_COLOR) pos = [constants.SCREEN_WIDTH/2 - (img.get_rect().size[0]/2), constants.SCREEN_HEIGHT/2 - (img.get_rect().size[1]/2)] screen.blit(img, pos) def update_reticles(self): # player1 keyboard, player2 joystick if self.player1.get_control() == -1: self.reticle1.set_center(pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1]) self.reticle2.set_center((self.player2.get_joystick().get_axis(4) * constants.JOYSTICK_RETICLE_DISTANCE) + self.player2.get_center()[0], (self.player2.get_joystick().get_axis(3) * constants.JOYSTICK_RETICLE_DISTANCE) + self.player2.get_center()[1] ) # player1 joystick, player2 keyboard elif self.player2.get_control() == -1: self.reticle1.set_center((self.player1.get_joystick().get_axis(4) * constants.JOYSTICK_RETICLE_DISTANCE) + self.player1.get_center()[0], (self.player1.get_joystick().get_axis(3) * constants.JOYSTICK_RETICLE_DISTANCE) + self.player1.get_center()[1] ) self.reticle2.set_center(pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1]) # player1 joystick, player2 joystick elif self.player1.get_control >= 0 and \ self.player2.get_control >= 0: self.reticle1.set_center((self.player1.get_joystick().get_axis(4) * constants.JOYSTICK_RETICLE_DISTANCE) + self.player1.get_center()[0], (self.player1.get_joystick().get_axis(3) * constants.JOYSTICK_RETICLE_DISTANCE) + self.player1.get_center()[1] ) self.reticle2.set_center((self.player2.get_joystick().get_axis(4) * constants.JOYSTICK_RETICLE_DISTANCE) + self.player2.get_center()[0], (self.player2.get_joystick().get_axis(3) * constants.JOYSTICK_RETICLE_DISTANCE) + self.player2.get_center()[1] ) def update_shields(self): if True: d = [0,0] d[0] = self.reticle1.get_center()[0] - self.player1.get_center()[0] d[1] = self.reticle1.get_center()[1] - self.player1.get_center()[1] hypo = math.sqrt( math.pow(d[0],2) + math.pow(d[1],2) ) if hypo == 0: hypo = 0.1 relative_pos = [ d[0]/hypo * constants.SHIELD_DISTANCE, d[1]/hypo * constants.SHIELD_DISTANCE] self.shield1.set_center(self.player1.get_center()[0] + relative_pos[0], self.player1.get_center()[1] + relative_pos[1]) if True: d = [0,0] d[0] = self.reticle2.get_center()[0] - self.player2.get_center()[0] d[1] = self.reticle2.get_center()[1] - self.player2.get_center()[1] hypo = math.sqrt( math.pow(d[0],2) + math.pow(d[1],2) ) if hypo == 0: hypo = 0.1 relative_pos = [ d[0]/hypo * constants.SHIELD_DISTANCE, d[1]/hypo * constants.SHIELD_DISTANCE] self.shield2.set_center(self.player2.get_center()[0] + relative_pos[0], self.player2.get_center()[1] + relative_pos[1]) def check_collisions(self): #self.check_blue_on_blue() #self.check_red_on_red() self.check_blue_on_red() if self.chaos_mode_on : self.check_yellow_on_yellow() self.check_yellow_on_red() self.check_yellow_on_blue() self.check_shields() self.check_players() def check_shields(self): blue_hits = pygame.sprite.spritecollide(self.shield1, self.blue_balls, False) for ball in blue_hits: ball.set_speed(ball.get_speed()[0]*-1,ball.get_speed()[1]*-1) red_hits = pygame.sprite.spritecollide(self.shield2, self.red_balls, False) for ball in red_hits: ball.set_speed(ball.get_speed()[0]*-1,ball.get_speed()[1]*-1) def check_players(self): if not self.game_over: blue_hits = pygame.sprite.spritecollide(self.player1, self.blue_balls, True) yellow_hits = pygame.sprite.spritecollide(self.player1, self.yellow_balls, True) if len(blue_hits) > 0 or len(yellow_hits) > 0: self.player1.damage() red_hits = pygame.sprite.spritecollide(self.player2, self.red_balls, True) yellow_hits = pygame.sprite.spritecollide(self.player2, self.yellow_balls, True) if len(red_hits) > 0 or len(yellow_hits) > 0: self.player2.damage() def check_health(self): self.player1_health_bar = Art().get_health_bar_image(1,str(self.player1.get_hit_points())) if self.player1.get_hit_points() <= 0: if not self.game_over: self.end_round() self.player2_health_bar = Art().get_health_bar_image(2,str(self.player2.get_hit_points())) if self.player2.get_hit_points() <= 0: if not self.game_over: self.end_round() def can_shoot(self, player_number): if player_number == 1: return pygame.time.get_ticks() - self.last_shot[0] > constants.SHOT_DELAY elif player_number == 2: return pygame.time.get_ticks() - self.last_shot[1] > constants.SHOT_DELAY def shoot(self, player_number): if player_number == 1 and self.can_shoot(player_number): self.last_shot[0] = pygame.time.get_ticks() d = [0,0] d[0] = self.reticle1.get_center()[0] - self.player1.get_center()[0] d[1] = self.reticle1.get_center()[1] - self.player1.get_center()[1] hypo = math.sqrt( math.pow(d[0],2) + math.pow(d[1],2) ) if hypo == 0: hypo = 0.1 speed = [ d[0]/hypo * constants.SHOT_SPEED, d[1]/hypo * constants.SHOT_SPEED] #print(speed) newBall = RedBall(self.player1.get_pos()[0], self.player1.get_pos()[1], speed[0], speed[1]) newBall.set_center(self.player1.get_center()[0], self.player1.get_center()[1]) self.red_balls.add(newBall) self.all_sprites.add(newBall) Sound().play_sound("player_shooting") elif player_number == 2 and self.can_shoot(player_number): self.last_shot[1] = pygame.time.get_ticks() d = [0,0] d[0] = self.reticle2.get_center()[0] - self.player2.get_center()[0] d[1] = self.reticle2.get_center()[1] - self.player2.get_center()[1] hypo = math.sqrt( math.pow(d[0],2) + math.pow(d[1],2) ) if hypo == 0: hypo = 0.1 speed = [ d[0]/hypo * constants.SHOT_SPEED, d[1]/hypo * constants.SHOT_SPEED] #print(speed) newBall = BlueBall(self.player2.get_pos()[0], self.player2.get_pos()[1], speed[0], speed[1]) newBall.set_center(self.player2.get_center()[0], self.player2.get_center()[1]) self.blue_balls.add(newBall) self.all_sprites.add(newBall) Sound().play_sound("player_shooting") def combine_blue_ball(self, ball1, ball2): pos = [0,0] speed = [0,0] multi = 0 pos[0] += ball1.get_pos()[0]/2 pos[0] += ball2.get_pos()[0]/2 pos[1] += ball1.get_pos()[1]/2 pos[1] += ball2.get_pos()[1]/2 speed[0] += ball1.get_speed()[0] speed[0] += ball2.get_speed()[0] speed[1] += ball1.get_speed()[1] speed[1] += ball2.get_speed()[1] multi += ball1.get_multiplier() multi += ball2.get_multiplier() return BlueBall(pos[0], pos[1], speed[0], speed[1]) def combine_red_ball(self, ball1, ball2): pos = [0,0] speed = [0,0] multi = 0 pos[0] += ball1.get_pos()[0]/2 pos[0] += ball2.get_pos()[0]/2 pos[1] += ball1.get_pos()[1]/2 pos[1] += ball2.get_pos()[1]/2 speed[0] += ball1.get_speed()[0] speed[0] += ball2.get_speed()[0] speed[1] += ball1.get_speed()[1] speed[1] += ball2.get_speed()[1] multi += ball1.get_multiplier() multi += ball2.get_multiplier() return RedBall(pos[0], pos[1], speed[0], speed[1]) def combine_yellow_ball(self, ball1, ball2): pos = [0,0] speed = [0,0] multi = 0 pos[0] += ball1.get_pos()[0]/2 pos[0] += ball2.get_pos()[0]/2 pos[1] += ball1.get_pos()[1]/2 pos[1] += ball2.get_pos()[1]/2 speed[0] += ball1.get_speed()[0] speed[0] += ball2.get_speed()[0] speed[1] += ball1.get_speed()[1] speed[1] += ball2.get_speed()[1] multi += ball1.get_multiplier() multi += ball2.get_multiplier() return NeutralBall(pos[0], pos[1], speed[0], speed[1]) def check_blue_on_blue(self): for ball in self.blue_balls: self.blue_balls.remove(ball) self.all_sprites.remove(ball) collide = pygame.sprite.spritecollide(ball, self.blue_balls, True) if len(collide) == 0: self.blue_balls.add(ball) self.all_sprites.add(ball) elif len(collide) == 1: # call class method # pass collide[0] and ball newBall = self.combine_blue_ball(collide[0], ball) self.blue_balls.add(newBall) self.all_sprites.add(newBall) def check_red_on_red(self): for ball in self.red_balls: self.red_balls.remove(ball) self.all_sprites.remove(ball) collide = pygame.sprite.spritecollide(ball, self.red_balls, True) if len(collide) == 0: self.red_balls.add(ball) self.all_sprites.add(ball) elif len(collide) == 1: newBall = self.combine_red_ball(collide[0], ball) self.red_balls.add(newBall) self.all_sprites.add(newBall) def check_yellow_on_yellow(self): for ball in self.yellow_balls: self.yellow_balls.remove(ball) self.all_sprites.remove(ball) collide = pygame.sprite.spritecollide(ball, self.yellow_balls, True) if len(collide) == 0: self.yellow_balls.add(ball) self.all_sprites.add(ball) elif len(collide) == 1 and self.chaos_mode_on: newBall = self.combine_yellow_ball(collide[0], ball) self.yellow_balls.add(newBall) self.all_sprites.add(newBall) def check_blue_on_red(self): blue_collide = pygame.sprite.groupcollide(self.blue_balls, self.red_balls, False, False) red_collide = pygame.sprite.groupcollide(self.red_balls, self.blue_balls, True, True) if len(blue_collide) == 1 and len(red_collide) == 1 and self.chaos_mode_on: # call class method # pass in blue_collide[0] and red_collide[0] #newBall = self.combine_yellow_ball(blue_collide[0], red_collide[0]) speed = [0,0] pos = [0,0] multi = 0 for ball in blue_collide: pos[0] += ball.get_pos()[0]/2 pos[1] += ball.get_pos()[1]/2 speed[0] += ball.get_speed()[0] speed[1] += ball.get_speed()[1] multi += ball.get_multiplier() for ball in red_collide: pos[0] += ball.get_pos()[0]/2 pos[1] += ball.get_pos()[1]/2 speed[0] += ball.get_speed()[0] speed[1] += ball.get_speed()[1] multi += ball.get_multiplier() newBall = NeutralBall(pos[0], pos[1], speed[0], speed[1]) self.yellow_balls.add(newBall) self.all_sprites.add(newBall) Sound().play_sound("balls_colliding") def check_yellow_on_red(self): yellow_collide = pygame.sprite.groupcollide(self.yellow_balls, self.red_balls, False, False) red_collide = pygame.sprite.groupcollide(self.red_balls, self.yellow_balls, True, True) if len(yellow_collide) > 0 and len(red_collide) > 0: speed = [0,0] pos = [0,0] multi = 0 for ball in yellow_collide: pos[0] += ball.get_pos()[0]/2 pos[1] += ball.get_pos()[1]/2 speed[0] += ball.get_speed()[0] speed[1] += ball.get_speed()[1] multi += ball.get_multiplier() for ball in red_collide: pos[0] += ball.get_pos()[0]/2 pos[1] += ball.get_pos()[1]/2 speed[0] += ball.get_speed()[0] speed[1] += ball.get_speed()[1] multi += ball.get_multiplier() newBall = NeutralBall(pos[0], pos[1], speed[0], speed[1]) self.yellow_balls.add(newBall) self.all_sprites.add(newBall) Sound().play_sound("balls_colliding") def check_yellow_on_blue(self): yellow_collide = pygame.sprite.groupcollide(self.yellow_balls, self.blue_balls, False, False) blue_collide = pygame.sprite.groupcollide(self.blue_balls, self.yellow_balls, True, True) if len(yellow_collide) > 0 and len(blue_collide) > 0: speed = [0,0] pos = [0,0] multi = 0 for ball in yellow_collide: pos[0] += ball.get_pos()[0]/2 pos[1] += ball.get_pos()[1]/2 speed[0] += ball.get_speed()[0] speed[1] += ball.get_speed()[1] multi += ball.get_multiplier() for ball in blue_collide: pos[0] += ball.get_pos()[0]/2 pos[1] += ball.get_pos()[1]/2 speed[0] += ball.get_speed()[0] speed[1] += ball.get_speed()[1] multi += ball.get_multiplier() newBall = NeutralBall(pos[0], pos[1], speed[0], speed[1]) self.yellow_balls.add(newBall) self.all_sprites.add(newBall) Sound().play_sound("balls_colliding") def generate_test_balls(self): for i in range(3): x = random.randrange(0, constants.SCREEN_WIDTH) y = random.randrange(0, constants.SCREEN_HEIGHT) speed_x = random.randrange(-2, 3) speed_y = random.randrange(-2, 3) blueBall = BlueBall(x, y, speed_x, speed_y, 1) self.blue_balls.add(blueBall) self.all_sprites.add(blueBall) for i in range(3): x = random.randrange(0, constants.SCREEN_WIDTH) y = random.randrange(0, constants.SCREEN_HEIGHT) speed_x = random.randrange(-2, 3) speed_y = random.randrange(-2, 3) redBall = RedBall(x, y, speed_x, speed_y, 1) self.red_balls.add(redBall) self.all_sprites.add(redBall) #Pause methods def pause(self): self.paused = True self.pause_menu.reset(0) pygame.mouse.set_visible(True) def unpause(self): self.paused = False self.pause_menu.reset() pygame.mouse.set_visible(False) def is_paused(self): return self.paused def toggle_pause(self): if self.paused: self.unpause() else: self.pause()
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,021
tienqpham/final-super-dodgeball-64
refs/heads/master
/main.py
import pygame import constants from level_manager import * from title_screen import * from file import * from art import * from sound import * from music import * pygame.init() pygame.joystick.init() screen = pygame.display.set_mode([constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]) clock = pygame.time.Clock() level_manager = LevelManager() level_manager.load_level(TitleScreen()) file = File() art = Art() sound = Sound() music = Music() done = False # -------- Main Program Loop ----------- while not done: # get current level from level manager current_level = level_manager.get_current_level() # exit game if current level == None if current_level == None: break # game logic current_level.update() current_level.draw(screen) # draw pygame.display.flip() clock.tick(60) # control logic loop for event in pygame.event.get(): current_level.handle_keyboard_event(event) if event.type == pygame.QUIT: done = True break pygame.quit()
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,022
tienqpham/final-super-dodgeball-64
refs/heads/master
/file.py
import os import json import sys sys.path.append('..') class File: class __File: def __init__(self): self.config = json.load(open('data.json')) def get_objects(self): return list(self.config.keys()) def load(self, key): if key in self.config: return self.config[key]['path'] return ValueError('object not found') def get_data(self, key): path = self.get_path(key) if os.path.exists(path): return open(path).read() return ValueError('media not found') def reopen(self): self.config = json.load(open('data.json')) instance = None def __init__(self): if not File.instance: File.instance = File.__File() def __getattr__(self, name): return getattr(self.instance, name)
{"/manualtest_control_select.py": ["/constants.py", "/art.py", "/control_select.py"], "/music.py": ["/file.py"], "/test/test_keyboard_player.py": ["/constants.py", "/keyboard_player.py", "/art.py"], "/soccer_goal.py": ["/constants.py", "/art.py", "/actor.py"], "/soccer_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/ball.py", "/game_screen.py"], "/control_select.py": ["/constants.py", "/art.py"], "/player.py": ["/constants.py", "/art.py", "/actor.py"], "/shield.py": ["/constants.py", "/art.py", "/actor.py"], "/gameover_screen.py": ["/constants.py", "/art.py"], "/credit_screen.py": ["/constants.py", "/art.py"], "/sound.py": ["/file.py"], "/test/test_ball.py": ["/constants.py", "/actor.py", "/ball.py"], "/art.py": ["/constants.py", "/file.py"], "/test_timer.py": ["/timer.py"], "/controller_screen.py": ["/constants.py", "/art.py", "/control_select.py", "/game_screen.py", "/soccer_screen.py"], "/test/test_actor.py": ["/constants.py", "/actor.py"], "/ball.py": ["/constants.py", "/actor.py", "/art.py"], "/joystick_player.py": ["/constants.py", "/player.py"], "/timer.py": ["/constants.py", "/art.py"], "/test/test_reticle.py": ["/constants.py", "/reticle.py", "/art.py"], "/reticle.py": ["/constants.py", "/art.py", "/file.py", "/actor.py"], "/keyboard_player.py": ["/constants.py", "/player.py"], "/test/test_vertical_menu.py": ["/constants.py", "/vertical_menu.py", "/art.py"], "/test/test_player.py": ["/constants.py", "/player.py", "/art.py"], "/howtoplay_screen.py": ["/constants.py", "/music.py", "/art.py"], "/actor.py": ["/constants.py"], "/title_screen.py": ["/constants.py", "/credit_screen.py", "/game_screen.py", "/soccer_screen.py", "/controller_screen.py", "/howtoplay_screen.py", "/art.py", "/music.py", "/vertical_menu.py", "/sound.py"], "/game_screen.py": ["/constants.py", "/art.py", "/music.py", "/sound.py", "/keyboard_player.py", "/joystick_player.py", "/reticle.py", "/shield.py", "/ball.py", "/vertical_menu.py", "/timer.py"], "/main.py": ["/constants.py", "/title_screen.py", "/file.py", "/art.py", "/sound.py", "/music.py"]}
34,051
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils_ken/log/__init__.py
from .getlog import get_logger from .getlog import get_logger_console from .getlog import get_logger_file
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,052
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils/utils_filterobject.py
def filterSize(classesID, probs, rects, frame) : classesIDN = [] probsN = [] rectsN = [] (HI,WI) = frame.shape[0:2] wmax = WI // 3 hmax = HI // 3 for i, (x, y, w, h) in enumerate(rects) : if (w < wmax) and (h < hmax) : classesIDN.append(classesID[i]) probsN.append(probs[i]) rectsN.append(rects[i]) return classesIDN, probsN, rectsN
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,053
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils_ken/log/runlog.py
from getlog import get_logger from getlog import get_logger_console from getlog import get_logger_file import time import logging def run() : logname = 'runlog' logfile = 'run.log' runloger = get_logger_console(logname=logname) # runloger = get_logger_file(logname=logname, logfile=logfile) runloger.debug('start') runloger.debug('This is debug') def test() : # Create a custom logger logger = logging.getLogger('hello') # Create handlers c_handler = logging.StreamHandler() f_handler = logging.FileHandler('file.log') c_handler.setLevel(logging.ERROR) f_handler.setLevel(logging.ERROR) # Create formatters and add it to handlers c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s') f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') c_handler.setFormatter(c_format) f_handler.setFormatter(f_format) # Add handlers to the logger logger.addHandler(c_handler) logger.addHandler(f_handler) logger.warning('This is a warning') logger.error('This is an error') if __name__ == '__main__' : while(True) : time.sleep(1) print("start") # test() run()
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,054
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils/utils_color.py
import cv2 import os import cv2 import time import numpy as np COLOR_BLACK = (0, 0, 0) COLOR_WHITE = (255, 255, 255) COLOR_RED = (0, 0, 255) COLOR_RED1 = (0, 125, 255) COLOR_GREEN = (0, 255, 0) COLOR_BLUE = (255, 0, 0) COLOR_PURPLE = (255, 0, 255) COLOR_PURPLE1 = (255, 255, 0) COLOR_YELLOW = (0, 255, 255) COLOR_YELLOW1 = (255, 255, 0) COLOR_TABEL = [COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_PURPLE, COLOR_YELLOW] COLOR_TABEL_OB = np.random.uniform(100, 255, size=(100, 3)) # COLOR_TABEL_LINE = np.random.uniform(100, 250, size=(100, 3)) COLOR_TABEL_LINE = np.random.randint(100, high = 255, size = (100,3)).tolist() # COLOR_TABEL_OB = np.random.randint(100, high = 255, size = (100,3)).tolist() # COLOR_TABEL_OB = [COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_PURPLE, COLOR_YELLOW, COLOR_PURPLE1, COLOR_YELLOW1] COLOR_1 = (255, 100, 100) COLOR_2 = (100, 255, 100) COLOR_3 = (100, 100, 255) COLOR_4 = (255, 255, 100) COLOR_5 = (255, 100, 255) COLOR_6 = (100, 255, 255) def draw_object_tracking2(frame, ObjectTracker,label_t, color_id1) : # for object_track in ObjectTracker.currentObjects : color_id = int(str(object_track.objectID)[-2:]) # x, y, w, h = object_track.bbox x1, y1, x2, y2 = object_track.bbox ycenter = object_track.trace[-1][1] xcenter = object_track.trace[-1][0] # cv2.circle(frame, (xcenter, ycenter), 7, COLOR_YELLOW, -1) cv2.rectangle(frame, (x1, y1), (x2, y2),COLOR_TABEL_OB[color_id1], 2) label = "{}".format(label_t) labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.75, 1) top = max(y1, labelSize[1]) cv2.rectangle(frame, (x1 - 1, top - round(labelSize[1])), (x2+1, top ), COLOR_TABEL_OB[color_id1], cv2.FILLED) cv2.putText(frame, label, (x1, top), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.75, COLOR_BLACK, lineType=cv2.LINE_AA) return frame
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,055
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils/utils_label_xml.py
import os import cv2 import time import datetime import numpy as np def save_image(frame,image_url, cam_cfg_id) : date_folder = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S') ob_name = "f_{}_{}".format(cam_cfg_id, date_folder) jpg_name = "{}.jpg".format(ob_name) jpg_full = os.path.join(image_url,jpg_name) cv2.imwrite(jpg_full, frame) # log_record.info("Save Image : {}".format(jpg_full))
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,056
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utilslegend/utils_draw_2way.py
import numpy as np import cv2 from utilslegend.utils_color import COLOR_TABEL_LINE from utilslegend.utils_color import COLOR_TABEL_OB X0 = 30 Y0 = 30 d_row = 30 d_clo = 100 COLOR_WHITE = (255, 255, 255) COLOR_RED = (0, 0, 255) COLOR_GREEN = (0, 255, 0) COLOR_BLUE = (255, 0, 0) COLOR_PURPLE = (255, 0, 255) COLOR_YELLOW = (0, 255, 255) COLOR_YELLOW1 = (135, 255, 255) COLOR_YELLOW2 = (135, 135, 255) COLOR_TABEL = [COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_PURPLE, COLOR_YELLOW,COLOR_YELLOW1,COLOR_YELLOW2] def draw_no_object21() : label = "{}".format("C1 : motobike/bicycel C2 : Car") labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1) top = max(y, labelSize[1]) print("labelSize {}, baseLine {}".format(labelSize, baseLine)) cv2.rectangle(frame, (x - 1, top - round(labelSize[1])), (x+w+1, top ), (0, 255, 255), cv2.FILLED) cv2.putText(frame, label, (x, top), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,0), 1) # def draw_no_object2(frame ) : def draw_no_next_id(frame, per_id, motor_id, car_id, bus_id, truck_id, index) : cv2.putText(frame, "Next_ID", (X0 + 220 + index*3*d_clo + 3*d_clo ,Y0 ),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_LINE[index], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(per_id), (X0 + 220 + index*3*d_clo + 3*d_clo ,Y0 + 1*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[1], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(motor_id), (X0 + 220 + index*3*d_clo + 3*d_clo ,Y0 + 2*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[2], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(car_id), (X0 + 220 + index*3*d_clo + 3*d_clo ,Y0 + 3*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[3], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(bus_id), (X0 + 220 + index*3*d_clo + 3*d_clo ,Y0 + 4*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[4], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(truck_id), (X0 + 220 + index*3*d_clo + 3*d_clo ,Y0 + 5*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[5], 2, lineType=cv2.LINE_AA) # def draw_no_object2(frame ) : def draw_no_current(frame, per_id, motor_id, car_id, bus_id, truck_id, index) : cv2.putText(frame, "Currently", (X0 + 220 + index*4*d_clo + 3*d_clo ,Y0 ),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_LINE[index], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(per_id), (X0 + 220 + index*4*d_clo + 3*d_clo ,Y0 + 1*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[1], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(motor_id), (X0 + 220 + index*4*d_clo + 3*d_clo ,Y0 + 2*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[2], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(car_id), (X0 + 220 + index*4*d_clo + 3*d_clo ,Y0 + 3*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[3], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(bus_id), (X0 + 220 + index*4*d_clo + 3*d_clo ,Y0 + 4*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[4], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(truck_id), (X0 + 220 + index*4*d_clo + 3*d_clo ,Y0 + 5*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[5], 2, lineType=cv2.LINE_AA) # def draw_no_object2(frame ) : def draw_no_object(frame, per_up, per_down, motor_up, motor_down, car_up, car_down,bus_up, bus_down,truck_up, truck_down, index) : cv2.putText(frame, "Up", (X0 + 220 + index*3*d_clo ,Y0 ),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_LINE[index], 2, lineType=cv2.LINE_AA) cv2.putText(frame, "Down", (X0 + 220 + index*3*d_clo + d_clo ,Y0 ),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_LINE[index], 2, lineType=cv2.LINE_AA) cv2.putText(frame, "Sum", (X0 + 220 + index*3*d_clo + 2*d_clo ,Y0 ),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_LINE[index], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(per_up), (X0 + 220 + index*3*d_clo ,Y0 + 1*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[1], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(per_down), (X0 + 220 + index*3*d_clo + d_clo ,Y0 + 1*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[1], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(per_down + per_up), (X0 + 220 + index*3*d_clo + 2*d_clo ,Y0 + 1*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[1], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(motor_up), (X0 + 220 + index*3*d_clo ,Y0 + 2*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[2], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(motor_down), (X0 + 220 + index*3*d_clo + d_clo ,Y0 + 2*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[2], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(motor_up + motor_down), (X0 + 220 + index*3*d_clo + 2*d_clo,Y0 + 2*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[2], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(car_up), (X0 + 220 + index*3*d_clo ,Y0 + 3*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[3], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(car_down), (X0 + 220 + index*3*d_clo + d_clo ,Y0 + 3*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[3], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(car_up + car_down), (X0 + 220 + index*3*d_clo + 2*d_clo ,Y0 + 3*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[3], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(bus_up), (X0 + 220 + index*3*d_clo ,Y0 + 4*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[4], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(bus_down), (X0 + 220 + index*3*d_clo + d_clo ,Y0 + 4*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[4], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(bus_up + bus_down), (X0 + 220 + index*3*d_clo + 2*d_clo ,Y0 + 4*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[4], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(truck_up), (X0 + 220 + index*3*d_clo ,Y0 + 5*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[5], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(truck_down), (X0 + 220 + index*3*d_clo + d_clo ,Y0 + 5*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[5], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(truck_up + truck_down), (X0 + 220 + index*3*d_clo + 2*d_clo ,Y0 + 5*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[5], 2, lineType=cv2.LINE_AA) def draw_number_index(frame, index ) : text_index = '{}'.format(index) cv2.putText(frame, text_index, ((X0 + 220 + 5*d_clo ,Y0 + 5*d_row)), cv2.FONT_HERSHEY_SIMPLEX, 5, COLOR_TABEL_LINE[index], 5, lineType=cv2.LINE_AA) def draw_title(frame) : text_per = "person" text_mor = "motor_bicy" text_car = "car" text_bus = "bus" text_str = "truck" cv2.putText(frame, text_per, (X0,Y0 + 1*d_row),cv2.FONT_HERSHEY_SIMPLEX, 1, COLOR_TABEL_OB[1], 2, lineType=cv2.LINE_AA) cv2.putText(frame, text_mor, (X0,Y0 + 2*d_row),cv2.FONT_HERSHEY_SIMPLEX, 1, COLOR_TABEL_OB[2], 2, lineType=cv2.LINE_AA) cv2.putText(frame, text_car, (X0,Y0 + 3*d_row),cv2.FONT_HERSHEY_SIMPLEX, 1, COLOR_TABEL_OB[3], 2, lineType=cv2.LINE_AA) cv2.putText(frame, text_bus, (X0,Y0 + 4*d_row),cv2.FONT_HERSHEY_SIMPLEX, 1, COLOR_TABEL_OB[4], 2, lineType=cv2.LINE_AA) cv2.putText(frame, text_str, (X0,Y0 + 5*d_row),cv2.FONT_HERSHEY_SIMPLEX, 1, COLOR_TABEL_OB[5], 2, lineType=cv2.LINE_AA) if __name__ =='__main__' : # Create a black image img = np.zeros((200,800,3), np.uint8) draw_title(img) draw_no_object(img, 1,2,3454,4344,424,243,73,3,92,13,0) draw_no_next_id(img,122,43,54,45,345,0) draw_no_current(img,122,43,54,45,345,0) # img = cv2.resize(img, (600,100)) cv2.imshow('a',img) k = cv2.waitKey(0) # Press q to break # if k == ord('q'): # break
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,057
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utilslegend/utils_label_xml.py
import os import cv2 import time import datetime import numpy as np from pascal_voc_writer import Writer as WriterXML # from detectmodel.SSD_Utils import * from detectmodel.Yolo_Utils import * def save_image(frame,image_url, cam_cfg_id) : date_folder = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S') ob_name = "f_{}_{}".format(cam_cfg_id, date_folder) jpg_name = "{}.jpg".format(ob_name) jpg_full = os.path.join(image_url,jpg_name) cv2.imwrite(jpg_full, frame) # log_record.info("Save Image : {}".format(jpg_full)) def save_label_object(classes_id, rects, frame, camera_id, folderobject) : (H, W) = frame.shape[0:2] now = datetime.datetime.now() # date_folder = now.strftime('%Y-%m-%d') date_folder = now.strftime('%Y_%m_%d_%H_%M_%S') current_minute = datetime.datetime.now().minute ob_name = "f_{}_{}_{}".format(camera_id,date_folder,np.random.randint(100)) xml_name = "{}.xml".format(ob_name) jpg_name = "{}.jpg".format(ob_name) print("save : {}".format(xml_name)) xml_full = os.path.join(folderobject,xml_name) jpg_full = os.path.join(folderobject,jpg_name) writerXML = WriterXML(jpg_full,W, H) for index, (x,y, w, h) in enumerate(rects) : xmin = max(0, x) ymin = max(0, y) xmax = min(x + w , W) ymax = min(y + h , H) label_ob = "{}".format(LABELS[classes_id[index]]) writerXML.addObject(label_ob, xmin, ymin, xmax, ymax) # print(jpg_full) cv2.imwrite(jpg_full, frame) writerXML.save(xml_full)
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,058
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils_ken/video/runcam.py
import json import cv2 from recapvideostream import RecapVideoStream def main(cam_cfg) : cam_cfg["step"] = 2 caps = RecapVideoStream(cam_cfg) caps.start() while True: frame = caps.get_frame() cv2.imshow("frame", frame) k = cv2.waitKey(1) & 0xff if k == ord('q') : break caps.terminate() if __name__ =='__main__' : with open("config.json") as f : cfgs = json.load(f) cam_cfgs = cfgs['list_cam'] for i in range(len(cam_cfgs)) : main(cam_cfgs[i])
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,059
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils/utils_polygon.py
from shapely.geometry import Point, Polygon import cv2 import numpy as np from skimage.draw import line, polygon, circle, ellipse # func_note = '579,258,7,600,174,719,1266,719,1270,403,1056,253' from utils.utils_color import COLOR_TABEL_LINE from utils.utils_color import COLOR_TABEL_OB def decode_note_counter_line(func_note) : points = func_note.split(",") if len(points) != 8 : print(points) raise "Error Format len point of counter line" line = points[0:4] point = points[4:8] line = [int(float(x)) for x in line] point = [int(float(x)) for x in point] return line, point def decode_note_counter(func_note) : points = func_note.split(",") if len(points) != 4 : print(points) raise "Error Format len point of counter line" line = points[0:4] line = [int(float(x)) for x in line] return line def decode_note_polygon(func_note): point = func_note.split(",") point = [int(float(x)) for x in point] if len(point) % 2 != 0 : print(point) raise "Error Format len point of polygon" point = [tuple([point[i], point[i+1]]) for i in range(0, len(point), 2)] return point # def decode_take_integer(func_note): # point = func_note.split(",") # point = [int(x) for x in point] # if len(point) % 2 != 0 : # print(point) # raise "Error Format len point of polygon" # point = [tuple([point[i], point[i+1]]) for i in range(0, len(point), 2)] # return point class utils_popygon() : def __init__(self, coords) : self.polygon = Polygon(coords) def isinside(self, bbox) : x, y, w, h = bbox points = [] points.append(Point(x, y)) points.append(Point(x + w, y)) points.append(Point(x, y + h)) points.append(Point(x + w, y + h)) points.append(Point(x + w//2, y + h//2)) points.append(Point(x + w//2, y + h//4)) points.append(Point(x + w//4, y + h//2)) points.append(Point(x + w//4, y + h//4)) sum_point = 0 for point in points : if self.polygon.contains(point) : sum_point += 1 if sum_point >=2 : return True else : return False def filter_ob(self,classesid, probs, bboxes) : class_new = [] bbox_new = [] probs_new = [] for i, bbox in enumerate(bboxes) : if self.isinside(bbox) : class_new.append(classesid[i]) bbox_new.append(bboxes[i]) probs_new.append(probs[i]) return class_new, probs_new, bbox_new def draw_polygon(frame, coords,index=10) : for i in range(-1, len(coords) - 1) : cv2.line(frame, coords[i],coords[i+1], COLOR_TABEL_LINE[index], 2) # cv2.line(frame, tuple(coords[i]),tuple(coords[i+1]),(120, 300, 100), 2) return frame def draw_polygon_fill(frame, coords,index=10) : h, w, c = frame.shape rr, cc = polygon(coords[:,0], coords[:,1], (w, h, c)) frame[cc, rr] = COLOR_TABEL_LINE[index] # frame[cc, rr] = (100, 100, 100) return frame
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,060
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils/utils_mode_counter.py
COUNTER_ONEWAY1 = 1 COUNTER_ONEWAY2 = 2 COUNTER_ONEWAY3 = 3 COUNTER_ONEWAY4 = 4 POLYGON_FILTER = 5 COUNTER_ONEWAY_IDS = [COUNTER_ONEWAY1, COUNTER_ONEWAY2, COUNTER_ONEWAY3, COUNTER_ONEWAY4] POLYGON_COUNTER_IDS = [11, 12, 13, 14]
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,061
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils_ken/video/video_stream.py
''' start a thread capture frames save frames to redis server ''' import sys import traceback from queue import Queue from threading import Thread import threading import cv2 as cv import logging import datetime import time # sys.path.append('../') from utils_ken.log.getlog import get_logger log_cam = get_logger(logname="cam", logfile='./logs/cam.log') class VideoStream(): ''' Instance used to capture video's frames ''' def __init__(self, cam_url, step=3): ''' Initialize new object for capturing Args: cam_cfg -> dict: information of camera (camera id, camera address, process fps, ...) Return: None ''' self.__cam_addr = cam_url self.__step = step self.__frame_queue = Queue(maxsize=4) self.__stopped = False self.__stopped_lock = threading.Lock() def start(self): ''' Get the object started and create new thread to run Args: None Return: None ''' self.thread_c = Thread(target=self.__update, args=()) self.thread_c.daemon = True self.thread_c.start() # return self def __update(self): ''' Repeated grab new frame from Camera IP and run on another thread created before Args: None Return: None ''' while not self.get_stopped(): try: cnt = 0 # capture or recapture log_cam.info("Start capture video") capturer = cv.VideoCapture(self.__cam_addr) while not self.get_stopped() : success, frame = capturer.read() cnt +=1 if not success : log_cam.info("break to recapture ") time.sleep(10) break if cnt >= self.__step: # print(cnt) if self.__frame_queue.full(): self.__frame_queue.get() log_cam.info("queue full and waiting ") time.sleep(0.1) cnt = 0 log_cam.info("queue put ") self.__frame_queue.put(frame) # log_cam.info('Cam : {} break Reconnection '.format(self.__cam_id)) while not self.__frame_queue.empty() : self.__frame_queue.get() except Exception as ex: traceback.print_exc() traceback.print_tb(ex.__traceback__) log_cam.info("Cam lose connection") # capturer.release() finally: capturer.release() log_cam.info('Cam release Reconnection ') while not self.__frame_queue.empty(): self.__frame_queue.get() log_cam.info('Cam is Stoped') def stop(self): ''' stop the camera thread ''' self.__stopped_lock.acquire() self.__stopped = True self.__stopped_lock.release() while not self.__frame_queue.empty(): self.__frame_queue.get() time_close = datetime.datetime.now() # log_cam.info("Join Thread capture at at {}:{}".format(time_close.hour,time_close.minute)) # self.thread_c.join() log_cam.info("Cam terminateed ") def get_stopped(self): ''' return true if thread need to stop, false if vice versa ''' self.__stopped_lock.acquire() stopped = self.__stopped self.__stopped_lock.release() return stopped def read(self): ''' Read a frame from Queue and return Args: None Return: frame -> np.array((H, W, 3) ): frame from Camera if available otherwise None ''' log_cam.info("queue get ") return self.__frame_queue.get()
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,062
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils/CheckSideUtils.py
class CheckSideLine : def __init__(self, line, point1, point2) : self.__line = self.__lineFrompoint(line[:2],line[2:]) self.point1 = point1 self.point2 = point2 self.distp1 = self.__distance(self.point1) self.distp2 = self.__distance(self.point2) def __lineFrompoint(self,P, Q) : # print(Q) # print(P) line = [] a = Q[1] - P[1] b = P[0] - Q[0] c = a*(P[0]) + b*(P[1]) # if(b < 0): # print("The line passing through points P:", P ,"and Q", Q ," is:", # a ,"x ",b ,"y = ",c ,"\n") # else: # print("The line passing through points P:", P ,"and Q", Q ," is:", # a ,"x + " ,b ,"y = ",c ,"\n") line.append(a) line.append(b) line.append(c) return line def __distance(self, point) : distance = self.__line[0]*point[0] + self.__line[1]*point[1] - self.__line[2] return distance def inside(self, point) : """ Args : Point to check Return : True if point inside line Fale if point outside line """ distpc1 = self.__distance(point) inside = self.__same_side(self.distp2, distpc1) return inside def check_right(self,pc1, pc2) : """ Args : point1, point2 is point tracking Return : True if from outsite to inside """ distpc1 = self.__distance(pc1) distpc2 = self.__distance(pc2) is_right = self.__same_side(self.distp1, distpc1) and self.__same_side(self.distp2, distpc2) # print("is_right : {}".format(is_right)) return is_right def check_lelf(self,pc1, pc2) : distpc1 = self.__distance(pc1) distpc2 = self.__distance(pc2) is_lelf = self.__same_side(self.distp1, distpc2) and self.__same_side(self.distp2, distpc1) # print("is_lelf : {}".format(is_lelf)) return is_lelf def not_same_side(self,pc1, pc2) : distpc1 = self.__distance(pc1) distpc2 = self.__distance(pc2) is_lelf = self.__same_side(distpc1, distpc2) # print("is_lelf : {}".format(is_lelf)) return not is_lelf def __same_side(self, dist1, dist2) : # print("dist1 * dist2 : {}".format(dist1 * dist2)) return True if (dist1 * dist2) > 0 else False
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,063
edigomes/jetson_people_counter_head_detection
refs/heads/master
/detectmodel/setting.py
# engine RUN_MODE_THREAD = False RESIZE_FACTOR = 0.5 DISPLAY_DETECT_FRAME_ONLY = False DISPLAY_TRACK_INDEX = False SAVE_VIDEO = True # detector DETECT_ENABLE = True DETECTION_THRESHOLD = 0.1 # tracker TRACKER_THRESHOLD_DISTANCE = 100 # 90 TRACKER_BUFFER_LENGTH = 100 TRACKER_KEEP_LENGTH = 5 DISTANCE_MARGIN_IN = 20 DISTANCE_MARGIN_OUT = -10 DISTANCE_THRESHOLD = 50
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,064
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils_machine.py
ROOT_PATH = '.' excels_output = '{}/output/excel_export'.format(ROOT_PATH) videos_output = '{}/output/videos'.format(ROOT_PATH) images_output = '{}/output/image_xml'.format(ROOT_PATH) # tree folder in local machine COMPUTER_ID = 7 COMPUTER_NAME = "Legend_raspberry"
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,065
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils/utils_counter.py
from utils.CheckSideUtils import CheckSideLine from shapely.geometry import Point, Polygon class Counter_Polygon() : def __init__(self, coords, maxlist = 100) : self.point_polygon = coords self.polygon = Polygon(coords) self.counter = 0 self.listObject = [] self.maxlist = maxlist def isinside(self, bbox) : x, y, w, h = bbox points = [] points.append(Point(x, y)) points.append(Point(x + w, y)) points.append(Point(x, y + h)) points.append(Point(x + w, y + h)) sum_point = 0 for point in points : if self.polygon.contains(point) : sum_point += 1 if sum_point >= 2 : return True else : return False def update(self, trackerlist) : for object_track in trackerlist : (x, y, w, h) = object_track.bbox y_feet = y + h//2 x_center = x + w//2 if (object_track.objectID not in self.listObject) : # if(self.polygon.contains(Point(x_center, y_feet))) : # if(self.isinside(object_track.bbox)) : if(self.isinside(object_track.bbox)) and object_track.appeared >= 5: self.counter +=1 self.listObject.append(object_track.objectID) # print("polygon :{}".format(object_track.objectID)) self.clean_track() # print('left : {}, right : {}'.format(self.counterRL,self.counterLR)) def get_counter(self) : # save counter object in current counter_ob = self.counter # clearn object save return counter_ob def get_counter_and_clean(self) : # save counter object in current counter_ob = self.counter # clearn object save self.counter = 0 return counter_ob def clean_track(self) : # clearn object tracking in list counter if len(self.listObject) > self.maxlist : for i in range(len(self.listObject) - self.maxlist) : del self.listObject[0] # clearn object tracking in list counter def clean(self) : self.counter = 0 self.listObject = [] # this class will counter two way of utils # --------------------------------------------------------------------------- # Counter Object in two way # --------------------------------------------------------------------------- class Counter_Line2Way() : def __init__(self, line, points) : self.point_line = line self.line = CheckSideLine(line=line,point1=points[0:2], point2=points[2:4]) self.counterLR = 0 self.listLR = [] self.counterRL = 0 self.listRL = [] self.maxlist = 2 def isinside(self, point) : x1_line, y1_line = self.point_line[:2] x2_line, y2_line = self.point_line[2:] x_min = min(x1_line,x2_line) x_max = max(x1_line,x2_line) y_min = min(y1_line,y2_line) y_max = max(y1_line,y2_line) x, y = point # print("x_min :{} x_max : {}".format(x_min, x_max)) # print("y_min :{} y_max : {}".format(y_min, y_max)) # print("x : {}, y :{}".format(x,y)) if (x > x_min and x < x_max) or (y > y_min and y < y_max) : # print("isinside") return True else : # print("not isinside") return False def update(self, trackerlist) : light_trackid = [] light_aciton = [] for object_track in trackerlist : # if (object_track.objectID not in self.listLR) and len(object_track.trace) > 2 and self.isinside(object_track.trace[-1]): if len(object_track.trace) > 2 and (object_track.objectID not in self.listLR) : # if len(object_track.trace) > 2 : if self.line.check_right(object_track.trace[-2], object_track.trace[-1]) : # if self.line.check_right(object_track.trace[-2], object_track.trace[-1]) and self.line.not_same_side(object_track.trace[-3], object_track.trace[-1]): self.counterLR +=1 self.listLR.append(object_track.objectID) light_trackid.append(object_track.objectID) light_aciton.append('in') # print("LR :{}".format(object_track.objectID)) for object_track in trackerlist : # if len(object_track.trace) > 2 and self.isinside(object_track.trace[-1]): # if (object_track.objectID not in self.listRL) and len(object_track.trace) > 2 and self.isinside(object_track.trace[-1]): if len(object_track.trace) > 2 and (object_track.objectID not in self.listRL) : # if len(object_track.trace) > 2 : if self.line.check_lelf(object_track.trace[-2], object_track.trace[-1]) : # if self.line.check_lelf(object_track.trace[-2], object_track.trace[-1]) and self.line.not_same_side(object_track.trace[-3], object_track.trace[-1]): self.counterRL +=1 self.listRL.append(object_track.objectID) light_trackid.append(object_track.objectID) light_aciton.append('out') # print("RL : {}".format(object_track.objectID)) self.clean_track() # print('left : {}, right : {}'.format(self.counterRL,self.counterLR)) return light_trackid, light_aciton def get_counter(self) : # save counter object in current counter_LR = self.counterLR counter_RL = self.counterRL # clearn object save return counter_LR, counter_RL def get_counter_and_clean(self) : # save counter object in current counter_LR = self.counterLR counter_RL = self.counterRL # clearn object save self.counterLR = 0 self.counterRL = 0 return counter_LR, counter_RL def clean_track(self) : # clearn object tracking in list counter if len(self.listLR) > self.maxlist : for i in range(len(self.listLR) - self.maxlist) : del self.listLR[0] # clearn object tracking in list counter if len(self.listRL) > self.maxlist : for i in range(len(self.listRL) - self.maxlist) : del self.listRL[0] def clean(self) : self.counterLR = 0 self.counterRL = 0 self.listLR = [] self.listRL = []
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,066
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils/utils_draw_2way.py
import numpy as np import cv2 from utils.utils_color import COLOR_TABEL_LINE from utils.utils_color import COLOR_TABEL_OB X0 = 30 Y0 = 30 d_row = 35 d_clo = 70 COLOR_WHITE = (255, 255, 255) COLOR_RED = (0, 0, 255) COLOR_GREEN = (0, 255, 0) COLOR_BLUE = (255, 0, 0) COLOR_PURPLE = (255, 0, 255) COLOR_YELLOW = (0, 255, 255) COLOR_YELLOW1 = (135, 255, 255) COLOR_YELLOW2 = (135, 135, 255) COLOR_TABEL = [COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_PURPLE, COLOR_YELLOW,COLOR_YELLOW1,COLOR_YELLOW2] def draw_no_object(frame,obiect_index, per_up, per_down, index) : cv2.putText(frame, "frontward", (X0 + 3*d_clo ,Y0 ),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_LINE[1], 2, lineType=cv2.LINE_AA) cv2.putText(frame, "backward", (X0 + 4*d_clo + d_clo ,Y0 ),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_LINE[1], 2, lineType=cv2.LINE_AA) cv2.putText(frame, obiect_index, (X0 ,Y0 + 40 + index*d_row),cv2.FONT_HERSHEY_SIMPLEX, 1, COLOR_TABEL_OB[index], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(per_up), (X0 + 3*d_clo ,Y0 + 40 + index*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[index], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(per_down), (X0 + 4*d_clo + d_clo ,Y0 + 40 + index*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[index], 2, lineType=cv2.LINE_AA) def draw_no_object_zone(frame,obiect_index, counter_no, index) : cv2.putText(frame, "counter", (X0 + 3*d_clo ,Y0 ),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_LINE[1], 2, lineType=cv2.LINE_AA) cv2.putText(frame, obiect_index, (X0 ,Y0 + 40 + index*d_row),cv2.FONT_HERSHEY_SIMPLEX, 1, COLOR_TABEL_OB[index], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(counter_no), (X0 + 3*d_clo ,Y0 + 40 + index*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[index], 2, lineType=cv2.LINE_AA) if __name__ =='__main__' : # Create a black image img = np.zeros((200,800,3), np.uint8) draw_title(img) draw_no_object(img, 1,2,3454,4344,424,243,73,3,92,13,0) draw_no_next_id(img,122,43,54,45,345,0) draw_no_current(img,122,43,54,45,345,0) # img = cv2.resize(img, (600,100)) cv2.imshow('a',img) k = cv2.waitKey(0) # Press q to break # if k == ord('q'): # break
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,067
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utilslegend/utils_draw_polygon.py
import numpy as np import cv2 from utilslegend.utils_color import COLOR_TABEL_LINE from utilslegend.utils_color import COLOR_TABEL_OB X0 = 30 Y0 = 30 d_row = 30 d_clo = 100 COLOR_WHITE = (255, 255, 255) COLOR_RED = (0, 0, 255) COLOR_GREEN = (0, 255, 0) COLOR_BLUE = (255, 0, 0) COLOR_PURPLE = (255, 0, 255) COLOR_YELLOW = (0, 255, 255) COLOR_YELLOW1 = (135, 255, 255) COLOR_YELLOW2 = (135, 135, 255) COLOR_TABEL = [COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_PURPLE, COLOR_YELLOW,COLOR_YELLOW1,COLOR_YELLOW2] def draw_no_object21() : label = "{}".format("C1 : motobike/bicycel C2 : Car") labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1) top = max(y, labelSize[1]) print("labelSize {}, baseLine {}".format(labelSize, baseLine)) cv2.rectangle(frame, (x - 1, top - round(labelSize[1])), (x+w+1, top ), (0, 255, 255), cv2.FILLED) cv2.putText(frame, label, (x, top), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,0), 1) # def draw_no_object2(frame ) : def draw_no_next_id(frame, per_id, motor_id, car_id, bus_id, truck_id, index) : cv2.putText(frame, "Next_ID", (X0 + 220 + 1*d_clo ,Y0 ),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_LINE[index], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(per_id), (X0 + 220 + 1*d_clo ,Y0 + 1*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[1], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(motor_id), (X0 + 220 + 1*d_clo ,Y0 + 2*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[2], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(car_id), (X0 + 220 + 1*d_clo ,Y0 + 3*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[3], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(bus_id), (X0 + 220 + 1*d_clo ,Y0 + 4*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[4], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(truck_id), (X0 + 220 + 1*d_clo ,Y0 + 5*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[5], 2, lineType=cv2.LINE_AA) # def draw_no_object2(frame ) : def draw_no_current(frame, per_id, motor_id, car_id, bus_id, truck_id, index) : cv2.putText(frame, "Currently", (X0 + 220 + 2*d_clo ,Y0 ),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_LINE[index], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(per_id), (X0 + 220 + 2*d_clo ,Y0 + 1*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[1], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(motor_id), (X0 + 220 + 2*d_clo ,Y0 + 2*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[2], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(car_id), (X0 + 220 + 2*d_clo ,Y0 + 3*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[3], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(bus_id), (X0 + 220 + 2*d_clo ,Y0 + 4*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[4], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(truck_id), (X0 + 220 + 2*d_clo ,Y0 + 5*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[5], 2, lineType=cv2.LINE_AA) # def draw_no_object2(frame ) : def draw_no_object(frame, per_up, motor_up, car_up, bus_up, truck_up, index) : cv2.putText(frame, "No", (X0 + 220 ,Y0 ),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_LINE[index], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(per_up), (X0 + 220 ,Y0 + 1*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[1], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(motor_up), (X0 + 220 ,Y0 + 2*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[2], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(car_up), (X0 + 220 ,Y0 + 3*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[3], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(bus_up), (X0 + 220 ,Y0 + 4*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[4], 2, lineType=cv2.LINE_AA) cv2.putText(frame, str(truck_up), (X0 + 220 ,Y0 + 5*d_row),cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_TABEL_OB[5], 2, lineType=cv2.LINE_AA) def draw_title(frame) : text_per = "person" text_mor = "motor" text_car = "car" text_bus = "bus" text_str = "truck" cv2.putText(frame, text_per, (X0,Y0 + 1*d_row),cv2.FONT_HERSHEY_SIMPLEX, 1, COLOR_TABEL_OB[1], 2, lineType=cv2.LINE_AA) cv2.putText(frame, text_mor, (X0,Y0 + 2*d_row),cv2.FONT_HERSHEY_SIMPLEX, 1, COLOR_TABEL_OB[2], 2, lineType=cv2.LINE_AA) cv2.putText(frame, text_car, (X0,Y0 + 3*d_row),cv2.FONT_HERSHEY_SIMPLEX, 1, COLOR_TABEL_OB[3], 2, lineType=cv2.LINE_AA) cv2.putText(frame, text_bus, (X0,Y0 + 4*d_row),cv2.FONT_HERSHEY_SIMPLEX, 1, COLOR_TABEL_OB[4], 2, lineType=cv2.LINE_AA) cv2.putText(frame, text_str, (X0,Y0 + 5*d_row),cv2.FONT_HERSHEY_SIMPLEX, 1, COLOR_TABEL_OB[5], 2, lineType=cv2.LINE_AA) def draw_number_index(frame, index ) : text_index = '{}'.format(index) cv2.putText(frame, text_index, ((X0 + 220 + 1*d_clo ,Y0 + 4*d_row)), cv2.FONT_HERSHEY_SIMPLEX, 5, COLOR_TABEL_LINE[index], 5, lineType=cv2.LINE_AA) if __name__ =='__main__' : # Create a black image img = np.zeros((200,600,3), np.uint8) draw_title(img) draw_no_object(img, 1,3454,424,73,92,0) draw_no_next_id(img,122,43,54,45,345,0) draw_no_current(img,122,43,54,45,345,0) draw_number_index(img,0) # img = cv2.resize(img, (600,100)) cv2.imshow('a',img) k = cv2.waitKey(0) # Press q to break # if k == ord('q'): # break
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,068
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils/utils_save_video.py
import os import cv2 import numpy as np import datetime import threading from utils_ken.log.getlog import get_logger """ This class will save small video at event have object action """ # ID for human log_video = get_logger('video_write','./logs/video_write.log') class SaveVideoHour : def __init__(self,url_folder, cam_id, No_Frame_Flow=60*15*20) : self.cam_id = cam_id self.url = url_folder self._write = None self.No_Frame_Flow = No_Frame_Flow self.writing = False self.counterSkip = 0 self.hour_record = -1 def __create_writer(self) : now = datetime.datetime.now() # date_folder = now.strftime('%Y-%m-%d') date_folder = now.strftime('%Y_%m_%d_%H_%M_%S') # Name folder video # folder_save = os.path.join(head_folder,date_folder) folder_save = self.url self.hour_record = now.hour # video_name = 'cam_{}_{}.avi'.format(date_folder,self.cam_id,np.random.randint(100)) video_name = '{}_cam_{}.avi'.format(date_folder,self.cam_id) self.video_url = os.path.join(folder_save, video_name) log_video.info("Create video : {}".format(self.video_url)) if not os.path.exists(folder_save) : log_video.info("os.makedirs : {}".format(folder_save)) os.makedirs(folder_save) # for save small size fourcc = cv2.VideoWriter_fourcc(*"MJPG") # for save youtube live # fourcc = cv2.VideoWriter_fourcc(*"MJPG") writer = cv2.VideoWriter(self.video_url, fourcc, 15,(1280, 720), True) return writer def update(self, frame) : current_hour = datetime.datetime.now().hour frame = cv2.resize(frame, (1280, 720)) if self.writing is False and current_hour != self.hour_record : self.writing = True if self.writing is True : if self._write is None : self._write = self.__create_writer() self._write.write(frame) self.counterSkip = 0 if self._write is not None : # frame = cv2.resize(frame, (1280, 720)) self._write.write(frame) self.counterSkip += 1 if current_hour != self.hour_record : self._write.release() log_video.info("release video ") # post_video(self.video_url) self.writing = False self._write = None def update1(self, frame) : thread = threading.Thread(target=self._update, args=(frame,)) thread.daemon = True thread.start() def run() : url = 'rtsp://user1:123456a@@374xd.vncctv.info//cam/realmonitor?channel=3&subtype=0' video_5minute = '/home/ken/workspace/nano_package/video_5minute' write = SaveVideoHour(video_5minute) video_cap = cv2.VideoCapture(url) while True : _,frame = video_cap.read() write.update(frame) if __name__ =='__main__' : run()
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,069
edigomes/jetson_people_counter_head_detection
refs/heads/master
/clear_video.py
import sys sys.path.append('../') import os import logging import datetime from utils_machine import videos_output from utils_ken.log.getlog import get_logger logging.basicConfig(level=logging.INFO, format='%(asctime)-12s : %(name)-5s : [%(levelname)-5s] : %(message)5s') clear_video = get_logger('clear_video_', './logs/clear_video_.log') # ROOT_PATH = '/home/ken/workspace/nano_package' # ------------------------------------------------------------------------------------ # pose video recored to server # ------------------------------------------------------------------------------------ def get_size(start_path): total_size = 0 list_file = [] for dirpath, dirnames, filenames in os.walk(start_path): for f in filenames: # print(filenames) fp = os.path.join(dirpath, f) # skip if it is symbolic link if not os.path.islink(fp): list_file.append(fp) total_size += os.path.getsize(fp) size_gibike = int(total_size/(1024*1024*1024)) list_file.sort() return size_gibike, list_file def main_processing(video_folder, max_size=10) : size_gibike, list_file = get_size(video_folder) clear_video.info('foldel : {} total size : {} Gb'.format(video_folder, size_gibike)) for file_1 in list_file : clear_video.info(file_1) # try : if len(list_file) > 0 : last_file = list_file[0] if size_gibike >= max_size : clear_video.info('deleted file'.format(last_file)) os.remove(last_file) # except : # clear_video.info('folder empty'.format(video_folder)) if __name__ == '__main__' : # main_processing(video_folder = './a') main_processing(video_folder = videos_output)
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,070
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils_ken/log/getlog.py
import sys import logging from logging.handlers import TimedRotatingFileHandler FORMATLOG = logging.Formatter('%(asctime)-12s : %(name)-5s : [%(levelname)-5s] : %(message)5s') # setup console logger def get_console_handler() : console_handler = logging.StreamHandler() console_handler.setFormatter(FORMATLOG) return console_handler def get_file_handler(logfile) : file_hander = TimedRotatingFileHandler(logfile, when="midnight",interval=1, backupCount=10) file_hander.setFormatter(FORMATLOG) # file_hander.setLevel(logging.INFO) return file_hander # # logname, logfile to save model # def get_logger(logname, logfile) : logger = logging.getLogger(logname) logger.setLevel(logging.DEBUG) logger.addHandler(get_console_handler()) logger.addHandler(get_file_handler(logfile)) # with this pattern, it's rarely necessary to propagate the error up to paren logger.propagate = False return logger def get_logger_console(logname) : logger = logging.getLogger(logname) logger.setLevel(logging.DEBUG) logger.addHandler(get_console_handler()) return logger def get_logger_file(logname, logfile) : logger = logging.getLogger(logname) logger.setLevel(logging.DEBUG) logger.addHandler(get_file_handler(logfile)) # with this pattern, it's rarely necessary to propagate the error up to paren logger.propagate = False return logger
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,071
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utilslegend/utils_mode_counter.py
COUNTER_ONEWAY1 = 1 COUNTER_ONEWAY2 = 5 COUNTER_ONEWAY3 = 6 COUNTER_ONEWAY4 = 7 COUNTER_TWOWAY1 = 5 COUNTER_TWOWAY2 = 9 COUNTER_TWOWAY3 = 10 COUNTER_TWOWAY4 = 11 COUNTER_ONEWAY_IDS = [COUNTER_ONEWAY1, COUNTER_ONEWAY2, COUNTER_ONEWAY3, COUNTER_ONEWAY4] COUNTER_TWOWAY_IDS = [COUNTER_TWOWAY1, COUNTER_TWOWAY2, COUNTER_TWOWAY3, COUNTER_TWOWAY4] HEAT_MAPS = 2 POLYGON_FILTER = 4 POLYGON_COUNTER1 = 12 POLYGON_COUNTER2 = 13 POLYGON_COUNTER3 = 14 POLYGON_COUNTER4 = 15 POLYGON_COUNTER_IDS =[POLYGON_COUNTER1, POLYGON_COUNTER2, POLYGON_COUNTER3, POLYGON_COUNTER4]
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,072
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utilslegend/utils_polygon.py
from shapely.geometry import Point, Polygon import cv2 import numpy as np from skimage.draw import line, polygon, circle, ellipse # func_note = '579,258,7,600,174,719,1266,719,1270,403,1056,253' from utilslegend.utils_color import COLOR_TABEL_LINE from utilslegend.utils_color import COLOR_TABEL_OB def decode_note_counter_line(func_note) : points = func_note.split(",") if len(points) != 8 : print(points) raise "Error Format len point of counter line" line = points[0:4] point = points[4:8] line = [int(x) for x in line] point = [int(x) for x in point] return line, point def decode_note_polygon(func_note): point = func_note.split(",") point = [int(x) for x in point] if len(point) % 2 != 0 : print(point) raise "Error Format len point of polygon" point = [tuple([point[i], point[i+1]]) for i in range(0, len(point), 2)] return point class utils_popygon() : def __init__(self, coords) : self.polygon = Polygon(coords) def isinside(self, bbox) : x, y, w, h = bbox points = [] points.append(Point(x, y)) points.append(Point(x + w, y)) points.append(Point(x, y + h)) points.append(Point(x + w, y + h)) sum_point = 0 for point in points : if self.polygon.contains(point) : sum_point += 1 if sum_point >=2 : return True else : return False def filter_ob(self,classesid, probs, bboxes) : class_new = [] bbox_new = [] probs_new = [] for i, bbox in enumerate(bboxes) : if self.isinside(bbox) : class_new.append(classesid[i]) bbox_new.append(bboxes[i]) probs_new.append(probs[i]) return class_new, probs_new, bbox_new def draw_polygon(frame, coords,index=10) : for i in range(-1, len(coords) - 1) : cv2.line(frame, coords[i],coords[i+1], COLOR_TABEL_LINE[index], 2) # cv2.line(frame, tuple(coords[i]),tuple(coords[i+1]),(120, 300, 100), 2) return frame def draw_polygon_fill(frame, coords,index=10) : h, w, c = frame.shape rr, cc = polygon(coords[:,0], coords[:,1], (w, h, c)) frame[cc, rr] = COLOR_TABEL_LINE[index] # frame[cc, rr] = (100, 100, 100) return frame def main() : import cv2 frame = np.zeros((800, 800, 3), 'uint8') poly = np.array(( (300 , 300), (320 ,480), (430 ,380), (590 ,220), (300 , 300), )) draw_polygon_fill(frame, poly) draw_polygon(frame, poly) cv2.imshow('iamge', frame) cv2.waitKey() if __name__ == '__main__' : main()
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,073
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utils_excel/utils_excel.py
import os import sys sys.path.append('../') import datetime from openpyxl import Workbook from openpyxl import load_workbook from utils_ken.log.getlog import get_logger from utilslegend.utils_mode_counter import POLYGON_COUNTER_IDS from utilslegend.utils_mode_counter import COUNTER_TWOWAY_IDS logexcel = get_logger('excel','./logs/excel.log') def get_datetime() : currentDT = datetime.datetime.now().strftime("%Y/%m/%d") return currentDT def get_hour() : currentHour = datetime.datetime.now().hour return currentHour class export_excel() : def __init__(self,excel_fille, camera_id, camera_name) : self.excel_file = excel_fille self.camera_id = camera_id self.camera_name = camera_name self.sheet = {} if os.path.isfile(self.excel_file) : self.load_file() else : self.create_file() def load_file(self) : logexcel.info("load_file : {}".format(self.excel_file)) try : self.book = load_workbook(self.excel_file) sheetnames = self.book.sheetnames for sheet_name in sheetnames : self.sheet[sheet_name] = self.book.get_sheet_by_name(sheet_name) # self.sheet = self.book.active except : self.create_file() def create_sheet(self, sheet_name, id_func, func_name) : # print(self.book.sheetnames) sheetnames = self.book.sheetnames if sheet_name not in sheetnames : self.sheet[sheet_name] = self.book.create_sheet(sheet_name,0) self.sheet[sheet_name]['A1'] = 'Cam Name : ' self.sheet[sheet_name]['B1'] = self.camera_name self.sheet[sheet_name]['A2'] = 'ID :' self.sheet[sheet_name]['B2'] = id_func self.sheet[sheet_name]['A3'] = 'Line Name :' self.sheet[sheet_name]['B3'] = func_name self.sheet[sheet_name]['A5'] = 'Time' if id_func in COUNTER_TWOWAY_IDS : self.sheet[sheet_name]['B5'] = 'Car' self.sheet[sheet_name]['D5'] = 'Truck' self.sheet[sheet_name]['F5'] = 'Bus' self.sheet[sheet_name]['H5'] = 'Bike' self.sheet[sheet_name]['J5'] = 'Person' self.sheet[sheet_name]['B6'] = 'up' self.sheet[sheet_name]['C6'] = 'down' self.sheet[sheet_name]['D6'] = 'up' self.sheet[sheet_name]['E6'] = 'down' self.sheet[sheet_name]['F6'] = 'up' self.sheet[sheet_name]['G6'] = 'down' self.sheet[sheet_name]['H6'] = 'up' self.sheet[sheet_name]['I6'] = 'down' self.sheet[sheet_name]['J6'] = 'up' self.sheet[sheet_name]['K6'] = 'down' if id_func in POLYGON_COUNTER_IDS : self.sheet[sheet_name]['B5'] = 'Car' self.sheet[sheet_name]['C5'] = 'Truck' self.sheet[sheet_name]['D5'] = 'Bus' self.sheet[sheet_name]['E5'] = 'Bike' self.sheet[sheet_name]['F5'] = 'Person' else : logexcel.info("shet : {} exits".format(sheet_name)) # pass def create_file(self) : logexcel.info("create_file : {}".format(self.excel_file)) self.book = Workbook() # self.sheet = self.book.active # self.sheet['A1'] = 'Date/Hour' # row = 1 # column = 4 # for i in range(24) : # self.sheet.cell(row=row, column=column).value = i # column +=1 # self.current_row = 2 def update_line(self, sheet_name, list_counter_up, list_counter_dow) : # print(self.sheet) current_row = self.get_current_row(sheet_name) current_column = 2 # print(current_row) hour = get_hour() label_time = '{}:00'.format(hour) # print(label_time) value_check = self.sheet[sheet_name].cell(row=current_row, column=current_column + 0).value if value_check is None : self.sheet[sheet_name].cell(row=current_row, column=current_column - 1 ).value = label_time self.sheet[sheet_name].cell(row=current_row, column=current_column + 0).value = list_counter_up[0] self.sheet[sheet_name].cell(row=current_row, column=current_column + 1).value = list_counter_dow[0] self.sheet[sheet_name].cell(row=current_row, column=current_column + 2).value = list_counter_up[1] self.sheet[sheet_name].cell(row=current_row, column=current_column + 3).value = list_counter_dow[1] self.sheet[sheet_name].cell(row=current_row, column=current_column + 4).value = list_counter_up[2] self.sheet[sheet_name].cell(row=current_row, column=current_column + 5).value = list_counter_dow[2] self.sheet[sheet_name].cell(row=current_row, column=current_column + 6).value = list_counter_up[3] self.sheet[sheet_name].cell(row=current_row, column=current_column + 7).value = list_counter_dow[3] self.sheet[sheet_name].cell(row=current_row, column=current_column + 8).value = list_counter_up[4] self.sheet[sheet_name].cell(row=current_row, column=current_column + 9).value = list_counter_dow[4] else : self.sheet[sheet_name].cell(row=current_row, column=current_column + 0).value = self.sheet[sheet_name].cell(row=current_row, column=current_column + 0).value + list_counter_up[0] self.sheet[sheet_name].cell(row=current_row, column=current_column + 1).value = self.sheet[sheet_name].cell(row=current_row, column=current_column + 1).value + list_counter_dow[0] self.sheet[sheet_name].cell(row=current_row, column=current_column + 2).value = self.sheet[sheet_name].cell(row=current_row, column=current_column + 2).value + list_counter_up[1] self.sheet[sheet_name].cell(row=current_row, column=current_column + 3).value = self.sheet[sheet_name].cell(row=current_row, column=current_column + 3).value + list_counter_dow[1] self.sheet[sheet_name].cell(row=current_row, column=current_column + 4).value = self.sheet[sheet_name].cell(row=current_row, column=current_column + 4).value + list_counter_up[2] self.sheet[sheet_name].cell(row=current_row, column=current_column + 5).value = self.sheet[sheet_name].cell(row=current_row, column=current_column + 5).value + list_counter_dow[2] self.sheet[sheet_name].cell(row=current_row, column=current_column + 6).value = self.sheet[sheet_name].cell(row=current_row, column=current_column + 6).value + list_counter_up[3] self.sheet[sheet_name].cell(row=current_row, column=current_column + 7).value = self.sheet[sheet_name].cell(row=current_row, column=current_column + 7).value + list_counter_dow[3] self.sheet[sheet_name].cell(row=current_row, column=current_column + 8).value = self.sheet[sheet_name].cell(row=current_row, column=current_column + 8).value + list_counter_up[4] self.sheet[sheet_name].cell(row=current_row, column=current_column + 9).value = self.sheet[sheet_name].cell(row=current_row, column=current_column + 9).value + list_counter_dow[4] def update_polygon(self, sheet_name, list_counter_up) : current_row = self.get_current_row(sheet_name) current_column = 2 # print(current_row) hour = get_hour() label_time = '{}:00'.format(hour) # print(label_time) self.sheet[sheet_name].cell(row=current_row, column=current_column - 1 ).value = label_time self.sheet[sheet_name].cell(row=current_row, column=current_column + 0).value = list_counter_up[0] self.sheet[sheet_name].cell(row=current_row, column=current_column + 1).value = list_counter_up[1] self.sheet[sheet_name].cell(row=current_row, column=current_column + 2).value = list_counter_up[2] self.sheet[sheet_name].cell(row=current_row, column=current_column + 3).value = list_counter_up[3] self.sheet[sheet_name].cell(row=current_row, column=current_column + 4).value = list_counter_up[4] def get_current_row(self, sheet_name) : current_time = get_datetime() column = 2 row = 6 while True : cellCR = self.sheet[sheet_name].cell(row=row, column=column).value if cellCR == None: current_row = row break else : print(cellCR) print(type(cellCR)) row += 1 return current_row # def get_current_column(self) : # current_hour = get_hour() # current_column = int(current_hour) + 4 # return current_column def save(self) : self.book.save(self.excel_file) def run() : now = datetime.datetime.now() date_folder = now.strftime('%Y-%m-%d') # logexcel.info(date_folder) excel_file = "cam_{}_{}_{}.xlsx".format(1,"helo",date_folder) camera_id = 10 camera_Name = 'nguyentho' sheet_name = 'line_id1' sheet_name2 = 'line_id2' id_func = 5 id_func2 = 12 func_name = 'abc' excel = export_excel(excel_file, camera_id, camera_Name) # print(excel.sheetnames) excel.create_sheet(sheet_name, id_func, func_name) excel.create_sheet(sheet_name2, id_func2, func_name) list_counter_up = [1,2,3,4,5] list_counter_dow = [6,7,8,9,1] # time_update = 45 excel.update_line(sheet_name, list_counter_up, list_counter_dow) # # time_update = 60 excel.update_line(sheet_name, list_counter_up, list_counter_dow) # # time_update = 65 # excel.update_line(sheet_name, list_counter_up, list_counter_dow) # # time_update = 70 # excel.update_line(sheet_name, list_counter_up, list_counter_dow) # # time_update = 830 # excel.update_line(sheet_name, list_counter_up, list_counter_dow) excel.update_polygon(sheet_name2, list_counter_up) excel.update_polygon(sheet_name2, list_counter_up) # excel.update_polygon(sheet_name2, list_counter_up) # excel.update_polygon(sheet_name2, list_counter_up) # # excel.update(10) print(excel.sheet) excel.save() if __name__ == '__main__' : run()
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,074
edigomes/jetson_people_counter_head_detection
refs/heads/master
/light/simple.py
# data = {'msg': 'Hi!!!'} # headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} # r = requests.post(url, data=json.dumps(data), headers=headers) # url = "http://104.248.23.210/person/action?personId=personId&actionName=out" # r = requests.post(url) import requests import json placeId = 'ViKAVCAwm9' trackingId ="1000" url = 'https://104.248.23.210:443/person?placeId={}&trackingId={}'.format(placeId,trackingId) print(url) r = requests.post(url,verify=False) print(r.status_code) r = r.json() print(r) personId = r['personId'] url = "https://104.248.23.210/person/action?personId={}&actionName={}".format(personId, 'out') print(url) r = requests.post(url, verify=False) print(r.json()) # import requests # import json # url = "https://104.248.23.210" # data = { # 'placeId': placeId, # 'trackingId' : trackingId # } # headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} # r = requests.post(url, data=json.dumps(data), headers=headers, verify=False) # print(r)
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,075
edigomes/jetson_people_counter_head_detection
refs/heads/master
/trackmodel/centroidRecognize.py
# import the necessary packages from scipy.spatial import distance as dist from collections import OrderedDict import numpy as np import time import cv2 # import matplotlib.pyplot as plt import datetime class Human(object): def __init__(self, objectID, centroid, inputRect,image=None, color=None, gender=None) : """ Feature Human : objectID : ID to recognize color : color of cothes gender : str (Male, Female) image : Newest image detected predict : centroid predict trace : list centroid detected (limit number) iscountered : recognize countered or not disappeared : max numer frame, or second can't detect in one camera appeared : numer framed detected to voice noise """ self.objectID = objectID self.color = color self.gender = gender self.image = image self.trace = [] self.bbox = inputRect self.appeared = 0 self.disappeared = 0 self.time_appeared = datetime.datetime.now() self.iscountered = False class RdfTracker: # def __init__(self, maxObjectTrack=7, maxDistance=400, maxTrace=3,maxDisappeared = 180): def __init__(self, maxObjectTrack=7, maxDistance=400, maxTrace=3, max_Timedisappeared = 10): """ maxObjectTrack : Max umber frame or second cann't detect object maxDistance : Distance between two object to match maxTrace : Max location skipp of one object """ # self.counter_object = 0 self.nextObjectID = 0 self.currentObjects = [] self.hiddenObjects = [] self.max_Timedisappeared = max_Timedisappeared self.maxObjectTrack = maxObjectTrack self.maxDistance = maxDistance self.maxTrace = maxTrace self.cur_day = datetime.datetime.now().day def __register(self, centroid, imageObject, inputRect): """ Create new object feature add to object tracker list """ now = datetime.datetime.now() id_s = now.strftime('%H%M%S') id_s = id_s + "00" + str(self.nextObjectID) id_i = int(id_s) track = Human(id_i, centroid,inputRect, imageObject) self.currentObjects.append(track) self.currentObjects[-1].trace.append(centroid) self.nextObjectID += 1 # print("self.nextObjectID : {}".format(str(self.nextObjectID))) def __to_hiddenObjects(self, tracksId) : tracksObject = [self.currentObjects[index] for index in range(len(self.currentObjects)) if index in tracksId] self.currentObjects = [self.currentObjects[index] for index in range(len(self.currentObjects)) if index not in tracksId] self.hiddenObjects += tracksObject def __to_currentObjects(self, tracksId) : tracksObject = [self.hiddenObjects[index] for index in range(len(self.hiddenObjects)) if index in tracksId] self.hiddenObjects = [self.hiddenObjects[index] for index in range(len(self.hiddenObjects)) if index not in tracksId] self.currentObjects += tracksObject def __deregister(self, objectID): """ Delete object from tracker list """ # print('Delete Object {}'.format(objectID)) del self.currentObjects[objectID] """ Match list object tracking end detect feature histogram of object return rows, cols object tracking, detect Matched """ def __match_hidden_distance(self,inputCentroids, inputCropObjects, inputRects) : number_ob_tracking = len(self.hiddenObjects) number_ob_detect = len(inputCentroids) objectCentroids = [self.hiddenObjects[index].trace[-1] for index in range(number_ob_tracking)] D_dis = dist.cdist(np.array(objectCentroids), inputCentroids) usedDetects = set() usedTracks = set() # usedTracks_1, usedDetects_1 = self.__match_distance(self.hiddenObjects, inputCentroids , inputCropObjects, inputRects) # # usedTracks_1, usedDetects_1 = self.__match_iou(self.hiddenObjects, inputCentroids , inputCropObjects, inputRects) # for (detect1, track1) in zip(usedDetects_1, usedTracks_1) : # usedDetects.add(detect1) # usedTracks.add(track1) # for (detect1, track1) in zip(usedDetects, usedTracks) : # D_dis[track1, :] = self.maxDistance # D_dis[:, detect1] = self.maxDistance while (D_dis.min() < self.maxDistance and not (len(usedDetects) == number_ob_detect or len(usedTracks) == number_ob_tracking )): tracks = D_dis.min(axis=1).argsort() detects = D_dis.argmin(axis=1)[tracks] for (track, detect) in zip(tracks, detects): if detect in usedDetects or track in usedTracks: continue # Next ID in create if maxDistance smale if D_dis[track, detect] >= self.maxDistance : continue # ------------------------------------------------------------------------------------ # print("hidden : {}".format(D_dis[track, detect])) self.hiddenObjects[track].image = inputCropObjects[detect] self.hiddenObjects[track].bbox = inputRects[detect] self.hiddenObjects[track].trace.append(inputCentroids[detect]) usedDetects.add(detect) usedTracks.add(track) for (track1, detect1) in zip(usedTracks, usedDetects) : D_dis[track1, :] = self.maxDistance D_dis[:, detect1] = self.maxDistance # print(D) # -------------------------------------------------------------------------------- # Clear object matched # -------------------------------------------------------------------------------- return usedTracks, usedDetects """ Match list object tracking end detect compare distance return rows, cols object tracking, detect Matched # """ def __match_distance_current(self, inputCentroids , inputCropObjects, inputRects) : number_ob_tracking = len(self.currentObjects) number_ob_detect = len(inputCentroids) # ---------------------------------------------------------------------------------------------- # Pool Maps ID Tracking And Detect # ---------------------------------------------------------------------------------------------- objectCentroids = [self.currentObjects[index].trace[-1] for index in range(number_ob_tracking)] D_DIS = dist.cdist(np.array(objectCentroids), inputCentroids) tracks = D_DIS.min(axis=1).argsort() detects = D_DIS.argmin(axis=1)[tracks] usedTracks = set() usedDetects = set() # print(' ------ next match ------ ') for (track, detect) in zip(tracks, detects): if track in usedTracks or detect in usedDetects: continue if D_DIS[track, detect] > 80: # print("Distance Object: {} max {}".format(D[track, detect], self.maxDistance)) continue # print('dis : {} {} {}'.format(track, detect,D_DIS[track, detect])) self.currentObjects[track].image = inputCropObjects[detect] self.currentObjects[track].bbox = inputRects[detect] self.currentObjects[track].trace.append(inputCentroids[detect]) usedTracks.add(track) usedDetects.add(detect) return usedTracks, usedDetects """ Match list object tracking end detect compare distance return rows, cols object tracking, detect Matched # """ def __clear_update_time(self) : # update time for object newest for currentObject in self.currentObjects : currentObject.time_appeared = datetime.datetime.now() # reset disappeared of object and delete if to long current_time = datetime.datetime.now() maxHiddenList = [] for i, hiddenObject in enumerate(self.hiddenObjects) : subtime = current_time - hiddenObject.time_appeared total_seconds = int(subtime.total_seconds()) if total_seconds > self.max_Timedisappeared: # print("del hiddenObject : {}".format(hiddenObject.objectID)) maxHiddenList.append(i) self.hiddenObjects = [self.hiddenObjects[index] for index in range(len(self.hiddenObjects)) if index not in maxHiddenList] # clear maximun object traing in hidden if(len(self.hiddenObjects) > self.maxObjectTrack) : for index in range(len(self.hiddenObjects) - self.maxObjectTrack) : # print("del max 8 hiddenObject : {}".format(self.hiddenObjects[0].objectID)) del self.hiddenObjects[0] for i in range(len(self.currentObjects)) : # Delete trace older than max if(len(self.currentObjects[i].trace) > self.maxTrace): for j in range(len(self.currentObjects[i].trace) - self.maxTrace): del self.currentObjects[i].trace[0] for i in range(len(self.hiddenObjects)) : # Delete trace older than max if(len(self.hiddenObjects[i].trace) > self.maxTrace): for j in range(len(self.hiddenObjects[i].trace) - self.maxTrace): del self.hiddenObjects[i].trace[0] current_date = datetime.datetime.now().day if current_date != self.cur_day and self.cur_day != 0: for i in range(len(self.currentObjects)) : del self.currentObjects[0] for i in range(len(self.hiddenObjects)) : del self.hiddenObjects[0] self.nextObjectID = 0 self.cur_day = current_date def update(self, rects, frame): # If frame can't detect any object # All tracking object will increate number disapper if len(rects) == 0: trackID = range(len(self.currentObjects)) self.__to_hiddenObjects(trackID) # there is nothing to match, clear object self.__clear_update_time() return self.currentObjects # prepare data inport to tracking # Convert from rect to point inputCentroids = np.zeros((len(rects), 2), dtype="int") for (i, (x, y, w, h)) in enumerate(rects): cX = int(x + w // 2.0) cY = int(y + h // 2.0) inputCentroids[i] = (cX, cY) # Convert from rect to point inputRects = rects img_size = np.asarray(frame.shape)[0:2] inputCropObjects = [] for (x, y, w, h) in rects : xmin = np.maximum(int(x), 0) xmax = np.minimum(int(x + w) , img_size[1]) ymin = np.maximum(int(y), 0) ymax = np.minimum(int(y + h) , img_size[0]) cropObject = frame[ymin : ymax, xmin : xmax] cropObject_rgb = cv2.cvtColor(cropObject, cv2.COLOR_BGR2RGB) inputCropObjects.append(cropObject_rgb) # --------------------------------------------------------------------------------- # If tracking list is empty # Create object to tracking # --------------------------------------------------------------------------------- # this case Len(INPUT) > 0 if len(self.currentObjects) == 0 and len(self.hiddenObjects) == 0 : for index in range(0, len(inputCentroids)): # print("Register new object ") # print(inputRects[index]) self.__register(inputCentroids[index], inputCropObjects[index], inputRects[index]) return self.currentObjects # centroids # Case for have Object in current, hiddent or both else : # grab the set of object IDs and corresponding centroids # Case for currebt Object > 0 and check hiddent if (len(self.currentObjects) > 0 ) : usedTracks,usedDetects = self.__match_distance_current(inputCentroids, inputCropObjects, inputRects) # ---------------------------------------------------------------------------------------------- # Counter frame object disappeared # ---------------------------------------------------------------------------------------------- unusedTracks = set(range(0, len(self.currentObjects))).difference(usedTracks) unusedDetects = set(range(0, len(inputCentroids))).difference(usedDetects) # change object tracking current to hiddent self.__to_hiddenObjects(unusedTracks) # object unmatch detect inputCentroids_unmatch = [inputCentroids[index] for index in range(len(inputCentroids)) if index in unusedDetects] inputCropObjects_unmatch = [inputCropObjects[index] for index in range(len(inputCropObjects)) if index in unusedDetects] inputRects_unmatch = [inputRects[index] for index in range(len(inputRects)) if index in unusedDetects] # case for match hiddentObejct if(len(unusedDetects) > 0 and len(self.hiddenObjects) > 0) : usedTracks2, usedDetects2 = self.__match_hidden_distance(inputCentroids_unmatch, inputCropObjects_unmatch, inputRects_unmatch) unusedDetects2 = set(range(0, len(unusedDetects))).difference(usedDetects2) # Chang object tracking hiddent to current self.__to_currentObjects(usedTracks2) for detectID in unusedDetects2 : # Register new object if in other side self.__register(inputCentroids_unmatch[detectID], inputCropObjects_unmatch[detectID],inputRects_unmatch[detectID]) else : for detectID in unusedDetects : # print("New object affter current ") self.__register(inputCentroids[detectID], inputCropObjects[detectID],inputRects[detectID]) # Case for currebt Object = 0 and hiddent Object > 0 elif (len(self.hiddenObjects) > 0 and len(inputCentroids) > 0) : usedTracks,usedDetects = self.__match_hidden_distance(inputCentroids, inputCropObjects, inputRects) unusedDetects = set(range(0, len(inputCentroids))).difference(usedDetects) # Chang object tracking hiddent to current self.__to_currentObjects(usedTracks) for detectID in unusedDetects : # Register new object if in other side self.__register(inputCentroids[detectID], inputCropObjects[detectID],inputRects[detectID]) # ---------------------------------------------------------------------------------------------- # Counter object have appeared > 5 # ---------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------- # Clear data # ---------------------------------------------------------------------------------------------- self.__clear_update_time() return self.currentObjects
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,076
edigomes/jetson_people_counter_head_detection
refs/heads/master
/ubidots/utils_ubidots.py
import time import requests import math import random import numpy as np import threading import datetime from utils_ken.log.getlog import get_logger from utils import Conf logubidot_line = get_logger('ubidot','./logs/ubidot.log') class Api_Ubidots() : def __init__(self, conf) : self.conf = conf self.token, self.machine, self.lat, self.lng = self.gettoken(self.conf) # ------------------------------------------- if self.lat is not None and self.lng is not None : self.send_postition(self.lat, self.lng) # ----------------------------------------------------------------------------------- # decode json to get token def gettoken(self, conf) : # data_configs = Conf(conf) token = conf['ubidot_token'] machine = conf['machine'] lat = conf['lat'] lng = conf['lng'] if token is None or machine is None : raise "ubidot error information" return token, machine, lat, lng # ----------------------------------------------------------------------------------- def build_payload_position(self, lat, lng) : payload = { "position" : {"value": 1, "context": {"lat": lat, "lng": lng}} } return payload # ----------------------------------------------------------------------------------- def build_payload_up(self, person) : payload = { "person_up_raw" : person } return payload # ----------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------- def build_payload_down(self, person) : payload = { "person_down_raw" : person } return payload def build_payload_sum(self, person) : payload = { "person_raw" : person } return payload # ----------------------------------------------------------------------------------- def post_request(self, payload): # Creates the headers for the HTTP requests url = "http://things.ubidots.com" url = "{}/api/v1.6/devices/{}".format(url, self.machine) headers = {"X-Auth-Token": self.token, "Content-Type": "application/json"} # Makes the HTTP requests status = 400 attempts = 0 while status >= 400 and attempts <= 5: req = requests.post(url=url, headers=headers, json=payload) status = req.status_code attempts += 1 time.sleep(5) # Processes results if status >= 400: logubidot_line.info("[ERROR] Could not send data after 5 attempts, please check \ your token credentials and internet connection") return False # logubidot_line.info("[INFO] request made properly, your device is updated") return True def _send_postition(self, lat, lng): payload = self.build_payload_position(lat, lng) self.post_request(payload) def _send_up_traffic(self, person ): payload = self.build_payload_up(person ) self.post_request(payload) def _send_down_traffic(self, person): payload = self.build_payload_down(person) self.post_request(payload) def _send_sum_traffic(self, person): payload = self.build_payload_sum(person) self.post_request(payload) def send_up_traffic(self, person ): logubidot_line.info("send count up {}".format([person])) thread = threading.Thread(target=self._send_up_traffic, args=(person,)) # thread.daemon = True thread.start() def send_down_traffic(self, person ): logubidot_line.info("send count down {}".format([person])) thread = threading.Thread(target=self._send_down_traffic, args=(person,)) # thread.daemon = True thread.start() def send_sum_traffic(self, person ): logubidot_line.info("send count sum {}".format([person])) thread = threading.Thread(target=self._send_sum_traffic, args=(person,)) # thread.daemon = True thread.start() def send_postition(self, lat, lng): logubidot_line.info("send position {}".format([lat, lng])) thread = threading.Thread(target=self._send_postition, args=(lat, lng,)) # thread.daemon = True thread.start() def main(): logubidot_line.info(" =========================================") people_count = np.random.randint(20, 25) bikebike_count = np.random.randint(20, 30) car_count = np.random.randint(100, 150) truck_count = np.random.randint(30, 50) bus_count = np.random.randint(30, 60) # init data accessor send_up_traffic(DEVICE_LABEL, people_count, id_line) send_down_traffic(DEVICE_LABEL,people_count, id_line) if __name__ == '__main__': # read database config main() pre_minute = datetime.datetime.now().minute while True: curent_minute = datetime.datetime.now().minute if pre_minute != curent_minute and curent_minute %15 == 1: main() pre_minute = curent_minute logubidot_line.info("update at :{}".format(curent_minute))
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,077
edigomes/jetson_people_counter_head_detection
refs/heads/master
/light/lightapi.py
import time import requests import math import random import numpy as np import threading import datetime from utils_ken.log.getlog import get_logger from utils import Conf light = get_logger('light','./logs/light.log') class ApiLight() : def __init__(self, conf) : self.conf = conf self.place_id, self.ip_machine = self.get_info(self.conf) # ------------------------------------------- # ----------------------------------------------------------------------------------- # decode json to get place_id def get_info(self, conf) : # data_configs = Conf(conf) place_id = conf['placeId'] ip_machine = conf['ip_machine'] if place_id is None or ip_machine is None : raise "place_id or ip_machine error information" return place_id, ip_machine # ----------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------- def _send_action(self, trackingId, actionName): # Creates the headers for the HTTP requests url1 = 'https://{}/person?placeId={}&trackingId={}'.format(self.ip_machine, self.place_id,trackingId) light.info('url {}'.format(url1)) # Makes the HTTP requests status = 400 attempts = 0 while status >= 400 and attempts <= 5: req = requests.post(url1,verify=False) print(req) status = req.status_code person_id = req.json()['personId'] light.info('personId {}'.format(person_id)) attempts += 1 time.sleep(5) if status == 200 : status = 400 attempts = 0 url2 = 'https://{}/person/action?personId={}&actionName={}'.format(self.ip_machine, person_id, actionName) light.info('url {}'.format(url2)) while status >= 400 and attempts <= 5: req = requests.post(url2,verify=False) print(req) status = req.status_code person_id = req.json()['personActionId'] light.info('personActionId {}'.format(person_id)) attempts += 1 time.sleep(5) # Processes results if status >= 400: light.info("[ERROR] Could not send data after 5 attempts, please check \ your token credentials and internet connection") return False # light.info("[INFO] request made properly, your device is updated") return True def send_action(self, trackingId, actionName ): light.info("send trackingId {} {} ".format(trackingId, actionName)) thread = threading.Thread(target=self._send_action, args=(trackingId, actionName,)) thread.daemon = True thread.start() if __name__ == '__main__': config_server = '../jetson/configs.json' conf = Conf(config_server) light_api = ApiLight(conf) light_api.send_action(123,"out")
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,078
edigomes/jetson_people_counter_head_detection
refs/heads/master
/core/Core_theard.py
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from utils_machine import videos_output from utils_machine import images_output from trackmodel.centroidRecognize import RdfTracker from threading import Thread from queue import Queue import datetime from utils_ken.log.getlog import get_logger from utils_ken.video.recapvideostream import RecapVideoStream from utils.utils_mode_counter import POLYGON_FILTER from utils.utils_mode_counter import COUNTER_ONEWAY_IDS from utils.utils_mode_counter import POLYGON_COUNTER_IDS from utils.utils_save_video import SaveVideoHour from utils.utils_color import * from utils.utils_color import draw_object_tracking2 from utils.utils_polygon import draw_polygon from utils.utils_polygon import utils_popygon from utils_excel.utils_excel_sum_hour import export_excel from display.draw_table_display import draw_table_display from utils.utils_counter import Counter_Line2Way from utils.utils_label_xml import save_image from ubidots.utils_ubidots import Api_Ubidots from utils.utils_counter import Counter_Polygon from light.lightapi import ApiLight from detectmodel.tf_detector import TfDetector from detectmodel.tracker import Tracker from detectmodel.setting import * from detectmodel import func logcore = get_logger('core','./logs/core.log') if not os.path.exists(videos_output) : logcore.info("os.makedirs : {}".format(videos_output)) os.makedirs(videos_output) if not os.path.exists(images_output) : logcore.info("os.makedirs : {}".format(images_output)) os.makedirs(images_output) sent_db = False class Core(): def __init__(self, conf, camCfg, lockDetect, frame_out): ''' Initilize model and specify video source ''' self.detector_lock = lockDetect self.__camCfg = camCfg print(self.__camCfg) self.List_object = conf['vehicle_type'] self.conf = conf self.model = TfDetector() self.tracker = Tracker() self.total_in = 0 self.total_out = 0 line_p1 = np.array(self.__camCfg['funcs'][1]['func_line'][:2]) line_p2 = np.array(self.__camCfg['funcs'][1]['func_line'][2:]) p3 = np.array(self.__camCfg['funcs'][1]['func_pont'][:2]) p4 = np.array(self.__camCfg['funcs'][1]['func_pont'][2:]) d1 = func.get_distance_from_line(line_p1, line_p2, p3) d2 = func.get_distance_from_line(line_p1, line_p2, p4) if d1 < 0 and d2 > 0: self.direction = True else: self.direction = False self.tracker_object = RdfTracker(maxObjectTrack=self.conf["maxObjectTrack"], maxDistance=self.conf["maxDistance"], maxTrace=5, max_Timedisappeared = self.conf["max_Timedisappeared"]) self.frame_out = frame_out # self.lock = lock self.__queue_frame = Queue(maxsize=4) self.__queue_predict = Queue(maxsize=4) self.thread_prec = Thread(target=self.__predict) self.thread_prec.daemon = True self.thread_prec.start() # self.__cap = CameraCapture(self.__camCfg) self.__cap = RecapVideoStream(self.__camCfg) # self.__cap = FileVideoStream(self.__camCfg['cam_Link'], step=1) if self.conf["send_ubidot"] : self.api_ubidot = Api_Ubidots(self.conf) if self.conf['light_api'] : self.light_api = ApiLight(self.conf) def check_valid_detection(self, rect_list, score_list, class_list): check_rect_list = [] check_score_list = [] # ----------------------- check validation using threshold and ROI ------------------------ for i in range(len(score_list)): if class_list[i] != 1 or score_list[i] < DETECTION_THRESHOLD: continue # check ROI roi = self.__camCfg['funcs'][0]['func_note'] if rect_list[i][0] + rect_list[i][2] < roi[0][0] * 2: continue elif rect_list[i][0] + rect_list[i][2] > roi[1][0] * 2: continue elif rect_list[i][1] + rect_list[i][3] < roi[0][1] * 2: continue elif rect_list[i][1] + rect_list[i][3] > roi[2][1] * 2: continue # check overlap with other rects f_overlap = False for j in range(len(check_rect_list)): if func.check_overlap_rect(check_rect_list[j], rect_list[i]): if check_score_list[j] < score_list[i]: check_score_list[j] = score_list[i] check_rect_list[j] = rect_list[i] f_overlap = True break if f_overlap: continue # check width/height rate w = rect_list[i][2] - rect_list[i][0] h = rect_list[i][3] - rect_list[i][1] if max(w, h) / min(w, h) > 2: continue # register data check_rect_list.append(rect_list[i]) check_score_list.append(score_list[i]) # ------------ check validation by check body and calculate distance from cross line ------ final_rect = [] final_score = [] final_distance = [] line_p1 = np.array(self.__camCfg['funcs'][1]['func_line'][:2]) line_p2 = np.array(self.__camCfg['funcs'][1]['func_line'][2:]) for i in range(len(check_rect_list)): r_body = check_rect_list[i] body_h = r_body[3] - r_body[1] body_w = r_body[2] - r_body[0] f_ignore = False for j in range(len(check_rect_list)): r2 = check_rect_list[j] if r_body[0] < (r2[0] + r2[2]) / 2 < r_body[2] or r2[0] < (r_body[0] + r_body[2]) / 2 < r2[2]: if abs(r_body[1] - r2[3]) * 1.5 < r2[3] - r2[1] and r_body[3] > r2[3] + 0.5 * (r2[3] - r2[1]): if body_h > 1.2 * (r2[3] - r2[1]) or body_w > 1.2 * (r2[2] - r2[0]): f_ignore = True break if not f_ignore: final_rect.append(check_rect_list[i]) final_score.append(check_score_list[i]) p3 = np.array([(check_rect_list[i][0] + check_rect_list[i][2]) / 2, (check_rect_list[i][1] + check_rect_list[i][3]) / 2]) final_distance.append(func.get_distance_from_line(line_p1, line_p2, p3)) return final_rect, final_score, final_distance def detect_frame(self, img): roi = self.__camCfg['funcs'][0]['func_note'] roi = [max(0, roi[0][0] - 20), max(0, roi[0][1] - 20), min(960, roi[1][0] + 20), min(540, roi[2][1] + 20)] img_crop = img[roi[1]:roi[3], roi[0]:roi[2]] det_rect_list, det_score_list, det_class_list = self.model.detect_from_images(img_crop) for i in range(len(det_rect_list)): det_rect_list[i][0] += roi[0] det_rect_list[i][1] += roi[1] det_rect_list[i][2] += roi[0] det_rect_list[i][3] += roi[1] return det_rect_list, det_score_list, det_class_list def __predict(self): """ Model Detect predict frame in thread Args : None return : None """ frame_ind = 0 while True: if not self.__queue_frame.empty(): frame_ind += 1 frame = self.__queue_frame.get() self.detector_lock.acquire() rects, probs, classesID = self.detect_frame(frame) valid_rects, valid_scores, valid_distances = self.check_valid_detection(rects, probs, classesID) cnt_in, cnt_out = self.tracker.update(frame_ind, valid_rects, valid_distances) if self.direction: self.total_in += cnt_in self.total_out += cnt_out else: self.total_in += cnt_out self.total_out += cnt_in self.detector_lock.release() self.__queue_predict.put((valid_rects, valid_scores, valid_distances, frame)) def disconnect(self): pass def process(self, show_video=True): ''' Detect human from Video source by loaded model ''' logcore.info('Cam- {:0>4} starting ...'.format(self.__camCfg['cam_ID'])) if self.conf['video_mode']: video_writer = SaveVideoHour(videos_output, self.__camCfg['cam_ID']) # video_writer_org = SaveVideoHour(videos_output, self.__camCfg['cam_ID']) if self.conf['save_excel']: now = datetime.datetime.now() # date_folder = now.strftime('%Y-%m-%d_%H_%M') date_folder = now.strftime('%Y-%m-%d') cam_ID = self.__camCfg['cam_ID'] cam_Name = self.__camCfg['cam_Name'] excel_file = "{}/{}_{}.xlsx".format(self.conf['excels_output'], cam_Name, date_folder) self.excel_report = export_excel(excel_file, cam_ID, cam_Name) logcore.info('excel_file {}'.format(excel_file)) # check function model run cam_funcs = [] for index, func in enumerate(self.__camCfg["funcs"]): if func["func_ID"] in COUNTER_ONEWAY_IDS : line_func = {} line_func['id'] = int(func["func_ID"]) line_func['func_Name'] = func["func_Name"] # line, points = decode_note_counter_line(func["func_note"]) line = func['func_line'] points = func['func_pont'] line_func["points"] = line line_func["points2"] = points line_func[0] = Counter_Line2Way(line, points) cam_funcs.append(line_func) # ---------------------------------------------------------------------------------------------------- if self.conf['save_excel'] is True : sheet_line_name = "{}_line_id{}".format(self.__camCfg['cam_ID'], func["func_Name"]) logcore.info('create_sheet : {}'.format(sheet_line_name)) self.excel_report.create_sheet(sheet_line_name, func["func_ID"], func["func_Name"]) # ---------------------------------------------------------------------------------------------------- logcore.info("line_func['id'] : {}".format(line_func['id'])) if func["func_ID"] in POLYGON_COUNTER_IDS : counter_func = {} counter_func['id'] = func["func_ID"] counter_func['func_Name'] = func["func_Name"] coords = func["func_note"] counter_func["func_Name"] = func["func_Name"] counter_func["coords"] = coords counter_func[0] = Counter_Polygon(coords) cam_funcs.append(counter_func) logcore.info("line_func['id'] : {}".format(counter_func['id'])) # ---------------------------------------------------------------------------------------------------- if self.conf['save_excel'] is True : sheet_polygon_name = "{}_zone_{}".format(self.__camCfg['cam_ID'],func["func_Name"]) logcore.info('create_sheet : {}'.format(sheet_polygon_name)) self.excel_report.create_sheet(sheet_polygon_name, func["func_ID"], func["func_Name"]) # ---------------------------------------------------------------------------------------------------- if func["func_ID"] == POLYGON_FILTER : polygon_func = {} polygon_func['id'] = POLYGON_FILTER # polygon_func["coords"] = decode_note_polygon(func["func_note"]) polygon_func["coords"] = func["func_note"] polygon_func["filter"] = utils_popygon(polygon_func["coords"]) cam_funcs.append(polygon_func) minute_write_xml = datetime.datetime.now().minute minute_send_data_keep = datetime.datetime.now().minute minute_counter = datetime.datetime.now().minute pre_day = datetime.datetime.now().day pre_hour = datetime.datetime.now().hour count_frame_process = 0 self.__cap.start() while True: frame = self.__cap.read() if not self.__queue_frame.full() and frame is not None: # frame = cv2.resize(frame, (1280,720) ) frame = cv2.resize(frame, (960, 540)) self.__queue_frame.put(frame) if frame is None : logcore.info("frame is None ") # predict and processing tracking if not self.__queue_predict.empty() : # Get predict detection # logcore.warning('----- track ------------------') (boxes, probs, distances, frame_pre) = self.__queue_predict.get() frame_ori = frame_pre.copy() count_frame_process +=1 # Get predict detection # ----------------------------------------------------------------------------------------------------------- probs_data = probs if self.conf['images_mode'] is True : current_minute = datetime.datetime.now().minute if len(probs_data) >= 1 and current_minute != minute_write_xml and current_minute % self.conf["take_every"] ==0: logcore.info("write image : {}".format(current_minute)) # save_label_object(classesID, boxes, frame_ori, self.__camCfg["cam_ID"], folderobject) save_image(frame_ori, images_output, self.__camCfg["cam_ID"]) minute_write_xml = current_minute # ----------------------------------------------------------------------------------------------------------- for cam_func in cam_funcs : if cam_func['id'] == POLYGON_FILTER : # classesID, probs, boxes = cam_func["filter"].filter_ob(classesID, probs, boxes) draw_polygon(frame_pre,cam_func['coords']) # classification object and tracking self.tracker_object.update(boxes, frame_pre) # classification counting object for many line for cam_func in cam_funcs : if cam_func['id'] in COUNTER_ONEWAY_IDS : light_trackid, light_aciton = cam_func[0].update(self.tracker_object.currentObjects) if self.conf['light_api'] : if len(light_trackid) > 0 : for index_id, track_id in enumerate(light_trackid) : self.light_api.send_action(light_trackid[index_id], light_aciton[index_id]) draw_table_display(cam_funcs, frame_pre, self.total_in, self.total_out) # ------------------------------------------------------------------------------- # Test counter line # Draw object, erea # ------------------------------------------------------------------------------- frame_pre = draw_object_tracking2(frame=frame_pre,ObjectTracker=self.tracker_object,label_t='person', color_id1=0) if self.conf['video_mode'] : video_writer.update(frame_pre) if 'DISPLAY' in os.environ and self.conf['show_video']: cv2.imshow("Video {}".format(self.__camCfg["cam_ID"]),frame_pre) k = cv2.waitKey(1) & 0xff if k == ord('q') : break # with self.lock : if self.frame_out.full() : self.frame_out.get() self.frame_out.put(frame_pre.copy()) else: self.frame_out.put(frame_pre.copy()) # --------------------------------------------------------------------------------------- minute_send_data = datetime.datetime.now().minute if minute_send_data_keep != minute_send_data and minute_send_data % self.conf["updated_every"] ==0: minute_send_data_keep = minute_send_data logcore.info("Update traffic log, static, excel : {}".format(minute_send_data_keep)) for cam_func in cam_funcs : if cam_func['id'] in COUNTER_ONEWAY_IDS : data_send = {} data_send['camera_id'] = self.__camCfg['cam_ID'] list_up_counter = [] list_down_counter = [] list_sum = [] cnt_up = self.total_in cnt_down = self.total_out self.total_in = 0 self.total_out = 0 # cnt_up, cnt_down = cam_func[0].get_counter_and_clean() data_send[0] = cnt_up + cnt_down list_up_counter.append(cnt_up) list_down_counter.append(cnt_down) list_sum.append(cnt_up + cnt_down) # if sent_db is True: # SEND database_api # self.database_api.send(data_send) if self.conf['save_excel'] is True : sheet_line_name = "{}_line_id{}".format(self.__camCfg['cam_ID'], cam_func["func_Name"]) self.excel_report.update_line(sheet_line_name, list_up_counter, list_down_counter) self.excel_report.save() if self.conf["send_ubidot"] : self.api_ubidot.send_up_traffic(*list_up_counter) self.api_ubidot.send_down_traffic(*list_down_counter) self.api_ubidot.send_sum_traffic(*list_sum) if cam_func['id'] in POLYGON_COUNTER_IDS : data_send = {} data_send['camera_id'] = self.__camCfg['cam_ID'] list_counter = [] for index, obiect_index in enumerate(self.List_object) : counter_no = cam_func[obiect_index].get_counter_and_clean() data_send[obiect_index] = counter_no list_counter.append(counter_no) # if sent_db is True: # SEND database_api # self.database_api.send(data_send) if self.conf['save_excel'] is True : sheet_polygon_name = "{}_zone_{}".format(self.__camCfg['cam_ID'], cam_func["func_Name"]) self.excel_report.update_polygon(sheet_polygon_name, list_counter) self.excel_report.save() if self.conf["send_ubidot"] : # self.api_ubidot.send_sum_traffic(*list_counter) self.api_ubidot.send_zone_traffic(*list_counter) # --------------------------------------------------------------------------------------- # write excel every five minute # --------------------------------------------------------------------------------------- minute_send_data = datetime.datetime.now().minute if minute_counter != minute_send_data : minute_counter = minute_send_data logcore.info("minute {} Cam {} processing {} Frame".format(minute_counter, self.__camCfg['cam_ID'], count_frame_process)) count_frame_process = 0 current_hour = datetime.datetime.now().hour current_day = datetime.datetime.now().day if current_day != pre_day : pre_day = current_day logcore.info("reset counter per day : {} ".format(current_day)) # ----------------------------------------------------------------------------------------- if self.conf['save_excel'] is True : now = datetime.datetime.now() # date_folder = now.strftime('%Y-%m-%d_%H_%M') date_folder = now.strftime('%Y-%m-%d') cam_ID = self.__camCfg['cam_ID'] cam_Name = self.__camCfg['cam_Name'] excel_file = "{}/{}_{}.xlsx".format(self.conf['excels_output'], cam_Name,date_folder) self.excel_report = export_excel(excel_file, cam_ID, cam_Name) logcore.info('excel_file {}'.format(excel_file)) # ----------------------------------------------------------------------------------------- for index, func in enumerate(self.__camCfg["funcs"]) : if func["func_ID"] in COUNTER_ONEWAY_IDS : if self.conf['save_excel'] is True : sheet_line_name = "{}_line_id{}".format(self.__camCfg['cam_ID'], func["func_Name"]) logcore.info('create_sheet : {}'.format(sheet_line_name)) self.excel_report.create_sheet(sheet_line_name, func["func_ID"], func["func_Name"]) if func["func_ID"] in POLYGON_COUNTER_IDS : if self.conf['save_excel'] is True : sheet_polygon_name = "{}_zone_{}".format(self.__camCfg['cam_ID'],func["func_Name"]) logcore.info('create_sheet : {}'.format(sheet_polygon_name)) self.excel_report.create_sheet(sheet_polygon_name, func["func_ID"], func["func_Name"]) # pre_minute = current_minute pre_hour = current_hour pre_day = current_day # logcore.warning('---------------- one round ------------------') logcore.warning('---------------- Exception 2 ------------------') def close(self): ''' Clean resources and terminate service ''' self.__del__() time_close = datetime.datetime.now() logcore.warning("Cam- {} closeed at {}:{}".format(self.__camCfg['cam_ID'],time_close.hour,time_close.minute)) def __del__(self): self.__cap.stop() logcore.info('Cleaning resources...\n')
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,079
edigomes/jetson_people_counter_head_detection
refs/heads/master
/run_apps.py
import os import json from utils_ken.log.getlog import get_logger from core.Core_theard import Core from flask import Response from flask import Flask from flask import render_template import threading from utils import Conf from queue import Queue from utils.utils_polygon import decode_note_counter from utils.utils_polygon import decode_note_polygon from flask import request from flask import redirect from flask import url_for from flask import session from datetime import timedelta import time import cv2 logruncv = get_logger('watchdog','./logs/watchdog.log') # initialize a flask object app = Flask(__name__) app.secret_key = "super secret key" app.permanent_session_lifetime = timedelta(minutes=5) myjsonfile = open('./jetson/jetson_config.json','r') jsondata = myjsonfile.read() obj = json.loads(jsondata) userJSON = str(obj['jetson_user']) passJSON = str(obj['jetson_pass']) frame_out = Queue(maxsize=4) @app.route("/") def default(): return redirect("/login") @app.route("/login", methods=['POST', 'GET']) def login(): error = None if request.method == 'POST' and request.form['submit_button'] == 'Login': user = request.form['user'] password = request.form['password'] session['admin'] = userJSON session.permanent = True if user == userJSON and password == passJSON: return redirect('/live', code=302) else: error = "Username or password not correct" elif "admin" in session: return redirect(url_for("home")) return render_template('/main/index.html', error=error) @app.route('/logout') def logout(): session.pop("admin", None) return redirect(url_for('login')) @app.route("/live") def home(): if "admin" not in session: return redirect(url_for('login'), code=302) return render_template("/main/live.html") @app.route("/setup/addcam", methods=['POST', 'GET']) def setup(): if "admin" not in session: return redirect(url_for('login')) path = './jetson/' filename = 'camera_info' data = {} if request.method == "POST": if request.form['submit_button'] == 'Add': data['camera_name'] = request.form['camera_name'] data['camera_id'] = request.form['camera_id'] data['camera_link'] = request.form['camera_link'] jsonToFile(path, filename, data) gen(reload=True) elif request.form['submit_button'] == 'Check': try : file = open('jetson/camera_info.json','r') fileData = file.read() objData = json.loads(fileData) camLink = str(objData['camera_link']) data['camera_name'] = str(objData['camera_name']) data['camera_id'] = str(objData['camera_id']) data['camera_link'] = str(objData['camera_link']) except : data['camera_name'] = request.form['camera_name'] data['camera_id'] = request.form['camera_id'] data['camera_link'] = request.form['camera_link'] return redirect('/checkcamera?camera_name={}&camera_id={}&camera_link={}'.format(data['camera_name'],data['camera_id'],data['camera_link']), code=302) return render_template("/main/setup.html") @app.route('/setup/zone', methods=['POST', 'GET']) def zone(): if "admin" not in session: return redirect(url_for('login')) if request.method == 'POST': data = request.get_json() if 'command' not in data: location = './jetson/' fileName = 'zone_info' jsonToFile(location, fileName, data) return redirect('/setup/zone?status=success') else: logruncv.info("restart service") cmd = 'sudo service jetson restart' os.system(cmd) return render_template('/main/setup-zone.html') @app.route('/video_feed', methods=['POST', 'GET']) def video_feed(): if "admin" not in session: return redirect(url_for('login')) return Response(gen(),mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/checkcamera') def checkcamera(): if "admin" not in session: return redirect(url_for('login')) name = request.args.get('camera_name') id = request.args.get('camera_id') link = request.args.get('camera_link') return '''<h2>The Camera Name Is : {}</h2> <h2>The Camera Id Is : {}</h2> <h2>The Camera Link Is : {}</h2>'''.format(name,id,link) def jsonToFile(path, filename, data): formatFile = './' + path + '/' + filename + '.json' with open(formatFile, 'w') as fp: json.dump(data, fp) def gen(reload=False): file = open('jetson/camera_info.json','r') fileData = file.read() objData = json.loads(fileData) camLink = str(objData['camera_link']) cap = cv2.VideoCapture(camLink) logruncv.info(cap) logruncv.info("cv2.VideoCapture(camLink) {}".format(camLink)) if cap.isOpened() == False: logruncv.info('Video Not Found') while(cap.isOpened()): logruncv.info(cap) ret, img = cap.read() if ret == True: # img = cv2.resize(img, (0,0), fx=1.0, fy=1.0) img = cv2.resize(img, (1280,720)) frame = cv2.imencode('.jpg', img)[1].tobytes() yield(b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') time.sleep(0.1) else: break if reload == True: cap.release() logruncv.info("reload == True") return gen() def logout_asd(): session.clear() return redirect(url_for('login')) # def core_thread(cam_cfg, modelDetect, detector_lock, interTracker, tracker_lock): def core_thread(conf, camCfg, detector_lock, frame_out): # log information logruncv.info('CV get camera ID: {}'.format(camCfg['cam_ID'])) # logruncv.info('CV counter at line ID: {}'.format(camCfg['lines'])) rdfCVObj = Core(conf, camCfg, detector_lock, frame_out) # process - detect,tracking,counter rdfCVObj.process(show_video=True) rdfCVObj.close() logruncv.info('[INFO] Done process') def get_config_file (file): # with open('config2.json') as f: with open(file) as f: cam_cfgs = json.load(f) return cam_cfgs def generate(): # grab global references to the output frame and lock variables global frame_out # loop over frames from the output stream while True: # wait until the lock is acquired # with lock: # check if the output frame is available, otherwise skip # the iteration of the loop if frame_out.empty(): time.sleep(0.001) # print("empty") continue # encode the frame in JPEG format (flag, encodedImage) = cv2.imencode(".jpg", frame_out.get()) # ensure the frame was successfully encoded if not flag: # print(flag) continue time.sleep(0.05) # print("success") # yield the output frame in the byte format yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(encodedImage) + b'\r\n') @app.route("/video_feed1") def video_feed1(): # return the response generated along with the specific media # type (mime type) return Response(generate(), mimetype = "multipart/x-mixed-replace; boundary=frame") def run_core(conf) : # bait global lock, frame_out detector_lock = threading.Lock() logruncv.info('Get camera List to run') # cam_cfgs = get_config_file() # camera_infor = Conf(conf['camera_info']) camera_infor = Conf(conf['camera_info']) zone_infor = Conf(conf['zone_info']) if camera_infor['camera_link'] is None or camera_infor['camera_link'] is None or camera_infor['camera_id'] is None : raise "camera_infor slack information" if zone_infor['1'] is None or zone_infor['2'] is None or zone_infor['3'] is None : raise "zone_infor slack information" cam_cfgs = {} cam_cfgs['cam_Link'] = camera_infor['camera_link'] cam_cfgs['step'] = 1 cam_cfgs['cam_Name'] = camera_infor['camera_name'] cam_cfgs['cam_ID'] = camera_infor['camera_id'] cam_cfgs['funcs'] = [] zone_fillter = {} counter_infor = {} zone_fillter["func_ID"] = 5 zone_fillter["func_Name"] = "zone filtter" zone_fillter["func_note"] = decode_note_polygon(zone_infor['1']) counter_infor["func_ID"] = 1 counter_infor["func_Name"] = "counter" counter_infor["func_line"] = decode_note_counter(zone_infor['2']) counter_infor["func_pont"] = decode_note_counter(zone_infor['3']) cam_cfgs['funcs'].append(zone_fillter) cam_cfgs['funcs'].append(counter_infor) logruncv.info(cam_cfgs) # start 1 thread for 1 camera thread = threading.Thread(target=core_thread, args=(conf, cam_cfgs, detector_lock, frame_out)) thread.daemon = True thread.start() # start the flask app app.run(host='0.0.0.0', port=8888, debug=False, threaded=True, use_reloader=False) if __name__ == '__main__': config_server = './jetson/configs.json' conf = Conf(config_server) run_core(conf)
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,080
edigomes/jetson_people_counter_head_detection
refs/heads/master
/utilslegend/utils_color.py
import cv2 # from detectmodel.SSD_Utils import LABELS from detectmodel.Yolo_Utils import LABELS # from Yolo_Utils import LABELS import os import cv2 import time import numpy as np COLOR_BLACK = (0, 0, 0) COLOR_WHITE = (255, 255, 255) COLOR_RED = (0, 0, 255) COLOR_RED1 = (0, 125, 255) COLOR_GREEN = (0, 255, 0) COLOR_BLUE = (255, 0, 0) COLOR_PURPLE = (255, 0, 255) COLOR_PURPLE1 = (255, 255, 0) COLOR_YELLOW = (0, 255, 255) COLOR_YELLOW1 = (255, 255, 0) COLOR_TABEL = [COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_PURPLE, COLOR_YELLOW] # COLOR_TABEL_OB = np.random.uniform(100, 255, size=(100, 3)) # COLOR_TABEL_LINE = np.random.uniform(100, 250, size=(100, 3)) COLOR_TABEL_LINE = np.random.randint(100, high = 255, size = (100,3)).tolist() # COLOR_TABEL_OB = np.random.randint(100, high = 255, size = (100,3)).tolist() # COLOR_TABEL_OB = [COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_PURPLE, COLOR_YELLOW, COLOR_PURPLE1, COLOR_YELLOW1] COLOR_1 = (255, 100, 100) COLOR_2 = (100, 255, 100) COLOR_3 = (100, 100, 255) COLOR_4 = (255, 255, 100) COLOR_5 = (255, 100, 255) COLOR_6 = (100, 255, 255) COLOR_TABEL_OB = [COLOR_1, COLOR_2, COLOR_3, COLOR_4, COLOR_5, COLOR_6, COLOR_6] def draw_object_predict(classes, probes, boxes, image) : (H, W) = image.shape[0:2] for index, (x, y, w, h) in enumerate(boxes) : xmin = max(0, x) ymin = max(0, y) xmax = min(xmin + w , W) ymax = min(ymin + h , H) label = "{}".format(LABELS[classes[index]], probes[index]) # label = "{} : {:.2}".format(classes[index], probes[index]) color = [int(c) for c in COLOR_TABEL_OB[classes[index]]] cv2.rectangle(image, (xmin, ymin), (xmax, ymax),color, 2) labelSize, baseLine = cv2.getTextSize(label, cv2.FORMATTER_FMT_CSV, 0.75, 1) top = max(y, labelSize[1]) cv2.rectangle(image, (x - 1, top - round(labelSize[1])), (x + w + 1, top ), color, cv2.FILLED) cv2.putText(image, label, (x, top), cv2.FORMATTER_FMT_CSV, 0.75, COLOR_BLACK, 1) return image # # Database configuration parameters # # Log mode # ------------------------------------------------------------------------------- # Draw Line, pylogon in config # ------------------------------------------------------------------------------- def draw_object_tracking2(frame, ObjectTracker,label_t, color_id1) : # for object_track in ObjectTracker.currentObjects : color_id = int(str(object_track.objectID)[-2:]) x, y, w, h = object_track.bbox ycenter = object_track.trace[-1][1] xcenter = object_track.trace[-1][0] cv2.circle(frame, (xcenter, ycenter), 7, COLOR_YELLOW, -1) cv2.rectangle(frame, (x, y), (x+w, y+h),COLOR_TABEL_OB[color_id1], 2) label = "{}".format(label_t) labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.75, 1) top = max(y, labelSize[1]) cv2.rectangle(frame, (x - 1, top - round(labelSize[1])), (x+w+1, top ), COLOR_TABEL_OB[color_id1], cv2.FILLED) cv2.putText(frame, label, (x, top), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.75, COLOR_BLACK, lineType=cv2.LINE_AA) # text = "{}".format(object_track.objectID) # cv2.putText(frame, text, (x + 20, y + 20), # cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLOR_TABEL_OB[color_id1], 2) # for object_track in ObjectTracker.hiddenObjects : # color_id = int(str(object_track.objectID)[-2:]) # x, y, w, h = object_track.bbox # ycenter = object_track.trace[-1][1] # xcenter = object_track.trace[-1][0] # cv2.circle(frame, (xcenter, ycenter), 7, COLOR_GREEN, -1) # cv2.rectangle(frame, (x, y), (x+w, y+h),COLOR_TABEL_OB[color_id1], 2) # label = "{}".format(label_t) # labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.75, 1) # top = max(y, labelSize[1]) # cv2.rectangle(frame, (x - 1, top - round(labelSize[1])), (x+w+1, top ), COLOR_TABEL_OB[color_id1], cv2.FILLED) # cv2.putText(frame, label, (x, top), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.75, COLOR_BLACK, 1) # text = "{}".format(object_track.objectID) # cv2.putText(frame, text, (x + 20, y + 20), # cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLOR_TABEL_OB[color_id1], 2) # label = "Next ID : {}".format(str(ObjectTracker.nextObjectID)[-3:]) # cv2.putText(frame, label, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_YELLOW, 2) return frame # ------------------------------------------------------------------------------- # Draw Line, pylogon in config # ------------------------------------------------------------------------------- def draw_object_tracking(frame, ObjectTracker,label_t, color_id1) : # for object_track in ObjectTracker.currentObjects : color_id = int(str(object_track.objectID)[-2:]) x, y, w, h = object_track.bbox ycenter = object_track.trace[-1][1] xcenter = object_track.trace[-1][0] cv2.circle(frame, (xcenter, ycenter), 7, COLOR_YELLOW, -1) cv2.rectangle(frame, (x, y), (x+w, y+h),COLOR_TABEL_OB[color_id1], 2) label = "{}".format(label_t) labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.75, 1) top = max(y, labelSize[1]) cv2.rectangle(frame, (x - 1, top - round(labelSize[1])), (x+w+1, top ), COLOR_TABEL_OB[color_id1], cv2.FILLED) cv2.putText(frame, label, (x, top), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.75, COLOR_BLACK, 1) # text = "{}".format(object_track.objectID) # cv2.putText(frame, text, (x + 20, y + 20), # cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLOR_TABEL_OB[color_id1], 2) # for object_track in ObjectTracker.hiddenObjects : # color_id = int(str(object_track.objectID)[-2:]) # x, y, w, h = object_track.bbox # ycenter = object_track.trace[-1][1] # xcenter = object_track.trace[-1][0] # cv2.circle(frame, (xcenter, ycenter), 7, COLOR_YELLOW, -1) # cv2.rectangle(frame, (x, y), (x+w, y+h),COLOR_TABEL_OB[color_id1], 2) # label = "{}".format(label_t) # labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.75, 1) # top = max(y, labelSize[1]) # cv2.rectangle(frame, (x - 1, top - round(labelSize[1])), (x+w+1, top ), COLOR_TABEL_OB[color_id1], cv2.FILLED) # cv2.putText(frame, label, (x, top), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.75, COLOR_BLACK, 1) # text = "{}".format(object_track.objectID) # cv2.putText(frame, text, (x + 20, y + 20), # cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLOR_TABEL_OB[color_id1], 2) # label = "Next ID : {}".format(str(ObjectTracker.nextObjectID)[-3:]) # cv2.putText(frame, label, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, COLOR_YELLOW, 2) return frame # ------------------------------------------------------------------------------- # Draw Line, pylogon in config # -------------------------------------------------------------------------------
{"/utils_ken/log/__init__.py": ["/utils_ken/log/getlog.py"], "/utilslegend/utils_draw_2way.py": ["/utilslegend/utils_color.py"], "/utils/utils_polygon.py": ["/utils/utils_color.py"], "/utils_ken/video/video_stream.py": ["/utils_ken/log/getlog.py"], "/utils/utils_counter.py": ["/utils/CheckSideUtils.py"], "/utils/utils_draw_2way.py": ["/utils/utils_color.py"], "/utilslegend/utils_draw_polygon.py": ["/utilslegend/utils_color.py"], "/utils/utils_save_video.py": ["/utils_ken/log/getlog.py"], "/clear_video.py": ["/utils_machine.py", "/utils_ken/log/getlog.py"], "/utilslegend/utils_polygon.py": ["/utilslegend/utils_color.py"], "/utils_excel/utils_excel.py": ["/utils_ken/log/getlog.py", "/utilslegend/utils_mode_counter.py"], "/ubidots/utils_ubidots.py": ["/utils_ken/log/getlog.py"], "/light/lightapi.py": ["/utils_ken/log/getlog.py"], "/core/Core_theard.py": ["/utils_machine.py", "/trackmodel/centroidRecognize.py", "/utils_ken/log/getlog.py", "/utils/utils_mode_counter.py", "/utils/utils_save_video.py", "/utils/utils_color.py", "/utils/utils_polygon.py", "/utils/utils_counter.py", "/utils/utils_label_xml.py", "/ubidots/utils_ubidots.py", "/light/lightapi.py", "/detectmodel/setting.py"], "/run_apps.py": ["/utils_ken/log/getlog.py", "/core/Core_theard.py", "/utils/utils_polygon.py"]}
34,085
sirius-tinkoff-recsys-team/recsys-project
refs/heads/main
/src/features/group_and_compute_distances.py
import pandas as pd from haversine import haversine_vector from pandarallel import pandarallel from src.context import ctx from src.config import params def process_one_user(df_one_user): df_one_user = df_one_user.sort_values("timestamp") df_one_user["dist"] = 0 geopositions = df_one_user[["long", "lat"]].values df_one_user.iloc[1:, df_one_user.columns.get_loc("dist")] = haversine_vector( geopositions[:-1], geopositions[1:], ) return df_one_user def group_and_compute_distances(df): result = ( df .groupby("userId") .parallel_apply(process_one_user) ) result.index.names = ["index_0", "index_1"] return result if __name__ == "__main__": pandarallel.initialize(progress_bar=True) df = pd.read_csv(ctx.data_dir / "interim" / "label_encoded.csv") result = group_and_compute_distances(df) result.to_csv(ctx.data_dir / "interim" / "grouped_by_user_with_distances.csv")
{"/src/models/lstm/train.py": ["/src/models/lstm/data.py", "/src/models/lstm/model.py"]}
34,086
sirius-tinkoff-recsys-team/recsys-project
refs/heads/main
/src/features/categorize_geoposition.py
import pandas as pd from src.context import ctx from src.config import params def categorize_geoposition(df): result = df[[]].copy() result["round_long"] = df["long"].round(params.geoposition.round_precision).astype(str) result["round_lat"] = df["lat"].round(params.geoposition.round_precision).astype(str) result["geo_place"] = result["round_long"] + "_" + result["round_lat"] result = result[["geo_place"]] return result if __name__ == "__main__": df_filtered = pd.read_csv(ctx.data_dir / "interim" / "filtered_by_frequency.csv") result = categorize_geoposition(df_filtered) result.to_csv(ctx.data_dir / "interim" / "categorical_geoposition.csv", index=False)
{"/src/models/lstm/train.py": ["/src/models/lstm/data.py", "/src/models/lstm/model.py"]}
34,087
sirius-tinkoff-recsys-team/recsys-project
refs/heads/main
/serving/backend/main.py
import random from typing import Optional, List from glob import glob from time import sleep from fastapi import FastAPI import imagesize app = FastAPI() available_footage = list(glob("/footage/*.jpg")) + list(glob("../footage/*.jpg")) available_footage = [i for i in available_footage if "lazy" not in i] FIXED_WIDTH = 400 def _compute_height(width, height): return int(height / width * FIXED_WIDTH) def generate_items_from_item_ids(item_ids: List["str"]): image_uris = random.sample(available_footage, len(item_ids)) result = [] for i, item_id in enumerate(item_ids): try: width, height = imagesize.get(image_uris[i]) result.append({ "item_id": item_id, "url": image_uris[i], "lazy_url": image_uris[i].replace(".jpg", ".lazy.jpg"), "height": _compute_height(width, height), "title": "Top western road trips", "subtitle": "lat: -10.03, long: 123.04", "outlined": False, }) except: pass return result @app.get("/api") def read_root(): return {"status": "ok", "message": "it works"} @app.get("/api/options") def read_item(): return {"status": "ok", "items": generate_items_from_item_ids(range(70))} @app.post("/api/recommend") def read_item(items: List[str]): sleep(1.3) return {"status": "ok", "items": generate_items_from_item_ids(range(70))}
{"/src/models/lstm/train.py": ["/src/models/lstm/data.py", "/src/models/lstm/model.py"]}
34,088
sirius-tinkoff-recsys-team/recsys-project
refs/heads/main
/src/features/split_data_by_time.py
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from src.context import ctx from src.config import params def split_data(df): quantile = params.split.time_based_train_size dt = pd.to_datetime(df.timestamp) threshold = pd.to_datetime(np.quantile(dt.values.astype("int64"), quantile)) train_df, test_df = df[dt.values < threshold], df[dt.values >= threshold] return train_df, test_df if __name__ == "__main__": df = pd.read_csv(ctx.data_dir / "interim" / "grouped_by_user_with_distances.csv", index_col=[0, 1]) train_df, test_df = split_data(df) train_df.to_csv(ctx.data_dir / "interim" / "time_based_split_train.csv") test_df.to_csv(ctx.data_dir / "interim" / "time_based_split_test.csv")
{"/src/models/lstm/train.py": ["/src/models/lstm/data.py", "/src/models/lstm/model.py"]}
34,089
sirius-tinkoff-recsys-team/recsys-project
refs/heads/main
/serving/worker/main.py
from typing import Optional, List from fastapi import FastAPI app = FastAPI() @app.post("/api/predict") def read_item(items: List[str]): return {"status": "ok", "items": ["1", "2", "3"]}
{"/src/models/lstm/train.py": ["/src/models/lstm/data.py", "/src/models/lstm/model.py"]}
34,090
sirius-tinkoff-recsys-team/recsys-project
refs/heads/main
/src/models/lstm/data.py
import pandas as pd import pytorch_lightning as pl import torch from torch.utils.data import DataLoader from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence from src.context import ctx from src.config import params, config def _extract_key_from_dict_list(d, key): return [i[key] for i in d] def _pad_and_pack(sequence, sequence_lengths): sequence = list(map(torch.tensor, sequence)) sequence = pad_sequence(sequence, batch_first=True) return sequence def collate_fn(items): batch = dict() sequence_lengths = torch.tensor(_extract_key_from_dict_list(items, "sequence_lengths")) batch["sequence_lengths"] = sequence_lengths if "sequence" in items[0]: sequence = _extract_key_from_dict_list(items, "sequence") batch["sequence"] = _pad_and_pack(sequence, sequence_lengths) if "target" in items[0]: sequence = _extract_key_from_dict_list(items, "target") batch["target"] = _pad_and_pack(sequence, sequence_lengths) if "last_item" in items[0]: last_item = torch.tensor(_extract_key_from_dict_list(items, "last_item")) batch["last_item"] = last_item return batch class BrightkiteDataset: def __init__(self, frame, kind="train"): assert kind in ["train", "valid"] self.frame = frame self.kind = kind self.present_indices = self.frame.index.get_level_values(0).unique() def __getitem__(self, idx): user_history = self.frame.loc[self.present_indices[idx]] loc_id_sequence = user_history.loc_id.values item = dict() if self.kind == "train": item["sequence"] = loc_id_sequence[:-2] item["target"] = loc_id_sequence[1:-1] item["sequence_lengths"] = len(loc_id_sequence) - 2 else: item["sequence"] = loc_id_sequence[:-1] item["target"] = loc_id_sequence[1:] item["last_item"] = loc_id_sequence[-1] item["sequence_lengths"] = len(loc_id_sequence) - 1 return item def __len__(self): return len(self.present_indices) class BrightkiteDataModule(pl.LightningDataModule): def train_dataloader(self): train_frame = pd.read_csv(ctx.data_dir / "processed" / "train.csv", index_col=[0, 1]) self.train_dataset = BrightkiteDataset( frame=train_frame, kind="train" ) return DataLoader( dataset=self.train_dataset, batch_size=params.lstm.data.batch_size_train, num_workers=config.resources.dl_train.num_workers, collate_fn=collate_fn, ) def val_dataloader(self): # valid_frame = pd.read_csv(ctx.data_dir / "processed" / "test.csv", index_col=[0, 1]) train_frame = pd.read_csv(ctx.data_dir / "processed" / "train.csv", index_col=[0, 1]) self.valid_dataset = BrightkiteDataset( frame=train_frame, kind="valid" ) return DataLoader( dataset=self.valid_dataset, batch_size=params.lstm.data.batch_size_valid, num_workers=config.resources.dl_valid.num_workers, collate_fn=collate_fn, )
{"/src/models/lstm/train.py": ["/src/models/lstm/data.py", "/src/models/lstm/model.py"]}
34,091
sirius-tinkoff-recsys-team/recsys-project
refs/heads/main
/src/models/lstm/model.py
import numpy as np import pandas as pd import pytorch_lightning as pl from sklearn.metrics import top_k_accuracy_score import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import Adam from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts, ReduceLROnPlateau from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from src.context import ctx from src.config import params, config from src.logger import logger class LSTMModel(pl.LightningModule): def __init__(self, num_items): super().__init__() self.num_items = num_items self.item_embedding = nn.Embedding( num_embeddings=self.num_items, embedding_dim=params.lstm.model.embedding_dim, padding_idx=0, ) self.model = nn.LSTM( input_size=params.lstm.model.embedding_dim, hidden_size=params.lstm.model.hidden_dim, num_layers=params.lstm.model.num_layers, batch_first=True, dropout=params.lstm.model.dropout, ) self.linear = nn.Linear(params.lstm.model.hidden_dim, num_items) def forward(self, batch): sequence = batch["sequence"] sequence_lengths = batch["sequence_lengths"] sequence = self.item_embedding(sequence) packed_sequence = pack_padded_sequence(sequence, sequence_lengths.cpu(), batch_first=True, enforce_sorted=False) hidden_states, last_hidden_state = self.model(packed_sequence) padded_sequence, _ = pad_packed_sequence(hidden_states, batch_first=True) logits = self.linear(padded_sequence) return logits def training_step(self, batch, batch_idx): sequence = batch["sequence"] sequence_lengths = batch["sequence_lengths"] target = batch["target"] logits = self.forward(batch) loss = self.criterion(logits, target, sequence_lengths) logger.log_metric("train_loss", loss.item()) return {"loss": loss} def training_epoch_end(self, outputs): train_loss_mean = torch.stack([x["loss"] for x in outputs]).mean() logs = { "train_loss": train_loss_mean, } for key, value in logs.items(): logger.log_metric(key, value.item(), dvc=True) return def validation_step(self, batch, batch_idx): sequence = batch["sequence"] sequence_lengths = batch["sequence_lengths"] target = batch["target"] last_items = batch["last_item"] logits = self.forward(batch) loss = self.criterion(logits, target, sequence_lengths) last_item_predictions = torch.softmax(logits[:, -1], dim=1) accuracies = { f"valid_acc@{k}": top_k_accuracy_score( last_items.detach().cpu().numpy(), last_item_predictions.detach().cpu().numpy(), k=k, labels=np.arange(self.num_items) ) for k in [20, 50, 100] } return {"valid_loss": loss, **accuracies} def validation_epoch_end(self, outputs): valid_loss_mean = torch.stack([x["valid_loss"] for x in outputs]).mean() logs = { "valid_loss": valid_loss_mean, } for k in [20, 50, 100]: logs[f"valid_acc@{k}"] = np.mean([x[f"valid_acc@{k}"] for x in outputs]) for key, value in logs.items(): logger.log_metric(key, value.item(), dvc=True) return def criterion(self, logits, targets, sequence_lengths): mask = torch.zeros_like(targets).float() targets = targets.view(-1) predictions = torch.log_softmax(logits, dim=2) predictions = predictions.view(-1, self.num_items) for row, col in enumerate(sequence_lengths): mask[row, :col.item()] = 1. mask = mask.view(-1) valid_items = int(torch.sum(mask).item()) predictions = predictions[range(predictions.shape[0]), targets] * mask ce_loss = - torch.sum(predictions) / valid_items return ce_loss def configure_optimizers(self): self.optimizer = Adam(self.model.parameters(), lr=params.lstm.optimizer.learning_rate) return self.optimizer
{"/src/models/lstm/train.py": ["/src/models/lstm/data.py", "/src/models/lstm/model.py"]}
34,092
sirius-tinkoff-recsys-team/recsys-project
refs/heads/main
/src/models/lstm/train.py
import pickle import pytorch_lightning as pl from src.models.lstm.data import BrightkiteDataModule from src.models.lstm.model import LSTMModel from src.logger import init_logger from src.config import params from src.utils.lightning import DVCLiveCompatibleModelCheckpoint, DVCLiveNextStepCallback def train(): init_logger(tags=["debug"]) num_items = _get_num_items() model = LSTMModel(num_items) dm = BrightkiteDataModule() checkpoint_callback = DVCLiveCompatibleModelCheckpoint( dirpath="artifacts", filename="lstm", save_top_k=-1, verbose=True, ) dvclive_next_step_callback = DVCLiveNextStepCallback() trainer = pl.Trainer( checkpoint_callback=checkpoint_callback, deterministic=True, logger=False, max_epochs=params.lstm.optimizer.epochs, gpus=-1, callbacks=[dvclive_next_step_callback] ) trainer.fit(model, dm) def _get_num_items(): encoders = pickle.load(open("artifacts/label_encoders.pkl", "rb")) num_items = len(encoders["loc_id"].classes_) + 1 return num_items if __name__ == "__main__": train()
{"/src/models/lstm/train.py": ["/src/models/lstm/data.py", "/src/models/lstm/model.py"]}
34,093
sirius-tinkoff-recsys-team/recsys-project
refs/heads/main
/setup.py
import setuptools setuptools.setup( name="src", packages=setuptools.find_packages(), install_requires=[ "attrs", "python-box", "rich", "pandarallel", "haversine", "torch", "pytorch_lightning", "pandas", "numpy", "scikit-learn", "dvclive", "neptune-client", ], )
{"/src/models/lstm/train.py": ["/src/models/lstm/data.py", "/src/models/lstm/model.py"]}
34,094
sirius-tinkoff-recsys-team/recsys-project
refs/heads/main
/src/data/filter_by_frequency.py
import pandas as pd from src.context import ctx from src.config import params def filter_by_frequency(df): deduplicated = df.drop_duplicates( subset=["userId", "loc_id"], keep="first" ) location_to_unique_visitors_count = ( deduplicated .groupby("loc_id") .agg({"userId": "count"}) .reset_index() ) satisfying_locations = location_to_unique_visitors_count[ location_to_unique_visitors_count.userId > params.filter.required_unique_visitors ].loc_id df = df.loc[df.loc_id.isin(satisfying_locations)] deduplicated = df.drop_duplicates( subset=["userId", "loc_id"], keep="first" ) visitor_to_unique_places_count = ( deduplicated .groupby("userId") .agg({"loc_id": "count"}) .reset_index() ) satisfying_visitors = visitor_to_unique_places_count[ visitor_to_unique_places_count.loc_id > params.filter.required_unique_places ].userId result = df.loc[df.userId.isin(satisfying_visitors)] return result if __name__ == "__main__": df = pd.read_csv( ctx.data_dir / "raw" / "loc-brightkite_totalCheckins.txt", sep="\t", header=None, names=["userId","timestamp","long","lat","loc_id"], ) result = filter_by_frequency(df) result.to_csv(ctx.data_dir / "interim" / "filtered_by_frequency.csv", index=False)
{"/src/models/lstm/train.py": ["/src/models/lstm/data.py", "/src/models/lstm/model.py"]}
34,095
sirius-tinkoff-recsys-team/recsys-project
refs/heads/main
/src/features/label_encode.py
import pickle import pandas as pd from sklearn.preprocessing import LabelEncoder from src.context import ctx from src.config import params def label_encode(df, encoders=None): result = df.copy() encoders = encoders or dict() for col in ["userId", "loc_id", "geo_place"]: if col in encoders: encoder = encoders[col] result[col] = encoder.transform(df[col]) + 1 else: encoder = LabelEncoder() result[col] = encoder.fit_transform(df[col]) + 1 encoders[col] = encoder return result, encoders if __name__ == "__main__": df_filtered = pd.read_csv(ctx.data_dir / "interim" / "filtered_by_frequency.csv") df_categorical_geoposition = pd.read_csv(ctx.data_dir / "interim" / "categorical_geoposition.csv") df = pd.concat([df_filtered, df_categorical_geoposition], axis=1) result, encoders = label_encode(df) result.to_csv(ctx.data_dir / "interim" / "label_encoded.csv", index=False) pickle.dump(encoders, open(ctx.root_dir / "artifacts" / "label_encoders.pkl", "wb"))
{"/src/models/lstm/train.py": ["/src/models/lstm/data.py", "/src/models/lstm/model.py"]}
34,096
sirius-tinkoff-recsys-team/recsys-project
refs/heads/main
/src/features/split_data.py
import pandas as pd from sklearn.model_selection import train_test_split from src.context import ctx from src.config import params def split_data(df): unique_users = df.index.get_level_values(0).unique() users_train, users_test = train_test_split( unique_users, test_size=params.split.test_size, random_state=params.split.random_state, ) train_df, test_df = df.loc[users_train], df.loc[users_test] return train_df, test_df if __name__ == "__main__": df = pd.read_csv(ctx.data_dir / "interim" / "grouped_by_user_with_distances.csv", index_col=[0, 1]) train_df, test_df = split_data(df) train_df.to_csv(ctx.data_dir / "processed" / "train.csv") test_df.to_csv(ctx.data_dir / "processed" / "test.csv")
{"/src/models/lstm/train.py": ["/src/models/lstm/data.py", "/src/models/lstm/model.py"]}
34,132
arturkaa231/clickhouse_api
refs/heads/master
/WV/migrations/0011_auto_20170807_1137.py
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-08-07 11:37 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('WV', '0010_auto_20170725_1353'), ] operations = [ migrations.AlterField( model_name='options', name='text', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='WV.Data'), ), migrations.AlterField( model_name='tags', name='text', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='TAGS', to='WV.Data'), ), ]
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,133
arturkaa231/clickhouse_api
refs/heads/master
/spyrecorder/urls.py
from django.conf.urls import url from spyrecorder import views urlpatterns = [ url(r'^',views.AddCH, name='AddCH'), ]
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,134
arturkaa231/clickhouse_api
refs/heads/master
/WV/apps.py
from django.apps import AppConfig class WvConfig(AppConfig): name = 'WV'
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,135
arturkaa231/clickhouse_api
refs/heads/master
/log_downloader.py
from lxml import etree from time import time from datetime import datetime,timedelta import xml.etree.ElementTree as ET from infi.clickhouse_orm import models as md from infi.clickhouse_orm import fields as fd from infi.clickhouse_orm import engines as en from infi.clickhouse_orm.database import Database import sys import requests class Hits_with_visits(md.Model): # describes datatypes and fields idSite=fd.Int32Field() idVisit = fd.UInt64Field() visitIp=fd.StringField(default='none') visitorId=fd.StringField() goalConversions=fd.UInt64Field() siteCurrency=fd.StringField() siteCurrencySymbol=fd.StringField() serverDate=fd.DateField() visitServerHour=fd.UInt64Field() lastActionTimestamp=fd.UInt64Field() lastActionDateTime=fd.StringField() userId=fd.StringField() visitorType=fd.StringField() visitorTypeIcon=fd.StringField() visitConverted=fd.UInt64Field() visitConvertedIcon=fd.StringField() visitCount=fd.UInt64Field() firstActionTimestamp=fd.UInt64Field() visitEcommerceStatus=fd.StringField() visitEcommerceStatusIcon=fd.StringField() daysSinceFirstVisit=fd.UInt64Field() daysSinceLastEcommerceOrder=fd.UInt64Field() visitDuration=fd.UInt64Field() visitDurationPretty=fd.StringField() searches=fd.UInt64Field() actions=fd.UInt64Field() interactions=fd.UInt64Field() referrerType=fd.StringField() referrerTypeName=fd.StringField() referrerName=fd.StringField() referrerKeyword=fd.StringField() referrerKeywordPosition=fd.UInt64Field() referrerUrl=fd.StringField() referrerSearchEngineUrl=fd.StringField() referrerSearchEngineIcon=fd.StringField() languageCode=fd.StringField() language=fd.StringField() deviceType=fd.StringField() deviceTypeIcon=fd.StringField() deviceBrand=fd.StringField() deviceModel=fd.StringField() operatingSystem=fd.StringField() operatingSystemName=fd.StringField() operatingSystemIcon=fd.StringField() operatingSystemCode=fd.StringField() operatingSystemVersion=fd.StringField() browserFamily=fd.StringField() browserFamilyDescription=fd.StringField() browser=fd.StringField() browserName=fd.StringField() browserIcon=fd.StringField() browserCode=fd.StringField() browserVersion=fd.StringField() events=fd.UInt64Field() continent=fd.StringField() continentCode=fd.StringField() country=fd.StringField() countryCode=fd.StringField() countryFlag=fd.StringField() region=fd.StringField() regionCode=fd.StringField() city=fd.StringField() location=fd.StringField() latitude=fd.Float64Field() longitude=fd.Float64Field() visitLocalTime=fd.StringField() visitLocalHour=fd.UInt64Field() daysSinceLastVisit=fd.UInt64Field() customVariables=fd.StringField() resolution=fd.StringField() plugins=fd.StringField() pluginsIcons=fd.StringField() provider=fd.StringField() providerName=fd.StringField() providerUrl=fd.StringField() dimension1=fd.StringField() campaignId=fd.StringField() campaignContent=fd.StringField() campaignKeyword=fd.StringField() campaignMedium=fd.StringField() campaignName=fd.StringField() campaignSource=fd.StringField() serverTimestamp=fd.UInt64Field() serverTimePretty=fd.StringField() serverDatePretty=fd.StringField() serverDatePrettyFirstAction=fd.StringField() serverTimePrettyFirstAction=fd.StringField() totalEcommerceRevenue=fd.Float64Field() totalEcommerceConversions=fd.UInt64Field() totalEcommerceItems=fd.UInt64Field() totalAbandonedCartsRevenue=fd.Float64Field() totalAbandonedCarts=fd.UInt64Field() totalAbandonedCartsItems=fd.UInt64Field() AdCampaignId=fd.StringField() AdBannerId=fd.StringField() AdChannelId=fd.StringField() AdDeviceType=fd.StringField() AdGroupId=fd.StringField() AdKeywordId=fd.StringField() AdPosition=fd.StringField() AdPositionType=fd.StringField() AdRegionId=fd.StringField() AdRetargetindId=fd.StringField() AdPlacement=fd.StringField() AdTargetId=fd.StringField() AdvertisingSystem=fd.StringField() DRF=fd.StringField() Gclid=fd.StringField() SmartClickId=fd.StringField() Type=fd.StringField() goalName=fd.StringField(default='none') goalId=fd.UInt64Field() revenue=fd.UInt64Field() goalPageId=fd.StringField(default='none') url=fd.StringField(default='none') pageTitle=fd.StringField(default='none') pageIdAction=fd.UInt64Field(default=0) pageId=fd.UInt64Field(default=0) generationTimeMilliseconds=fd.UInt64Field(default=0) generationTime=fd.StringField() interactionPosition=fd.UInt64Field(default=0) icon=fd.StringField(default='none') timestamp=fd.UInt64Field(default=0) idpageview=fd.StringField(default='none') serverTimePrettyHit=fd.StringField() sign=fd.Int8Field() # creating an sampled MergeTree engine = en.CollapsingMergeTree('serverDate', ('idSite','idVisit','visitIp','visitorId','goalConversions','siteCurrency','siteCurrencySymbol','serverDate','visitServerHour', 'lastActionTimestamp','lastActionDateTime','userId','visitorType','visitorTypeIcon','visitConverted','visitConvertedIcon', 'visitCount','firstActionTimestamp','visitEcommerceStatus','visitEcommerceStatusIcon','daysSinceFirstVisit','daysSinceLastEcommerceOrder', 'visitDuration','visitDurationPretty','searches','actions','interactions','referrerType','referrerTypeName','referrerName','referrerKeyword', 'referrerKeywordPosition','referrerUrl','referrerSearchEngineUrl','referrerSearchEngineIcon','languageCode','language','deviceType','deviceTypeIcon','deviceBrand','deviceModel', 'operatingSystem','operatingSystemName','operatingSystemIcon','operatingSystemCode','operatingSystemVersion','browserFamily','browserFamilyDescription', 'browser','browserName','browserIcon','browserCode','browserVersion','events','continent','continentCode', 'country','countryCode','countryFlag','region','regionCode','city','location','latitude','longitude','visitLocalTime','visitLocalHour', 'daysSinceLastVisit','customVariables','resolution','plugins','pluginsIcons','provider','providerName','providerUrl','dimension1','campaignId', 'campaignContent','campaignKeyword','campaignMedium','campaignName','campaignSource','serverTimestamp','serverTimePretty','serverDatePretty', 'serverDatePrettyFirstAction','serverTimePrettyFirstAction','totalEcommerceRevenue','totalEcommerceConversions','totalEcommerceItems','totalAbandonedCartsRevenue', 'totalAbandonedCarts','totalAbandonedCartsItems','AdCampaignId','AdBannerId','AdChannelId','AdDeviceType','AdGroupId','AdKeywordId','AdPosition','AdPositionType', 'AdRegionId','AdRetargetindId','AdPlacement','AdTargetId','AdvertisingSystem','DRF','Gclid','SmartClickId','Type','goalName','goalId','revenue','goalPageId','url','pageTitle','pageIdAction', 'pageId','generationTimeMilliseconds','generationTime','interactionPosition','icon','timestamp','idpageview','serverTimePrettyHit'),'sign') def safely_get_data(element, key): try: for child in element: if child.tag == key: return child.text except: return "not found" def get_clickhouse_data(query,host,connection_timeout=1500): r=requests.post(host,params={'query':query},timeout=connection_timeout) return r.text def parse_clickhouse_xml(filename, db_name, db_host): hits_buffer =[] tree = ET.fromstring(filename) #root = tree.getroot() #for i in root: #print(i.tag) for result in tree: idSite=safely_get_data(result, 'idSite') idVisit=safely_get_data(result, 'idVisit') visitIp=safely_get_data(result, 'visitIp') visitorId=safely_get_data(result, 'visitorId') goalConversions =safely_get_data(result, 'goalConversions') siteCurrency=safely_get_data(result, 'siteCurrency') siteCurrencySymbol=safely_get_data(result, 'siteCurrencySymbol') serverDate=safely_get_data(result, 'serverDate') visitServerHour=safely_get_data(result, 'visitServerHour') lastActionTimestamp =safely_get_data(result, 'lastActionTimestamp') lastActionDateTime =safely_get_data(result, 'lastActionDateTime') userId=safely_get_data(result, 'userId') visitorType= safely_get_data(result, 'visitorType') visitorTypeIcon=safely_get_data(result, 'visitorTypeIcon') visitConverted =safely_get_data(result, 'visitConverted') visitConvertedIcon =safely_get_data(result, 'visitConvertedIcon') visitCount =safely_get_data(result, 'visitCount') firstActionTimestamp =safely_get_data(result, 'firstActionTimestamp') visitEcommerceStatus =safely_get_data(result, 'visitEcommerceStatus') visitEcommerceStatusIcon =safely_get_data(result, 'visitEcommerceStatusIcon') daysSinceFirstVisit =safely_get_data(result, 'daysSinceFirstVisit') daysSinceLastEcommerceOrder =safely_get_data(result, 'daysSinceLastEcommerceOrder') visitDuration =safely_get_data(result, 'visitDuration') visitDurationPretty =safely_get_data(result, 'visitDurationPretty') searches =safely_get_data(result, 'searches') actions =safely_get_data(result, 'actions') interactions =safely_get_data(result, 'interactions') referrerType =safely_get_data(result, 'referrerType') referrerTypeName =safely_get_data(result, 'referrerTypeName') referrerName =safely_get_data(result, 'referrerName') referrerKeyword =safely_get_data(result, 'referrerKeyword') referrerKeywordPosition =safely_get_data(result, 'referrerKeywordPosition') referrerUrl =safely_get_data(result, 'referrerUrl') referrerSearchEngineUrl=safely_get_data(result, 'referrerSearchEngineUrl') referrerSearchEngineIcon =safely_get_data(result, 'referrerSearchEngineIcon') languageCode =safely_get_data(result, 'languageCode') language =safely_get_data(result, 'language') deviceType =safely_get_data(result, 'deviceType') deviceTypeIcon =safely_get_data(result, 'deviceTypeIcon') deviceBrand =safely_get_data(result, 'deviceBrand') deviceModel =safely_get_data(result, 'deviceModel') operatingSystem =safely_get_data(result, 'operatingSystem') operatingSystemName =safely_get_data(result, 'operatingSystemName') operatingSystemIcon =safely_get_data(result, 'operatingSystemIcon') operatingSystemCode =safely_get_data(result, 'operatingSystemCode') operatingSystemVersion =safely_get_data(result, 'operatingSystemVersion') browserFamily =safely_get_data(result, 'browserFamily') browserFamilyDescription =safely_get_data(result, 'browserFamilyDescription') browser =safely_get_data(result, 'browser') browserName =safely_get_data(result, 'browserName') browserIcon =safely_get_data(result, 'browserIcon') browserCode =safely_get_data(result, 'browserCode') browserVersion =safely_get_data(result, 'browserVersion') events =safely_get_data(result, 'events') continent =safely_get_data(result, 'continent') continentCode=safely_get_data(result, 'continentCode') country =safely_get_data(result, 'country') countryCode =safely_get_data(result, 'countryCode') countryFlag =safely_get_data(result, 'countryFlag') region =safely_get_data(result, 'region') regionCode =safely_get_data(result, 'regionCode') city =safely_get_data(result, 'city') location =safely_get_data(result, 'location') latitude =safely_get_data(result, 'latitude') longitude =safely_get_data(result, 'longitude') visitLocalTime =safely_get_data(result, 'visitLocalTime') visitLocalHour =safely_get_data(result, 'visitLocalHour') daysSinceLastVisit =safely_get_data(result, 'daysSinceLastVisit') customVariables =safely_get_data(result, 'customVariables') resolution =safely_get_data(result, 'resolution') plugins =safely_get_data(result, 'plugins') pluginsIcons =safely_get_data(result, 'pluginsIcons') provider =safely_get_data(result, 'provider') providerName =safely_get_data(result, 'providerName') providerUrl =safely_get_data(result, 'providerUrl') dimension1 =safely_get_data(result, 'dimension1') campaignId =safely_get_data(result, 'campaignId') campaignContent =safely_get_data(result, 'campaignContent') campaignKeyword =safely_get_data(result, 'campaignKeyword') campaignMedium =safely_get_data(result, 'campaignMedium') campaignName =safely_get_data(result, 'campaignName') campaignSource =safely_get_data(result, 'campaignSource') serverTimestamp=safely_get_data(result, 'serverTimestamp') serverTimePretty=safely_get_data(result, 'serverTimePretty') serverDatePretty=safely_get_data(result, 'serverDatePretty') serverDatePrettyFirstAction =safely_get_data(result, 'serverDatePrettyFirstAction') serverTimePrettyFirstAction =safely_get_data(result, 'serverTimePrettyFirstAction') totalEcommerceRevenue =safely_get_data(result, 'totalEcommerceRevenue') totalEcommerceConversions =safely_get_data(result, 'totalEcommerceConversions') totalEcommerceItems =safely_get_data(result, 'totalEcommerceItems') totalAbandonedCartsRevenue=safely_get_data(result, 'totalAbandonedCartsRevenue') totalAbandonedCarts =safely_get_data(result, 'totalAbandonedCarts') totalAbandonedCartsItems=safely_get_data(result, 'totalAbandonedCartsItems') AdCampaignId=safely_get_data(result, 'AdCampaignId') AdBannerId=safely_get_data(result, 'AdBannerId') AdChannelId=safely_get_data(result, 'AdChannelId') AdDeviceType=safely_get_data(result, 'AdDeviceType') AdGroupId=safely_get_data(result, 'AdGroupId') AdKeywordId=safely_get_data(result, 'AdKeywordId') AdPosition=safely_get_data(result, 'AdPosition') AdPositionType=safely_get_data(result, 'AdPositionType') AdRegionId=safely_get_data(result, 'AdRegionId') AdRetargetindId=safely_get_data(result, 'AdRetargetingId') AdPlacement=safely_get_data(result, 'AdPlacementId') AdTargetId=safely_get_data(result, 'AdTargetId') AdvertisingSystem=safely_get_data(result, 'AdvertisingSystem') DRF=safely_get_data(result, 'DRF') Gclid=safely_get_data(result, 'Gclid') SmartClickId=safely_get_data(result, 'SmartClickId') strings=[visitIp,visitorId,siteCurrency,siteCurrencySymbol,lastActionDateTime,userId,visitorType,visitorTypeIcon,visitConvertedIcon,visitEcommerceStatus,visitEcommerceStatusIcon, visitDurationPretty,referrerType,referrerTypeName,referrerName,referrerKeyword,referrerUrl,referrerSearchEngineUrl,referrerSearchEngineIcon,languageCode,language,deviceType,deviceTypeIcon,deviceBrand,deviceModel, operatingSystem,operatingSystemName,operatingSystemIcon,operatingSystemCode,operatingSystemVersion,browserFamily,browserFamilyDescription, browser,browserName,browserIcon,browserCode,browserVersion,continent,continentCode, country,countryCode,countryFlag,region,regionCode,city,location,visitLocalTime,customVariables,resolution,plugins,pluginsIcons,provider,providerName,providerUrl,dimension1,campaignId, campaignContent,campaignKeyword,campaignMedium,campaignName,campaignSource,serverTimePretty,serverDatePretty, serverDatePrettyFirstAction,serverTimePrettyFirstAction,AdCampaignId,AdBannerId,AdChannelId,AdDeviceType,AdGroupId,AdKeywordId,AdPosition,AdPositionType, AdRegionId,AdRetargetindId,AdPlacement,AdTargetId,AdvertisingSystem,DRF,Gclid,SmartClickId] ints=[idSite,idVisit,goalConversions,visitServerHour,lastActionTimestamp,visitConverted,visitCount,firstActionTimestamp,daysSinceFirstVisit,daysSinceLastEcommerceOrder,visitDuration,searches,actions, interactions,referrerKeywordPosition,events,latitude,longitude,visitLocalHour,daysSinceLastVisit,serverTimestamp,totalEcommerceRevenue,totalEcommerceConversions,totalEcommerceItems,totalAbandonedCartsRevenue, totalAbandonedCarts,totalAbandonedCartsItems] for i in range(len(strings)): if strings[i] == None: strings[i]='none' for i in range(len(ints)): if ints[i] == None: ints[i]=0 for res in result.find('actionDetails'): print('hui') Type=safely_get_data(res, 'type') goalName=safely_get_data(res, 'goalName') goalId=safely_get_data(res, 'goalId') revenue=safely_get_data(res, 'revenue') goalPageId=safely_get_data(res, 'goalPageId') url=safely_get_data(res, 'url') pageTitle=safely_get_data(res, 'pageTitle') pageIdAction=safely_get_data(res, 'pageIdAction') pageId=safely_get_data(res, 'pageId') generationTimeMilliseconds=safely_get_data(res, 'generationTimeMilliseconds') generationTime=safely_get_data(res, 'generationTime') interactionPosition=safely_get_data(res, 'interactionPosition') icon=safely_get_data(res, 'icon') timestamp=safely_get_data(res, 'timestamp') idpageview=safely_get_data(res, 'idpageview') serverTimePrettyHit=safely_get_data(res, 'serverTimePretty') Astrings=[Type,goalName,goalPageId,url,pageTitle,generationTime,icon,idpageview,serverTimePrettyHit] Aints=[goalId,revenue,pageIdAction,pageId,generationTimeMilliseconds,interactionPosition,timestamp] for i in range(len(Astrings)): if Astrings[i] == None or Astrings[i] == '': Astrings[i]='none' for i in range(len(Aints)): if Aints[i] == None or Aints[i] == '' : Aints[i]=0 insert_hits = Hits_with_visits( idSite=ints[0], idVisit=ints[1], visitIp=strings[0], visitorId=strings[1], goalConversions=ints[2], siteCurrency=strings[2], siteCurrencySymbol=strings[3], serverDate=serverDate, visitServerHour=ints[3], lastActionTimestamp=ints[4], lastActionDateTime=strings[4], userId=strings[5], visitorType=strings[6], visitorTypeIcon=strings[7], visitConverted=ints[5], visitConvertedIcon=strings[8], visitCount=ints[6], firstActionTimestamp=ints[7], visitEcommerceStatus=strings[9], visitEcommerceStatusIcon=strings[10], daysSinceFirstVisit=ints[8], daysSinceLastEcommerceOrder=ints[9], visitDuration=ints[10], visitDurationPretty=strings[11], searches=ints[11], actions=ints[12], interactions=ints[13], referrerType=strings[12], referrerTypeName=strings[13], referrerName=strings[14], referrerKeyword=strings[15], referrerKeywordPosition=ints[14], referrerUrl=strings[16], referrerSearchEngineUrl=strings[17], referrerSearchEngineIcon=strings[18], languageCode=strings[19], language=strings[20], deviceType=strings[21], deviceTypeIcon=strings[22], deviceBrand=strings[23], deviceModel=strings[24], operatingSystem=strings[25], operatingSystemName=strings[26], operatingSystemIcon=strings[27], operatingSystemCode=strings[28], operatingSystemVersion=strings[29], browserFamily=strings[30], browserFamilyDescription=strings[31], browser=strings[32], browserName=strings[33], browserIcon=strings[34], browserCode=strings[35], browserVersion=strings[36], events=ints[15], continent=strings[37], continentCode=strings[38], country=strings[39], countryCode=strings[40], countryFlag=strings[41], region=strings[42], regionCode=strings[43], city=strings[44], location=strings[45], latitude=ints[16], longitude=ints[17], visitLocalTime=strings[46], visitLocalHour=ints[18], daysSinceLastVisit=ints[19], customVariables=strings[47], resolution=strings[48], plugins=strings[49], pluginsIcons=strings[50], provider=strings[51], providerName=strings[52], providerUrl=strings[53], dimension1=strings[54], campaignId=strings[55], campaignContent=strings[56], campaignKeyword=strings[57], campaignMedium=strings[58], campaignName=strings[59], campaignSource=strings[60], serverTimestamp=ints[20], serverTimePretty=strings[61], serverDatePretty=strings[62], serverDatePrettyFirstAction=strings[63], serverTimePrettyFirstAction=strings[64], totalEcommerceRevenue=ints[21], totalEcommerceConversions=ints[22], totalEcommerceItems=ints[23], totalAbandonedCartsRevenue=ints[24], totalAbandonedCarts=ints[25], totalAbandonedCartsItems=ints[26], AdCampaignId=strings[65], AdBannerId=strings[66], AdChannelId=strings[67], AdDeviceType=strings[68], AdGroupId=strings[69], AdKeywordId=strings[70], AdPosition=strings[71], AdPositionType=strings[72], AdRegionId=strings[73], AdRetargetindId=strings[74], AdPlacement=strings[75], AdTargetId=strings[76], AdvertisingSystem=strings[77], DRF=strings[78], Gclid=strings[79], SmartClickId=strings[80], Type=Astrings[0], goalName=Astrings[1], goalId=Aints[0], revenue=Aints[1], goalPageId=Astrings[2], url=Astrings[3], pageTitle=Astrings[4], pageIdAction=Aints[2], pageId=Aints[3], generationTimeMilliseconds=Aints[4], generationTime=Astrings[5], interactionPosition=Aints[5], icon=Astrings[6], timestamp=Aints[6], idpageview=Astrings[7], serverTimePrettyHit=Astrings[8], sign=1, ) # appends data into couple hits_buffer.append(insert_hits) res.clear() result.clear() # open database with database name and database host values db = Database(db_name, db_url=db_host) # create table to insert prepared data insert prepared data into # database db.insert(hits_buffer) if __name__ == '__main__': create_query="""CREATE TABLE CHdatabase.hits_with_visits (idSite Int32,idVisit Int,visitIp String,visitorId String,goalConversions Int,siteCurrency String,siteCurrencySymbol String,serverDate Date,visitServerHour Int, lastActionTimestamp Int,lastActionDateTime String,userId String,visitorType String,visitorTypeIcon String ,visitConverted Int,visitConvertedIcon String, visitCount Int,firstActionTimestamp Int,visitEcommerceStatus String,visitEcommerceStatusIcon String,daysSinceFirstVisit Int,daysSinceLastEcommerceOrder Int, visitDuration Int,visitDurationPretty String,searches Int,actions Int,interactions Int,referrerType String,referrerTypeName String,referrerName String,referrerKeyword String, referrerKeywordPosition Int,referrerUrl String,referrerSearchEngineUrl String,referrerSearchEngineIcon String,languageCode String,language String,deviceType String,deviceTypeIcon String,deviceBrand String,deviceModel String, operatingSystem String,operatingSystemName String,operatingSystemIcon String,operatingSystemCode String,operatingSystemVersion String,browserFamily String,browserFamilyDescription String, browser String,browserName String,browserIcon String,browserCode String,browserVersion String,events Int,continent String,continentCode String, country String,countryCode String,countryFlag String,region String,regionCode String,city String,location String,latitude Float,longitude Float,visitLocalTime String,visitLocalHour Int, daysSinceLastVisit Int,customVariables String,resolution String,plugins String,pluginsIcons String,provider String,providerName String,providerUrl String,dimension1 String,campaignId String, campaignContent String,campaignKeyword String,campaignMedium String,campaignName String,campaignSource String,serverTimestamp Int,serverTimePretty String,serverDatePretty String, serverDatePrettyFirstAction String,serverTimePrettyFirstAction String,totalEcommerceRevenue Float,totalEcommerceConversions Int,totalEcommerceItems Int,totalAbandonedCartsRevenue Float, totalAbandonedCarts Int,totalAbandonedCartsItems Int,AdCampaignId String,AdBannerId String,AdChannelId String,AdDeviceType String,AdGroupId String,AdKeywordId String,AdPosition String,AdPositionType String, AdRegionId String,AdRetargetindId String,AdPlacement String,AdTargetId String,AdvertisingSystem String,DRF String,Gclid String,SmartClickId String,Type String,goalName String,goalId Int,revenue Int,goalPageId String,url String,pageTitle String,pageIdAction Int, pageId Int,generationTimeMilliseconds Int,generationTime String,interactionPosition Int,icon String,timestamp String,idpageview String,serverTimePrettyHit Int,sign Int32) engine=CollapsingMergeTree(sign) PARTITION BY (idSite,serverDate) ORDER BY (visitIp,visitorId,siteCurrency,siteCurrencySymbol,lastActionDateTime,userId,visitorType,visitorTypeIcon,visitConvertedIcon,visitEcommerceStatus,visitEcommerceStatusIcon, visitDurationPretty,referrerType,referrerTypeName,referrerName,referrerKeyword,referrerUrl,referrerSearchEngineUrl,referrerSearchEngineIcon,languageCode,language,deviceType,deviceTypeIcon,deviceBrand,deviceModel, operatingSystem,operatingSystemName,operatingSystemIcon,operatingSystemCode,operatingSystemVersion,browserFamily,browserFamilyDescription, browser,browserName,browserIcon,browserCode,browserVersion,continent,continentCode, country,countryCode,countryFlag,region,regionCode,city,location,visitLocalTime,customVariables,resolution,plugins,pluginsIcons,provider,providerName,providerUrl,dimension1,campaignId, campaignContent,campaignKeyword,campaignMedium,campaignName,campaignSource,serverTimePretty,serverDatePretty, serverDatePrettyFirstAction,serverTimePrettyFirstAction,AdCampaignId,AdBannerId,AdChannelId,AdDeviceType,AdGroupId,AdKeywordId,AdPosition,AdPositionType, AdRegionId,AdRetargetindId,AdPlacement,AdTargetId,AdvertisingSystem,DRF,Gclid,SmartClickId,idSite,idVisit,goalConversions,visitServerHour,lastActionTimestamp,visitConverted,visitCount,firstActionTimestamp,daysSinceFirstVisit,daysSinceLastEcommerceOrder,visitDuration, interactions,referrerKeywordPosition,latitude,longitude,visitLocalHour,daysSinceLastVisit,serverTimestamp,totalEcommerceRevenue,totalEcommerceConversions,totalEcommerceItems,totalAbandonedCartsRevenue, totalAbandonedCarts,totalAbandonedCartsItems,Type,goalName,goalPageId,url,pageTitle,generationTime,icon,idpageview,serverTimePrettyHit,goalId,revenue,pageIdAction,pageId,generationTimeMilliseconds,interactionPosition,timestamp)""" xml=requests.get('https://robodigital.ru/pdev/?module=API&method=Live.getLastVisitsDetails&idSite=2&period=range&date={date1},{date2}&format=XML&token_auth=eeb033448123fc92e83478b5b63d8af3&countVisitorsToFetch=1000'.format(date1=datetime.today().strftime('%Y-%m-%d'),date2=datetime.today().strftime('%Y-%m-%d'))).content parse_clickhouse_xml( xml, 'CHdatabase', 'http://85.143.172.199:8123')
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,136
arturkaa231/clickhouse_api
refs/heads/master
/WV/migrations/0008_auto_20170724_1635.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-07-24 13:35 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('WV', '0007_auto_20170724_1624'), ] operations = [ migrations.RenameField( model_name='options', old_name='components', new_name='div', ), migrations.AddField( model_name='options', name='script', field=models.TextField(blank=True, default=None, null=True), ), ]
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,137
arturkaa231/clickhouse_api
refs/heads/master
/test.py
import json import requests import time from datetime import datetime, timedelta from io import BytesIO import pandas as pd from infi.clickhouse_orm import models as md from infi.clickhouse_orm import fields as fd from infi.clickhouse_orm import engines as en from infi.clickhouse_orm.database import Database import pprint from urllib.parse import urlparse from urllib.parse import parse_qs from googleads import oauth2 import xmltodict import os from googleads import adwords from Word2Vec import settings class Adstat(md.Model): idSite=fd.UInt64Field() AdCampaignId=fd.StringField() AdBannerId=fd.StringField() AdDeviceType=fd.StringField() AdGroupId=fd.StringField() AdKeywordId=fd.StringField() AdPosition=fd.StringField() AdPositionType=fd.StringField() AdRegionId=fd.StringField() AdRetargetindId=fd.StringField() AdPlacement=fd.StringField() AdTargetId=fd.StringField() AdvertisingSystem=fd.StringField() DRF=fd.StringField() campaignContent=fd.StringField() campaignKeyword=fd.StringField() campaignMedium=fd.StringField() campaignName=fd.StringField() campaignSource=fd.StringField() StatDate=fd.DateField() StatDateTime = fd.DateTimeField() Impressions=fd.UInt64Field() Clicks=fd.UInt64Field() Cost=fd.Float64Field() IntegrationId=fd.StringField() Sign = fd.Int8Field() engine = en.CollapsingMergeTree(('StatDate','IntegrationId'),('StatDate','IntegrationId','idSite','AdCampaignId','AdBannerId','AdDeviceType','AdGroupId','AdKeywordId','AdPosition' ,'AdPositionType','AdRegionId','AdRetargetindId','AdPlacement','AdTargetId','AdvertisingSystem','DRF', 'campaignContent','campaignKeyword','campaignMedium','campaignName','campaignSource','StatDateTime'),'Sign') def get_clickhouse_data(query, host, connection_timeout=1000050): """Метод для обращения к базе данных CH""" r = requests.post(host, params={'query': query}, timeout=connection_timeout) return r.text def chunks(l,n): for i in range(0,len(l),n): yield l[i:i+n] def ga_stat_daily(integration, period1, period2): ''' integration={ "id": 1, "credential": { "expires_in": 31536000, "token_type": "bearer", "access_token": "AQAAAAALL2cIAAGQs2VDPflIVkTSsKxS-uLw9Rk", "refresh_token": "1:jogkSFI-GF5Xwd2X:_bgdvu3yWWEnMfZPJoZbkZodqpnFszGMQ3fetlSbJn-fd9w7SJH6:NSLR-Jf7eYA1LzRvs9t32w" }, "active": true, "settings": { "ad_client_id": 18 }, "type": 3, "site": 35 } period1=date('2018-01-01') period2=date('2018-02-01') ''' past_hour = "'" + (datetime.now() - timedelta(hours=2)).strftime('%Y-%m-%d %H:00:00') + "'" StatDate = "'" + str(datetime.now().strftime('%Y-%m-%d')) + "'" if int(datetime.now().strftime('%H')) == 1: past_hour = "'" + (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d 23:00:00') + "'" StatDate = "'" + str((datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')) + "'" client = json.loads(requests.get('https://s.analitika.online/api/ad/ad_clients?id={id}'.format(id=integration['settings']['ad_client_id']),headers=headers).content.decode('utf-8'))['results'][0] print(client) # Проверка. Берем из таблицы данные за прошлый час и сравниваем с текущими данными, если показатели изменились, то записываем в таблицу эту разницу query = """SELECT toString(idSite),AdCampaignId,AdBannerId,AdDeviceType,AdGroupId,AdKeywordId,AdPosition,AdPositionType,AdRegionId,AdRetargetindId,AdPlacement,AdTargetId,AdvertisingSystem,DRF,StatDate,toString(IntegrationId),Impressions,Clicks,Cost FROM CHdatabase.adstat WHERE StatDate={StatDate} FORMAT JSON""".format( StatDate=StatDate, hour=past_hour) last_day = json.loads(get_clickhouse_data(query, 'http://46.4.81.36:8123'))['data'] stat_days = [] delta = int((period2 - period1).days) total_sum = 0 total_clicks = 0 ad_units = json.loads(requests.get( 'https://s.analitika.online/api/ad/ad_units?adclient__id={id}'.format(id=integration['settings']['ad_client_id']),headers=headers).content.decode('utf-8')) banners = ad_units['results'][0]['banners'] keywords = ad_units['results'][0]['keywords'] campaigns = ad_units['results'][0]['campaigns'] adgroups = ad_units['results'][0]['ad_groups'] d_t = datetime.now() REFRESH_TOKEN = integration['credential']['refresh_token'] oauth2_client = oauth2.GoogleRefreshTokenClient(settings.ADWORDS_CLIENT_ID, settings.ADWORDS_CLIENT_SECRET, REFRESH_TOKEN) adwords_client = adwords.AdWordsClient(settings.ADWORDS_DEVELOPER_TOKEN, oauth2_client, settings.ADWORDS_USER_AGENT, client_customer_id=client['client_id']) report_downloader = adwords_client.GetReportDownloader(version='v201705') report = { 'reportName': 'Last 7 days AD_PERFORMANCE_REPORT', 'dateRangeType': 'CUSTOM_DATE', 'reportType': 'AD_PERFORMANCE_REPORT', 'downloadFormat': 'XML', 'selector': { 'dateRange': {'min': period1.strftime("%Y%m%d"), 'max': period2.strftime("%Y%m%d")}, 'fields': ['CampaignId', 'AdGroupId', 'Device', 'Slot', 'AdNetworkType2', 'AveragePosition', 'CreativeFinalUrls', 'CreativeTrackingUrlTemplate', 'Id', 'CriterionId', 'Date', 'Cost', 'Clicks', 'Impressions'], } } raw_data = report_downloader.DownloadReportAsString(report, skip_report_header=True, skip_column_header=True, skip_report_summary=True) if len(raw_data) > 0: v = json.dumps(xmltodict.parse(raw_data)) ad_stat = json.loads(v.replace('@', ''))['report']['table']['row'] else: ad_stat = [] temp = [] kws_stat = {} device_map = { 'Mobile devices with full browsers': 'mobile', 'Tablets with full browsers': 'tablet', 'Computers': 'desktop' } total_sum = 0 total_clicks = 0 if type(ad_stat) is not list: ad_stat = [ad_stat] for stat in chunks(ad_stat, 10000): temp = [] ad_buffer = [] for s in stat: if str(s['keywordID']) in keywords: s['keyword'] = keywords[s['keywordID']]['keyword'] else: s['keyword'] = 'Не определено' account = client['tracking_template'] if str(s['campaignID']) in campaigns: campaign = campaigns[str(s['campaignID'])] else: tracking_template = {} url = parse_qs( urlparse(s['trackingTemplate'].replace('#', '').replace('{lpurl}', 'http://test.ru/?')).query) if 'utm_source' in url: tracking_template['utm_source'] = url['utm_source'][0] if 'utm_medium' in url: tracking_template['utm_medium'] = url['utm_medium'][0] if 'utm_campaign' in url: tracking_template['utm_campaign'] = url['utm_campaign'][0] if 'utm_term' in url: tracking_template['utm_term'] = url['utm_term'][0] if 'utm_content' in url: tracking_template['utm_content'] = url['utm_content'][0] campaign = { 'name': s['campaign'], 'tracking_template': tracking_template } if not s['adID'] in banners: tracking_template = {'adGroupId': s['adGroupID'], 'tracking_template': {}} url = parse_qs(urlparse( json.loads(s['finalURL'])[0].replace('#', '').replace('{lpurl}', 'http://test.ru/?')).query) if 'utm_source' in url: tracking_template['tracking_template']['utm_source'] = url['utm_source'][0] if 'utm_medium' in url: tracking_template['tracking_template']['utm_medium'] = url['utm_medium'][0] if 'utm_campaign' in url: tracking_template['tracking_template']['utm_campaign'] = url['utm_campaign'][0] if 'utm_term' in url: tracking_template['tracking_template']['utm_term'] = url['utm_term'][0] if 'utm_content' in url: tracking_template['tracking_template']['utm_content'] = url['utm_content'][0] banners[s['adID']] = tracking_template if not s['adGroupID'] in adgroups: adgroups[s['adGroupID']] = {'tracking_template': {}} if s['adID'] in banners: utms = banners[str(s['adID'])] adgroup = adgroups[utms['adGroupId']] ##добавляем шаблон отслеживания из ключа if str(s['keywordID']) in keywords: utms = {**utms, **keywords[s['keywordID']]} if not 'utm_source' in utms: utms['utm_source'] = \ google_check_tracking_templates('utm_source', account, campaign['tracking_template'], adgroup['tracking_template'], banners[str(s['adID'])]['tracking_template'])['utm_source'] if not 'utm_medium' in utms: utms['utm_medium'] = \ google_check_tracking_templates('utm_medium', account, campaign['tracking_template'], adgroup['tracking_template'], banners[str(s['adID'])]['tracking_template'])['utm_medium'] if not 'utm_campaign' in utms: utms['utm_campaign'] = \ google_check_tracking_templates('utm_campaign', account, campaign['tracking_template'], adgroup['tracking_template'], banners[str(s['adID'])]['tracking_template'])['utm_campaign'] if not 'utm_term' in utms: utms['utm_term'] = \ google_check_tracking_templates('utm_term', account, campaign['tracking_template'], adgroup['tracking_template'], banners[str(s['adID'])]['tracking_template'])['utm_term'] if not 'utm_content' in utms: utms['utm_content'] = \ google_check_tracking_templates('utm_content', account, campaign['tracking_template'], adgroup['tracking_template'], banners[str(s['adID'])]['tracking_template'])['utm_content'] new_utm = match_google_utm_experiment(utms, s) if len(new_utm) == 0: new_utm = {'utm_source': 'google', 'utm_medium': 'cpc', 'utm_campaign': 'не определено', 'utm_term': 'не определено', 'utm_content': 'не определено'} else: new_utm = {'utm_source': 'google', 'utm_medium': 'cpc', 'utm_campaign': 'не определено', 'utm_term': 'не определено', 'utm_content': 'не определено'} s['Cost'] = (int(s['cost']) / 1000000) s['Clicks'] = int(s['clicks']) s['Impressions'] = int(s['impressions']) if s['topVsOther'] == 'Google Display Network': s['position_type'] = 'none' elif s['topVsOther'] == 'Google search: Top': s['position_type'] = 'premium' elif s['topVsOther'] == 'Google search: Other': s['position_type'] = 'other' total_sum += s['Cost'] total_clicks += s['Clicks'] print(s) try: position_type=str(s['position_type']) except: position_type='' values = [str(integration['site_db_id']), str(s['campaignID']), str(s['adID']), str(s['device']), str(s['adGroupID']), str(s['keywordID']), str(s['avgPosition']),position_type, '', '', str(s['networkWithSearchPartners']), '', "google adwords", "", str(new_utm['utm_content']), str(new_utm['utm_term']), str(new_utm['utm_medium']), str(new_utm['utm_campaign']), str(new_utm['utm_source']), str(s['day']), str(hour), str(s['Impressions']), str(s['Clicks']), str(s['Cost']), str(integration['id']), str(1)] compare_values = values[:14] compare_values.append(values[19]) compare_values.append(values[24]) new_values = values for string in last_day: if list(string.values())[:-3] == compare_values: NewImpressions = int(values[21]) - string['Impressions'] NewClicks = int(values[22]) - string['Clicks'] NewCost = float(values[23]) - string['Cost'] if NewImpressions != 0 and NewClicks != 0 and NewCost != 0: new_values[21] = str(NewImpressions) new_values[22] = str(NewClicks) new_values[23] = str(NewCost) break else: new_values = 0 break if new_values != 0: pass else: continue print(new_values) insert = Adstat( idSite=int(new_values[0]), AdCampaignId=new_values[1], AdBannerId=new_values[2], AdDeviceType=new_values[3], AdGroupId=new_values[4], AdKeywordId=new_values[5], AdPosition=new_values[6], AdPositionType=new_values[7], AdRegionId=new_values[8], AdRetargetindId=new_values[9], AdPlacement=new_values[10], AdTargetId=new_values[11], AdvertisingSystem=new_values[12], DRF=new_values[13], campaignContent=new_values[14], campaignKeyword=new_values[15], campaignMedium=new_values[16], campaignName=new_values[17], campaignSource=new_values[18], StatDate=new_values[19], StatDateTime=new_values[20], Impressions=int(new_values[21]), Clicks=int(new_values[22]), Cost=float(new_values[23]), IntegrationId=new_values[24], Sign=int(new_values[25]), ) ad_buffer.append(insert) db = Database('CHdatabase', db_url='http://46.4.81.36:8123') db.insert(ad_buffer) print('total sum' + str(total_sum)) print('total clicks' + str(total_clicks)) def google_check_tracking_templates(utm, account, campaign, adgroup, banner): if utm == 'utm_source': new_utm = {'utm_source': 'google'} elif utm == 'utm_medium': new_utm = {'utm_medium': 'cpc'} else: new_utm = {utm: 'не определено'} if utm in account: new_utm[utm] = account[utm] if utm in campaign: new_utm[utm] = campaign[utm] if utm in adgroup: new_utm[utm] = adgroup[utm] if utm in banner: new_utm[utm] = banner[utm] return new_utm def match_google_utm_experiment(utms, s): new_utm = {} for k, v in utms.items(): # print (utms) if 'utm' in k: new_utm[k] = str(utms[k]).replace('{creative}', s['adID']).replace('{campaignid}', s['campaignID']) \ .replace('{keyword}', s['keyword']).replace('{phrase_id}', s['keywordID']) return new_utm headers = { 'Authorization': 'JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxOSwiZW1haWwiOiIiLCJ1c2VybmFtZSI6ImFydHVyIiwiZXhwIjoxNTE4MTIxNDIyfQ._V0PYXMrE2pJlHlkMtZ_c-_p0y0MIKsv8o5jzR5llpY', 'Content-Type': 'application/json'} if int(datetime.now().strftime('%H')) == 0: hour =(datetime.now()- timedelta(days=1)).strftime('%Y-%m-%d 23:00:00') DateFrom = datetime.now() - timedelta(days=1) else: DateFrom = datetime.now() hour = (datetime.now()- timedelta(hours=1)).strftime('%Y-%m-%d %H:00:00') for res in json.loads(requests.get('https://s.analitika.online/api/integrations?all=1',headers=headers).content.decode('utf-8'))['results']: if res['type']==4: ga_stat_daily(res,DateFrom,DateFrom)
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,138
arturkaa231/clickhouse_api
refs/heads/master
/WV/migrations/0012_auto_20170808_0818.py
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-08-08 08:18 from __future__ import unicode_literals import django.core.files.storage from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('WV', '0011_auto_20170807_1137'), ] operations = [ migrations.AddField( model_name='options', name='cbow', field=models.BooleanField(default=False), ), migrations.AddField( model_name='options', name='skipgr', field=models.BooleanField(default=True), ), migrations.AlterField( model_name='options', name='img', field=models.ImageField(blank=True, default=None, null=True, storage=django.core.files.storage.FileSystemStorage(location='/opt/static/'), upload_to=''), ), ]
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,139
arturkaa231/clickhouse_api
refs/heads/master
/Word2Vec/settings.py
""" Django settings for Word2Vec project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os from datetime import datetime, timedelta, date, time as dt_time from celery.schedules import crontab stas_api='https://api.smartanalytics.io/api/' DB='CHdatabase' BROKER_URL = 'redis://localhost:6379/1' # храним результаты выполнения задач так же в redis CELERY_RESULT_BACKEND = 'redis://localhost:6379/1' # в течение какого срока храним результаты, после чего они удаляются CELERY_TASK_RESULT_EXPIRES = 7*86400 # 7 days # это нужно для мониторинга наших воркеров # место хранения периодических задач (данные для планировщика) #CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" # CELERY SETTINGS CELERY_ENABLE_UTC = True CELERY_TIMEZONE = 'Europe/Moscow' #BROKER_URL = 'redis://localhost:6379/1' CELERY_ACCEPT_CONTENT = ['json'] BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 172800} CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TRACK_STARTED = True #CELERY_RESULT_BACKEND = 'redis://' CELERY_SEND_EVENTS = True #CELERY_RESULT_BACKEND = 'redis://localhost:6379/1' CELERY_IMPORTS = ("api.tasks","api.tasks_test","api.tasks_test_v2") CELERY_DEFAULT_QUEUE = 'log_loader_queue' #CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" CELERYCAM_EXPIRE_SUCCESS = timedelta(days=1) CELERYCAM_EXPIRE_ERROR = timedelta(days=3) CELERYCAM_EXPIRE_PENDING = timedelta(days=5) CELERY_QUEUES = { 'default': { "exchange": "default", "binding_key": "default", }, 'log_loader_queue': { 'exchange': 'log_loader_queue', 'routing_key': 'log_loader_queue', }, } CELERYBEAT_SCHEDULE = { # crontab(hour=0, minute=0, day_of_week='saturday') 'CH_get_stat':{ # example: 'file-backup' 'task': 'api.tasks.task_log_loader_main', # example: 'files.tasks.cleanup' 'schedule': crontab(minute='*/3'), #'args': (), 'options': {'queue': 'log_loader_queue'}, },'ad_stat_loader':{ 'task':'api.tasks.task_adstat_loader', 'schedule':crontab(minute='0',hour='2'), 'options': {'queue': 'log_loader_queue'}}, 'CH_get_stat_test':{ # example: 'file-backup' 'task': 'api.tasks_test.task_log_loader_main_test', # example: 'files.tasks.cleanup' 'schedule': crontab(minute='*/3'), #'args': (), 'options': {'queue': 'log_loader_queue'}, },'ad_stat_loader_test':{ 'task':'api.tasks_test.task_adstat_loader_test', 'schedule':crontab(minute='0',hour='*/3'), 'options': {'queue': 'log_loader_queue'}}, 'CH_get_stat_test_v2':{ # example: 'file-backup' 'task': 'api.tasks_test_v2.task_log_loader_main_test_v2', # example: 'files.tasks.cleanup' 'schedule': crontab(minute='*/3'), #'args': (), 'options': {'queue': 'log_loader_queue'}, } } # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR= os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '@%f+@fq)*-7g6t*s0@w(mie#tr6u-7+b-rf5#5svu3^(+3nh6r' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['database.smartanalytics.io'] LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/home/artur/CHapi/clickhouse/debug.log', }, }, 'loggers': { 'django.request': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'loginsys', #'djcelery', #'django_celery_beat', 'api', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Word2Vec.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), ] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Word2Vec.wsgi.application' ADWORDS_DEVELOPER_TOKEN = 'yJ5krprbCJ9cUe68QmugFw' ADWORDS_CLIENT_ID='662752301475-qecc0ib0ap0o8jeri1fkai38dmv50a14.apps.googleusercontent.com' ADWORDS_CLIENT_SECRET='DOGpl942QcIGWMLF7qIZBPzl' ADWORDS_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'api/static/'), ] STATIC_ROOT="/home/artur/CHapi/clickhouse/static/" MEDIA_ROOT = '/home/artur/CHapi/clickhouse/media/' MEDIA_URL = '/media/'
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,140
arturkaa231/clickhouse_api
refs/heads/master
/spyrecorder/views.py
from django.shortcuts import render,render_to_response import json from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from time import time import datetime from infi.clickhouse_orm import models as md from infi.clickhouse_orm import fields as fd from infi.clickhouse_orm import engines as en from infi.clickhouse_orm.database import Database from spyrecorder.CHmodels import Actions # Create your views here. @csrf_exempt def AddCH(request): def parse_clickhouse_json(jsonBody, db_name, db_host): visits_buffer = [] for i in jsonBody: #print(i) # inserting data into clickhouse model representation insert_visits = Actions( user_id=i['user_id'], user_name = i['user_name'], time = i['time'], event_type = i['event_type'], screen_name = i['screen_name'], app_name = i['app_name'], app_productname = i['app_productname'], app_version = i['app_version'], app_publisher =i['app_publisher'], app_file =i['app_file'], app_copyright =i['app_copyright'], app_language = i['app_language'], file_versioninfo =i['file_versioninfo'], file_description = i['file_description'], file_internalname =i['file_internalname'], file_originalname =i['file_originalname'], ) visits_buffer.append(insert_visits) db = Database(db_name, db_url=db_host) # create table to insert prepared data db.create_table(Actions) # insert prepared data into database db.insert(visits_buffer) if request.method == 'POST': #print(json.loads(request.body.decode('utf-8'))) parse_clickhouse_json(json.loads(request.body.decode('utf-8')),'spy_recorder','http://85.143.172.199:8123') pass else: print('')
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,141
arturkaa231/clickhouse_api
refs/heads/master
/WV/migrations/0006_auto_20170724_1617.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-07-24 13:17 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('WV', '0005_auto_20170724_1034'), ] operations = [ migrations.AddField( model_name='options', name='html', field=models.FileField(blank=True, default=None, null=True, upload_to=''), ), migrations.AlterField( model_name='options', name='text', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='WV.Data'), ), ]
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,142
arturkaa231/clickhouse_api
refs/heads/master
/WV/migrations/0015_options_preview.py
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-08-16 13:42 from __future__ import unicode_literals import django.core.files.storage from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('WV', '0014_auto_20170815_1048'), ] operations = [ migrations.AddField( model_name='options', name='preview', field=models.ImageField(blank=True, default=None, null=True, storage=django.core.files.storage.FileSystemStorage(location='/opt/static/'), upload_to=''), ), ]
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,143
arturkaa231/clickhouse_api
refs/heads/master
/api/forms.py
from django.forms import ModelForm,fields from django import forms class RequestForm(forms.Form): flat=forms.CharField(required=False) sort_order=forms.CharField(required=False) limit=forms.IntegerField(required=False) offset=forms.IntegerField(required=False) dimensions=forms.CharField(required=False) period=forms.DateField(required=False) global_filter=forms.CharField(required=False)
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,144
arturkaa231/clickhouse_api
refs/heads/master
/WV/migrations/0017_imageoptions_num_neighbors.py
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-08-29 11:57 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('WV', '0016_data_data_model'), ] operations = [ migrations.AddField( model_name='imageoptions', name='num_neighbors', field=models.IntegerField(blank=True, default=30, null=True), ), ]
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,145
arturkaa231/clickhouse_api
refs/heads/master
/WV/migrations/0009_auto_20170725_1117.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-07-25 08:17 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('WV', '0008_auto_20170724_1635'), ] operations = [ migrations.CreateModel( name='Tags', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('Tags_text', models.CharField(blank=True, max_length=100, null=True)), ], options={ 'db_table': 'tags', 'ordering': ('Tags_text',), }, ), migrations.AddField( model_name='data', name='Data_tags', field=models.ManyToManyField(to='WV.Tags'), ), ]
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,146
arturkaa231/clickhouse_api
refs/heads/master
/WV/migrations/0014_auto_20170815_1048.py
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-08-15 10:48 from __future__ import unicode_literals import django.core.files.storage from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('WV', '0013_options_num_clusters'), ] operations = [ migrations.CreateModel( name='ImageOptions', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('num_clusters', models.IntegerField(default=20)), ('img', models.ImageField(blank=True, default=None, null=True, storage=django.core.files.storage.FileSystemStorage(location='/opt/static/'), upload_to='')), ('script', models.TextField(blank=True, default=None, null=True)), ('div', models.TextField(blank=True, default=None, null=True)), ], options={ 'db_table': 'Images', }, ), migrations.RemoveField( model_name='options', name='div', ), migrations.RemoveField( model_name='options', name='img', ), migrations.RemoveField( model_name='options', name='num_clusters', ), migrations.RemoveField( model_name='options', name='script', ), migrations.AddField( model_name='options', name='alg', field=models.IntegerField(blank=True, default=0, null=True), ), migrations.AddField( model_name='imageoptions', name='opt', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='image', to='WV.Options'), ), ]
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,147
arturkaa231/clickhouse_api
refs/heads/master
/api/urls.py
from django.conf.urls import url from api import views urlpatterns=[ url(r'^stat/segment_stat/*$',views.segment_stat, name='segment_stat'), url(r'^diagram_stat/$',views.diagram_stat, name='diagram_stat'), url(r'^stat/$',views.CHapi, name='CHapi'), ]
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,148
arturkaa231/clickhouse_api
refs/heads/master
/WV/views.py
from django.shortcuts import render from wsgiref.util import FileWrapper from django.http.response import HttpResponse, Http404 from django.template.loader import get_template from django.template import Context from django.shortcuts import render_to_response, redirect from django.template.context_processors import csrf from django.core.urlresolvers import reverse from django.contrib import auth from django.core.paginator import Paginator from datetime import datetime,date from gensim.models import Word2Vec import xlrd from django.views.decorators.csrf import csrf_exempt import xlwt import os.path import numpy as np import matplotlib.pyplot as plt from bokeh.plotting import figure, show, output_file from bokeh.models import ColumnDataSource, Range1d, LabelSet, Label,Tool from bokeh.models import CustomJS,TapTool,LassoSelectTool from bokeh.models.widgets import TextInput import random from WV.models import Data,Templates,Options,Tags,ImageOptions from WV.forms import EnterData,EnterOptions,TagsForm,EnterImageOptionsForm,CentroidForm,SimilarWordForm,MinFrequencyWordForm from bokeh.plotting import figure, output_file, show from bokeh.embed import components import re from sklearn.datasets import fetch_20newsgroups from sklearn.manifold import TSNE from Word2Vec.settings import BASE_DIR,MEDIA_ROOT,STATICFILES_DIRS,STATIC_ROOT from uuid import uuid4 from sklearn import decomposition from bokeh.io import export_png,export_svgs from bokeh.models.sources import AjaxDataSource from django.http import JsonResponse import json from sklearn.cluster import KMeans from django.core.cache import cache def Split(tags): return tags.split(',') def MainPage(request): args = {} args.update(csrf(request)) args['username'] = auth.get_user(request).username if request.method=="POST": form_text=EnterData(request.POST, request.FILES) form_tg=TagsForm(request.POST) if not request.FILES: args['form_text'] = EnterData args['form'] = TagsForm args['error'] = 'Please, add a file' return render_to_response('EnterData.html', args) #form.article_auth=auth.get_user(request).username if form_text.is_valid() and form_tg.is_valid() : form_text.save() #разделяем строку с тегами на отдельные теги cleaned_tags=Split(request.POST['tg']) for i in cleaned_tags: tg=Tags(text_id=Data.objects.get(Data_xls=('./'+str(request.FILES['Data_xls']))).id,tg=i) tg.save() return redirect(reverse('options',args=[Data.objects.get(Data_xls=('./'+str(request.FILES['Data_xls']))).id])) else: args['form_text'] = EnterData args['form'] = TagsForm args['error'] = 'The file is not supported. Or bad tags' return render_to_response('EnterData.html', args) else: args['form_text'] = EnterData args['form'] = TagsForm return render_to_response('EnterData.html', args) def Enteroptions(request,Data_id): args = {} args.update(csrf(request)) args['username'] = auth.get_user(request).username if request.method == "POST": form = EnterOptions(request.POST) #data=Data.objects.get(id=Data_id) #xls=data.Data_xls if form.is_valid(): options=form.save(commit=False) options.text=Data.objects.get(id=Data_id) if 'cbow' in request.POST: options.alg=0 else: options.alg=1 #проверка на повторяющиеся сеты параметров if 'cbow' in request.POST: for i in Options.objects.filter(text_id=Data_id)[:]: if int(request.POST['size'])==i.size and int(request.POST['win'])== i.win and int(request.POST['minc'])== i.minc and bool(request.POST['cbow'])==i.cbow: args = {} args.update(csrf(request)) args['username'] = auth.get_user(request).username args['form'] = EnterOptions args['templates'] = Templates.objects.all() args['Data_id'] = Data_id args['error'] = 'these parameters already exist' return render_to_response('EnterOptions.html', args) else: for i in Options.objects.filter(text_id=Data_id)[:]: if int(request.POST['size'])==i.size and int(request.POST['win'])== i.win and int(request.POST['minc'])== i.minc and bool(request.POST['skipgr'])==i.skipgr: args = {} args.update(csrf(request)) args['username'] = auth.get_user(request).username args['form'] = EnterOptions args['templates'] = Templates.objects.all() args['Data_id'] = Data_id args['error'] = 'these parameters already exist' return render_to_response('EnterOptions.html', args) form.save() Opt_id=options.id return redirect(reverse('imageoptions', args=[Data_id,Opt_id])) else: args['form'] = EnterOptions args['templates']=Templates.objects.all() args['Data_id']=Data_id return render_to_response('EnterOptions.html',args) def EnterImageOptions(request,Data_id,Opt_id): args = {} args.update(csrf(request)) args['username'] = auth.get_user(request).username if request.method=='POST': form=EnterImageOptionsForm(request.POST) data = Data.objects.get(id=Data_id) opt=Options.objects.get(id=Opt_id) alg=opt.alg if form.is_valid(): imgopt=form.save(commit=False) imgopt.opt=Options.objects.get(id=Opt_id) data=Data.objects.get(id=Data_id) for i in ImageOptions.objects.filter(opt_id=Data_id)[:]: if int(request.POST['num_clusters']) == i.num_clusters and int(request.POST['num_neighbors']) == i.num_neighbors: args = {} args.update(csrf(request)) args['username'] = auth.get_user(request).username args['form'] = EnterImageOptionsForm args['Data_id'] = Data_id args['Opt_id'] = Opt_id args['error'] = 'these image parameters already exist' return render_to_response('EnterImageOptions.html', args) def Map(xls, size, win, minc,alg,num_cl,num_neigh): def ChangeName(filename): ext = filename.split('.')[-1] # get filename filename = '{}.{}'.format(uuid4().hex, ext) # return the whole path to the file return filename def clean(text): for i in ['/',";","'",'.',',','#', ':', '!', '?','%','^','<','>','&',')','(','{','}',']','[','$','@']: text = text.replace(i, '') text = text.lower() return text # Read words from xls def ReadXls(xls): wb = xlrd.open_workbook(os.path.join(xls)) wb.sheet_names() sh = wb.sheet_by_index(0) WL = [] i = 0 while i < sh.nrows: Load = sh.cell(i, 0).value WL.append(Load) i += 1 return WL # Write to xls def WriteXls(xls): # rb=xlrd.open_workbook(a) wb = xlwt.Workbook() ws = wb.add_sheet('result') # sheet=book.sheet_by_index(0) # wb=xlcopy(rb) ws = wb.get_sheet(0) k = 0 for i in model.wv.vocab.keys(): ws.write(k, 0, i) k += 1 k = 0 for i in model.wv.vocab.keys(): ws.write(k, 1, str(model.wv[i])) k += 1 wb.save(xls) def BuildWordMap(): h = .02 # step size in the mesh for weights in ['uniform', 'distance']: # we create an instance of Neighbours Classifier and fit the data. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) plt.xlim(-1, 1) plt.ylim(-1, 1) plt.title('words map') for i, text in enumerate(model.wv.vocab.keys()): plt.annotate(text, (X[:, 0][i], X[:, 1][i])) plt.show() def BuildHtmlMap(): freq = [] for i in model.wv.vocab: freq.append(model.wv.vocab[i].count) scale = max(freq) /50 s1 = ColumnDataSource(data=dict(x=X[:, 0], y=X[:, 1], words=list(model.wv.vocab))) # s1 = ColumnDataSource(data=dict(x=list(X_tsne[:, 0]), y=list(X_tsne[:, 1]), words=sentence,color=['#000000' for i in range(len(sentence))])) p1 = figure(tools="pan,lasso_select,wheel_zoom,undo,reset,save,tap", title="Select Here", plot_width=1000, plot_height=600) p1.scatter(x='x', y='y', size=10, source=s1, alpha=0) def lbset(i, j, size, tcol): x = [] x.append(j[0]) y = [] y.append(j[1]) z = [] z.append(i) col = [] col.append(tcol) s = ColumnDataSource(data=dict(x=x, y=y, words=z, color=col)) return LabelSet(x=j[0], y=j[1], text='words', source=s, text_font_size=size, render_mode='canvas', text_color='color') lbsets = [] for i, j in zip(model.wv.vocab, X): lbsets.append( lbset(i, j, str(12 + model.wv.vocab[i].count / scale) + 'pt', word_centroid_map[i])) s1.callback = CustomJS(args=dict(s1=s1), code=""" var inds = cb_obj.selected['1d'].indices; var d1 = cb_obj.data; for (i = 0; i < inds.length; i++) { d1['color'][inds[i]]='#DC143C' } s1.change.emit(); """) tap = p1.select(type=TapTool) tap.callback = CustomJS(args=dict(s1=s1), code=""" var inds = cb_obj.selected['1d'].indices; var d1 = cb_obj.data; for (i = 0; i < inds.length; i++) { d1['words'][inds[i]]='' d1['x'][inds[i]]=100 } s1.change.emit(); """) for i in lbsets: p1.add_layout(i) script, div = components(p1) picture_name=ChangeName('.png') export_png(p1,os.path.join(STATIC_ROOT,picture_name))#продакшн STATIC_ROOT imgopt.img = picture_name imgopt.script = script imgopt.div = div form.save() img_id=imgopt.id args['username'] = auth.get_user(request).username args['script'] = script args['div'] = div args['num_clusters']=int(request.POST['num_clusters']) args['num_neighbors'] = int(request.POST['num_neighbors']) args['form']=CentroidForm() args['form2'] = SimilarWordForm() args['form3'] = MinFrequencyWordForm() args['Data_id'] = Data_id args['Img_id'] = img_id args['Opt_id'] = Opt_id WL = ReadXls(xls) W = [] # clean from punctuations for i in WL: i = clean(i) W.append(i) Words = [] for i in W: i = i.split(' ') Words.append(i) # Create the model model = Word2Vec(Words, size=size, window=win, min_count=minc,sg=alg) modelname=os.path.join(MEDIA_ROOT,ChangeName('.bin')) model.save(modelname) data.Data_model=modelname data.save() X = [] for i in model.wv.vocab.keys(): X.append(model.wv[i]) X = np.array(X) tsne = TSNE(n_components=2, perplexity=num_neigh) np.set_printoptions(suppress=True) X = tsne.fit_transform(X) #num_clusters = int(model.wv.syn0.shape[0] / 20) num_clusters=num_cl kmeans = KMeans(n_clusters=num_clusters) idx = kmeans.fit_predict(model.wv.syn0) color = [] for i in range(num_clusters): color.append("#%02X%02X%02X" % (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) new_color = [] for i in idx: new_color.append(color[i]) # словарь слово:цвет word_centroid_map = dict(zip(model.wv.index2word, new_color)) WriteXls(xls) # BuildWordMap() BuildHtmlMap() return args return render_to_response('WordMap.html',Map(os.path.join(MEDIA_ROOT,data.Data_xls.name),opt.size,opt.win,opt.minc,alg,int(request.POST['num_clusters']),int(request.POST['num_neighbors']))) else: args = {} args.update(csrf(request)) args['username'] = auth.get_user(request).username args['form'] = EnterImageOptionsForm args['Data_id'] = Data_id args['Opt_id'] = Opt_id return render_to_response('EnterImageOptions.html', args) def Template(request,size,win,minc,Data_id): args={} args.update(csrf(request)) args['username'] = auth.get_user(request).username args['form'] = EnterOptions args['templates'] = Templates.objects.all() args['size']=size args['win'] = win args['minc'] = minc args['Data_id']=Data_id return render_to_response('EnterOptions.html', args) def DownloadedTexts(request,page_number=1): args={} args.update(csrf(request)) args['username'] = auth.get_user(request).username if request.method=="POST" : form=TagsForm(request.POST) if form.is_valid(): return redirect(reverse('FilteredTexts',args=[1,request.POST['tg']])) else: all_texts = Data.objects.all().order_by('-id') args['texts'] = Paginator(all_texts, 10).page(page_number) args['form'] = TagsForm return render_to_response('DownloadedTexts.html', args) else: all_texts = Data.objects.all().order_by('-id') args['texts'] = Paginator(all_texts, 10).page(page_number) args['form']=TagsForm return render_to_response('DownloadedTexts.html',args) def FilteredTexts(request, page_number=1,tags=''): args = {} args.update(csrf(request)) args['username'] = auth.get_user(request).username if request.method == "POST": form = TagsForm(request.POST) if form.is_valid(): return redirect(reverse('FilteredTexts',args=[1,request.POST['tg']])) else: args['tags'] = tags args['texts'] =None args['form'] = TagsForm return render_to_response('FilteredTexts.html', args) else: cleaned_tags = Split(tags) data=Data.objects for i in cleaned_tags: data=data.filter(TAGS__tg=i) args['tags'] = tags args['texts'] = Paginator(data.all(),10).page(page_number) args['form'] = TagsForm return render_to_response('FilteredTexts.html', args) def Maps(request,Data_id,page_number=1): args={} args.update(csrf(request)) args['username'] = auth.get_user(request).username # Добавление пагинации all_options = Options.objects.filter(text_id=Data_id) args['options'] = Paginator(all_options,2).page(page_number) args['Data_id']=Data_id args['text']=Data.objects.get(id=Data_id) return render_to_response('maps.html',args) def Images(request,Data_id,Opt_id,page_number=1): args={} args.update(csrf(request)) args['username'] = auth.get_user(request).username # Добавление пагинации all_images = ImageOptions.objects.filter(opt_id=Opt_id) args['images'] = Paginator(all_images,1).page(page_number) args['Data_id']=Data_id args['opt']=Options.objects.get(id=Opt_id) return render_to_response('images.html',args) def Showmap(request,Data_id,Opt_id,Img_id): args = {} args.update(csrf(request)) args['username'] = auth.get_user(request).username #html=Options.objects.get(id=Opt_id).html script=ImageOptions.objects.get(id=Img_id).script div = ImageOptions.objects.get(id=Img_id).div args['script'] = script args['div'] = div args['Opt_id'] = Opt_id args['Data_id'] = Data_id args['Img_id'] = Img_id args['num_clusters']=ImageOptions.objects.get(id=Img_id).num_clusters args['num_neighbors'] = ImageOptions.objects.get(id=Img_id).num_neighbors args['form']=CentroidForm() args['form2'] = SimilarWordForm() args['form3'] = MinFrequencyWordForm() return render_to_response("WordMap.html",args) def DeleteOpt(request,Opt_id, Data_id): options=Options.objects.get(id=Opt_id) options.delete() return redirect(reverse('maps',args=[Data_id,1])) def DeleteImageOpt(request,Data_id,Opt_id, Img_id): images=ImageOptions.objects.get(id=Img_id) images.delete() return redirect(reverse('images',args=[Data_id,Opt_id,1])) def SetPreview(request,Data_id, Opt_id,img): option=Options.objects.get(id=Opt_id) option.preview=img option.save() return redirect(reverse('images', args=[Data_id, Opt_id, 1])) #Задание центроид руками def Centroids(request,Data_id,Opt_id,Img_id): args = {} args.update(csrf(request)) args['username'] = auth.get_user(request).username if request.method == 'POST': form = CentroidForm(request.POST) data = Data.objects.get(id=Data_id) opt = Options.objects.get(id=Opt_id) if form.is_valid(): imgopt =ImageOptions.objects.get(id=Img_id) imgopt.opt = Options.objects.get(id=Opt_id) num_clusters = ImageOptions.objects.get(id=Img_id).num_clusters num_neighbors = ImageOptions.objects.get(id=Img_id).num_neighbors model = Word2Vec.load(data.Data_model.name) centroids = Split(request.POST['centroids']) for i in centroids: if i not in model.wv.vocab: args['username'] = auth.get_user(request).username args['script'] = imgopt.script args['div'] = imgopt.div args['Img_id'] = Img_id args['error'] = "Bad centroids(Must be in vocabulary and separated by commas)" args['form'] = CentroidForm() args['form2'] = SimilarWordForm() args['form3'] = MinFrequencyWordForm() args['Data_id'] = Data_id args['Opt_id'] = Opt_id args['num_clusters'] = imgopt.num_clusters args['num_neighbors'] = imgopt.num_neighbors return render_to_response('WordMap.html', args) # Удаляем старое изображение imgopt.delete() def Map(num_cl,num_neigh,centerwords): # Write to xls def WriteXls(xls): # rb=xlrd.open_workbook(a) wb = xlwt.Workbook() ws = wb.add_sheet('result') # sheet=book.sheet_by_index(0) # wb=xlcopy(rb) ws = wb.get_sheet(0) k = 0 for i in model.wv.vocab.keys(): ws.write(k, 0, i) k += 1 k = 0 for i in model.wv.vocab.keys(): ws.write(k, 1, str(model.wv[i])) k += 1 wb.save(xls) def BuildHtmlMap(): freq = [] for i in model.wv.vocab: freq.append(model.wv.vocab[i].count) scale = max(freq) / 50 s1 = ColumnDataSource(data=dict(x=X[:, 0], y=X[:, 1], words=list(model.wv.vocab))) # s1 = ColumnDataSource(data=dict(x=list(X_tsne[:, 0]), y=list(X_tsne[:, 1]), words=sentence,color=['#000000' for i in range(len(sentence))])) p1 = figure(tools="pan,lasso_select,wheel_zoom,undo,reset,save,tap", title="Select Here", plot_width=1000, plot_height=600) p1.scatter(x='x', y='y', size=10, source=s1, alpha=0) def lbset(i, j, size, tcol): x = [] x.append(j[0]) y = [] y.append(j[1]) z = [] z.append(i) col = [] col.append(tcol) s = ColumnDataSource(data=dict(x=x, y=y, words=z, color=col)) return LabelSet(x=j[0], y=j[1], text='words', source=s, text_font_size=size, render_mode='canvas', text_color='color') lbsets = [] for i, j in zip(model.wv.vocab, X): if i in centerwords: a='#000000' else: a = word_centroid_map[i] lbsets.append( lbset(i, j, str(12 + model.wv.vocab[i].count / scale) + 'pt', a)) s1.callback = CustomJS(args=dict(s1=s1), code=""" var inds = cb_obj.selected['1d'].indices; var d1 = cb_obj.data; for (i = 0; i < inds.length; i++) { d1['color'][inds[i]]='#DC143C' } s1.change.emit(); """) tap = p1.select(type=TapTool) tap.callback = CustomJS(args=dict(s1=s1), code=""" var inds = cb_obj.selected['1d'].indices; var d1 = cb_obj.data; for (i = 0; i < inds.length; i++) { d1['words'][inds[i]]='' d1['x'][inds[i]]=100 } s1.change.emit(); """) for i in lbsets: p1.add_layout(i) script, div = components(p1) def ChangeName(filename): ext = filename.split('.')[-1] # get filename filename = '{}.{}'.format(uuid4().hex, ext) # return the whole path to the file return filename picture_name = ChangeName('.png') export_png(p1, os.path.join(STATIC_ROOT, picture_name)) # продакшн STATIC_ROOT imgopt = ImageOptions.objects.create(id=Img_id) imgopt.img = picture_name imgopt.num_clusters = num_cl imgopt.num_neighbors = num_neigh imgopt.opt = Options.objects.get(id=Opt_id) imgopt.script = script imgopt.div = div imgopt.save() args['username'] = auth.get_user(request).username args['script'] = script args['div'] = div args['Img_id'] = Img_id args['form'] = CentroidForm() args['form2'] = SimilarWordForm() args['form3'] = MinFrequencyWordForm() args['Data_id'] = Data_id args['Opt_id'] = Opt_id args['num_clusters'] = num_cl args['num_neighbors'] = num_neigh X = [] for i in model.wv.vocab.keys(): X.append(model.wv[i]) X = np.array(X) tsne = TSNE(n_components=2, perplexity=num_neigh) np.set_printoptions(suppress=True) X = tsne.fit_transform(X) centers=[] for i in centerwords: centers.append(model.wv[i]) centers=np.array(centers) # centers =np.array((model.wv.syn0[1],model.wv.syn0[15],model.wv.syn0[0]), np.float64) # num_clusters = int(model.wv.syn0.shape[0] / 20) num_clusters = num_cl kmeans = KMeans(n_clusters=num_clusters,n_init=1,init=centers) #kmeans = KMeans(n_clusters=num_clusters) idx = kmeans.fit_predict(model.wv.syn0) color = [] for i in range(num_clusters): color.append("#%02X%02X%02X" % (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) new_color = [] for i in idx: new_color.append(color[i]) # словарь слово:цвет word_centroid_map = dict(zip(model.wv.index2word, new_color)) # WriteXls(xls) # BuildWordMap() BuildHtmlMap() return args return render_to_response('WordMap.html', Map(int(num_clusters),int(num_neighbors),centroids)) @csrf_exempt def SimilarWords(request): if request.method=='POST': word=request.POST.get('word') Data_id=request.POST.get('Data_id') model=Word2Vec.load(Data.objects.get(id=int(Data_id)).Data_model.name) response_data = {} response_data['word1']=model.wv.most_similar(word)[0] response_data['word2'] = model.wv.most_similar(word)[1] response_data['word3'] = model.wv.most_similar(word)[2] response_data['word4'] = model.wv.most_similar(word)[3] response_data['word5'] = model.wv.most_similar(word)[4] response_data['word6'] = model.wv.most_similar(word)[5] response_data['word7'] = model.wv.most_similar(word)[6] return HttpResponse( json.dumps(response_data), content_type="application/json" ) def MinFrequencyWord(request,Data_id,Opt_id,Img_id): args = {} args.update(csrf(request)) args['username'] = auth.get_user(request).username if request.method == 'POST': form = MinFrequencyWordForm(request.POST) data = Data.objects.get(id=Data_id) if form.is_valid(): imgopt = ImageOptions.objects.get(id=Img_id) num_clusters= ImageOptions.objects.get(id=Img_id).num_clusters num_neighbors = ImageOptions.objects.get(id=Img_id).num_neighbors #Удаляем старое изображение imgopt.delete() def Map(num_cl,num_neigh,minfreq): # Write to xls def BuildHtmlMap(): freq = [] for i in model.wv.vocab: freq.append(model.wv.vocab[i].count) scale = max(freq) / 50 s1 = ColumnDataSource(data=dict(x=X[:, 0], y=X[:, 1], words=words)) # s1 = ColumnDataSource(data=dict(x=list(X_tsne[:, 0]), y=list(X_tsne[:, 1]), words=sentence,color=['#000000' for i in range(len(sentence))])) p1 = figure(tools="pan,lasso_select,wheel_zoom,undo,reset,save,tap", title="Select Here", plot_width=1000, plot_height=600) p1.scatter(x='x', y='y', size=10, source=s1, alpha=0) def lbset(i, j, size, tcol): x = [] x.append(j[0]) y = [] y.append(j[1]) z = [] z.append(i) col = [] col.append(tcol) s = ColumnDataSource(data=dict(x=x, y=y, words=z, color=col)) return LabelSet(x=j[0], y=j[1], text='words', source=s, text_font_size=size, render_mode='canvas', text_color='color') lbsets = [] for i, j in zip(words, X): lbsets.append( lbset(i, j, str(12 + model.wv.vocab[i].count / scale) + 'pt', word_centroid_map[i])) s1.callback = CustomJS(args=dict(s1=s1), code=""" var inds = cb_obj.selected['1d'].indices; var d1 = cb_obj.data; for (i = 0; i < inds.length; i++) { d1['color'][inds[i]]='#DC143C' } s1.change.emit(); """) tap = p1.select(type=TapTool) tap.callback = CustomJS(args=dict(s1=s1), code=""" var inds = cb_obj.selected['1d'].indices; var d1 = cb_obj.data; for (i = 0; i < inds.length; i++) { d1['words'][inds[i]]='' d1['x'][inds[i]]=100 } s1.change.emit(); """) for i in lbsets: p1.add_layout(i) script, div = components(p1) def ChangeName(filename): ext = filename.split('.')[-1] # get filename filename = '{}.{}'.format(uuid4().hex, ext) # return the whole path to the file return filename picture_name = ChangeName('.png') export_png(p1, os.path.join(STATIC_ROOT, picture_name)) # продакшн STATIC_ROOT #Создаем новое изображение imgopt=ImageOptions.objects.create(id=Img_id) imgopt.img = picture_name imgopt.num_clusters=num_cl imgopt.num_neighbors = num_neigh imgopt.opt=Options.objects.get(id=Opt_id) imgopt.script = script imgopt.div = div imgopt.save() args['username'] = auth.get_user(request).username args['script'] = script args['div'] = div args['Img_id'] = imgopt.id args['form'] = CentroidForm() args['form2'] = SimilarWordForm() args['form3'] = MinFrequencyWordForm() args['Data_id'] = Data_id args['Opt_id'] = Opt_id args['num_clusters'] =num_cl args['num_neighbors'] = num_neigh # Create the model model = Word2Vec.load(data.Data_model.name) words = [] for i in model.wv.vocab: if model.wv.vocab[i].count > minfreq: words.append(i) vectors = [model[w] for w in words] tsne = TSNE(n_components=2, perplexity=num_neigh) np.set_printoptions(suppress=True) X = tsne.fit_transform(vectors) # centers =np.array((model.wv.syn0[1],model.wv.syn0[15],model.wv.syn0[0]), np.float64) # num_clusters = int(model.wv.syn0.shape[0] / 20) num_clusters = num_cl kmeans = KMeans(n_clusters=num_clusters) # kmeans = KMeans(n_clusters=num_clusters) idx = kmeans.fit_predict(vectors) color = [] for i in range(num_clusters): color.append("#%02X%02X%02X" % (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) new_color = [] for i in idx: new_color.append(color[i]) # словарь слово:цвет word_centroid_map = dict(zip(model.wv.index2word, new_color)) # WriteXls(xls) # BuildWordMap() BuildHtmlMap() return args return render_to_response('WordMap.html', Map(int(num_clusters),int(num_neighbors),int(request.POST['freq']))) def DownloadText(request,Data_id): filename =Data.objects.get(id=Data_id).Data_xls.name content_type = 'application/vnd.ms-excel' file_path = os.path.join(MEDIA_ROOT, filename) response = HttpResponse(FileWrapper(open(file_path,'rb')), content_type=content_type) response['Content-Disposition'] = 'attachment; filename=%s' % ( filename) response['Content-Length'] = os.path.getsize(file_path) return response
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,149
arturkaa231/clickhouse_api
refs/heads/master
/WV/forms.py
from django.forms import ModelForm, fields from WV.models import Data,Options,Tags,ImageOptions from Word2Vec import settings from uuid import uuid4 import os.path from django import forms class EnterOptions(ModelForm): class Meta: model = Options fields = ['size','win','minc','cbow','skipgr'] def __str__(self): return self.as_div() # run the parent validation firs class EnterImageOptionsForm(ModelForm): class Meta: model = ImageOptions fields = ['num_clusters','num_neighbors'] def __str__(self): return self.as_div() class EnterData(ModelForm): class Meta: model=Data fields = ['Data_title','Data_xls'] def __str__(self): return self.as_div() def clean(self): def ChangeName(filename): ext = filename.split('.')[-1] # get filename filename = '{}.{}'.format(uuid4().hex, ext) return filename cleaned_data = self.cleaned_data cleaned_data['Data_xls'].name=ChangeName(filename= cleaned_data['Data_xls'].name) return cleaned_data def is_valid(self): valid = super(EnterData, self).is_valid() # we're done now if not valid if not valid: return valid extensions = ['.xls', '.xlsx','.xlsm','.csv','.xlt','.xltx'] filename, file_extension = os.path.splitext(self.cleaned_data['Data_xls'].name) if file_extension not in extensions: return False # run the parent validation first else: return True class TagsForm(ModelForm): class Meta: model=Tags fields = ['tg'] def __str__(self): return self.as_div() def is_valid(self): valid = super(TagsForm, self).is_valid() # we're done now if not valid if not valid: return valid punct=['/',";","'",'.','#', ':', '!', '?','%','^','<','>','&',')','(','{','}',']','[','$','@'] for i in self.cleaned_data['tg']: if i in punct: return False if not self.cleaned_data['tg']: return False # run the parent validation first else: return True #Форма для добавления центроид class CentroidForm(forms.Form): centroids= forms.CharField() class SimilarWordForm(forms.Form): word= forms.CharField() class MinFrequencyWordForm(forms.Form): freq= forms.IntegerField()
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,150
arturkaa231/clickhouse_api
refs/heads/master
/WV/migrations/0010_auto_20170725_1353.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-07-25 10:53 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('WV', '0009_auto_20170725_1117'), ] operations = [ migrations.AlterModelOptions( name='tags', options={}, ), migrations.RemoveField( model_name='data', name='Data_tags', ), migrations.RemoveField( model_name='tags', name='Tags_text', ), migrations.AddField( model_name='tags', name='text', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='WV.Data'), ), migrations.AddField( model_name='tags', name='tg', field=models.CharField(blank=True, default=None, max_length=100, null=True), ), ]
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,151
arturkaa231/clickhouse_api
refs/heads/master
/Word2Vec/gunicorn.conf.py
bind = '127.0.0.1:8001' workers = 10 threads = 10 user = "www-data"
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,152
arturkaa231/clickhouse_api
refs/heads/master
/spyrecorder/apps.py
from django.apps import AppConfig class SpyrecorderConfig(AppConfig): name = 'spyrecorder'
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,153
arturkaa231/clickhouse_api
refs/heads/master
/loginsys/views.py
from django.shortcuts import render_to_response, redirect from django.contrib import auth from django.template.context_processors import csrf from django.contrib.auth.forms import UserCreationForm # Create your views here. def login(request): args={} args.update(csrf(request)) if request.POST: username=request.POST.get('username','') password=request.POST.get('password','') user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return redirect('login.html',args) else: args['login_error']="User is not found" return render_to_response('login.html',args) else: return render_to_response('login.html',args) def logout(request): auth.logout(request) return redirect('/') def register(request): args={} args.update(csrf(request)) args['form']=UserCreationForm() if request.POST: new_user_form=UserCreationForm(request.POST) if new_user_form.is_valid(): new_user_form.save() newuser=auth.authenticate(username=new_user_form.cleaned_data['username'], password=new_user_form.cleaned_data['password2']) auth.login(request,newuser) return redirect('/') else: args['form']=new_user_form args['error']='Bad password or user already exists' return render_to_response('register.html',args)
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}
34,154
arturkaa231/clickhouse_api
refs/heads/master
/WV/migrations/0016_data_data_model.py
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-08-23 12:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('WV', '0015_options_preview'), ] operations = [ migrations.AddField( model_name='data', name='Data_model', field=models.FileField(blank=True, default=None, null=True, upload_to=''), ), ]
{"/spyrecorder/views.py": ["/spyrecorder/CHmodels.py"], "/WV/views.py": ["/WV/models.py", "/WV/forms.py", "/Word2Vec/settings.py"], "/WV/forms.py": ["/WV/models.py"], "/api/views.py": ["/Word2Vec/settings.py"], "/WV/models.py": ["/Word2Vec/settings.py"], "/WV/admin.py": ["/WV/models.py"]}