#!/usr/bin/python

""" Not written by me:
    Heavy modified version of https://github.com/kiritbasu/Fake-Apache-Log-Generator"""

import time
import datetime
import random
import sys
import argparse

class switch(object):
    def __init__(self, value):
        self.value = value
        self.fall = False

    def __iter__(self):
        """Return the match method once, then stop"""
        yield self.match
        raise StopIteration

    def match(self, *args):
        """Indicate whether or not to enter a case suite"""
        if self.fall or not args:
            return True
        elif self.value in args: # changed for v1.5, see below
            self.fall = True
            return True
        else:
            return False

parser = argparse.ArgumentParser(__file__, description="Fake Apache Log Generator")
parser.add_argument("--num", "-n", dest='num_lines', help="Number of lines to generate (0 for infinite)", type=int, default=1)
parser.add_argument("--sleep", "-s", help="Sleep this long between lines (in seconds)", default=0.0, type=float)

args = parser.parse_args()

log_lines = args.num_lines

timestr = time.strftime("%Y%m%d-%H%M%S")
otime = datetime.datetime.now()

f = sys.stdout

response=["200","404","500","301"]
verb=["GET","POST","DELETE","PUT"]
resources=["/list","/wp-content.png","/wp-admin.png"]

ualist = ["test uasdf us "]

flag = True
while (flag):
    if args.sleep:
        increment = datetime.timedelta(seconds=args.sleep)
    else:
        increment = datetime.timedelta(seconds=random.randint(30, 300))
    otime += increment

    ip_list = ["1.1.1.1", "2.100.15.1", "255.255.255.255", "123.41.4.111", "10.10.1.1"]
    ip = random.choice(ip_list)
    dt = otime.strftime('%d/%b/%Y:%H:%M:%S')
    tz = datetime.datetime.now().strftime('%z')
    vrb = "2"

    uri = random.choice(resources)
    if uri.find("apps")>0:
        uri += str(random.randint(1000,10000))

    code = ["GET", "POST","GTFO"]
    resp = random.choice(code) #"5000"

    idz = ["ABCD", "AZYR", "NOEN", "YAYE", "TEST"]
    ids = random.choice(idz)

    byt = int(random.gauss(5000,50))

    referer = "/whynot.png " #aker.uri()
    #print "127.0.0.1 - ABCD [22/Oct/2018:12:38:12 -0700] \"GET /sample-image.png HTTP/2\" 200 1479"
    f.write("{} - {} [{} -0000] \"{} {}\n".format(ip, ids, dt, resp, uri))
    f.flush()

    log_lines = log_lines - 1
    flag = False if log_lines == 0 else True
    if args.sleep:
        time.sleep(args.sleep)


import discord
from discord.ext import commands
from discord.ext.commands import MissingPermissions
from tesda import cooldConvert
import datetime

