#REQUIREMENTS
# ffmpeg
# vosk
# youtube-dl
##

import vosk
import os
import sys
import getopt
from traceback import print_exc
from subprocess import Popen, PIPE
import shlex
import json
from vosk import Model, KaldiRecognizer, SetLogLevel

def main(*argv):

    try:
        #argv = argv[0]
        argv = sys.argv[1:]
        model_path = "./model"
        audio_filename = ""
        youtube_link = ""

        try:

            opts, _ = getopt.getopt(argv, "l:f:m:",
                                        ["link =","file_name =",
                                        "model_path ="])

            #print(opts)
            #print(args)

        except Exception as err:
            print(repr(err))
            raise Exception("Option Error")

        for opt, arg in opts:
            if opt in ['-f', '--audio_filename']:
                audio_filename = arg
            elif opt in ['-m', '--model_path']:
                model_path = arg
            elif opt in ['-l', '--youtube_Link']:
                youtube_link = arg

        if not os.path.exists(model_path):
            print ("Please download the model from https://alphacephei.com/vosk/models and unpack as 'model' in the current folder.")
            raise Exception("Model Cannot Found")

        if(youtube_link != ""):
            audio_filename = get_youtube_audio(youtube_link)

        #TODO
        assert(youtube_link != "" or audio_filename != "") ("Input Error")
        print( "LINK:",youtube_link,"FILE: ", audio_filename, " MODEL: ",model_path)

        SetLogLevel(-1)
        sample_rate=16000
        model = Model(model_path)
        rec = KaldiRecognizer(model, sample_rate)

        process = Popen(['ffmpeg', '-loglevel', 'quiet', '-i',
                                    audio_filename,
                                    '-ar', str(sample_rate) , '-ac', '1', '-f', 's16le', '-'],
                                    stdout=PIPE)

        result = ""
        while True:
            data = process.stdout.read(4000)
            if len(data) == 0:
                break
            if rec.AcceptWaveform(data):
                data = json.loads(rec.Result())
                result += data['text']

        #print(result)
        data = json.loads(rec.FinalResult())
        result += data['text']
        print("\n")
        print(result)

    except Exception as error:
        print("ERROR: {}".format(error))
        print_exc()

def get_youtube_audio(link):
    extension = ".m4a"
    filename = ""
    try:

        command = "youtube-dl --get-filename  -o '%(title)s by %(uploader)s on %(upload_date)s.%(ext)s' " + link
        args = shlex.split(command)
        with Popen(args, stdout=PIPE, stderr=PIPE) as process:
            process.wait()
            for line in process.stdout.readlines():
                temp = line.decode().strip()
                filename = temp[:temp.index('.')]
                filename = filename + extension
                print(filename)

        command = "youtube-dl -x --audio-format m4a " + link + " -o '%(title)s by %(uploader)s on %(upload_date)s.%(ext)s'"
        args = shlex.split(command)
        with Popen(args, stdout=PIPE, stderr=PIPE) as process:

            process.wait()
            error_check = True
            for line in process.stdout.readlines():
                print(line.decode().strip())

            for line in process.stdout.readlines():
                error_check = False
                print(line)

            assert(error_check)
            assert(process.returncode == 0)
            return filename

    except:
        raise Exception("youtube-dl error")

    return filename

if __name__ == '__main__':
    #args = ['-l', 'https://www.youtube.com/watch?v=gt027PfguDQ']
    main()


from django.contrib.auth.models import User
from django.db import models
from django.db.models import Index

class EquipmentType(models.Model):
    """
        Тип оборудования
    """
    name = models.CharField(max_length=255, verbose_name='Type name')
    serial_number_mask = models.CharField(max_length=50, verbose_name='Mask of serial numbers')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Type of equipment'
        verbose_name_plural = 'Type of equipment'
        ordering = ['name']
        indexes = (
            Index(fields=['name'], name='equ_typ__name__idx'),
        )
        constraints = [
            models.UniqueConstraint(
                fields=['name'],
                name='equ_typ__name__unq'
            ),
        ]

class Equipment(models.Model):
    """
        Оборудование
    """
    equipment_type = models.ForeignKey('EquipmentType', on_delete=models.PROTECT, related_name='equipments',
                                       verbose_name='Type of equipment')
    serial_number = models.CharField(max_length=50, verbose_name='Serial number of equipment')
    description = models.TextField(verbose_name='Description of equipment', null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='Created at')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='Updated at')
    is_archived = models.BooleanField(default=False, verbose_name='Is archived')
    created_by = models.ForeignKey(User, on_delete=models.PROTECT, related_name='created_by',
                                   null=True, blank=True, verbose_name='Created by')
    updated_by = models.ForeignKey(User, on_delete=models.PROTECT, related_name='updated_by',
                                   null=True, blank=True, verbose_name='Updated by')

    class Meta:
        verbose_name = 'Equipment'
        verbose_name_plural = 'Equipment'
        ordering = ['id']
        indexes = (
            Index(
                fields=['is_archived', 'equipment_type', 'serial_number'],
                name='equ__type_serial_number__idx'
            ),
        )
        constraints = [
            models.UniqueConstraint(
                fields=['equipment_type', 'serial_number'],
                name='equ__type_serial_number__unq'
            ),
        ]


import requests
from bs4 import BeautifulSoup
import pandas as pd

def extract(page):
    url = f'https://in.indeed.com/jobs?q=python+developer&l=India&start={page}'
    res = requests.get(url)
    # return res.status_code
    soup = BeautifulSoup(res.content, 'html.parser')
    return soup

job_list = []

def transfrom(soup):
    divs = soup.find_all('div', class_='jobsearch-SerpJobCard')

    for i in divs:
        title = i.find('a').text.strip()
        print(title)
        company = i.find('span', class_='company').text.strip()
        print(company)
        summary = i.find(
            'div', class_='summary').text.strip().replace('\n', '')
        print(summary)

        job = {
            'title': title,
            "company": company,
            "summary": summary
        }
        job_list.append(job)

for i in range(0, 50, 10):
    print(f'Getting Page,{i}')

    c = extract(0)
    transfrom(c)

# print(len(job_list))

df = pd.DataFrame(job_list)
print(df.head())
df.to_csv('indeed.csv')


#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3
import random
import datetime
import os

current_file_path = os.path.realpath(__file__)
current_directory_path = os.path.dirname(current_file_path)
resources_directory_path = os.path.join(current_directory_path, '..', 'resources')
db_directory_path = os.path.join(current_directory_path, '..', 'db')

connection = sqlite3.connect(os.path.join(db_directory_path, 'BAS.db'), 300)

cursor = connection.cursor()

import sys

try:
    from Tkinter import *
except ImportError:
    from tkinter import *

import PIL
from PIL import Image
from PIL import ImageTk

from tkcalendar import Calendar, DateEntry

global cart, session_type

cart = []

class Table:

    def __init__(
        self,
        root,
        lst,
        w=16,
        foreg='black',
        backg='white',
        ):
        for i in range(len(lst)):
            for j in range(len(lst[0])):

                self.e = Entry(root, width=w, fg=foreg, bg=backg,
                               font=('Arial', 16))

                self.e.grid(row=i, column=j)
                self.e.insert(END, lst[i][j])

def confirm_update_inventory():
    global confirm_update_inventory_window
    confirm_update_inventory_window = Tk()
    confirm_update_inventory_window.geometry('500x150+300+120')
    confirm_update_inventory_window.title('Confirm Book Update')
    isbn = str(ei1.get())
    name = str(ei2.get())
    auth = str(ei3.get())
    price = str(ei4.get())
    cat = str(ei5.get())
    pub = str(ei6.get())
    number_of_copies = str(ei7.get())
    threshold_number_of_books = str(ei8.get())
    average_days_of_procuring = str(ei9.get())

    if isbn != '' and name != '' and auth != '' and price != '' and cat \
        != '' and pub != '' and number_of_copies != '' \
        and threshold_number_of_books != '' \
        and average_days_of_procuring != '':
        l1 = Label(confirm_update_inventory_window,
                   text='Are you sure you want to update this book?',
                   font=10)
        b1 = Button(confirm_update_inventory_window, text='Yes',
                    width=10, height=3, command=update_book_in_db)
        b2 = Button(confirm_update_inventory_window, text='No',
                    width=10, height=3, command=confbdest)

        l1.place(x=60, y=20)
        b1.place(x=80, y=80)
        b2.place(x=320, y=80)
    else:

        l10 = Label(inv, text='Please enter all details', fg='red',
                    font=10)
        l10.place(x=150, y=440)
        confirm_update_inventory_window.destroy()
        l10.after(3000, lambda : l10.place_forget())

def confbkadd():
    global confirmb
    confirmb = Tk()
    confirmb.geometry('500x150+300+120')
    confirmb.title('Confirm Book')
    isbn = str(ei1.get())
    name = str(ei2.get())
    auth = str(ei3.get())
    price = str(ei4.get())
    cat = str(ei5.get())
    pub = str(ei6.get())
    number_of_copies = str(ei7.get())
    threshold_number_of_books = str(ei8.get())
    average_days_of_procuring = str(ei9.get())

    if isbn != '' and name != '' and auth != '' and price != '' and cat \
        != '' and pub != '' and number_of_copies != '' \
        and threshold_number_of_books != '' \
        and average_days_of_procuring != '':
        l1 = Label(confirmb,
                   text='Are you sure you want to add this book?',
                   font=10)
        b1 = Button(confirmb, text='Yes', width=10, height=3,
                    command=bookadd)
        b2 = Button(confirmb, text='No', width=10, height=3,
                    command=confbdest)

        l1.place(x=60, y=20)
        b1.place(x=80, y=80)
        b2.place(x=320, y=80)
    else:

        l10 = Label(inv, text='Please enter all details', fg='red',
                    font=10)
        l10.place(x=150, y=440)
        confirmb.destroy()
        l10.after(3000, lambda : l10.place_forget())

def confbdest():
    confirmb.destroy()

def update_book_in_db():
    confirm_update_inventory_window.destroy()
    isbn = str(ei1.get())
    name = str(ei2.get())
    auth = str(ei3.get())
    price = float(ei4.get())
    cat = str(ei5.get())
    pub = str(ei6.get())
    number_of_copies = int(ei7.get())
    threshold_number_of_books = int(ei8.get())
    average_days_of_procuring = int(ei9.get())

    vis = Label(update_inventory_window,
                text='Book updated successfully!', font=8)
    vis.place(x=150, y=460)
    vis.after(3000, lambda : vis.place_forget())
    cursor.execute('UPDATE Book SET Book_Name=?, Author=?, Price=?, Category=?, Publisher=?, number_of_copies=?, threshold=?, average_number_of_days_to_procure=?, rack_number=? WHERE Book_ISBN=?'
                   , (
        name,
        auth,
        price,
        cat,
        pub,
        number_of_copies,
        threshold_number_of_books,
        average_days_of_procuring,
        1,
        isbn,
        ))
    connection.commit()
    return

def bookadd():
    confirmb.destroy()
    isbn = str(ei1.get())
    name = str(ei2.get())
    auth = str(ei3.get())
    price = float(ei4.get())
    cat = str(ei5.get())
    pub = str(ei6.get())
    number_of_copies = int(ei7.get())
    threshold_number_of_books = int(ei8.get())
    average_days_of_procuring = int(ei9.get())

    vis = Label(inv, text='Book Added successfully!', font=8)
    vis.place(x=150, y=460)
    vis.after(3000, lambda : vis.place_forget())
    cursor.execute('INSERT INTO Book VALUES (?,?,?,?,?,?,?,?,?,?)', (
        isbn,
        name,
        auth,
        price,
        cat,
        pub,
        number_of_copies,
        threshold_number_of_books,
        average_days_of_procuring,
        1,
        ))
    connection.commit()
    return

