def __init__(self, mode, network, network_criterion, n_clusters,
                 clustering_criterion, cluster_update_interval,
                 no_of_clustering_channels, n_epochs, no_of_pretrain_epochs,
                 batch_size, lr, alpha, downsampling_step, sequence_length,
                 kernel_size):
        self.mode = mode
        self.network = network
        self.network_criterion = network_criterion
        self.n_clusters = n_clusters
        self.clustering_criterion = clustering_criterion
        self.cluster_update_interval = cluster_update_interval
        self.no_of_clustering_channels = no_of_clustering_channels
        self.n_epochs = n_epochs
        self.no_of_pretrain_epochs = no_of_pretrain_epochs
        self.batch_size = batch_size
        self.lr = lr
        self.alpha = alpha
        self.downsampling_step = downsampling_step
        self.sequence_length = sequence_length
        self.kernel_size = kernel_size

        self.path = './{} N{} NC{} Ncl{} CUI{} NclCh{} E{} PE{} BS{} LR{} A{} DS{} SL{} KS{}'.format(
            self.mode, self.network.__class__.__name__, self.network_criterion,
            self.n_clusters, self.cluster_update_interval,
            self.no_of_clustering_channels, self.n_epochs,
            self.no_of_pretrain_epochs, self.batch_size, self.lr, self.alpha,
            self.downsampling_step, self.sequence_length, self.kernel_size)

        functions.createFolder(self.path)
            def createadmin_submit1():

                createFolder('./AdminDetails')
                try:
                    if os.path.exists('./AdminDetails/admin_details.csv'):
                        print('Details directory already exists')
                    else:
                        print("Details directory doesn't Exist")
                        with open('./AdminDetails/admin_details.csv',
                                  'w') as file:
                            writer = csv.writer(file)
                            writer.writerow([
                                "AdminIds", "AdminUserNames",
                                "AdminPhoneNumbers", "AdminEmailIds",
                                "AdminPasswords"
                            ])
                        print(
                            "Creating new directory for employee_details.csv.")
                except OSError:
                    print("File Already Exists")

                AdminId = admin_id_entry.get()
                AdminUserName = admin_username_entry.get()
                AdminPhoneNumber = admin_phonenumber_entry.get()
                AdminEmailId = admin_emailid_entry.get()
                AdminPassword = admin_password_entry.get()

                df = pd.read_csv('./AdminDetails/admin_details.csv')
                if int(AdminId) in df['AdminIds'].values:
                    output.delete(0.0, END)
                    output.insert(END,
                                  'Database Error: Admin ID Already Exists')
                elif len(AdminPhoneNumber) != 10:
                    output.delete(0.0, END)
                    output.insert(
                        END, 'Input Validation Error: Wrong Phone Number')
                elif int(AdminPhoneNumber) in df['AdminPhoneNumbers'].values:
                    output.delete(0.0, END)
                    output.insert(
                        END, 'Database Error: Phone Number Already Exist')
                elif AdminEmailId in df['AdminEmailIds'].values:
                    output.delete(0.0, END)
                    output.insert(END,
                                  'Database Error: Email Id Already Exist')
                else:
                    output.delete(0.0, END)
                    try:
                        createadmin(AdminId, AdminUserName, AdminPhoneNumber,
                                    AdminEmailId, AdminPassword)
                        output_string = 'New Admin Created: ' + AdminUserName
                    except:
                        output_string = "Failed to create Admin"
                    output.insert(END, output_string)
Beispiel #3
0
def modelTrainer():
    print('\nModule Versions: ')
    print('OpenCv: ' + cv2.__version__, '\nNumpy: ' + np.__version__,
          '\nPillow>>Image: ' + Image.__version__)
    print('\nTraining Initialized...')
    start_time = time.time()
    #Creatung directories

    createFolder('./Model/')

    #recognizer = cv2.face.createLBPHFaceRecognizer()
    #recognizer = cv2.face.LBPHFaceRecognizer_create()
    #OpenCv: 4.1.2
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

    def getImagesAndLabels(path):
        imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
        #empty lists for storing Lables and features
        faceSamples = []
        Ids = []
        for imagePath in imagePaths:

            pilImage = Image.open(imagePath).convert('L')
            imageNp = np.array(pilImage, 'uint8')
            Id = int(os.path.split(imagePath)[-1].split(".")[1])
            faces = detector.detectMultiScale(imageNp)
            for (x, y, w, h) in faces:
                faceSamples.append(imageNp[y:y + h, x:x + w])
                Ids.append(Id)
        return faceSamples, Ids

    start_time = time.time()
    faces, Ids = getImagesAndLabels('./EmployeeDetails/dataSet')

    #training model on dataSet
    recognizer.train(faces, np.array(Ids))
    #trainer.yml stored in the folder trainer
    recognizer.save('Model/model.yml')

    recognizer = cv2.face.LBPHFaceRecognizer_create()
    recognizer.read('Model/model.yml')
    cascadePath = "haarcascade_frontalface_default.xml"
    faceCascade = cv2.CascadeClassifier(cascadePath)

    print("----Training Done in : %s seconds----" % (time.time() - start_time))
