<jupyter_start><jupyter_text>**DATA SCIENCE TEAM 1**<NAME> - Data Science Manager<NAME> - Data Scientist <NAME> - Data Analyst<NAME> - Data Science Researcher <NAME> - Quantitative Analyst<NAME> - Data Analyst - Project Lead<NAME> - Data Scientist In this model we will be creating a Payment Processing and Network Application using Python and Deploying it.<jupyter_code>#Importing the essential libraries for the payment application. 
import flask #Importing flask for api use. 
import numpy as np #helps create arrays and manipulate the data. 
import pandas as pd #to work with a data frame and optimize.
import matplotlib.pyplot as plt #to create plots with the data. 
#import seaborn as sns not quite sure if we will use charts yet.   


#! mkdir PPNPflask - I was going to create an environment but googlecolab
# doesn't seem to understand the environment, any advice? ~ Ryan T resource I was looking at https://help.pythonanywhere.com/pages/IPythonNotebookVirtualenvs/
#! cd PPNPflask
#! python3 -m venv venv
! sudo apt install python3-tk tk
! virtualenv --python=python3 ../venv
#! source ../"tbd"


#Truelayer API
#d76d0409-b033-46c6-b0ca-a251684d5eea - secretclientID
#dswclientid-a1185d - clientid
#Data API
#https://api.truelayer.com/data/v1/cards

#curl -X POST \
- d grant_type= \
- d client_id=${dswclientid-a1185d} \
- d client_secret=${<KEY>} \
- d scope =payments \
#https://auth.truelayer.com/connect/token<jupyter_output><empty_output><jupyter_text>A small banking appication using python:Create account INPUT: Full name, initial balance (min. Rs. 5,000) OUTPUT: Account number (new)Balance query INPUT: Account number OUTPUT: BalanceDeposit amount: INPUT: Account number, amount OUTPUT: Final balanceWithdraw amount: INPUT: Account number, amount OUTPUT: Final balance (ensure minimum balance is Rs. 5,000)Search by name: INPUT: Name (Full or partial) OUTPUT: Full name, Account numberClose account: INPUT: Account number OUTPUT: Balance (to be refunded) (status should become inactive or closed and should reflect appropriately in all operations)<jupyter_code>#I am not sure if we would even be used.
import datetime#Helps with time in python.
import re #Used to / 
import pickle#Sterlizing the objects but concerned that non-Python programs might 
#not recognize.

def save_obj(obj, name):
    with open('obj/'+ name + '.pkl', 'wb') as f:
        pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)

def load_obj(name):
    with open('obj/' + name + '.pkl', 'rb') as f:
        return pickle.load(f)

class Account:
	number_accounts = 0
	#interest_rate = {'Savings':#, 'Current':#,'Fixed':#}

	def __init__(person):
		pass

	def create_account(person, name, balance):
		Account.number_accounts += 1
		person.account_no = Account.number_accounts
		person.active = 1
		person.name = name
		person.balance = balance
		return person.account_no

	def update_interest(person):
		rate = Account.interest_rate[person.account_type]

		if (datetime.datetime.now().year == person.last_updated[1]):
			dif = (datetime.datetime.now().month - person.last_updated[0])
		else:
			if (datetime.datetime.now().month < person.last_updated[0]):
				dif = (datetime.datetime.now().year - person.last_updated[1]-1)*12 + 12 - (person.last_updated[0] - datetime.datetime.now().month)
			else:
				dif = (datetime.datetime.now().year - person.last_updated[1])*12 + (datetime.datetime.now().month - person.last_updated[0])

		person.balance += (dif*rate*person.balance/100)
		person.last_updated = [datetime.datetime.now().month, datetime.datetime.now().year]

	def balance_query(person):
		person.update_interest()		
		return person.balance

	def deposit(person):
		person.update_interest()
		dep_amount = input("Enter the amount you wish to deposit: ")
		person.balance += dep_amount
		return person.balance

	def withdraw(person):
		withdraw_amount = input("Enter the amount you wish to withdraw: ")

		if person.balance - withdraw_amount >= 0:
			person.balance -= withdraw_amount
			return person.balance

		print("Insufficient funds to withdraw given amount.")
		return -1

	def compare_name(person, search_name):
		pattern = '[\w\s]*'+search_name+'[\w\s]*'
		prog = re.compile(pattern,re.I)
		result = prog.match(person.name)
		if result == None:
			return [-1]
		if result.group(0) == person.name:
			person.balance_query()
			return [1, person.name, person.account_no]
		else:
			return [-1]

	def close_account(person):
		balance = person.balance_query()
		person.balance = 0
		print("You have withdrawn an amount of " + str(balance) + " and closed your account.")
		person.active = 0

