Exemple #1
0
 def video_width(self):
     '''Returns the width of the video in pixels'''
     try:
         result =  int(str2float(self.info["Video"]["Width"]) if \
                       str2float(self.info["Video"]["Width"]) < WIDTH else WIDTH)
         return result
     except KeyError:
         raise VideoWidthError
Exemple #2
0
 def video_height(self):
     '''Returns the height of the video in pixels'''
     try:
         result =  int(str2float(self.info["Video"]["Height"]) if \
                       str2float(self.info["Video"]["Height"]) < HEIGHT else HEIGHT)
         return result
     except KeyError:
         raise VideoHeightError
Exemple #3
0
 def test__format_item(self):
     s = "1{0}/201{0};orgao{0};situacao{0};nome{0};cpf{0};cargo{0};1{0},{0};100{0},{0};200{0},3{0};vinculo{0};matricula{0}"
     itens = [s.format(i) for i in range(1, 5)]
     for item in itens:
         a, b, c, d, e, f, g, h, i, j, k = item.split(";")
         g = str2float(g)
         h = str2float(h)
         i = str2float(i)
         resp = (a, b, c, d, e, f, g, h, i, j, k)
         self.assertEqual(_format_item(item), resp)
Exemple #4
0
 def more_than_sd(self):
     try:
         if str2float(self.info["Video"]["Width"]) > WIDTH:
             return True
         elif str2float(self.info["Video"]["Height"]) > HEIGHT:
             return True
         elif str2float(self._bitrate()) > max(BITRATES):
             return True
         return False
     except KeyError:
         print("Media info for {} is invalid, cannot compare to SD".format(
             self.file_path))
         return False
Exemple #5
0
def correct_assignment_demo(answers):
    if len(answers) != 3:
        raise InvalidAnswersFormat

    return [
        str2int(answers[0]) == 9487,
        abs(str2float(answers[1]) - 9487.9487) <= 0.01,
        answers[2] == "Joe 487",
    ]
def get_vec():
    """ Loads sentence vectors from file.

    :return: list of sentence vectors for train, dev, and test
    """
    vec_list = list()
    for vec_file in [CONFIG.train_sent_vec, CONFIG.dev_sent_vec, CONFIG.test_sent_vec]:
        vec = read_msgpack(vec_file)
        vec_list.append(str2float(vec))
    return vec_list
Exemple #7
0
 def pick_bitrate(bitrate):
     '''Picks the best possible bitrate out of the BITRATES array'''
     br = int(str2float(next(b for b in bitrate.split('/') \
              if 'Unknown' not in b)))
     if br in BITRATES:
         return br
     elif br < min(BITRATES):
         return min(BITRATES)
     elif br > max(BITRATES):
         return max(BITRATES)
     else:
         return min(BITRATES, key=lambda x: abs(x - br))
 def process(self, url, params):
     if url == '/THERMOSTAT/':
         return self._get_state()
     elif url == '/THERMOSTAT/SET/':
         try:
             if 'IS_HEATER' in params:
                 self._config['is_heater'] = utils.str2bool(
                     params['IS_HEATER'])
             if 'DESIRED_TEMPERATURE' in params:
                 desired_temperature = utils.str2float(
                     params['DESIRED_TEMPERATURE'])
                 if 0.0 <= desired_temperature and desired_temperature <= 100.0:
                     self._config[
                         'desired_temperature'] = desired_temperature
             if 'HYSTERESIS' in params:
                 hysteresis = utils.str2float(params['HYSTERESIS'])
                 if 0.1 <= hysteresis and hysteresis <= 5.0:
                     self._config['hysteresis'] = hysteresis
         except Exception as e:
             utils.printWarn('THERMOSTAT', 'exception during process')
             utils.printWarn('THERMOSTAT', e)
         utils.writeJson(_CONFIG_FILE, self._config)
         return self._get_state()
     return None
