Example #1
0
    def run(self):
        ''' run all patterns in the playbook '''
        plays = []
        matched_tags_all = set()
        unmatched_tags_all = set()

        # loop through all patterns and run them
        self.callbacks.on_start()
        for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs):
            play = Play(self, play_ds, play_basedir, vault_password=self.vault_password)
            assert play is not None

            matched_tags, unmatched_tags = play.compare_tags(self.only_tags)

            matched_tags_all = matched_tags_all | matched_tags
            unmatched_tags_all = unmatched_tags_all | unmatched_tags

            # Remove tasks we wish to skip
            matched_tags = matched_tags - set(self.skip_tags)

            # if we have matched_tags, the play must be run.
            # if the play contains no tasks, assume we just want to gather facts
            # in this case there are actually 3 meta tasks (handler flushes) not 0
            # tasks, so that's why there's a check against 3
            if (len(matched_tags) > 0 or len(play.tasks()) == 3):
                plays.append(play)

        # if the playbook is invoked with --tags or --skip-tags that don't
        # exist at all in the playbooks then we need to raise an error so that
        # the user can correct the arguments.
        unknown_tags = ((set(self.only_tags) | set(self.skip_tags)) -
                        (matched_tags_all | unmatched_tags_all))

        for t in RESERVED_TAGS:
            unknown_tags.discard(t)

        if len(unknown_tags) > 0:
            for t in RESERVED_TAGS:
                unmatched_tags_all.discard(t)
            msg = 'tag(s) not found in playbook: %s.  possible values: %s'
            unknown = ','.join(sorted(unknown_tags))
            unmatched = ','.join(sorted(unmatched_tags_all))
            raise errors.AnsibleError(msg % (unknown, unmatched))

        for play in plays:
            ansible.callbacks.set_play(self.callbacks, play)
            ansible.callbacks.set_play(self.runner_callbacks, play)
            if not self._run_play(play):
                break

        ansible.callbacks.set_play(self.callbacks, None)
        ansible.callbacks.set_play(self.runner_callbacks, None)

        # summarize the results
        results = {}
        for host in self.stats.processed.keys():
            results[host] = self.stats.summarize(host)
        return results
Example #2
0
    def __init__(self):
        QtCore.QObject.__init__(self)
        Play.__init__(self, continuous=True)
        self._play = None
        self._goalie_id = None
        self.add_transition(Behavior.State.start, Behavior.State.running,
                            lambda: True, 'immediately')

        # if a play fails for some reason, we can temporarily blacklist it, which removes it from play
        # selection for the next iteration, then enables it again
        self.temporarily_blacklisted_play_class = None
        self._currently_restarting = False
    def suma(nombre):

        sonido=Play(1024)
        Datos=sonido.open(nombre)
        sonido.start(Datos[0],Datos[1],Datos[2])
        sonido.play(Datos[3])
        sonido.closed()
Example #4
0
    def play(self, reset_gamefile):
        self.players = set()
        self.hands = set()
        self.cards = set()
        self.me = None
        self.conviction = None

        self.gamefile = open('gamefile.txt', 'w+' if reset_gamefile else 'r+', buffering=1)
        self.prompt_queue = [x.rstrip("\n") for x in self.gamefile]

        setup = Setup()
        setup.run(self)

        play = Play()
        play.run(self)
Example #5
0
 def open(self):
     init_analysis(self.main_window)
     self.main_window.analysis_next_btn.setEnabled(True)
     if self.source.media == 'file':
         self.source.base_name = get_base_file(self.file) 
         self.source.analysis_frames = cv2.VideoCapture(self.file)
     if self.source.media == 'camera':
         init_analysis_camera(self.main_window)
         print("Setting analysis frames for camera")
         # release camera resource for analysis
         self.source.setup_frames.release()
         self.source.analysis_frames = cv2.VideoCapture(config['camera'])
     # images folder
     directory = 'images/' + self.source.base_name
     create_dir(directory) 
     self.get_video()
     if self.source.media == 'file':
         self.setup.load_video(self.video.id)
     self.background = Background(self.source) 
     self.background.get_db(self.video.id)
     self.source.background = self.background
     self.polygon = Polygon(self.source, self.setup) 
     self.polygon.get_points(self.video.id)
     self.polygon.draw_setup(self.background.frame, self.polygon.points)
     self.source.polygon = self.polygon
     self.play = Play(self.source, self.setup)
     self.play.run_analysis()
     # set location
     self.location.set_location(self.video.address_id)
     # play
     self.click_analysis_play_btn()
	def scrapePlay(self, playLink, playType):
		title = self.strip(playLink.get_text())
		print("PLAY: "+str(title)+" a "+playType)
		play = Play(None, title, playType)
		url = playLink.attrs['href']
		playKey = url.split("/")[0]
		play.urlkey = playKey
		play = self.storePlay(play)

		scenes = self.getPage("http://shakespeare.mit.edu/"+url)
		links = scenes.findAll("a", href=re.compile("^("+playKey+")\.[0-9]\.[0-9]\.(html)"))
		for link in links:
			url = link.attrs["href"]
			urlSplit = url.split(".")
			scene = Scene(None, play, urlSplit[1], urlSplit[2])
			self.getScene(url, scene)
Example #7
0
    def run(self):
        ''' run all patterns in the playbook '''
        plays = []
        matched_tags_all = set()
        unmatched_tags_all = set()

        # loop through all patterns and run them
        self.callbacks.on_start()
        for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs):
            play = Play(self, play_ds, play_basedir)
            matched_tags, unmatched_tags = play.compare_tags(self.only_tags)
            matched_tags_all = matched_tags_all | matched_tags
            unmatched_tags_all = unmatched_tags_all | unmatched_tags

            # if we have matched_tags, the play must be run.
            # if the play contains no tasks, assume we just want to gather facts
            if (len(matched_tags) > 0 or len(play.tasks()) == 0):
                plays.append(play)

        # if the playbook is invoked with --tags that don't exist at all in the playbooks
        # then we need to raise an error so that the user can correct the arguments.
        unknown_tags = set(self.only_tags) - (matched_tags_all | unmatched_tags_all)
        unknown_tags.discard('all')

        if len(unknown_tags) > 0:
            unmatched_tags_all.discard('all')
            msg = 'tag(s) not found in playbook: %s.  possible values: %s'
            unknown = ','.join(sorted(unknown_tags))
            unmatched = ','.join(sorted(unmatched_tags_all))
            raise errors.AnsibleError(msg % (unknown, unmatched))

        for play in plays:
            if not self._run_play(play):
                break

        # summarize the results
        results = {}
        for host in self.stats.processed.keys():
            results[host] = self.stats.summarize(host)
        return results
Example #8
0
 def open(self):
     self.source.base_name = get_base_file(self.file) 
     # background folder
     directory = 'backgrounds/' + self.source.base_name
     create_dir(directory) 
     init_setup_new(self.main_window)
     self.source.setup_frames = cv2.VideoCapture(self.file)
     self.get_data()
     self.populate_setup()
     self.address_window = AddressWindow(self, self.main_window)
     self.polygon = Polygon(self, self.source)
     self.draw_status = False
     self.play = Play(self.source, self)
     self.play.run_setup()
     self.background = Background(self.source)