class Savings(Account):
	def __init__(person):
		person.last_updated = [datetime.datetime.now().month, datetime.datetime.now().year]
		person.account_type = "Savings"

	def withdraw(person):
		withdraw_amount = input("Amount you wish to withdraw: ")

		if person.balance - withdraw_amount >= 100000:# Not sure the amount or if I should link back to account.
			person.balance -= withdraw_amount
			return person.balance

		print("Insufficient funds.")
		return -1

class Current(Account):
	def __init__(person):
		person.last_updated = [datetime.datetime.now().month, datetime.datetime.now().year]
		person.account_type = "Current"	


class Fixed(Account):#Higher Interest account
	def __init__(person):
		person.last_updated = [datetime.datetime.now().month, datetime.datetime.now().year]
		person.account_type = "Fixed"

	def deposit(person):
		print("This is a Fixed Account. You will not be able to deposit.")
		return -1

	def withdraw(person):
		print("This is a Fixed account. Close the account if you want to withdraw.")
		return -1



accounts = load_obj('accounts')
closed_accounts = load_obj('closed_accounts')
Account.number_accounts = accounts[0]

while 1:
	print("1. Create Account\s2. Balance query\s3. Deposit\s4. Withdraw\s5. Search by name\s6. Close Account\s0. Exit")
	choice = input()

	if choice == 1:
		choice = input("1. Savings\s2. Current\s3. Fixed\s")

		if choice == 1:
			new_account = Savings()

		elif choice == 2:
			new_account = Current()

		elif choice == 3:
			new_account = Fixed()

		else:
			print("Invalid Choice")

		name = raw_input("Enter Full Name: ")
		balance = input("Initial balance: ")

		ac_no = new_account.create_account(name, balance)
		accounts[ac_no] = new_account
		print("Your account number is ", ac_no)

	elif choice == 2:
		ac_no = input("Enter your account number: ")
		account = accounts[ac_no]
		print("Your balance is ", account.balance_query())

	elif choice == 3:
		ac_no = input("Enter your account number: ")
		account = accounts[ac_no]
		balance = account.deposit()
		if balance != -1:
				print("Your balance is ", balance)

	elif choice == 4:
		ac_no = input("Enter your account number: ")
		account = accounts[ac_no]
		balance = account.withdraw()
		if balance != -1:
				print("Your balance is ", balance)		
		
	elif choice == 5:
		search_name = raw_input("Enter name you want to search for: ")
		flag = 0
		for ac_no, account in accounts.iteritems():
			if ac_no != 0:
				result = account.compare_name(search_name)
				if result[0] == 1:
					print(str(result[1])+' '+str(result[2]))
					flag = 1

		if flag == 0:
			print("Name hasn't been found")	

	elif choice == 6:
		ac_no = input("Enter your account number: ")
		account = accounts[ac_no]
		if (raw_input("Are you sure you want to close your account? (y/n): ") == 'y'):
			account.close_account()
			closed_accounts[ac_no] = account
			del accounts[ac_no]

	elif choice == 0:
		accounts[0] = Account.number_accounts
		save_obj(accounts,'accounts')
		save_obj(closed_accounts,'closed_accounts')

		break

	else:
		print("Invalid input")<jupyter_output><empty_output><jupyter_text>I am getting some errors with the Tkinter library.  When I run it locally I get the error "_tkinter.TclError: couldn't open "pile1.gif": no such file or directory".  pile1.gif is one of the images (which will change once it is operational), I originally thought the issue had to do with my working directory but I found it did not as I made sure I had all the same images in the correct working directory and got the same error, then I went onto comment out this line and still got the same error. I've had trouble solving this issue.  Now when I run it on the colab I am getting a different error with Tkinter, this error has to do with display ("no display name and no $DISPLAY environment variable"), pretty sure this issue has to do with the display.<jupyter_code>#I'm getting an error reading an image in
