def get(self): bind_id = self.get_argument("bind_id") youtube_id = self.get_argument("youtube_id", "-1") time_watched = self.get_argument("time_watched", -1) logger.debug( "Set-top box list request received: bind_id: %s, youtube_id: %s, time_watched: %s", bind_id, youtube_id, time_watched, ) try: if youtube_id != "-1" and youtube_id != "Title": Video.mark_watched(bind_id=bind_id, youtube_id=youtube_id, time_watched=time_watched) except: dbutils.Session.rollback() try: container = Video.get_list(bind_id=bind_id, is_stb=True) playback_url = fetch_yt_link(container["nowplaying"]["url"]) playback_url = escape(playback_url + "&title=.mp4") container["nowplaying"]["url"] = escape(container["nowplaying"]["url"]) container["nowplaying"]["title"] = escape(container["nowplaying"]["title"]) container["nowplaying"]["youtube_id"] = escape(container["nowplaying"]["youtube_id"]) container["nowplaying"]["playback_url"] = playback_url except: dbutils.Session.rollback() container = [] logger.info("timewatched: %s youtube_id:%s bind_id:%s", time_watched, youtube_id, bind_id) # self.content_type = 'text/xml' //HACK wtf why doesn't this work..? self._headers["Content-Type"] = "text/xml; charset=UTF-8" if container != []: self.write(dict2xml({"nowplaying": container["nowplaying"]})) dbutils.Session.remove() self.finish()
def main(): global theClock, theBoard print "" pygame.init() pygame.display.set_mode((640, 480), pygame.OPENGL | pygame.DOUBLEBUF) Video.initThings(144, 136, 160) theClock = pygame.time.Clock() timeDelta = 0 prepareBoard() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: checkKeys(event) draw(timeDelta) pygame.display.flip() timeDelta = theClock.tick(60) # Limit ourselves to 60 FPS
def get(self): bind_id = self.get_argument("bind_id") youtube_id = self.get_argument("youtube_id", "-1") response_format = self.get_argument("response_format", "xml") time_watched = self.get_argument("time_watched", -1) limit = self.get_argument("limit", 50) logger.debug( "List request received: bind_id: %s, youtube_id (just watched): %s, response_format: %s, time_watched:%s", bind_id, youtube_id, response_format, time_watched, ) try: if youtube_id != "-1" and youtube_id != "Title": Video.mark_watched(bind_id=bind_id, youtube_id=youtube_id, time_watched=time_watched) except: dbutils.Session.rollback() try: container = Video.get_list(bind_id=bind_id, limit=int(limit)) except: dbutils.Session.rollback() container = {} if response_format == "json": self.content_type = "application/json" self.write(json.dumps(container)) else: self.content_type = "text/xml" self.write(dict2xml(container)) dbutils.Session.remove() self.finish()
def main(): global theClock print "" pygame.init() pygame.display.set_mode((640, 480), pygame.OPENGL | pygame.DOUBLEBUF) Video.initThings(144, 136, 160) theClock = pygame.time.Clock() timeDelta = 0 while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: checkKeys(event) draw(timeDelta) pygame.display.flip() timeDelta = theClock.tick(60) # Limit ourselves to 60 FPS
def __init__(self, parent=None): super(VideoWindow, self).__init__(parent) self.setWindowTitle("Video Annotator") self.video1 = Video(self) self.video2 = Video(self) self.playButton = QPushButton() self.playButton.setEnabled(False) self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playButton.clicked.connect(self.play) self.positionSlider = QSlider(Qt.Horizontal) self.positionSlider.setRange(0, 0) self.positionSlider.sliderMoved.connect(self.setPosition) self.errorLabel = QLabel() self.errorLabel.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) # Create new action openAction1 = QAction(QIcon('open.png'), '&Open1', self) openAction2 = QAction(QIcon('open.png'), '&Open2', self) openAction1.triggered.connect(self.video1.openFile) openAction2.triggered.connect(self.video2.openFile) # Create exit action exitAction = QAction(QIcon('exit.png'), '&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self.exitCall) # Create menu bar and add action menuBar = self.menuBar() fileMenu = menuBar.addMenu('&File') #fileMenu.addAction(newAction) fileMenu.addAction(openAction1) fileMenu.addAction(openAction2) fileMenu.addAction(exitAction) # Create a widget for window contents wid = QWidget(self) self.setCentralWidget(wid) # Create layouts to place inside widget controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) controlLayout.addWidget(self.playButton) controlLayout.addWidget(self.positionSlider) layout = QVBoxLayout() layout.addWidget(self.video1.videoWidget) layout.addWidget(self.video2.videoWidget) layout.addLayout(controlLayout) layout.addWidget(self.errorLabel) # Set widget to contain window contents wid.setLayout(layout)
def get(self): bind_id = self.get_argument("bind_id") youtube_id = self.get_argument("youtube_id") logger.debug("Single video add request received: bind_id: %s, youtube_id: %s", bind_id, youtube_id) video = Video.youtube_metadata_grabber(youtube_id) Video.insert_video(bind_id=bind_id, video=video) dbutils.Session.remove() self.finish()
def main(): global theClock, theBoard, thePiece, thePieceColor global pieceX, pieceY, idealX, idealY global boardWidth, boardHeight global borderWidth, borderHeight, extraBorder, countFrom global theEventQueue, timeDelta, theScore, theMultiplyer, gameTime print "" boardWidth = 16 boardHeight = 15 borderWidth = 8 borderHeight = 8 extraBorder = 35 gameTime = 0 # Time the game has been running (allowed to overflow) countFrom = 0 # Time we count from for countdown pieceX = pieceY = idealX = idealY = 0.0 theScore = 0 theMultiplyer = 1 random.seed() pygame.init() pygame.display.set_mode((640, 480), pygame.OPENGL | pygame.DOUBLEBUF) pygame.key.set_repeat(100, 100) # Turn on key repeat for us Video.initThings(boardWidth * 8 + borderWidth * 2 + extraBorder, boardHeight * 8 + borderHeight * 2, 160) theClock = pygame.time.Clock() timeDelta = 0 theEventQueue = EventQueue.EventQueue() theEventQueue.addToQueue("Gamestate", "Get New Board") theEventQueue.addToQueue("Gamestate", "Get New Piece") theEventQueue.addToQueue("Score", "Reset Score") while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: theEventQueue.addToQueue("Program", "Quit") elif event.type == pygame.KEYDOWN: checkKeys(event) theEventQueue.addToQueue("Gamestate", "Update Piece Position") theEventQueue.addToQueue("Video", "Redraw Buffer") theEventQueue.addToQueue("Video", "Swap Buffers") theEventQueue.addToQueue("Program", "Tick Clock") runThroughQueue()
def count_frame(self): """This function only work after defined exactly filename""" if self.use_image: print ("Not implemented yet") else: for vid in self.name: video = Video(vid) num_fr, fps = video.get_frame_count() self.num_frames.append(num_fr)
def draw(timeInMS): """Draw the scene for us""" global theBoard Video.sinkEm(theBoard, timeInMS) Video.startDrawing() Video.drawHolder(16, 15, 8, 8) Video.drawBlocksInBoard(theBoard, 16, 15, 8, 8) Video.finishDrawing()
def main(): global theClock, theBoard, thePiece, thePieceColor global pieceX, pieceY, idealX, idealY, pieceAngle, idealAngle global boardWidth, boardHeight global borderWidth, borderHeight global theEventQueue, timeDelta print "" pieceX = pieceY = idealX = idealY = pieceAngle = idealAngle = 0.0 thePieceColor = 4 boardWidth = 16 boardHeight = 15 borderWidth = 8 borderHeight = 8 angle = idealAngle = 0 # Angle is degrees rotated clockwise thePiece = Pieces.piecesArray[7] # Temporary piece pygame.init() pygame.display.set_mode((640, 480), pygame.OPENGL | pygame.DOUBLEBUF) Video.initThings(boardWidth * 8 + borderWidth * 2, boardHeight * 8 + borderHeight * 2, 160) theClock = pygame.time.Clock() timeDelta = 0 prepareBoard() theEventQueue = EventQueue.EventQueue() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: theEventQueue.addToQueue("Program", "Quit") elif event.type == pygame.KEYDOWN: checkKeys(event) theEventQueue.addToQueue("Gamestate", "Update Piece Position") theEventQueue.addToQueue("Video", "Redraw Buffer") theEventQueue.addToQueue("Video", "Swap Buffers") theEventQueue.addToQueue("Program", "Tick Clock") runThroughQueue()
def post(self): youtube_ids = self.get_argument("youtube_ids", []) try: youtube_ids = json.loads(youtube_ids) logger.debug("Video bulk insert (post) request received: youtube_ids: %s", simplejson.dumps(youtube_ids)) except JSONDecodeError: self.write("ERROR INVALID JSON") logger.error("Invalid youtube id array json") youtube_ids = [] self.write("Received " + str(len(youtube_ids)) + " guids") logger.info("Received %d youtube guids for insert", len(youtube_ids)) Video.import_youtube_videos(youtube_ids) logger.info("Import from youtube scrape complete, finishing response") self.finish()
def dodajT(app, url, value=None): if value == None: provjera = provjeriURL(url) else: provjera = value br = 0 if provjera == 'video': video = Video(url) tekst = video.title app.lista.insert(app.lista.size(), tekst) app.inp.delete(0, "end") ##updateaj status updateStatus(app, tekst) ##dodaj u dictionary app.mainDict[tekst] = video elif provjera == 'playlist': lista = izradiListu( url ) ##parsiraj html i za svaki link pokreni proceduru za dodavanje for i in lista: dodajT(app, i, 'video') elif provjera == 'playlist_dorada': ##doradi link i pokreni rekurzivno kao da se poslao originalni playlist link dodajT(app, "http://www.youtube.com/playlist?" + url.split('&')[1], 'playlist') else: updateStatus(app, 'Uneseni URL nije validan!') app.inp.delete(0, "end")
def run(self,vid): print("Processing: " + str(vid)) if not os.path.exists(vid): raise "Video does not exist at specified path" if self.args.threaded: #load tensorflow session and model if in threaded mode to keep thread safe if self.args.tensorflow: import tensorflow as tf print("Loading Tensorflow model") self.sess=tf.Session() tf.saved_model.loader.load(self.sess,[tf.saved_model.tag_constants.SERVING], self.args.path_to_model) print("Complete") else: sess=None else: sess=None #Create Video Class self.video_instance=Video.Video(vid,args=self.args,tensorflow_session=self.sess) #close tensorflow session to keep thread safe if self.args.threaded: if self.args.tensorflow: self.sess.close()
def get_url2(url_list, a_href_line): # String variable that holds the current URL url = '' # Boolean that states whether the first quote of the tag has been found. If false, then we have not found a quote, but if true then we have found the first quote first_quote_found = False # Variable that holds the position of the first letter after the first quote beginning = 0 # Looping through current line to isolate the URL for i in range(0, len(a_href_line)): # If a double quote is found, determine whether its the first or second if a_href_line[i] == '"': # If its the first then set the appropriate variable, record where the first quote is if first_quote_found == False: first_quote_found = True beginning = i + 1 # Otherwise slice the current line and record the URL part else: url = website_name + a_href_line[beginning:i] id = url.rpartition('/')[2].partition('?')[0] number = -1 for j in id.split('-'): if j.isdigit(): number = int(j) break if number in download_list: print('adding episode: ' + str(number)) video_list.insert(0, Video.Video(url, id, number)) break
def __init__(self, *, w: int, h: int, file_name: str, scaled_w: int = 100, stretch: float = 1, gradient: typing.Union[int, str] = 0): self.w = w self.h = h self.aspect_ratio = self.w/self.h self.stretch = stretch self.sw = scaled_w self.sh = int(math.ceil(self.aspect_ratio*self.sw)) self.sw = math.ceil(self.sw*self.stretch) self.file_name = file_name self.video = Video(w=self.w, h=self.h, file_name=self.file_name) self.video_input = self.video.video_input.video self.fps = self.video.fps self.process = None self.frames = None self.viewer = None if isinstance(gradient, int): if 0 <= gradient < len(gradients): self.grad = gradients[gradient] else: self.grad = gradients[0] else: self.grad = gradient
def main(): global theClock, theBoard, thePiece, thePieceColor global pieceX, pieceY, idealX, idealY global boardWidth, boardHeight global borderWidth, borderHeight global theEventQueue, timeDelta print "" boardWidth = 16 boardHeight = 15 borderWidth = 8 borderHeight = 8 pieceX = pieceY = idealX = idealY = 0.0 random.seed() pygame.init() pygame.display.set_mode((640, 480), pygame.OPENGL | pygame.DOUBLEBUF) Video.initThings(boardWidth * 8 + borderWidth * 2, boardHeight * 8 + borderHeight * 2, 160) theClock = pygame.time.Clock() timeDelta = 0 theEventQueue = EventQueue.EventQueue() theEventQueue.addToQueue("Gamestate", "Get New Board") theEventQueue.addToQueue("Gamestate", "Get New Piece") while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: theEventQueue.addToQueue("Program", "Quit") elif event.type == pygame.KEYDOWN: checkKeys(event) theEventQueue.addToQueue("Gamestate", "Update Piece Position") theEventQueue.addToQueue("Video", "Redraw Buffer") theEventQueue.addToQueue("Video", "Swap Buffers") theEventQueue.addToQueue("Program", "Tick Clock") runThroughQueue()
def play(self): if not self.thread_flag: self.thread_flag = True self.file_path_temp = file.askopenfilename(filetypes=[ ("all video format", ".mp4"), ("all video format", ".flv"), ("all video format", ".avi"), ]) if self.file_path_temp == "": return else: self.file_path = self.file_path_temp video.get_video(self.file_path) self.thread = threading.Thread(target=self.play_thread) self.thread.start()
def main(): global theClock, theBoard, thePiece global pieceX, pieceY, idealX, idealY global boardWidth, boardHeight global borderWidth, borderHeight print "" pieceX = pieceY = idealX = idealY = 0.0 boardWidth = 16 boardHeight = 15 borderWidth = 8 borderHeight = 8 angle = idealAngle = 0 # Angle is degrees rotated clockwise thePiece = Pieces.piecesArray[7] # Temporary piece pygame.init() pygame.display.set_mode((640, 480), pygame.OPENGL | pygame.DOUBLEBUF) Video.initThings(boardWidth * 8 + borderWidth * 2, boardHeight * 8 + borderHeight * 2, 160) theClock = pygame.time.Clock() timeDelta = 0 prepareBoard() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: checkKeys(event) updatePiecePosition(timeDelta) draw(timeDelta) pygame.display.flip() timeDelta = theClock.tick(60) # Limit ourselves to 60 FPS
def get(self): bind_id = self.get_argument("bind_id") youtube_id = self.get_argument("youtube_id", "-1") time_watched = self.get_argument("time_watched", -1) logger.info( "Mark watch request received: bind_id: %s, youtube_id (just watched): %s, time_watched:%s", bind_id, youtube_id, time_watched, ) try: if youtube_id != "-1" and youtube_id != "Title": Video.mark_watched(bind_id=bind_id, youtube_id=youtube_id, time_watched=time_watched) except: dbutils.Session.rollback() dbutils.Session.remove() self.finish()
def get_random_setup(self, num_apps, stream_fps): apps = [] video = Video.Video(stream_fps) for i in range(num_apps): app = self.get_random_app() apps.append(app) return Setup(apps, video)
def get_random_setup(self, num_apps, stream_fps): budget = random.choice(self.budget_options) apps = [] video = Video.Video(stream_fps) for i in range(num_apps): app = self.get_random_app() apps.append(app) return Setup(apps, budget, video)
def main(): """The main program.""" # Initialize Pygame pygame.init() # First we set some stuff up. prefs = Preferences.Preferences() prefs.loadPreferences() video = Video.Video(prefs) video.prepareVideo() carObject = Car.Car() groundObject = Map.Map() groundObject.loadMapData(test_map.t_d, test_map.t_w, test_map.t_h) groundObject.setupObjects() carObject.setXYPosition(8.0, 9.0) carDir = 0.0 while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() carDir += 1.0 if (carDir >= 360.0): carDir -= 360.0 carObject.setAngle(carDir) video.prepareNewFrame() video.setupCamera() video.setupLights() # Drawing happens here glLoadIdentity() # drawReference(0.0, 0.0, 0.0, 1.0) groundObject.draw() carObject.draw() video.finishNewFrame() pygame.time.wait(33)
def main(): """The main program.""" # Initialize Pygame pygame.init() # First we set some stuff up. prefs = Preferences.Preferences() prefs.loadPreferences() video = Video.Video(prefs) video.prepareVideo() carObject = Car.Car() groundObject = Ground.Ground() carDir = 0.0 while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() carDir += 1.0 if (carDir >= 360.0): carDir -= 360.0 carObject.setAngle(carDir) video.prepareNewFrame() video.setupCamera() video.setupLights() # Drawing happens here glLoadIdentity() drawReference(0.0, 0.0, 0.0, 1.0) video.drawSimulationObject(groundObject) video.drawSimulationObject(carObject) video.finishNewFrame() pygame.time.wait(33)
def MotionMeerkat(): parser = argparse.ArgumentParser() parser.add_argument( '-gcs_uri', help='The Google Cloud Storage URI of the video.', default='gs://api-project-773889352370-ml/Videos/jantest.mp4') args = parser.parse_args() #create instance video_instance = Video.Video(args.gcs_uri) #send to google for labels video_instance.label() #download file to play locally video_instance.download() #show video video_instance.write()
def run(path, keep, write, view, vidpath=""): #create instance video_instance = Video.Video(path=path, vidpath=vidpath, keep=keep, write=write, view=view) #send to google for labels video_instance.label() #download file to play locally video_instance.download() #show video with annotations video_instance.show() #cleanup video staging file video_instance.cleanup()
def parse(self,filename): inputfile = open(filename, 'r') firstline = inputfile.readline() param = firstline[:-1].split(' ') num_videos, num_endpoints, num_descriptions, num_caches, capacity = int(param[0]), int(param[1]), int(param[2]), int(param[3]), int(param[4]) videoline = inputfile.readline() videos = videoline[:-1].split(' ') for size in videos: vid = Video(size) self.videoList.append(vid) for i in range(num_caches): cache = Cache(capacity) self.cacheList.append(cache) for endpoint in num_endpoints: ep_line = inputfile.readline()[:-1] ep_line = ep_line.split(' ') datacenter_latency = ep_line[0] cache_count = ep_line[1] ep = EndPoint(datacenter_latency) for cache in cache_count: cache_line = inputfile.readline()[:-1] cache_line = cache_line.split(' ') cache_id = cache_line[0] cache_latency = cache_line[1] ep.addCache(cache_id, cache_latency) self.endPointList.append(ep) for i in range(num_descriptions): request_line = inputfile.readline()[:-1] request_line = request_line.split(' ') id_vid, id_ep, num= int(request_line[0]), int(request_line[1]), int(request_line[2]) req = Request(id_vid,id_ep,num) self.requestList.append(req)
def letGoButton(self): SpeechDuration = self.durationInMinutes.get( ) * 60 + self.durationInSeconds.get() if SpeechDuration != "" and self.title.get( ) != "" and self.location != "": name = re.compile(r'^[a-zA-Z][a-zA-Z ]*$') if name.match(self.title.get()): self.root.destroy() from Files.datastore import datastore import Video datastore.name = self.enter datastore.title = self.title.get() Video.Video(self.location, SpeechDuration, self.title.get(), self.name) else: messagebox.showinfo( "Error Message", "Please,You must Write Only English Letters") else: messagebox.showinfo("Error Message", "Please,You must Enter Video Title")
def runThroughQueue(): global timeDelta, theEventQueue, theClock global idealX, idealY, boardWidth, boardHeight global theBoard, thePiece, thePieceColor global theScore, theMultiplyer, gameTime, countFrom global theHighScore, highScoreHasChanged while theEventQueue.isEmpty() == 0: type, info, tuple = theEventQueue.getFromQueue() if type == "Gamestate": if info == "Check For Squares": squareList = theBoard.findSquaresToRemove() if len(squareList) > 0: # Squares were found, mark 'em dead. # Note that by putting "Done With Blocks" on the event queue # now, it will be executed AFTER the block scores are added for i in range(len(squareList)): dataTuple = (i + 1) * 100 theEventQueue.addToQueueFront("Score", "Block Found", dataTuple) (x, y) = squareList[i] theBoard.markSquareAsDead(x, y) elif info == "Get New Board": prepareBoard() elif info == "Get New Piece": idealX = idealY = pieceX = pieceY = 0.0 thePiece = Pieces.getPiece() thePieceColor = random.randint(1, 7) elif info == "Out of Time": theEventQueue.addToQueueFront("Input", "Place Piece", "Forced") elif info == "Update Piece Position": updatePiecePosition(timeDelta) else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Input": if info == "Move Piece Down": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if (yLoc <= (boardHeight - 3)): if (theBoard.checkForCollision(xLoc, yLoc + 1, thePiece) <= 0): idealY += 8.0 else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Move Piece Left": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if (xLoc >= 0): if (theBoard.checkForCollision(xLoc - 1, yLoc, thePiece) <= 0): idealX -= 8.0 else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Move Piece Right": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if (xLoc <= (boardWidth - 3)): if (theBoard.checkForCollision(xLoc + 1, yLoc, thePiece) <= 0): idealX += 8.0 else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Move Piece Up": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if (yLoc >= 0): if (theBoard.checkForCollision(xLoc, yLoc - 1, thePiece) <= 0): idealY -= 8.0 else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Place Piece": # First we get the x,y of the piece xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if theBoard.checkForCollision(xLoc, yLoc, thePiece) == 0: countFrom = gameTime # Resets the countdown, move to event? theBoard.placePiece(xLoc, yLoc, thePiece, thePieceColor) theEventQueue.addToQueueFront("Score", "Placed Piece") theEventQueue.addToQueueFront("Gamestate", "Get New Piece") theEventQueue.addToQueueFront("Gamestate", "Check For Squares") else: if tuple == "Forced": theEventQueue.addToQueueFront("Gamestate", "Game Over") theEventQueue.addToQueueFront("Notification", "Game Over") else: theEventQueue.addToQueueFront("Notification", "Can't Place") elif info == "Rotate Clockwise": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) tempPiece = RotateBlocks.rotateRight(thePiece) if (theBoard.checkForCollision(xLoc, yLoc, tempPiece) <= 0): thePiece = tempPiece else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Rotate Counterclockwise": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) tempPiece = RotateBlocks.rotateLeft(thePiece) if (theBoard.checkForCollision(xLoc, yLoc, tempPiece) <= 0): thePiece = tempPiece else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Notification": if info == "Can't Move": pass elif info == "Can't Place": pass elif info == "Game Over": pass elif info == "Got High Score": pass elif info == "Out Of Time": pass elif info == "Piece Placed": pass elif info == "Squares Removed": pass else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Program": if info == "Game Over": # Game over stuff goes here pass elif info == "Get Highscore": getTheHighScore() highScoreHasChanged = False elif info == "Help": help() elif info == "Print FPS": print "FPS: %.1f" % (theClock.get_fps()) elif info == "Quit": sys.exit() elif info == "Save Highscore": if highScoreHasChanged: saveTheHighScore() elif info == "Tick Clock": timeDelta = theClock.tick(60) # Limit ourselves to 60 FPS gameTime = gameTime + timeDelta if abs(gameTime - countFrom) > 10000: countFrom = gameTime theEventQueue.addToQueueFront("Gamestate", "Out of Time") else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Score": if info == "Add To Score": oldScore = theScore theScore = theScore + tuple if (theScore > theHighScore): if (oldScore < theHighScore): highScoreHasChanged = True theEventQueue.addToQueueFront("Notification", "Got High Score") theHighScore = theScore elif info == "Block Found": if tuple == None: theEventQueue.addToQueueFront("Score", "Add To Score", 100 * theMultiplyer) else: theEventQueue.addToQueueFront("Score", "Add To Score", tuple * theMultiplyer) elif info == "Placed Piece": theEventQueue.addToQueueFront("Score", "Add To Score", 5) elif info == "Reset Score": theScore = 0 theMultiplyer = 1 elif info == "Reset High Score": theHighScore = 0 highScoreHasChanged = True else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Video": if info == "Change Culling": Video.changeCulling() elif info == "Decrease Light X": Video.moveLight(-0.5, 0, 0) elif info == "Decrease Light Y": Video.moveLight(0, -0.5, 0) elif info == "Decrease Light Z": Video.moveLight(0, 0, -0.5) elif info == "Increase Light X": Video.moveLight(0.5, 0, 0) elif info == "Increase Light Y": Video.moveLight(0, 0, 0.5) elif info == "Increase Light Z": Video.moveLight(0, 0, 0.5) elif info == "Print Light Position": Video.moveLight(0, 0, 0) elif info == "Redraw Buffer": draw(timeDelta) elif info == "Sink Blocks": Video.sinkEm(theBoard, timeDelta) elif info == "Swap Buffers": pygame.display.flip() elif info == "Toggle Lights": Video.toggleLights() else: print "Unknown %s event '%s' disregarded." % (type, info) else: print "Event of unknown type '%s' with info '%s' disregarded." % ( type, info) return # Done here
def draw(timeInMS): """Draw the scene for us""" global theBoard, thePiece, pieceX, pieceY, thePieceColor global boardWidth, boardHeight global borderWidth, borderHeight, extraBorder global theScore, gameTime, countFrom, theHighScore timeLeftInCountDown = abs(gameTime - countFrom) # Difference in times timeLeftInCountDown = 10000 - timeLeftInCountDown # MS left to 0 timeLeftInCountDown = timeLeftInCountDown / 1000 # Into seconds timeLeftInCountDown = timeLeftInCountDown + 1 # So it's 10-1, not 9-0 Video.sinkEm(theBoard, timeInMS) Video.startDrawing() Video.drawHolder(boardWidth, boardHeight, borderWidth, borderHeight, extraBorder) Video.drawBlocksInBoard(theBoard, boardWidth, boardHeight, borderWidth, borderHeight) Video.drawPiece(pieceX, pieceY, thePiece, thePieceColor, borderWidth, borderHeight) Video.drawInfo(theScore, timeLeftInCountDown, theHighScore) Video.finishDrawing()
def get(self): bind_id = self.get_argument("bind_id") logger.debug("Score compute request received: bind_id: %s", bind_id) Video.compute_scores(bind_id) dbutils.Session.remove() self.finish()
def checkKeys(event): """Check the keypresses to see if we care.""" global theClock if event.key == pygame.K_ESCAPE: sys.exit() elif event.key == pygame.K_c: Video.changeCulling() elif event.key == pygame.K_h: help() elif event.key == pygame.K_l: Video.toggleLights() elif event.key == pygame.K_p: Video.moveLight(0, 0, 0) elif event.key == pygame.K_q: Video.moveLight(0.5, 0, 0) elif event.key == pygame.K_a: Video.moveLight(-0.5, 0, 0) elif event.key == pygame.K_w: Video.moveLight(0, 0.5, 0) elif event.key == pygame.K_s: Video.moveLight(0, -0.5, 0) elif event.key == pygame.K_e: Video.moveLight(0, 0, 0.5) elif event.key == pygame.K_d: Video.moveLight(0, 0, -0.5) elif event.key == pygame.K_f: print "FPS: %.1f" % (theClock.get_fps())
def get(self): bind_id = self.get_argument("bind_id") logger.debug("Nuke request received: bind_id: %s", bind_id) Video.nuke_user_videos(bind_id) dbutils.Session.remove() self.finish()
def Dancify(source_video, target, source_beats=None, target_beats=None, synch_video_beat=0, synch_audio_beat=0, beat_offset=0, leadin=None, nbeats=None, unfold_to_n=None, source_harmonic=None, source_harmonic_offset=None, target_harmonic=None, target_harmonic_offset=None, force_recompute=None, warp_type="quad", name_tag=None, name_tag_prefix=None, output_path=None, momentum=0.1, **kwargs): """ :param source_video: :param target: :param source_beats: :param target_beats: :param synch_video_beat: :param synch_audio_beat: :param beat_offset: :param leadin: :param nbeats: :param unfold_to_n: :param source_harmonic: :param target_harmonic: :param source_harmonic_offset: :param target_harmonic_offset: :param force_recompute: :param warp_type: :param name_tag: :param name_tag_prefix: :param output_path: :param momentum: :param kwargs: :return: """ if (output_path is not None) and (not force_recompute): if os.path.exists(output_path): return Video(output_path) if isinstance(target, Video): target_audio = target.getAudio() else: target_audio = target synchaudio = synch_audio_beat synchvideo = synch_video_beat lead_in = leadin if lead_in is None: lead_in = min(synchaudio, synchvideo) elif isinstance(lead_in, str) and lead_in[0] == "<": # lead_in = min(synchaudio, synchvideo, int(lead_in)) lead_in = min(synchaudio, int(lead_in)) start_audio_beat = synchaudio - lead_in start_video_beat = synchvideo - lead_in if beat_offset and beat_offset > 0: start_audio_beat = start_audio_beat + beat_offset start_video_beat = start_video_beat + beat_offset print("Warping {} to {}".format(source_video.getName(), target_audio.getName())) bitrate = None vbeats = source_beats if source_beats is None: vbeats = source_video.getVisualBeats() tbeats = target_beats if target_beats is None: tbeats = target_audio.getBeatEvents() if start_video_beat < 0: if synchvideo == 0: vbeats = [vbeats[0].clone()] + vbeats vbeats[0].start = vbeats[0].start - (vbeats[2].start - vbeats[1].start) vbadd = Event.SubdivideIntervals(vbeats[:2], -start_video_beat) vbeats = vbadd + vbeats[2:] start_video_beat = 0 vbeats = vbeats[start_video_beat:] tbeats = tbeats[start_audio_beat:] if source_harmonic == "half": vbeats = Event.Half(vbeats, source_harmonic_offset) elif source_harmonic == "third": vbeats = Event.Third(vbeats, source_harmonic_offset) elif source_harmonic == "double": vbeats = Event.Double(vbeats) if target_harmonic == "half": tbeats = Event.Half(tbeats, target_harmonic_offset) elif target_harmonic == "third": tbeats = Event.Third(tbeats, target_harmonic_offset) elif target_harmonic == "double": tbeats = Event.Double(tbeats) if nbeats: print("Rendering {} beats of result".format(nbeats)) if len(vbeats) > nbeats: vbeats = vbeats[:nbeats] print(len(vbeats)) if unfold_to_n: vbeats = Event.UnfoldToN(vbeats, unfold_to_n, momentum=momentum) if len(tbeats) > len(vbeats): tbeats = tbeats[:len(vbeats)] if warp_type is "weight": vbeats = source_video.visualBeatsFromEvents(vbeats) if name_tag is None: name_tag = (warp_type + "_sab_" + str(start_audio_beat) + "_svb_" + str(start_video_beat)) if name_tag_prefix is not None: name_tag = name_tag + name_tag_prefix warp_args = dict( target=target_audio, source_events=vbeats, target_events=tbeats, warp_type=warp_type, force_recompute=force_recompute, name_tag=name_tag, ) if bitrate: warp_args.update(dict(bitrate=bitrate)) warp_args.update(kwargs) warped_result = source_video.getWarped(**warp_args) if output_path: final_output_path = output_path if os.path.isfile(final_output_path): output_filename = os.path.basename(output_path) name_parts = os.path.splitext(output_filename) output_filename_base = name_parts[0] output_directory_path = os.path.dirname(output_path) if output_directory_path == "": output_directory_path = "." output_ext = name_parts[1] ntry = 1 tryname = output_filename_base + "_" + str(ntry) while (os.path.isfile( os.path.join(output_directory_path, tryname + output_ext)) and ntry < 100): ntry = ntry + 1 tryname = output_filename_base + "_" + str(ntry) final_output_path = os.path.join(output_directory_path, tryname + output_ext) shutil.copy2(src=warped_result.getPath(), dst=final_output_path) n_frames_total = warped_result.num_frames_total warp_used = warped_result.getInfo("warp_used") warped_result_final = Video(path=final_output_path, num_frames_total=n_frames_total) warped_result_final.setInfo(label="warp_used", value=warp_used) os.remove(warped_result.getPath()) warped_result = warped_result_final return warped_result def getVBSegments( self, source_video, source_beats=None, search_tempo=None, search_window=None, max_height=None, beat_limit=None, n_return=None, unary_weight=None, binary_weight=None, break_on_cuts=None, peak_vars=None, ): source = source_video if source_beats is None: if peak_vars is not None: vbeats = source.getFeature("simple_visual_beats", **peak_vars) else: vbeats = source.getFeature("simple_visual_beats") else: vbeats = source_beats # if search_tempo is not None: tempo = search_tempo beat_time = np.true_divide(60.0, tempo) clips = VisualBeat.PullOptimalPaths_Basic( vbeats, target_period=beat_time, unary_weight=unary_weight, binary_weight=binary_weight, break_on_cuts=break_on_cuts, window_size=search_window, ) else: clips = VisualBeat.PullOptimalPaths_Autocor( vbeats, unary_weight=unary_weight, binary_weight=binary_weight, break_on_cuts=break_on_cuts, window_size=search_window, ) if beat_limit is None: beat_limit = 2 print("There were {} candidates".format(len(vbeats))) nclips = 0 segments = [] for S in clips: if len(S) > beat_limit: nclips = nclips + 1 segments.append(S) if n_return is not None: segments.sort(key=len, reverse=True) segments = segments[:n_return] return segments
def main(): pygame.init() pygame.display.set_mode((640, 480), pygame.OPENGL | pygame.DOUBLEBUF) Video.initThings(144, 136, 160) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: sys.exit() elif event.key == pygame.K_c: Video.changeCulling() elif event.key == pygame.K_h: help() elif event.key == pygame.K_l: Video.toggleLights() elif event.key == pygame.K_p: Video.moveLight(0, 0, 0) elif event.key == pygame.K_q: Video.moveLight(0.5, 0, 0) elif event.key == pygame.K_a: Video.moveLight(-0.5, 0, 0) elif event.key == pygame.K_w: Video.moveLight(0, 0.5, 0) elif event.key == pygame.K_s: Video.moveLight(0, -0.5, 0) elif event.key == pygame.K_e: Video.moveLight(0, 0, 0.5) elif event.key == pygame.K_d: Video.moveLight(0, 0, -0.5) Video.startDrawing() Video.drawHolder(16, 15, 8, 8) #Video.drawReference(8, 1, 8) Too small to be seen, so we don't draw Video.drawBlock(16, 0, 8, 1) Video.drawBlock(20, 0, 16, 2) Video.drawBlock(24, 0, 24, 3) Video.finishDrawing() pygame.display.flip() pygame.time.wait(10)
def runThroughQueue(): global timeDelta, theEventQueue, theClock global idealX, idealY, boardWidth, boardHeight while theEventQueue.isEmpty() == 0: type, info = theEventQueue.getFromQueue() if type == "Gamestate": if info == "Update Piece Position": updatePiecePosition(timeDelta) else: print "Unknown %s event '%s' disgarded." % (type, info) elif type == "Input": if info == "Move Piece Down": idealY += 8.0 if (idealY > (boardHeight - 3) * 8.0): idealY = (boardHeight - 3) * 8.0 elif info == "Move Piece Left": idealX -= 8.0 if (idealX < 0.0): idealX = 0.0 elif info == "Move Piece Right": idealX += 8.0 if (idealX > (boardWidth - 3) * 8.0): idealX = (boardWidth - 3) * 8.0 elif info == "Move Piece Up": idealY -= 8.0 if (idealY < 0.0): idealY = 0.0 elif info == "Place Piece": pass # This is where we place the piece elif info == "Rotate Clockwise": idealAngle += 90 if (idealAngle >= 360): idealAngle -= 360 elif info == "Rotate Counterclockwise": idealAngle -= 90 if (idealAngle < 0): idealAngle += 360 else: print "Unknown %s event '%s' disgarded." % (type, info) elif type == "Program": if info == "Help": help() elif info == "Print FPS": print "FPS: %.1f" % (theClock.get_fps()) elif info == "Quit": sys.exit() elif info == "Tick Clock": timeDelta = theClock.tick(60) # Limit ourselves to 60 FPS else: print "Unknown %s event '%s' disgarded." % (type, info) elif type == "Video": if info == "Change Culling": Video.changeCulling() elif info == "Decrease Light X": Video.moveLight(-0.5, 0, 0) elif info == "Decrease Light Y": Video.moveLight(0, -0.5, 0) elif info == "Decrease Light Z": Video.moveLight(0, 0, -0.5) elif info == "Increase Light X": Video.moveLight(0.5, 0, 0) elif info == "Increase Light Y": Video.moveLight(0, 0, 0.5) elif info == "Increase Light Z": Video.moveLight(0, 0, 0.5) elif info == "Print Light Position": Video.moveLight(0, 0, 0) elif info == "Redraw Buffer": draw(timeDelta) elif info == "Swap Buffers": pygame.display.flip() elif info == "Toggle Lights": Video.toggleLights() else: print "Unknown %s event '%s' disgarded." % (type, info) else: print "Event of unknown type '%s' with info '%s' disgarded." % (type, info) return # Done here
from Video import * from cv2 import * if __name__ == '__main__': vide = Video("direccion del video a modificar") im = cv2.imread("direccion de imagen para cargar", cv2.IMREAD_COLOR) #recibe segundo de inicio, segundo de terminacion, posicion en fila, posicion en columna y la imagen #cabe resaltar que se le pueden meter tantas imagenes se quieran para modificar el video vide.anadirModificacion(4, 8, 60, 60, im) vide.anadirModificacion(15, 20, 120, 120, im) #recibe direccion para cargar la cancion vide.setMusica("mrdm.mp3") #guarda el video modificado vide.guardarVideoModificado("./plytchingon.mp4")
def draw(timeInMS): """Draw the scene for us""" global theBoard, thePiece, pieceX, pieceY global boardWidth, boardHeight global borderWidth, borderHeight Video.sinkEm(theBoard, timeInMS) Video.startDrawing() Video.drawHolder(boardWidth, boardHeight, borderWidth, borderHeight) Video.drawBlocksInBoard(theBoard, boardWidth, boardHeight, borderWidth, borderHeight) Video.drawPiece(pieceX, pieceY, thePiece, 4, borderWidth, borderHeight) Video.finishDrawing()
def checkKeys(event): """Check the keypresses to see if we care.""" global theClock, idealX, idealY, boardWidth, boardHeight if event.key == pygame.K_ESCAPE: sys.exit() elif event.key == pygame.K_c: Video.changeCulling() elif event.key == pygame.K_h: help() elif event.key == pygame.K_l: Video.toggleLights() elif event.key == pygame.K_p: Video.moveLight(0, 0, 0) elif event.key == pygame.K_q: Video.moveLight(0.5, 0, 0) elif event.key == pygame.K_a: Video.moveLight(-0.5, 0, 0) elif event.key == pygame.K_w: Video.moveLight(0, 0.5, 0) elif event.key == pygame.K_s: Video.moveLight(0, -0.5, 0) elif event.key == pygame.K_e: Video.moveLight(0, 0, 0.5) elif event.key == pygame.K_d: Video.moveLight(0, 0, -0.5) elif event.key == pygame.K_f: print "FPS: %.1f" % (theClock.get_fps()) elif event.key == pygame.K_UP: idealY -= 8.0 if (idealY < 0.0): idealY = 0.0 elif event.key == pygame.K_DOWN: idealY += 8.0 if (idealY > (boardHeight - 3) * 8.0): idealY = (boardHeight - 3) * 8.0 elif event.key == pygame.K_LEFT: idealX -= 8.0 if (idealX < 0.0): idealX = 0.0 elif event.key == pygame.K_RIGHT: idealX += 8.0 if (idealX > (boardWidth - 3) * 8.0): idealX = (boardWidth - 3) * 8.0
import cv2 import Images as images import Utils as util import Video as video print(util.getTime("/", ":") + " init face recognition") print(util.getTime("/", ":") + " loading cascade path") cascade_path = "./venv/lib/python3.7/site-packages/cv2/data/" faceCascade = cv2.CascadeClassifier(cascade_path + "haarcascade_frontalface_alt.xml") # faceCascade = cv2.CascadeClassifier(cascade_path + "haarcascade_profileface.xml") # faceCascade = cv2.CascadeClassifier(cascade_path + "haarcascade_eye_tree_eyeglasses.xml") # faceCascade = cv2.CascadeClassifier(cascade_path + "haarcascade_eye.xml") # faceCascade = cv2.CascadeClassifier(cascade_path + "haarcascade_licence_plate_rus_16stages.xml") # faceCascade = cv2.CascadeClassifier(cascade_path + "haarcascade_smile.xml") # faceCascade = cv2.CascadeClassifier(cascade_path + "haarcascade_fullbody.xml") print(util.getTime("/", ":") + " cascade path loaded") video.video() # images.images(faceCascade)
def draw(timeInMS): """Draw the scene for us""" global theBoard, thePiece, pieceX, pieceY, pieceAngle, idealAngle global boardWidth, boardHeight global borderWidth, borderHeight Video.sinkEm(theBoard, timeInMS) Video.startDrawing() Video.drawHolder(boardWidth, boardHeight, borderWidth, borderHeight) Video.drawBlocksInBoard(theBoard, boardWidth, boardHeight, borderWidth, borderHeight) tempPiece = thePiece if idealAngle > 0: if idealAngle == 90: tempPiece = RotateBlocks.rotateRight(tempPiece) elif idealAngle == 180: tempPiece = RotateBlocks.rotateRight(tempPiece) tempPiece = RotateBlocks.rotateRight(tempPiece) elif idealAngle == 270: tempPiece = RotateBlocks.rotateLeft(tempPiece) Video.drawPiece(pieceX, pieceY, pieceAngle, tempPiece, 4, borderWidth, borderHeight) Video.finishDrawing()
def Dancefer(source_video, target, synch_video_beat=0, synch_audio_beat=0, beat_offset=0, leadin=None, nbeats=None, source_harmonic=None, target_harmonic=None, source_harmonic_offset=None, target_harmonic_offset=None, force_recompute=None, warp_type="quad", name_tag=None, name_tag_prefix=None, output_path=None, **kwargs): """ :param source_video: video to warp :param target: music to warp to :param synch_video_beat: integer specifying a beat (as in the nth beat) from the video to synchronize with synch_audio_beat :param synch_audio_beat: integer specifying a beat (as in the nth beat) from the video to synchronize with synch_video_beat :param beat_offset: Lets you offset which beats you want to render. This is mostly for testing different parts of an output. :param leadin: how many beats before the synch beats to render :param nbeats: lets you restrict output to rendering n beats :param source_harmonic: can be None, 'half', or 'double'. 'half' will use every other beat, which you can offset with source_harmonic_offset. 'double' will add an additional beat between every consecutive beat. update - added 'third' for waltzes. :param target_harmonic: can be None, 'half', or 'double'. 'half' will use every other beat, which you can offset with source_harmonic_offset. 'double' will add an additional beat between every consecutive beat. update - added 'third' for waltzes. :param source_harmonic_offset: optional offset for harmonic :param target_harmonic_offset: optional offset for harmonic :param force_recompute: :param warp_type: :param name_tag: :param name_tag_prefix: :param output_path: :param kwargs: :return: """ if (output_path is not None) and (not force_recompute): if os.path.exists(output_path): return Video(output_path) if isinstance(target, Video): target_audio = target.getAudio() else: target_audio = target synchaudio = synch_audio_beat synchvideo = synch_video_beat lead_in = leadin if lead_in is None: lead_in = min(synchaudio, synchvideo) elif isinstance(lead_in, str) and lead_in[0] == "<": # lead_in = min(synchaudio, synchvideo, int(lead_in)) lead_in = min(synchaudio, int(lead_in)) start_audio_beat = synchaudio - lead_in start_video_beat = synchvideo - lead_in if beat_offset and beat_offset > 0: start_audio_beat = start_audio_beat + beat_offset start_video_beat = start_video_beat + beat_offset print("Warping {} to {}".format(source_video.getName(), target_audio.getName())) bitrate = None vbeats = source_video.audio.getBeatEvents() tbeats = target_audio.getBeatEvents() if start_video_beat < 0: if synchvideo == 0: vbeats = [vbeats[0].clone()] + vbeats vbeats[0].start = vbeats[0].start - (vbeats[2].start - vbeats[1].start) vbadd = Event.SubdivideIntervals(vbeats[:2], -start_video_beat) vbeats = vbadd + vbeats[2:] start_video_beat = 0 vbeats = vbeats[start_video_beat:] tbeats = tbeats[start_audio_beat:] if source_harmonic == "half": vbeats = Event.Half(vbeats, source_harmonic_offset) elif source_harmonic == "third": vbeats = Event.Third(vbeats, source_harmonic_offset) elif source_harmonic == "double": vbeats = Event.Double(vbeats) if target_harmonic == "half": tbeats = Event.Half(tbeats, target_harmonic_offset) elif target_harmonic == "third": tbeats = Event.Third(tbeats, target_harmonic_offset) elif target_harmonic == "double": tbeats = Event.Double(tbeats) if nbeats: print("Rendering {} beats of result".format(nbeats)) if len(vbeats) > nbeats: vbeats = vbeats[:nbeats] print(len(vbeats)) if len(tbeats) > nbeats: tbeats = tbeats[:nbeats] print(len(tbeats)) else: if vbeats[-1].start < source_video.getDuration(): print(tbeats) print("length of tbeats is: {}".format(len(tbeats))) print("start_video_beat: {}, start_audio_beat: {}".format( start_video_beat, start_audio_beat)) newbeat = vbeats[-1].clone() deltatime = source_video.getDuration() - newbeat.start newbeat.start = source_video.getDuration() target_newbeat = tbeats[-1].clone() target_newbeat.start = min(target_newbeat.start + deltatime, target_audio.getDuration()) tbeats.append(target_newbeat) if warp_type is "weight": vbeats = source_video.visualBeatsFromEvents(vbeats) if name_tag is None: name_tag = (warp_type + "_sab_" + str(start_audio_beat) + "_svb_" + str(start_video_beat)) if name_tag_prefix is not None: name_tag = name_tag + name_tag_prefix warp_args = dict( target=target_audio, source_events=vbeats, target_events=tbeats, warp_type=warp_type, force_recompute=force_recompute, name_tag=name_tag, ) if bitrate: warp_args.update(dict(bitrate=bitrate)) warp_args.update(kwargs) warped_result = source_video.getWarped(**warp_args) if output_path: final_output_path = output_path if os.path.isfile(final_output_path): output_filename = os.path.basename(output_path) name_parts = os.path.splitext(output_filename) output_filename_base = name_parts[0] output_directory_path = os.path.dirname(output_path) if output_directory_path == "": output_directory_path = "." output_ext = name_parts[1] ntry = 1 tryname = output_filename_base + "_" + str(ntry) while (os.path.isfile( os.path.join(output_directory_path, tryname + output_ext)) and ntry < 100): ntry = ntry + 1 tryname = output_filename_base + "_" + str(ntry) final_output_path = os.path.join(output_directory_path, tryname + output_ext) shutil.copy2(src=warped_result.getPath(), dst=final_output_path) n_frames_total = warped_result.num_frames_total warp_used = warped_result.getInfo("warp_used") warped_result_final = Video(path=final_output_path, num_frames_total=n_frames_total) warped_result_final.setInfo(label="warp_used", value=warp_used) os.remove(warped_result.getPath()) warped_result = warped_result_final return warped_result
def runThroughQueue(): global timeDelta, theEventQueue, theClock global idealX, idealY, boardWidth, boardHeight global theBoard, thePiece, thePieceColor global theScore, theMultiplyer while theEventQueue.isEmpty() == 0: type, info = theEventQueue.getFromQueue() if type == "Gamestate": if info == "Check For Squares": squareList = theBoard.findSquaresToRemove() if len(squareList) > 0: # Squares were found, mark 'em dead. # Note that by putting "Done With Blocks" on the event queue # now, it will be executed AFTER the block scores are added theEventQueue.addToQueueFront("Score", "Done With Blocks") for i in range(len(squareList)): theEventQueue.addToQueueFront("Score", "Block Found") (x, y) = squareList[i] theBoard.markSquareAsDead(x, y) elif info == "Get New Board": prepareBoard() elif info == "Get New Piece": idealX = idealY = pieceX = pieceY = 0.0 thePiece = Pieces.getPiece() thePieceColor = random.randint(1, 7) elif info == "Update Piece Position": updatePiecePosition(timeDelta) else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Input": if info == "Move Piece Down": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if (yLoc <= (boardHeight - 3)): if (theBoard.checkForCollision(xLoc, yLoc + 1, thePiece) <= 0): idealY += 8.0 else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Move Piece Left": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if (xLoc >= 0): if (theBoard.checkForCollision(xLoc - 1, yLoc, thePiece) <= 0): idealX -= 8.0 else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Move Piece Right": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if (xLoc <= (boardWidth - 3)): if (theBoard.checkForCollision(xLoc + 1, yLoc, thePiece) <= 0): idealX += 8.0 else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Move Piece Up": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if (yLoc >= 0): if (theBoard.checkForCollision(xLoc, yLoc - 1, thePiece) <= 0): idealY -= 8.0 else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Place Piece": # First we get the x,y of the piece xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if theBoard.checkForCollision(xLoc, yLoc, thePiece) == 0: theBoard.placePiece(xLoc, yLoc, thePiece, thePieceColor) theEventQueue.addToQueueFront("Score", "Placed Piece") theEventQueue.addToQueueFront("Gamestate", "Get New Piece") theEventQueue.addToQueueFront("Gamestate", "Check For Squares") else: theEventQueue.addToQueueFront("Notification", "Can't Place") elif info == "Rotate Clockwise": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) tempPiece = RotateBlocks.rotateRight(thePiece) if (theBoard.checkForCollision(xLoc, yLoc, tempPiece) <= 0): thePiece = tempPiece else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Rotate Counterclockwise": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) tempPiece = RotateBlocks.rotateLeft(thePiece) if (theBoard.checkForCollision(xLoc, yLoc, tempPiece) <= 0): thePiece = tempPiece else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Notification": if info == "Can't Move": pass elif info == "Can't Place": pass elif info == "Out Of Time": pass elif info == "Piece Placed": pass elif info == "Squares Removed": pass else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Program": if info == "Help": help() elif info == "Print FPS": print "FPS: %.1f" % (theClock.get_fps()) elif info == "Quit": sys.exit() elif info == "Tick Clock": timeDelta = theClock.tick(60) # Limit ourselves to 60 FPS else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Score": if info == "Block Found": theScore = theScore + 100 * theMultiplyer theMultiplyer = theMultiplyer + 1 elif info == "Done With Blocks": theMultiplyer = 1 elif info == "Placed Piece": theScore = theScore + 5 elif info == "Reset Score": theScore = 0 theMultiplyer = 1 else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Video": if info == "Change Culling": Video.changeCulling() elif info == "Decrease Light X": Video.moveLight(-0.5, 0, 0) elif info == "Decrease Light Y": Video.moveLight(0, -0.5, 0) elif info == "Decrease Light Z": Video.moveLight(0, 0, -0.5) elif info == "Increase Light X": Video.moveLight(0.5, 0, 0) elif info == "Increase Light Y": Video.moveLight(0, 0, 0.5) elif info == "Increase Light Z": Video.moveLight(0, 0, 0.5) elif info == "Print Light Position": Video.moveLight(0, 0, 0) elif info == "Redraw Buffer": draw(timeDelta) elif info == "Sink Blocks": Video.sinkEm(theBoard, timeDelta) elif info == "Swap Buffers": pygame.display.flip() elif info == "Toggle Lights": Video.toggleLights() else: print "Unknown %s event '%s' disregarded." % (type, info) else: print "Event of unknown type '%s' with info '%s' disregarded." % (type, info) return # Done here
import csv as csv # import Picture as picture import Video as video # print "Python Version" + sys.version # print "Numpy version " + np.__version__ # print "Video Version " + cv.__version__ def write_csv(path, data): csv_file = open(path, 'w', newline='') csv_writer = csv.writer(csv_file, delimiter=',', quoting=csv.QUOTE_ALL) csv_writer.writerows(data) # csv_writer.writerow(data[i]) # frames, analysis = video.capture(320, 240, 30) frames, analysis = video.read( 'E:/Desktop/PhD/Datasets/M3C Speakers Localization v3/00001.mp4', 25) # video.save('Output/output.avi', frames, 25) # write_csv('Output/output.csv', analysis)
def runThroughQueue(): """Go through the queue and deal with the events in it.""" global timeDelta, theEventQueue, theClock global idealX, idealY, boardWidth, boardHeight global theBoard, thePiece, thePieceColor global theScore, theMultiplyer, gameTime, countFrom global theHighScore, highScoreHasChanged while theEventQueue.isEmpty() == 0: type, info, tuple = theEventQueue.getFromQueue() if type == "Gamestate": if info == "Check For Squares": squareList = theBoard.findSquaresToRemove() if len(squareList) > 0: # Squares were found, mark 'em dead. # Note that by putting "Done With Blocks" on the event queue # now, it will be executed AFTER the block scores are added for i in range(len(squareList)): dataTuple = (i + 1) * 100 theEventQueue.addToQueueFront("Score", "Block Found", dataTuple) (x, y) = squareList[i] theBoard.markSquareAsDead(x, y) elif info == "Get New Board": prepareBoard() elif info == "Get New Piece": idealX = idealY = pieceX = pieceY = 0.0 thePiece = Pieces.getPiece() thePieceColor = random.randint(1, 7) elif info == "Out of Time": theEventQueue.addToQueueFront("Input", "Place Piece", "Forced") elif info == "Update Piece Position": updatePiecePosition(timeDelta) else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Input": if info == "Move Piece Down": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if (yLoc <= (boardHeight - 3)): if (theBoard.checkForCollision(xLoc, yLoc + 1, thePiece) <= 0): idealY += 8.0 else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Move Piece Left": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if (xLoc >= 0): if (theBoard.checkForCollision(xLoc - 1, yLoc, thePiece) <= 0): idealX -= 8.0 else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Move Piece Right": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if (xLoc <= (boardWidth - 3)): if (theBoard.checkForCollision(xLoc + 1, yLoc, thePiece) <= 0): idealX += 8.0 else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Move Piece Up": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if (yLoc >= 0): if (theBoard.checkForCollision(xLoc, yLoc - 1, thePiece) <= 0): idealY -= 8.0 else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Place Piece": # First we get the x,y of the piece xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) if theBoard.checkForCollision(xLoc, yLoc, thePiece) == 0: countFrom = gameTime # Resets the countdown, move to event? theBoard.placePiece(xLoc, yLoc, thePiece, thePieceColor) theEventQueue.addToQueueFront("Score", "Placed Piece") theEventQueue.addToQueueFront("Gamestate", "Get New Piece") theEventQueue.addToQueueFront("Gamestate", "Check For Squares") else: if tuple == "Forced": theEventQueue.addToQueueFront("Program", "Game Over") theEventQueue.addToQueueFront("Notification", "Game Over") else: theEventQueue.addToQueueFront("Notification", "Can't Place") elif info == "Rotate Clockwise": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) tempPiece = RotateBlocks.rotateRight(thePiece) if (theBoard.checkForCollision(xLoc, yLoc, tempPiece) <= 0): thePiece = tempPiece else: theEventQueue.addToQueueFront("Notification", "Can't Move") elif info == "Rotate Counterclockwise": xLoc = int(idealX / 8.0) yLoc = int(idealY / 8.0) tempPiece = RotateBlocks.rotateLeft(thePiece) if (theBoard.checkForCollision(xLoc, yLoc, tempPiece) <= 0): thePiece = tempPiece else: theEventQueue.addToQueueFront("Notification", "Can't Move") else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Notification": if info == "Can't Move": Sound.playSound("Bad Move") elif info == "Can't Place": Sound.playSound("Bad Place") elif info == "Game Over": Sound.playSound("Game Over") elif info == "Got High Score": Sound.playSound("Got High") elif info == "Out Of Time": Sound.playSound("Forced") elif info == "Piece Placed": Sound.playSound("Place") elif info == "Squares Removed": Sound.playSound("Removed") else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Program": if info == "Game Over": # Game over stuff goes here # For now, just quit theEventQueue.addToQueueFront("Program", "Quit") theEventQueue.addToQueueFront("Program", "Save Highscore") elif info == "Get Highscore": getTheHighScore() highScoreHasChanged = False elif info == "Help": help() elif info == "Print FPS": print "FPS: %.1f" % (theClock.get_fps()) elif info == "Quit": sys.exit() elif info == "Save Highscore": if highScoreHasChanged: saveTheHighScore() elif info == "Tick Clock": timeDelta = theClock.tick(60) # Limit ourselves to 60 FPS gameTime = gameTime + timeDelta if abs(gameTime - countFrom) > 10000: countFrom = gameTime theEventQueue.addToQueueFront("Gamestate", "Out of Time") else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Score": if info == "Add To Score": oldScore = theScore theScore = theScore + tuple if (theScore > theHighScore): if (oldScore < theHighScore): highScoreHasChanged = True theEventQueue.addToQueueFront("Notification", "Got High Score") theHighScore = theScore elif info == "Block Found": if tuple == None: theEventQueue.addToQueueFront("Score", "Add To Score", 100 * theMultiplyer) else: theEventQueue.addToQueueFront("Score", "Add To Score", tuple * theMultiplyer) elif info == "Placed Piece": theEventQueue.addToQueueFront("Score", "Add To Score", 5) elif info == "Reset Score": theScore = 0 theMultiplyer = 1 elif info == "Reset High Score": theHighScore = 0 highScoreHasChanged = True else: print "Unknown %s event '%s' disregarded." % (type, info) elif type == "Video": if info == "Change Culling": Video.changeCulling() elif info == "Decrease Light X": Video.moveLight(-0.5, 0, 0) elif info == "Decrease Light Y": Video.moveLight(0, -0.5, 0) elif info == "Decrease Light Z": Video.moveLight(0, 0, -0.5) elif info == "Increase Light X": Video.moveLight(0.5, 0, 0) elif info == "Increase Light Y": Video.moveLight(0, 0, 0.5) elif info == "Increase Light Z": Video.moveLight(0, 0, 0.5) elif info == "Print Light Position": Video.moveLight(0, 0, 0) elif info == "Redraw Buffer": draw(timeDelta) elif info == "Sink Blocks": Video.sinkEm(theBoard, timeDelta) elif info == "Swap Buffers": pygame.display.flip() elif info == "Toggle Lights": Video.toggleLights() else: print "Unknown %s event '%s' disregarded." % (type, info) else: print "Event of unknown type '%s' with info '%s' disregarded." % (type, info) return # Done here
def draw(timeInMS): """Draw the scene for us""" Video.startDrawing() Video.drawHolder(16, 15, 8, 8) #Video.drawReference(8, 1, 8) Too small to be seen, so we don't draw Video.drawBlock(16, 0, 8, 1) Video.drawBlock(20, 0, 16, 2) Video.drawBlock(24, 0, 24, 3) Video.finishDrawing()
def get(self): bind_id = self.get_argument("bind_id") logger.debug("Insert likes request received: bind_id: %s", bind_id) Video.insert_fb_likes(bind_id) dbutils.Session.remove() self.finish()
def runThroughQueue(): global timeDelta, theEventQueue, theClock global idealX, idealY, boardWidth, boardHeight global idealAngle global theBoard, thePiece, thePieceColor while theEventQueue.isEmpty() == 0: type, info = theEventQueue.getFromQueue() if type == "Gamestate": if info == "Update Piece Position": updatePiecePosition(timeDelta) else: print "Unknown %s event '%s' disgarded." % (type, info) elif type == "Input": if info == "Move Piece Down": idealY += 8.0 if (idealY > (boardHeight - 3) * 8.0): idealY = (boardHeight - 3) * 8.0 elif info == "Move Piece Left": idealX -= 8.0 if (idealX < 0.0): idealX = 0.0 elif info == "Move Piece Right": idealX += 8.0 if (idealX > (boardWidth - 3) * 8.0): idealX = (boardWidth - 3) * 8.0 elif info == "Move Piece Up": idealY -= 8.0 if (idealY < 0.0): idealY = 0.0 elif info == "Place Piece": # First we get the x,y of the piece xLoc = idealX / 8.0 yLoc = idealY / 8.0 # We need a piece rotated like the user's piece tempPiece = thePiece if idealAngle > 0: if idealAngle == 90: tempPiece = RotateBlocks.rotateRight(tempPiece) elif idealAngle == 180: tempPiece = RotateBlocks.rotateRight(tempPiece) tempPiece = RotateBlocks.rotateRight(tempPiece) elif idealAngle == 270: tempPiece = RotateBlocks.rotateLeft(tempPiece) if theBoard.pieceCanFit(xLoc, yLoc, tempPiece): theBoard.placePiece(xLoc, yLoc, tempPiece, thePieceColor) else: theEventQueue.addToQueueFront("Notification", "Can't Place") elif info == "Rotate Clockwise": idealAngle += 90 if (idealAngle >= 360): idealAngle -= 360 elif info == "Rotate Counterclockwise": idealAngle -= 90 if (idealAngle < 0): idealAngle += 360 else: print "Unknown %s event '%s' disgarded." % (type, info) elif type == "Program": if info == "Help": help() elif info == "Print FPS": print "FPS: %.1f" % (theClock.get_fps()) elif info == "Quit": sys.exit() elif info == "Tick Clock": timeDelta = theClock.tick(60) # Limit ourselves to 60 FPS else: print "Unknown %s event '%s' disgarded." % (type, info) elif type == "Video": if info == "Change Culling": Video.changeCulling() elif info == "Decrease Light X": Video.moveLight(-0.5, 0, 0) elif info == "Decrease Light Y": Video.moveLight(0, -0.5, 0) elif info == "Decrease Light Z": Video.moveLight(0, 0, -0.5) elif info == "Increase Light X": Video.moveLight(0.5, 0, 0) elif info == "Increase Light Y": Video.moveLight(0, 0, 0.5) elif info == "Increase Light Z": Video.moveLight(0, 0, 0.5) elif info == "Print Light Position": Video.moveLight(0, 0, 0) elif info == "Redraw Buffer": draw(timeDelta) elif info == "Swap Buffers": pygame.display.flip() elif info == "Toggle Lights": Video.toggleLights() else: print "Unknown %s event '%s' disgarded." % (type, info) else: print "Event of unknown type '%s' with info '%s' disgarded." % (type, info) return # Done here