from data import IsItEnglishTrainDataset, Vocab, Tokenize, TokensToIDs, ToTensor, character_tokenize, RidAttributes
from data import Collate
from torchvision.transforms import Compose
from train import BinaryClassification
from model import CNNForCorruptionClassification
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
from torch.utils.data import DataLoader
import torch

TRAIN_PATH = 'data/train.json'
VALID_PATH = 'data/valid.json'

def train(bsz: int,
          lr: float
          ) -> None:
    vocab = Vocab.construct_from_json_dataset(TRAIN_PATH)
    transform = Compose([
        Tokenize(tokenize_fn = character_tokenize),
        TokensToIDs(vocab = vocab),
        ToTensor(),
        RidAttributes(['original_tokens', 'corrupted_tokens', 'original_ids', 'corrupted_ids'])
    ])
    train_ds = IsItEnglishTrainDataset.from_json(TRAIN_PATH, transform=transform)
    valid_ds = IsItEnglishTrainDataset.from_json(VALID_PATH, transform=transform)
    train_loader = DataLoader(train_ds,
                              batch_size=bsz,
                              shuffle=True,
                              collate_fn=Collate(vocab))
    valid_loader = DataLoader(valid_ds,
                              batch_size=bsz,
                              shuffle=True,
                              collate_fn=Collate(vocab))
    model = CNNForCorruptionClassification(vocab = vocab,
                                           embed_dim = 128,
                                           out_channels = 32,
                                           window_sizes = [4, 8, 16])
    pl_module = BinaryClassification(model=model,
                                     lr=lr)
    trainer = pl.Trainer(log_every_n_steps=1,
                         #gpus=1,
                         max_epochs=10,
                         auto_lr_find='lr',
                         callbacks=[
                             ModelCheckpoint(monitor='valid_acc',
                                                 mode='max')
                         ])
    trainer.fit(pl_module,
                 train_dataloaders=train_loader,
                 val_dataloaders=valid_loader)

if __name__ == '__main__':
    train(bsz=32, lr=1e-2)


import numpy as np

from tf_agents.environments import py_environment
from tf_agents.specs import BoundedArraySpec
from tf_agents.trajectories.time_step import StepType
from tf_agents.trajectories.time_step import TimeStep