#I tried commenting that line our but still get the error, I think it has to do with Tkinter
# For some reason I'm having trouble using the package 
import tkinter as tk
from tkinter import messagebox
from time import gmtime, strftime
import matplotlib
matplotlib.use('Agg')
#OS is used to get access to images locally
import os
os.chdir("working directory where .gif images are saved")


#Function to check if input is number
def is_number(s):
    try:
        float(s)
        return 1
    except ValueError:
        return 0
#Function to check account number
def check_acc_nmb(num):
    try:
        fpin=open(num+".txt",'r')
    except FileNotFoundError:
        messagebox.showinfo("Error","Invalid Credentials!\nTry Again!")
        return 0
    fpin.close()
    return
#Function to return home 
def home_return(master):
  master.destroy()
  Main_Menu()
 #Function to check account number
def write(master,name,oc,pin):

    if( (is_number(name)) or (is_number(oc)==0) or (is_number(pin)==0)or name==""):
        messagebox.showinfo("Error","Invalid Credentials\nPlease try again.")
    master.destroy()
    return

    f1=open("Accnt_Record.txt",'r')
    accnt_no=int(f1.readline())
    accnt_no+=1
    f1.close()

    f1=open("Accnt_Record.txt",'w')
    f1.write(str(accnt_no))
    f1.close()

    fdet=open(str(accnt_no)+".txt","w")
    fdet.write(pin+"\n")
    fdet.write(oc+"\n")
    fdet.write(str(accnt_no)+"\n")
    fdet.write(name+"\n")
    fdet.close()

    frec=open(str(accnt_no)+"-rec.txt",'w')
    frec.write("Date                             Credit      Debit     Balance\n")
    frec.write(str(strftime("[%Y-%m-%d] [%H:%M:%S]  ",gmtime()))+"     "+oc+"              "+oc+"\n")
    frec.close()

    messagebox.showinfo("Details","Your Account Number is:"+str(accnt_no))
    master.destroy()
    return

#Write credit 
def crdt_write(master,amt,accnt,name):

    if(is_number(amt)==0):
        messagebox.showinfo("Error","Invalid Credentials\nPlease try again.")
    master.destroy()
    return

    fdet=open(accnt+".txt",'r')
    pin=fdet.readline()
    camt=int(fdet.readline())
    fdet.close()
    amti=int(amt)
    cb=amti+camt
    fdet=open(accnt+".txt",'w')
    fdet.write(pin)
    fdet.write(str(cb)+"\n")
    fdet.write(accnt+"\n")
    fdet.write(name+"\n")
    fdet.close()
    frec=open(str(accnt)+"-rec.txt",'a+')
    frec.write(str(strftime("[%Y-%m-%d] [%H:%M:%S]  ",gmtime()))+"     "+str(amti)+"              "+str(cb)+"\n")
    frec.close()
    messagebox.showinfo("Operation Successfull!!","Amount Credited Successfully!!")
    master.destroy()
    return

def debit_write(master,amt,accnt,name):

    if(is_number(amt)==0):
        messagebox.showinfo("Error","Invalid Credentials\nPlease try again.")
        master.destroy()
        return

    fdet=open(accnt+".txt",'r')
    pin=fdet.readline()
    camt=int(fdet.readline())
    fdet.close()
    if(int(amt)>camt):
        messagebox.showinfo("Error!!","You dont have that amount left in your account\nPlease try again.")
    else:
        amti=int(amt)
        cb=camt-amti
        fdet=open(accnt+".txt",'w')
        fdet.write(pin)
        fdet.write(str(cb)+"\n")
        fdet.write(accnt+"\n")
        fdet.write(name+"\n")
        fdet.close()
        frec=open(str(accnt)+"-rec.txt",'a+')
        frec.write(str(strftime("[%Y-%m-%d] [%H:%M:%S]  ",gmtime()))+"     "+"              "+str(amti)+"              "+str(cb)+"\n")
        frec.close()
        messagebox.showinfo("Operation Successfull!!","Amount Debited Successfully!!")
        master.destroy()
        return