def vsrec():

    cursor.execute('SELECT * FROM Sales')
    rows = cursor.fetchall()

    searchres = Tk()
    searchres.geometry('960x640+100+120')
    searchres.title('Sales Records')

    srl = Label(searchres, text='Sales Records:', font=('Sales Records:'
                , 13), bg='Moccasin', fg='black')
    srl.place(x=80, y=40)

    l1 = Label(searchres, text='Sales ID', font=('Sales ID', 10))
    l2 = Label(searchres, text='Customer ID', font=('Customer', 10))
    l3 = Label(searchres, text='Invoice No', font=('Invoice No', 10))
    l4 = Label(searchres, text='Sales Date', font=('Sales Date', 10))
    l5 = Label(searchres, text='Bill Amount', font=('Bill Amount', 10))

    l1.place(x=60, y=80)
    l2.place(x=235, y=80)
    l3.place(x=410, y=80)
    l4.place(x=585, y=80)
    l5.place(x=760, y=80)

    col = 100
    for r in rows:
        row = 60
        for x in r:
            templabel = Label(searchres, text=x, font=(str(x), 8))
            templabel.place(x=row, y=col)
            row = row + 175
        col = col + 15

    return

def update_inventory():
    global update_inventory_window
    update_inventory_window = Tk()
    update_inventory_window.geometry('720x600+500+120')
    update_inventory_window.title('Book Inventory')
    wel = Label(update_inventory_window, text='Update Book', fg='black'
                , bg='Moccasin', font=16)
    global ei1, ei2, ei3, ei4, ei5, ei6, ei7, ei8, ei9
    l1 = Label(update_inventory_window, text='Book ISBN:', font=10)
    l2 = Label(update_inventory_window, text='Book Name:', font=10)
    l3 = Label(update_inventory_window, text='Author:', font=10)
    l4 = Label(update_inventory_window, text='Price:', font=10)
    l5 = Label(update_inventory_window, text='Category:', font=10)
    l6 = Label(update_inventory_window, text='Publisher:', font=10)
    l7 = Label(update_inventory_window, text='Number of copies:',
               font=10)
    l8 = Label(update_inventory_window,
               text='Threshold number of copies:', font=10)
    l9 = Label(update_inventory_window,
               text='Average number of days to procure:', font=10)

    ei1 = Entry(update_inventory_window, font=10, bd=5)
    ei2 = Entry(update_inventory_window, font=10, bd=5)
    ei3 = Entry(update_inventory_window, font=10, bd=5)
    ei4 = Entry(update_inventory_window, font=10, bd=5)
    ei5 = Entry(update_inventory_window, font=10, bd=5)
    ei6 = Entry(update_inventory_window, font=10, bd=5)
    ei7 = Entry(update_inventory_window, font=10, bd=5)
    ei8 = Entry(update_inventory_window, font=10, bd=5)
    ei9 = Entry(update_inventory_window, font=10, bd=5)

    b1 = Button(update_inventory_window, text='Update Book', width=20,
                height=3, command=confirm_update_inventory)
    wel.place(x=150, y=40)
    l1.place(x=70, y=80)
    ei1.place(x=420, y=80)
    l2.place(x=70, y=120)
    ei2.place(x=420, y=120)
    l3.place(x=70, y=160)
    ei3.place(x=420, y=160)
    l4.place(x=70, y=200)
    ei4.place(x=420, y=200)
    l5.place(x=70, y=240)
    ei5.place(x=420, y=240)
    l6.place(x=70, y=280)
    ei6.place(x=420, y=280)
    l7.place(x=70, y=320)
    ei7.place(x=420, y=320)
    l8.place(x=70, y=360)
    ei8.place(x=420, y=360)
    l9.place(x=70, y=400)
    ei9.place(x=420, y=400)
    b1.place(x=150, y=500)
    return

def addinv():
    global inv
    inv = Tk()
    inv.geometry('720x600+500+120')
    inv.title('Book Inventory')
    wel = Label(inv, text='Add New Book', fg='black', bg='Moccasin',
                font=16)
    global ei1, ei2, ei3, ei4, ei5, ei6, ei7, ei8, ei9
    l1 = Label(inv, text='Book ISBN:', font=10)
    l2 = Label(inv, text='Book Name:', font=10)
    l3 = Label(inv, text='Author:', font=10)
    l4 = Label(inv, text='Price:', font=10)
    l5 = Label(inv, text='Category:', font=10)
    l6 = Label(inv, text='Publisher:', font=10)
    l7 = Label(inv, text='Number of copies:', font=10)
    l8 = Label(inv, text='Threshold number of copies:', font=10)
    l9 = Label(inv, text='Average number of days to procure:', font=10)

    ei1 = Entry(inv, font=10, bd=5)
    ei2 = Entry(inv, font=10, bd=5)
    ei3 = Entry(inv, font=10, bd=5)
    ei4 = Entry(inv, font=10, bd=5)
    ei5 = Entry(inv, font=10, bd=5)
    ei6 = Entry(inv, font=10, bd=5)
    ei7 = Entry(inv, font=10, bd=5)
    ei8 = Entry(inv, font=10, bd=5)
    ei9 = Entry(inv, font=10, bd=5)

    b1 = Button(inv, text='Add Book', width=20, height=3,
                command=confbkadd)
    wel.place(x=150, y=40)
    l1.place(x=70, y=80)
    ei1.place(x=420, y=80)
    l2.place(x=70, y=120)
    ei2.place(x=420, y=120)
    l3.place(x=70, y=160)
    ei3.place(x=420, y=160)
    l4.place(x=70, y=200)
    ei4.place(x=420, y=200)
    l5.place(x=70, y=240)
    ei5.place(x=420, y=240)
    l6.place(x=70, y=280)
    ei6.place(x=420, y=280)
    l7.place(x=70, y=320)
    ei7.place(x=420, y=320)
    l8.place(x=70, y=360)
    ei8.place(x=420, y=360)
    l9.place(x=70, y=400)
    ei9.place(x=420, y=400)
    b1.place(x=150, y=500)
    return

def viewpur():
    cursor.execute('SELECT * FROM Purchase')
    rows = cursor.fetchall()

    searchres = Tk()
    searchres.geometry('840x640+100+120')
    searchres.title('Purchase Records')

    srl = Label(searchres, text='Purchase Records:',
                font=('Purchase Records:', 13), bg='Moccasin',
                fg='black')
    srl.place(x=80, y=40)

    l1 = Label(searchres, text='Purchase ID', font=('Sales ID', 10))
    l2 = Label(searchres, text='Supplier ID', font=('Customer', 10))
    l3 = Label(searchres, text='Purchase Date', font=('Invoice No', 10))
    l4 = Label(searchres, text='Amount Paid', font=('Sales Date', 10))

    l1.place(x=40, y=80)
    l2.place(x=240, y=80)
    l3.place(x=440, y=80)
    l4.place(x=640, y=80)

    col = 100
    for r in rows:
        row = 40
        for x in r:
            templabel = Label(searchres, text=x, font=(str(x), 8))
            templabel.place(x=row, y=col)
            row = row + 200
        col = col + 15

    return

def puradd():
    confirmp.destroy()
    purid = str('pur' + str(random.randint(150, 1000000)))
    supid = str(ep2.get())
    now = datetime.datetime.now()
    date = now.strftime('%Y-%m-%d')
    price = float(ep6.get())

    vis = Label(pur, text='Purchase Added successfully!', font=8)
    vis.place(x=150, y=460)
    vis.after(3000, lambda : vis.place_forget())
    cursor.execute('INSERT INTO Purchase VALUES (?,?,?,?)', (purid,
                   supid, date, price))
    connection.commit()
    return

def confpur():
    global confirmp
    confirmp = Tk()
    confirmp.geometry('500x150+300+120')
    confirmp.title('Confirm Purchase')
    supid = str(ep2.get())
    price = str(ep6.get())

    if supid != '' and price != '':
        l1 = Label(confirmp,
                   text='Are you sure you want to add this purchase?',
                   font=10)
        b1 = Button(confirmp, text='Yes', width=10, height=3,
                    command=puradd)
        b2 = Button(confirmp, text='No', width=10, height=3,
                    command=confdest)

        l1.place(x=40, y=20)
        b1.place(x=80, y=80)
        b2.place(x=320, y=80)
    else:
        l2 = Label(pur, text='Please enter all details', font=10,
                   fg='red')
        l2.place(x=200, y=430)
        l2.after(3000, lambda : l2.place_forget())
        confdest()

def confdest():
    confirmp.destroy()

def addpur():
    global pur
    pur = Tk()
    pur.geometry('640x400+500+120')
    pur.title('Book Purchase')
    wel = Label(pur, text='New Book Purchase from Suplier', fg='black',
                font=16)
    global ep1, ep2, ep3, ep4, ep5, ep6

    l2 = Label(pur, text='Supplier ID:', font=10)
    l7 = Label(pur, text='Price:', font=10)

    ep2 = Entry(pur, font=10, bd=5)
    ep6 = Entry(pur, font=10, bd=5)

    b1 = Button(
        pur,
        text='Add Purchase Record',
        width=30,
        height=3,
        bg='lightgreen',
        command=confpur,
        )
    b2 = Button(
        pur,
        text='Find supplier ID',
        width=30,
        height=3,
        bg='lightblue',
        command=search_supplier,
        )

    wel.place(x=150, y=40)

    l2.place(x=70, y=100)
    ep2.place(x=230, y=100)
    l7.place(x=70, y=190)
    ep6.place(x=230, y=190)

    b2.place(x=60, y=250)
    b1.place(x=360, y=250)
    return

def reqadd():
    confirmr.destroy()
    book = str(cb1.get())
    auth = str(ca1.get())

    vis = Label(request, text='Request made successfully!', font=8)
    vis.place(x=150, y=460)
    vis.after(3000, lambda : vis.place_forget())
    cursor.execute('INSERT INTO Request VALUES (?,?)', (book, auth))
    connection.commit()
    return

def confreqdest():
    confirmr.destroy()

def confreq():
    global confirmr
    confirmr = Tk()
    confirmr.geometry('500x150+300+120')
    confirmr.title('Confirm Request')

    l1 = Label(confirmr,
               text='Are you sure you want to request this book?',
               font=10)
    b1 = Button(confirmr, text='Yes', width=10, height=3,
                command=reqadd)
    b2 = Button(confirmr, text='No', width=10, height=3,
                command=confreqdest)

    l1.place(x=40, y=20)
    b1.place(x=80, y=80)
    b2.place(x=320, y=80)

def cusreq():
    global cb1, ca1
    global request
    request = Tk()
    request.geometry('640x480+700+120')
    request.title('Request Book')
    disp = Label(request, text='Request your book here:', fg='black',
                 bg='Moccasin', font=12)
    disp.place(x=200, y=70)
    sl1 = Label(request, text='Book Title:', font=('Book Title:', 10))
    cb1 = Entry(request, font=10, bd=5)

    sl2 = Label(request, text='Author:', font=('Author:', 10))
    ca1 = Entry(request, font=10, bd=5)

    sl1.place(x=100, y=140)
    cb1.place(x=210, y=140)

    sl2.place(x=100, y=220)
    ca1.place(x=210, y=220)

    sb = Button(request, text='Request Book', width=20, height=2,
                command=confreq)
    sb.place(x=210, y=300)
    return

def logoutadm():
    session_type = 0
    admpg.destroy()
    return

