def localcall(barcodeData, idR, c, URL, URLV, date, csv): ######Datetime registry = dt.datetime.now() value = 0 for x in master1: if barcodeData == x: value = 1 pass else: pass pass if value == 1: GPIO.setup(pluma, GPIO.OUT) GPIO.output(pluma, GPIO.LOW) time.sleep(1) GPIO.output(pluma, GPIO.HIGH) GPIO.setup(pluma, GPIO.IN) logging.info('Acceso concedido') csv.write("{},{},{}\n".format(registry, barcodeData, "Valido")) csv.flush() time.sleep(3) pass else: print("No Encontrado") awsCall(barcodeData, idR, c, URL, URLV) pass return
def entry(): print("******************************** New Entry ********************************") ID = 'S20' + input("Enter student ID: S20") import csv with open('Pin_List.csv', 'rt') as f: reader = csv.reader(f, delimiter=',') # good point by @paco for row in reader: for field in row: if field == ID: print("You have already registered!\nContact operators for further assistance...\n") return digitlist = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] while True: err = 0 PIN = input("Enter a 3 digit pin: ") if len(PIN) != 3: print("Error: Pin entered does not contain 3 digits!") err = 1 for digit in PIN: if digit not in digitlist: print("Error: invalid pin (pin must be digits 1-9 only)") err = 1 if err == 0: PIN = int(PIN) break email = input("Enter your email address: ") print("\nYour information:\nStudent ID: " + ID + "\nPin: " + str(PIN) + "\nEmail Address: " + email) confirm = input("All data correct?(Y/N): ") con = ['Y', 'y'] if confirm in con: filename = "Pin_List.csv" ap = argparse.ArgumentParser() ap.add_argument("-o", "--output", type=str, default=filename, help="path to output CSV file containing barcodes") args = vars(ap.parse_args()) csv = open(args["output"], "a") found = set() if ID not in found: csv.write("{},{},{}\n".format(ID, PIN, email)) csv.flush() found.add(ID) print("Ok, data saved!") else: print("Data discarded!") print("\n")
def readQR(self, num): ap = argparse.ArgumentParser() ap.add_argument("-o", "--output", type=str, default="barcodes.csv", help="path to output CSV file containing barcodes") args = vars(ap.parse_args()) print("[INFO] starting video stream...") vs = VideoStream(src=0).start() csv = open(args["output"], "a") found = set() frame = vs.read() frame = imutils.resize(frame, width=400) barcodes = pyzbar.decode(frame) for barcode in barcodes: (x, y, w, h) = barcode.rect cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) barcodeData = barcode.data.decode("utf-8") barcodeType = barcode.type text = "{} ({})".format(barcodeData, barcodeType) cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) if barcodeData not in found: csv.write("{}\n".format(barcodeData)) csv.flush() found.add(barcodeData) cv2.imshow("Barcode Scanner", frame) key = cv2.waitKey(1) & 0xFF cv2.waitKey(2000) print("[INFO] cleaning up...") csv.close() cv2.destroyAllWindows() vs.stop()
def bench(ex, i): print("calling bench on %s %s" % (ex, i)) cmd_params = [ex[-1]] language = ex[0] algo = ex[3] options = ex[2] executable_used = ex[-1] input_size = i.split("/")[-1].split("-")[0] # file name : size-version.in t =0 devnull = open('/tmp/blu', 'w') inp = open(i, 'r') reps = 1 # no repetition yet for rep in range(reps): res = subprocess.check_output(cmd_params, stdin=inp, stderr=devnull) t += int(res.decode('utf-8')) exec_time = t / reps csv.write("%s,%s,%s,%s,%s,%s,%s,%s\n" % (machine, language, algo, options, executable_used, i.split("/")[-1], input_size, exec_time)) csv.flush()
def bench(ex, i): print("calling bench on %s %s" % (ex, i)) cmd_params = [ex[-1]] language = ex[0] algo = ex[3] options = ex[2] executable_used = ex[-1] input_size = i.split("/")[-1].split("-")[0] # file name : size-version.in t = timeit.Timer( stmt="subprocess.call(%s, stdin=inp, stdout=devnull, stderr=devnull)" % (cmd_params), setup= "import subprocess; devnull = open('/tmp/blu', 'w'); inp = open('%s', 'r')" "" % i) reps = 3 # no repetition yet exec_time = min( t.repeat(reps, number=1) ) # recommended by python doc... # sum(t.repeat(reps, number=1)) / reps csv.write("%s,%s,%s,%s,%s,%s,%s,%s\n" % (machine, language, algo, options, executable_used, i.split("/")[-1], input_size, exec_time)) csv.flush()
print "Original script (Seb's stats script v0.4 ) written by Sebastien Pierrel produced only statistics for objects created" print "=========================================================================" print "Input variables " print "list of users by team : vectors users [1] to [6]" print "date_from=" + str(date_from) print "date_to=" + str(date_to) print "bbox : min_lon=" + str(min_lon) + ", max_lon=" + str( max_lon) + ", min_lat=" + str(min_lat) + ", max_lat=" + str(max_lat) print "Checking changesets for " osmApi = OsmApi.OsmApi(app="api.openstreetmap.fr", debug=True) csv = open(nom_csv, 'wb') csv.write( "ekip, user, changeset, node_c,way_c,relation_c, node_m,way_m,relation_m, node_d,way_d,relation_d \n" ) csv.flush() nom_csv_team = nom_csv + '_team' csv_team = open(nom_csv_team, 'wb') csv_team.write( "ekip, user, changeset, node_c,way_c,relation_c, node_m,way_m,relation_m, node_d,way_d,relation_d \n" ) csv_team.flush() print "trainee number of changesets" for ekip in range(1, 8): stats_team = { "changeset": 0, "node_c": 0, "way_c": 0, "relation_c": 0, "node_m": 0, "way_m": 0,
print " Statistics of history of contribution by user and team" print "date range and bbox as input" print "Objects (ie. nodes, ways, relations) created, modified and deleted" print "Original script (Seb's stats script v0.4 ) written by Sebastien Pierrel produced only statistics for objects created" print "=========================================================================" print "Input variables " print "list of users by team : vectors users [1] to [6]" print "date_from=" + str(date_from) print "date_to=" + str(date_to) print "bbox : min_lon=" + str(min_lon) + ", max_lon=" + str(max_lon) + ", min_lat=" + str(min_lat) + ", max_lat=" + str(max_lat) print "Checking changesets for " osmApi = OsmApi.OsmApi(app = "api.openstreetmap.fr",debug=True) csv = open(nom_csv, 'wb') csv.write("ekip, user, changeset, node_c,way_c,relation_c, node_m,way_m,relation_m, node_d,way_d,relation_d \n") csv.flush() nom_csv_team=nom_csv+'_team' csv_team = open(nom_csv_team, 'wb') csv_team.write("ekip, user, changeset, node_c,way_c,relation_c, node_m,way_m,relation_m, node_d,way_d,relation_d \n") csv_team.flush() print "trainee number of changesets" for ekip in range(1,8): stats_team= {"changeset":0,"node_c":0, "way_c":0, "relation_c":0,"node_m":0, "way_m":0, "relation_m":0,"node_d":0, "way_d":0, "relation_d":0} print "\n ekip " + str(ekip) for user in users[ekip]: stats = {"changeset":0,"node_c":0, "way_c":0, "relation_c":0,"node_m":0, "way_m":0, "relation_m":0,"node_d":0, "way_d":0, "relation_d":0} changesets = getChangesets(username=user) nb_changesets=len(changesets) # print string.rjust(`x`, 2), string.rjust(`x*x`, 3), #print str(user) +"\t\t" + str(nb_changesets) print'%-20s %6d' % (user,nb_changesets)
def continuous_mode(self): # initialize the video stream and allow the camera sensor to warm up print("[INFO] starting video stream...") # vs = VideoStream(src=0).start() vs = VideoStream(usePiCamera=False).start( ) #JM changing to false since we are not using Pi camera.. time.sleep(2.0) # open the output CSV file for writing and initialize the set of # barcodes found thus far csv = open(args["output"], "w") found = set() # loop over the frames from the video stream while True: # grab the frame from the threaded video stream and resize it to # have a maximum width of 400 pixels frame = vs.read() frame = imutils.resize(frame, width=400) # find the barcodes in the frame and decode each of the barcodes barcodes = pyzbar.decode(frame) # loop over the detected barcodes for barcode in barcodes: # extract the bounding box location of the barcode and draw # the bounding box surrounding the barcode on the image (x, y, w, h) = barcode.rect cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) # the barcode data is a bytes object so if we want to draw it # on our output image we need to convert it to a string first barcodeData = barcode.data.decode("utf-8") barcodeType = barcode.type # draw the barcode data and barcode type on the image text = "{} ({})".format(barcodeData, barcodeType) cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) # if the barcode text is currently not in our CSV file, write # the timestamp + barcode to disk and update the set if barcodeData not in found: csv.write("{},{}\n".format(datetime.datetime.now(), barcodeData)) csv.flush() found.add(barcodeData) # show the output frame cv2.imshow("Barcode Scanner", frame) key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop if key == ord("q"): break # close the output CSV file do a bit of cleanup print("[INFO] cleaning up...") csv.close() cv2.destroyAllWindows() vs.stop()
def video(): # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-o", "--output", type=str, default="barcodes.csv", help="path to output CSV file containing barcodes") # ap.add_argument("-o1", "--output2", type=str, default=files_name, # help="path to output CSV file containing barcodes") args = vars(ap.parse_args()) # initialize time and date and make filename friendly time_header = str(datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')) # initialize the video stream and allow the camera sensor to warm up print("[ALERT] starting video stream...") print("Press 'Q' to exit") vs = VideoStream(src=0).start() # this is for a mobile solution #vs = VideoStream(usePiCamera=True).start() time.sleep(5.0) # open the output CSV file for writing and initialize the set of # barcodes found thus far csv = open(args["output"], "w") # time track variables. These are used to keep track of QR codes as they enter the screen found = [] found_time = [] found_status = [] ctxAuth = AuthenticationContext(url=settings['url']) # loop over the frames from the video stream while True: # grab the frame from the threaded video stream and resize it to # have a maximum width of 400 pixels frame = vs.read() frame = imutils.resize(frame, width=400) # find the barcodes in the frame and decode each of the barcodes barcodes = pyzbar.decode(frame) timestr = strftime("%m/%d/%Y %H:%M") # loop over the detected barcodes for barcode in barcodes: # extract the bounding box location of the barcode and draw # the bounding box surrounding the barcode on the image (x, y, w, h) = barcode.rect cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) # the barcode data is a bytes object so if we want to draw it # on our output image we need to convert it to a string first barcodeData = barcode.data.decode("utf-8") barcodeType = barcode.type # draw the barcode data and barcode type on the image text = "{} ({})".format(barcodeData, barcodeType) cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) # if the barcode text is currently not in our CSV file, write # the timestamp + barcode to disk and update the set # if barcode data has never been seen, check the user in and record id, date, and time information if barcodeData not in found: csv.write("{},{},{},{}\n".format(system_id, datetime.datetime.now(), barcodeData, "IN")) csv.flush() contentstr = "{},{},{},{}\n".format(system_id, timestr, barcodeData, "IN") create_list_item(ctx, contentstr) fname = "QRT" + "-" + system_id + "_" + time_header + ".csv" upload_file(ctx, contentstr, fname, bkcsvfolder) found.append(barcodeData) found_time.append(datetime.datetime.now()) found_status.append("IN") sys.stdout.write('\a') sys.stdout.flush() print(barcodeData + " checking IN at " + str(datetime.datetime.now()) + " at location: " + system_id) # if barcode information is found... elif barcodeData in found: time_check = datetime.datetime.now() - found_time[found.index( barcodeData)] status_check = found_status[found.index(barcodeData)] # if time exceeds wait period and user is checked in then check them out if time_check > t_value and status_check == "IN": index_loc = found.index(barcodeData) found_status[index_loc] = "OUT" found_time[index_loc] = datetime.datetime.now() csv.write("{},{},{},{},{}\n".format( system_id, datetime.datetime.now(), barcodeData, "OUT", time_check)) csv.flush() contentstr = "{},{},{},{},{}\n".format( system_id, timestr, barcodeData, "OUT", time_check) create_list_item(ctx, contentstr) fname = "QRT" + "-" + system_id + "_" + time_header + ".csv" upload_file(ctx, contentstr, fname, bkcsvfolder) sys.stdout.write('\a') sys.stdout.flush() print(barcodeData + " checking OUT at " + str(datetime.datetime.now()) + " at location: " + system_id + " for duration of " + str(time_check)) # if found and check-in time is less than the specified wait time then wait elif time_check < t_value and status_check == "OUT": pass # if found and time check exceeds specified wait time and user is checked out, delete ID and affiliated data from the list. This resets everything for said user and allows the user to check back in at a later time. elif time_check > t_value and status_check == "OUT": del found_status[index_loc] del found_time[index_loc] del found[index_loc] else: print("Something happened... error") # show the output frame cv2.imshow("QR Toolbox", frame) key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop if key == ord("q"): break # close the output CSV file do a bit of cleanup print("[ALERT] cleaning up... \n") csv.close() cv2.destroyAllWindows() vs.stop()
def awsCall(barcodeData, idR, c, URL, URLV): #Send AWS z = datetime.strftime("%A") arrival_time = str(time.strftime("%H:%M")) Day = z.lower() qr = str(barcode) # defining a params dict for the parameters to be sent to the API PARAMS = { 'qrCode': barcodeData, 'arrival_time': arrival_time, 'Day': Day, 'residential_id': idR, 'cpu_serial': c } print(PARAMS) # sending get request and saving the response as response object conexion = False try: with eventlet.Timeout(10): r = requests.get(url=URL, params=PARAMS) except: logging.info('Error al verificar el codigo') time.sleep(4) return # extracting data in json format try: message = r.json() print(message) QRstatus = message['result'] logging.info('%s', QRstatus) tipolector = configLec.get('garitappiot', 'tipo') funcionlector = configLec.get('garitappiot', 'funcion') if funcionlector == 'Entrada' and tipolector == 'CONRF': if QRstatus == "Valido": fotofile = message['photo'] if QRstatus == "Invalido": fotofile = "no valido" fotofile = message['photo'] cortesia = "Bienvenido" print(QRstatus, fotofile) if funcionlector == 'Salida' and tipolector == 'CONRF': if QRstatus == "Valido": fotofile = message['photo'] if QRstatus == "Invalido": fotofile = "no valido" cortesia = "Buen viaje" print(QRstatus, fotofile) if funcionlector == 'Entrada' and tipolector == 'NORF': fotofile = "norfacial" cortesia = "Bienvenido" if funcionlector == 'Salida' and tipolector == 'NORF': fotofile = "norfacial" cortesia = "Buen viaje" print(QRstatus, cortesia, fotofile) if QRstatus == "Invalido": led.on() time.sleep(2) led.off() time.sleep(3) if QRstatus == "Valido" and tipolector == 'CONRF': for x in range(3): logging.info('Comenzando reconocimiento facial') os.system( 'sudo wget http://' + IP + ':9000/?action=snapshot -O /home/pi/Documents/QRscan/cara.jpg' ) img = Image.open("/home/pi/Documents/QRscan/cara.jpg") img.save("/home/pi/Documents/QRscan/patron.jpg", dpi=(640, 480)) targetFile = '/home/pi/Documents/QRscan/patron.jpg' sourceFile = fotofile coincidence = 0 client = boto3.client('rekognition') imageTarget = open(targetFile, 'rb') try: response = client.compare_faces( SimilarityThreshold=70, SourceImage={ 'S3Object': { 'Bucket': 'garitapp.guest.id.pictures', 'Name': sourceFile } }, TargetImage={'Bytes': imageTarget.read()}) for faceMatch in response['FaceMatches']: similarity = str(faceMatch['Similarity']) coincidence = float(similarity) print(coincidence) logging.info('Similitud de un %s', similarity) imageTarget.close() if coincidence >= 85: GPIO.setup(pluma, GPIO.OUT) GPIO.output(pluma, GPIO.LOW) time.sleep(1) GPIO.output(pluma, GPIO.HIGH) GPIO.setup(pluma, GPIO.IN) logging.info('Acceso concedido') csv.write("{},{},{},{}\n".format( datetime, barcodeData, "Valido", coincidence)) csv.flush() #validate if it is simple invitation if barcodeData.split("_")[0] == "001": # defining a params dict for the parameters to be sent to the API PARAMS = { 'qrCode': barcodeData, 'arrival_time': arrival_time, 'Day': Day, 'residential_id': idR, 'cpu_serial': c } # sending get request and saving the response as response object while True: try: with eventlet.Timeout(10): r = requests.get(url=URLV, params=PARAMS) break except: pass else: logging.info('Acceso denegado') csv.write("{},{},{}\n".format(datetime, barcodeData, "Invalido")) csv.flush() time.sleep(3) break except: logging.info('Usuario no detectado') csv.write("{},{},{}\n".format(datetime, barcodeData, "Invalido")) csv.flush() time.sleep(5) if QRstatus == "Valido" and tipolector == 'NORF': GPIO.setup(pluma, GPIO.OUT) GPIO.output(pluma, GPIO.LOW) time.sleep(1) GPIO.output(pluma, GPIO.HIGH) GPIO.setup(pluma, GPIO.IN) logging.info('Acceso concedido') csv.write("{},{},{}\n".format(datetime, barcodeData, "Valido")) csv.flush() except: logging.info('Error leyedo datos') time.sleep(5) pass
def scan(): # construct the argument parser and parse the arguments start = time.time() ap = argparse.ArgumentParser() ap.add_argument("-o", "--output", type=str, default="barcodes.csv", help="path to output CSV file containing barcodes") args = vars(ap.parse_args()) # initialize the video stream and allow the camera sensor to warm up # print("[INFO] starting video stream...") vs = VideoStream(src=0, resolution=(1280, 720)).start() # vs = VideoStream(usePiCamera=True,resolution=(960, 720),framerate=30).start() time.sleep(0.5) # open the output CSV file for writing and initialize the set of # barcodes found thus far csv = open(args["output"], "w") found = set() scanning = True # loop over the frames from the video stream while scanning: # grab the frame from the threaded video stream and resize it to # have a maximum width of 400 pixels frame = vs.read() frame = imutils.resize(frame, width=720) # find the barcodes in the frame and decode each of the barcodes barcodes = pyzbar.decode(frame) # loop over the detected barcodes for barcode in barcodes: # extract the bounding box location of the barcode and draw # the bounding box surrounding the barcode on the image (x, y, w, h) = barcode.rect cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) # the barcode data is a bytes object so if we want to draw it # on our output image we need to convert it to a string first barcodeData = barcode.data.decode("utf-8") barcodeType = barcode.type # draw the barcode data and barcode type on the image text = "{} ({})".format(barcodeData, barcodeType) cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) # if the barcode text is currently not in our CSV file, write # the timestamp + barcode to disk and update the set if barcodeData not in found: #csv.write("{},{}\n".format(datetime.datetime.now(), #barcodeData)) csv.write("{}\n".format(barcodeData)) csv.flush() found.add(barcodeData) scanning = False break # show the output frame cv2.imshow("Barcode Scanner", frame) key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop if key == ord("q"): break csv.close() cv2.destroyAllWindows() vs.stop() while True: if scanning != True: name = read_query_output() break flight_id = gate_no(name[0]) infor = gate_infor(flight_id[0]) gate = infor[0] status = infor[1] board = infor[2] departure = infor[3] dest = infor[4] #print ("Gate number is {}".format(gate[0])) #print ("Location on x_coord is {}".format(x[0])) #print ("Location on y_coord is {}".format(y[0])) info_file = open("info_file.txt", "w+") info_file.write(name[0] + '\n') info_file.write(flight_id[0] + '\n') info_file.write(str(gate[0]) + '\n') info_file.write(status[0] + '\n') info_file.write(str(board[0]) + '\n') info_file.write(str(departure[0]) + '\n') info_file.write(dest[0] + '\n') info_file.close() clean_db() link(flight_id[0]) return ({ 'gate_no': gate, 'flight_id': flight_id, 'status': status, 'boarding_time': board, 'depature_time': departure, 'destination': dest })
def file_scan(): from imutils.video import VideoStream from pyzbar import pyzbar import argparse import datetime import imutils import time import cv2 import csv # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-o", "--output", type=str, default="barcodes.csv", help="path to output CSV file containing barcodes") args = vars(ap.parse_args()) # initialize the video stream and allow the camera sensor to warm up print("[BILGI] Video kamera calisiyor...") vs = VideoStream(src=0).start() #vs = VideoStream(usePiCamera=True).start() time.sleep(2.0) # open the output CSV file for writing and initialize the set of # barcodes found thus far csv = open(args["output"], "w") found = set() count = 0 # loop over the frames from the video stream while True: # grab the frame from the threaded video stream and resize it to # have a maximum width of 400 pixels frame = vs.read() #frame = imutils.resize(frame, width=400) #find the barcodes in the frame and decode each of the barcodes barcodes = pyzbar.decode(frame) # loop over the detected barcodes for barcode in barcodes: # extract the bounding box location of the barcode and draw # the bounding box surrounding the barcode on the image (x, y, w, h) = barcode.rect cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) # the barcode data is a bytes object so if we want to draw it # on our output image we need to convert it to a string first barcodeData = barcode.data.decode("utf-8") barcodeType = barcode.type # draw the barcode data and barcode type on the image text = "{} ({})".format(barcodeData, barcodeType) cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) # if the barcode text is currently not in our CSV file, write # the timestamp + barcode to disk and update the set if barcodeData not in found: if 5012345678900 == int(barcodeData): csv.write("{},{}\n".format(barcodeData, "Bin1")) csv.flush() found.add(barcodeData) elif 811204012344 == int(barcodeData): csv.write("{},{}\n".format(barcodeData, "Bin2")) csv.flush() found.add(barcodeData) elif 8691014000012 == int(barcodeData): csv.write("{},{}\n".format(barcodeData, "Bin3")) csv.flush() found.add(barcodeData) elif 3245456345344 == int(barcodeData): print("I found the second") csv.write("{},{}\n".format(barcodeData, "Bin2")) csv.flush() found.add(barcodeData) # show the output frame cv2.imshow("Barcode Scanner", frame) key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop #count = count + 1 if key == ord("q"): break # close the output CSV file do a bit of cleanup print("[BILGI] Islem sonlandi...") cv2.destroyAllWindows() vs.stop() csv.close()