class Mute(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command(aliases=["to"])
    @commands.has_permissions(kick_members=True)
    async def mute(self, ctx, user: discord.Member = None, time=None, *, reason=None):
        if user is None:
            return await ctx.send("Veuillez indiquer un membre.")
        elif time is None:
            return await ctx.send("Veuillez indiquer une durée.")
        elif reason is None:
            return await ctx.send("Veuillez indiquer une raison.")
        await user.timeout(until=datetime.datetime(time), reason=reason)
        await ctx.send(f"{user} à été mute pour {cooldConvert(time)} (`{reason}`).")

    @mute.error
    async def to_error(self, ctx, error):
        if isinstance(error, MissingPermissions):
            await ctx.send("Vous n'avez pas la permission (`expulser des membres`).")

async def setup(client):
    await client.add_cog(Mute(client))


import os
import tarfile
import zipfile
from typing import List, Generator, Callable

import rarfile

class XarInfo(object):
    '''Informational class which holds the details about an archive member given by a XarFile.'''

    def __init__(self, _xarinfo, arctype='tar'):
        self._info = _xarinfo
        self.arctype = arctype

    @property
    def name(self) -> str:
        if self.arctype == 'tar':
            return self._info.name
        return self._info.filename

    @property
    def size(self) -> int:
        if self.arctype == 'tar':
            return self._info.size
        return self._info.file_size

class XarFile(object):
    '''
    The XarFile Class provides an interface to tar/rar/zip archives.

    Args:
        name(str) : file or directory name to be archived
        mode(str) : specifies the mode in which the file is opened, it must be:
            ========   ==============================================================================================
            Charater   Meaning
            --------   ----------------------------------------------------------------------------------------------
            'r'        open for reading
            'w'        open for writing, truncating the file first, file will be saved according to the arctype field
            'a'        open for writing, appending to the end of the file if it exists
            ========   ===============================================================================================
        arctype(str) : archive type, support ['tar' 'rar' 'zip' 'tar.gz' 'tar.bz2' 'tar.xz' 'tgz' 'txz'], if
                       the mode if 'w' or 'a', the default is 'tar', if the mode is 'r', it will be based on actual
                       archive type of file
    '''

    def __init__(self, name: str, mode: str, arctype: str = 'tar', **kwargs):
        # if mode is 'w', adjust mode according to arctype field
        if mode == 'w':
            if arctype in ['tar.gz', 'tgz']:
                mode = 'w:gz'
                self.arctype = 'tar'
            elif arctype == 'tar.bz2':
                mode = 'w:bz2'
                self.arctype = 'tar'
            elif arctype in ['tar.xz', 'txz']:
                mode = 'w:xz'
                self.arctype = 'tar'
            else:
                self.arctype = arctype
        # if mode is 'r', adjust mode according to actual archive type of file
        elif mode == 'r':
            if tarfile.is_tarfile(name):
                self.arctype = 'tar'
                mode = 'r:*'
            elif zipfile.is_zipfile(name):
                self.arctype = 'zip'
            elif rarfile.is_rarfile(name):
                self.arctype = 'rar'
        elif mode == 'a':
            self.arctype = arctype
        else:
            raise RuntimeError('Unsupported mode {}'.format(mode))

        if self.arctype in ['tar.gz', 'tar.bz2', 'tar.xz', 'tar', 'tgz', 'txz']:
            self._archive_fp = tarfile.open(name, mode, **kwargs)
        elif self.arctype == 'zip':
            self._archive_fp = zipfile.ZipFile(name, mode, **kwargs)
        elif self.arctype == 'rar':
            self._archive_fp = rarfile.RarFile(name, mode, **kwargs)
        else:
            raise RuntimeError('Unsupported archive type {}'.format(self.arctype))

    def __del__(self):
        self._archive_fp.close()

    def __enter__(self):
        return self

    def __exit__(self, exit_exception, exit_value, exit_traceback):
        if exit_exception:
            print(exit_traceback)
            raise exit_exception(exit_value)
        self._archive_fp.close()
        return self

    def add(self, name: str, arcname: str = None, recursive: bool = True, exclude: Callable = None):
        '''
        Add the file `name' to the archive. `name' may be any type of file (directory, fifo, symbolic link, etc.).
        If given, `arcname' specifies an alternative name for the file in the archive. Directories are added
        recursively by default. This can be avoided by setting `recursive' to False. `exclude' is a function that
        should return True for each filename to be excluded.
        '''
        if self.arctype == 'tar':
            self._archive_fp.add(name, arcname, recursive, filter=exclude)
        else:
            self._archive_fp.write(name)
            if not recursive or not os.path.isdir(name):
                return
            items = []
            for _d, _sub_ds, _files in os.walk(name):
                items += [os.path.join(_d, _file) for _file in _files]
                items += [os.path.join(_d, _sub_d) for _sub_d in _sub_ds]

            for item in items:
                if exclude and not exclude(item):
                    continue
                self._archive_fp.write(item)

    def extract(self, name: str, path: str):
        '''Extract a file from the archive to the specified path.'''
        return self._archive_fp.extract(name, path)

    def extractall(self, path: str):
        '''Extract all files from the archive to the specified path.'''
        return self._archive_fp.extractall(path)

    def getnames(self) -> List[str]:
        '''Return a list of file names in the archive.'''
        if self.arctype == 'tar':
            return self._archive_fp.getnames()
        return self._archive_fp.namelist()

    def getxarinfo(self, name: str) -> List[XarInfo]:
        '''Return the instance of XarInfo given 'name'.'''
        if self.arctype == 'tar':
            return XarInfo(self._archive_fp.getmember(name), self.arctype)
        return XarInfo(self._archive_fp.getinfo(name), self.arctype)

def open(name: str, mode: str = 'w', **kwargs) -> XarFile:
    '''
    Open a xar archive for reading, writing or appending. Return
    an appropriate XarFile class.
    '''
    return XarFile(name, mode, **kwargs)

def archive(filename: str, recursive: bool = True, exclude: Callable = None, arctype: str = 'tar') -> str:
    '''
    Archive a file or directory

    Args:
        name(str) : file or directory path to be archived
        recursive(bool) : whether to recursively archive directories
        exclude(Callable) : function that should return True for each filename to be excluded
        arctype(str) : archive type, support ['tar' 'rar' 'zip' 'tar.gz' 'tar.bz2' 'tar.xz' 'tgz' 'txz']

    Returns:
        str: archived file path

    Examples:
        .. code-block:: python

            archive_path = '/PATH/TO/FILE'
            archive(archive_path, arcname='output.tar.gz', arctype='tar.gz')
    '''
    basename = os.path.splitext(os.path.basename(filename))[0]
    savename = '{}.{}'.format(basename, arctype)
    with open(savename, mode='w', arctype=arctype) as file:
        file.add(filename, recursive=recursive, exclude=exclude)

    return savename

def unarchive(name: str, path: str):
    '''
    Unarchive a file

    Args:
        name(str) : file or directory name to be unarchived
        path(str) : storage name of archive file

    Examples:
        .. code-block:: python

            unarchive_path = '/PATH/TO/FILE'
            unarchive(unarchive_path, path='./output')
    '''
    with open(name, mode='r') as file:
        file.extractall(path)

def unarchive_with_progress(name: str, path: str) -> Generator[str, int, int]:
    '''
    Unarchive a file and return the unarchiving progress -> Generator[filename, extrace_size, total_size]

    Args:
        name(str) : file or directory name to be unarchived
        path(str) : storage name of archive file

    Examples:
        .. code-block:: python

            unarchive_path = 'test.tar.gz'
            for filename, extract_size, total_szie in unarchive_with_progress(unarchive_path, path='./output'):
                print(filename, extract_size, total_size)
    '''
    with open(name, mode='r') as file:
        total_size = extract_size = 0
        for filename in file.getnames():
            total_size += file.getxarinfo(filename).size

        for filename in file.getnames():
            file.extract(filename, path)
            extract_size += file.getxarinfo(filename).size
            yield filename, extract_size, total_size

def is_xarfile(file: str) -> bool:
    '''Return True if xarfile supports specific file, otherwise False'''
    _x_func = [zipfile.is_zipfile, tarfile.is_tarfile, rarfile.is_rarfile]
    for _f in _x_func:
        if _f(file):
            return True
    return False


import scrapy
import json
from .. import items
class CountrycovSpider(scrapy.Spider):
    name = 'CountryCov'

    start_urls = ['https://news.sina.com.cn/project/fymap/ncp2020_full_data.json?_=1674182940846&callback=jsoncallback']

    def parse(self, response):
        res = response.text
        res = res.replace("jsoncallback(","").replace(");","")
        res = json.loads(res)
        obj = res["data"]["otherlist"]
        item = items.CountryItem()
        for ik in obj:
            item["conNum"]=int(ik["conNum"]),
            item["conadd"]=int(ik["conadd"]),
            item["cureNum"]=int(ik["cureNum"]),
            item["deathNum"]=int(ik["deathNum"]),
            item["name"]=ik["name"],
            yield item


import torch
import kornia
import random
from torchvision import transforms as TR
import torch.nn.functional as F

class AugmentPipe_kornia(torch.nn.Module):
    def __init__(self, prob, no_masks):
        super().__init__()
        self.prob = prob
        self.no_masks = no_masks

    def forward(self, batch):
        x = batch["images"]
        if not self.no_masks:
            mask = batch["masks"]
            mask_ch = mask.shape[1]

        ref = x
        if not self.no_masks:
            new_mask = mask.clone()
        sh = x[-1].shape
        x = combine_fakes(x)

        if not self.no_masks:
            for i in range(len(x)):
                for ch in range(mask_ch, 0, -3):
                    if ch > 2:
                        x[i] = torch.cat((x[i], mask[i].unsqueeze(0)[:, ch-3:ch, :, :]), dim=(0))
                    else:
                        x[i] = torch.cat((x[i], mask[i].unsqueeze(0).repeat(1, 4-ch, 1, 1)[:, :3, :, :]), dim=(0))

        if random.random() < self.prob/2:
            tr = kornia.augmentation.RandomCrop(size=(sh[2], sh[3]), same_on_batch=True)
            for i in range(sh[0]):
                x[i] = torch.nn.functional.interpolate(x[i], size=(2*sh[2], 2*sh[3]), mode="bilinear")
                x[i] = tr(x[i])

        if random.random() < self.prob:
            if random.random() < 0.5:
                r = random.random() * 0.25 + 0.75
                tr = kornia.augmentation.RandomCrop(size=(int(sh[2]*r), int(sh[3]*r)), same_on_batch=True)
                for i in range(sh[0]):
                    x[i] = tr(x[i])
                    x[i] = torch.nn.functional.interpolate(x[i], size=(sh[2], sh[3]), mode="bilinear")
            else:
                tr = kornia.augmentation.RandomRotation(degrees=8, same_on_batch=True)
                for i in range(sh[0]):
                    x[i] = tr(x[i])
                tr = kornia.augmentation.CenterCrop(size=(sh[2]*0.80, sh[3]*0.80))
                for i in range(sh[0]):
                    x[i] = tr(x[i])
                    x[i] = torch.nn.functional.interpolate(x[i], size=(sh[2], sh[3]), mode="bilinear")

        if random.random() < self.prob:
            tr = kornia.augmentation.RandomHorizontalFlip(p=1.0, same_on_batch=True)
            for i in range(sh[0]):
                x[i] = tr(x[i])

        if random.random() < self.prob:
            for i in range(sh[0]):
                x[i] = translate_v_fake(x[i], fraction=(0.05, 0.3))
        if random.random() < self.prob:
            for i in range(sh[0]):
                x[i] = translate_h_fake(x[i], fraction=(0.05, 0.3))

        if not self.no_masks:
            for i in range(len(x)):
                for ch in reversed(range(mask_ch, 0, -3)):
                    if ch > 2:
                        new_mask[i, ch-3:ch] = x[i][-1-(ch-1)//3]
                    else:
                        new_mask[i, :ch] = x[i][-1][:ch]
                x[i] = x[i][:-1-(ch-1)//3]
        x = detach_fakes(x, ref)

        batch["images"] = x
        if not self.no_masks:
            batch["masks"] = new_mask
        return batch

def combine_fakes(inp):
    sh = inp[-1].shape
    ans = list()
    for i in range(sh[0]):
        cur = torch.zeros_like(inp[-1][0, :, :, :]).repeat(len(inp), 1, 1, 1)
        for j in range(len(inp)):
            cur[j, :, :, :] = F.interpolate(inp[j][i, :, :, :].unsqueeze(0), size=(sh[2], sh[3]),
                                                              mode="bilinear")
        ans.append(cur)
    return ans

def detach_fakes(inp, ref):
    ans = list()
    sh = ref[-1].shape
    for i in range(len(ref)):
        cur = torch.zeros_like(ref[i])
        for j in range(sh[0]):
            cur[j, :, :, :] = F.interpolate(inp[j][i, :, :, :].unsqueeze(0),
                                                              size=(ref[i].shape[2], ref[i].shape[3]),
                                                              mode="bilinear")
        ans.append(cur)
    return ans

class myRandomResizedCrop(TR.RandomResizedCrop):
    def __init__(self, size=256, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.), ):
        super(myRandomResizedCrop, self).__init__(size, scale, ratio)

    def __call__(self, img):
        i, j, h, w = self.get_params(img, self.scale, self.ratio)
        return TR.functional.resized_crop(img, i, j, h, w, (img.size[1], img.size[0]), self.interpolation)

def translate_v_fake(x, fraction):
    margin = torch.rand(1) * (fraction[1] - fraction[0]) + fraction[0]
    direct_up = (torch.rand(1) < 0.5)  # up or down
    height, width = x.shape[2], x.shape[3]
    left, right = 0, width
    if direct_up:
        top, bottom = 0, int(height * margin)
    else:
        top, bottom = height - int(height * margin), height
    im_to_paste = torch.flip(x[:, :, top:bottom, left:right], (2,))
    if not direct_up:
        x[:, :, 0:height - int(height * margin), :] = x[:, :, int(height * margin):height, :].clone()
        x[:, :, height - int(height * margin):, :] = im_to_paste
    else:
        x[:, :, int(height * margin):height, :] = x[:, :, 0:height - int(height * margin), :].clone()
        x[:, :, :int(height * margin), :] = im_to_paste
    return x

def translate_h_fake(x, fraction):
    margin = torch.rand(1) * (fraction[1] - fraction[0]) + fraction[0]
    direct_left = (torch.rand(1) < 0.5)  # up or down
    height, width = x.shape[2], x.shape[3]
    top, bottom = 0, height
    if direct_left:
        left, right = 0, int(width * margin)
    else:
        left, right = width - int(width * margin), width
    im_to_paste = torch.flip(x[:, :, top:bottom, left:right], (3,))
    if not direct_left:
        x[:, :, :, 0:width - int(width * margin)] = x[:, :, :, int(width * margin):width].clone()
        x[:, :, :, width - int(width * margin):] = im_to_paste
    else:
        x[:, :, :, int(width * margin):width] = x[:, :, :, 0:width - int(width * margin)].clone()
        x[:, :, :, :int(width * margin)] = im_to_paste
    return x


import os
import gc
import re
import time
import socket

from gateway import CameraGateway
from utils import load_options, to_pb_image
from frames_loader import FramesLoader

from is_msgs.camera_pb2 import CameraConfig
from google.protobuf.empty_pb2 import Empty
from is_msgs.common_pb2 import FieldSelector
from is_wire.rpc import ServiceProvider, LogInterceptor
from opencensus.ext.zipkin.trace_exporter import ZipkinExporter
from is_wire.core import Channel, Message, Logger, Tracer, AsyncTransport

def create_exporter(service_name, uri):
    log = Logger(name="CreateExporter")
    zipkin_ok = re.match("http:\\/\\/([a-zA-Z0-9\\.]+)(:(\\d+))?", uri)
    if not zipkin_ok:
        log.critical("Invalid zipkin uri \"{}\", expected http://<hostname>:<port>", uri)
    exporter = ZipkinExporter(
        service_name=service_name,
        host_name=zipkin_ok.group(1),
        port=zipkin_ok.group(3),
        transport=AsyncTransport)
    return exporter

def main():

    service_name = "CameraGateway"
    log = Logger(service_name)
    options = load_options()
    camera = CameraGateway(fps=options["fps"])

    publish_channel = Channel(options['broker_uri'])
    rpc_channel = Channel(options['broker_uri'])
    server = ServiceProvider(rpc_channel)
    logging = LogInterceptor()
    server.add_interceptor(logging)

    server.delegate(topic=service_name + ".*.GetConfig",
                    request_type=FieldSelector,
                    reply_type=CameraConfig,
                    function=camera.get_config)

    server.delegate(topic=service_name + ".*.SetConfig",
                    request_type=CameraConfig,
                    reply_type=Empty,
                    function=camera.set_config)

    exporter = create_exporter(service_name=service_name, uri=options["zipkin_uri"])

    while True:

        # iterate through videos listed
        for video in options['videos']:

            # id of the first sequence of videos
            person_id = video['person_id']
            gesture_id = video['gesture_id']

            # getting the path of the 4 videos
            video_files = {
                cam_id:
                os.path.join(options['folder'],
                             'p{:03d}g{:02d}c{:02d}.mp4'.format(person_id, gesture_id, cam_id))
                for cam_id in options["cameras_id"]
            }

            for iteration in range(video['iterations']):

                info = {
                    "person": person_id,
                    "gesture": gesture_id,
                    "iteration": iteration
                }
                log.info('{}', str(info).replace("'", '"'))

                # object that let get images from multiples videos files
                video_loader = FramesLoader(video_files)

                # iterate through all samples on video
                while True:

                    time_initial = time.time()

                    # listen server for messages about change
                    try:
                        message = rpc_channel.consume(timeout=0)
                        if server.should_serve(message):
                            server.serve(message)
                    except socket.timeout:
                        pass

                    frame_id, frames = video_loader.read()

                    for cam in sorted(frames.keys()):
                        tracer = Tracer(exporter)
                        span = tracer.start_span(name='frame')
                        pb_image = to_pb_image(frames[cam])
                        msg = Message(content=pb_image)
                        msg.inject_tracing(span)
                        topic = 'CameraGateway.{}.Frame'.format(cam)
                        publish_channel.publish(msg, topic=topic)
                        tracer.end_span()

                    took_ms = (time.time() - time_initial) * 1000

                    dt = (1 / camera.fps) - (took_ms / 1000)
                    if dt > 0:
                        time.sleep(dt)
                        info = {
                            "sample": frame_id,
                            "took_ms": took_ms,
                            "wait_ms": dt * 1000
                        }
                        log.info('{}', str(info).replace("'", '"'))

                    if frame_id >= (video_loader.num_samples - 1):
                        video_loader.release()
                        del video_loader
                        gc.collect()
                        break

        if options['loop'] is False:
            break

if __name__ == "__main__":
    main()


from aiogram import types
from states.main import ShopState
from loader import dp, db
from aiogram.dispatcher.storage import FSMContext
from keyboards.default.menu import back_btn, cart_btn
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton

@dp.message_handler(text="PHONE 📱", state="*")
async def bot_echo(message: types.Message, state: FSMContext):
    # await state.finish()
    cats_markup = ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
    cats_markup.add(back_btn, cart_btn)
    cats = db.select_all_cats()
    for cat in cats:
        cats_markup.insert(KeyboardButton(text=cat[1]))

    user_id = message.from_user.id
    cart_id = db.select_cart(user_id=user_id)[0]
    await state.update_data({"cart_id": cart_id})
    await message.answer("<b>O'zingizga kerakli bo'limni tanlang</b> 🌐\n\nSizni qaysi turdagi telefon qiziqtiryabdi? 🧐", reply_markup=cats_markup)
    await ShopState.category.set()

@dp.message_handler(text="Sozlamalar ⚙", state="*")
async def bot_echo(message: types.Message, state: FSMContext):
    username = message.from_user.first_name
    await message.reply("bu bo'lim tez orada qo'shiladi 🤩")
    await message.answer(f"{username}, kechirasiz, xali bu bolim ishga tushmadi 😔")

@dp.message_handler(text="Hamyonim 💰", state="*")
async def bot_echo(message: types.Message, state: FSMContext):
    username = message.from_user.first_name
    await message.reply("bu bo'lim tez orada qo'shiladi 🤩")
    await message.answer(f"{username}, kechirasiz, xali bu bo'lim ishga tushmadi 😔")


# -*- coding: utf-8 -*-
"""
Created on Wed Nov 30 23:06:11 2022

@author: maths
"""
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA

mode = 'per_game'

csv_filename_train = 'all_nba_player_{mode}_train.csv'.format(mode=mode)
csv_filename_test = 'all_nba_player_{mode}_test.csv'.format(mode=mode)

features = {
    'Year' : 0,
    'Player':1,
    'Pos':2,
    'Age':3,
    'Tm':4, #team
    'G':5,  #Games played
    'GS':6,
    'MP':7, # minutes per game
    'FG':8,
    'FGA':9,
    'FG%':10,
    '3P':11,
    '3PA':12,
    '3P%':13,
    '2P':14,
    '2PA':15,
    '2P%':16,
    'eFG%':17,
    'FT':18,
    'FTA':19,
    'FT%':20,
    'ORB':21,
    'DRB':22,
    'TRB':23,
    'AST':24,
    'STL':25,
    'BLK':26,
    'TOV':27,
    'PF':28,
    'PTS':29,
    'all-nba_1':30,
    'all-nba_2':31,
    'all-nba_3':32,
    'all-defensive_1':33,
    'all-defensive_2':34,
    'all-rookie_1':35,
    'all-rookie_2':36,
    'all_star_game_rosters_1':37,
    'all_star_game_rosters_2':38,
    'class':39
  }

features_list = ['Age','G','MP','FG','FGA','3P','3PA','2P','2PA','FT','FTA','ORB','DRB','TRB','AST','STL','BLK','TOV','PF','PTS']
def read_data(csv_file):

    df = pd.read_csv(csv_file)
    #print(df.head())
    X1=df.iloc[:,features['Age']]

    X3=df.iloc[:,features['G']]
    X4=df.iloc[:,features['MP']]
    X5=df.iloc[:,features['FG']]
    X6=df.iloc[:,features['FGA']]
    X7=df.iloc[:,features['3P']]
    X8=df.iloc[:,features['3PA']]
    X9=df.iloc[:,features['2P']]
    X10=df.iloc[:,features['2PA']]
    X11=df.iloc[:,features['FT']]
    X12=df.iloc[:,features['FTA']]
    X13=df.iloc[:,features['ORB']]
    X14=df.iloc[:,features['DRB']]
    X15=df.iloc[:,features['TRB']]
    X16=df.iloc[:,features['AST']]
    X17=df.iloc[:,features['STL']]
    X18=df.iloc[:,features['BLK']]
    X19=df.iloc[:,features['TOV']]
    X20=df.iloc[:,features['PF']]
    X21=df.iloc[:,features['PTS']]
    X = np.column_stack((X1,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12,X13,X14,X15,X16,X17,X18,X19,X20,X21))

    y = df.iloc[:,features['class']]
    return X,y

def norm(X):
    import pandas as pd
    from sklearn import preprocessing
    from sklearn.preprocessing import StandardScaler
    min_max_scaler = preprocessing.MinMaxScaler()
    X_sclaed = min_max_scaler.fit_transform(X)
    # df = pd.DataFrame(x_scaled)

    # X_sclaed = StandardScaler().fit_transform(X)

    return X_sclaed

binary_class_problem = 1
def reduce_class(y):
    # class 0 for nothing
    # class 1 for all-nba
    # class 2 for all-defender
    if(binary_class_problem):
        y[y==1] = 1 #set rookie 1st to 0
        y[y==2] = 1 #set rookie 1st to 0
        y[y==3] = 1 #set rookie 2nd to 0

        y[y==4] = 0 #set rookie 1st to 0
        y[y==5] = 0 #set rookie 2nd to 0

        y[y==6] = 0 #set rookie 1st to 0
        y[y==7] = 0 #set rookie 2nd to 0
    else:
        pass

    return y

def select_feature(X,y):
    from sklearn.linear_model import LogisticRegression
    from sklearn.svm import LinearSVC
    from sklearn.feature_selection import SelectFromModel

    x_df = pd.DataFrame(
        data=X,
        columns=features_list)

    selector = SelectFromModel(estimator=LogisticRegression()).fit(x_df, y)

    print(selector.estimator_.coef_)
    #coef_ is of shape (1, n_features)
    importance = np.abs(selector.estimator_.coef_[0])
    feature_names = np.array(features_list)
    plt.bar(height=importance, x=feature_names)
    plt.title("Feature importances via coefficients")
    plt.xticks(rotation=90)
    plt.show()

    print(selector.estimator_.coef_)
    #coef_ is of shape (1, n_features)
    efs = selector.estimator_.coef_[0]
    importance = np.abs(efs[efs >1.0])
    feature_names = np.array(features_list)
    plt.bar(height=importance, x=feature_names[efs >1.0])
    plt.title("Selected Features")
    plt.xticks(rotation=90)
    plt.show()

    feature_idx = selector.get_support()
    feature_name = x_df.columns[feature_idx]

    print(feature_name)
    # model.get_feature_names_out()
    X_new = selector.transform(X)
    # print(X_new.shape, X_new)
def change_class_to_label(y):
    if binary_class_problem:
        y[y==0] = 'No Award'
        y[y==1] = 'all-nba'
    else:
        y[y==0] = 'No Award'
        y[y==1] = 'all-nba-1st'
        y[y==2] = 'all-nba-2nd'
        y[y==3] = 'all-nba-3rd'
        y[y==4] = 'all-defender-1nd'
        y[y==5] = 'all-defender-2nd'
        y[y==6] = 'all-rookie-1'
        y[y==7] = 'all-rookie-2'
    return y

def data_vis_multiclass(X, y):
    import matplotlib.pyplot as plt
    import seaborn as sns

    y = change_class_to_label(y)
    y = np.column_stack((y,))

    print(type(X), type(y))
    print(X.shape, y.shape)
    x_df = pd.DataFrame(
        data=X,
        columns=features_list)

    x_df_tag = pd.DataFrame(
        data = y,
        columns =['class'])
    x_df = pd.concat([x_df, x_df_tag] , axis=1)

    # sns.FacetGrid(x_df, hue="class", size=5).map(plt.scatter, "PCA1", "PCA2").add_legend()
    sns.FacetGrid(x_df, hue="class", size=5).map(plt.scatter, "DRB", "AST", s=2).add_legend()
    plt.title('nba data from 1980-2022: binary')

    plt.show()

def data_vis_multiclass_pca(X, y):
    import matplotlib.pyplot as plt
    import seaborn as sns

    y = change_class_to_label(y)
    y = np.column_stack((y,))

    print(type(X), type(y))
    print(X.shape, y.shape)
    x_df = pd.DataFrame(
        data=X,
        columns=['PCA1', 'PCA2'])

    x_df_tag = pd.DataFrame(
        data = y,
        columns =['class'])
    x_df = pd.concat([x_df, x_df_tag] , axis=1)

    # sns.FacetGrid(x_df, hue="class", size=5).map(plt.scatter, "AST", "PTS").add_legend()
    sns.FacetGrid(x_df, hue="class", size=5).map(plt.scatter, "PCA1", "PCA2",s=2).add_legend()
    if binary_class_problem:
        plt.title('nba data from 1980-2022: binary')
    else:
        plt.title('nba data from 1980-2022: multinomial')
    plt.show()

def pca_analysis(X_train):
    # how many features we need
    pca = PCA(n_components=0.99)

    # Fit and transform data
    pca.fit_transform(X_train)

    # Bar plot of explained_variance
    plt.bar(
        range(1,len(pca.explained_variance_)+1),
        pca.explained_variance_
        )

    plt.xlabel('PCA Feature')
    plt.ylabel('Explained variance')
    plt.title('Feature Explained Variance')
    plt.show()

def data_summary(y):
    y = y.tolist()
    print('size of data is',len(y))
    print('size of no label is', y.count(0))
    print('size of 1 label is', y.count(1))
    print('size of 2 label is', y.count(2))
    print('size of 3 label is', y.count(3))
    print('size of 4 label is', y.count(4))
    print('size of 5 label is', y.count(5))
    print('size of 6 label is', y.count(6))
    print('size of 7 label is', y.count(7))

    pass

def ref():
    import numpy as np
    import matplotlib.pyplot as plt

    N = 3
    ind = np.arange(N)
    width = 0.25

    xvals = [8, 9, 2]
    bar1 = plt.bar(ind, xvals, width, color = 'r')

    yvals = [10, 20, 30]
    bar2 = plt.bar(ind+width, yvals, width, color='g')

    zvals = [11, 12, 13]
    bar3 = plt.bar(ind+width*2, zvals, width, color = 'b')

    plt.xlabel("Dates")
    plt.ylabel('Scores')
    plt.title("Players Score")

    plt.xticks(ind+width,['2021Feb01', '2021Feb02', '2021Feb03'])
    plt.legend( (bar1, bar2, bar3), ('Player1', 'Player2', 'Player3') )
    plt.show()

def plt_pred_summary():
    import matplotlib.pyplot as plt
    import numpy as np

    labels = ['lOGlOSS', 'Precision', 'Recall', 'F1score']
    SVC = [0.039, 0.77, 0.57, 0.65]
    KNN = [0.041, 0.80, 0.40, 0.53]
    RF = [0.051, 0.71, 0.40, 0.51]
    MLP = [0.052, 0.76, 0.43, 0.55]
    DUMMY = [0.773, 0.00, 0.00, 0.0]

    N = 4
    ind = np.arange(N)
    width = 0.1

    plt.figure(dpi=200, figsize=(10,6))
    bar1 = plt.bar(ind, SVC, width, color = 'r')
    bar2 = plt.bar(ind+width, KNN, width, color='g')
    bar3 = plt.bar(ind+width*2, RF, width, color = 'b')
    bar4 = plt.bar(ind+width*3, MLP, width, color = 'y')
    bar5 = plt.bar(ind+width*4, DUMMY, width, color = 'c')

    plt.xlabel("merics")
    plt.ylabel('Scores')
    plt.title("scores by different aproches")

    plt.xticks(ind+width, labels)
    plt.legend( (bar1, bar2, bar3, bar4, bar5), ('SVC', 'KNN', 'RF', 'MLP', 'DUMMY'),loc = 'upper left' )
    plt.show()

if __name__ == '__main__':
    import matplotlib.pyplot as plt

    import warnings
    warnings.filterwarnings('ignore')  # "error", "ignore", "always", "default", "module" or "once"

    X_train, y_train = read_data(csv_filename_train)
    X_test, y_test = read_data(csv_filename_test)
    import pandas
    data_summary(y_train.append(y_test))
    # data_summary(y_test)

    reduce_class(y_train)
    reduce_class(y_test)
    data_vis_multiclass(X_train, y_train)

    print('-----------------',type(y_test))
# must do norm for svm, otherwise program stuck, why?
    X_train = norm(X_train)
    X_test = norm(X_test)

    pca_analysis(X_train)

    select_feature(X_train, y_train)

    pca = PCA(n_components=2)
    X_train = pca.fit_transform(X_train)

    data_vis_multiclass_pca(X_train, y_train)
    # ref()
    plt_pred_summary()


from pathlib import Path

from synthesizer.hparams import hparams
from synthesizer.train import train
from utils.argutils import print_args
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("run_id", type=str, help= \
        "Name for this model. By default, training outputs will be stored to saved_models/<run_id>/. If a model state "
        "from the same run ID was previously saved, the training will restart from there. Pass -f to overwrite saved "
        "states and restart from scratch.")
    parser.add_argument("syn_dir", type=Path, help= \
        "Path to the synthesizer directory that contains the ground truth mel spectrograms, "
        "the wavs and the embeds.")
    parser.add_argument("-m", "--models_dir", type=Path, default="saved_models", help=\
        "Path to the output directory that will contain the saved model weights and the logs.")
    parser.add_argument("-s", "--save_every", type=int, default=1000, help= \
        "Number of steps between updates of the model on the disk. Set to 0 to never save the "
        "model.")
    parser.add_argument("-b", "--backup_every", type=int, default=25000, help= \
        "Number of steps between backups of the model. Set to 0 to never make backups of the "
        "model.")
    parser.add_argument("-f", "--force_restart", action="store_true", help= \
        "Do not load any saved model and restart from scratch.")
    parser.add_argument("--hparams", default="", help=\
        "Hyperparameter overrides as a comma-separated list of name=value pairs")
    args = parser.parse_args()
    print_args(args, parser)

    args.hparams = hparams.parse(args.hparams)

    # Run the training
    train(**vars(args))


from dataclasses import dataclass
from typing import Union, List, Dict

from pm2_model import PSequence, PSequenceStep, ModelTableWriter
from pm2_runtime_shared import RuntimeComponent, SerializableParams

# noinspection PyUnreachableCode
if False:
	# noinspection PyUnresolvedReferences
	from _stubs import *

class SequenceMap(RuntimeComponent, SerializableParams):

	def _ParseSequences(self) -> List[PSequence]:
		seqDat = self.op('selected_sequences')  # type: DAT
		stepDat = self.op('selected_steps')  # type: DAT
		return [
			self._ParseSequence(seqDat, stepDat, i)
			for i in range(1, seqDat.numRows)
		]

	def BuildSequenceInfoTable(self, dat: 'DAT'):
		mergedSequence = self._BuildMergedSequence()
		ModelTableWriter(dat).writeSequences([mergedSequence])

	def BuildSequenceStepTable(self, dat: 'DAT'):
		mergedSequence = self._BuildMergedSequence()
		ModelTableWriter(dat).writeSequenceSteps([mergedSequence], includeMeta=True, includeSequenceName=False)

	def BuildShapeSequenceStepMaskTable(self, dat: 'DAT', shapeCount: int):
		mergedSequence = self._BuildMergedSequence()
		ModelTableWriter(dat).writeShapeSequenceStepMaskTable(
			mergedSequence,
			shapeCount=shapeCount)

	@staticmethod
	def _ParseSequence(seqDat: 'DAT', stepDat: 'DAT', seqRow: Union[str, int]) -> PSequence:
		name = str(seqDat[seqRow, 'sequenceName'] or '')
		stepsByIndex = {}
		maxIndex = 0
		for i in range(1, stepDat.numRows):
			if stepDat[i, 'sequenceName'] != name:
				continue
			step = _parseSequenceStepRow(stepDat, i)
			stepsByIndex[step.sequenceIndex] = step
			maxIndex = max(maxIndex, step.sequenceIndex)
		# make sure there's a step for each sequence index even if there aren't any shapes in them
		paddedSteps = [
			stepsByIndex.get(i) if i in stepsByIndex else PSequenceStep(sequenceIndex=i)
			for i in range(maxIndex + 1)
		]
		return PSequence(
			sequenceName=name,
			steps=paddedSteps,
		)

	@staticmethod
	def _BuildMergedSequential(sequences: List[PSequence]):
		mergedSteps = []  # type: List[PSequenceStep]
		sequenceNames = []
		for sequenceIndex, sequence in enumerate(sequences):
			if not sequence.steps:
				continue
			sequenceNames.append(sequence.sequenceName)
			baseIndex = len(mergedSteps)
			# TODO: Handle missing / empty steps properly ...
			for step in sequence.steps:
				mergedSteps.append(PSequenceStep(
					sequenceIndex=baseIndex + step.sequenceIndex,
					shapeIndices=list(step.shapeIndices or []),
					meta={'sequenceName': sequence.sequenceName, 'sequenceIndex': sequenceIndex}
				))
		return PSequence(
			sequenceName='',
			steps=mergedSteps,
			meta={'sequenceNames': ' '.join(sequenceNames)},
		)

	# def BuildParallelStepLookupChop(
	# 		self,
	# 		chop: 'scriptCHOP'):
	# 	chop.clear()
	# 	sequences = self._ParseSequences()
	# 	if not sequences:
	# 		pass
	# 	# alignstart alignend
	# 	# stretchfirst stretchlong stretchshort - NOT CURRENTLY SUPPORTED
	# 	alignMode = self.par.Sequencealignmode.eval()
	# 	if alignMode.startswith('align'):
	# 		self._BuildParallelStepLookupAligned(chop, sequences, alignMode)
	# 	elif alignMode.startswith('stretch'):
	# 		raise NotImplementedError('stretch alignment not supported')
	#
	# @staticmethod
	# def _BuildParallelStepLookupAligned(chop: 'scriptCHOP', sequences: List[PSequence], mode: str):
	# 	totalStepCount = max([len(seq.steps) for seq in sequences])
	# 	chop.numSamples = totalStepCount
	# 	usingStart = mode == 'alignstart'
	# 	for sequence in sequences:
	# 		chan = chop.appendChan('step_' + sequence.sequenceName)
	# 		if usingStart:
	# 			# seq 1:  0  1  2  3  4  5  6  7
	# 			# seq 2:  0  1  2  3  4  x  x  x
	# 			for i in range(totalStepCount):
	# 				if i < len(sequence.steps):
	# 					chan[i] = i
	# 				else:
	# 					chan[i] = - 1
	# 		else:
	# 			# seq 1:  0  1  2  3  4  5  6  7
	# 			# seq 2:  x  x  x  0  1  2  3  4
	# 			startIndex = totalStepCount - len(sequence.steps)
	# 			for i in range(len(sequence.steps)):
	# 				pass
	# 			for step in sequence.steps:
	# 				chan[step.sequenceIndex + startIndex] = step.sequenceIndex

	def _BuildMergedSequence(self):
		sequences = self._ParseSequences()
		if not sequences:
			return PSequence()
		if len(sequences) == 1:
			sequence = sequences[0]
		elif self.par.Sequencemergetype == 'sequential':
			sequence = self._BuildMergedSequential(sequences)
		else:
			sequence = self._BuildMergedParallelAligned(sequences)
		if self.par.Reversesequence:
			sequence = self._ReverseSequence(sequence)
		return sequence

	@staticmethod
	def _ReverseSequence(origSequence: PSequence):
		n = len(origSequence.steps)
		newSteps = []
		for i in range(n):
			origStep = origSequence.steps[n - i - 1]
			newSteps.append(
				PSequenceStep(
					sequenceIndex=i,
					shapeIndices=list(origStep.shapeIndices),
					meta=dict(origStep.meta),
				)
			)
		return PSequence(
			origSequence.sequenceName,
			meta=dict(origSequence.meta),
			steps=newSteps)

	def _BuildMergedParallelAligned(self, sequences: List[PSequence]):
		if not sequences:
			return PSequence()
		totalStepCount = max([len(seq.steps) for seq in sequences])
		alignMode = self.par.Sequencealignmode.eval()
		usingStart = alignMode == 'alignstart'
		stepListsByIndex = {}  # type: Dict[int, List[_StepWithName]]
		for sequence in sequences:
			if usingStart:
				indexOffset = 0
			else:
				indexOffset = totalStepCount - len(sequence.steps)
			for step in sequence.steps:
				newIndex = indexOffset + step.sequenceIndex
				if newIndex not in stepListsByIndex:
					stepListsByIndex[newIndex] = []
				stepListsByIndex[newIndex].append(_StepWithName(sequence.sequenceName, step))
		mergedSteps = []  # type: List[PSequenceStep]
		for index in range(totalStepCount):
			shapeIndices = set()
			partNames = []
			for step in stepListsByIndex.get(index) or []:
				shapeIndices.update(step.step.shapeIndices)
				partNames.append(f'{step.sequenceName}.{step.step.sequenceIndex}')
			mergedSteps.append(PSequenceStep(
				sequenceIndex=index,
				shapeIndices=list(sorted(shapeIndices)),
				meta={'steps': partNames},
			))
		return PSequence(
			steps=mergedSteps,
			meta={'sequences': [sequence.sequenceName for sequence in sequences]}
		)

@dataclass
class _StepWithName:
	sequenceName: str
	step: PSequenceStep

def _parseSequenceStepRow(dat: 'DAT', row: Union[str, int]):
	indices = dat[row, 'shapeIndices']
	if not indices:
		indices = []
	else:
		indices = [int(part) for part in indices.val.split(' ')]
	return PSequenceStep(
		sequenceIndex=int(dat[row, 'stepIndex'] or 0),
		shapeIndices=indices,
	)


from tkinter import *
from tkinter import ttk
import datetime
import math
from pathlib import Path
import os, shutil
#---------------------------
import keras
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Activation
from keras.models import Sequential
from pathlib import Path
from keras.optimizers import SGD,RMSprop,adam
from keras.utils import np_utils
from google_images_download import google_images_download
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import os
import theano
from PIL import Image
from numpy import *
# SKLEARN
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
#-----------------------------
import cv2, time
from keras.models import model_from_json
from pathlib import Path
from keras.preprocessing import image
import numpy as np
from PIL import Image
import tkinter as tk
from tkinter import messagebox

class MainPage:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.titlelbl = tk.Label(self.frame, text = "Easy CNN")
        self.titlelbl.config(font=("Helvetica", 20))
        self.titlelbl.pack()
        self.namelbl = tk.Label(self.frame, text = "made by Bryan Kyritz")
        self.namelbl.config(font=("Helvetica", 10))
        self.namelbl.pack()
        #tensorflow logo
        dir_path = os.path.dirname(os.path.realpath(__file__))
        load = Image.open(dir_path + "\data\pictures\logo.png")

        image = tk.PhotoImage(file=dir_path + "\data\pictures\logo.png")

        self.tfLogoPic = tk.Label(self.frame, image = image)
        self.tfLogoPic.config(image=image)
        self.tfLogoPic.photo = image
        self.tfLogoPic.pack()
        # -----------------------------------------------------------------
        self.titlelbl = tk.Label(self.frame, text = "Menu")
        self.titlelbl.config(font=("Helvetica", 12))
        self.titlelbl.pack()
        self.helpBtn = tk.Button(self.frame, text = 'More Info', width = 25, command = self.help_window)
        self.helpBtn.pack()
        self.trainBtn = tk.Button(self.frame, text = 'Train Model', width = 25, command = self.train_window)
        self.trainBtn.pack()
        self.testBtn = tk.Button(self.frame, text = 'Test Model', width = 25, command = self.test_window)
        self.testBtn.pack()
        self.genCodeBtn = tk.Button(self.frame, text = 'Generate Code', width = 25, command = self.genCode_window)
        self.genCodeBtn.pack()
        self.getDataOnlineBtn = tk.Button(self.frame, text = 'Get Data from online', width = 25, command = self.getDataOnline_window)
        self.getDataOnlineBtn.pack()
        self.getDataFromVideoBtn = tk.Button(self.frame, text = 'Get Data from video', width = 25, command = self.getDataVideo_window)
        self.getDataFromVideoBtn.pack()
        self.analyzeVidBtn = tk.Button(self.frame, text = 'Analyze pre-recorded video', width = 25, command = self.analyzeVid_window)
        self.analyzeVidBtn.pack()
        self.analyzeVidBtn = tk.Button(self.frame, text = 'Analyze image', width = 25, command = self.analyzeImg_window)
        self.analyzeVidBtn.pack()
        self.frame.pack()
    def help_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = HelpPage(self.newWindow)
    def train_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = TrainPage(self.newWindow)
    def test_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = TestPage(self.newWindow)
    def genCode_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = GenCodePage(self.newWindow)
    def getDataOnline_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = GetDataOnlinePage(self.newWindow)
    def getDataVideo_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = GetDataFromVideo(self.newWindow)
    def analyzeVid_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = analyzeVideoPage(self.newWindow)
    def analyzeImg_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = analyzeImagePage(self.newWindow)
class HelpPage:
    def __init__(self, master):
        titleFontSize = 20
        subtitleFontSize = 16
        answerFontSize = 12
        self.master = master
        self.frame = tk.Frame(self.master)
        self.titleMessage = tk.Label(self.master, text="Help")
        self.titleMessage.config(font=("Helvetica", titleFontSize))
        self.titleMessage.pack()

        self.one = tk.Label(self.master,  text="What does this application do?")
        self.one.config(font=("Helvetica", subtitleFontSize))
        self.one.pack()
        self.oneA = tk.Label(self.master, justify=LEFT, text ="    This app was made by Bryan Kyritz in order to make the implication of \n" +
                                                "    Convolutional neural network(CNN) for image detection easy for those who do not know \n" +
                                                "    how to use tensorflow. This app can only detect if a single object is present in an image \n"+
                                                "    or video. Future updates will include the ability to:\n\n"+
                                                "    •Train for multiple objects\n"+
                                                "    •Generate bounding boxes around the objects by implementing RCNN or YOLO\n"+
                                                "    •More customizability (Changing the training settings within the app")
        self.oneA.config(font=("Helvetica", answerFontSize))
        self.oneA.pack()

        self.two = tk.Label(self.master,  text="How does this app work?")
        self.two.config(font=("Helvetica", subtitleFontSize))
        self.two.pack()
        self.twoA = tk.Label(self.master, justify=LEFT, text= "    This app uses Tensorflow, developed by Google, to build a neural netowork which\n"+
                                                    "    is a mathematical model that can learn to detect patterns in order to solve problems.\n"+
                                                    "    The model that is built is a Convolutional Neural Network(CNN) a convolutional neural network \n"+
                                                    "    is a class of deep neural networks, most commonly applied to analyzing visual imagery(computer vision). CNNs use a \n"+
                                                    "    variation of multilayer perceptrons designed to require minimal preprocessing.")
        self.twoA.config(font=("Helvetica", answerFontSize))
        self.twoA.pack()
        self.frame.pack()
class TrainPage:

    nameOfObject = ""
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.title = tk.Label(self.master, text="Train Model \n")
        self.title.config(font=("Helvetica", 20))
        self.title.pack()
        self.msglbl = tk.Label(self.master, text = "*Make sure you put the data into the training folders*")
        self.msglbl.pack()
        self.nameOfObjectlbl = tk.Label(self.master,text = "Enter the object you are training for:")
        self.nameOfObjectlbl.pack()
        self.nameOfObjTrainingtxt = tk.Text(self.master,width = 20, height = 1)
        self.nameOfObjTrainingtxt.pack()
        self.trainBtn = tk.Button(self.master, text="Train", command = self.train)
        self.trainBtn.pack()
        self.frame.pack()
    #------------------------------------------------------------------------------Deletes all files in a directory
    def deleteFilesInDir(self, folder):
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                print(e)
    def train(self):
        print("Train Model")

        self.modelName = self.nameOfObjTrainingtxt.get("1.0",END).replace('\n','')
        debug = True
        dir_path = os.path.dirname(os.path.realpath(__file__))
        nameOfObject = self.modelName
        print(dir_path)
        #-----------------------------------------------------------------------Directories being used to get images and save images
        org_Obj_dir = dir_path + r"\training_data\object"
        org_not_Obj_dir = dir_path + r"\training_data\not_object"
        edited_obj_dir = dir_path + r"\training_data\edited_object"
        edited_not_obj_dir = dir_path + r"\training_data\edited_not_object"
        all_data_new = dir_path + r"\training_data\allDataNew"

        #pictures are downsized to 200 by 200 pixels
        img_rows, img_cols = 200, 200

        #number of channels (red, green, blue)
        img_channels = 3

        print("------------------------------------------------------------------")

        self.deleteFilesInDir(all_data_new)
        self.deleteFilesInDir(edited_not_obj_dir)
        self.deleteFilesInDir(edited_obj_dir)
        print("Reset folders")

        listing = os.listdir(org_Obj_dir)
        num_samples_obj = size(listing)
        print("Number of object samples:" + str(num_samples_obj))

        for file in listing:
            im = Image.open(org_Obj_dir + '\\' + file)
            img = im.resize((img_rows, img_cols))
            img.save(edited_obj_dir + '\\' + file, "JPEG")
            img.save(all_data_new + '\\' + file, "JPEG")

        if (debug):
            print("Done editing pictures!")

        # converts images into an array
        imlist = os.listdir(edited_obj_dir)
        im1 = array(Image.open(edited_obj_dir + '\\' + imlist[0]))  # open one image to get size
        m, n = im1.shape[0:2]  # get the size of the images
        imnbr = len(imlist)  # get the number of images

        # -------------------------------------------------------------Edits noncube pictures
        listing = os.listdir(org_not_Obj_dir)
        num_samples_not_obj = size(listing)

        if (debug):
            print("Number of non-object samples:" + str(num_samples_not_obj))

        for file in listing:
            im = Image.open(org_not_Obj_dir + '\\' + file)
            img = im.resize((img_rows, img_cols))
            img.save(edited_not_obj_dir + '\\' + file, "JPEG")
            img.save(all_data_new + '\\' + file, "JPEG")

        if (debug):
            print("Done editing object pictures!")

        # converts images into an array
        imlist2 = os.listdir(edited_not_obj_dir)
        im2 = array(Image.open(edited_not_obj_dir + '\\' + imlist2[0]))  # open one image to get size
        m, n = im2.shape[0:2]  # get the size of the images
        imnbr = len(imlist2)  # get the number of images
        # -------------------------------------------------------------Creates matrix to store all flattened images

        both_lists = imlist + imlist2

        print(len(both_lists))

        try:
            immatrix = array([array(Image.open(all_data_new + '\\' + im3)).flatten()
                          for im3 in both_lists], 'f')  #'f'
        except ValueError:
            print("error in classic spot")
            messagebox.showerror("ERROR", "There is an error with your training data")
            self.deleteFilesInDir(all_data_new)
            self.deleteFilesInDir(edited_not_obj_dir)
            self.deleteFilesInDir(edited_obj_dir)
            return 0
        total_Samples = num_samples_obj + num_samples_not_obj
        label = np.ones((total_Samples,), dtype=int)
        label[0:num_samples_obj] = 1  # object
        label[num_samples_not_obj:] = 0  # not object

        data, Label = shuffle(immatrix, label, random_state=2)
        train_data = [data, Label]

        print(train_data[0].shape)
        print(train_data[1].shape)

        # -------------------------------------------------------------Neural network Settings
        # batch_size to train
        batch_size = 32
        # number of output classes
        nb_classes = 2  # 1 = has cube. 0 = doesnt have cube
        # number of epochs to train
        nb_epoch = 20
        # number of convolutional filters to use
        nb_filters = 32
        # size of pooling area for max pooling
        nb_pool = 2
        # convolution kernel size
        nb_conv = 3
        # -------------------------------------------------------------split X and y into training and testing sets
        (X, y) = (train_data[0], train_data[1])
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=4)

        X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, img_channels)
        X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, img_channels)

        X_train = X_train.astype('float32')
        X_test = X_test.astype('float32')

        X_train /= 255
        X_test /= 255
        if (debug):
            print('X_train shape:', X_train.shape)
            print(X_train.shape[0], 'train samples')
            print(X_test.shape[0], 'test samples')

        Y_train = np_utils.to_categorical(y_train, nb_classes)
        Y_test = np_utils.to_categorical(y_test, nb_classes)
        # -------------------------------------------------------------Neural Network Model
        model = Sequential()

        model.add(Conv2D(nb_filters, (nb_conv, nb_conv),
                         padding='same',
                         input_shape=(img_rows, img_cols, img_channels)))
        convout1 = Activation('relu')
        model.add(convout1)
        model.add(Conv2D(nb_filters, (nb_conv, nb_conv), padding='same'))

        convout2 = Activation('relu')
        model.add(convout2)
        model.add(MaxPooling2D(pool_size=(nb_pool, nb_pool)))
        model.add(Dropout(0.5))

        model.add(Flatten())
        model.add(Dense(128))
        model.add(Activation('relu'))
        model.add(Dropout(0.5))
        model.add(Dense(nb_classes))
        model.add(Activation('softmax'))

        model.compile(loss='binary_crossentropy',
                      optimizer='adadelta',  # 'adam' also an option
                      metrics=['accuracy'])
        # -------------------------------------------------------------Train the Neural network
        model.fit(
            X_train,
            Y_train,
            batch_size=batch_size,
            epochs=nb_epoch,
            verbose=1,
            validation_data=(X_test, Y_test), )

        model.fit(
            X_train,
            Y_train,
            batch_size=batch_size,
            epochs=nb_epoch,
            verbose=1,
            validation_split=0.2, )

        # Save neural network's trained weights and structure
        savelink = dir_path + r"\saved_Weights\model_structure_" + nameOfObject + ".json"

        model_structure = model.to_json()
        f = Path(savelink)
        f.write_text(model_structure)

        saveLink2 = dir_path + r"\saved_Weights\model_weights_" + nameOfObject + ".h5"
        model.save_weights(saveLink2)
        self.deleteFilesInDir(all_data_new)
        self.deleteFilesInDir(edited_not_obj_dir)
        self.deleteFilesInDir(edited_obj_dir)
        messagebox.showinfo("Good News", "Done Training!")
        print("Done!")