Exemple #9
0
        def update_db(self, date_s=None, date_e=None):
            if date_s is None:
                date_s = self.date_e + datetime.timedelta(
                    days=1) if self.date_e is not None else datetime.date(
                        1900, 1, 1)
            if date_e is None:
                date_e = datetime.date.today()
            if date_s > date_e:
                date_s = date_e

            date_start = date_s.strftime('%d/%m/%Y')
            date_end = date_e.strftime('%d/%m/%Y')

            db_filename = self.__get_dbfilename()
            url = r'http://www.cbr.ru/scripts/XML_dynamic.asp'

            if self.trace:
                print(
                    f'History: Запрашиваем историю для {self.curr_id} {date_start}:{date_end} у сервера ЦБ'
                )

            params = {
                'VAL_NM_RQ': self.curr_id,
                'date_req1': date_start,
                'date_req2': date_end
            }

            try:
                resp = requests.get(url, params)
            except:
                if self.trace:
                    print('History: Ошибка обращения к серверу ЦБ')
                return

            if self.trace:
                print(f'History: responce code is {resp.status_code}')

            if resp.status_code == 200 and len(resp.text):

                # with open(db_filename + '.xml', 'w') as xmlfile:
                #    xmlfile.write(resp.text)

                converted = 0
                xml_tree = Xml.fromstring(resp.text)
                xml_tree_len = len(xml_tree)
                for record in xml_tree:
                    nominal = record.find('Value').text
                    nominal = int(
                        nominal) if len(nominal) and nominal.isdigit() else 1
                    value = record.find('Value').text
                    self.db[self.cnv_date(record.attrib['Date']
                                          )] = utils.str2float(value) / nominal
                    converted += 1

                    if self.trace:
                        percent = int(converted / xml_tree_len * 100)
                        utils.pbprint('History:', percent,
                                      f'записей {converted}')

                if converted == 0:  # нет новых данных
                    if self.trace:
                        print('History: Обновления истории нет')
                    self.date_ask = datetime.date.today()  # когда запрашивали
                    with open(
                            db_filename, 'wb'
                    ) as db_file:  # но необходимо обновить дату опроса ЦБ
                        pickle.dump(self.date_ask, db_file)
                        pickle.dump(self.date_s, db_file)
                        pickle.dump(self.date_e, db_file)
                        pickle.dump(self.db, db_file)
                    return resp.status_code

                date_sorted = sorted(self.db.keys())
                if len(date_sorted):
                    if self.trace:
                        print('History: from', date_sorted[0], 'to',
                              date_sorted[-1])
                    self.date_ask = datetime.date.today()  # когда запрашивали
                    self.date_s = date_sorted[0]  # первая дата истории
                    self.date_e = date_sorted[-1]  # последняя дата истории
                    with open(db_filename, 'wb') as db_file:
                        pickle.dump(self.date_ask, db_file)
                        pickle.dump(self.date_s, db_file)
                        pickle.dump(self.date_e, db_file)
                        pickle.dump(self.db, db_file)

                        if self.trace:
                            print(
                                f'History: сохранили историю в файл \'{self.curr_id}.dat\''
                            )

            return resp.status_code
    parser.add_argument('-b',
                        '--bins',
                        required=False,
                        type=int,
                        default=10,
                        help='the number of bins')
    parser.add_argument('-p',
                        '--plot',
                        required=False,
                        action="store_true",
                        help='plot the histogram')
    args = parser.parse_args()

    scores = []
    for line in utils.get_input(args.input):
        score = utils.str2float(line.split()[args.column])
        if score != None:
            scores.append(score)
    lower = np.min(scores)
    upper = np.max(scores)
    magnitude = np.max(np.abs(scores))
    norm_lower = -1
    norm_upper = 1

    if args.lower is not None and args.upper is not None:
        if args.normalize:
            lower = args.lower * magnitude
            upper = args.upper * magnitude
            norm_lower = args.lower
            norm_upper = args.upper
        else:
Exemple #11
0
 def test_str2float(self):
     valor = str2float("12,2")
     self.assertEqual(valor, 12.2)
     valor = str2float("12345678,77")
     self.assertEqual(valor, 12345678.77)