Example #9
0
 def camera(self):
     print("Camera in setup")
     # background folder
     directory = 'backgrounds/' + self.source.base_name
     create_dir(directory) 
     self.status = True
     init_setup_new(self.main_window)
     self.source.setup_frames = cv2.VideoCapture(config['camera'])
     self.get_data()
     self.populate_setup()
     self.address_window = AddressWindow(self, self.main_window)
     self.polygon = Polygon(self, self.source)
     self.draw_status = False
     self.play = Play(self.source, self)
     self.play.run_setup()
     self.background = Background(self.source)
Example #10
0
class Setup:
    def __init__(self, source):
        self.source = source
        self.files = source.setup_list
        self.main_window = source.main_window
        self.dbs = source.dbs
        self.admin = source.admin
        self.pointer = 0
        self.sentinel = len(self.files)
        self.line_status = False
        self.draw_status = False
        self.status = False 
        self.analysis = None

        # init setup ui
        init_address(self.main_window)

        # enable address button
        self.main_window.setup_address_btn.setEnabled(True)
        
        # signals
        # connect setup save button
        self.main_window.connect(self.main_window.setup_save_btn, \
            SIGNAL("clicked()"), self.save_setup)
        self.main_window.setup_save_btn.setEnabled(True)
        # connect address button
        self.main_window.connect(self.main_window.setup_address_btn, \
            SIGNAL("clicked()"), self.click_address_btn)
        # setup play button
        self.main_window.connect(self.main_window.setup_play_btn, \
            SIGNAL("clicked()"), self.click_setup_play_btn)
        # setup pause button
        self.main_window.connect(self.main_window.setup_pause_btn, \
            SIGNAL("clicked()"), self.click_setup_pause_btn)
        # setup background button
        self.main_window.connect(self.main_window.setup_bg_btn, \
            SIGNAL("clicked()"), self.click_setup_bg_btn)
        # setup reset button
        self.main_window.connect(self.main_window.setup_reset_btn, \
            SIGNAL("clicked()"), self.click_reset_btn)
        # setup draw button
        self.main_window.connect(self.main_window.setup_draw_btn, \
            SIGNAL("clicked()"), self.click_draw_btn)
        # setup line button
        self.main_window.connect(self.main_window.setup_line_btn, \
            SIGNAL("clicked()"), self.click_line_btn)

        # setup frame mousePressEvent overide
        self.main_window.setup_frame.mousePressEvent = \
            self.setup_frame_click

    def get_data(self):
        if self.source.media == "file":
            print("Gathering video properties")
            self.path = self.file
            self.metadata = get_metadata(self.file)
            self.base_name = get_base_name(self.file)
            self.fps = get_fps(self.metadata)
            self.duration = get_duration(self.metadata)
            self.resolution = get_resolution(self.metadata)
            self.format = get_format(self.metadata)
        if self.source.media == "camera":
            self.base_name = self.source.base_name 
            self.path = self.source.path 
            self.metadata = None
            self.fps = None
            self.duration = None
            self.resolution = None
            self.format = None

    def valid_setup(self):
        rv = True
        message = ''
        # address
        if self.address_window.valid_address():
            print("Creating address for video in db")
            self.address_window.create_address()
            self.address = self.address_window.address
        else:
            message = message + "Address is incomplete!\n"
            rv = False
        # background
        if self.background.path is None:
            message = message + "Background image is None!\n"
            rv = False
        # polygon
        if self.polygon.no_of_points <= 3:
            message = message + "Polygon is not yet set!\n"
            rv = False
        if rv is False:
            print(message)
            self.dialog = DialogWindow("Setup", message)
        return rv

    def save_db(self):
        file = self.base_name
        path = self.path
        background = self.background.path
        fps = self.fps
        duration = None
        created_time = None
        admin_id = self.admin.id
        address_id = self.address.id

        video = Video(file, path, background, \
            fps, duration, created_time, admin_id, \
            address_id)
        
        self.video = video 
        print("Creating video in db", video)
        s = self.dbs
        s.add(video)
        s.commit()

        # save polygon after acquiring video 
        self.polygon.save_db()

    def start_analysis(self):
        print("Nothing to setup!")
        self.dialog = DialogWindow("Setup", "Setup is finished!")
        self.status = False
        print("Start analysis here")
        self.analysis = Analysis(self.source, self)
        self.source.analysis = self.analysis

    def save_setup(self):
        print("Clicked save setup button")
        if self.valid_setup():
            self.save_db()
            if self.status == True:
                if self.source.media == 'file':
                    self.sequencer()
                if self.source.media == 'camera':
                   self.start_analysis() 

    def click_address_btn(self):
        self.address_window.ui.show()

    def populate_setup(self):
        self.main_window.name_lbl.setText(self.base_name)
        self.main_window.fps_lbl.setText(self.fps)
        self.main_window.duration_lbl.setText(self.duration)
        self.main_window.resolution_lbl.setText(self.resolution)
        self.main_window.format_lbl.setText(self.format)
        self.main_window.statusbar.showMessage("Path: %s" % self.path)

    def open(self):
        self.source.base_name = get_base_file(self.file) 
        # background folder
        directory = 'backgrounds/' + self.source.base_name
        create_dir(directory) 
        init_setup_new(self.main_window)
        self.source.setup_frames = cv2.VideoCapture(self.file)
        self.get_data()
        self.populate_setup()
        self.address_window = AddressWindow(self, self.main_window)
        self.polygon = Polygon(self, self.source)
        self.draw_status = False
        self.play = Play(self.source, self)
        self.play.run_setup()
        self.background = Background(self.source)

    def sequencer(self):
        init_setup(self.main_window)
        if self.pointer != len(self.files):
            self.status = True
            self.file = self.files[self.pointer]
            self.path = self.file
            self.open()
            self.pointer += 1
        else:
            self.start_analysis()

    def camera(self):
        print("Camera in setup")
        # background folder
        directory = 'backgrounds/' + self.source.base_name
        create_dir(directory) 
        self.status = True
        init_setup_new(self.main_window)
        self.source.setup_frames = cv2.VideoCapture(config['camera'])
        self.get_data()
        self.populate_setup()
        self.address_window = AddressWindow(self, self.main_window)
        self.polygon = Polygon(self, self.source)
        self.draw_status = False
        self.play = Play(self.source, self)
        self.play.run_setup()
        self.background = Background(self.source)

    def click_setup_play_btn(self):
        print("Clicked setup play button!")
        self.play.setup_status = True
        self.play.setup_timer.start()
        self.main_window.setup_pause_btn.setEnabled(True)
        self.main_window.setup_play_btn.setEnabled(False)

    def click_setup_pause_btn(self):
        print("Clicked setup pause button!")
        self.play.setup_status = False 
        self.play.setup_timer.stop()
        self.main_window.setup_pause_btn.setEnabled(False)
        self.main_window.setup_play_btn.setEnabled(True)

    def click_setup_bg_btn(self):
        print("Clicked capture background button")
        self.background.capture_frame()

    def click_draw_btn(self):
        print("Clicked draw button")
        self.line_status = False
        self.draw_status = True
        if self.play.setup_status == False:
            self.play.run_setup_pause()
        self.main_window.setup_draw_btn.setEnabled(False)
        self.main_window.setup_line_btn.setEnabled(True)
        # get area of polygon
        area = self.polygon.compute_area()
        self.main_window.area_lbl.setText(str(self.polygon.area))

    def click_line_btn(self):
        print("Clicked line button")
        self.line_status = True 
        self.draw_status = False 
        if self.play.setup_status == False:
            self.play.run_setup_pause()
        self.main_window.setup_line_btn.setEnabled(False)
        self.main_window.setup_draw_btn.setEnabled(True)
        self.main_window.area_lbl.setText("") 

    def click_reset_btn(self):
        print("Clicked reset button")
        self.polygon.reset()
        if self.play.setup_status == False:
            self.play.run_setup_reset()
        self.main_window.setup_reset_btn.setEnabled(False)
        self.main_window.setup_line_btn.setEnabled(False)
        self.main_window.setup_draw_btn.setEnabled(False)
        self.line_status = False 
        self.draw_status = False

    def setup_frame_click(self, event):
        if self.play.setup_status == True:
            print("Pause the source before assigning coordinates")
        else:
            print("Clicked setup frame") 
            x = event.pos().x()
            y = event.pos().y()
            print(x, y)
            print(event.pos())
            point = (x, y)
            self.polygon.append(point)
            self.polygon.get_no_points()
            if self.polygon.no_of_points > 0:
                self.main_window.setup_reset_btn.setEnabled(True)
            if self.polygon.no_of_points > 1:
                self.line_status = True
            if self.polygon.no_of_points > 2:
                self.main_window.setup_draw_btn.setEnabled(True)
            self.play.run_setup_pause()

    def get_video(self):
        return self.video

    def load_video(self, video_id):
        load = False
        s = self.dbs
        result = s.query(Video).filter(Video.id == video_id)
        if result.count() == 1:
            video = result.first() 
            load = True
        elif result.count() > 1:
            print("Found more than 1 match in database!")
        else:
            print("No match found in database!")
        if load == True: 
            self.path = video.path
            self.base_name = video.name 
            self.fps = str(video.fps) 
            self.duration = video.duration
            # address
            self.address_window = AddressWindow(self, self.main_window)
            self.address_window.get_address(video.address_id)
            # polygon
            self.polygon = Polygon(self, self.source)
            self.polygon.get_points(video.id)
            self.polygon.compute_area()
            area = self.polygon.area
            self.main_window.area_lbl.setText(str(abs(area)))
            self.metadata = get_metadata(self.path)
            self.duration = get_duration(self.metadata)
            self.resolution = get_resolution(self.metadata)
            self.format = get_format(self.metadata)
            # load in setup
            self.populate_setup()