class TestPage:
    save = False
    def __init__(self, master):
        titleFontSize = 20
        subtitleFontSize = 16
        answerFontSize = 12
        self.master = master
        self.frame = tk.Frame(self.master)
        self.titleMessage = tk.Label(self.master, text="Testing")
        self.titleMessage.config(font=("Helvetica", titleFontSize))
        self.titleMessage.pack()
        self.trainlbl = tk.Label(self.master, text = "Enter the Name of object:")
        self.trainlbl.pack()
        self.nameOfObjTrainingtxt = tk.Text(self.master,width = 20, height = 1)
        self.nameOfObjTrainingtxt.pack()
        self.askSave = tk.Checkbutton(self.master, text = "Save", command = self.check)
        self.askSave.pack()
        self.cameraBtn = tk.Button(self.master, text="Camera", command = self.camera)
        self.cameraBtn.pack()
        self.frame.pack()

    def check(self):
        if self.save == True:
            self.save = False
        else:
            self.save = True
    def camera(self):

        foundPath = True
        nameOfObject = self.nameOfObjTrainingtxt.get("1.0",END).replace('\n','')

        dir_path = os.path.dirname(os.path.realpath(__file__))

        savelink = dir_path + r"\saved_Weights\model_structure_" + nameOfObject + ".json"
        saveLink2 = dir_path + r"\saved_Weights\model_weights_" + nameOfObject + ".h5"

        print(dir_path)

        class_labels = ["Not Object",nameOfObject]
        #Load the json file that contains the model's structure
        try:
            foundPath = True
            f = Path(savelink)
            model_structure = f.read_text()
        except IOError:
            foundPath = False
            messagebox.showerror("ERROR", "Could not find weights for: "+nameOfObject)

        if foundPath:
            f = Path(savelink)
            model_structure = f.read_text()
            # Recreate the Keras model object from the json data
            model = model_from_json(model_structure)

            # Re-load the model's trained weights
            model.load_weights(saveLink2)

            # -----------------------------------------------------------------------------------Resizes image
            img_rows = 200  # what we converted all the training data to (200x200 image)
            img_cols = 200

            #---------------------------------------------------------SAVING VIDEO INFO
            FILE_OUTPUT = nameOfObject + '.avi'

            if os.path.isfile(FILE_OUTPUT): #deletes old video with thw same name
                os.remove(FILE_OUTPUT)

            video = cv2.VideoCapture(0)
            if self.save == True:
                fourcc = cv2.VideoWriter_fourcc(*'MJPG')
                width = video.get(cv2.CAP_PROP_FRAME_WIDTH)   # float
                height = video.get(cv2.CAP_PROP_FRAME_HEIGHT)
                fps = video.get(cv2.CAP_PROP_FPS)

                out = cv2.VideoWriter(FILE_OUTPUT, fourcc, 20.0, (int(width), int(height)))

            while True:
                check, frame = video.read()
                cv2.imwrite('currentFrame.jpg', frame)

                im = Image.open("currentFrame.jpg")  # image name
                img = im.resize((img_rows, img_cols))
                image_to_test = image.img_to_array(img)
                list_of_images = np.expand_dims(image_to_test, axis=0)
                results = model.predict(list_of_images)
                single_result = results[0]
                most_likely_class_index = int(np.argmax(single_result))
                class_likelihood = single_result[most_likely_class_index]
                class_label = class_labels[most_likely_class_index]

                # Print the result
                print("This is image is a {} - Likelihood: {:2f}".format(class_label, class_likelihood))
                key = cv2.waitKey(10)
                if key == ord('q'):
                    break

                font = cv2.FONT_HERSHEY_SIMPLEX
                bottomLeftCornerOfText = (80, 30)
                fontScale = 0.5
                fontColor = (255, 255, 255)
                lineType = 2

                cv2.putText(frame,str(class_label) + "|" + str(class_likelihood),
                            bottomLeftCornerOfText,
                            font,
                            fontScale,
                            fontColor,
                            lineType)
                # Edit image in here
                if most_likely_class_index == 0:
                    cv2.circle(frame, (50, 50), 20, (0, 0, 255), -1) #not object indicator
                else:
                    cv2.circle(frame, (50, 50), 20, (0, 255, 0), -1) #object indicator

                # Saving image in here
                if self.save == True:  # saves video
                    out.write(frame)
                #-----------------------
                cv2.imshow("Capturing", frame)
            if self.save == True:
                out.release()
                messagebox.showinfo("Good News", "Saved Video!")
            video.release()
            cv2.destroyAllWindows()