class Env2048(py_environment.PyEnvironment):
  """
  """

  def __init__(self, n: int, dims: int, discount=1.0):
    """Initializes Env2048.
    Args:
      rng: size of the grid.
      dims: number of dims.
      discount: Discount for reward.
    """
    super(Env2048, self).__init__()
    self._n = n
    self._dims = dims
    self._discount = np.asarray(discount, dtype=np.float32)
    self._n_news = ((n**self._dims)//2**4)*2
    self._shape = tuple([self._n for i in range(self._dims)])
    self._actions = [(dim, 0) for dim in range(self._dims)] + [(dim, 1) for dim in range(self._dims)]
    self._states = None
    self._total_score = 0

  def action_spec(self):
    return BoundedArraySpec((1,), np.int32, minimum=[0], maximum=[self._dims*2 - 1])

  def observation_spec(self):
    return BoundedArraySpec([self._n for i in range(self._dims)], np.float32, minimum=0., maximum=1.)

  def _reset(self):
    np.random.seed(123)
    self._total_score = 0.
    self._states = np.zeros(self._shape, np.float32)
    self._add_numbers()
    return TimeStep(StepType.FIRST, np.asarray(0.0, dtype=np.float32),
                    self._discount, self._states)

  #def _legal_actions(self, states: np.ndarray):
  #  return list(zip(*np.where(states == 0)))

  def _add_numbers(self):
    idx_zero = np.argwhere((self._states == 0))
    if idx_zero.shape[0] > self._n_news:
      insert_idx = idx_zero[np.argsort(np.random.uniform(size=idx_zero.shape[0]))[:self._n_news], :]
    elif idx_zero.shape[0] > 0 and idx_zero.shape[0] <= self._n_news:
      insert_idx = idx_zero
    else:
      return 1
    np.put(self._states, np.ravel_multi_index(insert_idx.T, self._shape), np.float32(2/2048), mode='raise')
    return 0

  def get_state(self) -> TimeStep:
    return self._current_time_step

  def set_state(self, time_step: TimeStep):
    self._current_time_step = time_step
    self._states = time_step.observation

  def _step(self, action: np.ndarray):
    if self._current_time_step.is_last():
      return self._reset()
    action = self._actions[action[0]]
    score = 0.
    if action[1]:
        it_list = zip(range(self._n-1, 0, -1), range(self._n-2, -1, -1))
    else:
        it_list = zip(range(self._n-1), range(1,self._n))
    for i, next_i in it_list:
      index_base = np.ones(shape=[1 for x in range(self._dims)], dtype=np.int32)
      xi = np.take_along_axis(self._states, index_base*i, axis=action[0])
      xiplus = np.take_along_axis(self._states, index_base*next_i, axis=action[0])
      with np.nditer([xi, xiplus], flags=[], op_flags=[['readwrite'], ['readwrite']]) as it:
        for j, next_j in it:
          if j[...] != 0. and next_j[...] == 0.:
            next_j[...] = j[...]
            j[...] = 0.
          elif j[...] == next_j[...]:
            next_j *= 2.
            j[...] = 0.
            score += next_j[...]
      np.put_along_axis(self._states, index_base*i, xi, axis=action[0])
      np.put_along_axis(self._states, index_base*next_i, xiplus, axis=action[0])
    self._total_score += score
    is_final = self._add_numbers()

    return TimeStep(
        StepType.LAST if is_final else StepType.MID,
        np.asarray(self._total_score, dtype=np.float32) if is_final else np.asarray(0., dtype=np.float32),
        self._discount,
        self._states
    )

    # def show(self, video=None):
    #     n = self.n
    #     block_size = 50

    #     img = (self.board * (np.iinfo(np.uint8).max/np.max(self.board))).astype(np.uint8)
    #     img = Image.fromarray(img, "L")
    #     img_reshaped = img.resize((n * block_size, n * block_size), resample=Image.BOX)
    #     img_reshaped = np.float32(img_reshaped)
    #     text_color = (200, 20, 220)
    #     for i in range(n):
    #         for j in range(n):
    #             block_value = str(int(self.board[i, j]))
    #             cv2.putText(
    #                 img_reshaped,
    #                 block_value,
    #                 (j*block_size+int(block_size / 2)-10*len(block_value), i*block_size+int(block_size/2)+10),
    #                 fontFace=cv2.FONT_HERSHEY_DUPLEX,
    #                 fontScale=1,
    #                 color=text_color
    #             )
    #     if video is not None:
    #         video.write(np.uint8(img_reshaped))
    #     else:
    #         cv2.imshow('2048',img_reshaped)


from JSONdb.DBHelper import DBHelper
import datetime,json,random

DBName = 'database'

STUDENT_TABLE = 'students'
PREDMET_TABLE = 'predmets'
BALL_TABLE = 'balls'
OTDEL_TABLE = 'otdels'
USER_TABLE = 'users'

NAME_FIELD = 'name'
FIRSTNAME_FIELD = 'firstname'
LASTNAME_FIELD = 'lastname'
PATR_FIELD = 'patr'
NUMBER_FIELD = 'number'
OTDEL_ID_FIELD = 'otdel_id'
KOLVO_CHASOV_FIELD = 'kolvo_chasov'
BALL_FIELD = 'ball'
PREDMET_ID_FIELD = 'predmet_id'
STUDENT_ID_FIELD = 'student_id'
DATE_FIELD = 'date'
ID_FIELD = 'id'
EMAIL_FIELD = 'email'
PASSWORD_FIELD = 'password'

def getDate():
    now = datetime.datetime.now()
    return '{0}.{1}.{2} {3}:{4}'.format(now.day,now.month,now.year,now.hour,now.minute)

def createTables(DBName):
    try:
        with open(DBName + ".json", "r", encoding="utf-8") as file:
            json.load(file)
            db = DBHelper(DBName)
    except FileNotFoundError:
        db = DBHelper(DBName)
        db.newTable(STUDENT_TABLE,[FIRSTNAME_FIELD,LASTNAME_FIELD,PATR_FIELD,NUMBER_FIELD,OTDEL_ID_FIELD,DATE_FIELD])
        db.newTable(PREDMET_TABLE,[NAME_FIELD,KOLVO_CHASOV_FIELD,DATE_FIELD])
        db.newTable(OTDEL_TABLE,[NAME_FIELD,DATE_FIELD])
        db.newTable(BALL_TABLE,[BALL_FIELD,PREDMET_ID_FIELD,STUDENT_ID_FIELD,DATE_FIELD])
        db.newTable(USER_TABLE,[EMAIL_FIELD,PASSWORD_FIELD,DATE_FIELD])
    return db

def getStatByPredmet():
    db = createTables(DBName)
    balls = db.select(db.SELECT_TYPE_STANDARD, BALL_TABLE, 0)
    predmets = db.select(db.SELECT_TYPE_STANDARD, PREDMET_TABLE, 0)

    predmet_list = []
    for predmet in predmets:
        count = 0
        summ = 0
        string = ' '
        for ball in balls:
            if predmet != db.IDS and predmet != db.COLUMN_LIST and ball != db.IDS and ball != db.COLUMN_LIST:
                if predmet == balls[ball][PREDMET_ID_FIELD]:
                    count+=1
                    summ+=int(balls[ball][BALL_FIELD])
        try:
            string = '{:.4}'.format(str(summ/count))

            predmet_list.append([string,predmets[predmet][NAME_FIELD]])
        except:pass
    return predmet_list

def getStatByStudent():
    db = createTables(DBName)
    balls = db.select(db.SELECT_TYPE_STANDARD, BALL_TABLE, 0)
    students = db.select(db.SELECT_TYPE_STANDARD, STUDENT_TABLE, 0)

    student_list = []
    for student in students:
        count = 0
        summ = 0
        string = ' '

        for ball in balls:
            if student != db.IDS and students != db.COLUMN_LIST and ball != db.IDS and ball != db.COLUMN_LIST:
                if student == balls[ball][STUDENT_ID_FIELD]:
                    count+=1
                    summ+=int(balls[ball][BALL_FIELD])
        try:
            string = '{:.4}'.format(str(summ/count))

            student_list.append([string,students[student][LASTNAME_FIELD] + ' ' +
                        students[student][FIRSTNAME_FIELD]+ ' ' +
                        students[student][PATR_FIELD]])
        except:
            pass
    return student_list

def autoadd():
    db = DBHelper(DBName)
    for j in range(10):
        num = j + 1
        db.addRow(OTDEL_TABLE, ['Отделение' + str(num), getDate()])
        db.addRow(PREDMET_TABLE, ['Предмет' + str(num), str(random.randint(24, 89)), getDate()])
        db.addRow(STUDENT_TABLE,
                  ['Имя' + str(num),
                   'Фамилия' + str(num),
                   'Отчество' + str(num),
                   str(random.randint(87270000000, 87970000000)),
                   str(random.randint(1, 10)),
                   getDate()])
    for i in range(300):
        db.addRow(BALL_TABLE,[str(random.randint(2, 5)),
                              str(random.randint(1, 10)),
                              str(random.randint(1, 10)),
                              getDate()])
def addInTable(*args):
    db = createTables(DBName)
    db.addRow(args)

def addUser(ColumnListVariables,email):
    db = createTables(DBName)
    #ColumnListVariables.append(getDate())
    id = db.base[USER_TABLE][db.IDS] + 1
    db.base[USER_TABLE][db.IDS] = id
    list = db.base[USER_TABLE][db.COLUMN_LIST]
    column_dict = {}
    for i in range(len(list)):
        column_dict.update(dict([(list[i], ColumnListVariables[i])]))
    column_dict.update([('id', id)])
    di = dict([(email, column_dict)])
    db.base[USER_TABLE].update(di)

    # Update base
    db.CreateOrUpdateBase(db.DBName)


from flask import Flask
from flask_restful import Api, Resource, reqparse

app = Flask(__name__)
api = Api(app)

users = [
    {
        "name": "Nicholas",
        "age": 42,
        "occupation": "Network Engineer"
    },
    {
        "name": "Elvin",
        "age": 32,
        "occupation": "Doctor"
    },
    {
        "name": "Jass",
        "age": 22,
        "occupation": "Web Developer"
    }
]

class User(Resource):
    def get(self, name):
        for user in users:
            if(name == user["name"]):
                return user, 200
        return "User not found", 404

    def post(self, name):
        parser = reqparse.RequestParser()
        parser.add_argument("age")
        parser.add_argument("occupation")
        args = parser.parse_args()

        for user in users:
            if(name == user["name"]):
                return "User with name {} already exists".format(name), 400

        user = {
            "name": name,
            "age": args["age"],
            "occupation": args["occupation"]
        }
        users.append(user)
        return user, 201

    def put(self, name):
        parser = reqparse.RequestParser()
        parser.add_argument("age")
        parser.add_argument("occupation")
        args = parser.parse_args()

        for user in users:
            if(name == user["name"]):
                user["age"] = args["age"]
                user["occupation"] = args["occupation"]
                return user, 200

        user = {
            "name": name,
            "age": args["age"],
            "occupation": args["occupation"]
        }
        users.append(user)
        return user, 201

    def delete(self, name):
        global users
        users = [user for user in users if user["name"] != name]
        return "{} is deleted.".format(name), 200

api.add_resource(User, "/user/<string:name>")

app.run(debug=True)

#2. Accessing APIs using Clients
#    a. Using client Insomnia
#    - Install "Insomnia" client application to send RestAPI calls in chrome. Access it using (chrome://apps/)
#        GET: 127.0.0.1:5000/user/Elvin
#        POST: 127.0.0.1:5000/user/Amit
#        DELETE: 127.0.0.1:5000/user/Amit
#    b. Using firefox web Browser:        http://127.0.0.1:5000/user/Elvin
#    c. Using Python Code    https://www.geeksforgeeks.org/get-post-requests-using-python/


import pytest

from CheckEnvs import check_env
from CheckEnvs import MissingEnvVar

from TransportQuery import TransportQuery

from DataModels import Route
from DataModels import Stop

from main import find_most_stops
from main import find_min_stops
from main import find_stop_intersection

# Speaking of environment variables, my tests don't specify defaults.
# I think best practice would be mocking those.

class TestCheckEnvs:
    """
    Test the Check Envs functionality
    """
    def test_check_env(self):
        # Do we return a value when present?
        assert check_env('BASE_REQUEST_URL') is not None

        # Do we raise an error when not present?
        with pytest.raises(MissingEnvVar):
            check_env('FOO') is not None

class TestTransportQuery:
    def test_get_routes_by_type(self):
        new_transport_query = TransportQuery()
        # Does the function to generate a query return the right string?
        assert new_transport_query.generate_route_by_type_url([0,1]) == "routes?filter[type]=0,1"

        routes = new_transport_query.get_routes_by_type([0,1])
        # Does the function that queries the routes return the right results? This requires API access!
        assert [str(route) for route in routes] == ['Red Line', 'Mattapan Trolley', 'Orange Line', 'Green Line B', 'Green Line C', 'Green Line D', 'Green Line E', 'Blue Line']

    def test_generate_stop_by_routes(self):
        route = Route("Red", "Red Line")

        new_transport_query = TransportQuery()
        # Does the function to generate a query return the right string?
        assert new_transport_query.generate_stop_by_route_url(route) == "stops?fields[stop]=name&filter[route]=Red"

        stops = new_transport_query.get_stops_by_routes([route])
        # Does the query to get stops return the right count as a proxy for working function?
        assert len(stops["Red"]) == 22

class TestMain:

    route_stops = {Route("Red", "Red Line"): [Stop("1", "stop1"), Stop("2", "stop2"), Stop("3", "stop3")],
                        Route("Blue", "Blue Line"): [Stop("2", "stop2"), Stop("4", "stop4")],
                        Route("Green", "Green Line"): [Stop("5", "stop5")]}

    def test_max_stops(self):
        # Do we find the correct max stops route?
        assert find_most_stops(self.route_stops) == ("Red Line", 3)

    def test_min_stops(self):
        # Do we find the correct min stops route?
        assert find_min_stops(self.route_stops) == ("Green Line", 1)

    def test_find_stop_intersection(self):
        # Do we find the intersections?
        intersections = find_stop_intersection(self.route_stops)
        assert intersections[0][0] == "stop2"
        assert intersections[0][1][0].id == "Red"
        assert intersections[0][1][1].id == "Blue"


"""Verificação de idade para votação: Escreva um programa que peça a idade do usuário e
verifique se ele pode votar ou não. Se a idade for igual ou superior a 16 anos, exiba a
mensagem "Você pode votar". Caso contrário, exiba "Você ainda não pode votar"."""

idade = int(input("informe sua idade: "))

if idade >= 16:
    print("Você pode votar")
else:
    print("Você ainda não pode votar")


import math
from matplotlib import pyplot as plt

#This function causes the signal to be decimated by the block size
def block_average(buffer, block_size):
    block_index = 0
    output_buffer = []

    while(block_index < len(buffer)):
        stretch_factor = 0
        sum = 0
        for i in range(block_size):
            if(block_index + block_size >= len(buffer)):
                stretch_factor += 1
                break
            else:
                sum += buffer[block_index + block_size]
                stretch_factor += 1

        #We need to stretch the signal so that it matches the time scale of the input
        #signal
        output_buffer += [sum/len(buffer)] * stretch_factor
        block_index += block_size

    print(output_buffer)
    return output_buffer

##############################################
# Control values for the test signal
##############################################
signal_freq = 60 #Hz
signal_freq_rad = (signal_freq) * 2 * math.pi #60Hz in radians/second
phase = math.pi #seconds
dc_offset = 0.0
amplitude = 2.0

#Used to record signal values
buffer = []
#Used to record sampling time indices
time_buffer = []

#The frequency at which the signal is sampled
sampling_freq = 240 #Hz
sampling_freq_rad = sampling_freq * 2 * math.pi
#Amount of time to capture for in seconds
capture_time = .1 #second

#Use the sampling frequence and amount of time beign captured for
#to determine how long the buffer needs to be
buffer_len = math.ceil(sampling_freq_rad * capture_time)
print(buffer_len)

sample_time = 0
for i in range(buffer_len):
    buffer.append( amplitude * math.sin(signal_freq_rad * sample_time + phase) + dc_offset )
    sample_time += 1/sampling_freq_rad
    time_buffer.append(sample_time)

# plt.scatter(time_buffer, buffer)
plt.plot(time_buffer, buffer)
plt.plot(time_buffer, block_average(buffer, 15))
plt.show()


import contextlib, logging, math, sys
from OpenGL import GL as gl
import glfw

log = logging.getLogger(__name__)

@contextlib.contextmanager
def create_main_window():
    if not glfw.init():
        log.error('failed to initialize GLFW')
        sys.exit(1)
    try:
        log.debug('requiring modern OpenGL without any legacy features')
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

        log.debug('opening window')
        title = 'Tutorial 1: Window'
        window = glfw.create_window(500, 400, title, None, None)
        if not window:
            log.error('failed to open GLFW window.')
            sys.exit(2)
        glfw.make_context_current(window)

        log.debug('set background to dark blue')
        gl.glClearColor(0, 0, 0.4, 0)

        yield window

    finally:
        glfw.terminate()

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    with create_main_window() as window:
        while (
            glfw.get_key(window, glfw.KEY_ESCAPE) != glfw.PRESS and
            not glfw.window_should_close(window)
        ):
            gl.glClear(gl.GL_COLOR_BUFFER_BIT)
            glfw.swap_buffers(window)
            glfw.poll_events()


import threading
import time
import requests

import json
import os
import random

import cv2 as cv
import numpy as np
import scipy.io
import subprocess
from subprocess import Popen
import json

from utils_models import load_model

# Imports
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import cv2
import numpy as np
import csv
import time
from packaging import version

from collections import defaultdict
from io import StringIO
from PIL import Image

# Object detection imports
from utils import label_map_util
from utils import visualization_utils as vis_util
from pathlib import Path

class Process(threading.Thread):
    def __init__(self, video_path, context_id):
        threading.Thread.__init__(self)
        self.context_id = context_id
        self.video_path = video_path
        self.processing_percents = 0
        self.processing_path = 'Images/Processing/' + self.context_id
        self.images_path = self.processing_path + '/cars/{}'
        self.create_dir()
        print("init", context_id)

    def create_dir(self):
        Path(self.processing_path).mkdir(parents=True, exist_ok=True)
        Path(self.processing_path + '/cars/').mkdir(parents=True, exist_ok=True)

    def load_model_init(self):
        model = load_model()
        model.load_weights('models/model.96-0.89.hdf5')

        cars_meta = scipy.io.loadmat('devkit/cars_meta')
        class_names = cars_meta['class_names']  # shape=(1, 196)
        class_names = np.transpose(class_names)

        return model, cars_meta, class_names

    def get_detection_time(self, milliseconds):
        seconds = milliseconds / 1000.0
        return seconds

    def create_detections(self, results):
        objects_detection_format = []

        for result in results:
            objects_detection_format.append({
                "ContextId": self.context_id,
                "DetectionType": 0,
                "DetectionTime": result["frame_number"],
                "Description": "car detection",
                "Accuracy": float(result["prob"]),
                "Color": result["detection_car"][0],
                "Manufacturer": result["label"],
                "LicensePlate": result["license_car"]
            })

        response = requests.post('https://detections-api20210802233301.azurewebsites.net/Detections/CreateCars', json=objects_detection_format, verify=True)

        print("created cars on detection api: " + str(response.json()))

        return response.json()

    def detect_license_car(self, img_path):
        command = '''docker run -it --rm -v $(pwd):/data:ro openalpr/openalpr  -j -c eu ''' + img_path
        process = Popen(command,shell=True,stdout=subprocess.PIPE)
        result = process.communicate()
        a,b = result

        return json.loads(a)

    def write_detections_locally(self, responses, results):
        for index, response in enumerate(responses):
            img = results[index]["img"]
            detection_id = response["id"]
            path = self.images_path.format(detection_id) + '.png'
            print("path to save: " + str(path))
            cv2.imwrite(path.format(detection_id), img)

    def model_detect_car(self, car_to_detect, model, cars_meta, class_names):
        img_width, img_height = 224, 224

        results = []

        for car in car_to_detect:
            image_name = car["countercars"]
            print(image_name)
            filename = os.path.join(self.processing_path, str(image_name) + '.jpg')
            print('Start processing image: {}'.format(filename))
            try:
                bgr_img = cv.imread(filename)
                bgr_img = cv.resize(bgr_img, (img_width, img_height), cv.INTER_CUBIC)
                rgb_img = cv.cvtColor(bgr_img, cv.COLOR_BGR2RGB)
                rgb_img = np.expand_dims(rgb_img, 0)
                preds = model.predict(rgb_img)
                #license_car = self.detect_license_car(filename)
                license_plate = "N/A"
                # if license_car["results"]:
                #     license_plate = license_car["results"][0]["plate"]
                #     print("plate: " + str(license_plate))
                #     print("data: " + str(license_car["results"][0]))
                prob = np.max(preds)
                class_id = np.argmax(preds)
                results.append({'label': class_names[class_id][0][0], 'prob': '{:.4}'.format(prob), 'picture name': image_name, 'frame_number': car["detection_time"], 'detection_car': car["type"], 'license_car': license_plate, 'img': bgr_img})
                #text = ('Predict: {}, prob: {}'.format(class_names[class_id][0][0], prob))
                #cv.imwrite('Images/{}_out.png'.format(image_name), bgr_img)
                #cv2.imwrite(self.processing_path + "/" + str(i) + '.jpg', crop_img)

                print("successfully")
            except Exception as e:
                print(str(e))

        print(results)
        print("finished round of detetctions")

        responses = self.create_detections(results)

        self.write_detections_locally(responses, results)

        print("send it to the detection service")
        #K.clear_session()

    def crop_objects(self, width, height, image_np, output_dict, i):
        image = {}
        image["status"] = False

        global ymin, ymax, xmin, xmax
        #width, height = image.size

        #Coordinates of detected objects
        ymin = int(output_dict['detection_boxes'][0][0]*height)
        xmin = int(output_dict['detection_boxes'][0][1]*width)
        ymax = int(output_dict['detection_boxes'][0][2]*height)
        xmax = int(output_dict['detection_boxes'][0][3]*width)
        crop_img = image_np[ymin:ymax, xmin:xmax]

        # 1. Only crop objects that are detected with an accuracy above 50%,
        # images
        # with objects below 50% will be filled with zeros (black image)
        # This is something I need in my program
        # 2. Only crop the object with the highest score (Object Zero)

        if output_dict['detection_scores'][0] < 0.8:
            return image

        #print(crop_img.shape)

        if crop_img.shape[1] > 0 and crop_img.shape[0] > 0:
            #Save cropped object into image
            cv2.imwrite(self.processing_path + "/" + str(i) + '.jpg', crop_img)

        image["status"] = True
        image["crop_img"] = crop_img

        return image

    def print_length_video(self, cap):
        print("processing video: ")
        print(str(self.video_path))

         # print the length
        fps = cap.get(cv2.CAP_PROP_FPS)      # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
        frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        self.frames_in_video = frame_count
        duration = frame_count/fps

        print('fps = ' + str(fps))
        print('number of frames = ' + str(frame_count))
        print('duration (S) = ' + str(duration))
        minutes = int(duration/60)
        seconds = duration%60
        print('duration (M:S) = ' + str(minutes) + ':' + str(seconds))

    def calc_processing_percents(self, video_capture):

        # get next frame number out of all the frames for video
        next_frame_no = video_capture.get(cv2.CAP_PROP_POS_FRAMES)
        # get total number of frames in the video
        total_frames = video_capture.get(cv2.CAP_PROP_FRAME_COUNT)

        complete = round(next_frame_no/total_frames, 4)

        self.processing_percents = format(complete * 90, ".2f")

        print(self.processing_percents, "%")

    def object_detection_function(self, source_video, command):
        # input video
        cap = cv2.VideoCapture(self.video_path)

        #print info about video length
        self.print_length_video(cap)

        # Variables
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        fps = int(cap.get(cv2.CAP_PROP_FPS))

        # By default I use an "SSD with Mobilenet" model here. See the detection model zoo (https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md) for a list of other models that can be run out-of-the-box with varying speeds and accuracies.
        # What model to download.
        MODEL_NAME = 'ssd_mobilenet_v1_coco_2018_01_28'
        MODEL_FILE = MODEL_NAME + '.tar.gz'
        DOWNLOAD_BASE = \
            'http://download.tensorflow.org/models/object_detection/'

        # Path to frozen detection graph. This is the actual model that is used for the object detection.
        PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'

        # List of the strings that is used to add correct label for each box.
        PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')

        NUM_CLASSES = 90

        # Download Model
        # uncomment if you have not download the model yet
        # Load a (frozen) Tensorflow model into memory.
        detection_graph = tf.Graph()
        with detection_graph.as_default():
            od_graph_def = tf.compat.v1.GraphDef() # use this line to run it with TensorFlow version 2.x
            with tf.compat.v2.io.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: # use this line to run it with TensorFlow version 2.x
                serialized_graph = fid.read()
                od_graph_def.ParseFromString(serialized_graph)
                tf.import_graph_def(od_graph_def, name='')

        # Loading label map
        # Label maps map indices to category names, so that when our convolution network predicts 5, we know that this corresponds to airplane. Here I use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine
        label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
        categories = label_map_util.convert_label_map_to_categories(label_map,
                max_num_classes=NUM_CLASSES, use_display_name=True)
        category_index = label_map_util.create_category_index(categories)

        count_frames = 0
        car_to_detect = []
        counter_cars = 0

        if(command=="imwrite"):
            fourcc = cv2.VideoWriter_fourcc(*'XVID')
            output_movie = cv2.VideoWriter(source_video.split(".")[0]+'_output.avi', fourcc, fps, (width, height))

        with detection_graph.as_default():
            # with tf.Session(graph=detection_graph) as sess:
            with tf.compat.v1.Session(graph=detection_graph) as sess: # use this line to run it with TensorFlow version 2.x

                # Definite input and output Tensors for detection_graph
                image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

                # Each box represents a part of the image where a particular object was detected.
                detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

                # Each score represent how level of confidence for each of the objects.
                # Score is shown on the result image, together with the class label.
                detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
                detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
                num_detections = detection_graph.get_tensor_by_name('num_detections:0')

                # for all the frames that are extracted from input video
                while cap.isOpened():
                    (ret, frame) = cap.read()

                    if not ret:
                        print ('end of the video file...')
                        break

                    input_frame = frame
                    count_frames = count_frames + 1
                    self.calc_processing_percents(cap)

                    # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
                    image_np_expanded = np.expand_dims(input_frame, axis=0)

                    # Actual detection.
                    (boxes, scores, classes, num) = \
                        sess.run([detection_boxes, detection_scores,
                                detection_classes, num_detections],
                                feed_dict={image_tensor: image_np_expanded})

                    print("classes: " )
                    print(classes)

                    output_dict = {}

                    for box, score in zip(boxes, scores):
                        for box_inside, score_inside in zip(box, score):
                            counter_cars = counter_cars + 1
                            output_dict["detection_scores"] = []
                            output_dict["detection_scores"].append(score_inside)
                            output_dict["detection_boxes"] = []
                            output_dict["detection_boxes"].append([])

                            output_dict["detection_boxes"][0].append(box_inside[0])
                            output_dict["detection_boxes"][0].append(box_inside[1])
                            output_dict["detection_boxes"][0].append(box_inside[2])
                            output_dict["detection_boxes"][0].append(box_inside[3])
                            result_crop = self.crop_objects(width, height, frame, output_dict, counter_cars)

                            if result_crop["status"] != False:
                                result_crop["countercars"] = counter_cars
                                result_crop["box"] = box_inside
                                #get time of detection
                                milliseconds = cap.get(cv2.CAP_PROP_POS_MSEC)
                                detection_time = self.get_detection_time(milliseconds)
                                result_crop["detection_time"] = detection_time
                                car_to_detect.append(result_crop)

                    #Visualization of the results of a detection.
                    (counter, csv_line,  box_to_display_str_map, box_to_color_map) = \
                        vis_util.visualize_boxes_and_labels_on_image_array(
                        cap.get(1),
                        input_frame,
                        np.squeeze(boxes),
                        np.squeeze(classes).astype(np.int32),
                        np.squeeze(scores),
                        category_index,
                        use_normalized_coordinates=True,
                        line_thickness=4,
                        )

                    for type_box in box_to_display_str_map:
                        val_type_car = box_to_display_str_map[type_box]
                        for car in car_to_detect:
                            if (np.array_equal(car["box"], type_box, equal_nan=False)):
                                car["type"] = val_type_car

                    if len(car_to_detect) > 1000000:
                        new_list = list(car_to_detect)

                        print("try to process.....")
                        print("loading model for: " + str(self.context_id))
                        model, cars_meta, class_names = self.load_model_init()
                        print("finished loading model for: " + str(self.context_id))
                        self.model_detect_car(new_list, model, cars_meta, class_names)
                        car_to_detect = []

                    if(command=="imshow"):
                        x = "imshow"
                        # cv2.imshow('vehicle detection', input_frame)

                        # if cv2.waitKey(1) & 0xFF == ord('q'):
                        #     break
                    elif(command=="imwrite"):
                        output_movie.write(input_frame)
                        #print("writing frame...")

                    if csv_line != 'not_available':
                        with open('traffic_measurement.csv', 'a') as f:
                            writer = csv.writer(f)
                            (size, color, direction, speed) = \
                                csv_line.split(',')
                            writer.writerows([csv_line.split(',')])

                if len(car_to_detect) >= 1:
                    print("loading model for: " + str(self.context_id))
                    model, cars_meta, class_names = self.load_model_init()
                    print("finished loading model for: " + str(self.context_id))
                    new_list = list(car_to_detect)

                    print("try to process.....")
                    self.model_detect_car(new_list, model, cars_meta, class_names)
                    car_to_detect = []

                self.processing_percents = 100

                cap.release()
                #cv2.destroyAllWindows()

    def start_detection(self):
        print('start detections')
        self.object_detection_function(self.video_path, "imshow")

    def run(self):
        self.start_detection()


# Условие: Дан текст: в первой строке задано число строк, далее идут сами строки. Выведите слово, которое в этом тексте встречается чаще всего. Если таких слов несколько, выведите то, которое меньше в лексикографическом порядке.
# Решение:
a = {}
max = 0

for _ in range(int(input())):
    for word in input().split():
        if word in a:
            a[word]+=1 # если слово в словаре есть, то добавляем +1, если нет, то значение у него просто 1
        else:
            a[word] = 1

        if a[word] > max: # в этом же цикле ищем значение max
            max = a[word]

for key, value in sorted(a.items()): # этот цикл имеет значение вывод
    if value == max: # в выводе пробегают пары это key и value - у нас они отсортированные
        print(key) # если значение равно у нас max, то выводим ключ и заканчиваем цикл for
        break

11. Словари/4.Самоечастноечисло.py

4.Самоечастноечисло.py