def test():
    print("Loading KNN classifier...")
    with open(TRAINED_KNN_MODEL, 'rb') as f:
        model = pickle.load(f)

    conn = sqlite3.connect(cfg['database'])
    cursor = conn.cursor()

    query = "SELECT * from checkins"
    cursor.execute(query)
    rows = cursor.fetchall()
    counter = Counter([r[0] for r in rows])
    labels = np.load(label_path)
    print("Loading complete")

    acc = {}
    # STEP 2: Using the trained classifier, make predictions for unknown images
    for person in os.listdir(train_dir):
        images = os.listdir(os.path.join(train_dir, person))
        if len(images) == 0:
            continue

        print("Processing {} [{} images] ..".format(person, len(images)))

        if len(images) > 1:
            sorted_images = sorted(
                images,
                key=lambda x: str2float(os.path.basename(x).split('.png')[0]
                                        ))[1:]
        else:
            sorted_images = sorted(
                images,
                key=lambda x: str2float(os.path.basename(x).split('.png')[0]))

        acc[person] = {}
        acc[person]['num_images'] = len(images)
        acc[person]['top1'] = []
        acc[person]['top5'] = []
        acc[person]['num_checkins'] = counter[person]
        acc[person]['distance_top1'] = []
        acc[person]['distance_top5'] = []

        all_predictions = []
        for idx, im in enumerate(sorted_images):
            print("{}/{}".format(idx + 1, len(images)), end='\r', flush=True)
            full_file_path = os.path.join(train_dir, person).replace(
                "/", r"\\") + r"\\" + im
            # X_img = cv2.imread(full_file_path)[:, :, ::-1]
            X_img = face_recognition.load_image_file(full_file_path,
                                                     mode='RGB')
            if len(images) <= 1:
                X_face_locations = face_recognition.face_locations(X_img)
            else:
                h, w = X_img.shape[:2]
                X_face_locations = [[0, w, h, 0]]

            # Find encodings for faces in the test image
            faces_encodings = face_recognition.face_encodings(
                X_img, known_face_locations=X_face_locations)

            # Use the KNN model to find the best matches for the test face
            res = model.kneighbors(faces_encodings, n_neighbors=50)
            all_predictions.append(res)

        batch_size = 10
        num_batches = len(sorted_images) // batch_size
        for i in range(num_batches + 1):
            low = i
            if i + batch_size >= len(sorted_images):
                hi = len(sorted_images)
                low = max(0, hi - batch_size)
            else:
                hi = low + batch_size

            neighbors = {}
            for res in all_predictions[low:hi]:
                dis = res[0][0].tolist()
                nbs = res[1][0].tolist()
                for d, n in zip(dis, nbs):
                    pred = labels[n]
                    if d < face_thresh:
                        if pred not in neighbors:
                            neighbors[pred] = [d]
                        else:
                            neighbors[pred].append(d)

            final_predictions = []
            for p, v in neighbors.items():
                mean_dist = np.mean(v)
                final_predictions.append([p, len(v), mean_dist])

            final_predictions = sorted(final_predictions, key=lambda x: -x[1])

            if person == final_predictions[0][0]:
                acc[person]['top1'].append(1)
                acc[person]['top5'].append(1)
                acc[person]['distance_top1'].append(final_predictions[0][-1])
            elif person in [fp[0] for fp in final_predictions[:5]]:
                acc[person]['top1'].append(0)
                acc[person]['top5'].append(1)
                found = [fp[0] for fp in final_predictions[:5]].index(person)
                acc[person]['distance_top5'].append(
                    final_predictions[found][-1])
            else:
                acc[person]['top1'].append(0)
                acc[person]['top5'].append(0)

        for k in ['top1', 'top5', 'distance_top1', 'distance_top5']:
            if np.sum(acc[person][k]) > 0:
                acc[person][k] = np.mean(acc[person][k])
            else:
                acc[person][k] = 0

        print(person, acc[person])

    with open("evaluation.pkl", 'wb') as f:
        pickle.dump(acc, f, pickle.HIGHEST_PROTOCOL)
Exemple #13
0
def get_eye_angle(code_str):
    angle_list = code_str.split(',')
    float_angle_list = utils.str2float(angle_list)
    angle = utils.detect_outliter(float_angle_list)
    return angle
Exemple #14
0
 def radio(self, ratio):
     "Handler for radio buttons (controls fixed amounts of neg/pos ratio)"
     self.active_button_index = self.radio_labels.index(ratio)
     self.ratio = str2float(ratio)
     self.redraw(ratio=self.ratio, items=('ratio'), comment='from radio')