def demo_mode():
    try:
        points = ImageRandomiser(IMAGE_NAME, IMAGE_SIZE, IMAGE_SIZE, PIXEL_SIZE, CAMERA)
        
        demo.run(args.time, points, DISPLAY, KEYBOARD)
        
    except Exception as e:
        LOGGER.info(str(e))
        KEYBOARD.close()
        DISPLAY.stop()
Ejemplo n.º 2
0
    def bibi(self):
        url = "https://passport.bilibili.com/login"
        self.browser.get(url)
        xpath = '//*[@id="login-username"]'
        self.wait.until(EC.presence_of_element_located(
            (By.XPATH, xpath))).send_keys('Python')
        xpath = '//*[@id="login-passwd"]'
        self.wait.until(EC.presence_of_element_located(
            (By.XPATH, xpath))).send_keys('Python')
        xpath = '//*[@id="geetest-wrap"]/div/div[5]/a[1]'
        self.click(xpath)

        xpath = '/html/body/div[2]/div[2]/div[6]/div/div/div[2]/div[1]/div/div[2]/img'
        logo = self.wait.until(
            EC.presence_of_element_located((By.XPATH, xpath)))
        f = logo.get_attribute('src')
        if f:
            res = requests.get(f)
            res = res.content
            with open(f"bilbil.jpg", 'wb') as f:
                f.write(res)
        res = demo.run("bilbil.jpg")
        plan = demo.to_selenium(res)

        # xpath = "/html/body/div[2]/div[2]/div[6]/div/div/div[2]/div[1]/div/div[2]"
        # logo = self.wait.until(EC.presence_of_element_located(
        #     (By.XPATH, xpath)))
        print(logo.location)
        print(logo.size)
        X, Y = logo.location['x'], logo.location['y']
        print(X, Y)
        lan_x = 259 / 334
        lan_y = 290 / 384
        #     print(X+x, Y+y)
        time.sleep(1)
        # ActionChains(self.browser).move_by_offset(200, 0).click().perform()
        for p in plan:
            x, y = p['place']
            print(x, y)
            ActionChains(self.browser).move_by_offset(
                X - 40 + x * lan_x, Y + y * lan_y).click().perform()
            ActionChains(self.browser).move_by_offset(
                -(X - 40 + x * lan_x),
                -(Y + y * lan_y)).perform()  # 将鼠标位置恢复到移动前
            time.sleep(1)

        xpath = "/html/body/div[2]/div[2]/div[6]/div/div/div[3]/a/div"
        self.click(xpath)
        print(res)
        print(plan)
        time.sleep(1000)
Ejemplo n.º 3
0
                        "metric (object appearance).",
                        type=float,
                        default=0.2)
    parser.add_argument("--nn_budget",
                        help="Maximum size of the appearance descriptors "
                        "gallery. If None, no budget is enforced.",
                        type=int,
                        default=100)
    return parser.parse_args()


if __name__ == "__main__":
    args = parse_args()

    os.makedirs(args.output_dir, exist_ok=True)
    sequences = os.listdir(args.mot_dir)
    for sequence in sequences:
        print("Running sequence %s" % sequence)
        sequence_dir = os.path.join(args.mot_dir, sequence)
        detection_file = os.path.join(args.detection_dir, "%s.npy" % sequence)
        output_file = os.path.join(args.output_dir, "%s.txt" % sequence)
        demo.run(sequence_dir,
                 detection_file,
                 output_file,
                 args.min_confidence,
                 args.nms_max_overlap,
                 args.min_detection_height,
                 args.max_cosine_distance,
                 args.nn_budget,
                 display=False)
Ejemplo n.º 4
0
from demo import run, get_args

parser = argparse.ArgumentParser()
parser.add_argument('--gpuid', type=int, default=0,
                    help="Negative value means cpu-only")
parser.add_argument('--loss', type=str, default='CCL', choices=['KCL', 'CCL'],
                    help="The clustering criteria. Default: CCL")
parser.add_argument('--num_cluster', type=int, default=100,
                    help="The number of cluster. Default: 100 (unknown number of cluster)")
config = parser.parse_args()


print('STEP1: Train SPN on Omniglot background set')
if not os.path.isfile('outputs/Omniglot_VGGS_DPS.model.pth'):
    argv = '--loss DPS --dataset Omniglot --model_type vgg --model_name VGGS --schedule 30 40 --epochs 50'.split(' ')
    run(get_args(argv))
print('STEP1: Done')


omniglot_evaluation_alphabet_set = [
    'Angelic',
    'Atemayar_Qelisayer',
    'Atlantean',
    'Aurek',
    'Avesta',
    'Ge_ez',
    'Glagolitic',
    'Gurmukhi',
    'Kannada',
    'Keble',
    'Malayalam',
Ejemplo n.º 5
0
import demo

demo.run()

exit()
Ejemplo n.º 6
0
                        type=str,
                        default='train',
                        help='train, test or demo.')
    parser.add_argument('--demo_path',
                        type=str,
                        default='demo/inputs/1',
                        help='Please specify the demo path.')
    return parser.parse_args()