Example #11
0
    def __init__(self):
        """Whole project is run from this constructor
        """

        # +++++++++++++++ Init +++++++++++++++ #

        self.keep_run = 0  # used in run for daemon loop, reset by SIGTERM

        self.log = Log(self)
        self.settings = Settings(self)
        self.led = LED(self)
        self.dbhandle = DBHandle(self)
        self.mixer = AlsaMixer(self)
        self.usb = UsbManager(self)
        self.rfcomm = RFCommServer(self)
        self.cmd = EvalCmd(self)
        self.listmngr = PlayListManager(self)
        self.play = Play(self)
        self.lirc = LircThread(self)
        self.buttons = Buttons(self)
        self.keep_run = 1
        self.ret_code = 0  # return code to command line (10 = shutdown)

        self.led.reset_leds()

        # invoke arg parser and parse config or create new config if not found
        self.settings.parse()

        # check if we can load database, create otherwise
        self.dbhandle.dbconnect()

        # restore alsa mixer settings
        self.mixer.restore_mixer()

        # load connected usb before bluetooth
        self.usb.check_new_usb()

        # initialize sound mixer
        self.play.init_mixer()

        # load latest playlist from database
        self.listmngr.load_active_playlist()

        # open cmd fifo to read commands
        self.cmd.open_fifo()

        # fire up bluetooth service
        self.rfcomm.start_server_thread()

        # start lirc thread
        self.lirc.start()

        # fire up one thread per each button
        self.buttons.start()

        # +++++++++++++++ Daemoninze +++++++++++++++ #

        self.check_pidfile()
        self.daemonize()
        self.create_pidfile()

        self.led.show_init_done()

        # +++++++++++++++ Daemon loop +++++++++++++++ #

        self.run()

        # +++++++++++++++ Finalize +++++++++++++++ #

        self.listmngr.save_active()
        self.led.cleanup()
        self.delete_pidfile()
	def initUI(self):
		self.setWindowIcon(QtGui.QIcon('logo.png'))
		self.vr = VoiceRec()
		self.pl = Play()
		self.vrThread = QThread()
		self.plThread = QThread()
		self.vr.moveToThread(self.vrThread)
		self.pl.moveToThread(self.plThread)

		self.figure = plt.figure(1)
		self.canvas = FigureCanvas(self.figure)
		self.toolbar = NavigationToolbar(self.canvas, self)
		self.centralwidget = QtGui.QWidget(self)
		self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
		self.verticalLayout.addWidget(self.toolbar)
		self.verticalLayout.addWidget(self.canvas)
		self.centralwidget.setGeometry(10,10,825,330)

		openFile = QtGui.QAction(QtGui.QIcon('open.png'), '&Open', self)
		openFile.setShortcut('Ctrl+O')
		openFile.setStatusTip('Open new File')
		openFile.triggered.connect(self.showDialogOpen)

		chUser = QtGui.QAction('&Change Speaker', self)
		chUser.setStatusTip('Change Speaker')
		chUser.triggered.connect(self.changeUser)

		exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
		exitAction.setShortcut('Ctrl+Q')
		exitAction.setStatusTip('Exit application')
		exitAction.triggered.connect(self.closeEvent)

		utf_8 = QtGui.QAction('&UTF-8', self)
		utf_8.setStatusTip('utf-8')
		utf_8.triggered.connect(self.encodeUTF8)

		utf_16 = QtGui.QAction('&UTF-16', self)
		utf_16.setStatusTip('utf-16')
		utf_16.triggered.connect(self.encodeUTF16)

		Ascii = QtGui.QAction('&ASCII', self)
		Ascii.setStatusTip('ascii')
		Ascii.triggered.connect(self.encodeASCII)

		about = QtGui.QAction('&About', self)
		about.setStatusTip('More About Voice Recorder')
		about.triggered.connect(self.showAbout)

		self.textEdit = QtGui.QTextEdit(self)
		self.textEdit.setGeometry(10,360,825,104)
		self.textEdit.setStyleSheet("QTextEdit {font-size: 14pt}")
		self.textEdit.setText("Please Open a File...")
		self.textEdit.setReadOnly(True)

		self.Open = QtGui.QPushButton('Open', self)
		self.Open.move(10,480)
		self.Open.clicked.connect(self.showDialogOpen)

		self.Record = QtGui.QPushButton('Record', self)
		self.Record.move(155,480)
		self.Record.setEnabled(False)
		self.Record.clicked.connect(self.record)

		self.Stop = QtGui.QPushButton('Stop', self)
		self.Stop.move(300,480)
		self.Stop.setEnabled(False)
		self.Stop.clicked.connect(self.stop)

		self.Play = QtGui.QPushButton('Play', self)
		self.Play.move(445,480)
		self.Play.setEnabled(False)
		self.Play.clicked.connect(self.play)

		self.Back = QtGui.QPushButton('Back', self)
		self.Back.move(590,480)
		self.Back.setEnabled(False)
		self.Back.clicked.connect(self.showBack)

		self.Next = QtGui.QPushButton('Next', self)
		self.Next.move(735,480)
		self.Next.setEnabled(False)
		self.Next.clicked.connect(self.showNext)

		menubar = self.menuBar()
		fileMenu = menubar.addMenu('&File')
		fileMenu.addAction(openFile)
		fileMenu.addAction(chUser)
		fileMenu.addAction(exitAction)
		encodeMenu = menubar.addMenu('&Encoding')
		encodeMenu.addAction(Ascii)
		encodeMenu.addAction(utf_8)
		encodeMenu.addAction(utf_16)
		helpMenu = menubar.addMenu('&Help')
		helpMenu.addAction(about)

		self.setGeometry(200,200, 845, 550)
		self.setFixedSize(845 , 550)
		self.setWindowTitle('Akshar Voice Recorder')
		self.user = User(self)