def getbooksunderthreshold():
    threshold = Tk()
    threshold.geometry('1000x600+700+120')
    threshold.title('Book threshold')
    cursor.execute('SELECT Book_ISBN, Book_Name, number_of_copies, Price, Publisher FROM Book b WHERE b.number_of_copies <= b.threshold'
                   )
    rows = cursor.fetchall()

    srl = Label(threshold, text='Books below or at threshold level',
                font=('Customer Book threshold:', 12), bg='Moccasin',
                fg='black')
    srl.place(x=80, y=40)

    l1 = Label(threshold, text='ISBN', font=('Sales ID', 10))
    l2 = Label(threshold, text='Name', font=('Customer', 10))
    l3 = Label(threshold, text='Number of copies', font=('Customer',
               10))
    l4 = Label(threshold, text='Price', font=('Customer', 10))
    l5 = Label(threshold, text='Publisher', font=('Customer', 10))

    l1.place(x=60, y=80)
    l2.place(x=210, y=80)
    l3.place(x=430, y=80)
    l4.place(x=580, y=80)
    l5.place(x=730, y=80)

    col = 100
    ix = 0
    for r in rows:
        row = 60
        ix = 0
        for x in r:
            extend = 220
            if not ix or ix == 3 or ix == 2:
                extend = 150
            templabel = Label(threshold, text=x, font=(str(x), 8))
            templabel.place(x=row, y=col)
            row = row + extend
            ix += 1

        col = col + 15

    return

def show_sales_statistics():
    sales_statistics_selection_window = Tk()
    sales_statistics_selection_window.geometry('800x640+500+200')
    sales_statistics_selection_window.title('Sales statistics selection'
            )

    global calfrom, calto
    calfrom = DateEntry(sales_statistics_selection_window,
                        selectmode='day', year=2022, month=4, day=12)
    calto = DateEntry(sales_statistics_selection_window,
                      selectmode='day', year=2022, month=4, day=14)

    calfrom.pack(pady=10)
    calto.pack(pady=40)

    l1 = Label(sales_statistics_selection_window, text='From date',
               font=('Times New Roman', 10))
    l2 = Label(sales_statistics_selection_window, text='To date',
               font=('Times New Roman', 10))

    l1.place(x=80, y=20)
    l2.place(x=80, y=80)

    Button(sales_statistics_selection_window,
           text='Get statistics for this period',
           command=sales_statistics).pack(pady=10)

    return

def parse_date(d):
    i = 0
    ch = d[i]
    day = ''
    month = ''
    year = ''

    while ch != '/':
        day += ch
        i += 1
        ch = d[i]

    if len(day) < 2:
        day = '0' + day

    i += 1
    while ch != '/':
        month += ch
        i += 1
        ch = d[i]

    if len(month) < 2:
        month = '0' + month

    i += 1
    while ch != '/':
        year += ch
        i += 1
        ch = d[i]

    return (int(day), int(month), int(year))

def sales_statistics():
    sales_statistics_window = Tk()
    sales_statistics_window.geometry('1280x700+500+200')
    sales_statistics_window.title('Sales statistics')

    lst2 = []
    lst2.append((
        'ISBN',
        'Name',
        'Price',
        'Publisher',
        'Copies sold',
        'Total revenue',
        ))
    from_date = calfrom.get_date()
    to_date = calto.get_date()

    cursor.execute('SELECT isbn, quantity from book_sales WHERE time_of_sale >= ? AND time_of_sale <= ?'
                   , (from_date.strftime('%Y-%m-%d'),
                   to_date.strftime('%Y-%m-%d')))

    sales_rows = cursor.fetchall()

    ctr = 1
    stats = {}
    for i in sales_rows:
        cursor.execute('SELECT Book_Name, Price, Publisher FROM Book b WHERE Book_ISBN = ?'
                       , (i[0], ))
        book_rows = cursor.fetchall()
        if len(book_rows) > 0:
            if not stats.has_key(i[0]):
                stats[i[0]] = {}
                stats[i[0]]['isbn'] = i[0]
                stats[i[0]]['name'] = book_rows[0][0]
                stats[i[0]]['price'] = book_rows[0][1]
                stats[i[0]]['quantity'] = i[1]
                stats[i[0]]['publisher'] = book_rows[0][2]
            else:
                stats[i[0]]['quantity'] += i[1]

    for s in stats:
        lst2.append((
            s,
            stats[s]['name'],
            str(stats[s]['price']),
            stats[s]['publisher'],
            str(stats[s]['quantity']),
            str(stats[s]['quantity'] * stats[s]['price']),
            ))

    tbl = Table(sales_statistics_window, lst2)
    return

def show_not_in_stock_books():
    show_not_in_stock_window = Tk()
    show_not_in_stock_window.geometry('1280x700+500+200')
    show_not_in_stock_window.title('Not in stock books')

    lst2 = []
    lst2.append(('ISBN', 'Name', 'Price', 'Publisher', 'Query count'))

    cursor.execute('SELECT * FROM not_in_stock')
    not_in_stock_rows = cursor.fetchall()

    ctr = 1
    for s in not_in_stock_rows:
        cursor.execute('SELECT Book_Name, Price, Publisher FROM Book b WHERE Book_ISBN = ?'
                       , (s[0], ))
        book_rows = cursor.fetchall()
        if len(book_rows) > 0:
            lst2.append((s[0], book_rows[0][0], book_rows[0][1],
                        book_rows[0][2], s[1]))

    tbl = Table(show_not_in_stock_window, lst2)
    return

def adminpage():
    global admpg
    user = str(ea1.get())
    pasw = str(ea2.get())

    cursor.execute('SELECT Login_ID,Password,Admin_ID,position FROM Admin'
                   )
    rows = cursor.fetchall()
    flag = 0

    for r in rows:
        if user == r[0] and pasw == r[1]:
            session_type = r[3]
            var = Label(adm, text='Login Successful',
                        font=('Login Successful', 18), fg='green')
            var.place(x=150, y=400)
            adm.destroy()
            admpg = Tk()
            admpg.geometry('840x640+500+120')
            admpg.title('Administration Portal')
            var = 'Welcome  ' + r[2] + '!'
            l1 = Label(admpg, text=var, fg='black', bg='Moccasin',
                       font=(var, 16))
            l1.place(x=200, y=50)

            b = Button(
                admpg,
                text='Log Out',
                fg='blue',
                width=5,
                height=1,
                command=logoutadm,
                )
            b.place(x=600, y=50)

            if session_type == 1 or session_type == 2 or session_type \
                == 3:
                b2 = Button(admpg, text='Add to inventory', width=20,
                            height=3, command=addinv)
                b2.place(x=100, y=100)

            if session_type == 2 or session_type == 3 or session_type \
                == 1:
                b7 = Button(admpg, text='Update inventory', width=20,
                            height=3, command=update_inventory)
                b7.place(x=340, y=100)

            if session_type == 2 or session_type == 1 or session_type \
                == 3:
                b8 = Button(admpg, text='Create Order', width=20,
                            height=3, command=porder)
                b8.place(x=100, y=250)

            if session_type == 2 or session_type == 3:
                b1 = Button(admpg, text='View Sales Record', width=20,
                            height=3, command=vsrec)
                b1.place(x=340, y=250)

            if session_type == 2 or session_type == 3:
                b3 = Button(admpg, text='View Purchase Record',
                            width=25, height=3, command=viewpur)
                b3.place(x=100, y=400)

            if session_type == 2 or session_type == 3:
                b4 = Button(admpg, text='Add Purchase Record',
                            width=25, height=3, command=addpur)
                b4.place(x=340, y=400)

            if session_type == 2 or session_type == 3:
                b5 = Button(admpg, text='Customer Requests', width=20,
                            height=3, command=request)
                b5.place(x=100, y=550)

            if session_type == 3:
                b6 = Button(admpg, text='Books under threshold',
                            width=25, height=3,
                            command=getbooksunderthreshold)
                b6.place(x=340, y=550)

            if session_type == 3:
                b9 = Button(admpg, text='Sales Statistics', width=25,
                            height=3, command=show_sales_statistics)
                b9.place(x=580, y=400)

            if session_type == 3:
                b10 = Button(admpg, text='Not in stock books',
                             width=25, height=3,
                             command=show_not_in_stock_books)
                b10.place(x=580, y=250)

            b11 = Button(admpg, text='Search books', width=25,
                         height=3, command=sbook)
            b11.place(x=580, y=100)

            flag = 1

    if flag == 0:
        var = Label(adm, text='Incorrect Username/Password',
                    font=('Incorrect Username/Password', 10), fg='black'
                    )
        var.place(x=150, y=420)
    return

def spacesearch(x):
    if x == 0:
        return 90
    elif x == 1:
        return 276
    elif x == 2:
        return 216
    elif x == 3:
        return 90
    elif x == 4:
        return 168
    elif x == 5:
        return 0

def spacesearch2(x):
    if x == 0:
        return 110
    elif x == 1:
        return 275
    elif x == 2:
        return 210
    elif x == 3:
        return 300
    elif x == 4:
        return 180

def sbookfun():
    var1 = str(se1.get())

    bname = '%' + var1 + '%'
    bname = bname.lower()

    var2 = str(se2.get())
    auth = '%' + var2 + '%'
    auth = auth.lower()

    var3 = str(se3.get())
    cat = '%' + var3 + '%'
    cat = cat.lower()

    cursor.execute('SELECT * FROM Book WHERE LOWER(Book_Name) LIKE ? AND LOWER(Author) LIKE ? AND LOWER(Category) LIKE ?'
                   , (bname, auth, cat))

    rows = cursor.fetchall()

    searchres = Tk()
    searchres.geometry('1280x640+100+120')
    searchres.title('Search Results')

    srl = Label(searchres, text='Search Results:',
                font=('Search Results:', 14), bg='Moccasin', fg='black')
    srl.place(x=80, y=40)

    global search_results_list, books

    scroll_bar = Scrollbar(searchres)

    scroll_bar.pack(side=RIGHT, fill=Y)

    search_results_list = Listbox(searchres,
                                  yscrollcommand=scroll_bar.set,
                                  width=60, selectmode=SINGLE, height=5)

    for r in rows:
        search_results_list.insert(END, str(r[1]) + ' by ' + str(r[2])
                                   + ' at INR ' + str(r[3]) + ' ISBN: '
                                   + str(r[0]))

    search_results_list.pack(side=LEFT, fill=BOTH)

    scroll_bar.config(command=search_results_list.yview)

    books = []
    books.append((
        'ISBN',
        'Name',
        'Author',
        'Price',
        'Category',
        'Publisher',
        'Number of Copies',
        'Rack Number',
        ))
    for r in rows:
        books.append((
            r[0],
            r[1],
            r[2],
            r[3],
            r[4],
            r[5],
            r[6],
            r[9] or 1,
            ))

    if len(rows) > 0:
        sb = Button(searchres, text='View selected book', width=25,
                    height=2, command=view_book_window_fun)
        sb.place(x=800, y=350)

    return

def view_book_window_fun():
    global view_book_window
    view_book_window = Tk()
    view_book_window.geometry('1280x640+500+120')
    view_book_window.title('View Book')

    book = books[search_results_list.curselection()[0] + 1]
    isbn = book[0]

    lst = []
    lst.append(books[0])
    for b in books:
        if b[0] == isbn:
            lst.append(b)
            break

    if book[6] <= 0:
        cursor.execute('SELECT count(*) from `not_in_stock` WHERE ISBN = ?'
                       , (isbn, ))
        count = cursor.fetchall()

        if count[0][0] > 0:
            cursor.execute('UPDATE `not_in_stock` SET count = ((SELECT count FROM `not_in_stock` WHERE ISBN = ?) + 1) WHERE ISBN = ?'
                           , (isbn, isbn))
            connection.commit()
        else:
            cursor.execute('INSERT INTO `not_in_stock` VALUES (?,?)',
                           (isbn, 1))
            connection.commit()

    tbl = Table(view_book_window, lst, w=14)