class GenCodePage:
    def __init__(self, master):
        titleFontSize = 20
        subtitleFontSize = 16
        answerFontSize = 12
        self.master = master
        self.frame = tk.Frame(self.master)
        self.titleMessage = tk.Label(self.master, text="Generate Code")
        self.titleMessage.config(font=("Helvetica", titleFontSize))
        self.titleMessage.pack()
        self.trainlbl = tk.Label(self.master, text="Enter the Name of object:")
        self.trainlbl.pack()
        self.nameOfObjTrainingtxt = tk.Text(self.master,width = 20, height = 1)
        self.nameOfObjTrainingtxt.pack()
        self.genBtn = tk.Button(self.master, text="Generate", command = self.genCode)
        self.genBtn.pack()

    def genCode(self):
        nameOfObject = self.nameOfObjTrainingtxt.get("1.0", END).replace('\n', '')
        f = open(nameOfObject + "_Generated_Code" + ".txt", "w")
        f.write("from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Activation\n"+
                "from keras.models import Sequential\n"+
                "from pathlib import Path\n"+
                "from keras.optimizers import SGD,RMSprop,adam\n"+
                "def camera(self):\n" +
                "import cv2, time\n"+
                "from keras.models import model_from_json\n"+
                "from pathlib import Path\n"+
                "from keras.preprocessing import image\n"+
                "import numpy as np\n"+
                "import theano\n" +
                "\tfoundPath = True\n" +
                "\tdir_path = os.path.dirname(os.path.realpath(__file__))\n" +
                "\tsavelink = dir_path + r\"\saved_Weights\model_structure_\" + nameOfObject + \".json\"\n" +
                "\tsaveLink2 = dir_path + r\"\saved_Weights\model_weights_\" + nameOfObject + \".h5\"\n" +
                "\tclass_labels = [\"Not Object\", nameOfObject,]\n" +
                "\ttry:\n" +
                "\t\tfoundPath = True\n" +
                "\t\tf = Path(savelink)\n" +
                "\t\tmodel_structure = f.read_text()\n" +
                "\texcept IOError:\n" +
                "\t\tfoundPath = False\n" +
                "\t\tmessagebox.showerror(\"ERROR\", \"Could not find weights for: \"+nameOfObject)\n" +
                "\tif foundPath:\n" +
                "\t\tf = Path(savelink)\n" +
                "\t\tfmodel_structure = f.read_text()\n" +
                "\t\tmodel = model_from_json(model_structure)\n" +
                "\t\tmodel.load_weights(saveLink2)\n" +
                "\t\timg_rows = 200\n" +
                "\t\timg_cols = 200\n" +
                "\t\tvideo = cv2.VideoCapture(0)\n" +
                #---------------------------------------------------
                "\t\tim = Image.open(\"currentFrame.jpg\")  # image name\n" +
                "\t\timg = im.resize((img_rows, img_cols))\n" +
                "\t\timage_to_test = image.img_to_array(img)\n" +
                "\t\tlist_of_images = np.expand_dims(image_to_test, axis=0)\n" +
                "\t\tresults = model.predict(list_of_images)\n" +
                "\t\tsingle_result = results[0]\n" +
                "\t\tmost_likely_class_index = int(np.argmax(single_result))\n" +
                "\t\tclass_likelihood = single_result[most_likely_class_index]\n" +
                "\t\tclass_label = class_labels[most_likely_class_index]\n" +
                "\t\tprint(\"This is image is a {} - Likelihood: {:2f}\".format(class_label, class_likelihood))\n" +
                "\t\tif most_likely_class_index == 0:\n" +
                "\t\t\treturn False\n" +
                "\t\telse:\n" +
                "\t\t\treturn True\n"
                )
