def main(bName, im): files_dir = str(Python.getPlatform().getApplication().getFilesDir()) fileimg1 = join(dirname(files_dir), "input.jpg") fileimg2 = join(dirname(files_dir), "output.jpg") print("**********Reached Python**************") imgb = bytes(im, 'ascii') img_bytes = base64.decodebytes(imgb) with open(fileimg1, 'wb') as ip: ip.write(img_bytes) #reader = easyocr.Reader(['en']) image = cv2.imread(fileimg1) #res = reader.readtext(fileimg1) #for (bbox, text, prob) in res: # unpack the bounding box # (tl, tr, br, bl) = bbox # tl = (int(tl[0]), int(tl[1])) # tr = (int(tr[0]), int(tr[1])) # br = (int(br[0]), int(br[1])) # bl = (int(bl[0]), int(bl[1])) # cv2.rectangle(image, tl, br, (0, 255, 0), 2) # cv2.putText(image, text, (tl[0], tl[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2) #plt.rcParams['figure.figsize'] = (16, 16) cv2.imwrite(fileimg2, image) encoded_string = ' ' with open(fileimg2, "rb") as op: encoded_string = base64.b64encode(op.read()) return "" + str(encoded_string, 'utf-8')
def get_all_feed_events(): path = str(Python.getPlatform().getApplication().getFilesDir()) #public_key = ect.EventCreationTool.get_stored_feed_ids(directory_path=path, as_strings=False, relative=False)[0] db = kotlin.KotlinFunction() query_output = db.get_all_kotlin_events() pretty_output = [] for tuple in query_output: type = tuple[0] if type == "post": timestamp = tuple[2] text = tuple[1] t = (type, get_uname_by_key(db, tuple[3]), timestamp, text) elif type == "username": new = tuple[1] old = tuple[2] timestamp = tuple[3] t = (type, new, old, timestamp) pretty_output.append(t) #print("query output") #print(query_output) #print("printing output") #print(pretty_output) return pretty_output
def __init__(self): DB_PATH = str(Python.getPlatform().getApplication().getFilesDir()) DB_PATH = join(DB_PATH, "KotlinDB.sqlite") self.sqlAlchemyConnector = SqLiteDatabase(SQLITE, dbname=DB_PATH) self.sqlAlchemyConnector.create_chat_event_table() self.sqlAlchemyConnector.create_kotlin_table() self.sqlAlchemyConnector.create_master_table()
def __init__(self, last_event=None, path_to_keys=None, path_to_keys_relative=True, signing_algorithm='ed25519', hashing_algorithm='sha256'): super().__init__() path_to_keys = str(Python.getPlatform().getApplication().getFilesDir()) if path_to_keys is not None: self.set_path_to_keys(path_to_keys, path_to_keys_relative) if last_event is not None: last_event = Event.from_cbor(last_event) self.public_key = last_event.meta.feed_id self.sequence_number = last_event.meta.seq_no if last_event.meta.signature_info in self._SIGN_INFO.values(): self._signing_algorithm = last_event.meta.signature_info else: raise SigningAlgorithmNotFoundException if last_event.meta.hash_of_content[0] in self._HASH_INFO.values(): self._hashing_algorithm = last_event.meta.hash_of_content[0] else: raise HashingAlgorithmNotFoundException self.hash_of_previous_meta = self._calculate_hash( last_event.meta.get_as_cbor()) else: self.public_key = self.generate_feed() self.sequence_number = -1 self.hash_of_previous_meta = None self.set_signing_algorithm(signing_algorithm) self.set_hashing_algorithm(hashing_algorithm)
def android_data_dir(): try: import jnius context = jnius.autoclass('org.kivy.android.PythonActivity').mActivity except ImportError: from com.chaquo.python import Python context = Python.getPlatform().getApplication() return context.getFilesDir().getPath() + '/data'
def change_uname(new_uname): path = str(Python.getPlatform().getApplication().getFilesDir()) db = kotlin.KotlinFunction() eg = ect.EventFactory(last_event=db.get_last_kotlin_event(), path_to_keys= path, path_to_keys_relative= False) timestamp = strftime("%Y-%m-%d %H:%M", gmtime()) uname_event = eg.next_event("KotlinUI/username", {"newUsername": new_uname, "oldUsername": get_uname_by_key(db, get_pk()), "timestamp": timestamp}) db.insert_data(uname_event) set_master_uname(new_uname)
def gui_get_pk(): db = kotlin.KotlinFunction() path = str(Python.getPlatform().getApplication().getFilesDir()) #print("printing both keys in get_pk()") public_key = ect.EventCreationTool.get_stored_feed_ids(directory_path=path, as_strings=False, relative=False) #print(public_key) if str(public_key[0]) == str(db.get_host_master_id()): return public_key[1].hex() return public_key[0].hex()
def predict(test_X, model_file_name='ocsvm.pickle'): ''' :param test_X: (n, 64) float :param model_file_name: :return: (n,) int ''' files_dir = str(Python.getPlatform().getApplication().getFilesDir()) with open(join(files_dir, model_file_name), 'rb') as f: model = pickle.load(f) return model.predict(test_X)
def __init__(self): self.CONFIDENCE_THRESHOLD = 0.2 self.NMS_THRESHOLD = 0.4 self.COLORS = [(0, 255, 255), (255, 255, 0), (0, 255, 0), (255, 0, 0)] self.classes = ['1p', '2p', '5p', '10p', '20p', '50p', '1P', '2P'] self.yoloWeights = self.readWeights() self.yoloCfg = self.readCfg() self.yoloNet = self.readNet() self.yoloModel = self.setModel() self.files_dir = str( Python.getPlatform().getApplication().getFilesDir())
def directory(): # pragma: no cover try: from com.chaquo.python import Python file_dir = str(Python.getPlatform().getApplication().getFilesDir() ) + '/certificates/credentials.txt' return file_dir except ModuleNotFoundError as e: if str(e) != "No module named 'com'": raise else: file_dir = './credentials.txt' return file_dir
def scale_data(raw_data, load_scaler=False, save_scaler=False): ''' :param raw_data: 2D array if before reshape [n,9] if after gen feature [n, 64] :return: scaled data by column or None ''' python_raw_data = java.cast(java.jarray(java.jarray(java.jfloat)), raw_data) files_dir = str(Python.getPlatform().getApplication().getFilesDir()) X = np.array(python_raw_data) if load_scaler: scaler_min_max_array = np.load(join(files_dir,"scaler.npy")) return _scale_data(X, data_min_=scaler_min_max_array[0], data_max_=scaler_min_max_array[1]) else: return _scale_data(X, save_scaler=save_scaler)
def directory(): try: from com.chaquo.python import Python file_dir = str(Python.getPlatform().getApplication().getFilesDir() ) + '/certificates' if not path.exists(file_dir): makedirs(file_dir) return file_dir except ModuleNotFoundError as e: if str(e) != "No module named 'com'": raise else: file_dir = './certificates' if not path.exists(file_dir): makedirs(file_dir)
def _scale_data(X, data_min_=None, data_max_=None, save_scaler=False): scaler = MinMaxScaler() files_dir = str(Python.getPlatform().getApplication().getFilesDir()) if data_min_ is not None: scaler.fit_transform(np.array([data_min_, data_max_])) scaled_data = scaler.transform(X) else: scaled_data = scaler.fit_transform(X) if save_scaler: np.save(join(files_dir,"scaler.npy"), np.vstack((scaler.data_min_, scaler.data_max_))) if np.all(scaled_data >= -0.4) and np.all(scaled_data <= 1.4): return scaled_data else: np.save(join(files_dir,"null.npy"),scaled_data) return None
def train_and_save_model(train_X, nu=0.092, gamma=1.151, model_file_name='ocsvm.pickle'): ''' :param train_X: (n, 64) float :param nu: :param gamma: :param model_file_name: :return: ''' model = OneClassSVM(kernel="rbf", nu=nu, gamma=gamma) model.fit(train_X) files_dir = str(Python.getPlatform().getApplication().getFilesDir()) with open(join(files_dir, model_file_name), 'wb') as f: pickle.dump(model, f) print("save model done!")
def get_my_feed_events(): path = str(Python.getPlatform().getApplication().getFilesDir()) public_key = get_pk() db = kotlin.KotlinFunction() #print("printing master id") #print(db.get_host_master_id().hex()) #print("----------------------------------------------------------------") #print("printing public key") #print(public_key.hex()) #print("----------------------------------------------------------------") query_output = db.get_all_entries_by_feed_id(public_key) pretty_output = [] uname = get_uname_by_key(db, public_key) for tuple in query_output: type = tuple[0] if type == "post": timestamp = tuple[2] text = tuple[1] t = (type, uname, timestamp, text) elif type == "username": new = tuple[1] old = tuple[2] timestamp = tuple[3] t = (type, new, old, timestamp) pretty_output.append(t) #print('printing last kotlin event-------------------') #event = Event.Event.from_cbor(db.get_last_kotlin_event()) #print("printing all kotlin events") #print(db.get_all_kotlin_events()) #print("finished printing kotlin events") #print(event.meta.seq_no) #print('------------------------------------------------------------------------') #print("query output") #print(query_output) #print("printing output") #print(pretty_output) return pretty_output
def get_uname(): path = str(Python.getPlatform().getApplication().getFilesDir()) public_key = ect.EventCreationTool.get_stored_feed_ids(directory_path=path, as_strings=False, relative=False) if not public_key: return "NOT FOUND - PUBLIC KEY ARRAY EMPTY" else: public_key = public_key[0] db = kotlin.KotlinFunction() list = db.get_usernames_and_feed_id() print(len(list)) for tuple in list: #print("comparing {} to {}".format(str(tuple[1]), str(public_key))) #print(str(tuple[1])) if str(tuple[1]) == str(public_key): uname = str(tuple[0]) return uname return "NOT FOUND - USER NOT IN DB"
def main(bName, im): files_dir = str(Python.getPlatform().getApplication().getFilesDir()) fileimg1 = join(dirname(files_dir), "input.jpg") fileimg2 = join(dirname(files_dir), "samp.jpg") fileimg3 = join(dirname(files_dir), "intr.jpg") fileimg4 = join(dirname(files_dir), "output.jpg") print("reached python" + " " + im) #text = bName #pattern = list(text.split(" ")) found = False imgb = bytes(im, 'ascii') img_bytes = base64.decodebytes(imgb) with open(fileimg1, 'wb') as ip: ip.write(img_bytes) Original_Image = Image.open("input.jpg") rotated_image2 = Original_Image.transpose(Image.ROTATE_90) print("Reached near samp") rotated_image2.save("samp.jpg") reader = easyocr.Reader(['en']) image = cv2.imread('samp.jpg') res = reader.readtext('samp.jpg') for (bbox, text, prob) in res: # unpack the bounding box (tl, tr, br, bl) = bbox tl = (int(tl[0]), int(tl[1])) tr = (int(tr[0]), int(tr[1])) br = (int(br[0]), int(br[1])) bl = (int(bl[0]), int(bl[1])) cv2.rectangle(image, tl, br, (0, 255, 0), 2) cv2.putText(image, text, (tl[0], tl[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2) plt.rcParams['figure.figsize'] = (16, 16) cv2.imwrite(fileimg3, image) Original_Image = Image.open("intr.jpg") rotated_image2 = Original_Image.transpose(Image.ROTATE_270) rotated_image2.save("output.jpg") encoded_string = '' with open("output.jpg", "rb") as op: encoded_string = base64.b64encode(op.read()) return "" + str(encoded_string, 'utf-8')
def insert_cbor(type, text): path = str(Python.getPlatform().getApplication().getFilesDir()) db = kotlin.KotlinFunction() db.get_host_master_id() timestamp = strftime("%Y-%m-%d %H:%M", gmtime()) public_keys = ect.EventCreationTool.get_stored_feed_ids(directory_path=path, as_strings=False, relative=False) #if True: if not public_keys: eg = ect.EventFactory(path_to_keys=path, path_to_keys_relative=False) # VERY first event (for feedCTRL) first_event = eg.first_event('KotlinUI', db.get_host_master_id()) db.insert_data(first_event) # first event (INSERTED BY user) where the user get assigned the name Anonymous first_event_byApp = eg.next_event('KotlinUI/username', {"newUsername": "******", "oldUsername": "", "timestamp": timestamp}) set_master_uname("Anonymous") db.insert_data(first_event_byApp) # re-compute public_keys, now it should contain exactly one element public_keys = ect.EventCreationTool.get_stored_feed_ids(directory_path=path, as_strings=False, relative=False) public_key = str(public_keys[0]) list = db.get_usernames_and_feed_id() uname = get_uname_by_key(db, public_key) # this should NEVER EVER be true, EVER if uname == "NOT FOUND": uname = "Anonymous" eg = ect.EventFactory(last_event=db.get_last_kotlin_event(), path_to_keys= path, path_to_keys_relative= False) if type == "username": new_event = eg.next_event("KotlinUI/username", {"newUsername": uname, "oldUsername": "******", "timestamp": timestamp}) set_master_uname(uname) else: new_event = eg.next_event("KotlinUI/post", {"username": uname, "timestamp": timestamp, "text": text}) db.insert_data(new_event)
def start(): feedCTRL.cli('') #print("feed control control") #return path = str(Python.getPlatform().getApplication().getFilesDir()) db = kotlin.KotlinFunction() db.get_host_master_id() timestamp = strftime("%Y-%m-%d %H:%M", gmtime()) public_keys = ect.EventCreationTool.get_stored_feed_ids(directory_path=path, as_strings=False, relative=False) if len(public_keys) <= 1: eg = ect.EventFactory(path_to_keys=path, path_to_keys_relative=False) # VERY first event (for feedCTRL) #first_event = eg.next_event('KotlinUI/MASTER', {'master_feed': eg.get_feed_id()}) first_event = eg.first_event('KotlinUI', db.get_host_master_id()) #first_event = eg.first_event('KotlinUI', eg.get_feed_id()) #first_event = eg.next_event('KotlinUI', eg.get_feed_id()) db.insert_data(first_event) first_event_byApp = eg.next_event('KotlinUI/username', {"newUsername": "******", "oldUsername": "", "timestamp": timestamp}) db.insert_data(first_event_byApp) set_master_uname("Anonymous") #feedCTRL.cli('-t 0 0') #feedCTRL.cli('-t 0 1') #feedCTRL.cli('-t 1 0') #feedCTRL.cli('-t 1 1') #print("printing the len of public keys") #print(len(public_keys)) #print("finished printing len of public keys") #print("This should contain AT LEAST 2 events") #print(db.get_all_kotlin_events()) #print("-----------------------") print('TESTING CLI FUNCTION')
import ECT_FCTRL_DB.eventCreationTool.EventCreationTool as ect import ECT_FCTRL_DB.logStore.appconn.kotlin_connection as kotlin #from eventCreator import EventCreationToolTests import viktor LIST_PUBLIC_KEYS = "list pks" DELETE_PUBLIC_KEYS = "del pks" GET_USERNAME = "******" LS = "ls" options = [LIST_PUBLIC_KEYS, GET_USERNAME, DELETE_PUBLIC_KEYS, LS] FILES_DIR = str(Python.getPlatform().getApplication().getFilesDir()) SECRET_ABSOLUTE_PATH = join(FILES_DIR, "secret") #MY_FEED_ABSOLUTE_PATH = join(FILES_DIR, "my_feed.pcap") #VIKTOR_DB_ABSOLUTE_PATH = join(FILES_DIR, "stData") def list_directories(): for root, dirs, files in os.walk(FILES_DIR): for filename in files: print(filename) def delete_pks(): p = re.compile("[a-zA-Z0-9]+\.key") for root, dirs, files in os.walk(FILES_DIR):
def android_data_dir(): from com.chaquo.python import Python context = Python.getPlatform().getApplication() return context.getFilesDir().getPath() + '/data'
def __init__(self): DB_PATH = str(Python.getPlatform().getApplication().getFilesDir()) DB_PATH = join(DB_PATH, "cborDatabase.sqlite") self.sqlAlchemyConnector = SqLiteDatabase(SQLITE, dbname=DB_PATH) self.sqlAlchemyConnector.create_cbor_db_tables()