def sbook():
    global se1, se2, se3
    searchbk = Tk()
    searchbk.geometry('640x480+700+120')
    searchbk.title('Search Book')
    disp = Label(searchbk, text='Enter keywords for search', fg='black'
                 , bg='Moccasin', font=12)
    disp.place(x=200, y=70)
    sl1 = Label(searchbk, text='Book Title:', font=('Book Title:', 10))
    se1 = Entry(searchbk, font=10, bd=5)

    sl2 = Label(searchbk, text='Author:', font=('Author:', 10))
    se2 = Entry(searchbk, font=10, bd=5)

    sl3 = Label(searchbk, text='Genre:', font=('Category:', 10))
    se3 = Entry(searchbk, font=10, bd=5)

    sl1.place(x=100, y=140)
    se1.place(x=210, y=140)

    sl2.place(x=100, y=220)
    se2.place(x=210, y=220)

    sl3.place(x=100, y=300)
    se3.place(x=210, y=300)

    sb = Button(searchbk, text='Search Available Books', width=25,
                height=2, command=sbookfun)
    sb.place(x=210, y=350)

    sl4 = Label(searchbk, text="Can't find the book you're looking for?"
                , font=("Can't find the book you're looking for?", 10),
                fg='blue')
    sb1 = Button(
        searchbk,
        text='Click Here',
        fg='blue',
        width=10,
        height=2,
        command=cusreq,
        )

    sl4.place(x=100, y=420)
    sb1.place(x=390, y=410)
    return

def add_supplier_to_db():
    confirmsup.destroy()
    isbn = str(supei1.get())
    name = str(supei2.get())
    auth = str(supei3.get())
    price = str(supei4.get())

    vis = Label(add_supplier_window, text='Supplier added successfully!'
                , font=8)
    vis.place(x=150, y=460)
    vis.after(3000, lambda : vis.place_forget())
    cursor.execute('INSERT INTO Supplier VALUES (?,?,?,?,?)', ('sup'
                   + str(random.randint(300, 10000)), isbn, name, auth,
                   price))
    connection.commit()
    return

def destroy_confirm_add_supplier():
    confirmsup.destroy()

def confirm_add_supplier():
    global confirmsup
    confirmsup = Tk()
    confirmsup.geometry('500x150+300+120')
    confirmsup.title('Confirm Supplier')
    isbn = str(supei1.get())
    name = str(supei2.get())
    auth = str(supei3.get())
    price = str(supei4.get())

    if isbn != '' and name != '' and auth != '' and price != '':
        l1 = Label(confirmsup,
                   text='Are you sure you want to add this book?',
                   font=10)
        b1 = Button(confirmsup, text='Yes', width=10, height=3,
                    command=add_supplier_to_db)
        b2 = Button(confirmsup, text='No', width=10, height=3,
                    command=destroy_confirm_add_supplier)

        l1.place(x=60, y=20)
        b1.place(x=80, y=80)
        b2.place(x=320, y=80)
    else:

        l10 = Label(add_supplier_window, text='Please enter all details'
                    , fg='red', font=10)
        l10.place(x=150, y=440)
        confirmsup.destroy()
        l10.after(3000, lambda : l10.place_forget())

def add_supplier():
    global add_supplier_window
    add_supplier_window = Tk()
    add_supplier_window.geometry('720x600+500+120')
    add_supplier_window.title('Book Inventory')
    wel = Label(add_supplier_window, text='Add New Supplier', fg='black'
                , bg='Moccasin', font=16)
    global supei1, supei2, supei3, supei4
    supl1 = Label(add_supplier_window, text='Supplier Name:', font=10)
    supl2 = Label(add_supplier_window, text='Publication:', font=10)
    supl3 = Label(add_supplier_window, text='Email:', font=10)
    supl4 = Label(add_supplier_window, text='Phone:', font=10)

    supei1 = Entry(add_supplier_window, font=10, bd=5)
    supei2 = Entry(add_supplier_window, font=10, bd=5)
    supei3 = Entry(add_supplier_window, font=10, bd=5)
    supei4 = Entry(add_supplier_window, font=10, bd=5)

    b1 = Button(add_supplier_window, text='Add Supplier', width=20,
                height=3, command=confirm_add_supplier)
    wel.place(x=150, y=40)
    supl1.place(x=70, y=80)
    supei1.place(x=420, y=80)
    supl2.place(x=70, y=120)
    supei2.place(x=420, y=120)
    supl3.place(x=70, y=160)
    supei3.place(x=420, y=160)
    supl4.place(x=70, y=200)
    supei4.place(x=420, y=200)
    b1.place(x=150, y=500)
    return

def search_supplier_access():
    var1 = str(sse2.get())
    bname = '%' + var1 + '%'
    bname = bname.lower()

    cursor.execute('SELECT * FROM Supplier WHERE LOWER(Supplier_Name) LIKE ? OR LOWER(Publication) LIKE ? OR LOWER(Email_ID) LIKE ?'
                   , (bname, bname, bname))
    rows = cursor.fetchall()

    searchres = Tk()
    searchres.geometry('1280x640+100+120')
    searchres.title('Search Results')

    srl = Label(searchres, text='Search Results:',
                font=('Search Results:', 13), bg='Moccasin', fg='black')
    srl.place(x=80, y=40)

    l1 = Label(searchres, text='Supplier_ID', font=('ISBN', 12))
    l2 = Label(searchres, text='Supplier_Name', font=('Name', 12))
    l3 = Label(searchres, text='Publication', font=('Author', 12))
    l4 = Label(searchres, text='Email_ID', font=('Price', 12))
    l5 = Label(searchres, text='Phone_No', font=('Category', 12))

    l1.place(x=65, y=80)
    l2.place(x=175, y=80)
    l3.place(x=450, y=80)
    l4.place(x=660, y=80)
    l5.place(x=960, y=80)

    col = 100
    for r in rows:
        row = 65
        for x in range(len(r)):
            templabel = Label(searchres, text=r[x], font=(str(r[x]),
                              10))
            templabel.place(x=row, y=col)
            row = row + spacesearch2(x)
        col = col + 40

    return

def search_supplier():
    global sse2
    search_supplier_window = Tk()
    search_supplier_window.geometry('640x480+700+120')
    search_supplier_window.title('Search Suppliers')
    disp = Label(search_supplier_window,
                 text='Enter name or address of supplier', fg='black',
                 bg='Moccasin', font=12)
    disp.place(x=200, y=70)
    sl2 = Label(search_supplier_window, text='Supplier: ',
                font=('Book Title:', 10))
    sse2 = Entry(search_supplier_window, font=10, bd=5)

    sl2.place(x=100, y=220)
    sse2.place(x=210, y=220)

    sb = Button(search_supplier_window,
                text='Search Available Suppliers', width=25, height=2,
                command=search_supplier_access)
    sb.place(x=210, y=350)

    sl4 = Label(search_supplier_window,
                text="Can't find the supplier you're looking for?",
                font=("Can't find the book you're looking for?", 10),
                fg='blue')
    sb1 = Button(
        search_supplier_window,
        text='Add one',
        fg='blue',
        width=10,
        height=2,
        command=add_supplier,
        )

    sl4.place(x=100, y=420)
    sb1.place(x=390, y=410)
    return

def salord():
    salid = 'sal' + str(random.randint(1, 10000))
    cusid = str(epo2.get())
    invo = random.randint(800, 1000000)
    now = datetime.datetime.now()
    date = now.strftime('%Y-%m-%d')
    isbn = str(epo1.get())

    cursor.execute('INSERT INTO Sales VALUES(?,?,?,?,?)', (salid,
                   cusid, invo, date, pri))
    connection.commit()

    for book in cart:
        cursor.execute('UPDATE Book SET number_of_copies=((SELECT number_of_copies FROM Book WHERE Book_ISBN=?)-1) WHERE Book_ISBN=?'
                       , (book, book))
        connection.commit()

    new_cart = {}

    for j in cart_books:
        i = j[0]
        if not new_cart.has_key(i[0]):
            new_cart[i[0]] = {}
            new_cart[i[0]]['isbn'] = i[0]
            new_cart[i[0]]['name'] = i[1]
            new_cart[i[0]]['price'] = i[2]
            new_cart[i[0]]['quantity'] = 1
        else:
            new_cart[i[0]]['quantity'] += 1

    for item in new_cart:
        cursor.execute('INSERT INTO book_sales (customer_id, isbn, sales_id, quantity, time_of_sale) VALUES(?,?,?,?,?)'
                       , (cusid, isbn, salid, new_cart[isbn]['quantity'
                       ], date))
        connection.commit()

    check.destroy()
    confirmch.destroy()
    show = Label(pord, text='Order placed successfully', font=8)
    show.place(x=100, y=320)
    show.after(3000, lambda : show.place_forget())

    show_sale_receipt(salid, new_cart)

    return

def show_sale_receipt(sale_id, new_cart):
    sale_receipt_window = Tk()
    sale_receipt_window.geometry('1024x700+500+200')
    sale_receipt_window.title('Receipt')

    lst2 = []
    lst2.append(('Sr No.', 'Book', 'Price', 'Quantity', 'Total Amount'))

    ctr = 1
    for book in new_cart:
        lst2.append((ctr, new_cart[book]['name'], new_cart[book]['price'
                    ], str(new_cart[book]['quantity']),
                    str(new_cart[book]['quantity']
                    * new_cart[book]['price'])))
        ctr += 1

    tbl = Table(sale_receipt_window, lst2)
    return

def delbook(pri, book, p):
    cart.remove(book)
    pri = pri - p
    check.destroy()
    viewcart()
    return

def cartdest():
    check.destroy()
    return

def space(x):
    if x == 0:
        return 100
    elif x == 1:
        return 400
    else:
        return 50

def confchdest():
    confirmch.destroy()
    return

def confcheck():
    global confirmch
    confirmch = Tk()
    confirmch.geometry('500x150+500+120')
    confirmch.title('Confirm Checkout')

    l1 = Label(confirmch, text='Are you sure you want to checkout?',
               font=10)
    b1 = Button(confirmch, text='Yes', width=10, height=3,
                command=salord)
    b2 = Button(confirmch, text='No', width=10, height=3,
                command=confchdest)

    l1.place(x=60, y=20)
    b1.place(x=80, y=80)
    b2.place(x=320, y=80)

def viewcart():
    global pri
    pri = 0
    global check
    check = Tk()
    check.geometry('840x700+500+200')
    check.title('View Bill')
    disp = Label(check, text='This Bill:', fg='black', bg='Moccasin',
                 font=('Times New Roman', 20))
    disp.place(x=130, y=70)

    backButton = Button(check, text='<-- Back', width=6, height=2,
                        command=cartdest)
    backButton.place(x=20, y=40)

    l1 = Label(check, text='ISBN', font=('ISBN', 15))
    l2 = Label(check, text='Title', font=('Title', 15))
    l3 = Label(check, text='Price', font=('Price', 15))

    l1.place(x=100, y=120)
    l2.place(x=200, y=120)
    l3.place(x=600, y=120)
    col = 170
    global cart_books
    cart_books = []
    for book in cart:
        cursor.execute('SELECT Book_ISBN,Book_Name,Price from Book where Book_ISBN=?'
                       , (book, ))
        rows = cursor.fetchall()
        for r in rows:
            row = 100
            cart_books.append(rows)
            for x in range(len(r)):
                templabel = Label(check, text=r[x], font=(str(r[x]),
                                  13))
                templabel.place(x=row, y=col)
                row = row + space(x)
            pri = pri + float(r[2])
        col = col + 40

    tempButton = Button(check, text='Remove', width=6, height=1,
                        command=lambda : delbook(pri, book, r[2]))
    tempButton.place(x=row + 40, y=col - 40)

    l4 = Label(check, text='Bill Amount : ', font=('Bill Amount : ',
               12))
    l5 = Label(check, text=str(pri), font=(str(pri), 12))
    l4.place(x=450, y=500)
    l5.place(x=600, y=500)
    checkButton = Button(check, text='Checkout', width=6, height=1,
                         command=confcheck)
    checkButton.place(x=400, y=600)
    return