class GetDataOnlinePage:
    saveChoice = 1 #1 = normal   | #2 = different

    def __init__(self, master):
        titleFontSize = 20
        subtitleFontSize = 16
        answerFontSize = 12
        self.master = master
        self.frame = tk.Frame(self.master)
        self.titleMessage = tk.Label(self.master, text="Get Data Online")
        self.titleMessage.config(font=("Helvetica", titleFontSize))
        self.titleMessage.pack()
        self.trainlbl = tk.Label(self.master, text="Enter the Name of object:")
        self.trainlbl.pack()
        self.nameOfObjTrainingtxt = tk.Text(self.master,width = 20, height = 1)
        self.nameOfObjTrainingtxt.pack()
        self.numlbl = tk.Label(self.master, text="How many Images?")
        self.numlbl.pack()
        self.numtxt = tk.Text(self.master,width = 20, height = 1)
        self.numtxt.pack()
        self.saveNorm = tk.Radiobutton(self.master, text="Normal Save(may overide old data)", variable=self.saveChoice, value=1).pack(anchor=W)
        self.saveDif = tk.Radiobutton(self.master, text="Different save", variable=self.saveChoice, value=2).pack(anchor=W)
        self.dirlbl = tk.Label(self.master, text="Directory to save(only if you selected \"Different save\"")
        self.dirlbl.pack()
        self.dirtxt = tk.Text(self.master,width = 20, height = 1)
        self.dirtxt.pack()
        self.genBtn = tk.Button(self.master, text="Get Data", command = self.getData)
        self.genBtn.pack()
    #---------------------------------------------------------------------------------Delets broken downloads
    def deleteBrokenFiles(self, folder):
        counter = 0
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            ending = file_path[-3:]
            if ending != "jpg":
                counter = counter+1
                if os.path.isfile(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
        print("Deleted " + str(counter) + " broken pictures")
    #----------------------------------------------------------------------------------Downloads and organizes saved images from google images, used to build a dataset
    def getData(self):

        nameOfObject = self.nameOfObjTrainingtxt.get("1.0",END).replace('\n','')
        numLimit = self.numtxt.get("1.0",END).replace('\n','')

        isVal = True
        if nameOfObject == "":
            isVal = False
        if numLimit == "":
            isVal = False

        if isVal:
            self.loadingLbl = tk.Label(self.master, text="Downloading...This may take a while...")
            self.loadingLbl.pack()
            nameOfObject = self.nameOfObjTrainingtxt.get("1.0",END).replace('\n','')
            numLimit = self.numtxt.get("1.0",END).replace('\n','')

            dir_path = os.path.dirname(os.path.realpath(__file__))

            response = google_images_download.googleimagesdownload()
            arguments = {"keywords": nameOfObject, "limit": numLimit, "format": "jpg", "chromedriver": dir_path + r"\data\chromedriver.exe"}
            absolute_image_paths = response.download(arguments)

            self.loadingLbl.destroy()
            folder = dir_path + "\downloads\\" + nameOfObject
            self.deleteBrokenFiles(folder)
            messagebox.showinfo("Good News", "Done Downloading!\nIt is recommended to check the pictures.")
        else:
            if nameOfObject == "":
                messagebox.showerror("ERROR", "Enter the name of the object")
            if numLimit == "":
               messagebox.showerror("ERROR", "Enter the number images")
class GetDataFromVideo:
    save = False
    def __init__(self, master):
        titleFontSize = 20
        subtitleFontSize = 16
        answerFontSize = 12
        self.master = master
        self.frame = tk.Frame(self.master)
        self.titleMessage = tk.Label(self.master, text="Generate images from video")
        self.titleMessage.config(font=("Helvetica", titleFontSize))
        self.titleMessage.pack()
        self.pathlbl = tk.Label(self.master, text="Directory of video")
        self.pathlbl.pack()
        self.pathtxt = tk.Text(self.master,width = 20, height = 1)
        self.pathtxt.pack()
        self.askSaveDir = tk.Checkbutton(self.master, text = "Save in Different Location?", command = self.check)
        self.askSaveDir.pack()
        self.savePathlbl = tk.Label(self.master, text="Save Directory of images")
        self.savePathlbl.pack()
        self.savePathtxt = tk.Text(self.master,width = 20, height = 1)
        self.savePathtxt.pack()
        self.genBtn = tk.Button(self.master, text="Generate", command = self.splitVideo)
        self.genBtn.pack()
    def check(self):
        if self.save == True:
            self.save = False
        else:
            self.save = True
    def splitVideo(self):
        dir_path = os.path.dirname(os.path.realpath(__file__))

        path = self.pathtxt.get("1.0", END).replace('\n', '')

        if path == "":
            messagebox.showerror("ERROR", "Enter in the directory of the video.")
            return 0
        if not os.path.exists(path):
            messagebox.showerror("ERROR", "Video Path does not exist")
            return 0
        #checks if folder exists and if it doesnt, then makes one
        if self.save == True:
            if self.savePathtxt.get("1.0", END).replace('\n', '') == "":
                messagebox.showerror("ERROR", "Enter in another save directory or save in the default folder")
                return 0
            else:
                savePath = self.savePathtxt.get("1.0", END).replace('\n', '')
        else:
            try:
                nameOfFile = path
                index = nameOfFile.rfind("\\")

                nameOfFile = nameOfFile[index+1:-4]
                print(nameOfFile)
                if not os.path.exists(dir_path + '\downloads\\' + nameOfFile):
                    os.makedirs(dir_path+ '\downloads\\' + nameOfFile)
                    print("Made folder for image")
                savePath = dir_path + "\downloads\\" + nameOfFile
            except OSError:
                print('Error: Creating directory of data')

        videoFile = path
        imagesFolder = savePath
        currentFrame = 0

        cap = cv2.VideoCapture(path)
        while (True):
            # Capture frame-by-frame
            ret, frame = cap.read()
            if not ret:
                break
            # Saves image of the current frame in jpg file
            name = imagesFolder +"\\" + nameOfFile + "_"+str(currentFrame) + '.jpg'
            print('Creating...' + name)
            cv2.imwrite(name, frame)

            # To stop duplicate images
            currentFrame += 1

        # When everything done, release the capture
        cap.release()
        cv2.destroyAllWindows()
        messagebox.showinfo("Good News", "Done Saving images! Images saved in: \n"+imagesFolder)
class analyzeVideoPage:
    def __init__(self, master):
        titleFontSize = 20
        subtitleFontSize = 16
        answerFontSize = 12
        self.master = master
        self.frame = tk.Frame(self.master)
        self.titleMessage = tk.Label(self.master, text="Analyze Video")
        self.titleMessage.config(font=("Helvetica", titleFontSize))
        self.titleMessage.pack()
        self.nameOfObjTraininglbl = tk.Label(self.master, text="Name of model")
        self.nameOfObjTraininglbl.pack()
        self.nameOfObjTrainingtxt = tk.Text(self.master,width = 20, height = 1)
        self.nameOfObjTrainingtxt.pack()
        self.pathlbl = tk.Label(self.master, text="Directory of video")
        self.pathlbl.pack()
        self.pathtxt = tk.Text(self.master,width = 20, height = 1)
        self.pathtxt.pack()
        self.genBtn = tk.Button(self.master, text="Generate", command = self.analyze)
        self.genBtn.pack()
    def analyze(self):

        foundPath = True
        nameOfObject = self.nameOfObjTrainingtxt.get("1.0",END).replace('\n','')
        videoPath = self.pathtxt.get("1.0",END).replace('\n','')
        dir_path = os.path.dirname(os.path.realpath(__file__))

        savelink = dir_path + r"\saved_Weights\model_structure_" + nameOfObject + ".json"
        saveLink2 = dir_path + r"\saved_Weights\model_weights_" + nameOfObject + ".h5"

        print(dir_path)

        class_labels = ["Not Object",nameOfObject]
        #Load the json file that contains the model's structure
        try:
            foundPath = True
            f = Path(savelink)
            model_structure = f.read_text()
        except IOError:
            foundPath = False
            messagebox.showerror("ERROR", "Could not find weights for: "+nameOfObject)

        if foundPath:
            f = Path(savelink)
            model_structure = f.read_text()
            # Recreate the Keras model object from the json data
            model = model_from_json(model_structure)

            # Re-load the model's trained weights
            model.load_weights(saveLink2)

            # -----------------------------------------------------------------------------------Resizes image
            img_rows = 200  # what we converted all the training data to (200x200 image)
            img_cols = 200

            #---------------------------------------------------------SAVING VIDEO INFO
            FILE_OUTPUT = nameOfObject + '.avi'

            if os.path.isfile(FILE_OUTPUT): #deletes old video with thw same name
                os.remove(FILE_OUTPUT)

            video = cv2.VideoCapture(videoPath)

            fourcc = cv2.VideoWriter_fourcc(*'MJPG')
            width = video.get(cv2.CAP_PROP_FRAME_WIDTH)   # float
            height = video.get(cv2.CAP_PROP_FRAME_HEIGHT)
            fps = video.get(cv2.CAP_PROP_FPS)

            out = cv2.VideoWriter(FILE_OUTPUT, fourcc, 20.0, (int(width), int(height)))

            while True:
                check, frame = video.read()
                cv2.imwrite('currentFrame.jpg', frame)

                if check:
                    try:
                        im = Image.open("currentFrame.jpg")  # image name
                    except IOError:
                        print("Error")
                        messagebox.showerror("ERROR", "An error ocurred!")
                else:
                    messagebox.showinfo("Good News", "Saved Analyzed Video!")
                    return 0
                img = im.resize((img_rows, img_cols))
                image_to_test = image.img_to_array(img)
                list_of_images = np.expand_dims(image_to_test, axis=0)
                results = model.predict(list_of_images)
                single_result = results[0]
                most_likely_class_index = int(np.argmax(single_result))
                class_likelihood = single_result[most_likely_class_index]
                class_label = class_labels[most_likely_class_index]

                # Print the result
                print("This is image is a {} - Likelihood: {:2f}".format(class_label, class_likelihood))
                key = cv2.waitKey(10)
                if key == ord('q'):
                    break

                font = cv2.FONT_HERSHEY_SIMPLEX
                bottomLeftCornerOfText = (80, 50)
                fontScale = 0.5
                fontColor = (255, 255, 255)
                lineType = 2

                cv2.putText(frame,str(class_label) + "|" + str(class_likelihood),
                            bottomLeftCornerOfText,
                            font,
                            fontScale,
                            fontColor,
                            lineType)
                # Edit image in here
                if most_likely_class_index == 0:
                    cv2.circle(frame, (50, 50), 20, (0, 0, 255), -1) #not object indicator
                else:
                    cv2.circle(frame, (50, 50), 20, (0, 255, 0), -1) #object indicator

                # Saving image in here  # saves video
                out.write(frame)
                #-----------------------
                cv2.imshow("Analyzing", frame)
            out.release()
            messagebox.showinfo("Good News", "Saved Analyzed Video!")
            video.release()
            cv2.destroyAllWindows()
class analyzeImagePage:
    def __init__(self, master):
        titleFontSize = 20
        subtitleFontSize = 16
        answerFontSize = 12
        self.master = master
        self.frame = tk.Frame(self.master)
        self.titleMessage = tk.Label(self.master, text="Analyze Image")
        self.titleMessage.config(font=("Helvetica", titleFontSize))
        self.titleMessage.pack()
        self.nameOfObjTraininglbl = tk.Label(self.master, text="Name of model")
        self.nameOfObjTraininglbl.pack()
        self.nameOfObjTrainingtxt = tk.Text(self.master,width = 20, height = 1)
        self.nameOfObjTrainingtxt.pack()
        self.pathlbl = tk.Label(self.master, text="Directory of image")
        self.pathlbl.pack()
        self.pathtxt = tk.Text(self.master,width = 20, height = 1)
        self.pathtxt.pack()
        self.genBtn = tk.Button(self.master, text="Analyze", command = self.analyze)
        self.genBtn.pack()

    def analyze(self):
        foundPath = True
        nameOfObject = self.nameOfObjTrainingtxt.get("1.0",END).replace('\n','')
        imgPath = self.pathtxt.get("1.0",END).replace('\n','')
        dir_path = os.path.dirname(os.path.realpath(__file__))

        savelink = dir_path + r"\saved_Weights\model_structure_" + nameOfObject + ".json"
        saveLink2 = dir_path + r"\saved_Weights\model_weights_" + nameOfObject + ".h5"

        print(dir_path)

        class_labels = ["Not Object",nameOfObject]
        #Load the json file that contains the model's structure
        try:
            foundPath = True
            f = Path(savelink)
            model_structure = f.read_text()
        except IOError:
            foundPath = False
            messagebox.showerror("ERROR", "Could not find weights for: "+nameOfObject)

        if foundPath:
            f = Path(savelink)
            model_structure = f.read_text()
            # Recreate the Keras model object from the json data
            model = model_from_json(model_structure)

            # Re-load the model's trained weights
            model.load_weights(saveLink2)

            # -----------------------------------------------------------------------------------Resizes image
            img_rows = 200  # what we converted all the training data to (200x200 image)
            img_cols = 200

            #---------------------------------------------------------SAVING Image INFO
            try:
                im = Image.open(imgPath)  # image name
            except IOError:
                print("Error")
                messagebox.showerror("ERROR", "Image not found!")

            img = im.resize((img_rows, img_cols))
            image_to_test = image.img_to_array(img)
            list_of_images = np.expand_dims(image_to_test, axis=0)
            results = model.predict(list_of_images)
            single_result = results[0]
            most_likely_class_index = int(np.argmax(single_result))
            class_likelihood = single_result[most_likely_class_index]
            class_label = class_labels[most_likely_class_index]

            # Print the result
            print("This is image is a {} - Likelihood: {:2f}".format(class_label, class_likelihood))

            font = cv2.FONT_HERSHEY_SIMPLEX
            bottomLeftCornerOfText = (80, 50)
            fontScale = 0.5
            fontColor = (255, 255, 255)
            lineType = 2

            cv2.putText(img,str(class_label) + "|" + str(class_likelihood),
                        bottomLeftCornerOfText,
                        font,
                        fontScale,
                        fontColor,
                        lineType)
            # Edit image in here
            if most_likely_class_index == 0:
                cv2.circle(img, (50, 50), 20, (0, 0, 255), -1) #not object indicator
            else:
                cv2.circle(img, (50, 50), 20, (0, 255, 0), -1) #object indicator

            # Saving image in here  # saves video
            Image.write(img)
            messagebox.showinfo("Good News", "Saved Analyzed Picture!")
def main():
    root = tk.Tk()
    root.minsize(300,300)
    root.title("Easy CNN 1.0")
    dir_path = os.path.dirname(os.path.realpath(__file__))
    root.iconbitmap(dir_path + "\data\pictures\icon.ico")
    root.resizable(False, False)
    center(root)
    app = MainPage(root)
    root.mainloop()
def center(toplevel): #centers the main window
    toplevel.update_idletasks()

    # PyQt way to find the screen resolution
    screen_width = toplevel.winfo_screenwidth()
    screen_height = toplevel.winfo_screenheight()

    x = screen_width/2 - toplevel.winfo_width()/2
    y = screen_height/2 - toplevel.winfo_height()/2
    toplevel.geometry("+%d+%d" % (x, y))

if __name__ == '__main__':
    main()


"""Panda package management for Windows.

Application core constant objects.
"""
from pathlib import Path

# Package's installation config files

PKG_CFG_DNAME = 'conf'

# Package info descriptor file
PKG_INFO_FPATH = 'pkginfo.json'
# Package extra installation options descriptor file
PKG_EXTCFG_FEXT = 'extra'
PKG_EXTCFG_FNAME = '.'.join(['{pkg_name}', PKG_EXTCFG_FEXT, 'j2'])
PKG_EXTCFG_FPATH = str(Path(PKG_CFG_DNAME, PKG_EXTCFG_FNAME))
# Package service options descriptor file
PKG_SVCCFG_FEXT = 'nssm'
PKG_SVCCFG_FNAME = '.'.join(['{pkg_name}', PKG_SVCCFG_FEXT, 'j2'])
PKG_SVCCFG_FPATH = str(Path(PKG_CFG_DNAME, PKG_SVCCFG_FNAME))

# List of package installation config file extensions
PKG_INSTCFG_FEXTS = [PKG_EXTCFG_FEXT, PKG_SVCCFG_FEXT]


__author__ = "Sergio Gonzalez Diaz"
__copyright__ = "Social Robots Group. Robotics Lab. University Carlos III of Madrid"
__credits__ = ["Sergio Gonzalez Diaz"]
__license__ = "LEUC3M v1.0"
__version__ = "0.0.0"
__maintainer__ = "Sergio Gonzalez Diaz"
__email__ = "sergigon@ing.uc3m.es"
__status__ = "Development"

# ROS libraries
import rospy
import rospkg

# Libraries
import paramiko
from scp import SCPClient, SCPException
import socket
import ctypes
from threading import Timer
import threading # https://www.geeksforgeeks.org/python-different-ways-to-kill-a-thread/
                 # Fix thread exception: https://stackoverflow.com/questions/38667755/killing-a-thread-in-python-simple-program-does-not-seem-to-work
import yaml
import os
import subprocess

# Exceptions
class NoKey(Exception):
    pass
class NoTabletParams(Exception):
    pass

## @brief Thread with exception
#  Class made to manage methods with exceptions
class PcTabletSyncThread(threading.Thread):

    # Constants
    SUCCESS, ERROR, CON_ERROR = 0, -1, -2
    TIME_WAIT = 5 # sec
    PKG_NAME = 'tablet_data_connections'

    ## @brief Init method
    #  @param name: Name of the method
    #  @param ssh: SSH object
    #  @param arg1: First argument
    #  @param arg2: Second argument
    #  @param recursive: Transfer files and directories recursively
    def __init__(self, name):
        # Thread initialization
        threading.Thread.__init__(self)
        # Local paths
        rospack = rospkg.RosPack()
        pkg_path = rospack.get_path(self.PKG_NAME) + '/' # Package path
        self.path_data = pkg_path + 'data/' # Data path
        self.path_alz = self.path_data + os.environ['HOSTNAME'] + '/' # Alz path
        self.tablet_params_filepath = self.path_alz + 'tablet_ssh_params.yaml' # Tablet SSH params filepath
        self.key_filepath = "/home/user/.ssh/id_tablet.pub" # SSH key filepath
        # Arguments initializarion
        self.name = name
        # Connection variables
        self._server, self._port, self._user = None, None, None
        self.key = None
        # Variables initialization
        self.timer = None
        self.filename_prev, self.sent_prev = '', 0
        # Result variables
        self.result = self.CON_ERROR
        self.info = None

    ## @brief Start the timer
    def start_timer(self):
        self.timer = Timer(self.TIME_WAIT, self.raise_exception)
        self.timer.start()

    ## @brief Cancel the timer
    def cancel_timer(self):
        # Canel the timer
        if(self.timer!=None):
            self.timer.cancel()

    ## @brief Target function of the thread class
    #  Executes the methods specified and check the errors
    def run(self):
        self.read_tablet_params()
        # Methods
        try:
            # rsync pull
            if(self.name == 'rsync_pull'):
                self.rsync_pull()
            elif(self.name == 'rsync_push'):
                self.rsync_push()
            # Wrong name
            else:
                rospy.logerr('Wrong name; %s. Closing thread' % self.name)
                self.result = self.ERROR
        # Exceptions
        except NoKey as e:
            rospy.logerr('NoKey: %s' % e)
            self.result = self.ERROR
        except NoTabletParams as e:
            rospy.logerr('NoTabletParams: %s' % e)
            self.result = self.ERROR
        except OSError as e: # No PC file
            rospy.logerr('OSError: %s ' % e)
            self.result = self.ERROR
        except IOError as e: # No PC directory (scp_get)
                             # Directory no exists (sftp_listdir)
                             # Directory already exists or directory root no exists (sftp_mkdir)
                             # Newpath is a folder or something goes wrong (sftp_rename)
                             # Bad file descriptor (SSH client badly created)
            rospy.logerr('IOError: %s ' % e)
            if(e=='[Errno 9] Bad file descriptor'):
                self.result = self.CON_ERROR
            else:
                self.result = self.ERROR
        except EOFError as e: # EOFError transfer
            rospy.logerr ('EOFError: %s ' % e)
            self.result = self.CON_ERROR
        except paramiko.transport as e:
            rospy.logerr ('transport: %s ' % e)
            self.result = self.CON_ERROR
        except: # Timeout or error
            raise
            rospy.logerr('Timeout or Error')
            self.result = self.CON_ERROR
        else: # Executes if no exceptions
            self.result = self.SUCCESS
        finally: # Executes always
            # Cancel the timer
            self.cancel_timer()

    def read_tablet_params(self):
        try:
            rospy.logdebug('Reading: ' + self.tablet_params_filepath)
            stream = open(self.tablet_params_filepath, 'r')
            params_dict = yaml.load(stream) # Loads value
            self._ip, self._port, self._user = params_dict['tablet_IP'], params_dict['tablet_port'], params_dict['tablet_user']
        except IOError as e: # Reading file error
            rospy.logerr(e)
            self._ip, self._port, self._user = None, None, None # Reset value
            result = self.ERROR
        except KeyError as e: # Reading file error
            rospy.logerr(e)
            self._ip, self._port, self._user = None, None, None # Reset value
            result = self.ERROR
        else: # No errors
            result = self.SUCCESS
        return result

    ## @brief Progress callback that prints the current percentage
    #    completed for the file sending
    #  @param filename: Path of the sent file
    #  @param size: Size of the sent file
    #  @param sent: Current size sent of the sent file.
    def progress(self, filename, size, sent):
        rospy.logdebug("%s\'s progress: %.2f%%   \r" % (filename, float(sent)/float(size)*100) )
        # Checks if it is stuck
        if(self.filename_prev!=filename or self.sent_prev!=sent): # It is not stuck
            self.cancel_timer()
            self.start_timer()
        # Fill prev variables
        self.filename_prev, self.sent_prev = filename, sent

    ########################## Methods ##########################

    def rsync_pull(self):
        self.start_timer()
        rospy.logdebug('rsync pulling')
        cmd = "rsync -av --delete -O -e 'ssh -p " + str(self._port) + "' " + self._user + "@" + self._ip + ":/sdcard/multimedia/testimg/ ../Pictures/"
        os.system(cmd)

    def rsync_push(self):
        self.start_timer()
        rospy.logdebug('rsync pushing')
        cmd = "rsync -av --delete -O -e 'ssh -p " + str(self._port) + "' ../Pictures/ " + self._user + "@" + self._ip + ":/sdcard/multimedia/testimg"
        os.system(cmd)

    ## @brief scp get method
    def scp_get(self, remote_path, local_path, recursive):
        # Start timer
        self.start_timer()
        rospy.logdebug('Establish rsync connection')
        #cmd = "rsync -av -e 'ssh -p 8022' " + full_remote_path + " " + local_path
        #full_remote_path = tablet_user + '@' + tablet_IP + ':' + remote_path
        os.system("rsync -av -e 'ssh -p 8022' u0_a121@192.168.1.106:/sdcard/multimedia/testimg/ Pictures/")
        #subprocess.call(['rsync', '-av', '-e', '"ssh -p 8022"', 'u0_a121@192.168.1.106:/sdcard/Pictures/', 'Pictures/' ])

    ##################### Thread functions ######################

    ## @brief Returns id of the respective thread
      #  @return id: id of the respective thread
    def get_id(self):
        if hasattr(self, '_thread_id'):
            return self._thread_id
        for id, thread in threading._active.items():
            if thread is self:
                return id

    ## @brief Raise an exception in the active thread
    def raise_exception(self):
        thread_id = self.get_id()
        res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread_id),
              ctypes.py_object(SystemExit))
        if res > 1:
            ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
            rospy.logerr('Exception raise failure')

    ## @brief Returns thread result
      #  @return result: thread result
    def return_result(self):
        return self.result

    ## @brief Returns thread info
      #  @return info: thread info
    def return_info(self):
        return self.info