if __name__ == '__main__':
    args = parse_args()
    cfg = CONFIG(args.config)
    cfg.update_config(args.__dict__)
    from net_utils.utils import initiate_environment
    initiate_environment(cfg.config)
    '''Configuration'''
    cfg.log_string('Loading configurations.')
    cfg.log_string(cfg.config)
    cfg.write_config()
    '''Run'''
    if cfg.config['mode'] == 'train':
        import train
        train.run(cfg)
    if cfg.config['mode'] == 'test':
        import test
        test.run(cfg)
    if cfg.config['mode'] == 'demo':
        import demo
        demo.run(cfg)
Ejemplo n.º 7
0
			self.emit("click", date_time)
			
	def get_click_count(self):
		return self.invoke("getClickCount")
			
class SimpleDemo(demo.DemoApp):
	
	def __init__(self):
		self._web_widget = SimpleWebWidget()
		self._web_widget.connect("click", self._on_click)
		
	def get_title(self):
		return "Simple Demo"
    
	def get_description(self):
		return """Demonstrates message passing between Python and JavaScript in an embedded HTML page.

Click events are logged in the console."""
	
	def get_content(self):
		return self._web_widget
		
	def _on_click(self, widget, date_time):
		print "clicked: ", date_time
		print "click count: " , self._web_widget.get_click_count()

if __name__ == '__main__':
	demo = SimpleDemo()
	demo.build_ui()
	demo.run()
Ejemplo n.º 8
0
def main():
    try:
        import demo
        demo.run()
    except ImportError:
        print("Warning: demo.py not found.")
Ejemplo n.º 9
0
import demo 

if __name__ == '__main__':
   
   #min_learning_rate = 0.0001
   demo.run(0.0001)
   
   for i in range(55, 100):
      demo.run(float(i)/1000000)
   #new_err = (demo.run(0.0001)
   #if (float(new_err) < float(min_err)):
      #min_err = new_err
      #min_learning_rate = i 

   #print(min_err)
   #print(min_learning_rate)

   """finding the min here is difficult due to float limitations. 
      Python Decimals may be too slow."""
Ejemplo n.º 10
0
        if frame_number % 80 == 0:
            if i == 1:
                name = "img/" + str(frame_number) + '.jpg'
                cv2.imwrite(name, face)
            else:
                name = "img/" + str(frame_number) + '_' + str(i) + '.jpg'
                cv2.imwrite(name, face)
            i += 1

            score = 0
            index = 0
            for n in range(len(known_faces_name)):
                path = "face/" + known_faces_name[n] + ".png"
                score_new = demo.run(appid=APPID,
                                     apisecret=APISECRET,
                                     apikey=APIKEY,
                                     img1_path=path,
                                     img2_path=name)
                if (score < score_new) and (score_new > 0.5):
                    score = score_new
                    index = n
            face_names.append(known_faces_name[index])
        else:
            face_names.append("")

    for n in range(len(known_faces_name)):
        if frame_number <= frame_last_number[n]:
            frame = cv2ImgAddText(frame, known_faces_name[n], frame_left[n],
                                  frame_top[n], (255, 0, 0), 50)
            frame = cv2ImgAddText(frame, contents[n], frame_left[n],
                                  frame_top[n] + 100, (255, 0, 0), 25)
Ejemplo n.º 11
0
 def __init__(self):
     
   save_files = session.query(Player).filter_by(id=1).all()
   # save_files = []
   while True:  
     print("[N]ew Game")
     if save_files:
       print("[C]ontinue")
     else:
       cprint("[C]ontinue", "grey")
     choice = input()
     if choice.lower() == 'n':
       for each in views.intro:
         print (each)
         print(views.cont)
         input()
       print("Do-do-do-do-da-dodo")
       print("Not Golden Sun")
       new = Player(gender = views.gender(self),
                   name = views.name(),
                   level = 10,
                   hp = 50,
                   max_hp = 50,
                   mp = 9,
                   max_mp = 9,
                   strength = 50,
                   fortitude = 50,
                   agility = 45,
                   skill_points = 0,
                   gold = 20,
                   poisoned = False
       )
       skills = []
       print("*TEST*"*5, "\nWhat skills do you want?")
       for each in session.query(Skill).all():
         while True:
           # output = each.name, str(index)
           print(each.name, "\ny/n")
           choice = input()
           if choice == 'y':
             skills.append(each)
             break
           elif choice == 'n':
             break
       break
     elif choice.lower() == 'c':
       if save_files:
         for index, each in enumerate(save_files, start=1):
           print(index, each.name)
         choice = input()
         if int(choice) in range(1, len(save_files)+1):
           new = save_files[int(choice)-1]
           skills = [session.query(Skill).filter_by(id = each.skill_id).all()[0] for each in session.query(SkillOwnership).filter_by(player_id = new.id).all()]
           break
       else:
         print("You have no saved games.")
         input(views.cont)
     else:
       print(views.try_again)
       input(views.cont)
   choice = demo.run(new, skills)
   if choice == 'battle':
     battle.Battle(new, skills).encounter()