def addtocart():
    global cart

    isbn = str(epo1.get())
    username2 = str(epo2.get())
    if isbn == '' or username2 == '':
        l2 = Label(pord, text='Please enter the ISBN', font=8)
        l2.place(x=100, y=320)
        l2.after(3000, lambda : l2.place_forget())
        return

    cursor.execute('SELECT * FROM Book where Book_ISBN=?', (isbn, ))
    rows = cursor.fetchall()
    if len(rows) == 0 or rows[0][6] <= 0:
        l1 = Label(pord, text='Book not in stock!', font=8)
        l1.place(x=130, y=320)
        l1.after(3000, lambda : l1.place_forget())
    else:
        cart.append(isbn)
        l3 = Label(pord, text='Added to Bill!', font=8)
        l3.place(x=140, y=320)
        l3.after(3000, lambda : l3.place_forget())

    return

def porder():
    global pord
    pord = Tk()
    pord.geometry('640x360+500+200')
    pord.title('Order')
    disp = Label(pord, text='Book Order', fg='black', bg='Moccasin',
                 font=12)
    disp.place(x=130, y=70)

    l1 = Label(pord, text='ISBN:', font=10)
    l3 = Label(pord, text='Customer username:', font=10)
    l2 = Label(pord, text='Want to know ISBN of book?',
               font=('Want to know ISBN of Book?', 10))

    global epo1, epo2
    epo1 = Entry(pord, font=10, bd=5, width=10)
    epo2 = Entry(pord, font=10, bd=5, width=10)

    b1 = Button(
        pord,
        text='Click here',
        fg='blue',
        width=6,
        height=1,
        command=sbook,
        )
    b2 = Button(pord, text='Add To Bill', width=14, height=2,
                command=addtocart)
    b3 = Button(pord, text='View Items in Bill', width=14, height=2,
                command=viewcart)

    l1.place(x=40, y=120)
    epo1.place(x=250, y=120)
    l3.place(x=40, y=180)
    epo2.place(x=250, y=180)
    l2.place(x=40, y=240)
    b1.place(x=230, y=240)
    b2.place(x=40, y=290)
    b3.place(x=250, y=290)
    return

def viewcomporder():

    cursor.execute('SELECT Sales_ID,Invoice_no,S_Date,Bill_Amount FROM Sales WHERE Customer_ID=?'
                   , (userc, ))
    rows = cursor.fetchall()

    searchres = Tk()
    searchres.geometry('840x640+100+120')
    searchres.title('Completed Orders')

    srl = Label(searchres, text='Completed Orders:',
                font=('Completed Orders:', 13), bg='Moccasin',
                fg='black')
    srl.place(x=80, y=40)

    l1 = Label(searchres, text='Sales ID', font=('Sales ID', 10))
    l2 = Label(searchres, text='Invoice Number', font=('Invoice Number'
               , 10))
    l3 = Label(searchres, text='Sales Date', font=('Sales Date', 10))
    l4 = Label(searchres, text='Bill Amount', font=('Bill Amount', 10))

    l1.place(x=40, y=80)
    l2.place(x=240, y=80)
    l3.place(x=440, y=80)
    l4.place(x=640, y=80)

    col = 100
    for r in rows:
        row = 40
        for x in r:
            templabel = Label(searchres, text=x, font=(str(x), 8))
            templabel.place(x=row, y=col)
            row = row + 200
        col = col + 15

    return

def request():
    requests = Tk()
    requests.geometry('640x480+700+120')
    requests.title('Book Requests')
    cursor.execute('SELECT * FROM Request')
    rows = cursor.fetchall()

    srl = Label(requests, text='Customer Book Requests:',
                font=('Customer Book Requests:', 13), bg='Moccasin',
                fg='black')
    srl.place(x=80, y=40)

    l1 = Label(requests, text='Book Name', font=('Sales ID', 10))
    l2 = Label(requests, text='Author', font=('Customer', 10))

    l1.place(x=60, y=80)
    l2.place(x=235, y=80)

    col = 100
    for r in rows:
        row = 60
        for x in r:
            templabel = Label(requests, text=x, font=(str(x), 8))
            templabel.place(x=row, y=col)
            row = row + 175
        col = col + 15

    return

def logoutcust():
    cuspg.destroy()
    return

def custpage():
    global userc
    global cuspg

    userc = str(ec1.get())
    paswc = str(ec2.get())

    cursor.execute('SELECT Customer_ID,Password,Customer_Name FROM Customer'
                   )
    rows = cursor.fetchall()
    flag = 0
    for r in rows:
        if userc == r[0] and paswc == r[1]:
            var = Label(cust, text='Login Successful',
                        font=('Login Successful', 18), fg='green')
            var.place(x=150, y=400)
            cust.destroy()
            cuspg = Tk()
            cuspg.geometry('640x480+500+120')
            cuspg.title('CustPage')
            var = 'WELCOME ' + r[2] + '!'

            l1 = Label(cuspg, text=var, fg='black', bg='Moccasin',
                       font=(var, 16))
            l1.place(x=160, y=50)

            b = Button(
                cuspg,
                text='Log Out',
                fg='blue',
                width=5,
                height=1,
                command=logoutcust,
                )
            b.place(x=540, y=50)

            b1 = Button(cuspg, text='Search Books', width=20, height=3,
                        command=sbook)
            b1.place(x=100, y=150)

            b3 = Button(cuspg, text='View Completed Orders', width=20,
                        height=3, command=viewcomporder)
            b3.place(x=100, y=300)

            b4 = Button(cuspg, text='Request', width=20, height=3,
                        command=cusreq)
            b4.place(x=400, y=150)
            flag = 1
    if flag == 0:
        var = Label(cust, text='Incorrect Username/Password',
                    font=('Incorrect Username/Password', 10), fg='black'
                    )
        var.place(x=150, y=400)

def admin():
    global adm
    adm = Tk()
    adm.geometry('480x480+500+120')
    adm.title('Admin')

    disa1 = Label(adm, text='Admin ID', font=('Admin ID', 10))
    disa2 = Label(adm, text='Password', font=('Password', 10))
    ba1 = Button(adm, text='Login', width=5, height=2,
                 command=adminpage)
    disa3 = Label(adm, text='Welcome Admin', fg='black', bg='Moccasin',
                  font=('Welcome Admin', 16))
    global ea1
    ea1 = Entry(adm, font=10, bd=5)
    global ea2
    ea2 = Entry(adm, font=10, bd=5, show='*')
    disa3.place(x=150, y=100)
    disa1.place(x=70, y=230)
    disa2.place(x=70, y=290)
    ba1.place(x=200, y=370)
    ea1.place(x=150, y=230)
    ea2.place(x=150, y=290)
    return

def customer():
    global cust
    cust = Tk()
    cust.geometry('480x480+500+120')
    cust.title('Customer')
    global ec1
    global ec2
    disc1 = Label(cust, text='Customer ID', font=('Customer ID', 10))
    disc2 = Label(cust, text='Password', font=('Password', 10))
    bc1 = Button(cust, text='Login', width=5, height=2,
                 command=custpage)
    disc3 = Label(cust, text='Welcome Customer', fg='black',
                  bg='Moccasin', font=('Welcome Admin', 16))
    ec1 = Entry(cust, font=10, bd=5)
    ec2 = Entry(cust, font=10, bd=5, show='*')
    disc3.place(x=150, y=100)
    disc1.place(x=70, y=230)
    disc2.place(x=70, y=290)
    bc1.place(x=200, y=370)
    ec1.place(x=180, y=230)
    ec2.place(x=180, y=290)
    return

def sinpg():
    cusid = str(es1.get())
    pasw1 = str(es2.get())
    pasw2 = str(es21.get())
    cname = str(es3.get())
    city = str(es4.get())
    stre = str(es5.get())
    stat = str(es6.get())
    phno = str(es7.get())

    if pasw1 != pasw2:
        vis = Label(sig, text='  Passwords  dont  match', font=8)
        vis.place(x=150, y=460)
        vis.after(3000, lambda : vis.place_forget())
    elif cusid == '' or pasw1 == '' or pasw2 == '' or cname == '' \
        or city == '' or stre == '' or stat == '' or phno == '':

        l1 = Label(sig, text='Please fill all details', font=8, fg='red'
                   )
        l1.place(x=150, y=460)
        l1.after(3000, lambda : l1.place_forget())
    else:
        vis = Label(sig, text='Account Created successfully', font=8)
        vis.place(x=150, y=460)
        vis.after(3000, lambda : vis.place_forget())
        cursor.execute('INSERT INTO Customer VALUES (?,?,?,?,?,?,?)', (
            cusid,
            pasw1,
            cname,
            city,
            stre,
            stat,
            phno,
            ))
        connection.commit()
    return

def signup():
    global sig
    sig = Tk()
    sig.geometry('480x480+500+120')
    sig.title('Customer')
    wel = Label(sig, text='Customer SignUp', fg='black', bg='Moccasin',
                font=16)
    global es1, es2, es21, es3, es4, es5, es6, es7
    l1 = Label(sig, text='Customer ID', font=10)
    l2 = Label(sig, text='Password', font=10)
    l21 = Label(sig, text='Re-enter Password', font=10)
    l3 = Label(sig, text='Name', font=10)
    l4 = Label(sig, text='City', font=10)
    l5 = Label(sig, text='Street', font=10)
    l6 = Label(sig, text='State', font=10)
    l7 = Label(sig, text='Phone No', font=10)

    es1 = Entry(sig, font=10, bd=5)
    es2 = Entry(sig, font=10, bd=5, show='*')
    es21 = Entry(sig, font=10, bd=5, show='*')
    es3 = Entry(sig, font=10, bd=5)
    es4 = Entry(sig, font=10, bd=5)
    es5 = Entry(sig, font=10, bd=5)
    es6 = Entry(sig, font=10, bd=5)
    es7 = Entry(sig, font=10, bd=5)

    b1 = Button(sig, text='Sign Up', width=20, height=3, command=sinpg)
    wel.place(x=150, y=40)
    l1.place(x=70, y=80)
    es1.place(x=230, y=80)
    l2.place(x=70, y=120)
    es2.place(x=230, y=120)
    l21.place(x=70, y=160)
    es21.place(x=230, y=160)
    l3.place(x=70, y=200)
    es3.place(x=230, y=200)
    l4.place(x=70, y=240)
    es4.place(x=230, y=240)
    l5.place(x=70, y=280)
    es5.place(x=230, y=280)
    l6.place(x=70, y=320)
    es6.place(x=230, y=320)
    l7.place(x=70, y=360)
    es7.place(x=230, y=360)
    b1.place(x=150, y=400)
    return

global gui
gui = Tk()

gui.geometry('1080x700+200+0')
gui.title('BOOKSHOP AUTOMATION SYSTEM')
image = Image.open(os.path.join(resources_directory_path, 'academic-complex.jpg'))
photo_image = ImageTk.PhotoImage(image)
label = Label(gui, image=photo_image)
label.pack()

deli = 120
svar = StringVar()
labl = Label(
    gui,
    textvariable=svar,
    height=3,
    width=200,
    bg='Moccasin',
    fg='Black',
    font=('Times New Roman', 15),
    )

dis = Label(
    gui,
    text='BOOKSHOP AUTOMATION SYSTEM',
    height=3,
    width=92,
    bg='Moccasin',
    fg='Black',
    font=('Times New Roman', 18),
    )
disp = Label(gui, text='New User?', bg='Moccasin',
             font=('Times New Roman', 15))
b1 = Button(
    gui,
    text='Admin Login',
    width=25,
    height=3,
    command=admin,
    font=('Times New Roman', 18),
    bg='lightgreen',
    borderwidth=0,
    )
b2 = Button(
    gui,
    text='Customer Login',
    width=25,
    height=3,
    command=customer,
    font=('Times New Roman', 18),
    bg='lightgreen',
    borderwidth=0,
    )
b3 = Button(
    gui,
    text='Customer Signup',
    width=25,
    height=3,
    command=signup,
    font=('Times New Roman', 18),
    bg='lightgreen',
    borderwidth=0,
    )
