#dbA = SQLAlchemy(app) conn = mysql.connect() cursor = conn.cursor() # Initialize extensions mail = Mail(app) celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) #Firebase connection firebase = firebaseConnection() #.................... @app.route("/") def home(): return render_template("home.html") @app.route("/login", methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): # Check id user exisit in the database cur, db , engine = connection2()
def Detect(self, businessRule_ID): cur1, db1, engine1 = connection2() #SMI_DB status, cur2, db2, engine2 = BankConnection() #bank_DB self.businessRule_ID = businessRule_ID #0 from template , 1 bank uplaoded their rules '''Firebase''' firebase = firebaseConnection() db = firebase.database() if self.businessRule_ID == 0: #from template self.risk_countries = db.child('Rule1').child( 'highRiskCountries').get().val() self.sanction_list = db.child('Rule4').child( 'blackList').get().val() self.exceed_avg_tran = db.child('Rule2').child( 'exceedingAvgTransaction').get().val() self.amount = db.child('Rule3').child( 'suspiciousTransaction').child('amount').get().val() if self.businessRule_ID == 1: # from bank file self.Rules = db.child('Rules').get().val() self.sanctionList = db.child('sanctionList').get().val() self.highRiskCountries = db.child('highRiskCountries').get().val() self.MultiLevelRules = db.child('MultiLevelRules').get().val() '''df = pd.read_csv('GeneratedDataset.csv') df.to_sql(name='transaction', con=engine2, if_exists='append', index=False)''' classifier = DecisionTree() classifier.DecisionTreeClassifier() #MULTI CERTIREA #Create profiles cur2.execute('SELECT clientID, clientName FROM bank_db.transaction') result = list(set(list(cur2.fetchall()))) cur2.close() db2.close() #get client who flagged suspious transactions cur1.execute('SELECT clientName FROM SMI_DB.SuspiciousTransaction') suspsuoiusClient = list(set(list(cur1.fetchall()))) i = 1 numOFclean = 0 numOFLow = 0 numOfHigh = 0 numOFMeduim = 0 for id, name in result: dt_class = 0 mc_class = 0 transaction_class = 0 profile_score = 0 profile_class = 'clean' GeneralSearch_result = 0 GeneralSearch_class = 0 NumberOfRecord = 0 weightTree = 0.5 if self.businessRule_ID == 0: # from template mc = MultiCriteria() mc_class = mc.multi_criteria(id, self.risk_countries, self.sanction_list, self.exceed_avg_tran, self.amount) if self.businessRule_ID == 1: #from bank file mc = NewMultiCriteria() mc_class = mc.getRules(self.Rules, self.sanctionList, self.highRiskCountries, self.MultiLevelRules, id) print('mc_class', mc_class) print('mc_class type', type(mc_class)) # If the client has any suspsuoius transaction run general search if any(name in s for s in suspsuoiusClient): dt_class = 1 '''search = GeneralSearch('"' + name + '"', id) search.twitter_search() GeneralSearch_result, GeneralSearch_class = search.google_search()''' if (name in s for s in suspsuoiusClient ): #counter for the number of suspsuoius transactions NumberOfRecord = NumberOfRecord + 1 if NumberOfRecord < 1: weightTree = 0.75 try: transaction_class = ((weightTree * dt_class) + ((1 - weightTree) * mc_class) / 2) except ZeroDivisionError: transaction_class = 0 profile_score = (0.5 * transaction_class) + (0.5 * GeneralSearch_result) if 0.7 < profile_score <= 1: profile_class = 'High' numOfHigh = numOfHigh + 1 elif 0.33 < profile_score <= 0.7: profile_class = 'Medium' numOFMeduim = numOFMeduim + 1 elif 0 < profile_score <= 0.33: profile_class = 'Low' numOFLow = numOFLow + 1 else: profile_class = 'Clean' numOFclean = numOFclean + 1 print('client ID: ', id) print('client Name: ', name) print('Multi Criteria Score: ', mc_class) #print('Before IF statment', profile_class) print('search_result: ', GeneralSearch_result) print('transaction_class: ', transaction_class) print('GeneralSearch_class: ', GeneralSearch_class) print('profile class: ', profile_class) print('***********************') if (profile_class == 'High') or (profile_class == 'Medium'): date_now = datetime.now() formatted_date = date_now.strftime('%Y-%m-%d %H:%M:%S') query = "INSERT INTO ClientCase (caseClassification, date, clientID) VALUES(%s,%s, %s)" val = (profile_class, formatted_date, id) cur1.execute(query, val) cur1.execute( "UPDATE SMI_DB.Client SET profileClassification= '%s'WHERE clientID='%s' " % (profile_class, id)) cur1.close() db1.close() print('Summary:') print('************') print('Total Number of clients', len(result)) print('Number of clean clients:', numOFclean) print('Number of Low clients:', numOFLow) print('Number of Meduim clients:', numOFMeduim) print('Number of High clients:', numOfHigh)
def uploadBR(): # Only logged in users can access bank profile if session.get('username') == None: return redirect(url_for('home')) form = manageBankDataForm() search_form = SearchForm() status, cur, db, engine = BankConnection() is_Br_submitted = 0 file_exttintion_json = 0 isFB_Connected = 'false' operands = ['==', 'not', 'or', 'in', 'and', '<', '>', '<=', '>='] print() target = os.path.join(APP_ROOT, 'Br_User/') print(target) if not os.path.isdir(target): os.mkdir(target) file = request.files.get('file_user') print(file) if file is None: return render_template("ManageBankData.html", form=form, form2=search_form, isFB_Connected=isFB_Connected, is_Br_submitted=1) filename = file.filename print(filename) if filename.split(".", 1)[1] != 'json': file_exttintion_json = 1 return render_template("ManageBankData.html", form=form, form2=search_form, isFB_Connected=isFB_Connected, is_Br_submitted=is_Br_submitted, file_exttintion_json=file_exttintion_json) else: dest = "/".join([target, filename]) print(dest) file.save(dest) with open('Br_file/Br1.json') as f: data = json.load(f) pprint(data) if 'Rules' not in data: print( 'ERROR...your file is not well structured... please follow the file format in the sample' ) firebase = firebaseConnection() fb = firebase.database() print('Number of rules', len(data['Rules'])) i = 1 for each in data['Rules']: ### 1-check Key words structure ##### if 'Rule{}'.format(i) not in data['Rules']: print( 'ERROR in your file structure in Rule{} please follow the format' .format(i)) break else: print('Correct format') ### 2- check if all attriubtes in dataset ### if data['Rules']['Rule' + str(i)][0] not in cur.column_names: print('Rule{} attribute {} not found in the dataset'.format( i, data['Rules']['Rule1'][0])) break else: print('all attributes were found in dataset') ### 3- check if theres illegal operand #### if data['Rules']['Rule' + str(i)][1] not in operands: print('Illegal operand ({})in Rule{}'.format( data['Rules']['Rule1'][1], i)) break else: print('all legal operand') #### 4- If there's rule for sanction, check if names are uploaded and get the names #### if data['Rules']['Rule' + str(i)][2] == 'sanctionList': print('Rule for sanction list') if ('sanctionList' not in data): print( 'for Rule{} Please upload the sanction list section to the file' .format(i)) else: print('Sanction list is uploaded:') if len(data['sanctionList']) == 0: print('Sanction List is empty please upload the names') print(data['sanctionList']) else: print('No Rule for sanction list ') #### 5- If there's rule for risk countries, check if countries are uploaded and get the countries #### if data['Rules']['Rule' + str(i)][2] == 'HighRiskCountries': print('Rule for Risk countries') if ('HighRiskCountries' not in data): print( 'for Rule{} Please upload the HighRiskCountries list section to the file' .format(i)) else: print('HighRiskCountries list is uploaded:') if len(data['HighRiskCountries']) == 0: print( 'HighRiskCountries is empty please upload the names' ) print(data['HighRiskCountries']) else: print('No Rule for HighRiskCountries ') print('*******************************') fb.child('Rules').child('Rule' + str(i)).set(data['Rules']['Rule' + str(i)]) i = i + 1 return redirect((url_for('manageBankData', form=form, form2=search_form, isFB_Connected=isFB_Connected, is_Br_submitted=is_Br_submitted)))