def createadmin(AdminId, AdminUserName, AdminPhoneNumber, AdminEmailId,
                AdminPassword):
    createFolder('./AdminDetails')

    try:
        if os.path.exists('./AdminDetails/admin_details.csv'):
            print('Details directory already exists')
        else:
            print("Details directory doesn't Exist")
            with open('./AdminDetails/admin_details.csv', 'w') as file:
                writer = csv.writer(file)
                writer.writerow([
                    "AdminIds", "AdminUserNames", "AdminPhoneNumbers",
                    "AdminEmailIds", "AdminPasswords"
                ])
            print("Creating new directory for employee_details.csv.")
    except OSError:
        print("File Already Exists")

    AdminId = int(AdminId)
    AdminUserName = AdminUserName
    AdminPhoneNumber = AdminPhoneNumber
    AdminEmailId = AdminEmailId
    AdminPassword = AdminPassword

    df = pd.read_csv('./AdminDetails/admin_details.csv')

    if int(AdminId) in df['AdminIds'].values:
        print("\nAdmin already exists!!!")
        print("\nExiting.")
    else:
        print("\nCreating New Admin.")
        data = [{
            'AdminIds': AdminId,
            'AdminUserNames': AdminUserName,
            'AdminPhoneNumbers': AdminPhoneNumber,
            'AdminEmailIds': AdminEmailId,
            'AdminPasswords': AdminPassword
        }]
        df = pd.read_csv('./AdminDetails/admin_details.csv')
        df = df.append(data, ignore_index=True, sort=False)
        df.to_csv('./AdminDetails/admin_details.csv', index=False)
    upload_to_database()
Beispiel #5
0
def main():

    ourClasses, youtubeClasses, youtubeClassesID, labelsTF = getClasses(
        'classes.csv', "data/ontology.json", 'data/class_labels_indices.csv')

    # ourClasses = [ourClasses[3]]
    # youtubeClasses = [youtubeClasses[3]]
    # youtubeClassesID = [youtubeClassesID[3]]
    # labelsTF = [labelsTF[3]]

    #Print to check
    for i in range(0, len(ourClasses)):
        print("Under {}".format(ourClasses[i]))
        print(youtubeClasses[i])
        print(youtubeClassesID[i])
        print(labelsTF[i])

    #Create all the folders!!!
    createFolder("data/test_rawAudio")
    createFolder("data/train_rawAudio")

    for c in ourClasses:
        createFolder("data/test_rawAudio/" + c)
        createFolder("data/train_rawAudio/" + c)

    #Download the raw train set
    print("====Downloading Train Data====")
    downloadYoutubeCSV("data/unbalanced_train_segments.csv",
                       "data/temp_train4.mp3",
                       "data/train_rawAudio/",
                       ourClasses,
                       youtubeClassesID,
                       startRow=500000)

    return

    #Download the raw test set
    print("====Downloading Test  Data====")
    downloadYoutubeCSV("data/eval_segments.csv", "data/temp_test.mp3",
                       "data/test_rawAudio/", ourClasses, youtubeClassesID)