dis.place(x=0, y=140)
b1.place(x=100, y=530)
b2.place(x=630, y=530)
b3.place(x=360, y=360)
disp.place(x=483, y=325)

gui.mainloop()


import argparse
import re
import os
import pickle

'''--------------------Parsing argumnts--------------------'''
parser = argparse.ArgumentParser(description="Этот код создаёт модель, обученную на текстах песен")
parser.add_argument(
    '--input_dir',
    type=str,
    help="Путь к папке с песнями"
)
parser.add_argument(
    '--model',
    type=str,
    default="model.pkl",
    help="Путь к файлу, в который сохраняется модель(с расширением pkl)"
)
args = parser.parse_args()
if args.input_dir==None:
    args.input_dir = input("Введите путь к папке с текстами: ")

'''--------------------Generating model--------------------'''
model = {}
data = os.listdir(path=args.input_dir)
for file in data:
    with open(args.input_dir+"/"+file,"r",encoding="utf-8") as file:
        text = ""
        for i in file:
            text += i
        text = re.sub(r'\W+',' ',text)
        text = text.lower().strip().split()
        for i in range(len(text)-1):
            if i>0:
                model[text[i-1]+" "+text[i]] = model.get(text[i-1]+" "+text[i],[])
                model[text[i-1]+" "+text[i]].append(text[i+1])
            model[text[i]] = model.get(text[i],[])
            model[text[i]].append(text[i+1])
'''--------------------Saving model--------------------'''
with open(args.model,"wb") as f:
    pickle.dump(model,f)


import os
import xml.etree.ElementTree as ET
import json

def append_barcode(results, barcode):
    result = {}
    result["attrib"] = barcode.attrib
    Values = get_elements(barcode, "Value")
    for Value in Values:
        result["text"] = Value.text
        result["value_attrib"] = Value.attrib
    results.append(result)

def get_elements(root, name):
    children = []
    for child in root:
        if child.tag == name:
            children.append(child)
    return children

for filename in os.listdir("./Markup"):
    if filename.endswith(".xml") == False:
        continue
    tree = ET.parse(os.path.join("./Markup",filename))
    root = tree.getroot()
    pages = root[0]
    results = []
    for page in pages:
        BarcodesRoot = get_elements(page, "Barcodes")[0]
        Barcodes = get_elements(BarcodesRoot, "Barcode")
        for barcode in Barcodes:
            append_barcode(results, barcode)
    name, ext = os.path.splitext(filename)
    txt_path = os.path.join("./Image",name+".txt")
    f = open (txt_path,"w")
    f.write(json.dumps(results))
    f.close()


import os
import queue
import json
from jsonschema import validate
import collections

class TestCase():
    """Attributes of a single test.

    Args:
        test_data (dict): data for a single test, parsed from JSON
                          test declaration.
    """
    __test__ = False  #: Ignored by Pytest

    def __init__(self, test_data):
        self.tag = test_data["tag"]

        #: list of couples of decl: List of IO declarations.
        self.io_decl = self._make_io_decl(test_data)

        #: int: ticks to pass before next input application.
        self.ticks_before_next_input = test_data["ticks_before_next_input"]

        #: int: ticks to pass before checking outputs
        self.ticks_before_checking = test_data["ticks_before_checking"]

    def _make_io_decl(self, test_data):
        """Make io_decl dictionaries from data.

        Args:
            test_data (dict): data for a single test parsed from a JSON tests
                              declaration file.

        Returns:
            list: a list of test declarations.
        """

        def compute_decl(decl):
            res = {}

            for signame, value in decl.items():
                if isinstance(value, str):
                    value = int(value, 2)
                res[signame] = value

            return res

        res = []

        for r in test_data["rounds"]:
            res += [(compute_decl(r["inputs"]), compute_decl(r["outputs"]))]

        return res

    def get_io_queues(self):
        """Generate input and expected io_decl queues.

        Args:
            testcase (TestDeclaration()): current test case.

        Returns:
            (queue.Queue(), queue.Queue()): input and expected declarations
                                            queues.
        """

        def _push_expected_values(q, is_first, expected_values):
            if is_first:
                for _ in range(self.ticks_before_checking):
                    q.put(None)
            else:
                for _ in range(self.ticks_before_next_input - 1):
                    q.put(None)

            q.put(expected_values)

            return q

        def _push_input_values(q, in_values):
            q.put(in_values)
            for _ in range(self.ticks_before_next_input - 1):
                q.put(None)

        in_q = queue.Queue()
        exp_q = queue.Queue()

        is_first = True
        for in_values, expected_values in self.io_decl:
            _push_input_values(in_q, in_values)
            _push_expected_values(exp_q, is_first, expected_values)
            is_first = False

        return in_q, exp_q

class TestsDeclaration():
    """Contains test declarations data.

    Args:
        filename (str): name of the test declaration JSON file.
    """

    __test__ = False  #: Ignored by Pytest

    def __init__(self, filename):
        #: dict: data parsed from JSON tests declaration.
        self._data = self._parse_testfile(filename)

        #: str: name of the testsuite.
        self.name = self._data["name"]

        #: list of TestAttributes(): list of each test's attributes.
        self.testcases = self._make_testcases()

    def _parse_testfile(self, filename):
        """Parses a JSON tests declaration from filename.

        Args:
            filename (str): name of the JSON file to parse.

        Returns:
            dict: data parsed from JSON file.
        """

        res = None

        with open(filename, 'r') as f:
            res = json.loads(
                f.read(), object_pairs_hook=collections.OrderedDict)

        self._validate_testfile(res)

        return res

    def _validate_testfile(self, data):
        """Validate raw data against JSON Scheme.

        Args:
            data (dict): data parsed from JSON file.
        """
        schema = None
        dir = os.path.dirname(os.path.realpath(__file__))
        with open(dir + "/testdecl_scheme.json", "r") as f:
            schema = json.loads(f.read())

        validate(data, schema)

    def _make_testcases(self):
        """Make a list of TestAttributes() from tests declaration.

        Returns:
            list: a list of TestAttributes().
        """
        res = []

        for t in self._data["tests"]:
            res += [TestCase(t)]

        return res


import sys
import os
sys.path.insert(0,  os.getcwd() + '/../keggimporter')

import logging
import logging.handlers
from Config import *
from Importer import *

config = Config()
config.loadConfiguration()
conf = config.getConfigurations()

logFile = conf.get( 'log', 'info' )

log = logging.getLogger('')
log.setLevel(logging.DEBUG)
format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(format)
log.addHandler(ch)

fh = logging.handlers.RotatingFileHandler( logFile , maxBytes=0, backupCount=0)
fh.setFormatter(format)
log.addHandler(fh)

log.info('keggimporter: START')

imp = Importer()

imp.startImporter()

log.info('writeTaxonomies: START')
imp.writeTaxonomies()
log.info('writeTaxonomies: DONE')

log.info('writePathways: START')
imp.writePathways()
log.info('writePathways: DONE')

log.info('writeEcs: START')
imp.writeEcs()
log.info('writeEcs: DONE')

log.info('writeOrganisms: START')
imp.writeOrganisms()
log.info('writeOrganisms: DONE')

log.info('writeProteins: START')
imp.writeProteins()
log.info('writeProteins: DONE')

log.info('writeProteinRelations: START')
imp.writeProteinRelations()
log.info('writeProteinRelations: DONE')

log.info('writeOrganismTaxonomies: START')
imp.writeOrganismTaxonomies()
log.info('writeOrganismTaxonomies: DONE')

log.info('writeProteinAccessions: START')
imp.writeProteinAccessions()
log.info('writeProteinAccessions: DONE')

log.info('writeEcMaps: START')
imp.writeEcMaps()
log.info('writeEcMaps: DONE')

log.info('keggimporter: DONE')


import warnings
import argparse

import mlflow
from mlflow.tracking.client import MlflowClient
warnings.filterwarnings("ignore", category=FutureWarning)

from custom_preproc_classes.config.core import config

def parse_bool(to_production: str):
    if to_production == "T":
        return True
    elif to_production == "F":
        return False
    else:
        raise ValueError("to_production must be T or F")

def register_mlflow_model(run_id: str, to_production: str, experiment_name: str):
    """
    This function registers a model from an experiment specific run and sets the stage of the model to "Production".

    Args:
        - run_id: Specific id of the model's run
        - to_production: If True, the stage of the newly registered model is set to 'Production'.

    """

    # ---- Register model ---- #
    model_uri = "runs:/" + run_id + "/model"
    mlflow.set_tracking_uri("sqlite:///mlruns.db")
    model_details = mlflow.register_model(model_uri=model_uri, name=experiment_name)
    # print(*model_details, sep = "\n")

    to_production = parse_bool(to_production)

    # ---- Change stage of registered model to production ---- #
    if to_production:
        client = MlflowClient()
        client.transition_model_version_stage(
            name=model_details.name,
            version=model_details.version,
            stage="Production"
        )

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument("-r", "--runid", required=True, type=str)
    parser.add_argument("-to_p", "--to_production", required=True, type=str)
    parser.add_argument("-exn", "--experiment_name", required=True, type=str)
    args = parser.parse_args()
    run_id = args.runid
    to_production = args.to_production
    experiment_name = args.experiment_name

    print(run_id)
    print(to_production)

    register_mlflow_model(run_id=run_id, to_production=to_production, experiment_name=experiment_name)


from enum import IntEnum, auto
from typing import Tuple, Sequence

from unsserv.common.utils import parse_node
from unsserv.common.structs import Node
from unsserv.common.rpc.structs import Message
from unsserv.common.rpc.protocol import AProtocol, ITranscoder, Command, Data, Handler
from unsserv.extreme.searching.structs import WalkResult, Walk

FIELD_COMMAND = "kwalker-command"
FIELD_WALK_ID = "kwalker-walk-id"
FIELD_ORIGIN_NODE = "kwalker-origin-node"
FIELD_TTL = "kwalker-ttl"
FIELD_DATA_ID = "kwalker-data-id"
FIELD_WALK_RESULT = "kwalker-walk-result"

class KWalkerCommand(IntEnum):
    WALK = auto()
    WALK_RESULT = auto()

class KWalkerTranscoder(ITranscoder):
    def encode(self, command: Command, *data: Data) -> Message:
        if command == KWalkerCommand.WALK:
            walk: Walk = data[0]
            message_data = {
                FIELD_COMMAND: KWalkerCommand.WALK,
                FIELD_WALK_ID: walk.id,
                FIELD_DATA_ID: walk.data_id,
                FIELD_ORIGIN_NODE: walk.origin_node,
                FIELD_TTL: walk.ttl,
            }
            return Message(self.my_node, self.service_id, message_data)
        elif command == KWalkerCommand.WALK_RESULT:
            walk_result: WalkResult = data[0]
            message_data = {
                FIELD_COMMAND: KWalkerCommand.WALK_RESULT,
                FIELD_WALK_ID: walk_result.walk_id,
                FIELD_WALK_RESULT: walk_result.result,
            }
            return Message(self.my_node, self.service_id, message_data)
        raise ValueError("Invalid Command")

    def decode(self, message: Message) -> Tuple[Command, Sequence[Data]]:
        command = message.data[FIELD_COMMAND]
        if command == KWalkerCommand.WALK:
            walk = Walk(
                id=message.data[FIELD_WALK_ID],
                data_id=message.data[FIELD_DATA_ID],
                origin_node=parse_node(message.data[FIELD_ORIGIN_NODE]),
                ttl=message.data[FIELD_TTL],
            )
            return KWalkerCommand.WALK, [walk]
        elif command == KWalkerCommand.WALK_RESULT:
            walk_result = WalkResult(
                walk_id=message.data[FIELD_WALK_ID],
                result=message.data[FIELD_WALK_RESULT],
            )
            return KWalkerCommand.WALK_RESULT, [walk_result]
        raise ValueError("Invalid Command")