Ejemplo n.º 12
0
def detect(queue, lock, config):
    url = 'http://10.75.4.42:10595/v1/malfunction/addMalfunctionRecord'
    malfunction_topic = 'bao_malfunction_steel'
    malfunction_status = False
    malfunction_count = 0
    malfunction_count_threshold = 40
    normal_count = 0
    normal_count_threshold = 30
    video_duration = 5  # record for 5 seconds
    video_timer = 0
    video_num = 0
    record_on = False

    # record timer for test purpose
    record_timer = 0

    millis = int(round(time.time() * 1000))
    servers = config.get('kafka', 'servers')
    producer = KafkaProducer(bootstrap_servers=servers)
    fourcc = cv2.VideoWriter_fourcc(*'avc1')

    while True:
        start = time.time()
        # lock.acquire()
        if queue.full():
            logging.error('detect queue full')
        if not queue.empty():
            data = queue.get()
            frame = data['data']
            # lock.release()
            print('detecting the image')
            _, processed_frame, warning = demo.run(frame)

            if warning:
                malfunction_count += 1
                # report malfunction if count > threshold
                if malfunction_count > malfunction_count_threshold:
                    if not malfunction_status:
                        print('malfunction recognized')
                        malfunction_status = True
                        current_time = int(time.time())
                        # set a gap period of 15 minuets for recording to avoid too much testing data
                        if current_time - record_timer > 15 * 60:
                            print('recording start')
                            record_timer = current_time
                            record_on = True
                            file_name = 'malfunction_{0}.mp4'.format(video_num)
                            video_num += 1
                            out = cv2.VideoWriter('video/' + file_name, fourcc,
                                                  25, (1024, 576))
                    else:
                        # send the malfunction image stream to kafka
                        _, img_encode = cv2.imencode('.jpg', processed_frame)
                        img_base64 = base64.b64encode(img_encode)
                        msg_dict = {
                            "type": "卡钢",
                            "position": data['position'],
                            "timestamp": millis,
                            "data": str(img_base64, 'ASCII'),
                            "complete": 1,
                            "desc": data['position'] + "卡钢"
                        }
                        message = json.dumps(msg_dict).encode('utf-8')
                        try:
                            producer.send(malfunction_topic, message)
                        except KafkaError as e:
                            logging.error(e)
            elif malfunction_status:
                # check malfunction stop
                if normal_count < normal_count_threshold:
                    # keep malfunction status and send the malfunction image stream to kafka
                    _, img_encode = cv2.imencode('.jpg', processed_frame)
                    img_base64 = base64.b64encode(img_encode)
                    msg_dict = {
                        "type": "卡钢",
                        "position": data['position'],
                        "timestamp": millis,
                        "data": str(img_base64, 'ASCII'),
                        "complete": 1,
                        "desc": data['position'] + "卡钢"
                    }
                    message = json.dumps(msg_dict).encode('utf-8')
                    try:
                        producer.send(malfunction_topic, message)
                    except KafkaError as e:
                        logging.error(e)
                    normal_count += 1
                else:
                    # malfunction stop, send the last frame to kafka with complete flag of 0
                    _, img_encode = cv2.imencode('.jpg', processed_frame)
                    img_base64 = base64.b64encode(img_encode)
                    msg_dict = {
                        "type": "卡钢",
                        "position": data['position'],
                        "timestamp": millis,
                        "data": str(img_base64, 'ASCII'),
                        "complete": 0,
                        "desc": data['position'] + "卡钢"
                    }
                    # msg_dict['data'] = str(img_base64, 'ASCII')
                    message = json.dumps(msg_dict).encode('utf-8')
                    try:
                        for i in range(
                                2
                        ):  # Simply send two times for frontend to stop the malfunction image
                            producer.send(malfunction_topic, message)
                    except KafkaError as e:
                        logging.error(e)
                    malfunction_status = False
                    # print('{0} frames in this malfunction'.format(malfunction_count))
                    malfunction_count = 0
                    print('malfunction stop')
                    normal_count = 0
            else:
                malfunction_count = 0
            # Record the malfunction video for a period of time
            if record_on and video_timer < video_duration * 25:
                out.write(processed_frame)
                video_timer += 1
            elif video_timer >= video_duration * 25:
                # recording finished
                print('recording stop')
                video_timer = 0
                out.release()
                record_on = False
                # save the malfunction record
                params = {
                    "cameraId": 1,
                    "desc": data['position'] + "卡钢",
                    "eventTime": millis,
                    "position": data['position'],
                    "type": "卡钢",
                    "videoPath": file_name
                }
                r = requests.put(url, json=params)
                response = json.loads(r.content)
                if response['success']:
                    print('Record saved')
                else:
                    print('Record save failed')
        # else:
        #     lock.release()
        end = time.time()
        print('time for detecting {0}'.format(end - start))