#Write Debit 
def debit_write(master,amt,accnt,name):

  if(is_number(amt)==0):
      messagebox.showinfo("Error","Invalid Credentials\nPlease try again.")
      master.destroy()
      return

  fdet=open(accnt+".txt",'r')
  pin=fdet.readline()
  camt=int(fdet.readline())
  fdet.close()
  if(int(amt)>camt):
    messagebox.showinfo("Error!!","You dont have that amount left in your account\nPlease try again.")
  else:
    amti=int(amt)
    cb=camt-amti
    fdet=open(accnt+".txt",'w')
    fdet.write(pin)
    fdet.write(str(cb)+"\n")
    fdet.write(accnt+"\n")
    fdet.write(name+"\n")
    fdet.close()
    frec=open(str(accnt)+"-rec.txt",'a+')
    frec.write(str(strftime("[%Y-%m-%d] [%H:%M:%S]  ",gmtime()))+"     "+"              "+str(amti)+"              "+str(cb)+"\n")
    frec.close()
    messagebox.showinfo("Operation Successfull!!","Amount Debited Successfully!!")
    master.destroy()
    return
#Get Credit Amount 
def Cr_Amt(accnt,name):
    creditwn=tk.Tk()
    creditwn.geometry("600x300")
    creditwn.title("Credit Amount")
    creditwn.configure(bg="orange")
    fr1=tk.Frame(creditwn,bg="blue")
    l_title=tk.Message(creditwn,text="UNITED BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="center")
    l_title.config(font=("Courier","50","bold"))
    l_title.pack(side="top")
    l1=tk.Label(creditwn,relief="raised",text="Enter Amount to be credited: ")
    e1=tk.Entry(creditwn,relief="raised")
    l1.pack(side="top")
    e1.pack(side="top")
    b=tk.Button(creditwn,text="Credit",relief="raised",command=lambda:crdt_write(creditwn,e1.get(),accnt,name))
    b.pack(side="top")
    creditwn.bind("<Return>",lambda x:crdt_write(creditwn,e1.get(),accnt,name))
#Get Debit Amount
def De_Amt(accnt,name):
    debitwn=tk.Tk()
    debitwn.geometry("600x300")
    debitwn.title("Debit Amount")
    debitwn.configure(bg="orange")
    fr1=tk.Frame(debitwn,bg="blue")
    l_title=tk.Message(debitwn,text="UNITED BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="center")
    l_title.config(font=("Courier","50","bold"))
    l_title.pack(side="top")
    l1=tk.Label(debitwn,relief="raised",text="Enter Amount to be debited: ")
    e1=tk.Entry(debitwn,relief="raised")
    l1.pack(side="top")
    e1.pack(side="top")
    b=tk.Button(debitwn,text="Debit",relief="raised",command=lambda:debit_write(debitwn,e1.get(),accnt,name))
    b.pack(side="top")
    debitwn.bind("<Return>",lambda x:debit_write(debitwn,e1.get(),accnt,name))
#Display Balance 
def disp_bal(accnt):
    fdet=open(accnt+".txt",'r')
    fdet.readline()
    bal=fdet.readline()
    fdet.close()
    messagebox.showinfo("Balance",bal)
 #Display Transaction History 
def disp_tr_hist(accnt):
    disp_wn=tk.Tk()
    disp_wn.geometry("900x600")
    disp_wn.title("Transaction History")
    disp_wn.configure(bg="orange")
    fr1=tk.Frame(disp_wn,bg="blue")
    l_title=tk.Message(disp_wn,text="UNITED BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="center")
    l_title.config(font=("Courier","50","bold"))
    l_title.pack(side="top")
    fr1=tk.Frame(disp_wn)
    fr1.pack(side="top")
    l1=tk.Message(disp_wn,text="Your Transaction History:",padx=100,pady=20,width=1000,bg="blue",fg="orange",relief="raised")
    l1.pack(side="top")
    fr2=tk.Frame(disp_wn)
    fr2.pack(side="top")
    frec=open(accnt+"-rec.txt",'r')
    for line in frec:
        l=tk.Message(disp_wn,anchor="w",text=line,relief="raised",width=2000)
        l.pack(side="top")
    b=tk.Button(disp_wn,text="Quit",relief="raised",command=disp_wn.destroy)
    b.pack(side="top")
    frec.close()
 #Display login menu 
 #uses images here, .gif
def logged_in_menu(accnt,name):
    rootwn=tk.Tk()
    rootwn.geometry("1600x500")
    rootwn.title("UNITED BANK-"+name)
    rootwn.configure(background='orange')
    fr1=tk.Frame(rootwn)
    fr1.pack(side="top")
    l_title=tk.Message(rootwn,text="SIMPLE BANKING\n SYSTEM",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="center")
    l_title.config(font=("Courier","50","bold"))
    l_title.pack(side="top")
    label=tk.Label(text="Logged in as: "+name,relief="raised",bg="black",fg="white",anchor="center",justify="center")
    label.pack(side="top")
    img2=tk.PhotoImage(file="credit.gif")
    myimg2=img2.subsample(2,2)
    img3=tk.PhotoImage(file="debit.gif")
    myimg3=img3.subsample(2,2)
    img4=tk.PhotoImage(file="balance1.gif")
    myimg4=img4.subsample(2,2)
    img5=tk.PhotoImage(file="transaction.gif")
    myimg5=img5.subsample(2,2)
    b2=tk.Button(image=myimg2,command=lambda: Cr_Amt(accnt,name))
    b2.image=myimg2
    b3=tk.Button(image=myimg3,command=lambda: De_Amt(accnt,name))
    b3.image=myimg3
    b4=tk.Button(image=myimg4,command=lambda: disp_bal(accnt))
    b4.image=myimg4
    b5=tk.Button(image=myimg5,command=lambda: disp_tr_hist(accnt))
    b5.image=myimg5

    img6=tk.PhotoImage(file="logout.gif")
    myimg6=img6.subsample(2,2)
    b6=tk.Button(image=myimg6,relief="raised",command=lambda: logout(rootwn))
    b6.image=myimg6


    b2.place(x=100,y=150)
    b3.place(x=100,y=220)
    b4.place(x=900,y=150)
    b5.place(x=900,y=220)
    b6.place(x=500,y=400)
#Display Log out 
def logout(master):

  messagebox.showinfo("Logged Out","You Have Been Successfully Logged Out!!")
  master.destroy()
  Main_Menu()
#Check if logged in 
def check_log_in(master,name,acc_num,pin):
    if(check_acc_nmb(acc_num)==0):
        master.destroy()
        Main_Menu()
        return

    if( (is_number(name))  or (is_number(pin)==0) ):
        messagebox.showinfo("Error","Invalid Credentials\nPlease try again.")
        master.destroy()
        Main_Menu()
    else:
      master.destroy()
      logged_in_menu(acc_num,name)
#Layout of log in page 
def log_in(master):
  master.destroy()
  loginwn=tk.Tk()
  loginwn.geometry("600x300")
  loginwn.title("Log in")
  loginwn.configure(bg="orange")
  fr1=tk.Frame(loginwn,bg="blue")
  l_title=tk.Message(loginwn,text="UNITED BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="center")
  l_title.config(font=("Courier","50","bold"))
  l_title.pack(side="top")
  l1=tk.Label(loginwn,text="Enter Name:",relief="raised")
  l1.pack(side="top")
  e1=tk.Entry(loginwn)
  e1.pack(side="top")
  l2=tk.Label(loginwn,text="Enter account number:",relief="raised")
  l2.pack(side="top")
  e2=tk.Entry(loginwn)
  e2.pack(side="top")
  l3=tk.Label(loginwn,text="Enter your PIN:",relief="raised")
  l3.pack(side="top")
  e3=tk.Entry(loginwn,show="*")
  e3.pack(side="top")
  b=tk.Button(loginwn,text="Submit",command=lambda: check_log_in(loginwn,e1.get().strip(),e2.get().strip(),e3.get().strip()))
  b.pack(side="top")
  b1=tk.Button(text="HOME",relief="raised",bg="black",fg="white",command=lambda: home_return(loginwn))
  b1.pack(side="top")
  loginwn.bind("<Return>",lambda x:check_log_in(loginwn,e1.get().strip(),e2.get().strip(),e3.get().strip()))
#Lsyout of Create Account Page
def Create():

    crwn=tk.Tk()
    crwn.geometry("600x300")
    crwn.title("Create Account")
    crwn.configure(bg="orange")
    fr1=tk.Frame(crwn,bg="blue")
    l_title=tk.Message(crwn,text="UNITED BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="center")
    l_title.config(font=("Courier","50","bold"))
    l_title.pack(side="top")
    l1=tk.Label(crwn,text="Enter Name:",relief="raised")
    l1.pack(side="top")
    e1=tk.Entry(crwn)
    e1.pack(side="top")
    l2=tk.Label(crwn,text="Enter opening credit:",relief="raised")
    l2.pack(side="top")
    e2=tk.Entry(crwn)
    e2.pack(side="top")
    l3=tk.Label(crwn,text="Enter desired PIN:",relief="raised")
    l3.pack(side="top")
    e3=tk.Entry(crwn,show="*")
    e3.pack(side="top")
    b=tk.Button(crwn,text="Submit",command=lambda: write(crwn,e1.get().strip(),e2.get().strip(),e3.get().strip()))
    b.pack(side="top")
    crwn.bind("<Return>",lambda x:write(crwn,e1.get().strip(),e2.get().strip(),e3.get().strip()))
    return
#Main Menu 
#Runs everything
def Main_Menu():
    rootwn=tk.Tk()
    rootwn.geometry("1600x500")
    rootwn.title("UNITED Bank")
    rootwn.configure(background='orange')
    fr1=tk.Frame(rootwn)
    fr1.pack(side="top")
    #bg_image = tk.PhotoImage(file ="pile1.gif")
    #x = tk.Label (image = bg_image)
    x.place(y=-400)
    l_title=tk.Message(text="SIMPLE BANKING\n SYSTEM",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="center")
    l_title.config(font=("Courier","50","bold"))
    l_title.pack(side="top")
    imgc1=tk.PhotoImage(file="new.gif")
    imglo=tk.PhotoImage(file="login.gif")
    imgc=imgc1.subsample(2,2)
    imglog=imglo.subsample(2,2)

    b1=tk.Button(image=imgc,command=Create)
    b1.image=imgc
    b2=tk.Button(image=imglog,command=lambda: log_in(rootwn))
    b2.image=imglog
    img6=tk.PhotoImage(file="quit.gif")
    myimg6=img6.subsample(2,2)

    b6=tk.Button(image=myimg6,command=rootwn.destroy)
    b6.image=myimg
    b1.place(x=800,y=300)
    b2.place(x=800,y=200)
    b6.place(x=920,y=400)

    rootwn.mainloop()

Main_Menu()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16109051663460186, 'fraction_numerical': 0.020928159166627564, 'mean_word_length': 4.304131408661025, 'pattern_counts': {'":': 1, '<': 26, '<?xml version=': 0, '>': 29, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '632585', 'license': 'Unlicense', 'n_tokens_mistral': 8096, 'n_tokens_neox': 7606, 'n_words': 1484, 'path': 'Project 19 - Banking_Project.ipynb', 'repo_name': 'Worlddatascience/DataScienceCohort', 'size': '21395'}