Example #13
0
class PyBlaster:
    """Daemon for PiBlaster project"""

    def __init__(self):
        """Whole project is run from this constructor
        """

        # +++++++++++++++ Init +++++++++++++++ #

        self.keep_run = 0  # used in run for daemon loop, reset by SIGTERM

        self.log = Log(self)
        self.settings = Settings(self)
        self.led = LED(self)
        self.dbhandle = DBHandle(self)
        self.mixer = AlsaMixer(self)
        self.usb = UsbManager(self)
        self.rfcomm = RFCommServer(self)
        self.cmd = EvalCmd(self)
        self.listmngr = PlayListManager(self)
        self.play = Play(self)
        self.lirc = LircThread(self)
        self.buttons = Buttons(self)
        self.keep_run = 1
        self.ret_code = 0  # return code to command line (10 = shutdown)

        self.led.reset_leds()

        # invoke arg parser and parse config or create new config if not found
        self.settings.parse()

        # check if we can load database, create otherwise
        self.dbhandle.dbconnect()

        # restore alsa mixer settings
        self.mixer.restore_mixer()

        # load connected usb before bluetooth
        self.usb.check_new_usb()

        # initialize sound mixer
        self.play.init_mixer()

        # load latest playlist from database
        self.listmngr.load_active_playlist()

        # open cmd fifo to read commands
        self.cmd.open_fifo()

        # fire up bluetooth service
        self.rfcomm.start_server_thread()

        # start lirc thread
        self.lirc.start()

        # fire up one thread per each button
        self.buttons.start()

        # +++++++++++++++ Daemoninze +++++++++++++++ #

        self.check_pidfile()
        self.daemonize()
        self.create_pidfile()

        self.led.show_init_done()

        # +++++++++++++++ Daemon loop +++++++++++++++ #

        self.run()

        # +++++++++++++++ Finalize +++++++++++++++ #

        self.listmngr.save_active()
        self.led.cleanup()
        self.delete_pidfile()

    def run(self):
        """Daemon loop"""

        # Expensive operations like new usb drive check
        # should not be run every loop run.
        poll_count = 0

        # -e flag is set, run only init and exit directly.
        self.keep_run = 0 if self.settings.exitafterinit else 1

        reset_poll_count = self.settings.keep_alive_count * 30 * 4

        # # # # # # DAEMON LOOP ENTRY # # # # # #

        while self.keep_run:

            poll_count += 1

            # Check cmd fifo for new commands.
            if poll_count % 10 == 0:
                # each 300 ms is enough
                self.cmd.read_fifo()

            # Check button events
            if self.buttons.has_button_events():
                self.buttons.read_buttons()

            # Check bluetooth channel for new messages/connections.
            self.rfcomm.check_incomming_commands()

            # Check if lirc thread has command in queue
            if self.lirc.queue_not_empty():
                ircmd = self.lirc.read_command()
                if ircmd is not None:
                    self.cmd.evalcmd(ircmd, "lirc")

            # Check if song has ended
            if poll_count % 4 == 0:
                # every 120 ms
                self.play.check_pygame_events()

            time.sleep(self.settings.polltime / 1000.)  # 30ms default in
                                                        # config

            if poll_count % self.settings.keep_alive_count == 0:
                self.led.set_led_green(1)

            if (poll_count - self.settings.flash_count) % \
                    self.settings.keep_alive_count == 0:
                self.led.set_led_green(0)

            # Check for new USB drives.
            if poll_count % 30 == 0:
                # If new usb device found, new usbdev instance will be created,
                # including dir and mp3 entries.
                # If usb device got lost, all its entries will be removed.
                # To check every ~900ms is enough
                self.usb.check_new_usb()

            # Multiple of all poll counts reached:
            # may reset poll count at reset_poll_count.
            if poll_count >= reset_poll_count:
                poll_count = 0

            # end daemon loop #

        # # # # # # DAEMON LOOP EXIT # # # # # #

        # join remaining threads
        self.mixer.save_mixer()
        self.lirc.join()
        self.buttons.join()
        self.rfcomm.join()

        self.log.write(log.MESSAGE, "---- closed regularly ----")

    # end run() #

    def daemonize(self):
        """Fork process and disable print in log object"""

        signal.signal(signal.SIGTERM, self.term_handler)
        signal.signal(signal.SIGINT, self.term_handler)

        if not self.settings.daemonize:
            self.log.init_log()
            return

        self.log.write(log.DEBUG1, "daemonizing")

        try:
            pid = os.fork()
        except OSError:
            self.log.write(log.EMERGENCY, "Failed to fork daemon")
            raise

        if pid == 0:
            os.setsid()
            try:
                pid = os.fork()
            except OSError:
                self.log.write(log.EMERGENCY, "Failed to fork daemon")
                raise

            if pid == 0:
                os.chdir("/tmp")
                os.umask(0)
            else:
                os._exit(0)
        else:
            os._exit(0)

        self.settings.is_daemonized = True
        self.log.init_log()
        self.log.write(log.MESSAGE, "daemonized.")

    # end daemonize() #

    def term_handler(self, *args):
        """ Signal handler to stop daemon loop"""
        self.keep_run = 0

    def check_pidfile(self):
        """Check if daemon already running, throw if pid file found"""

        if os.path.exists(self.settings.pidfile):
            self.log.write(log.EMERGENCY, "Found pid file for pyblaster, "
                           "another process running?")
            raise Exception("pid file found")

    def create_pidfile(self):
        """Write getpid() to file after daemonize()"""

        try:
            fpid = open(self.settings.pidfile, "w")
        except IOError:
            self.log.write(log.EMERGENCY, "failed to create pidfile %s" %
                           self.settings.pidfile)
            raise

        fpid.write("%s\n" % os.getpid())

    def delete_pidfile(self):
        """Try to remove pid file after daemon should exit"""

        if os.path.exists(self.settings.pidfile):
            try:
                os.remove(self.settings.pidfile)
            except OSError:
                self.log.write(log.EMERGENCY, "failed to remove pidfile %s" %
                               self.settings.pidfile)
                raise

    def kill_other_pyblaster(self):
        """Check if pid found in pid file and try to kill this (old) process"""

        if not os.path.exists(self.settings.pidfile):
            return

        try:
            f = open(self.settings.pidfile, "r")
        except IOError:
            self.log.write(log.EMERGENCY, "failed to read pidfile %s" %
                           self.settings.pidfile)
            raise

        pid = int(f.readline().strip())

        print("Trying to kill old process with pid %s..." % pid)

        try:
            os.kill(pid, signal.SIGTERM)
        except OSError:
            self.log.write(log.EMERGENCY,
                           "failed to kill process with pid %s" % pid)
            raise

        exit(0)