class KWalkerProtocol(AProtocol):
    def _get_new_transcoder(self):
        return KWalkerTranscoder(self.my_node, self.service_id)

    async def walk(self, destination: Node, walk: Walk):
        message = self._transcoder.encode(KWalkerCommand.WALK, walk)
        return await self._rpc.call_send_message(destination, message)

    async def walk_result(self, destination: Node, walk_result: WalkResult):
        message = self._transcoder.encode(KWalkerCommand.WALK_RESULT, walk_result)
        return await self._rpc.call_send_message(destination, message)

    def set_handler_walk(self, handler: Handler):
        self._handlers[KWalkerCommand.WALK] = handler

    def set_handler_walk_result(self, handler: Handler):
        self._handlers[KWalkerCommand.WALK_RESULT] = handler


from django.core.management.base import BaseCommand
from home2_app.models import Client

class Command(BaseCommand):
    help = "edit client  name "

    def add_arguments(self, parser):
        parser.add_argument('name', type=str, help="Client_name")
        parser.add_argument('new_name', type=str, help="New_Client_name")

    def handle(self, *args, **kwargs):
        name = kwargs.get('name')
        new_name = kwargs.get('new_name')
        client = Client.objects.filter(name=name).first()
        if client:
            client.name=new_name
            client.save()
            self.stdout.write(f'edit client{client}')
        self.stdout.write(f' clients {name} in base note found')


#!/usr/bin/env python
# coding: utf-8

# In[1]:

print("Hello World!")

# In[2]:

import librosa
import numpy as np
import matplotlib.pyplot as plt
import IPython.display as ipd
import librosa.display
from IPython.display import Audio
from scipy import stats

# In[3]:

y, sr = librosa.load("yours.mp3")

# In[4]:

# loading the audio file
# sphinx_gallery_thumbnail_path = '_static/playback-thumbnail.png'

# We'll need IPython.display's Audio widget

# In[5]:

Audio(data=y, rate=sr)

# In[6]:

print(y)

# In[7]:

# estimating the tempo of the song
onset_env = librosa.onset.onset_strength(y=y, sr=sr)
tempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sr)
tempo

# In[8]:

# class that uses the librosa library to analyze the key that an mp3 is in
# arguments:
#     waveform: an mp3 file loaded by librosa, ideally separated out from any percussive sources
#     sr: sampling rate of the mp3, which can be obtained when the file is read with librosa
#     tstart and tend: the range in seconds of the file to be analyzed; default to the beginning and end of file if not specified
class Tonal_Fragment(object):
    def __init__(self, waveform, sr, tstart=None, tend=None):
        self.waveform = waveform
        self.sr = sr
        self.tstart = tstart
        self.tend = tend

        if self.tstart is not None:
            self.tstart = librosa.time_to_samples(self.tstart, sr=self.sr)
        if self.tend is not None:
            self.tend = librosa.time_to_samples(self.tend, sr=self.sr)
        self.y_segment = self.waveform[self.tstart:self.tend]
        self.chromograph = librosa.feature.chroma_cqt(y=self.y_segment, sr=self.sr, bins_per_octave=24)

        # chroma_vals is the amount of each pitch class present in this time interval
        self.chroma_vals = []
        for i in range(12):
            self.chroma_vals.append(np.sum(self.chromograph[i]))
        pitches = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']
        # dictionary relating pitch names to the associated intensity in the song
        self.keyfreqs = {pitches[i]: self.chroma_vals[i] for i in range(12)}

        keys = [pitches[i] + ' major' for i in range(12)] + [pitches[i] + ' minor' for i in range(12)]

        # use of the Krumhansl-Schmuckler key-finding algorithm, which compares the chroma
        # data above to typical profiles of major and minor keys:
        maj_profile = [6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88]
        min_profile = [6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17]

        # finds correlations between the amount of each pitch class in the time interval and the above profiles,
        # starting on each of the 12 pitches. then creates dict of the musical keys (major/minor) to the correlation
        self.min_key_corrs = []
        self.maj_key_corrs = []
        for i in range(12):
            key_test = [self.keyfreqs.get(pitches[(i + m)%12]) for m in range(12)]
            # correlation coefficients (strengths of correlation for each key)
            self.maj_key_corrs.append(round(np.corrcoef(maj_profile, key_test)[1,0], 3))
            self.min_key_corrs.append(round(np.corrcoef(min_profile, key_test)[1,0], 3))

        # names of all major and minor keys
        self.key_dict = {**{keys[i]: self.maj_key_corrs[i] for i in range(12)},
                         **{keys[i+12]: self.min_key_corrs[i] for i in range(12)}}

        # this attribute represents the key determined by the algorithm
        self.key = max(self.key_dict, key=self.key_dict.get)
        self.bestcorr = max(self.key_dict.values())

        # this attribute represents the second-best key determined by the algorithm,
        # if the correlation is close to that of the actual key determined
        self.altkey = None
        self.altbestcorr = None

        for key, corr in self.key_dict.items():
            if corr > self.bestcorr*0.9 and corr != self.bestcorr:
                self.altkey = key
                self.altbestcorr = corr

    # prints the relative prominence of each pitch class
    def print_chroma(self):
        self.chroma_max = max(self.chroma_vals)
        for key, chrom in self.keyfreqs.items():
            print(key, '\t', f'{chrom/self.chroma_max:5.3f}')

    # prints the correlation coefficients associated with each major/minor key
    def corr_table(self):
        for key, corr in self.key_dict.items():
            print(key, '\t', f'{corr:6.3f}')

    def correlation_coefficients(self):
        return self.key_dict.items()

    # printout of the key determined by the algorithm; if another key is close, that key is mentioned
    def print_key(self):
        print("likely key: ", max(self.key_dict, key=self.key_dict.get), ", correlation: ", self.bestcorr, sep='')
        if self.altkey is not None:
                print("also possible: ", self.altkey, ", correlation: ", self.altbestcorr, sep='')

    # prints a chromagram of the file, showing the intensity of each pitch class over time
    def chromagram(self, title=None):
        C = librosa.feature.chroma_cqt(y=self.waveform, sr=sr, bins_per_octave=24)
        plt.figure(figsize=(12,4))
        librosa.display.specshow(C, sr=sr, x_axis='time', y_axis='chroma', vmin=0, vmax=1)
        if title is None:
            plt.title('Chromagram')
        else:
            plt.title(title)
        plt.colorbar()
        plt.tight_layout()
        plt.show()

# In[9]:

# this audio takes a long time to load because it has a very high sampling rate; be patient.
# the load function generates a tuple consisting of an audio object y and its sampling rate sr
# this function filters out the harmonic part of the sound file from the percussive part, allowing for
# more accurate harmonic analysis
y_harmonic, y_percussive = librosa.effects.hpss(y)

# In[10]:

# this block instantiates the Tonal_Fragment class with the first 22 seconds of the above harmonic part of une barque.
# the three methods called will print the determined key of the song, the correlation coefficients for all keys,
# and a chromogram, which shows the intensity of frequencies associated with each of the 12 pitch classes over time.

unebarque_fsharp_min = Tonal_Fragment(y_harmonic, sr, tend=22)
unebarque_fsharp_min.print_chroma()

# In[11]:

unebarque_fsharp_min.print_key()
unebarque_fsharp_min.corr_table()
unebarque_fsharp_min.chromagram("Une Barque sur l\'Ocean")

# In[12]:

# parts of the song that are more tonally ambiguous will show two keys with print_key(),
# if they are similarly well-correlated.
# this section of une barque is in E minor, though the algorithm suggests that it is in D major, a closely related key,
# though E minor is also listed since their correlation coefficients are very close.
unebarque_e_min = Tonal_Fragment(y_harmonic, sr, tstart=0)
unebarque_e_min.print_key()
unebarque_e_min.corr_table()

# In[13]:

# in the case of une barque sur l'ocean (and other songs), predictions become less reliable over short time frames
# the below block prints the predicted key of every 3-second-long cut of the piece.
bin_size = 3
for i in range(24):
    fragment = Tonal_Fragment(y_harmonic, sr, tstart = bin_size*i, tend=bin_size*(i+1))
    print(bin_size*i,"sec:",fragment.key)
    if fragment.altkey is not None:
        print("\t or:", fragment.altkey)

# In[14]:

# getting volume graph
rms = librosa.feature.rms(y=y)
plt.plot(rms[0])
plt.show()

# In[15]:

print(rms)
print(np.mean(rms[0]))
print(np.max(rms[0]))

# In[16]:

import librosa
import numpy as np
import matplotlib.pyplot as plt
import IPython.display as ipd
import librosa.display
from IPython.display import Audio
from scipy import stats
# Python program to explain os.listdir() method

# importing os module
import os

# Get the path of current working directory
path = os.getcwd()
path += "//Good Songs"

# Get the list of all files and directories
# in current working directory
songs_list = os.listdir(path)

#move the non-song item to end of list so that we can avoid using it for the data
songs_list.sort(key = 'librosapractice.ipynb'.__eq__)

# print the list
print(songs_list)

for song in songs_list:
    if song[-3:] == 'mp3':
        print(song)
        # load audio
        y, sr = librosa.load(path+"//"+song)
        Audio(data=y, rate=sr)
        print(y)
        # tempo
        onset_env = librosa.onset.onset_strength(y=y, sr=sr)
        tempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sr)
        print(tempo)
        # key
        onset_env = librosa.onset.onset_strength(y=y, sr=sr)
        tempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sr)
        tempo

        y_harmonic, y_percussive = librosa.effects.hpss(y)

        song_tonal_analysis = Tonal_Fragment(y_harmonic, sr, tend=22)
        song_tonal_analysis.print_chroma()
        song_tonal_analysis.print_key()
        song_tonal_analysis.corr_table()
        song_tonal_analysis.chromagram("song")

        unebarque_e_min = Tonal_Fragment(y_harmonic, sr, tstart=0)
unebarque_e_min.print_key()
unebarque_e_min.corr_table()

# In[17]:

# for extracting likely key/s for each song + spectogram
for song in songs_list:
    if song[-3:] == 'mp3':
        print(song)
        y, sr = librosa.load(song)
        Audio(data=y, rate=sr)
        print(y)

    onset_env = librosa.onset.onset_strength(y=y, sr=sr)
    tempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sr)
    tempo

    y_harmonic, y_percussive = librosa.effects.hpss(y)

    song_tonal_analysis = Tonal_Fragment(y_harmonic, sr, tend=22)
    song_tonal_analysis.print_chroma()
    song_tonal_analysis.print_key()
    song_tonal_analysis.corr_table()
    song_tonal_analysis.chromagram("song")

    unebarque_e_min = Tonal_Fragment(y_harmonic, sr, tstart=0)
unebarque_e_min.print_key()
unebarque_e_min.corr_table()

# In[18]:

# getting volume graph for each song in the list
def extract_volume(song):
    y, sr = librosa.load(song)
    Audio(data=y, rate=sr)
    rms = librosa.feature.rms(y=y)
    # plt.plot(rms[0])
    # plt.show()
    # print(rms)
    # print("volume mean: " + str(np.mean(rms[0])))
    # print("volume max: " + str(np.max(rms[0])))
    return np.mean(rms[0]), np.max(rms[0])

# In[19]:

# tempo function
def extract_tempo(song):
    y, sr = librosa.load(song)
    Audio(data=y, rate=sr)
    onset_env = librosa.onset.onset_strength(y=y, sr=sr)
    tempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sr)
    # print("tempo: " + str(tempo))
    return tempo

# In[20]:

