class Example(MDApp): def build(self): self.data_tables = MDDataTable( size_hint=(0.9, 0.6), use_pagination=True, check=True, column_data=[ ("No.", dp(30)), ("Column 1", dp(30)), ("Column 2", dp(30)), ("Column 3", dp(30)), ("Column 4", dp(30)), ("Column 5", dp(30)), ], row_data=[ (f'{i+1}', '4.1', '2.3', '82', '2.3', '0.82') for i in range(10) ] ) self.data_tables.bind(on_row_press = self.on_row_press) self.data_tables.bind(on_check_press = self.on_check_press) def on_row_press(self, inst_table, inst_row): print(inst_table, inst_row) def on_check_press(self, inst_table, inst_row): print(inst_table, inst_row) def on_start(self): self.data_tables.open()
def open_table(self, use_checkbox_state, use_pagination_state): cd = Actions.list_table() rd = [] for i in cd: rd.append((str(i[1]), str(i[2]), str(i[7]), str(i[8]))) data_tables = MDDataTable( pos_hint={ 'center_x': 0.5, 'center_y': 0.35 }, # auto_dismiss=False, size_hint=(0.9, 0.5), use_pagination=use_pagination_state, check=use_checkbox_state, rows_num=10, column_data=[ ("Cod", dp(30)), ("Descrição", dp(80)), ("Classificaçao", dp(50)), ("A/S", dp(30)), ], row_data=rd, ) data_tables.open()
class vParkApp(MDApp): def build(self): screen = Builder.load_string(screen_helper) self.data_tables = MDDataTable( size_hint=(0.9, 0.6), # name column, width column column_data=[("Particulars", dp(20)), ("Days Left", dp(20))], row_data=[("1. Insurance", ""), ("2. Pollution", ""), ("3. Service", ""), ("4. Driving Licence", "")]) return screen def open_table(self): self.data_tables.open() # Functions to change screens: def ShowProfile(self): self.root.ids.screen_manager.current = 'profile' def ShowHome(self): self.root.ids.screen_manager.current = 'home' def ShowCamera(self): self.root.ids.screen_manager.current = 'camera' def ShowManualEntryScreen(self): self.root.ids.screen_manager.current = 'MEScreen' def ShowInfo(self): self.root.ids.screen_manager.current = 'InfoScreen' def ShowCreateAccount(self): self.root.ids.screen_manager.current = 'create' def ShowLogin(self): self.root.ids.screen_manager.current = 'login' # def on_start(self): # self.root.ids.screen_manager.current = 'login' # Function for OCR (bare for now, needs optimisations, work on it after successful apk build) def OCR(self): # create a camera variable camera1 = self.root.ids['cam'] # capture a shot and export to png camera1.export_to_png("IMG.png") # open image in PIL(basically storing image in a variable) img = Image.open('IMG.png') # OCR using pytesseract stored in a variable named 'data' data = pytesseract.image_to_string(img) # Create a dialog to show the 'data' on screen and open the dialog self.ShowInfo(data) # Manual entry function: def ManualEntry(self): pass
def open_table(self, use_checkbox_state, use_pagination_state): data_tables = MDDataTable( size_hint=(0.9, 0.9), use_pagination=use_pagination_state, check=use_checkbox_state, rows_num=10, column_data=[ ("Desert (100g serving)", dp(70)), ("Calories", dp(30)), ("Fat (g)", dp(30)), ("Carbs (g)", dp(30)), ("Protein (g)", dp(30)), ("Sodium (mg)", dp(30)), ("Calcium (%)", dp(30)), ("Iron (%)", dp(30)), ], row_data=[ ("Yogurt", "159", "6.0", "24", "4.0", "87", "14%", "1%"), ("Cream", "23", "8.0", "67", "9.0", "187", "24%", "1%"), ("Eclair", "159", "180", "6.1", "4.4", "90", "18%", "0.1%"), ("Cupcake", "204", "7.0", "32", "5.0", "100", "9%", "2%"), ("Gingerbread", "302", "12.1", "89", "8.2", "95", "24%", "2%"), ("Jelly bean", "436", "7.3", "76", "6.7", "365", "0.6%", "3%"), ("Lollipop", "235", "6.0", "21", "0.0", "99", "6%", "1%"), ("KitKat", "445", "9.8", "123", "7.0", "324", "13%", "12%"), ("Honeycomb", "332", "1.8", "23", "1.0", "655", "43%", "2%"), ("Donut", "215", "2.4", "43", "2.0", "24", "1%", "0.3%"), # ------------------------------------------------------------- ("Yogurt", "159", "6.0", "24", "4.0", "87", "14%", "1%"), ("Cream", "23", "8.0", "67", "9.0", "187", "24%", "1%"), ("Eclair", "159", "180", "6.1", "4.4", "90", "18%", "0.1%"), ("Cupcake", "204", "7.0", "32", "5.0", "100", "9%", "2%"), ("Gingerbread", "302", "12.1", "89", "8.2", "95", "24%", "2%"), ("Jelly bean", "436", "7.3", "76", "6.7", "365", "0.6%", "3%"), ("Lollipop", "235", "6.0", "21", "0.0", "99", "6%", "1%"), ("KitKat", "445", "9.8", "123", "7.0", "324", "13%", "12%"), ("Honeycomb", "332", "1.8", "23", "1.0", "655", "43%", "2%"), ("Donut", "215", "2.4", "43", "2.0", "24", "1%", "0.3%"), # ------------------------------------------------------------- ("Yogurt", "159", "6.0", "24", "4.0", "87", "14%", "1%"), ("Cream", "23", "8.0", "67", "9.0", "187", "24%", "1%"), ("Eclair", "159", "180", "6.1", "4.4", "90", "18%", "0.1%"), ("Cupcake", "204", "7.0", "32", "5.0", "100", "9%", "2%"), ("Gingerbread", "302", "12.1", "89", "8.2", "95", "24%", "2%"), ("Jelly bean", "436", "7.3", "76", "6.7", "365", "0.6%", "3%"), ("Lollipop", "235", "6.0", "21", "0.0", "99", "6%", "1%"), ("KitKat", "445", "9.8", "123", "7.0", "324", "13%", "12%"), ("Honeycomb", "332", "1.8", "23", "1.0", "655", "43%", "2%"), ("Donut", "215", "2.4", "43", "2.0", "24", "1%", "0.3%"), ], ) data_tables.open()
def open_table(self, use_checkbox_state=False, use_pagination_state=False): if self.data.get('report_type') == 'total_report': data_tables = MDDataTable( size_hint=(0.9, 0.9), use_pagination=use_pagination_state, check=use_checkbox_state, rows_num=1000, column_data=[ ("Услуга", dp(70)), ("Кол-во", dp(30)), ("Стоимость", dp(30)), ], row_data=self.convert_to_tuple( self.data.get('data').get('report')), ) data_tables.open()
class Fun_Consultas(): data_tables: MDDataTable def __init__(self, **kwargs): super(Fun_Consultas, self).__init__() def md_table(self): try: self.APP_PATH = os.getcwd() self.DB_PATH = self.APP_PATH + "/bd_example.db" con = sqlite3.connect(self.DB_PATH) cursor = con.cursor() query = "select id,patente,Bultos,Tienda,Guia,Odometro from Movimientos " cursor.execute(query) record = cursor.fetchall() except Exception as e: print(e) self.data_tables = MDDataTable( use_pagination=True, size_hint=(0.9, 0.6), check=False, sort=True, # name column, width column column_data=[ ("Id", dp(20)), ("Patente", dp(20)), ("Bultos", dp(20)), ("Tienda", dp(40)), ("Guia", dp(20)), ("Odometro", dp(20)), ], row_data=record) self.data_tables.bind(on_row_press=Fun_Consultas.on_row_press) self.data_tables.bind(on_check_press=Fun_Consultas.on_check_press) self.data_tables.open() def on_row_press(instance_table, instance_row): no = instance_row.text print(no) def on_check_press(instance_table, current_row): print(instance_table, current_row)
class Main(MDApp): def table(self): self.tables = MDDataTable(size_hint=(0.9, 0.6), use_pagination=True, column_data=[ ("No.", dp(30)), ("Column 1", dp(30)), ("Column 2", dp(30)), ("Column 3", dp(30)), ("Column 4", dp(30)), ("Column 5", dp(30)), ], row_data=[(f"{i + 1}", "1", "2", "3", "4", "5") for i in range(50)]) self.tables.open() def build(self): return Builder.load_string(kv)
def view_ttd(): """Create and open datatable dialog popup""" app = MDApp.get_running_app() ## main app object reference data = lib.gen_ref_code.generate_reference_codes() ## create data rows for datatable \/ table_data = [( item['codigo_ref'], f"{item['cls_nome'][:60]}{' [ . . . ]' if len(item['cls_nome']) > 60 else ''}", item['fase_corrente'] if item['fase_corrente'].strip() != '' else '-', item['fase_intermediaria'] if item['fase_corrente'].strip() != '' else '-', item['dest_final']) for item in data] datatable = MDDataTable( size_hint=(0.95, 0.9), column_data=[("Código de Referência", dp(40)), ("Nome da Classe", dp(95)), ("Fase Corrente", dp(30)), ("Fase Intermediária", dp(40)), ("Destinação Final", dp(30))], rows_num=len(table_data) if len(table_data) > 0 else 1, row_data=table_data) datatable.bind(on_dismiss=lambda *x: app.root.switch_to_screen('pcd')) datatable.open()
class Example(MDApp): def build(self): DATA = pd.read_excel("downloaded_medals.xls") DATA = DATA.iloc[:, 1:] cols = DATA.columns.values values = DATA.values self.data_tables = MDDataTable(size_hint=(0.9, 0.6), use_pagination=True, column_data=[(col, dp(30)) for col in cols], row_data=values) self.data_tables.bind(on_row_press=self.on_row_press) self.data_tables.bind(on_check_press=self.on_check_press) self.button = MDRectangleFlatButton(pos_hint={ "center_x": .5, "center_y": .5 }, text="Abrir Tabla", on_release=self.open_table) return self.button def open_table(self, instance): self.data_tables.open() def on_row_press(self, instance_table, instance_row): '''Called when a table row is clicked.''' print(instance_table, instance_row) def on_check_press(self, instance_table, current_row): '''Called when the check box in the table row is checked.''' print(instance_table, current_row)
class Mainscreen(Screen): def __init__(self, **kwargs): super().__init__(**kwargs) def login(self): global user, passwd_ self.ids.bar.start() user_ = self.ids.username pass_ = self.ids.passw user = user_.text passw = pass_.text if user == "": return # print(user,passw) try: # self.ids.bar.stop() self.db = ms.connect( host="logs.c7xtjtjv8ph3.ap-south-1.rds.amazonaws.com", port=3306, user="******", passwd="shubh2003", db="tasker", ) self.db.autocommit = True self.cursor = self.db.cursor() self.cursor.execute( f'select passwd,email,insta,fb from users where name="{user}";' ) a = self.cursor.fetchall() except: self.ids.bar.start() return # db.close() # print(len(a)) for i in a: for k in i: if k == None: k = "" if len(a) == 0: user_.focus = True user_.error = True user_.text = "" # print(type(a)) elif passw != a[0][0]: user_.error = False pass_.focus = True pass_.error = True pass_.text = "" else: user_.error = False pass_.error = False self.ids.passwd_.text = a[0][0] self.ids.email.text = a[0][1] self.ids.insta.text = a[0][2] self.ids.fb.text = a[0][3] self.ids.fb.text = a[0][3] self.ids.bar.stop() self.ids.screen_manager.current = "scr 2" self.table() def show_time_picker(self): global user if user == "": pass time_dialog = MDTimePicker() time_dialog.bind(time=self.get_time) time_dialog.open() def get_time(self, instance, time): global time_ """ The method returns the set time. :type instance: <kivymd.uix.picker.MDTimePicker object> :type time: <class 'datetime.time'> """ sel_time = time time_ = str(time) # date = datetime.datetime.strptime('2018-01-01', '%Y-%m-%d').date() curr_time = datetime.strptime(str(datetime.now().strftime("%H:%M:00")), "%H:%M:00").time() # print(sel_time,curr_time) if sel_time > curr_time: strd = str(dt.datetime.now().strftime("%Y:%m:%d")) self.show_date_picker(datetime.strptime(strd, "%Y:%m:%d").date()) else: strd = str((dt.datetime.now() + dt.timedelta(days=1)).strftime("%Y:%m:%d")) # print(strd) self.show_date_picker(datetime.strptime(strd, "%Y:%m:%d").date()) # return time def show_date_picker(self, min): min_date = min max_date = datetime.strptime("2050:12:12", "%Y:%m:%d").date() dats = str(min).split("-") # print(str(min)) date_dialog = MDDatePicker( callback=self.get_date, min_date=min_date, max_date=max_date, year=int(dats[0]), month=int(dats[1]), day=int(dats[2]), ) date_dialog.open() return def get_date(self, date): global date_ """ :type date: <class 'datetime.date'> """ date_ = str(date) return def insert_task(self): global time_, date_, task, user if time_ == "" or date_ == "" or task == "" or user == "": print("eff") else: try: self.ids.bar2.stop() self.db.ping(reconnect=True, attempts=1) self.cursor.execute( f"insert into task values('{user}','{task}','{date_}','{time_}')" ) time_ = date_ = task = "" self.table() return except: self.ids.bar2.start() return def callback(self, instance): if instance.icon == "clock-check-outline": self.show_time_picker() return elif instance.icon == "note-outline": self.ids.screen_manager.current = "data entry" return elif instance.icon == "timetable": # print('hehehehe') self.show_table() return elif instance.icon == "send-outline": self.insert_task() return def grabtask(self): global task task_ = self.ids.task task = str(task_.text) # print(task) self.ids.screen_manager.current = "scr 2" return def table(self): # rw=() row_ = [] global user try: self.ids.bar2.stop() self.db.ping(reconnect=True, attempts=1) self.cursor.execute( f"select task.date,task.time,task.task from task where name='{user}';" ) r = self.cursor.fetchall() except: self.ids.bar2.start() return # db.close() if len(r) == 0: return for i in r: rw = () for k in i: rw += (str(k), ) row_.append(rw) # return row_ = row_[::-1] self.data_table = MDDataTable( size_hint=(0.9, 0.6), column_data=[ ("Date", dp(20)), ("Time", dp(20)), ("Task", dp(30)), ], row_data=row_, use_pagination=True, pagination_menu_pos="center", sort=True, ) # print(row_) return def show_table(self): try: self.data_table.open() return except: return def change_data(self): global user if user == "": return ema = self.ids.email f = self.ids.fb pas = self.ids.passwd_ ins = self.ids.insta email = ema.text paswd_ = pas.text fb = f.text insta = ins.text try: self.ids.bar2.stop() self.db.ping(reconnect=True, attempts=1) self.cursor.execute( f'update users set email="{email}",insta="{insta}",fb="{fb}",passwd="{paswd_}" where name="{user}";' ) return except: self.ids.bar2.start() # db.close() return
class sonarApp(MDApp): #Since we named class 'sonarApp', kivy auto-builds 'sonar.kv'. def build(self): self.theme_cls.primary_palette = 'DeepPurple' #Runs when user starts app. def on_start(self): self.conn = sqlite3.connect('database.db') #Ensure that results from sqlite queries are returned as dictionaries. self.conn.row_factory = database.dictFactory self.cursor = self.conn.cursor() #Make all relevant tables if they do not yet exist. database.dbSetup(self.conn, self.cursor) #Get hosts on network from a single ARP broadcast. hostsOnNetwork = networking.surveyNetwork('255.255.255.0', 1) currentNetworkId = database.getNetworkId(hostsOnNetwork, self.conn, self.cursor) self.cursor.execute('SELECT * FROM networks WHERE id = ?', [currentNetworkId]) currentNetwork = { currentNetworkId : self.cursor.fetchone() } self.cursor.execute('SELECT * FROM networks WHERE id != ?', [currentNetworkId]) restOfNetworks = { network['id'] : network for network in self.cursor.fetchall() } #Ensure that currentNetwork is first in 'networks', and thus on GUI. networks = { **currentNetwork, **restOfNetworks } #Create list of networks, which give a table of hosts when clicked. for network in networks.values(): columnWidth = (self.root.width * 0.69) / 5 / 5 networkListItem = OneLineListItem( text = network['ssid'], on_press = ( lambda _, network = network, columnWidth = columnWidth: self.networkTable(network, columnWidth) ) ) self.root.ids['networksList'].add_widget(networkListItem) self.hosts = database.catalogNetwork( self.conn, self.cursor, hostsOnNetwork) hostIdsOnNetwork = networking.getHostsOnNetwork( hostsOnNetwork, self.hosts) for hostId in self.hosts: onNetwork = (hostId in hostIdsOnNetwork) self.hosts[hostId]['onNetwork'] = onNetwork notifsQ = multiprocessing.Queue() hostsQ = multiprocessing.Queue() self.notifsProducerP = multiprocessing.Process( target = notifsProducer, args = (hostsOnNetwork, self.hosts, notifsQ, hostsQ,) ) self.notifsProducerP.start() #Play ringtone for each notif-enabled host that entered network. #Update self.hosts data. def notifsConsumer(_): if not notifsQ.empty(): for hostId in notifsQ.get_nowait(): MDDialog( title = '%s has entered the network' % self.hosts[hostId]['macAddr'] ).open() self.playRingtone(self.hosts[hostId]['tone']) #update host values. if not hostsQ.empty(): currentHosts = hostsQ.get_nowait() for hostId, host in currentHosts.items(): self.hosts[hostId] = host #Check / react to contents of notifsQ every 5 seconds. self.notifChecker = Clock.schedule_interval(notifsConsumer, 5) #Plays ringtone no. given from file in 'ringtones'. #Needs to be method of app class so it can be called from '.kv' file. def playRingtone(self, ringtoneNo): if ringtoneNo not in range(1,10): return else: #kivy's audio module has issues on debian systems (inc. mine), so we use pygame. pygame.mixer.init() filepath = os.path.abspath(__file__) filedir = os.path.dirname(filepath) musicpath = os.path.join(filedir, "ringtones/%d.wav" % ringtoneNo) pygame.mixer.music.load(os.path.abspath(musicpath)) pygame.mixer.music.play() #When user clicks a network row, display table showing its hosts. def networkTable(self, network, columnWidth): keysToShow = ['macAddr', 'ipAddr', 'manufacturer', 'notificationEnabled', 'onNetwork'] hostsRowData = [ list({ key:value for (key, value) in host.items() if key in keysToShow }.values()) for host in self.hosts.values() ] self.hostsTable = MDDataTable( column_data = [ ('MAC Address', columnWidth), ('IP Address', columnWidth), ('Manufacturer', columnWidth), ('Notifications Enabled', columnWidth), ('On Network', columnWidth) ], row_data = hostsRowData, size_hint = (0.7, 0.7) ) self.hostsTable.bind(on_row_press = self.onHostPress) self.hostsTable.open() #If user clicks row corresponding for host in self.hostsTable, display dialog. #Dialog allows user to enable notifications / set notif tone for relevant host. def onHostPress(self, instanceTable, instanceRow): rowIndex = floor(instanceRow.index / 5) hostData = instanceTable.row_data[rowIndex] content = notificationSettings(enabled = hostData[3]) hostId = list(self.hosts.values())[rowIndex]['id'] self.hostDialog = MDDialog( title = 'Notifications for %s' % hostData[0], content_cls = content, type = 'custom', buttons = [ ToggleButtonClass( text = 'Cancel', group = 'submit', on_release = (lambda _: self.hostDialog.dismiss(force = 1)) ), ToggleButtonClass( text = 'OK', group = 'submit', on_release = (lambda _: self.hostDialogSubmit(hostId, rowIndex)) ) ] ) #Nth value of checkbox bools indicate if checkbox n is selected. checkboxBools = [0] * 9 if hostData[3]: checkboxBools[int(self.hosts[hostId]['tone']) - 1] = 1 musicItems = [ itemConfirmMusic( text = ('Ringtone %d' % num), active = (checkboxBools[num - 1]), index = num ) for num in range(1,10) ] for item in musicItems: self.hostDialog.content_cls.ids['notifList'].add_widget(item) self.hostDialog.open() #When user submits host dialog, input info into db and update self.hosts. def hostDialogSubmit(self, hostId, hostIndex): #Get binary value of switch. notificationsEnabled = int( self.hostDialog.content_cls.ids['notificationsEnabled'].active) self.hosts[hostId]['notificationEnabled'] = notificationsEnabled if notificationsEnabled: selectedItem = None widgetList = list(enumerate( self.hostDialog.content_cls.ids['notifList'].children )) for index, widget in reversed(widgetList): if widget.ids['check'].active: selectedIndex = widget.index #update db; self.cursor.execute( 'UPDATE hosts SET notificationEnabled = 1, tone = ? WHERE id = ?', [selectedIndex, hostId]) self.conn.commit() self.hosts[hostId]['tone'] = selectedIndex #Close host's table and host dialog. #MDDataTable can't be updated, so we need to close. self.hostDialog.dismiss(force = 1) self.hostsTable.dismiss(force = 1) return #Tell user to select a tone value, since none were selected. Snackbar( text = "Please select an option", padding = "20dp" ).open() else: self.hostsTable.table_data.row_data[hostIndex][3] = '1' self.cursor.execute('UPDATE hosts SET notificationEnabled = 0 WHERE id = ?', [hostId]) self.conn.commit() self.hostDialog.dismiss(force = 1) #Callback to make "tone" checkboxes visible when user enables notifs. def selectNotifType(self): self.hostDialog.content_cls.ids['options'].opacity = 1 self.hostDialog.update_height()
class InfoScreen(Screen): def __init__(self, **kw): super().__init__(**kw) self.info = None """ 0 = id 1 = name 2 = address 3 = phone number 4 = website 5 to 11 = Monday - Sunday 12 = latitude 13 = longitude 14 = information 15 = distance in miles 16 = zip code latitude 17 = zip code longitude """ self.url = None self.phone_number = None self.map = None self.marker = None self.midpoint = None self.ideal_zoom = None self.phone_dialog = MDDialog( title="Phone Number", text="", buttons=[ MDFlatButton( text="Close", text_color=MDApp.get_running_app().theme_cls.primary_color, on_release=self.close_phone_number_dialog, ), MDFlatButton( text="Copy", text_color=MDApp.get_running_app().theme_cls.primary_color, on_release=self.copy_phone_number, ), ], ) self.schedule_data = None def on_enter(self, *args): self.info = MDApp.get_running_app().row self.ids.center_panel.ids.title_box.ids.title.text = self.info[1] self.ids.center_panel.ids.list_box.ids.address.text = self.info[2] print( self.ids.center_panel.ids.buttons_box.ids.call_container.ids.call_button.size ) day = datetime.datetime.today().weekday() day_name = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", ] for index in range(5, 12): if self.info[index] is None: self.info[index] = "Closed" self.ids.center_panel.ids.list_box.ids.hours.text = f"""{day_name[day]}: [color={get_hex_from_color( MDApp.get_running_app().theme_cls.primary_color)}]{self.info[day + 5]}[/color]""" if self.info[14] is not None: self.ids.center_panel.ids.information.text = self.info[14] self.ids.center_panel.ids.title_box.ids.distance.text = ( str(self.info[15]) + " Miles Away" ) # Modify the schedule data table # TODO: Make the data table take up the width of the screen self.schedule_data = MDDataTable( size_hint=(0.9, 0.8), column_data=[("Day", dp(20)), ("Hours", dp(35))], row_data=[ ("Monday", self.info[5]), ("Tuesday", self.info[6]), ("Wednesday", self.info[7]), ("Thursday", self.info[8]), ("Friday", self.info[9]), ("Saturday", self.info[10]), ("Sunday", self.info[11]), ], ) self.schedule_data.table_data.rows_num = 7 self.schedule_data.table_data.set_row_data() self.map = self.ids.map # calculates and sets the view to the midpoint of the foodbank and the person, calculates an ideal zoom value self.midpoint = midpoint( self.info[12], self.info[13], self.info[16], self.info[17] ) self.map.center_on(self.midpoint[0], self.midpoint[1]) self.map.zoom = 17 box = self.map.get_bbox() while not ( box[0] < (self.info[12] and self.info[16]) < box[2] and box[1] < (self.info[13] and self.info[17]) < box[3] ): self.map.zoom -= 1 box = self.map.get_bbox() self.ideal_zoom = self.map.zoom - 1 self.map.zoom = self.ideal_zoom # Adds the foodbank to the map self.marker = Marker( float(self.info[12]), float(self.info[13]), self.map, self.ideal_zoom ) self.map.add_widget(self.marker) # Disables the website button if there is no website self.url = self.info[4] if self.url is None: self.ids.center_panel.ids.buttons_box.ids.website_container.ids.website_button.disabled = ( True ) self.ids.center_panel.ids.buttons_box.ids.website_container.ids.website_button_text.text_color = ( MDApp.get_running_app().theme_cls.disabled_hint_text_color ) else: self.ids.center_panel.ids.buttons_box.ids.website_container.ids.website_button.disabled = ( False ) self.ids.center_panel.ids.buttons_box.ids.website_container.ids.website_button_text.text_color = ( MDApp.get_running_app().theme_cls.primary_color ) # Disables the call button if there is no phone number self.phone_number = self.info[3] if self.phone_number is None: self.ids.center_panel.ids.buttons_box.ids.call_container.ids.call_button.disabled = ( True ) self.ids.center_panel.ids.buttons_box.ids.call_container.ids.call_button_text.text_color = ( MDApp.get_running_app().theme_cls.disabled_hint_text_color ) else: # Modify the phone dialog self.phone_dialog.text = self.info[3] self.phone_dialog.size_hint_x = 0.8 self.phone_dialog.size[1] += 100 self.ids.center_panel.ids.buttons_box.ids.call_container.ids.call_button.disabled = ( False ) self.ids.center_panel.ids.buttons_box.ids.call_container.ids.call_button_text.text_color = ( MDApp.get_running_app().theme_cls.primary_color ) # Set the map size Clock.schedule_once(lambda _: self.resize_map()) def resize_map(self): self.ids.map.size = 100, Window.size[1] - self.ids.center_panel.height + 40 print(f"{self.ids.map.size} is the new size of the map") def open_url(self): print("opened url") webbrowser.open(self.url) def call_number(self): PythonActivity = autoclass("org.kivy.android.PythonActivity") Intent = autoclass("android.content.Intent") Uri = autoclass("android.net.Uri") number = Uri.parse(f"tel:{self.info[3].replace('-', '')}") intent = Intent(Intent.ACTION_DIAL, number) currentActivity = cast("android.app.Activity", PythonActivity.mActivity) currentActivity.startActivity(intent) def open_google_maps(self): PythonActivity = autoclass("org.kivy.android.PythonActivity") Intent = autoclass("android.content.Intent") Uri = autoclass("android.net.Uri") location = Uri.parse(f'geo:0,0?q={self.info[2].replace(" ", "+")}') intent = Intent(Intent.ACTION_VIEW, location) currentActivity = cast("android.app.Activity", PythonActivity.mActivity) currentActivity.startActivity(intent) def open_schedule_data(self): self.schedule_data.open() def center_on_midpoint(self): self.map.center_on(self.midpoint[0], self.midpoint[1]) self.map.zoom = self.ideal_zoom def copy_phone_number(self, _): Clipboard.copy(self.info[3]) Snackbar(text="Copied to Clipboard!").show() def close_phone_number_dialog(self, _): self.phone_dialog.dismiss() def close_schedule_data(self, _): self.schedule_data.dismiss() def go_back(self): self.map.remove_widget(self.marker) self.manager.current = "results_screen"
class mainApp(MDApp): def build(self): self.theme_cls.theme_style = 'Light' self.data_tables = MDDataTable( size_hint=(0.8, 0.5), column_data=[ ("Work", dp(45)), ("Cost", dp(45)), ("Time", dp(45)), ], row_data=[ # The number of elements must match the length # of the `column_data` list. ("Assignment", "3Rs/Page(2 sides) + Material", "24 hours"), ("Project", "cost of Project + Our Charge", "Depends on Project"), ("Practical", "3Rs/Page(2 sides) + Material ", "24 hours"), ("Fast Service", "5Rs/Page(2 sides) + Material ", "less than 24 hours"), ]) return Builder.load_string(kv) def reward(self): self.data_tables.open() def show(self): self.dialog = MDDialog( title='How to Connect?', text= "Connect With Us Following These Steps \n1) Fill Notes form! \n2) Take ScreenShot \n3) Click On Top-left-corner Icon. \n4)Send ScreenShot On Any Given Platform. ", size_hint=(0.7, 0.5), buttons=[ MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color, on_press=self.dismiss), MDFlatButton(text="Done", text_color=self.theme_cls.primary_color, on_press=self.dismiss), ], ) self.dialog.open() def Contact(self): self.dialog = MDDialog( title='How to Connect?', text= "Connect With Us Following These Steps \n1) Fill Notes form! \n2) Take ScreenShot \n3) Click On Top-left-corner Icon. \n4)Send ScreenShot On Any Given Platform. ", size_hint=(0.8, 0.6), buttons=[ MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color, on_press=self.dismiss), MDFlatButton(text="Done", text_color=self.theme_cls.primary_color, on_press=self.dismiss), ], ) self.dialog.open() def dismiss(self, obj): self.dialog.dismiss() def facebook(self): self.web = webbrowser.open( "https://www.facebook.com/Home-Work-106918057844725/") def instagram(self): self.ins = webbrowser.open( "https://www.instagram.com/homework_assign/?igshid=levzzeoh0rrt&fbclid=IwAR3huKGtL99qynenJJiv9iF6CbKHfCDnSZdCarBJHlZykfNjESgVbUTkCgo" )
class ReporteGastos(Screen): def __init__(self, **kwargs): super().__init__() self.app = MDApp.get_running_app() self.buttonPDF = MDFillRoundFlatButton( # BOTON PARA GENERAR PDF pos_hint={ "x": .05, "y": .1 }, size_hint=(.40, .1), text="Crear PDF", on_release=lambda x: self.opcionPDF()) self.buttonEXP = MDFillRoundFlatButton( # BOTON PARA EXPORTAR PDF pos_hint={ "x": .55, "y": .1 }, size_hint=(.40, .1), text="Exportar PDF a Drive", on_release=lambda x: self.exportarPDF()) self.buttontabla = MDFillRoundFlatButton( #Boton para mostrar tabla pos_hint={ "x": .3, "y": .3 }, size_hint=(.40, .1), text="Consultar Productos", on_release=lambda x: self.tablaproductos()) self.buttonconsulta = MDFillRoundFlatButton( # Boton para mostrar tabla pos_hint={ "x": .5, "y": .3 }, size_hint=(.40, .1), text="Consulta de prueba", on_release=lambda x: self.prueba()) #self.add_widget(self.buttonconsulta) #self.add_widget(self.data_tables)##### self.add_widget(self.buttonPDF) self.add_widget(self.buttonEXP) self.add_widget(self.buttontabla) #self.add_widget(self.buttonconsulta) # self.buttonactualizar.bind(on_press=lambda x: self.ActualizaPrecio()) def prueba(self): print("Estoy en prueba") APP_PATH = os.getcwd() DB_PATH = APP_PATH + '/prueba.db' # SE DEBE CAMBIAR EL NOMBRE AL NOMBRE DE LA BD FINAL con = sqlite3.connect(DB_PATH) # CONEXION A LA BD cursor = con.cursor() # CURSOR PARA EJECUTAR QUERYS cantidades = [] cantidadfinal = [] nomproductos = [] nomproductofinal = [] cursor.execute("""SELECT CANTIDAD FROM PRODUCTOS """) for a in cursor: cantidades.append(list(a)) for cantidad in cantidades: for elemento in cantidad: cantidadfinal.append(int(elemento)) cursor.execute("""SELECT NOMBRE FROM PRODUCTOS """) for a in cursor: nomproductos.append(list(a)) for nomprod in nomproductos: for elemento in nomprod: nomproductofinal.append(elemento) #print((cantidadfinal[1])>5) #print(nomproductofinal[1]) print(nomproductofinal) a = 0 cadena_escaso = 'Se te esta acabando: ' for c in cantidadfinal: #print(c > 4) if c < 2: print( f"Producto: {nomproductofinal[a]} con {cantidadfinal[a]}") cadena_escaso += str(nomproductofinal[a]) + ' tienes:' + str( cantidadfinal[a]) + ' ' continue a += 1 print(cadena_escaso) def tablaproductos(self): self.data_tables = MDDataTable( # TABLA QUE MUESTRA LOS PRODUCTOS Y SUS COSTOS pos_hint={ "x": .05, "y": .25 }, size_hint=(0.9, 0.6), use_pagination=True, column_data=[("Producto", dp(30)), ("Costo unitario", dp(30)), ("N° de unidades", dp(30)), ("Costo Total", dp(30))], row_data=self.obtiene_datos(), ) self.data_tables.open() def opcionPDF(self): self.dialog = MDDialog( title="Periodo de su reporte", # CUADROD DE DIALOGO PARA OBTENER EL PERIODO DEL REPORTE DE GASTOS text="¿De cuantas semanas desea el reporte?", size_hint=[.9, .9], auto_dismiss=True, buttons=[ MDFlatButton(text="UNO", on_release=lambda x: self.generaPDF('UNO')), MDFlatButton(text="DOS", on_release=lambda x: self.generaPDF('DOS')), MDFlatButton(text="TRES", on_release=lambda x: self.generaPDF('TRES')), MDFlatButton(text="CUATRO", on_release=lambda x: self.generaPDF('CUATRO')), MDFlatButton(text="Listo", on_release=self.dialog_close) ]) self.dialog.open() def dialog_close(self, *args): # Cierra el dialog del boton ayuda # print("Cerrando Dialog") self.dialog.dismiss() def my_callback( self, texto, popup_widget ): # funcion que ayuda a cerrar el dialog del boton actualizar print(texto) print(popup_widget) def generaPDF(self, valor): if valor == 'UNO': semanas = 1 elif valor == 'DOS': semanas = 2 elif valor == 'TRES': semanas = 3 elif valor == 'CUATRO': semanas = 4 print(semanas) APP_PATH = os.getcwd() DB_PATH = APP_PATH + '/prueba.db' # SE DEBE CAMBIAR EL NOMBRE AL NOMBRE DE LA BD FINAL con = sqlite3.connect(DB_PATH) # CONEXION A LA BD cursor = con.cursor() # CURSOR PARA EJECUTAR QUERYS dias = semanas * 7 base = datetime.datetime.today() date_list = [base - datetime.timedelta(days=x) for x in range(dias)] print(date_list[dias - 1].date()) fin = str(base.date()) inicio = str(date_list[dias - 1].date()) periodo = "El periodo es: de " + inicio + " a " + fin print(periodo) fechas = [inicio, fin] cursor.execute( """SELECT NOMBRE,PRECIO,CANTIDAD FROM PRODUCTOS WHERE FECHA BETWEEN ? AND ? """, fechas) columnas = [['Producto', 'Precio Unitario', 'Unidades', 'Costo Final']] # datos que pasan al PDF costoTotal = 0 for i in cursor: i = list(i) costoF = i[1] * i[2] costoTotal += costoF i.append(costoF) columnas.append(i) for i in columnas: print("valor", i) textCF = 'El costo total fue de: $' + str(costoTotal) print(textCF) fileName = 'ReporteGastos.pdf' pdf = SimpleDocTemplate(fileName, pagesize=letter) tabla = Table(columnas) estilo = TableStyle([('BACKGROUND', (0, 0), (3, 0), colors.green), ('BACKGROUND', (0, 1), (-1, -1), colors.beige), ('TEXTCOLOR', (0, 0), (-1, 0), colors.white), ('TEXTCOLOR', (0, 1), (-1, -1), colors.green), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('FONTNAME', (0, 0), (-1, -1), 'Courier'), ('FONTSIZE', (0, 0), (-1, -1), 16)]) tabla.setStyle(estilo) elems = [] titulo = 'REPORTE DE GASTOS' estiloParrafoP = ParagraphStyle('yourtitle', fontName="Courier-Bold", fontSize=18, alignment=0, spaceAfter=18, textColor=colors.green) estiloParrafo = ParagraphStyle('yourtitle', fontName="Courier", fontSize=16, alignment=0, spaceBefore=18, spaceAfter=18, textColor=colors.green) elems.append(Paragraph(titulo, estiloParrafoP)) elems.append(Paragraph(periodo, estiloParrafo)) # elems.append(periodo) elems.append(tabla) elems.append(Paragraph(textCF, estiloParrafo)) pdf.build(elems) def obtiene_datos(self): # Acceder a la BD APP_PATH = os.getcwd() DB_PATH = APP_PATH + '/prueba.db' # CAMBIAR EL NOMBRE A LA BD FINAL con = sqlite3.connect(DB_PATH) # CONEXION A LA BD cursor = con.cursor() # CURSOR PARA EJECUTAR QUERYS cursor.execute("""SELECT NOMBRE,PRECIO,CANTIDAD FROM PRODUCTOS""") datos = [] costoTotal = 0 for i in cursor: i = list(i) costoF = i[1] * i[2] costoTotal += costoF i.append(costoF) datos.append(i) con.close() return datos def exportarPDF(self): # SE DEBE BUSCAR LA FORMA DE HACERLO GENÉRICO """ import json import requests headers = { "Authorization": "Bearer ya29.a0AfH6SMDhLxJscYf1Cm4vYtjbKSPdHHIeNH3kuelzz6BgQtDk-sobO5Dzw7FwYrGf17vaKIR_qoKChEYXzc9In5lJVoTTAY5yfXdZdFxZdQ6jkZ2lcr2B6N36s5kihOV5xKjZUR5Kdsk39beA0vx7yTisCP3ulOf8fquyUugdXt0"} para = { "name": "ReporteGastos.pdf", } files = { 'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'), 'file': open("./ReporteGastos.pdf", "rb") } r = requests.post( "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", headers=headers, files=files ) print(r.text) """ gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile("mycreds.txt") if gauth.credentials is None: # Authenticate if they're not there gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("mycreds.txt") drive = GoogleDrive(gauth) folderName = "App Inventario" # folder = drive.CreateFile({'title' : folderName, 'mimeType' : 'application/vnd.google-apps.folder'}) # folder.Upload() fileList = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() contador = 0 if len(fileList) == 0: # No hay archivos print("No hay ningun archivo, creando el folder") folder = drive.CreateFile({ 'title': folderName, 'mimeType': 'application/vnd.google-apps.folder' }) folder.Upload() contador = -1 for file in fileList: # haciendo un for para comprobar los archivos # print('Title: %s, ID: %s' % (file['title'], file['id'])) # Get the folder ID that you want if file['title'] == folderName: print("Existe el folder necesario") contador = -1 break elif file['title'] != folderName: print("Archivo sin coincidencia") print('Title: %s, ID: %s' % (file['title'], file['id'])) contador = contador + 1 if contador == len( fileList ): # si son iguales significa que no existe carpeta de la App print("Se debe crear el archivo") folder = drive.CreateFile({ 'title': folderName, 'mimeType': 'application/vnd.google-apps.folder' }) folder.Upload() #-------Parte de actualizar arc folderName = "App Inventario" folder_id = '' # creacion archivo en un folder específico # folders = drive.ListFile( # {'q': "title='" + folderName + "' and mimeType='application/vnd.google-apps.folder' and trashed=false"}).GetList() file_list = drive.ListFile({ 'q': "'root' in parents and trashed=false" }).GetList() for file in file_list: if (file['title'] == folderName): folder_id = file['id'] break # 3) Build string dynamically (need to use escape characters to support single quote syntax) str = "\'" + folder_id + "\'" + " in parents and trashed=false" # 4) Starting iterating over files file_list = drive.ListFile({'q': str}).GetList() for file in file_list: print('title: %s, id: %s' % (file['title'], file['id'])) if file['title'] == "ReporteGastos.pdf": file.Delete() file2 = drive.CreateFile({'parents': [{'id': folder_id}]}) file2.SetContentFile('ReporteGastos.pdf') file2.Upload() # Informar que se ha subido el archivo snackbar = Snackbar( text="Se ha realizado el respaldo del Reporte en Google Drive") snackbar.show() def on_pre_enter(self, *args): """La función se ejecuta antes de ingresar a la clase Reporte de Gastos, la función actualiza el nombre del modulo correspondiente""" self.app.title = "Reporte de Gastos" #Muestra notificación de escaso print("Estoy en pre enter") APP_PATH = os.getcwd() DB_PATH = APP_PATH + '/prueba.db' # SE DEBE CAMBIAR EL NOMBRE AL NOMBRE DE LA BD FINAL con = sqlite3.connect(DB_PATH) # CONEXION A LA BD cursor = con.cursor() # CURSOR PARA EJECUTAR QUERYS cantidades = [] cantidadfinal = [] nomproductos = [] nomproductofinal = [] cursor.execute("""SELECT CANTIDAD FROM PRODUCTOS """) for a in cursor: cantidades.append(list(a)) for cantidad in cantidades: for elemento in cantidad: cantidadfinal.append(int(elemento)) cursor.execute("""SELECT NOMBRE FROM PRODUCTOS """) for a in cursor: nomproductos.append(list(a)) for nomprod in nomproductos: for elemento in nomprod: nomproductofinal.append(elemento) # print((cantidadfinal[1])>5) # print(nomproductofinal[1]) print(nomproductofinal) a = 0 cadena_escaso = 'Se te esta acabando: ' for c in cantidadfinal: # print(c > 4) if c < 2: print( f"Producto: {nomproductofinal[a]} con {cantidadfinal[a]}") cadena_escaso += str(nomproductofinal[a]) + ' tienes:' + str( cantidadfinal[a]) + ' ' continue a += 1 snackbar = Snackbar(text=cadena_escaso) snackbar.show()
class FirstScreen(Screen): #Pantalla comparador de precios """Clase principal donde se ejecuta el modulo comparador de precios, en ella se inicializan las variables correspondientes que se utilizaran en el módulo""" def __init__(self, **kwargs): super().__init__(**kwargs) self.app = MDApp.get_running_app() self.valorbarra = 0 self.buttonactualizar = MDRectangleFlatIconButton( pos_hint={ "center_x": .5, "top": .95 }, #size_hint = (.3,.1), icon="cart-arrow-down", text=" Precios", ) self.msgactualiza = MDLabel(text='Actualizando, espera por favor', pos_hint={ "center_x": .5, "top": .87 }, size_hint=(.8, .1), theme_text_color="Primary", font_style="Subtitle1", halign="center") self.barra = MDProgressBar(id="barrasss", value=0, pos_hint={ "center_x": .5, "center_y": .80 }, size_hint=(.9, .1)) self.etiqueta1 = MDLabel(text='Consultar por Tienda', pos_hint={ "center_x": .5, "top": .80 }, size_hint=(.5, .1), theme_text_color="Primary", font_style="Subtitle1", halign="center") self.buttonche = MDFillRoundFlatButton( pos_hint={ "x": .05, "y": .6 }, size_hint=(.40, .1), text="Chedraui", on_release=lambda x: self.verboton('che')) self.buttonsor = MDFillRoundFlatButton( pos_hint={ "x": .55, "y": .6 }, size_hint=(.40, .1), text="Soriana", on_release=lambda x: self.verboton('sor')) self.buttonhbe = MDFillRoundFlatButton( pos_hint={ "x": .05, "y": .45 }, size_hint=(.40, .1), #theme_text_color = "Primary", text="HBE", on_release=lambda x: self.verboton('hbe')) self.buttoncomer = MDFillRoundFlatButton( pos_hint={ "x": .55, "y": .45 }, size_hint=(.40, .1), text="La Comer", on_release=lambda x: self.verboton('comer')) self.etiqueta2 = MDLabel(text='Consultar por Categoría', pos_hint={ "center_x": .5, "top": .40 }, size_hint=(.5, .1), theme_text_color="Primary", font_style="Subtitle1", halign="center") self.buttonfrutas = MDFillRoundFlatButton( pos_hint={ "x": .05, "y": .20 }, size_hint=(.25, .1), text="Frutas", on_release=lambda x: self.verboton('frutas')) self.buttonverduras = MDFillRoundFlatButton( pos_hint={ "x": .35, "y": .20 }, size_hint=(.25, .1), text="Verduras", on_release=lambda x: self.verboton('verduras')) self.buttoncarnes = MDFillRoundFlatButton( pos_hint={ "x": .65, "y": .20 }, size_hint=(.25, .1), text='Carnes', on_release=lambda x: self.verboton('carnes')) self.buttonlacteos = MDFillRoundFlatButton( pos_hint={ "x": .20, "y": .05 }, size_hint=(.25, .1), text='Lácteos', on_release=lambda x: self.verboton('lacteos')) self.buttonenlatados = MDFillRoundFlatButton( pos_hint={ "x": .50, "y": .05 }, size_hint=(.25, .1), text='Enlatados', on_release=lambda x: self.verboton('enlatados')) self.buttonactualizar.bind(on_press=lambda x: self.ActualizaPrecio()) self.add_widget(self.buttonactualizar) self.add_widget(self.buttonche) self.add_widget(self.buttonsor) self.add_widget(self.buttonhbe) self.add_widget(self.buttoncomer) self.add_widget(self.etiqueta1) self.add_widget(self.etiqueta2) self.add_widget(self.buttonfrutas) self.add_widget(self.buttonverduras) self.add_widget(self.buttoncarnes) self.add_widget(self.buttonlacteos) self.add_widget(self.buttonenlatados) #food-steak carne food-drumstick #food-apple fruta #cheese lacteos #carrot verduras #dome-light #return self.button #def tabla(self, widget): def MuestraNotificacionComparador(self): """Se muestra las notificaciones que se anexaron al modulo del comparador de precios""" self.a = randint(1, 6) print(self.a) if self.a == 1: notification.notify( title='Como Actualizar los precios', message= 'Puedes actualizar los precios de los productos pulsando el boton de Actualizar que se encuentra en' 'la parte superior', timeout=20) snackbar = Snackbar( text= "Puedes actualizar los precios de los productos pulsando el boton de Actualizar que se encuentra en la parte superior" ) snackbar.show() if self.a == 2: notification.notify( title='Visualización de los Precios', message= 'Los precios pueden ser consultados deslizando la tabla que se muestra al consultar alguna categoría', timeout=20) snackbar = Snackbar( text= "Los precios pueden ser consultados deslizando la tabla que se muestra al consultar alguna categoría" ) snackbar.show() pass def ActualizaPrecio(self): """Función desde la cual se obtienen los precios, se llama una funcion que esta en el fichero Actualiza Precios, se ejecutan hilos para obtener los precios simultaneamente, de esta manera se previene el congelamiento de la aplicación, en esta función tambien se llama a la funcion actualiza barra""" ap.main() self.add_widget(self.barra) self.add_widget(self.msgactualiza) self.buttonactualizar.disabled = True self.hiloactualiza = threading.Thread( target=self.actualizabarra ) # Inicializar un hilo llamando a una funcion self.hiloactualiza.start() #self.actualizabarra() self.dialog = MDDialog( title="Actualización de Precios", text= "Se actualizarán los precios que se muestran en cada una de las categorías del comparador de precios," " este proceso puede demorar algunos un par de minutos, por favor sea paciente", size_hint=[.9, .9], auto_dismiss=True, buttons=[ MDFlatButton(text="CERRAR", on_release=self.dialog_close), ]) self.dialog.open() def actualizabarra(self): """Funcion que actualiza la barra mostrada en el módulo comparador de precios""" #if ap.sor.correccion_datos_sor() == True: for a in range(100): self.valorbarra = self.valorbarra + 1 self.barra.value = self.valorbarra sleep(1.3) sleep(5) self.remove_widget(self.msgactualiza) sleep(1) self.remove_widget(self.barra) def dialog_close(self, *args): # Cierra el dialog del boton ayuda """Funcion que cierra el dialog que se despliega al oprimir el botón actualizar""" print("Cerrando Dialog") self.dialog.dismiss() def verboton(self, valor): self.MuestraNotificacionComparador() if valor == 'comer': datos = pd.read_csv("csv/info_lacomer.csv", encoding='utf8') elif valor == 'hbe': datos = pd.read_csv("csv/info_hbe.csv", encoding='utf8') elif valor == 'sor': datos = pd.read_csv("csv/info_sor.csv", encoding='utf8') elif valor == 'che': datos = pd.read_csv("csv/info_che.csv", encoding='utf8') elif valor == 'frutas': datos = pd.read_csv("csv/infofrutas.csv", encoding='utf8') elif valor == 'verduras': datos = pd.read_csv("csv/infoverduras.csv", encoding='utf8') elif valor == 'carnes': datos = pd.read_csv("csv/infocarnes.csv", encoding='utf8') elif valor == 'lacteos': datos = pd.read_csv("csv/infolacteos.csv", encoding='utf8') elif valor == 'enlatados': datos = pd.read_csv("csv/infoenlatados.csv", encoding='utf8') datos = datos.iloc[:, 1:] # primer arg selecciona todas las filas, segundo cols = datos.columns.values values = datos.values self.table = MDDataTable( pos_hint={ 'center_x': 0.5, 'center_y': 0.5 }, size_hint=(0.99, 0.99), #font_size = 10, #check= True, use_pagination=True, rows_num=10, column_data=[(col, dp(40)) for col in cols], row_data=values) self.table.bind(on_check_press=self.check_press) self.table.bind(on_check_press=self.row_press) self.table.open() print(valor) def my_callback( self, texto, popup_widget ): # funcion que ayuda a cerrar el dialog del boton actualizar print(texto) print(popup_widget) def open_table(self, instance): """Despliega el contenido de la tabla correpondiente al boton pulsado""" #screen.add_widget(table) self.table.open() def check_press(self, instance_table, current_row): print(instance_table, current_row) def row_press(self, instance_table, instance_row): print(instance_table, instance_row) #self.sub_title = "Comparador" def on_pre_enter(self, *args): self.app.title = "Comparador de precios" pass
class SmartBricksApp(MDApp): def __init__(self, **kwargs): super().__init__(**kwargs) Window.bind(on_keyboard=self.events) self.manager_open = False self.file_manager = MDFileManager(exit_manager=self.exit_manager, select_path=self.select_path, previous=True, ext=['jpeg', 'png', 'jpg']) #self.menu_2 = self.create_menu("Button dots", self.root.ids.toolbar.ids.button_2) #print('HEREEEEEEE!!!!', self.root) #cm = CustomToolbar try: request_permissions([ Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE ]) except NameError: pass def dropdown(self, id): self.menu_2 = self.create_menu("Button dots", id) self.menu_2.open() def create_menu(self, instance): menu_items = [ { "right_content_cls": RightContentCls( #text=f"R", icon="apple-keyboard-command", ), "icon": "apple-keyboard-command", "text": text, } for text in ('RENAME', 'DELETE') ] return MDDropdownMenu(caller=instance, items=menu_items, width_mult=4) def build(self): #Window.bind(on_keyboard=self.key_input) self.screen = Builder.load_file("main.kv") return self.screen def on_pause(self): return True #def key_input(self, window, key, scancode, codepoint, modifier): # if key == 27: # return True # override the default behaviour # else: # the key now does nothing # return False #settings_path = app_storage_path() path = os.getcwd() df = pd.read_csv('%s/legoKeys.cvs' % (path), sep='\t') try: SD_CARD = primary_external_storage_path() + '/' + 'DCIM/Camera' out_dir = '%s/smartbricks_outputs/' % (primary_external_storage_path()) print('ANDROID mmodules loaded...') except NameError: print('ANDROID modules failed...') SD_CARD = '/home/omar/Pictures' out_dir = '%s/myproj_out/' % (path) pass isdir = os.path.isdir(out_dir) def plist(self): if self.isdir: plist_ = os.listdir(self.out_dir) else: os.mkdir(self.out_dir) plist_ = None return plist_ custom_sheet = None def callback_for_menu_items(self, *args): toast(args[0]) def openScreen(self, itemdrawer): self.openScreenName(itemdrawer.target) self.root.ids.nav_drawer.set_state("close") def openScreenName(self, screenName): self.root.ids.screen_manager.current = screenName def ifproject(self): print('PLIST!!!!!!!!!', self.plist()) print('PLIST TYPE!!!!!!!!!', type(self.plist())) if ((self.isdir) & (self.plist() is not None)): #clear widgets if any previously load to avoid staking of color palettes between projects self.root.ids.grid_list.clear_widgets() #self.root.ids.grid_list.remove_widget(self.root.ids.grid_list) self.openScreenName('projects') #if ((self.isdir) & (self.plist is not None)): for dir_ in self.plist(): self.root.ids.grid_list.add_widget( CustomSmartTileWithLabel( source=self.out_dir + dir_ + '/all.jpeg', text="[size=32]%s[/size]" % (dir_))) else: self.callback_for_menu_items( 'No projects saved yet. Select START to start a new project.') def chooseproject(self, img_source): #clear widgets if any previously load to avoid staking of color palettes between projects self.root.ids.content_drawer.ids.md_list.clear_widgets() self.root.ids.image.source = img_source self.openScreenName('main') self.img_path = os.path.dirname(img_source) tab = np.load(self.img_path + '/table.npz') self.tab = tab['data'] row_data = [] n2x2, n2x1, n1x1 = 0, 0, 0 for num, i in enumerate(self.tab.T[0][:-1]): if i == '0.0_0.0_0.0': continue R, G, B = i.split("_") R, G, B = [np.int(np.float(j)) for j in [R, G, B]] mask = (self.df['R'] == R) & (self.df['G'] == G) & (self.df['B'] == B) Nbrick, color_name = self.df['LEGO No.'][mask].item( ), self.df['Color'][mask].item() #print(R,G,B, Nbrick, color_name) # self.root.ids.content_drawer.ids.md_list.add_widget( CustomMDIconButton(color=(R / 256, G / 256, B / 256, 1), text=color_name, text_color=(1, 0, 0, 1), icon='checkbox-blank-circle-outline')) n2x2 += int(self.tab.T[1][num]) n2x1 += int(self.tab.T[2][num]) n1x1 += int(self.tab.T[3][num]) row_data.append( (color_name, self.tab.T[1][num], self.tab.T[2][num], self.tab.T[3][num], int(self.tab.T[1][num]) + int(self.tab.T[2][num]) + int(self.tab.T[3][num]))) row_data.append(('Total', n2x2, n2x1, n1x1, n2x2 + n2x1 + n1x1)) #if len(row_data) > 10: pagination = True #else: pagination = False self.data_tables = MDDataTable( size_hint=(0.9, 0.6), rows_num=20, use_pagination=True if len(row_data) > 20 else False, check=False, column_data=[("Color", dp(40)), ("2x2", dp(10)), ("2x1", dp(10)), ("1x1", dp(10)), ("All", dp(10))], row_data=row_data, ) self.root.ids.content_drawer.ids.md_list.add_widget( CustomMDIconButton( color=self.theme_cls.primary_color, text='All', icon='checkbox-blank-circle-outline', #text_color=(R/256,G/256,B/256,1), #icon='checkbox-marked-circle' )) self.root.ids.content_drawer.ids.md_list.add_widget( CustomMDIconButton(color=self.theme_cls.primary_color, text='Original', icon='')) keep = self.tab.T[0] == 'total' b2x2 = self.root.ids.brick_2x2 b2x1 = self.root.ids.brick_2x1 b1x1 = self.root.ids.brick_1x1 for num, brick, brickLab in zip([1, 2, 3], [b2x2, b2x1, b1x1], ['2x2', '2x1', '1x1']): brick.text = brickLab + ': ' + self.tab.T[num][keep][0] def choose_palette(self, img_bg_color, text, id): self.root.ids.palette_toolbar.md_bg_color = img_bg_color self.img_path = os.path.dirname(self.root.ids.image.source) #R,G,B = np.float(img_bg_color[0]*256), np.float(img_bg_color[1]*256), np.float(img_bg_color[2]*256) R, G, B = np.int(img_bg_color[0] * 256), np.int( img_bg_color[1] * 256), np.int(img_bg_color[2] * 256) mean = np.mean([R, G, B]) #print(R,G,B) #self.root.ids.image.parent.remove_widget(self.root.ids.image) if text not in ['All', 'Original']: self.root.ids.image.clear_widgets() self.root.ids.image.source = self.img_path + '/%s_%s_%s.zip' % ( str(R), str(G), str(B)) else: self.root.ids.image.source = self.img_path + '/%s.jpeg' % ( text.lower()) print('SOURCE!!!!!!!', self.root.ids.image.source) print('TEXT!!!!!!!', text) id.icon = 'checkbox-marked-circle' #Get bricks counts tab = np.load(self.img_path + '/table.npz') self.tab = tab['data'] if text not in ['All', 'Original']: keep = self.tab.T[0] == '%s_%s_%s' % (str(R), str(G), str(B)) else: keep = self.tab.T[0] == 'total' b2x2 = self.root.ids.brick_2x2 b2x1 = self.root.ids.brick_2x1 b1x1 = self.root.ids.brick_1x1 if mean > 180: test_color = [0, 0, 0, 1] #black invert = False else: test_color = [1, 1, 1, 1] #withe invert = True id.text_color = test_color for num, brick, brickLab in zip([1, 2, 3], [b2x2, b2x1, b1x1], ['2x2', '2x1', '1x1']): brick.text = brickLab + ': ' + self.tab.T[num][keep][0] brick.text_color = test_color #print(brick.text_color) b2x2_i = self.root.ids.brick_2x2_icon b2x1_i = self.root.ids.brick_2x1_icon b1x1_i = self.root.ids.brick_1x1_icon for num, brick, brickLab in zip([1, 2, 3], [b2x2_i, b2x1_i, b1x1_i], ['2x2', '2x1', '1x1']): #print('MAIN PATH:', self.path) if invert: brick.icon = "%s/images/%s_invert.jpg" % (self.path, brickLab) else: brick.icon = "%s/images/%s.jpg" % (self.path, brickLab) #self.root.ids.brick_2x2.text = '2x2: '+self.tab.T[1][keep][0] #self.root.ids.brick_2x1.text = '2x1: '+self.tab.T[2][keep][0] #self.root.ids.brick_1x1.text = '1x1: '+self.tab.T[3][keep][0] #print(mean, test_color, self.root.ids.brick_2x2.text_color) #self.root.ids.brick_2x2.text_color=test_color #if invert: self.root.ids.brick_2x2_icon.icon="/home/omar/myproj/SmartBricks/2x2_invert.jpg" #else: self.root.ids.brick_2x2_icon.icon="/home/omar/myproj/SmartBricks/2x2.jpg" #print(self.root.ids.brick_2x2.text_color) #def test(self, R, G, B): # return R,G,B,1 def callback_mosaic_size(self, instance, value): toast('mosaic size: %s' % (value)) self.mosaic_size_val = value def callback_mosaic_color(self, instance, value): toast('mosaic colors: %s' % (value)) self.mosaic_color_val = value def callback_mosaic_name(self, instance, value): toast('mosaic name: %s' % (value)) self.mosaic_name = value def show_alert_dialog(self, name): if not self.dialog: self.dialog = MDDialog( title="Replace existing project?", text= "Project '%s' already exists. Do you want to replace existing project?" % (name), buttons=[ MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color, on_press=lambda x: self.dialog.dismiss()), MDFlatButton( text="ACCEPT", text_color=self.theme_cls.primary_color, on_press=lambda x: self.show_dialog_progress()), ], ) else: self.dialog.dismiss() self.dialog.open() def create_mosaic(self): print('LOWSIZE --------', type(self.mosaic_size_val)) print('NCOLORS --------', type(self.mosaic_color_val)) print('OUTDIR --------', type(self.root.ids.project_name.text)) if (self.mosaic_size_val is None) or (self.mosaic_color_val is None) or (self.root.ids.project_name.text == ''): ttext = 'Define mosaic input values' if (self.mosaic_size_val is None): ttext += ', lower size' if (self.mosaic_color_val is None): ttext += ', colors' if (self.root.ids.project_name.text == ''): ttext += ', project name' print('TEXT ------ ', ttext) toast(ttext) #elif #elif (if not self.root.ids.project_name.text): # toast('Choose a project name first') else: #print(self.root.ids.setup_image.source) #print(int(self.mosaic_size_val)) #print(int(self.mosaic_color_val)) #print(self.root.ids.project_name.text) #print(self.out_dir+self.root.ids.project_name.text) self.imgpath = str(self.root.ids.setup_image.source) self.Ncolors = np.int(self.mosaic_color_val) self.lowsize = np.int(self.mosaic_size_val) self.outdir = str(self.out_dir + self.root.ids.project_name.text) for i in [self.imgpath, self.Ncolors, self.lowsize, self.outdir]: print(i, type(i)) if (self.plist() is not None): if (self.root.ids.project_name.text in self.plist()): print('project name already exist...') self.show_alert_dialog( name=self.root.ids.project_name.text) else: self.show_dialog_progress() else: self.show_dialog_progress() def show_dialog_progress(self): #if not self.dialog2: self.dialog2 = MDDialog( title="Creating mosaic. Please wait.", type="custom", #text="Creating mosaic. Please wait.", content_cls=progress_bar(), #self.pb, on_open=self.run_mosaic #on_open=self.puopen) #on_open=self.run_mosaic(imgpath=imgpath, Ncolors=Ncolors, lowsize=lowsize, outdir=outdir) ) self.dialog2.open() if self.dialog: self.dialog.dismiss() #self.dialog2.bind(on_open=self.run_mosaic) #self.run_mosaic #def run_mosaic(self, imgpath=None, Ncolors=None, lowsize=None, outdir=None): def run_mosaic(self, instance): #clear widgets if any previously load to avoid staking of color palettes between projects #self.pb.load_bar.clear_widgets() self.pb = progress_bar() #self.pb.load_bar.parent.remove_widget(self.pb.load_bar) self.pb.load_bar.value = 0 #print(self.pb.load_bar.value) #Nmax = np.int(self.mosaic_color_val) #+ 3 start = time.time() SB = SmartBricks(imgpath=self.imgpath, Ncolors=self.Ncolors, lowsize=self.lowsize, outdir=self.outdir) #print(SB.img) #print(SB.res1x1) #SB.saveProj() end = time.time() print('Total run time #1: %f sec' % (end - start)) print('point size', SB.size) import matplotlib.pyplot as plt ispathdir = os.path.isdir(self.outdir) if not ispathdir: os.makedirs(self.outdir, exist_ok=True) else: files = os.listdir(self.outdir) #print(self.outdir) for f in files: os.remove(self.outdir + '/' + f) start = time.time() #lmax = 10 if SB.w > SB.h: x_size, y_size = SB.lmax, SB.h * SB.lmax / SB.w else: x_size, y_size = SB.w * SB.lmax / SB.h, SB.lmax fig = plt.figure(figsize=(x_size, y_size)) #fig = plt.figure(figsize=(12,12)) ax = plt.gca() SB.bricksCanvas(img=SB.img, fig=fig, ax=ax, RGB=None, res2x2=SB.res2x2, res2x1=SB.res2x1, res1x1=SB.res1x1) figcvs = fig figall = fig #figoriginal = fig.copy #paletteLego = SB.palette(SB.img) #palette_flat = SB.imgFlat(paletteLego) Nmax = len(SB.palette_flat) self.pb.load_bar.max = Nmax table = [] #for num, pal in enumerate(palette_flat): for i in range(Nmax): print(self.pb.load_bar.value) pal = SB.palette_flat[i] N2x2, N2x1, N1x1 = SB.makeGiff( img=SB.img, RGB=pal, idxs=[SB.res2x2[2], SB.res2x1[2], SB.res1x1[2]], pathdir=self.outdir, fig=figcvs, ax=ax) r, g, b = pal color = '%s_%s_%s' % (r, g, b) table.append([color, N2x2, N2x1, N1x1]) self.pb.load_bar.value = i + 1 #self.value99 = i+1 t = np.array(table) N2x2total = np.sum(t[:, 1].astype(int)) N2x1total = np.sum(t[:, 2].astype(int)) N1x1total = np.sum(t[:, 3].astype(int)) table.append(['total', N2x2total, N2x1total, N1x1total]) end = time.time() print('Total run time #2: %f sec' % (end - start)) start = time.time() figall.subplots_adjust(left=SB.left, bottom=SB.bottom, right=SB.right, top=SB.top, wspace=None, hspace=None) ax = figall.add_subplot(111) ax.imshow(SB.img) #True if testing App from PC. if SB.frompc: figall.savefig('%s/all.jpeg' % (self.outdir), bbox_inches='tight', pad_inches=0) else: buffer = io.BytesIO() canvas = plt.get_current_fig_manager().canvas canvas.draw() pil_image = PIL.Image.frombytes('RGB', canvas.get_width_height(), canvas.tostring_rgb()) pil_image.save('%s/all.jpeg' % (self.outdir), 'JPEG') fig0 = plt.figure(figsize=(x_size, y_size)) fig0.subplots_adjust(left=SB.left, bottom=SB.bottom, right=SB.right, top=SB.top, wspace=None, hspace=None) ax = plt.gca() ax = fig0.add_subplot(111) ax.imshow(SB.img_original) if SB.frompc: fig0.savefig('%s/original.jpeg' % (self.outdir), bbox_inches='tight', pad_inches=0) else: buffer = io.BytesIO() canvas = plt.get_current_fig_manager().canvas canvas.draw() pil_image = PIL.Image.frombytes('RGB', canvas.get_width_height(), canvas.tostring_rgb()) pil_image.save('%s/original.jpeg' % (self.outdir), 'JPEG') #ax = figall.add_subplot(111) #ax.imshow(SB.img) #figall.savefig('%s/all.jpeg' %(self.outdir), bbox_inches = 'tight', pad_inches = 0) #fig0 = plt.figure(figsize=(12,12)) #ax = fig0.add_subplot(111) #plt.imshow(SB.img_original) #fig0.savefig('%s/original.jpeg' %(self.outdir), bbox_inches = 'tight', pad_inches = 0) np.savez_compressed('%s/table' % (self.outdir), data=table) end = time.time() print('Total run time #3: %f sec' % (end - start)) if Nmax == self.pb.load_bar.value: self.dialog2.dismiss() #SmartBricks(imgpath=self.imgpath, Ncolors=self.Ncolors, lowsize=self.lowsize, outdir=self.outdir).saveProj(self.pb.load_bar.value) self.chooseproject(self.outdir + '/all.jpeg') def next(self, dt): #if self.times == 0: #self.run_mosaic # SmartBricks(imgpath=self.imgpath, Ncolors=self.Ncolors, lowsize=self.lowsize, outdir=self.outdir).saveProj() # self.times = 1 if os.path.exists(self.outdir): #self.value99 += 1 print(self.pb.load_bar.value) Nmax = np.int(self.mosaic_color_val) + 3 self.pb.load_bar.max = Nmax Ncurrent = len( os.listdir(str(self.out_dir + self.root.ids.project_name.text))) print(self.pb.load_bar.value, self.pb.load_bar.max, Ncurrent) #print(self.pb.load_bar.value, self.pb.load_bar.max) if self.pb.load_bar.value >= Nmax: return False else: self.pb.load_bar.value = Ncurrent #self.pb.load_bar.value = self.value99 else: print('PATH DOES NOT EXIST YET!') #print(self.times) def puopen(self, instance): #self.times = 0 Clock.schedule_interval(self.next, 1 / 25) #self.run_mosaic def on_start(self): self.imgpath = None self.Ncolors = None self.lowsize = None self.outdir = None self.mosaic_size_val = None self.mosaic_color_val = None self.mosaic_name = None self.dialog = None self.dialog2 = None self.value99 = 0 #self.pb = progress_bar() self.menu_2 = self.create_menu(self.root.ids.toolbar) self.root.ids.avatar.source = '%s/images/logo.zip' % (self.path) self.root.ids.brick_2x2_icon.icon = "%s/images/%s.jpg" % (self.path, '2x2') self.root.ids.brick_2x1_icon.icon = "%s/images/%s.jpg" % (self.path, '2x1') self.root.ids.brick_1x1_icon.icon = "%s/images/%s.jpg" % (self.path, '1x1') for i in np.arange(8, 72, 8): self.root.ids.mosaic_size.add_widget( CustomMDChip(label='%s' % (str(i)), cb=self.callback_mosaic_size, icon='grid')) for i in np.arange(2, 18, 2): self.root.ids.mosaic_colors.add_widget( CustomMDChip(label=str(i), cb=self.callback_mosaic_color, icon='palette')) #print(self.custbutt.palette.md_bg_color) #self.root.ids.content_drawer.ids.palette.md_bg_color = (i/100,i/10,0,1) #md_bg_color=(1,0,0,1) # # self.root.ids.content_drawer.ids.md_list.add_widget( # ItemDrawer(target="screen1", text="Screen 1", # icon="home-circle-outline", # on_release=self.openScreen) # ) # self.root.ids.content_drawer.ids.md_list.add_widget( # ItemDrawer(target="screen2", text="Screen 2", # icon="settings-outline", # on_release=self.openScreen) # ) def custom_bottom_sheet(self): self.custom_sheet = MDCustomBottomSheet( screen=Factory.ContentCustomSheet()) self.custom_sheet.open() def show_gallery(self): self.openScreenName('camera') types = ('*.png', '*.jpeg', '*.jpg') # the tuple of file types files_grabbed = [] for files in types: files_grabbed.extend(glob.glob(os.path.join(self.SD_CARD, files))) files_grabbed.sort(key=os.path.getmtime) files_grabbed.reverse() for file in files_grabbed[:20]: self.root.ids.grid_list_camera.add_widget( CustomSmartTileWithLabelGallery(source=file, text="[size=18]%s[/size]" % (os.path.basename(file)))) def file_manager_open(self): #self.file_manager.show('/home/omar/Pictures') # output manager to the screen #self.file_manager.show(self.settings_path) self.file_manager.show(self.SD_CARD) self.manager_open = True def select_path(self, path): '''It will be called when you click on the file name or the catalog selection button. :type path: str; :param path: path to the selected directory or file; ''' try: self.exit_manager() except: pass self.openScreenName('setup') self.root.ids.setup_image.source = path toast(path) def exit_manager(self, *args): '''Called when the user reaches the root of the directory tree.''' self.manager_open = False self.file_manager.close() def show_dialog_eddit(self): if self.dialog: self.dialog.dismiss() #if not self.dialog2: self.dialog = MDDialog( title="Eddit project?", text="Make a new project with same image.", buttons=[ MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color, on_press=lambda x: self.dialog.dismiss()), MDFlatButton(text="ACCEPT", text_color=self.theme_cls.primary_color, on_press=lambda x: self.eddit_project()), ]) self.dialog.open() def eddit_project(self): #self.img_path = os.path.dirname(self.root.ids.image.source) img_path = self.img_path + '/original.jpeg' self.openScreenName('setup') if self.dialog: self.dialog.dismiss() self.root.ids.setup_image.source = img_path toast(img_path) def events(self, instance, keyboard, keycode, text, modifiers): '''Called when buttons are pressed on the mobile device.''' if keyboard in (1001, 27): if self.manager_open: self.file_manager.back() return True def goto_table(self): #self.openScreenName('mosaic_details') self.data_tables.open(self.root.ids.details) def back_main(self): self.data_tables.dismiss() self.openScreenName('main') def show_dialog_buy(self): if self.dialog: self.dialog.dismiss() #if not self.dialog2: self.dialog = MDDialog( title="Cooming Soon", text= "Apologies, SmartBricks does not deliver yet. We are working to deliver your favourite mosaic to you. Are you interested in buying? ", buttons=[ MDFlatButton(text="NO", text_color=self.theme_cls.primary_color, on_press=lambda x: self.dialog.dismiss()), MDFlatButton(text="YES", text_color=self.theme_cls.primary_color, on_press=lambda x: self.dialog.dismiss()), ]) self.dialog.open() def show_dialog_empty(self): if self.dialog: self.dialog.dismiss() #if not self.dialog2: self.dialog = MDDialog( title="Cooming Soon", text="This option is not yet available.", buttons=[ MDFlatButton(text="Cancel", text_color=self.theme_cls.primary_color, on_press=lambda x: self.dialog.dismiss()) ]) self.dialog.open()
class vParkApp(MDApp): def build(self): screen = Builder.load_string(screen_helper) self.data_tables = MDDataTable( size_hint=(0.9, 0.6), # name column, width column column_data=[("Particulars", dp(20)), ("Days Left", dp(20))], row_data=[("1. Insurance", ""), ("2. Pollution", ""), ("3. Service", ""), ("4. Driving Licence", "")]) return screen def open_table(self): self.data_tables.open() # Functions to change screens: def ShowProfile(self): self.root.ids.screen_manager.current = 'profile' def ShowHome(self): self.root.ids.screen_manager.current = 'home' def ShowCamera(self): self.root.ids.screen_manager.current = 'camera' def ShowManualEntryScreen(self): self.root.ids.screen_manager.current = 'MEScreen' def ShowInfo(self, data): self.root.ids.screen_manager.current = 'InfoScreen' def ShowCreateAccount(self): self.root.ids.screen_manager.current = 'create' def ShowLogin(self): self.root.ids.screen_manager.current = 'login' def ShowCreate(self): self.root.ids.screen_manager.current = 'create' def callback_for_menu_items(self, *args): toast(args[0]) def show_bottom_sheet(self): self.bottom_sheet_menu = MDGridBottomSheet() data = { "Facebook": "facebook-box", "WhatsApp": "whatsapp", "Telegram": "telegram", "Twitter": "twitter-box", "Gmail": "gmail", "Bluetooth": "bluetooth", } for item in data.items(): self.bottom_sheet_menu.add_item( item[0], lambda x, y=item[0]: self.callback_for_menu_items(y), icon_src=item[1], ) self.bottom_sheet_menu.open() # Function for OCR (bare for now, needs optimisations, work on it after successful apk build) def OCR(self): # create a camera variable camera1 = self.root.ids['cam'] # capture a shot and export to png camera1.export_to_png("IMG.png") # open image in PIL(basically storing image in a variable) img = Image.open('IMG.png') # OCR using pytesseract stored in a variable named 'data' data = pytesseract.image_to_string(img) # Create a dialog to show the 'data' on screen and open the dialog self.ShowInfo(data) print(data) # Manual entry function: def ManualEntry(self): pass db = DataBase("users.txt") email = ObjectProperty(None) password = ObjectProperty(None) def loginBtn(self): if self.db.validate(self.root.ids.email.text, self.root.ids.password.text): self.reset() self.root.ids.screen_manager.current = 'home' else: self.invalidLogin() def createBtn(self): self.reset() self.root.ids.screen_manager.current = "create" def reset(self): self.root.ids.email.text = "" self.root.ids.password.text = "" def invalidLogin(self): self.pop = MDDialog(text='Invalid username or password.', size_hint=(.5, .3)) self.pop.open() def invalidForm(self): self.pop = MDDialog(text='Please fill in all inputs', size_hint=(.8, .3)) self.pop.open() name1 = ObjectProperty(None) email1 = ObjectProperty(None) password1 = ObjectProperty(None) def submit(self): if self.root.ids.name1.text != "" and self.root.ids.email1.text != "" and self.root.ids.email1.text.count( "@") == 1 and self.root.ids.email1.text.count(".") > 0: if self.root.ids.password1 != "": self.db.add_user(self.root.ids.email1.text, self.root.ids.password1.text, self.root.ids.name1.text) self.reset() self.root.ids.screen_manager.current = "home" else: self.invalidForm() else: self.invalidForm() def lost_vehicle(self): pass