Example #14
0
from play import LoadWords, Play

# this will play the game.

if __name__ == '__main__':
    load_word = LoadWords()
    # get the word list.
    word_list = load_word.load_words()
    play = Play()
    # human plays the game.
    play.play_game(word_list)
Example #15
0
class Analysis:
    def __init__(self, source, setup):
        self.dbs = source.dbs
        self.main_window = source.main_window
        self.source = source
        self.setup = setup
        if self.source.media == 'file':
            self.files = source.files
        self.main_window.tabs.setCurrentIndex(1)
        self.pointer = 0
        self.location = Location(self.main_window, self.source)

        # signals
        # play button
        self.main_window.connect(self.main_window.analysis_play_btn, \
            SIGNAL("clicked()"), self.click_analysis_play_btn)
        # pause button
        self.main_window.connect(self.main_window.analysis_pause_btn, \
            SIGNAL("clicked()"), self.click_analysis_pause_btn)
        # stop button
        self.main_window.connect(self.main_window.analysis_stop_btn, \
            SIGNAL("clicked()"), self.click_analysis_stop_btn)
        # next button
        self.main_window.connect(self.main_window.analysis_next_btn, \
            SIGNAL("clicked()"), self.click_analysis_next_btn)
        # debug speed button
        self.main_window.connect(self.main_window.speed_btn, \
            SIGNAL("clicked()"), self.click_speed_btn)
        # debug road status button
        self.main_window.connect(self.main_window.road_status_btn, \
            SIGNAL("clicked()"), self.click_road_status_btn)
        # haar collect button
        self.main_window.connect(self.main_window.haar_capture_btn, \
            SIGNAL("clicked()"), self.click_haar_capture_btn)
        # haar classifier button
        self.main_window.connect(self.main_window.classifier_btn, \
            SIGNAL("clicked()"), self.click_classifier_btn)

        # choose media source
        if self.source.media == 'file':
            self.sequencer()
        if self.source.media == 'camera':
            self.open()

    def release_media(self):
        print("Releasing media")
        if self.source.setup_frames != None:
            self.source.setup_frames.release()
        self.source.analysis_frames.release()

    def sequencer(self):
        init_setup(self.main_window)
        if self.pointer != len(self.files):
            self.file = self.files[self.pointer]
            self.open()
            self.pointer += 1
        else:
            print("Nothing to analyse!")
            self.dialog = DialogWindow("Analysis", "Analysis is finished!")
            init_main(self.main_window)
            # self.main_window.tabs.hide()
            self.play.analysis_timer.stop()
            self.release_media()

    def open(self):
        init_analysis(self.main_window)
        self.main_window.analysis_next_btn.setEnabled(True)
        if self.source.media == 'file':
            self.source.base_name = get_base_file(self.file) 
            self.source.analysis_frames = cv2.VideoCapture(self.file)
        if self.source.media == 'camera':
            init_analysis_camera(self.main_window)
            print("Setting analysis frames for camera")
            # release camera resource for analysis
            self.source.setup_frames.release()
            self.source.analysis_frames = cv2.VideoCapture(config['camera'])
        # images folder
        directory = 'images/' + self.source.base_name
        create_dir(directory) 
        self.get_video()
        if self.source.media == 'file':
            self.setup.load_video(self.video.id)
        self.background = Background(self.source) 
        self.background.get_db(self.video.id)
        self.source.background = self.background
        self.polygon = Polygon(self.source, self.setup) 
        self.polygon.get_points(self.video.id)
        self.polygon.draw_setup(self.background.frame, self.polygon.points)
        self.source.polygon = self.polygon
        self.play = Play(self.source, self.setup)
        self.play.run_analysis()
        # set location
        self.location.set_location(self.video.address_id)
        # play
        self.click_analysis_play_btn()

    def click_analysis_play_btn(self):
        print("Clicked play button in analysis!")
        self.play.analysis_status = True
        self.play.analysis_timer.start()
        self.main_window.analysis_pause_btn.setEnabled(True)
        self.main_window.analysis_play_btn.setEnabled(False)
        self.play.timer.status = True
        self.play.timer.start()

    def click_analysis_pause_btn(self):
        print("Clicked pause button in analysis!")
        self.play.analysis_status = False 
        self.play.analysis_timer.stop()
        self.main_window.analysis_pause_btn.setEnabled(False)
        self.main_window.analysis_play_btn.setEnabled(True)

    def click_analysis_stop_btn(self):
        print("Clicked stop button in analysis!")
        self.play.analysis_status = False 
        self.play.analysis_timer.stop()
        stop_analysis(self.main_window)
        init_setup(self.main_window)
        # release media source
        self.release_media()
        self.main_window.tabs.setCurrentIndex(0)

    def get_video(self):
        if self.source.media == 'file':
            self.base_name = get_base_name(self.file)
        if self.source.media == 'camera':
            self.base_name = self.source.base_name
        s = self.dbs
        result = s.query(Video).filter(Video.name == self.base_name)
        if result.count() == 0:
            print("No video record found in database")
            self.video = None
        elif result.count() == 1:
            print("Found 1 record in database")
            self.video = result.first()
            self.source.video = self.video
            print(self.video)
            # get location of source
            self.source.location = s.query(Address).filter(Address.id \
                == self.video.address_id).first()
            print("Location of source is ", self.source.location)
        else:
            self.video = None

    def click_analysis_next_btn(self):
        print("Clicked next button in analysis!")
        self.sequencer()

    def click_speed_btn(self):
        if self.play.speed_debug == True:
            self.play.speed_debug = False
        else:
            self.play.speed_debug = True
        self.main_window.speed_debug_lbl.setText(\
            str(self.play.speed_debug))
        print("Speed debug status:", self.play.speed_debug)

    def click_road_status_btn(self):
        if self.play.road_status_debug == True:
            self.play.road_status_debug = False
        else:
            self.play.road_status_debug = True
        self.main_window.road_status_debug_lbl.setText(\
            str(self.play.road_status_debug))
        print("Speed debug status:", self.play.road_status_debug)

    def click_haar_capture_btn(self):
        print("Clicked haar capture button")
        if self.play.haar_collect == True:
            self.play.haar_collect = False
        else:
            self.play.haar_collect = True
        self.main_window.haar_capture_lbl.setText(\
            str(self.play.haar_collect))
        print("Haar collect status:", self.play.haar_collect)

    def click_classifier_btn(self):
        print("Clicked haar classifier button")
        if self.play.haar_activate == True:
            self.play.haar_activate = False
        else:
            self.play.haar_activate = True
        self.main_window.classifier_lbl.setText(\
            str(self.play.haar_activate))
        print("Haar activate status:", self.play.haar_activate)