def extract_key(song):
    y, sr = librosa.load(song)
    Audio(data=y, rate=sr)
    # print(y)

    onset_env = librosa.onset.onset_strength(y=y, sr=sr)
    tempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sr)

    y_harmonic, y_percussive = librosa.effects.hpss(y)

    """
    song_tonal_analysis = Tonal_Fragment(y_harmonic, sr, tend=22)
    song_tonal_analysis.print_chroma()
    song_tonal_analysis.print_key()
    song_tonal_analysis.corr_table()
    song_tonal_analysis.chromagram("song")
    """

    keyanalysis = Tonal_Fragment(y_harmonic, sr, tstart=0)
    # keyanalysis.print_key()
    # unebarque_e_min.corr_table()
    return keyanalysis.correlation_coefficients()

# In[21]:

list_of_emotions = []
list_of_all_songs = []
for song in songs_list:
    if song[-3:] == 'mp3':
        #print(song)
        tempo = extract_tempo(song)
        volume = extract_volume(song)
        key = extract_key(song)
        key_probabilities = [x[1] for x in list(key)]
        combined_list = [tempo[0]] + [volume[0], volume[1]] + key_probabilities
        #print(combined_list)
        list_of_all_songs += [combined_list]
    else:
        print(song)
        # I think I need to add the below code here???
print(list_of_all_songs)

# In[22]:

graph_colors = ['red', 'cyan', 'hotpink', 'lightslategrey']
from sklearn.decomposition import PCA
import csv
emotions_list = []

# opening the CSV file
#with open('final_music_dataset - Sheet1 (1).csv', mode ='r')as file:
with open('final_music_dataset - Sheet1 (1).csv', mode ='r')as file:

  # reading the CSV file
  csvFile = csv.reader(file)

  # displaying the contents of the CSV file
  n = 0
  for line in csvFile:
        # print(lines)
        if n >= 1:
            if line[3] == 'calm/neutral':
                emotions_list += [graph_colors[1]]
            elif line[3] == 'happy/joyous':
                emotions_list += [graph_colors[2]]
            elif line[3] == 'sad/melancholy':
                emotions_list += [graph_colors[3]]
            elif line[3] == 'angry/restlessness':
                emotions_list += [graph_colors[0]]
            else:
                print(line[3])
        n += 1
        # print(line[3] == "calm/neutral")

pca = PCA(n_components=2)
list_of_songs_numpy = np.array(list_of_all_songs)
print(list_of_songs_numpy)
two_d_output = pca.fit_transform(list_of_songs_numpy)
print(two_d_output)
print(emotions_list)

# In[23]:

import matplotlib.pyplot as plt
plt.scatter([v[0] for v in two_d_output], [v[1] for v in two_d_output], c = emotions_list)
plt.show()

# In[24]:

#import csv

# opening the CSV file
#with open('Music Dataset - Sheet1.csv', mode ='r')as file:

  # reading the CSV file
 # csvFile = csv.reader(file)

  # displaying the contents of the CSV file
  #for lines in csvFile:
       # print(lines)
        #print(lines[3])

# In[ ]:

# In[ ]:


# goal
# 실패율이 높은 스테이지부터 내림차순으로 스테이지의 번호가 담겨있는 배열을 return 하도록 solution 함수

# description
# 실패율 - 스테이지에 도달했으나 아직 클리어하지 못한 플레이어의 수 / 스테이지에 도달한 플레이어 수
# 전체 스테이지의 개수 N, 게임을 이용하는 사용자가 현재 멈춰있는 스테이지의 번호가 담긴 배열 stages가 매개변수

# condition
# 스테이지의 개수 N은 1 이상 500 이하의 자연수이다.
# stages의 길이는 1 이상 200,000 이하이다.
# stages에는 1 이상 N + 1 이하의 자연수가 담겨있다.
# 각 자연수는 사용자가 현재 도전 중인 스테이지의 번호를 나타낸다.
# 단, N + 1 은 마지막 스테이지(N 번째 스테이지) 까지 클리어 한 사용자를 나타낸다.
# 만약 실패율이 같은 스테이지가 있다면 작은 번호의 스테이지가 먼저 오도록 하면 된다.
# 스테이지에 도달한 유저가 없는 경우 해당 스테이지의 실패율은 0 으로 정의한다.

import collections

def solution(N, stages):
    total = len(stages)
    dic = {}
    # counter 함수 통해서 각 숫자별 개수 구하기
    stages_counter = collections.Counter(stages)

    # 1부터 N+1까지 돌려서 dic에 key(숫자) value(실패율)로 넣기 total에서 이전 숫자만큼 분모 빼면서 넣기
    # 끝까지 통과한 애들은 필요 없어서 N+1.
    for i in range(1, N+1):
        dic[i] = 0 if stages_counter[i] == 0 else stages_counter[i]/total
        total -= stages_counter[i]

    return [k for k, v in sorted(dic.items(), reverse=True, key=lambda x: x[1])]


"""
Django command to wait for DB to be available
"""
import time

# Shows error but the psycopg2 is successfully installed on docker
from psycopg2 import OperationalError as Psycopg2Error
from django.db.utils import OperationalError

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    """
    Django command to wait for db
    """

    def handle(self, *args, **options):

        self.stdout.write('Waiting for the Database to start....')
        db_up = False

        while db_up is False:

            try:
                self.check(databases=['default'])
                db_up = True

            except (Psycopg2Error, OperationalError):
                self.stdout.write("DB is unavailable right now. \
                 Waiting for 1 sec to restart the database")
                time.sleep(1)

        self.stdout.write(self.style.SUCCESS('DB is UP '))


"""
A script that compares image histograms quantitively. The user must specify either a single image or a directory (jpg/png).
"""
# system tools
import os
import argparse
import sys

# image and data tools
import cv2
import numpy as np
import glob
import pandas as pd

# plotting tools
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# function that specifies the required arguments
def parse_args():
    # Initialise argparse
    ap = argparse.ArgumentParser()

    # command line parameters
    ap.add_argument("-f", "--file_input", required = True, help = "The filename or directory we want to work with")

    args = vars(ap.parse_args())
    return args

# function to clean a file path name
def clean_name(name):
    split_filename = name.split("/")[-1]
    file_only = split_filename.split(".")[0]

    return file_only

# function to create the histogram
def create_histogram(image):
     # creating histograms for image
    hist = cv2.calcHist([image], [0,1,2], None, [8,8,8], [0,256, 0,256, 0,256])
    hist = cv2.normalize(hist, hist, 0,255, cv2.NORM_MINMAX) #normalizing with MINMAX

    return hist

# function to calculate similarity scores
def calc_sim_scores(filename):
    # parse argument
    args = parse_args()
    input_name = args['file_input']

     # if the path provided is a file
    isFile = os.path.isfile(input_name)
    if isFile == True:
        input_name = input_name.split("/")[:-1]
        input_name = '/'.join(input_name) # remove the filename to get the directory

    # get all full path names
    file_list = glob.glob(os.path.join(input_name, '*g'))
    file_list = sorted(file_list)

    target_image = mpimg.imread(filename) # loading target image
    target_hist = create_histogram(target_image)

    # initiating lists for results
    sim_value = []
    img_name = []

    for img in file_list:
        if img != filename: # excluding the target image
            image = mpimg.imread(img)
            hist = create_histogram(image)

            score = round(cv2.compareHist(target_hist, hist, cv2.HISTCMP_CHISQR), 2) # comparing each histogram to the target image
            img_name.append(img) # appending results to the lists
            sim_value.append(score)

    # zipping the lists together, sorting it, and selecting the top 3 results.
    scores = sorted(zip(sim_value, img_name))
    scores = scores[0:3]

    return scores

# function to create the plot and dataframe of the results
def hist_result(file, scores):
    target_image = mpimg.imread(file) # loading target image
    file_name = clean_name(file)

    # initiating a list for the output dataframe
    output_data = []
    output_data.append(file_name)

    # initiating plot
    plt.subplot(1, 4, 1) #the figure has 1 row, 4 columns, and this is the first plot
    plt.imshow(target_image, extent=[-4, 4, -1, 1], aspect=4) # aligning the size of the images
    plt.axis('off')
    plt.title('Main image')

    plot_number = 1 # creating counter for the subplots

    for value, image in scores:
        value = round(value) # rounding the similarity score for a cleaner output
        image_name = clean_name(image)

        output_data.append(image_name) # saving the results of each image in the output list
        output_data.append(value)

        # plotting
        plot_number += 1
        image_sub = mpimg.imread(image)

        # creating the subplots
        plt.subplot(1, 4, plot_number)
        plt.imshow(image_sub, extent=[-4, 4, -1, 1], aspect=4)
        plt.axis('off')
        plt.title(f"Score: {value}")

    # Saving the plot
    plt.suptitle("Most similar images")
    plt.savefig(f'output/hist_{file_name}.jpg')

    # creating the dataframe and transposing it to get columns
    df = pd.DataFrame(output_data, index = ["main_image", "1_image", "1_image_score", "2_image", "2_image_score", "3_image", "3_image_score"])
    df = df.transpose()

    outpath = os.path.join('output', f'hist_{file_name}.csv')
    df.to_csv(outpath, index = False)

    return

# function to create a dataframe of the similarity scores for multiple input files
def hist_all_results(input_name):

    # get all full path names
    file_list = glob.glob(os.path.join(input_name, '*g'))
    file_list = sorted(file_list)

    # initiate list for dataframe
    out_list = []
    for file in file_list:
        scores = calc_sim_scores(file)
        file_name = clean_name(file)

        output_data = [] # initiating output data for each main image
        output_data.append(file_name)

        # cleaning the values and names, and appending them to the output data
        for value, image in scores:
            value = round(value)
            image_name = clean_name(image)

            output_data.append(image_name)
            output_data.append(value)

        out_list.append(output_data) # appending the output data to the out_list for the dataframe

    # creating the dataframe
    df = pd.DataFrame(out_list, columns = ["main_image", "1_image", "1_image_score", "2_image", "2_image_score", "3_image", "3_image_score"])

    outpath = os.path.join('output', 'hist_all_files.csv')
    df.to_csv(outpath)

    return

def main():

    # parse arguments
    args = parse_args()
    input_name = args['file_input']

    # if path provided is a file:
    isFile = os.path.isfile(input_name)
    if isFile == True:
        scores = calc_sim_scores(input_name)
        hist_result(input_name, scores)

        print('Input is a file. Script success.')

    # if path provided is a directory:
    isDirectory = os.path.isdir(input_name)
    if isDirectory == True:
        hist_all_results(input_name)

        print('Input is a directory. Script success.')

    return

if __name__ == '__main__':
    main()


import pyautogui as pag
from collections import namedtuple,Counter
import random

"""
https://asyncfor.com/posts/doc-pyautogui.html
screenWidth, screenHeight = pyautogui.size()
currentMouseX, currentMouseY = pyautogui.position()
pyautogui.moveTo(100, 150)
pyautogui.click()
#  鼠标向下移动10像素
pyautogui.moveRel(None, 10)
pyautogui.doubleClick()
#  用缓动/渐变函数让鼠标2秒后移动到(500,500)位置
#  use tweening/easing function to move mouse over 2 seconds.
pyautogui.moveTo(1800, 500, duration=2, tween=pyautogui.easeInOutQuad)
#  在每次输入之间暂停0.25秒
pyautogui.typewrite('Hello world!', interval=0.25)
pyautogui.press('esc')
pyautogui.keyDown('shift')
pyautogui.press(['left', 'left', 'left', 'left', 'left', 'left'])
pyautogui.keyUp('shift')
pyautogui.hotkey('ctrl', 'c')
"""

#("mouse","click",(10,100)) ,("mouse","move",(10,100)),("key","press","a")
#status 默认为 None
CMD = namedtuple("CMD",["device","action","code","status"],defaults=[None])

#status_device_action_map
sda_map = {"bc":["mouse","click"],
               "kd":["keyboard","keyDown"],
                "None":["mouse","move"]}
#status:target name
pag.FAILSAFE = False
PC_bind = {
    "mouse":{"move":pag.moveTo,"click":pag.click},
    "keyboard":{}
}

Andriod_bind = {}