def collector(Id, UserName, PhoneNumber, EmailId):
    #created folder for saving dataset images of user
    createFolder('./EmployeeDetails/dataSet')

    #creating employee_details
    try:
        if os.path.exists('./EmployeeDetails/employee_details.csv'):
            print('Details directory already exists')
        else:
            print("Details directory doesn't Exist")
            with open('./EmployeeDetails/employee_details.csv', 'w') as file:
                writer = csv.writer(file)
                writer.writerow(
                    ["Ids", "UserNames", "PhoneNumbers", "EmailIds"])
            print("Creating new directory for employee_details.csv.")
    except OSError:
        print("File Already Exists")

    cam = cv2.VideoCapture(0)
    detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

    print("\n")
    Id = int(Id)
    UserName = UserName
    PhoneNumber = PhoneNumber
    EmailId = EmailId
    df = pd.read_csv('./EmployeeDetails/employee_details.csv')

    if int(Id) in df.values:
        print("\nEmployee already exists!!!")
        print("\nExiting.")
    else:
        print("\nCreating New User.")
        data = [{
            'Ids': Id,
            'UserNames': UserName,
            'PhoneNumbers': PhoneNumber,
            'EmailIds': EmailId
        }]
        df = pd.read_csv('./EmployeeDetails/employee_details.csv')
        df = df.append(data, ignore_index=True, sort=False)
        df.to_csv('./EmployeeDetails/employee_details.csv', index=False)
        df.drop(labels=['PhoneNumbers', 'UserNames'], axis=1, inplace=True)
        df = df.rename(columns={"Ids": "Passwords"})
        df.to_csv('./EmployeeDetails/employee_access_details.csv', index=False)

        sampleNum = 0
        while True:
            ret, img = cam.read()
            ret, img1 = cam.read()
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            faces = detector.detectMultiScale(gray, 1.3, 5)
            for (x, y, w, h) in faces:
                cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)

                #incrementing sample number
                sampleNum = sampleNum + 1
                sampleNum1 = str(sampleNum)
                text = sampleNum
                #saving the captured face in the dataset folder
                cv2.imwrite(
                    "EmployeeDetails/dataSet/User." + str(Id) + '.' +
                    UserName + '.' + str(sampleNum) + '.' + ".jpg",
                    gray[y:y + h, x:x + w])

                cv2.putText(img1, sampleNum1, (70, 150),
                            cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 3)
                cv2.imshow('Scans', img1)

            if cv2.waitKey(1) == 27:
                break
            # break if the sample number is morethan 20
            elif sampleNum > 99:
                break
        cam.release()
    cv2.destroyAllWindows()
    print("----Done----")
Beispiel #7
0
import os
import pandas as pd
import csv
import numpy as np
from datetime import datetime
from functions import createFolder, upload_to_database

#creating hierarchy of directories as Attendance/Year/Month/Day
print("--Creating Main Attendance Directory.--")

createFolder('./Attendance/main_attendance')

#DateTime,TimeStamp,WeekDay Variable
now = datetime.now()
year_dir = str(now.year)
month_dir = str(now.month)
if len(month_dir) == 2:
    pass
else:
    month_dir = '0' + str(now.month)

day_dir = str(now.day)
if len(day_dir) == 2:
    pass
else:
    day_dir = '0' + str(now.day)

weekDays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
            "Sunday")
weekday = str(weekDays[now.weekday()])
Beispiel #8
0
import os
import cv2
import numpy as np
from PIL import Image
import time
from functions import createFolder

print('\nModule Versions: ')
print('OpenCv: ' + cv2.__version__, '\nNumpy: ' + np.__version__,
      '\nPillow>>Image: ' + Image.__version__)
print('\nTraining Initialized...')
start_time = time.time()
#Creatung directories

createFolder('./Model/')

#recognizer = cv2.face.createLBPHFaceRecognizer()
#recognizer = cv2.face.LBPHFaceRecognizer_create()
#OpenCv: 4.1.2
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")


def getImagesAndLabels(path):
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
    #empty lists for storing Lables and features
    faceSamples = []
    Ids = []
    for imagePath in imagePaths:
def directory():
    #creating hierarchy of directories as Attendance/Year/Month/Day
    print("--Creating Main Attendance Directory.--")

    createFolder('./Attendance/main_attendance')

    #DateTime,TimeStamp,WeekDay Variable
    now = datetime.now()
    year_dir = str(now.year)
    month_dir = str(now.month)
    if len(month_dir) == 2:
        pass
    else:
        month_dir = '0' + str(now.month)

    day_dir = str(now.day)
    if len(day_dir) == 2:
        pass
    else:
        day_dir = '0' + str(now.day)

    weekDays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
                "Saturday", "Sunday")
    weekday = str(weekDays[now.weekday()])

    today_path = './Attendance/main_attendance/' + year_dir + '/' + month_dir
    createFolder(today_path)
    date_string = year_dir + '-' + month_dir + '-' + day_dir
    filename = date_string + '_' + weekday

    #student details csv
    student_csv_path = './EmployeeDetails/employee_details.csv'

    #adding more columns to students csv and saving the sheet for main_attendance
    main_attendance_csv_path = today_path + '/' + filename + '.csv'
    df = pd.read_csv(student_csv_path)
    df["Attendance"] = 'Absent'
    df["Attend_DateTime"] = int(0)
    df["Attend_TimeStamp"] = float(0.0)
    df["Leave_DateTime"] = int(0)
    df["Leave_TimeStamp"] = float(0.0)
    df.to_csv(main_attendance_csv_path, index=False)
    print('--csv file created for main attendance--')

    #creating csv and directory for
    if os.path.exists('./Attendance/employee_attendance'):

        for i in range(0, len(df)):
            student_csv_path = './Attendance/employee_attendance/' + str(
                df.iloc[i][0]) + '_' + df.iloc[i][1] + '.csv'

            if os.path.exists(student_csv_path):
                pass
            else:
                data = [
                    'Name', 'Date', 'Day', 'Attendance', 'Attend_DateTime',
                    'Attend_TimeStamp', 'Leave_DateTime', 'Leave_TimeStamp'
                ]
                df1 = pd.DataFrame(columns=data)
                df1.to_csv(student_csv_path, index=False)
                print('--csv file created for: ' + df.iloc[i][1] + '--')

    else:
        createFolder('./Attendance/employee_attendance')
        print("--Created Student Attendance Directory--")
        data = [
            'Name', 'Date', 'Day', 'Attendance', 'Attend_DateTime',
            'Attend_TimeStamp', 'Leave_DateTime', 'Leave_TimeStamp'
        ]
        for i in range(0, len(df)):
            student_csv_path = './Attendance/employee_attendance/' + str(
                df.iloc[i][0]) + '_' + df.iloc[i][1] + '.csv'
            df1 = pd.DataFrame(columns=data)
            df1.to_csv(student_csv_path, index=False)
            print('--csv file created for: ' + df.iloc[i][1] + '--')
        print('\n-----DONE-----')
    main_attendance_database()
    employee_attendance_database()
Beispiel #10
0
    
#################################################################################
    ### 700hP - Temp - RH
    fct.plt_700_humidity(fnx, fnx.geopotential_pl.sel(pressure = 700.,
                                             x = slice(lower_x, upper_x),
                                             y = slice(lower_y, upper_y)).isel(time=int(forecast_in_hours))/100, 
                     fnx.air_temperature_pl.sel(pressure = 700.,
                                                x = slice(lower_x, upper_x),
                                                y = slice(lower_y, upper_y)).isel(time = int(forecast_in_hours)) - 273.15, 
                     fnx.relative_humidity_pl.sel(pressure = 700.,
                                                  x = slice(lower_x, upper_x),
                                                  y = slice(lower_y, upper_y)).isel(time = int(forecast_in_hours))*100, 
                     andenes_x, andenes_y)

    if savefig == 1:
        fct.createFolder('%s/700hPa_RH_T/%s/' %(figdir,map_area))
        plt.savefig('%s/700hPa_RH_T/%s/%s' %(figdir, map_area, fig_name), format = form, bbox_inches='tight', transparent=True)
        print('plot saved: %s/700hPa_RH_T/%s/%s' %(figdir, map_area, fig_name))
    plt.close()

#################################################################################    

    # convert Geopotential to height
    # https://en.wikipedia.org/wiki/Geopotential
    a = 6.378*10**6     # average radius of the earth  [m]
    G = 6.673*10**(-11) # gravitational constant       [Nm2/kg2]
    ma = 5.975*10**24   #  mass of the earth           [kg]

    Z_1000 = (-a**2 * fnx.geopotential_pl.sel(pressure = 1000.,).isel(time = int(forecast_in_hours)))/\
             (a * fnx.geopotential_pl.sel(pressure = 1000.,).isel(time = int(forecast_in_hours)) - G * ma)
# -*- coding: utf-8 -*-
"""
Created on Thu May  2 19:19:15 2019

@author: Omkar Shidore
https://www.github.com/OmkarShidore
"""
import cv2
import os
import pandas as pd
import csv
from functions import createFolder

#created folder for saving dataset images of user
createFolder('./EmployeeDetails/dataSet')

#creating employee_details
try:
    if os.path.exists('./EmployeeDetails/employee_details.csv'):
        print('Details directory already exists')
    else:
        print("Details directory doesn't Exist")
        with open('./EmployeeDetails/employee_details.csv', 'w') as file:
            writer = csv.writer(file)
            writer.writerow(["Ids", "UserNames", "PhoneNumbers", "EmailIds"])
        print("Creating new directory for employee_details.csv.")
except OSError:
    print("File Already Exists")

cam = cv2.VideoCapture(0)
detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')