class Gui(QtGui.QMainWindow,QtGui.QWidget):

	def __init__(self):
		super(Gui, self).__init__()
		self.initUI()
		self.line=0
		self.text=[]
		self.decode=""
		self.fname="output"
		self.rec=0

	def initUI(self):
		self.setWindowIcon(QtGui.QIcon('logo.png'))
		self.vr = VoiceRec()
		self.pl = Play()
		self.spectro()
		self.vrThread = QThread()
		self.plThread = QThread()
		self.vr.moveToThread(self.vrThread)
		self.pl.moveToThread(self.plThread)

		openFile = QtGui.QAction(QtGui.QIcon('open.png'), '&Open', self)
		openFile.setShortcut('Ctrl+O')
		openFile.setStatusTip('Open new File')
		openFile.triggered.connect(self.showDialogOpen)

		exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
		exitAction.setShortcut('Ctrl+Q')
		exitAction.setStatusTip('Exit application')
		exitAction.triggered.connect(self.closeEvent)

		utf_8 = QtGui.QAction('&UTF-8', self)
		utf_8.setStatusTip('utf-8')
		utf_8.triggered.connect(self.encodeUTF8)

		utf_16 = QtGui.QAction('&UTF-16', self)
		utf_16.setStatusTip('utf-16')
		utf_16.triggered.connect(self.encodeUTF16)

		about = QtGui.QAction('&About', self)
		about.setStatusTip('More About Voice Recorder')
		about.triggered.connect(self.showAbout)

		self.textEdit = QtGui.QTextEdit(self)
		self.textEdit.setGeometry(10,30,825,104)
		self.textEdit.setStyleSheet("QTextEdit {font-size: 14pt}")
		self.textEdit.setText("Please Open a File...")
		self.textEdit.setReadOnly(True)

		self.Open = QtGui.QPushButton('Open', self)
		self.Open.move(10,160)
		self.Open.clicked.connect(self.showDialogOpen)

		self.Record = QtGui.QPushButton('Record', self)
		self.Record.move(155,160)
		self.Record.clicked.connect(self.record)

		self.Stop = QtGui.QPushButton('Stop', self)
		self.Stop.move(300,160)
		self.Stop.clicked.connect(self.stop)

		self.Play = QtGui.QPushButton('Play', self)
		self.Play.move(445,160)
		self.Play.clicked.connect(self.play)

		self.Back = QtGui.QPushButton('Back', self)
		self.Back.move(590,160)
		self.Back.clicked.connect(self.showBack)

		self.Next = QtGui.QPushButton('Next', self)
		self.Next.move(735,160)
		self.Next.clicked.connect(self.showNext)

		menubar = self.menuBar()
		fileMenu = menubar.addMenu('&File')
		fileMenu.addAction(openFile)
		fileMenu.addAction(exitAction)
		encodeMenu = menubar.addMenu('&Encoding')
		encodeMenu.addAction(utf_8)
		encodeMenu.addAction(utf_16)
		helpMenu = menubar.addMenu('&Help')
		helpMenu.addAction(about)

		self.setGeometry(200,200, 845, 550)
		self.setFixedSize(845 , 550)
		self.setWindowTitle('Voice Recorder')
		#self.setWindowIcon(QtGui.QIcon('logo.png'))
		self.show()

	def showDialogOpen(self):
		self.statusBar().showMessage('Open a File')
		self.fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file','/home')
		if(self.fname!=""):
			del self.text[:]
			f = open(self.fname, 'r')
			for lines in f:
				self.text.append(lines)
			f.close
			if(self.decode!=""):
				self.textEdit.setText(self.text[self.line].decode(self.decode))
			else:
				self.textEdit.setText(self.text[self.line].decode('utf-8'))
			self.line=0
		self.statusBar().showMessage('')

	def showNext(self):
		self.line+=1
		if(len(self.text)>self.line):
			if(self.decode!=""):
				self.textEdit.setText(self.text[self.line].decode(self.decode))
			else:
				self.textEdit.setText(self.text[self.line].decode('utf-8'))
		else:
			self.showDialogOpen()

	def showBack(self):
		self.line-=1
		if(len(self.text)>=self.line and self.line>=0):
			if(self.decode!=""):
				self.textEdit.setText(self.text[self.line].decode(self.decode))
			else:
				self.textEdit.setText(self.text[self.line].decode('utf-8'))
		else:
			self.showDialogOpen()

	def showAbout(self):
		self.popup1=About()
		self.popup1.exec_()

	def encodeUTF8(self):
		self.decode="utf-8"

	def encodeUTF16(self):
		self.decode="utf-16"

	def record(self):
		self.statusBar().showMessage('Recording')
		self.rec=1
		self.Record.setEnabled(False)
		self.Open.setEnabled(False)
		self.Play.setEnabled(False)
		self.Next.setEnabled(False)
		self.Back.setEnabled(False)
		self.vrThread.start()
		self.vr.record(self.fname, self.line)

	def stop(self):
		self.statusBar().showMessage('')
		if self.rec == 1:
			self.vr.stop()
			self.vrThread.exit()
			self.vrThread.wait()
			self.vrThread.quit()
		elif self.rec == 2:
			self.pl.stop()
			self.plThread.exit()
			self.plThread.wait()
			self.plThread.quit()
		self.Record.setEnabled(True)
		self.Open.setEnabled(True)
		self.Play.setEnabled(True)
		self.Next.setEnabled(True)
		self.Back.setEnabled(True)
		self.rec=0

	def play(self):
		self.statusBar().showMessage('Playing')
		self.rec=2
		self.Record.setEnabled(False)
		self.Open.setEnabled(False)
		self.Play.setEnabled(False)
		self.Next.setEnabled(False)
		self.Back.setEnabled(False)
		self.plThread.start()
		self.pl.play(self.fname, self.line, self)

	def spectro(self):
		self.centralwidget = QtGui.QWidget(self)
		self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
		self.qwtPlot = Qwt.QwtPlot(self.centralwidget)
		self.verticalLayout.addWidget(self.qwtPlot)
		self.centralwidget.setGeometry(10,200,825,330)

		self.c=Qwt.QwtPlotCurve()  
		self.c.attach(self.qwtPlot)

		self.qwtPlot.setAxisScale(self.qwtPlot.yLeft, 0, 32000)

		self.timer = QTimer()
		self.timer.start(1.0)

		self.connect(self.timer, SIGNAL('timeout()'), self.plotSomething) 

		self.SR=SwhRecorder()
		self.SR.setup()
		self.SR.continuousStart()

	def plotSomething(self):
		if self.SR.newAudio==False: 
			return
		xs,ys=self.SR.fft()
		self.c.setData(xs,ys)
		self.qwtPlot.replot()
		self.SR.newAudio=False

	def closeEvent(self, event):
		self.SR.close()
		QtGui.qApp.quit()
	def initUI(self):
		self.setWindowIcon(QtGui.QIcon('logo.png'))
		self.vr = VoiceRec()
		self.pl = Play()
		self.spectro()
		self.vrThread = QThread()
		self.plThread = QThread()
		self.vr.moveToThread(self.vrThread)
		self.pl.moveToThread(self.plThread)

		openFile = QtGui.QAction(QtGui.QIcon('open.png'), '&Open', self)
		openFile.setShortcut('Ctrl+O')
		openFile.setStatusTip('Open new File')
		openFile.triggered.connect(self.showDialogOpen)

		exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
		exitAction.setShortcut('Ctrl+Q')
		exitAction.setStatusTip('Exit application')
		exitAction.triggered.connect(self.closeEvent)

		utf_8 = QtGui.QAction('&UTF-8', self)
		utf_8.setStatusTip('utf-8')
		utf_8.triggered.connect(self.encodeUTF8)

		utf_16 = QtGui.QAction('&UTF-16', self)
		utf_16.setStatusTip('utf-16')
		utf_16.triggered.connect(self.encodeUTF16)

		about = QtGui.QAction('&About', self)
		about.setStatusTip('More About Voice Recorder')
		about.triggered.connect(self.showAbout)

		self.textEdit = QtGui.QTextEdit(self)
		self.textEdit.setGeometry(10,30,825,104)
		self.textEdit.setStyleSheet("QTextEdit {font-size: 14pt}")
		self.textEdit.setText("Please Open a File...")
		self.textEdit.setReadOnly(True)

		self.Open = QtGui.QPushButton('Open', self)
		self.Open.move(10,160)
		self.Open.clicked.connect(self.showDialogOpen)

		self.Record = QtGui.QPushButton('Record', self)
		self.Record.move(155,160)
		self.Record.clicked.connect(self.record)

		self.Stop = QtGui.QPushButton('Stop', self)
		self.Stop.move(300,160)
		self.Stop.clicked.connect(self.stop)

		self.Play = QtGui.QPushButton('Play', self)
		self.Play.move(445,160)
		self.Play.clicked.connect(self.play)

		self.Back = QtGui.QPushButton('Back', self)
		self.Back.move(590,160)
		self.Back.clicked.connect(self.showBack)

		self.Next = QtGui.QPushButton('Next', self)
		self.Next.move(735,160)
		self.Next.clicked.connect(self.showNext)

		menubar = self.menuBar()
		fileMenu = menubar.addMenu('&File')
		fileMenu.addAction(openFile)
		fileMenu.addAction(exitAction)
		encodeMenu = menubar.addMenu('&Encoding')
		encodeMenu.addAction(utf_8)
		encodeMenu.addAction(utf_16)
		helpMenu = menubar.addMenu('&Help')
		helpMenu.addAction(about)

		self.setGeometry(200,200, 845, 550)
		self.setFixedSize(845 , 550)
		self.setWindowTitle('Voice Recorder')
		#self.setWindowIcon(QtGui.QIcon('logo.png'))
		self.show()
class Gui(QtGui.QMainWindow,QtGui.QWidget):

	def __init__(self):
		super(Gui, self).__init__()
		self.speaker = ""
		self.directory = ""
		self.type = ""
		self.line=0
		self.text=[]
		self.decode=""
		self.fname="output"
		self.rec=0
		self.initUI()
		self.file = ""

	def initUI(self):
		self.setWindowIcon(QtGui.QIcon('logo.png'))
		self.vr = VoiceRec()
		self.pl = Play()
		self.vrThread = QThread()
		self.plThread = QThread()
		self.vr.moveToThread(self.vrThread)
		self.pl.moveToThread(self.plThread)

		self.figure = plt.figure(1)
		self.canvas = FigureCanvas(self.figure)
		self.toolbar = NavigationToolbar(self.canvas, self)
		self.centralwidget = QtGui.QWidget(self)
		self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
		self.verticalLayout.addWidget(self.toolbar)
		self.verticalLayout.addWidget(self.canvas)
		self.centralwidget.setGeometry(10,10,825,330)

		openFile = QtGui.QAction(QtGui.QIcon('open.png'), '&Open', self)
		openFile.setShortcut('Ctrl+O')
		openFile.setStatusTip('Open new File')
		openFile.triggered.connect(self.showDialogOpen)

		chUser = QtGui.QAction('&Change Speaker', self)
		chUser.setStatusTip('Change Speaker')
		chUser.triggered.connect(self.changeUser)

		exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
		exitAction.setShortcut('Ctrl+Q')
		exitAction.setStatusTip('Exit application')
		exitAction.triggered.connect(self.closeEvent)

		utf_8 = QtGui.QAction('&UTF-8', self)
		utf_8.setStatusTip('utf-8')
		utf_8.triggered.connect(self.encodeUTF8)

		utf_16 = QtGui.QAction('&UTF-16', self)
		utf_16.setStatusTip('utf-16')
		utf_16.triggered.connect(self.encodeUTF16)

		Ascii = QtGui.QAction('&ASCII', self)
		Ascii.setStatusTip('ascii')
		Ascii.triggered.connect(self.encodeASCII)

		about = QtGui.QAction('&About', self)
		about.setStatusTip('More About Voice Recorder')
		about.triggered.connect(self.showAbout)

		self.textEdit = QtGui.QTextEdit(self)
		self.textEdit.setGeometry(10,360,825,104)
		self.textEdit.setStyleSheet("QTextEdit {font-size: 14pt}")
		self.textEdit.setText("Please Open a File...")
		self.textEdit.setReadOnly(True)

		self.Open = QtGui.QPushButton('Open', self)
		self.Open.move(10,480)
		self.Open.clicked.connect(self.showDialogOpen)

		self.Record = QtGui.QPushButton('Record', self)
		self.Record.move(155,480)
		self.Record.setEnabled(False)
		self.Record.clicked.connect(self.record)

		self.Stop = QtGui.QPushButton('Stop', self)
		self.Stop.move(300,480)
		self.Stop.setEnabled(False)
		self.Stop.clicked.connect(self.stop)

		self.Play = QtGui.QPushButton('Play', self)
		self.Play.move(445,480)
		self.Play.setEnabled(False)
		self.Play.clicked.connect(self.play)

		self.Back = QtGui.QPushButton('Back', self)
		self.Back.move(590,480)
		self.Back.setEnabled(False)
		self.Back.clicked.connect(self.showBack)

		self.Next = QtGui.QPushButton('Next', self)
		self.Next.move(735,480)
		self.Next.setEnabled(False)
		self.Next.clicked.connect(self.showNext)

		menubar = self.menuBar()
		fileMenu = menubar.addMenu('&File')
		fileMenu.addAction(openFile)
		fileMenu.addAction(chUser)
		fileMenu.addAction(exitAction)
		encodeMenu = menubar.addMenu('&Encoding')
		encodeMenu.addAction(Ascii)
		encodeMenu.addAction(utf_8)
		encodeMenu.addAction(utf_16)
		helpMenu = menubar.addMenu('&Help')
		helpMenu.addAction(about)

		self.setGeometry(200,200, 845, 550)
		self.setFixedSize(845 , 550)
		self.setWindowTitle('Akshar Voice Recorder')
		self.user = User(self)

	def showDialogOpen(self):
		plt.clf()
		self.canvas.draw()
		self.statusBar().showMessage('Open a File')
		self.fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file')
		if(self.fname!=""):
			self.Record.setEnabled(True)
			self.Play.setEnabled(True)
			self.Next.setEnabled(True)
			self.Back.setEnabled(True)
			self.directory=str(self.file)+"/"+str(self.speaker)+"_"+str(self.type)+"_"+str(self.fname).split("/")[-1]
			if not os.path.exists(self.directory):
				os.makedirs(self.directory)
			del self.text[:]
			f = open(self.fname, 'r')
			for lines in f:
				self.text.append(lines)
			f.close
			if(self.decode!=""):
				self.textEdit.setText(self.text[self.line].decode(self.decode))
			else:
				self.textEdit.setText(self.text[self.line].decode('ascii'))
			self.line=0
		else:
			self.Record.setEnabled(False)
			self.Play.setEnabled(False)
			self.Next.setEnabled(False)
			self.Back.setEnabled(False)
		self.statusBar().showMessage('')

	def showNext(self):
		plt.clf()
		self.canvas.draw()
		self.line+=1
		if(len(self.text)>self.line):
			if(self.decode!=""):
				self.textEdit.setText(self.text[self.line].decode(self.decode))
			else:
				self.textEdit.setText(self.text[self.line].decode('utf-8'))
		else:
			self.showDialogOpen()

	def showBack(self):
		plt.clf()
		self.canvas.draw()
		self.line-=1
		if(len(self.text)>=self.line and self.line>=0):
			if(self.decode!=""):
				self.textEdit.setText(self.text[self.line].decode(self.decode))
			else:
				self.textEdit.setText(self.text[self.line].decode('utf-8'))
		else:
			self.showDialogOpen()

	def showAbout(self):
		self.popup1=About()
		self.popup1.exec_()

	def encodeUTF8(self):
		self.decode="utf-8"

	def encodeUTF16(self):
		self.decode="utf-16"

	def encodeASCII(self):
		self.decode="ascii"

	def changeUser(self):
		self.user.__init__(self)

	def record(self):
		plt.clf()
		self.canvas.draw()
		self.statusBar().showMessage('Recording')
		self.rec=1
		self.Record.setEnabled(False)
		self.Stop.setEnabled(True)
		self.Open.setEnabled(False)
		self.Play.setEnabled(False)
		self.Next.setEnabled(False)
		self.Back.setEnabled(False)
		self.vrThread.start()
		self.vr.record(self.directory, self.text[self.line].split(")")[0], self)

	def stop(self):
		self.statusBar().showMessage('')
		if self.rec == 1:
			self.vr.stop()
			self.vrThread.exit()
			self.vrThread.wait()
			self.vrThread.quit()
		elif self.rec == 2:
			self.pl.stop()
			self.plThread.exit()
			self.plThread.wait()
			self.plThread.quit()
		self.Record.setEnabled(True)
		self.Open.setEnabled(True)
		self.Play.setEnabled(True)
		self.Next.setEnabled(True)
		self.Back.setEnabled(True)
		self.rec=0

	def play(self):
		self.statusBar().showMessage('Playing')
		self.rec=2
		self.Record.setEnabled(False)
		self.Stop.setEnabled(True)
		self.Open.setEnabled(False)
		self.Play.setEnabled(False)
		self.Next.setEnabled(False)
		self.Back.setEnabled(False)
		self.plThread.start()
		self.pl.play(self.text[self.line].split(")")[0], self)
Example #19
0
        self.rating_run_outside_off = determine_off_rating(1,5,1,3)
        self.rating_run_outside_def = determine_def_rating(3,5,1,1)
        self.rating_pass_short_off = determine_off_rating(4,2,3,1) 
        self.rating_pass_short_def = determine_def_rating(1,5,3,1) 
        self.rating_pass_medium_off = determine_off_rating(4,0,4,2)
        self.rating_pass_medium_def = determine_def_rating(2,2,4,2)
        self.rating_pass_long_off = determine_off_rating(4,0,3,3) 
        self.rating_pass_long_def = determine_def_rating(3,1,3,3) 
        self.rating_special_teams_off = self.rating_sp
        self.rating_special_teams_def = ceil((self.rating_sp - 60) / 4)

        ##Testing
        print self.city, self.nickname, self.rating_run_inside_off,self.rating_run_inside_def,self.rating_run_outside_off,self.rating_run_outside_def,self.rating_pass_short_off,self.rating_pass_short_def,self.rating_pass_medium_off,self.rating_pass_medium_def,self.rating_pass_long_off,self.rating_pass_long_def,self.rating_special_teams_off,self.rating_special_teams_def
        ##Testing
        

def get_next_team_id():
    global next_team_id
    team_id = next_team_id
    next_team_id += 1
    return team_id

team1 = Team("Austin","Easy")
team2 = Team("Chicago","Grown Men")

for i in range (100):
    p = Play()
    p.onside_kickoff(team1,team2,3)

#print team1.id,team1.city,team1.nickname,team1.rating_qb,team1.rating_rb,team1.rating_wr,team1.rating_ol,team1.rating_dl,team1.rating_lb,team1.rating_cb,team1.rating_s,team1.rating_sp
#print team2.id,team2.city,team2.nickname,team2.rating_qb,team2.rating_rb,team2.rating_wr,team2.rating_ol,team2.rating_dl,team2.rating_lb,team2.rating_cb,team2.rating_s,team2.rating_sp