class Example(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, ) def build(self): return Builder.load_string(KV) def file_manager_open(self): self.file_manager.show('/') # output manager to the screen self.manager_open = True def select_path(self, path): self.exit_manager() toast(path) def exit_manager(self, *args): self.manager_open = False self.file_manager.close() def events(self, instance, keyboard, keycode, text, modifiers): if keyboard in (1001, 27, 8): if self.manager_open: self.file_manager.back() return True
class MainApp(MDApp): def build(self): manager = ScreenManager() manager.add_widget(Login(name='login_window')) manager.add_widget(Registration(name='register_window')) manager.add_widget(HomeWindow(name='home_window')) manager.add_widget(SettingsWindow(name='settings')) manager.add_widget(GroupWindow(name='group_window')) manager.add_widget(NewGroupWindow(name='new_group_window')) manager.add_widget(ActivityWindow(name='activity_window')) manager.add_widget(NewActivityWindow(name='new_activity_window')) manager.add_widget(JoinGroupWindow(name='join_group_window')) manager.add_widget(ActivityDetailWindow(name='activity_detail_window')) manager.add_widget(PaymentWindow(name='payment_window')) manager.add_widget(MyTransactionWindow(name='my_transaction_window')) manager.add_widget(ApprovalsWindow(name='approvals_window')) manager.add_widget(AddResourcesWindow(name='new_resource_window')) self.theme_cls.primary_palette = 'Blue' self.theme_cls.theme_style = "Light" self.title="Aaksathe" return manager # Below all functions are used to handle file manager 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, ) def file_manager_open(self): self.file_manager.show('/') # output manager to the screen 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; ''' print(path) self.exit_manager() 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 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
class Example(MDApp): dialog = None 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, ) def build(self): return Builder.load_string(KV) def file_manager_open(self): self.file_manager.show('/') # output manager to the screen 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; """ self.exit_manager() 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 events(self, instance, keyboard, keycode, text): """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 navigation_draw(self): self.dialog = MDDialog( title="Fake detector is an app that helps you detect fake currency", size_hint=(0.7, 1)) self.dialog.open()
class MainApp(MDApp): def __init__(self=None, **kwargs): self.title = "FLOW OF THOUGHTS" self.theme_cls.theme_style = "Light" self.theme_cls.primary_palette = "Indigo" super().__init__(**kwargs) con = sql.connect(blog_db) cur = con.cursor() cur.execute(create_content_query) cur.execute(create_users_query) cur.execute(first_user_query, (admin_email, admin_password, 1)) cur.execute(create_log_query) con.commit() con.close() self.manager_open = False self.file_manager = MDFileManager( exit_manager=self.exit_manager, select_path=self.select_path, previous=True, ) def on_checkbox_active(self, checkbox, value): global isprivate if value: isprivate = 1 else: isprivate = 0 def file_manager_open(self): self.file_manager.show('/') self.manager_open = True def select_path(self, path): global blob_path blob_path = path self.exit_manager() toast(path) def exit_manager(self): self.manager_open = False self.file_manager.close() def events(self, instance, keyboard, keycode, text, modifiers): if keyboard in (1001, 27): if self.manager_open: self.file_manager.back() return True
class Recetas(MDBoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) Window.bind(on_keyboard=self.events) # my_path = str(storagepath.get_pictures_dir()) self.manager_open = False self.file_manager = MDFileManager( exit_manager=self.exit_manager, select_path=self.select_path, preview=True, ) def file_manager_open(self): self.file_manager.show('/') # output manager to the screen 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; ''' self.exit_manager() 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 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 btn(self): print(str(storagepath.get_pictures_dir())) self.ids.fotos_label.text = str(storagepath.get_pictures_dir()) pass
class VChat(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, ) self.file_manager.ext = [] def build(self): return Builder.load_string(KV) def file_manager_open(self): self.file_manager.show('/') # output manager to the screen 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; ''' self.exit_manager() print(path) toast(path) path = "D:" + path self.start_music(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 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 start_music(self, path): sound = SoundLoader.load(path) if sound: sound.play()
class GincellApp(MDApp): path_label = ObjectProperty(None) 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=False, ) self.file_manager.ext = ['.xlsx'] def confirm_text(self): toast("Staks in progress...") def file_manager_open(self): self.file_manager.show( '/home/sveta/programming/git') #('/data/media/0') self.manager_open = True def select_path(self, path): self.t = str(path) self.exit_manager() toast(self.t) self.path_label.text = self.t def exit_manager(self, *args): self.manager_open = False self.file_manager.close() def events(self, instance, keyboard, keycode, text, modifiers): if keyboard in (1001, 27): if self.manager_open: self.file_manager.back() return True def build(self): self.theme_cls.theme_style = "Dark" self.theme_cls.primary_palette = "Orange" screen = Builder.load_string(KV) return screen
class Screen1(Screen): def __init__(self, *args, **kwargs): super(Screen1, self).__init__(**kwargs) entries = os.listdir('codigo/Empresas') for i in [*entries]: self.ids.wig.add_widget(Lista(i)) Window.bind(on_keyboard=self.events) self.manager_open = False self.file_manager = MDFileManager( exit_manager=self. exit_manager, # function called when the user reaches directory tree root select_path=self.select_path, ext=[".py", "kv"], ) self.file_manager.ext = [".json"] def file_manager_open(self): self.file_manager.show('/') # output manager to the screen self.manager_open = True def select_path(self, path): self.exit_manager() shutil.copy(path, 'codigo/Empresas') self.ids.wig.clear_widgets() entries = os.listdir('codigo/Empresas') for i in [*entries]: self.ids.wig.add_widget(Lista(i)) toast(path) def exit_manager(self, *args): self.manager_open = False self.file_manager.close() def events(self, instance, keyboard, keycode, text, modifiers): if keyboard in (1001, 27): if self.manager_open: self.file_manager.back() return True
class MainApp(MDApp): def __init__(self, **kwargs): self.title = "STEGANOGRAPHY" self.theme_cls.primary_palette = "Green" super().__init__(**kwargs) Window.bind(on_keyboard=self.events) self.file_manager = MDFileManager( exit_manager=self.exit_manager, select_path=self.select_path, ) def build(self): self.root = Factory.AppUI() def file_manager_open(self): self.file_manager.show('/') self.manager_open = True def select_path(self, path): self.exit_manager() toast(path) def exit_manager(self, *args): self.manager_open = False self.file_manager.close() def events(self, instance, keyboard, keycode, text, modifiers): if keyboard in (1001, 27): if self.manager_open: self.file_manager.back() return True def process(self): ''' PROCESS VIET O DAY ''' pass
class NavDrawer(MDNavigationDrawer): """Main menu""" def __init__(self, **kwargs): self.micro_sim = kwargs.pop('micro_sim') self.app = kwargs.pop('app') self.dpi = kwargs.pop('dpi') self.main_window = kwargs.pop('main_window') super().__init__(**kwargs) self.drawer_logo = 'assets/images/logo.jpg' self.spacing = 0 self.manager_open = False self.manager = None self.file_manager = None self.history = [] self.add_widget(NavigationDrawerSubheader(text='Menu:')) self.add_widget( NavigationDrawerIconButton(icon='paperclip', text='Load File', on_release=self.file_manager_open)) self.traffic_lights = NavigationDrawerIconButton( icon='traffic-light', text=TRAFFIC_LIGHT['menu_title'] + '. Current Port: ' + str(TRAFFIC_LIGHT['port']), on_release=self.io_config_open) self.seven_segment = NavigationDrawerIconButton( icon='numeric-7-box-multiple', text=SEVEN_SEGMENT_DISPLAY['menu_title'] + '. Current Port: ' + str(SEVEN_SEGMENT_DISPLAY['port']), on_release=self.io_config_open) self.ascii_table = NavigationDrawerIconButton( icon='alphabetical-variant', text=ASCII_TABLE['menu_title'] + '. Current Port: ' + str(ASCII_TABLE['port']), on_release=self.io_config_open) self.hex_keyboard = NavigationDrawerIconButton( icon='keyboard', text=HEX_KEYBOARD['menu_title'] + '. Current Port: ' + str(HEX_KEYBOARD['port']), on_release=self.io_config_open) self.add_widget(self.traffic_lights) self.add_widget(self.seven_segment) self.add_widget(self.ascii_table) self.add_widget(self.hex_keyboard) def io_config_open(self, instance): """ Opens IO configuration :param instance: obj """ dialog = MDInputDialog(title=instance.text, hint_text='Input port number [000-FFF]', text_button_ok='Save', text_button_cancel='Cancel', events_callback=self.save_io_ports) if self.dpi < 192: dialog.size_hint = (dp(0.4), dp(0.4)) else: dialog.size_hint = (dp(0.2), dp(0.2)) dialog.pos_hint = {'x': dp(0.15), 'y': dp(0.15)} dialog.open() def save_io_ports(self, *args): """ Saves IO device ports :param args: tuple """ if args[0] == 'Save': title = args[1].title text = args[1].text_field.text try: port = int(text, 16) if port < 0 or port > 4095: toast('Invalid port number. Valid port numbers [0-4095]') else: if is_valid_port(port): hex_port = convert_to_hex(port, 12) if TRAFFIC_LIGHT['menu_title'] in title: update_reserved_ports(TRAFFIC_LIGHT, TRAFFIC_LIGHT['port'], hex_port) self.traffic_lights.text = TRAFFIC_LIGHT[ 'menu_title'] + '. Current Port: ' + str( TRAFFIC_LIGHT['port']) toast_message = f'Changed Traffic Light I/O port number to {port}' elif SEVEN_SEGMENT_DISPLAY['menu_title'] in title: update_reserved_ports( SEVEN_SEGMENT_DISPLAY, SEVEN_SEGMENT_DISPLAY['port'], hex_port) self.seven_segment.text = SEVEN_SEGMENT_DISPLAY[ 'menu_title'] + '. Current Port: ' + str( SEVEN_SEGMENT_DISPLAY['port']) toast_message = f'Changed Seven Segment I/O port number to {port}' elif ASCII_TABLE['menu_title'] in title: if port > 4088: toast_message = 'Invalid port for ASCII Table. Valid ports [0-4088]' else: try: update_reserved_ports( ASCII_TABLE, ASCII_TABLE['port'], hex_port, True) self.ascii_table.text = ASCII_TABLE[ 'menu_title'] + '. Current Port: ' + str( ASCII_TABLE['port']) toast_message = f'Changed ASCII Table I/O port number to {port}' except MemoryError as e: toast_message = str(e) else: update_reserved_ports(HEX_KEYBOARD, HEX_KEYBOARD['port'], hex_port) self.hex_keyboard.text = HEX_KEYBOARD[ 'menu_title'] + '. Current Port: ' + str( HEX_KEYBOARD['port']) toast_message = f'Changed HEX Keyboard I/O port number to {port}' toast(toast_message) else: toast('Invalid input. That port is reserved!') except ValueError as e: toast(f'Not a valid port!') def file_manager_open(self, instance): """ Opens file manager :param instance: obj """ if not self.manager: manager_size = (dp(1), 1) if self.dpi < 192 else (dp(0.5), 1) self.manager = ModalView(auto_dismiss=False, size_hint=manager_size, background_color=[1, 1, 1, 1]) self.file_manager = MDFileManager(exit_manager=self.exit_manager, select_path=self.select_path, ext=['.asm', '.obj']) self.manager.add_widget(self.file_manager) # output manager to the screen self.file_manager.show(str(Path.home())) self.manager_open = True self.manager.open() self.history = self.file_manager.history 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; """ self.exit_manager() if path.endswith('.obj'): EVENTS['IS_OBJ'] = True EVENTS['EDITOR_SAVED'] = True EVENTS['CAN_WRITE'] = True EVENTS['FILE_PATH'] = path EVENTS['LOADED_FILE'] = True toast(f'{path} loaded successfully') EVENTS['IS_RAM_EMPTY'] = False update_indicators(self.main_window, EVENTS['LOADED_FILE']) def exit_manager(self, *args): """Called when the user reaches the root of the directory tree.""" self.manager.dismiss() self.manager_open = False self.file_manager.history = self.history def events(self, instance, keyboard): """Called when buttons are pressed on the mobile device..""" if keyboard in (1001, 27): if self.manager_open: self.file_manager.back() return True
class ShelfApp(MDApp): def __init__(self, **kwargs): self.title = "Shelf 3" self.theme_cls.theme_style = "Dark" self.theme_cls.primary_palette = "Teal" 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=False, ) self.file_manager.ext = ['.xlsx'] def build(self): #return MainScreen() return Builder.load_string(KV) def file_manager_open(self): self.file_manager.show("/") #('/data/media/0') self.manager_open = True # output manager to the screen def server_update(self, path): self.path = path self.delete_old_data() self.upload_data(self.path) def dict_from_xl(self, path): self.path = path self.wb = load_workbook(filename=self.path) self.ws = self.wb.worksheets[0] self.adres_dict = {} for i in range(1, len(self.ws["A"])): self.k = str(self.ws["A" + str(i)].value) self.v = str(self.ws["B" + str(i)].value) self.adres_dict.update([(self.k, self.v)]) print("dictionary passed") return self.adres_dict def upload_data(self, path): # TODO функция заполнения внутреннего xlsx файла # из внешнего, указанного пользователем print("Загрузка завершена") def delete_old_data(self): # TODO функция очистки внутреннего файла перед # заполнением (возможно не нужна) print("В процессе...") 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; ''' self.exit_manager() self.server_update(path) toast('Адреса обновлены') 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 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
class Example(MDApp): featureOne = ObjectProperty(None) featureTwo = ObjectProperty(None) def build(self): return Builder.load_file('template.kv') def on_start(self): '''''' # for i in ["first tab", "second tab", "third tab"]: # self.root.ids.tabs.add_widget(Tab(text=f"{i}")) def on_tab_switch(self, instance_tabs, instance_tab, instance_tab_label, tab_text): instance_tab.ids.label.text = "" # Can add text here ######################################################################### 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, ext=[".csv", ".xlsx"]) def file_manager_open(self): self.file_manager.show(r'C:\Users\Admin\OneDrive\Documents' ) # output manager to the screen 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; ''' self.exit_manager() # toast(path) # Use "path" to get the path of file selected from file manager, then can feed it into pandas df = pd.read_excel(path) df.to_csv("I DID IT.csv") def exit_manager(self, *args): '''Called when the user reaches the root of the directory tree.''' self.manager_open = True self.file_manager.close() 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 btn(self): # Get the text inputs from the kivy file featureOne = self.root.ids.featureOne featureTwo = self.root.ids.featureTwo print(featureOne.text, featureTwo.text) class ScrollableLabel(ScrollView): text = StringProperty('')
class ZipvyApp(MDApp): action_button_data = { 'language-python': 'Green', 'language-php': 'Orange', 'language-cpp': 'Blue', } 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) self.file_manager.ext = [".zip"] def on_start(self): self.icon = 'icon.ico' Logger.setLevel(LOG_LEVELS["debug"]) self.zip_path = None def build(self): if platform == 'android': from android import loadingscreen loadingscreen.hide_loading_screen() self.theme_cls.primary_palette = "Pink" self.theme_cls.secondary_palette = "Dark" ui = Builder.load_file('main_screen.kv') Logger.debug("Logger is started") return ui def select_zip(self, *args): if platform == 'android': if check_permission( Permission.WRITE_EXTERNAL_STORAGE ) == False: # check permission takes str not a list request_permission(Permission.WRITE_EXTERNAL_STORAGE) request_permission(Permission.READ_EXTERNAL_STORAGE) request_permission(Permission.MANAGE_EXTERNAL_STORAGE) request_permission(Permission.MANAGE_DOCUMENTS) #request_permisssion takes str and request_permissions takes list return self.secondary_ext_storage = secondary_external_storage_path() self.primary_ext_storage = primary_external_storage_path() self.app_path = app_storage_path() Logger.debug(" Storages are \n" + str(self.app_path) + "\n" + str(self.primary_ext_storage)) else: #self.root.ids.status_label.text = " I am not running in android " pass self.file_manager_open() def _select_zip(self): try: if self.zip_path == None or os.path.splitext( self.zip_path)[1] != '.zip': self._update_status("Wrong File is Selected ") return Logger.debug(self.zip_path) self.zip_name = os.path.basename(self.zip_path)[:-4] self._update_status(str(self.zip_name) + " is selected") self._update_progress_bar(20) except Exception as e: Logger.exception(e) self._update_status("Something went wrong ... Try again") def file_manager_open(self): if platform == "android": self.file_manager.show("/storage/emulated/0/") else: self.file_manager.show("/") # output manager to the screen 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; ''' self.zip_path = path print("printing selected zip path ... " + str(path)) self.exit_manager() def exit_manager(self, *args): '''Called when the user reaches the root of the directory tree.''' self.manager_open = False self.file_manager.close() if self.zip_path == None: self._update_status("No file is selected") return select_zip_thread = Thread(target=self._select_zip) select_zip_thread.start() 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 convert(self, *args): if platform == 'android': if check_permission( Permission.WRITE_EXTERNAL_STORAGE ) == False: # check permission takes str not a list request_permission(Permission.WRITE_EXTERNAL_STORAGE) request_permission( Permission.READ_EXTERNAL_STORAGE ) # request_permisssion takes str and request_permissions takes list return # Make a Folder for Zip # Make ChandanVideo Folder in Internal Storage if self.zip_path == None or os.path.splitext( self.zip_path)[1] != '.zip': self.root.ids.status_label.text = "Select a zip first " return self._update_status("Please Wait ... Checking Zip") self.clips_path = os.path.join(self.app_path, self.zip_name) self.video_folder = os.path.join(self.primary_ext_storage, "Zipvy") self.video_location = os.path.join(self.video_folder, self.zip_name + ".mp4") Logger.debug("Clips Path : " + str(self.clips_path) + "\n video_folder : " + str(self.video_folder) + "\n video_path:" + str(self.video_location)) convert_thread = Thread(target=self._convert) convert_thread.start() else: self.root.ids.prog.value = 75 self.root.ids.status_label.text = " I am running in " + str( platform) print(" I am running in " + str(platform)) def _convert(self): try: if not os.path.exists(self.clips_path): os.makedirs(self.clips_path) if not os.path.exists(self.video_folder): os.makedirs(self.video_folder) # Extract Zip to the folder unzip(self.zip_path, self.clips_path) self._update_status("Unzipped") Logger.debug("Unzipped clips for file " + str(self.zip_path)) Logger.debug("clips are available at " + str(self.clips_path)) # move clips to root move_to_root_folder(self.clips_path, self.clips_path) Logger.debug("Moving clips to root dir is done") # Delete Small clips ... deleted_clips = delete_small_clips(self.clips_path) Logger.debug( "Following Clips are deleted due to low size (less than 100kb)" ) for deleted_clip in deleted_clips: Logger.debug(deleted_clip) self._update_progress_bar(50) self._update_status("Ready to make video") # merge clips and make video Logger.debug("Entered to merging try block") merge(self.clips_path, self.video_location, self._update_progress) Logger.debug("End of merging try block") # Clearing Temp dir delete_all_clips(self.clips_path) self._update_status( os.path.basename(self.video_location)[:-4] + " is now ready to watch") self._toast("Always use Mx/Vlc Player to watch Videos") except Exception: Logger.exception('Something happened wrong at merge') self._update_status("Something happened wrong at merge") def open_video_folder(self, *args): if platform == 'android': pass pass def open_video(self, *args): if platform == 'android': pass #self._open(self.video_location) def action_button_callback(self, instance): if instance.icon == 'language-python': self.theme_cls.primary_palette = "Green" if instance.icon == 'language-php': self.theme_cls.primary_palette = "Orange" if instance.icon == 'language-cpp': self.theme_cls.primary_palette = "Blue" def _update_progress(self, file_no, file_name, files): percentage = int(file_no * 100 / files) self._update_progress_bar(50 + int(percentage / 2)) progress_text = "Merging Clips " + str(file_no) + "/" + str( files) + " " + str(percentage) + " %" self._update_status(progress_text) Logger.debug(progress_text + " of " + str(file_name)) @mainthread def _update_status(self, text): self.root.ids.status_label.text = str(text) @mainthread def _update_progress_bar(self, value): self.root.ids.prog.value = int(value) def _open(self, video_location): try: from kivy.setupconfig import USE_SDL2 if platform == 'android': from jnius import cast from jnius import autoclass if USE_SDL2: PythonActivity = autoclass( 'org.kivy.android.PythonActivity') else: PythonActivity = autoclass( 'org.renpy.android.PythonActivity') Intent = autoclass('android.content.Intent') String = autoclass('java.lang.String') Uri = autoclass('android.net.Uri') File = autoclass('java.io.File') shareIntent = Intent(Intent.ACTION_SEND) shareIntent.setType('"video/*"') VideoFile = File(video_location) uri = Uri.fromFile(VideoFile) parcelable = cast('android.os.Parcelable', uri) shareIntent.putExtra(Intent.EXTRA_STREAM, parcelable) currentActivity = cast('android.app.Activity', PythonActivity.mActivity) currentActivity.startActivity(shareIntent) except Exception as e: Logger.exception("Unable to share video") def _toast(self, text): try: from jnius import autoclass, cast PythonActivity = autoclass("org.kivy.android.PythonActivity") context = PythonActivity.mActivity AndroidString = autoclass('java.lang.String') Toast = autoclass('android.widget.Toast') duration = Toast.LENGTH_SHORT text_char_sequence = cast('java.lang.CharSequence', AndroidString(text)) toast = Toast.makeText(context, text_char_sequence, duration) toast.show() except Exception as e: Logger.exception(e)
class DemoApp(MDApp): def build(self): self.theme_cls.primary_palette = "Blue" # "BlueGray" self.theme_cls.primary_hue = "500" # "700" self.theme_cls.theme_style = "Light" screen = Builder.load_string(login_helper) self.lusername = Builder.load_string(helpers.lusername_input) self.lpassword = Builder.load_string(helpers.lpassword_input) button = MDRectangleFlatButton(text='Submit', pos_hint={ 'center_x': 0.5, 'center_y': 0.3 }, on_release=self.log_show_data) screen.add_widget(self.lusername) screen.add_widget(self.lpassword) screen.add_widget(button) sm.add_widget(screen) screen = Builder.load_string(signup_helper) self.username = Builder.load_string(helpers.username_input) self.mycontact = Builder.load_string(helpers.mycontact_input) self.email = Builder.load_string(helpers.email_input) self.password = Builder.load_string(helpers.password_input) self.age = Builder.load_string(helpers.age_input) button = MDRectangleFlatButton(text='Submit', pos_hint={ 'center_x': 0.5, 'center_y': 0.2 }, on_release=self.sign_show_data) screen.add_widget(self.username) screen.add_widget(self.mycontact) screen.add_widget(self.email) screen.add_widget(self.password) screen.add_widget(self.age) screen.add_widget(button) sm.add_widget(screen) screen = Builder.load_string(navigation_helper) sm.add_widget(screen) screen = Builder.load_string(screen_helper) self.abusername = Builder.load_string(helpers.abusername_input) self.contact = Builder.load_string(helpers.contact_input) self.reason = Builder.load_string(helpers.reason_input) button = MDRectangleFlatButton(text='Submit', pos_hint={ 'center_x': 0.5, 'center_y': 0.3 }, on_release=self.show_data) screen.add_widget(self.abusername) screen.add_widget(self.contact) screen.add_widget(self.reason) screen.add_widget(button) sm.add_widget(screen) screen = Builder.load_string(newsscraping) self.tap_target_view = MDTapTargetView( widget=screen.ids.button1, title_text="Teens having \nat least 1 social \nmedia profile", description_text=" 75% ", widget_position="center", title_position="right_top", title_text_size="20sp", outer_radius=250, ) sm.add_widget(screen) screen = Builder.load_string(conv_upload) sm.add_widget(screen) screen = Builder.load_string(screen_helper4) sm.add_widget(screen) screen = Builder.load_string(screen_helper5) sm.add_widget(screen) screen = Builder.load_string(screen_helper6) sm.add_widget(screen) return sm 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, ext=[".txt", ".py", "kv"], ) # Sign up validation def sign_show_data(self, obj): if self.username.text != "" and self.mycontact.text != "" and self.email.text != "" and self.password.text != "": if len(self.mycontact.text) == 10 and self.mycontact.text.isdigit( ) and self.age.text.isdigit(): if re.search(regex, self.email.text): if len(self.password.text) >= 8: print("USERNAME- " + self.username.text) print("CONTACT NUMBER- " + self.mycontact.text) print("EMAIL- " + self.email.text) print("PASSWORD- " + self.password.text) print("AGE- " + self.age.text) # self.reason.text, self.contact.text, self.username.text = "" # self.username.text = "" # self.mycontact.text = "" self.email.text = "" # self.age.text = "" user_error = "" else: user_error = "Please enter a valid password" else: user_error = "Please enter a valid email id" else: user_error = "Please enter a valid contact number." else: user_error = "Please enter the required fields" if user_error == "": sm.switch_to(Builder.load_string(navigation_helper)) else: self.dialog = MDDialog(text=user_error, size_hint=(0.8, 1), buttons=[ MDFlatButton( text='Close', on_release=self.close_dialog) ]) self.dialog.open() # Report portal validation def show_data(self, obj): if self.contact.text != "" and self.reason.text != "": if len(self.contact.text) == 10 and self.contact.text.isdigit(): print("ABUSER NAME- " + self.abusername.text) print(self.username.text, self.mycontact.text) print("CONTACT NUMBER- " + self.contact.text) print("REASON- " + self.reason.text) mail.main_func(self.username.text, self.mycontact.text, self.abusername.text, self.contact.text, self.reason.text, "message") self.abusername.text = "" self.contact.text = "" self.reason.text = "" user_error = "Your response has been noted. The immediate responders will contact you soon." else: user_error = "Please enter a valid contact number." else: user_error = "Please enter the required fields" self.dialog = MDDialog( text=user_error, size_hint=(0.8, 1), buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)]) self.dialog.open() def close_dialog(self, obj): self.dialog.dismiss() # do stuff after closing the dialog def info(self): self.dialog = MDDialog( text= 'The information entered below will be forwarded to the respective authorities.', size_hint=(0.8, 1), buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)]) self.dialog.open() # Login validation def log_show_data(self, obj): if self.lusername.text != "" and self.lpassword.text != "": if len(self.lpassword.text) >= 8: sm.switch_to(Builder.load_string(navigation_helper)) else: user_error = "Incorrect password. Please try again" self.dialog = MDDialog(text=user_error, size_hint=(0.8, 1), buttons=[ MDFlatButton( text='Close', on_release=self.close_dialog), ]) self.dialog.open() else: user_error = "Please enter the required details" self.dialog = MDDialog(text=user_error, size_hint=(0.8, 1), buttons=[ MDFlatButton( text='Close', on_release=self.close_dialog), ]) self.dialog.open() def close_dialog1(self, obj): self.dialog.dismiss() # do stuff after closing the dialog def tap_target_start1(self): if self.tap_target_view.state == "close": self.tap_target_view.start() else: self.tap_target_view.stop() def tap_target_start2(self): if self.tap_target_view.state == "close": self.tap_target_view.start() else: self.tap_target_view.stop() def info1(self): self.dialog = MDDialog( text= 'Sentimental Analysis displays the polarity ie. positive, negative and neutral polarity values of the whole conversation', size_hint=(0.9, 0.5), radius=[20, 7, 20, 7], buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)]) self.dialog.open() def info2(self): self.dialog = MDDialog( text= 'Emotional Analysis displays the various emotions and their value of the whole conversation', size_hint=(0.9, 0.5), radius=[20, 7, 20, 7], buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)]) self.dialog.open() def info3(self): self.dialog = MDDialog( text= 'Aspect Based Analysis displays the most talked category of the whole conversation', size_hint=(0.9, 0.5), radius=[20, 7, 20, 7], buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)]) self.dialog.open() def info4(self): self.dialog = MDDialog( text= 'Analysis on emotions and tones of conversations and visualise the results in the form of graphs.', size_hint=(1, 0), radius=[20, 7, 20, 7], buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)]) self.dialog.open() def infolda(self): self.dialog = MDDialog( text= 'Semantic analysis groups words which are used together frequently', size_hint=(0.9, 0.5), radius=[20, 7, 20, 7], buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)]) self.dialog.open() def callback(self, instance): print("Button is pressed") print('The button % s state is <%s>' % (instance, instance.state)) def file_manager_open(self): self.file_manager.show('/') # output manager to the screen self.file_manager.use_access = True self.manager_open = True # Read the conversation and prepare conv_anal screen. Also check for grooming if applicable 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; ''' self.exit_manager() global finalpath punc = '''/~$%^''' # remove '/' from the path for ele in path: if ele in punc: path1 = path.replace(ele, "") # path1 -> '/' symbol removed filepath /Users\Kripa\Desktop\exconvo.txt to Users\Kripa\Desktop\exconvo.txt tmplist = path1.split(os.sep) # splits the path and is put in the list tmplist # Users\Kripa\Desktop\exconvo.txt to ['Users','Kripa','Desktop','exconvo.txt'] finalpath = "" for wrd in tmplist: finalpath = finalpath + r"\\" + wrd finalpath = "C:" + finalpath # print(finalpath) #C:\\Users\Kripa\Desktop\exconvo.txt with open(finalpath, 'r') as in_file: stripped = (line.strip() for line in in_file) lines = (line.split(",") for line in stripped if line) with open('C:\\Users\\Kripa\\Desktop\\convo.csv', 'w', newline='') as out_file: writer = csv.writer(out_file) writer.writerow(('name', 'msg')) writer.writerows(lines) ct = 0 row_ct1 = 0 row_ct2 = 0 strname = "" # Get no.of messages for both users with open("C:\\Users\\Kripa\Desktop\\convo.csv", 'r') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: # lets tokenise if ct == 0 and row[0] != "name": strname = row[0] ct = ct + 1 if row[0] == strname: row_ct1 = row_ct1 + 1 else: row_ct2 = row_ct2 + 1 screen = Builder.load_string(conv_anal) self.tap_target_view = MDTapTargetView( widget=screen.ids.button, title_text="USER 1 USER 2", description_text=" " + str(row_ct1) + " " + str(row_ct2) + " \nMESSAGES MESSAGES", widget_position="center", title_position="right_top", title_text_size="20sp", outer_radius=250, ) sm.add_widget(screen) # GROOMING if int(self.age.text) < 18: with open("C:\\Users\\Kripa\Desktop\\convo.csv") as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') pred_name = "" p_ct = 0 for row in csv_reader: if p_ct == 0 and row[0] != "name" and row[ 0] != self.username.text: pred_name = row[0] p_ct = p_ct + 1 row[1] = row[1].lower() # convert to lowercase lemr = "" for word in row[1].split(): # Lemmatisation lem = (lemmatizer.lemmatize(word, pos="v")) lem = (lemmatizer.lemmatize(lem)) lemr = lemr + lem + " " no_punct = "" for char in lemr: # Remove punctuation if char not in punctuations: no_punct = no_punct + char data = word_tokenize(no_punct) stopWords = set(stopwords.words('english')) wordsFiltered = [] for w in data: # Remove stopwords if w not in stopWords: wordsFiltered.append(w) fp = "C:\\Users\\Kripa\\Desktop\\exconvo2.csv" with open(fp, 'a+', newline='') as out_file: writer = csv.writer(out_file, delimiter=' ') writer.writerow(wordsFiltered[:20]) # liwc def tokenize(text): for match in re.finditer(r'\w+', text, re.UNICODE): yield match.group(0) parse, category_names = liwc.load_token_parser( "C:\\Users\\Kripa\\Desktop\\bigdic.dic") cntt = array('i', [0, 0, 0, 0, 0, 0]) # Stages predator = "C:\\Users\\Kripa\\Desktop\\exconvo2.csv" with open(predator) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') ct = 0 i = 1 j = 0 for row in csv_reader: p = row.copy() p1 = listtostring(p).lower() p_token = tokenize(p1) from collections import Counter op1 = Counter(category for token in p_token for category in parse(token)) op = dict(op1) l = list(op.keys()) l.sort(reverse=True) if l: j = l[0] if j == "S1": cntt[0] = cntt[0] + 1 if j == "S2": cntt[1] = cntt[1] + 1 if j == "S3": cntt[2] = cntt[2] + 1 if j == "S4": cntt[3] = cntt[3] + 1 if j == "S5": cntt[4] = cntt[4] + 1 if j == "S6": cntt[5] = cntt[5] + 1 ''' cntt[0]=807 cntt[1]=396 cntt[2] =87 cntt[3] =79 cntt[4] =38 cntt[5] =226 ''' clf = joblib.load('svm.pkl') op = clf.predict([cntt]) if op == [1]: mail.main_func(self.username.text, self.mycontact.text, pred_name, "", "", "message1") self.dialog = MDDialog( text= "Grooming characteristics detected. Immediate responders have been informed.", size_hint=(0.8, 1), buttons=[ MDFlatButton(text='Close', on_release=self.close_dialog), ]) self.dialog.open() toast(finalpath) # return sm os.remove("C:\\Users\\Kripa\\Desktop\\exconvo2.csv") 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 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 # Aspect analysis def aspect_fn(self): with open("C:\\Users\\Kripa\\Desktop\\convo.csv") as file: data = list(csv.reader(file)) strin = " ".join(str(x) for x in data) natural_language_understanding.set_service_url( 'https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com/instances/c70c1850-5873-495c-b449-d84d30415f06' ) natural_language_understanding.set_disable_ssl_verification(True) response = natural_language_understanding.analyze( text=strin, features=Features( categories=CategoriesOptions(limit=3), )).get_result() cat1 = response['categories'] di1 = cat1[0] di2 = cat1[1] di3 = cat1[2] str1 = di1['label'] str11 = str(di1['score']) str2 = di2['label'] str21 = str(di2['score']) str3 = di3['label'] str31 = str(di3['score']) screen = Builder.load_string(screen_helper3) screen.ids.aspectlist.add_widget( TwoLineListItem(text=str1, secondary_text=str11)) screen.ids.aspectlist.add_widget( TwoLineListItem(text=str2, secondary_text=str21)) screen.ids.aspectlist.add_widget( TwoLineListItem(text=str3, secondary_text=str31)) sm.add_widget(screen) # Sentiment and emotiona enalysis def emo_fn(self): cn = cp = cng = e1 = e2 = e3 = e4 = e5 = 0 with open("C:\\Users\\Kripa\\Desktop\\convo.csv") as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: j = 0 row = listtostring(row) response = natural_language_understanding.analyze( text=row, language='en', features=Features( sentiment=SentimentOptions(), emotion=EmotionOptions(), )).get_result() sen1 = response.get('sentiment').get('document').get('score') sen2 = response.get('sentiment').get('document').get('label') if sen1 == 0: cn += 1 elif sen1 > 0: cp += 1 else: cng += 1 op = response.get('emotion').get('document').get('emotion') # Create a list of tuples sorted by index 1 i.e. value field listofTuples = sorted(op.items(), reverse=True, key=lambda x: x[1]) ll = listofTuples[0] d = dict(listofTuples) for k, v in d.items(): d1 = k d2 = v j += 1 if j > 0: break if d1 == 'sadness': e1 += 1 elif d1 == 'joy': e2 += 1 elif d1 == 'fear': e3 += 1 elif d1 == 'disgust': e4 += 1 else: e5 += 1 s = s1 = 0 s = cn + cng + cp pp = (cp * 100) / s ngp = (cng * 100) / s np = (cn * 100) / s s1 = e1 + e2 + e3 + e4 + e5 e1p = (e1 * 100) / s1 e2p = (e2 * 100) / s1 e3p = (e3 * 100) / s1 e4p = (e4 * 100) / s1 e5p = (e5 * 100) / s1 screen = Builder.load_string(screen_helper1) neutral = "Neutral: " + str(round(np, 2)) pos = "Positive: " + str(round(pp, 2)) neg = "Negative: " + str(round(ngp, 2)) screen.ids.sentimentlist.add_widget(OneLineListItem(text=neutral, )) screen.ids.sentimentlist.add_widget(OneLineListItem(text=pos, )) screen.ids.sentimentlist.add_widget(OneLineListItem(text=neg, )) sm.add_widget(screen) screen = Builder.load_string(screen_helper2) sad = "Sad: " + str(round(e1p, 2)) joy = "Joy: " + str(round(e2p, 2)) fear = "Fear: " + str(round(e3p, 2)) disgust = "Disgust: " + str(round(e4p, 2)) angry = "Angry: " + str(round(e5p, 2)) screen.ids.emotionallist.add_widget(OneLineListItem(text=sad, )) screen.ids.emotionallist.add_widget(OneLineListItem(text=joy, )) screen.ids.emotionallist.add_widget(OneLineListItem(text=fear, )) screen.ids.emotionallist.add_widget(OneLineListItem(text=disgust, )) screen.ids.emotionallist.add_widget(OneLineListItem(text=angry, )) sm.add_widget(screen) # Semantic analysis def lda_fn(self): screen = Builder.load_string(screen_helperlda) with open("C:\\Users\\Kripa\Desktop\\convo.csv", 'r') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: # lets tokenise raw = row[1] tokens = tokenizer.tokenize(raw) # remove stopwords stopped_tokens = [i for i in tokens if not i in en_stop] tagged = nltk.pos_tag(stopped_tokens) for word, tag in tagged: w_tag = get_wordnet_pos(tag) if w_tag is None: lemmatized_tokens = [lemmatizer.lemmatize(word)] else: lemmatized_tokens = [ lemmatizer.lemmatize(word, pos=w_tag) ] texts.append(lemmatized_tokens) # create_dict id2word = corpora.Dictionary(texts) # convert to document-term matrix corpus = [id2word.doc2bow(text) for text in texts] # generate lda lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus, id2word=id2word, num_topics=5, passes=20) # print(lda_model.print_topics(num_topics=5)) top_words_per_topic = [] # puting ouput to a csv file! for t in range(lda_model.num_topics): top_words_per_topic.extend([(t, ) + x for x in lda_model.show_topic(t)]) x = pd.DataFrame(top_words_per_topic, columns=['Tno', 'Word', 'P']) # .to_csv('C:\\Users\\Kripa\Desktop\\top_words.csv') y = x['Word'] name1 = [] for ele in y: name1.append(ele) screen.ids.ldalist.add_widget( ThreeLineListItem(text="Group 1", secondary_text=name1[0] + "," + name1[1] + "," + name1[2] + "," + name1[3] + "," + name1[4] + ",", tertiary_text=name1[5] + "," + name1[6] + "," + name1[7] + "," + name1[8] + "," + name1[9])) screen.ids.ldalist.add_widget( ThreeLineListItem( text="Group 2", secondary_text=name1[10] + "," + name1[11] + "," + name1[12] + "," + name1[13] + "," + name1[14] + ",", tertiary_text=name1[15] + "," + name1[16] + "," + name1[17] + "," + name1[18] + "," + name1[19])) screen.ids.ldalist.add_widget( ThreeLineListItem( text="Group 3", secondary_text=name1[20] + "," + name1[21] + "," + name1[22] + "," + name1[23] + "," + name1[24] + ",", tertiary_text=name1[25] + "," + name1[26] + "," + name1[27] + "," + name1[28] + "," + name1[29])) sm.add_widget(screen)
class DownloaderScreen(Screen): text = StringProperty("") text2 = StringProperty("") text3 = StringProperty("") text4 = StringProperty("") text5 = StringProperty("Choose your video/song's format type") hint_text = "File Path" error = False downloadChoices = "" menu = "" 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, ) def file_manager_open(self): self.file_manager.show('/') # output manager to the screen 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; ''' self.exit_manager() self.ids.FilePathTextField.text = os.path.abspath(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 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 button_press(self): self.manager.transition = FadeTransition(duration=1.2) self.manager.current = "downloading" t = Thread(target=self.download) t.daemon = True t.start() def download(self): self.song_name = self.ids.SongName.text args = { "no_encode": False, } spotdl_handler = Spotdl(args) spotdl_handler.download_track(self.song_name) self.manager.transition = FadeTransition(duration=1.2) self.manager.current = "Downloader" toast("Download complete") def change_file_path(self): self.file_path = self.ids.FilePathTextField.text os.chdir(self.file_path)
class main(MDApp): spin_active = BooleanProperty(False) storage_url = "https://farmzon-abdcb.appspot.com" database_url = "https://farmzon-abdcb.firebaseio.com/.json" data = {"uu": {"Joe Tilsed": "me"}} auth_key = "sBlt6fzvguYnrGl2FlXRK3k4vRxSfZJBV2P7yIRv" # Clock.max_iteration = 20 size_x = NumericProperty(0) size_y = NumericProperty(0) count = 11 count_screen = NumericProperty(0) dialog = None # XXX-------USER LOGIN VAR-------XXX user_name = StringProperty("") user_phone = StringProperty("") user_password = StringProperty("") user_city = StringProperty("") user_email = StringProperty("") user_address = StringProperty("") user_location = StringProperty("") user_image = StringProperty("") user_products = StringProperty("") user_followers = StringProperty("") user_purchased = StringProperty("") user_latitude = StringProperty("") user_longitude = StringProperty("") user_true = BooleanProperty(False) # XXX-------ADMIN LOGIN VAR-------XXX admin_name = StringProperty("") admin_phone = StringProperty("") admin_password = StringProperty("") admin_city = StringProperty("") admin_email = StringProperty("") admin_address = StringProperty("") admin_image = StringProperty("") admin_products = StringProperty("") admin_followers = StringProperty("") admin_purchased = StringProperty("") admin_true = BooleanProperty(False) # XXX-------USER REGISTER VAR-------XXX admin_r_name = StringProperty("") admin_r_phone = StringProperty("") admin_r_password = StringProperty("") admin_r_city = StringProperty("") admin_r_email = StringProperty("") admin_r_address = StringProperty("") type_business = StringProperty("company") # XXX-------USER REGISTER VAR-------XXX user_r_name = StringProperty("") user_r_phone = StringProperty("") user_r_password = StringProperty("") user_r_city = StringProperty("") user_r_email = StringProperty("") user_r_address = StringProperty("") # XXX-------CATEGORIES VAR----------XXX real_source = StringProperty("") label_name = StringProperty("") food_count = NumericProperty(0) fruit_count = NumericProperty(0) herbs_count = NumericProperty(0) # XXX------PRODUCT VAR-------XXX products_id = StringProperty("") product_image = StringProperty("") product_name = StringProperty("") product_max_price = StringProperty("") product_min_price = StringProperty("") product_full_sack = NumericProperty(0) product_half_sack = NumericProperty(0) product_date = StringProperty("") product_month = StringProperty("") product_year = StringProperty("") product_time = StringProperty("") product_state = StringProperty("") screen_name = [] # XXX------FRIENDLY FUNCTIONS------XXX def __init__(self, **kwargs): super().__init__() self.file_manager = MDFileManager() self.file_manager.exit_manager = self.exit_manager self.file_manager.select_path = self.select_path self.file_manager.preview = True self.file_manager.previous = True # self.file_manager.search = "files" def remember_me(self, user, password, name, image): with open("login.txt", "w") as fl: fl.write(user + "\n") fl.write(password) with open("user_info.txt", "w") as ui: ui.write(image + "\n") ui.write(name) fl.close() ui.close() def remember_me_admin(self, user, password, name, image): with open("admin.txt", "w") as fl: fl.write(user + "\n") fl.write(password) with open("admin_info.txt", "w") as ui: ui.write(image + "\n") ui.write(name) fl.close() ui.close() def Permission(self, android=None): if platform == 'android': from android.permissions import request_permissions, Permission # todo request_permissions([Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE]) # todo self.file_manager_open() # todo def check(self): te = self.root.ids.user_phone tex = te.text te.helper_text_mode = "on_focus" te.helper_text = "remain" + " " + str(self.count) self.count = tex.__len__() self.count = 10 - self.count if tex.__len__() < 10 or tex.__len__() > 10: te.icon_right = "alpha-x" te.icon_right_color = 1, 0, 0, 1 elif tex.__len__() == 10: te.icon_right = "check" te.icon_right_color = 0, 1, 0, 1 te.helper_text = "correct" def phone_number(self, phone): new_number = "" for i in range(phone.__len__()): if i == 0: pass else: new_number = new_number + phone[i] number = "+255" + new_number if not carrier._is_mobile(number_type(phonenumbers.parse(number))): toast("wrong number") te = self.root.ids.user_phone te.text = "start with 07 or 06" return False else: return True def dark(self): self.theme_cls.theme_style = "Dark" def light(self): self.theme_cls.theme_style = "Light" def actively(self): if self.spin_active: self.spin_active = False def actively_reg(self): sm = self.root if self.spin_active: self.spin_active = False sm.current = "login screen" toast("Succefull Registerd!") def on_start(self): # screen manager sm = self.root sm.transition = SM.FadeTransition(duration=.2) EventLoop.window.bind(on_keyboard=self.hook_keyboard) self.user_memory() self.fps_monitor_start() def user_memory(self): file_size = os.path.getsize("login.txt") if file_size == 0: pass else: sm = self.root self.user_true = True file1 = open('login.txt', 'r') file2 = open("user_info.txt") Lines = file1.readlines() Lines2 = file2.readlines() count = 0 # Strips the newline character self.user_phone = Lines[0].strip() self.user_password = Lines[1].strip() self.user_name = Lines2[1] self.user_image = "alpha-" + self.user_name[0].lower() self.Signing_in(self.user_phone, self.user_password) sm.current = "main" def admin_memory(self): file_size = os.path.getsize("admin.txt") if file_size == 0: sm = self.root sm.current = "login_screen_admin" self.count_screen += 1 else: sm = self.root self.admin_true = True file1 = open('admin.txt', 'r') file2 = open("admin_info.txt") Lines = file1.readlines() Lines2 = file2.readlines() count = 0 # Strips the newline character self.admin_phone = Lines[0].strip() self.admin_password = Lines[1].strip() self.admin_name = Lines2[1] self.admin_image = Lines2[0] self.Signing_in_admin(self.admin_phone, self.admin_password) sm.current = "admin_main" self.count_screen += 1 def show_alert_dialog(self): if not self.dialog: self.dialog = MDDialog( text="Do you real want to quit?", buttons=[ MDFlatButton( text="CANCEL", text_color=self.theme_cls.primary_color, on_release=self.kill ), MDRaisedButton( text="QUIT!", text_color=self.theme_cls.primary_color, on_release=quit ), ], ) self.dialog.open() def kill(self, *kwargs): self.dialog.dismiss() def hook_keyboard(self, window, key, *largs): count = self.screen_name.__len__() - 1 sm = self.root if key == 27 and self.count_screen == 0: self.show_alert_dialog() return True elif key == 27 and self.count_screen > 0: sm.current = "main" self.count_screen -= 1 return True def resize_bottom_tabs(self): # bottom_nav bv = self.root.ids.bottom_nav bv.on_resize() def screen_collector(self, name): self.screen_name.append(name) return self.screen_name.__len__() def Screen_changer(self, screen_name): sm = self.root sm.current = screen_name # XXX-------PROFILE VALIDATIONS FUNCTIONS------XXX def validate_user(self, phone, password): if phone == "": toast("please enter your phone number correctly") elif password == "": toast("please enter your password") else: self.spin_active = True self.Signing_in(phone, password) def Signing_in(self, phone, password): thread = threading.Thread(target=self.Signing_in_function, args=(phone, password,)) thread.start() def Signing_in_function(self, phone, password): if phone != "" and password != "": if UI.Signing_in(UI(), phone, password): sm = self.root # image = self.root.ids.user_image # taken from database self.user_name = UI.name self.user_image = "alpha-" + self.user_name[0].lower() self.remember_me(phone, password, self.user_name, UI.image) # image.source = UI.image # Clock.schedule_interval(lambda x: self.image_loader_user(UI.image), 1) self.user_purchased = UI.purchased self.user_products = UI.product self.user_followers = UI.follower if not self.user_true: sm.current = "main" self.screen_collector("main") self.spin_active = False else: toast("oop! phone number or password in correct or " "check your internet connection", 5) self.spin_active = False def image_loader_user(self, y): image = self.root.ids.drawer_logo Cache.remove(image.texture) image.source = y image.reload() def validate_registration1(self, name, phone, password, city, email, address): self.spin_active = True Clock.schedule_once(lambda x: self.validate_registration(name, phone, password, city, email, address), 2) def validate_registration(self, name, phone, password, city, email, address): if city != " " and address != " " and city.isalpha() and address.isalpha(): if self.phone_number(phone): self.user_location = address + "/" + city sm = self.root if LA.Generate_address(LA(), self.user_location): self.user_location = str(LA.location2) self.user_latitude = str(LA.latitude) self.user_longitude = str(LA.longitude) if name != "" and phone != "" and phone.__len__() == 10 and password != "" and city != "" and address != "" and email != "" and email.count( "@") == 1 and email.count(".") > 0: self.spin_active = True self.register(name, phone, password, city, address, email, self.user_location, self.user_latitude, self.user_longitude) else: toast("something is wrong") self.spin_active = False else: toast("your address is not available") self.spin_active = False city = self.root.ids.user_city district = self.root.ids.user_address city.text = " " district.text = " " else: toast("check your phone number") self.spin_active = False else: toast("your city, address and phone number invalid", 3) self.spin_active = False city = self.root.ids.user_city district = self.root.ids.user_address city.text = " " district.text = " " def register(self, name, phone, password, city, address, email, location, latitude, longitude): thread = threading.Thread(target=UI.upload_data_user, args=( UI(), name, phone, password, city, address, email, location, latitude, longitude)) thread.start() thread.join() self.actively_reg() def register_user(self): sm = self.root sm.current = "register screen" self.screen_collector("register screen") # XXX-------ADMIN FUNCTIONS------XXX def validate_admin(self, phone, password): if phone == "" and phone.Isdigit(): toast("please enter your phone number correctly") elif password == "": toast("please enter your password") else: self.spin_active = True thread = threading.Thread(target=self.Signing_in_admin_function, args=(phone, password)) thread.start() def Signing_in_admin(self, phone, password): thread = threading.Thread(target=self.Signing_in_admin_function, args=(phone, password,)) thread.start() def Signing_in_admin_function(self, phone, password): if UI.Signing_in_admin(UI(), phone, password): sm = self.root image = self.root.ids.admin_image self.admin_name = UI.name_admin self.admin_image = UI.image_admin image.source = UI.image_admin Clock.schedule_interval(lambda x: self.image_loder_admin(UI.image_admin), 0.1) self.admin_purchased = UI.purchased_admin self.admin_products = UI.product_admin self.admin_followers = UI.follower_admin self.remember_me_admin(phone, password, self.admin_name, self.admin_image) if not self.admin_true: sm.current = "admin_main" else: self.spin_active = False toast("oops! phone number or password in correct") def image_loder_admin(self, x): image = self.root.ids.admin_image image.source = x def validate_registration_admin(self, name, phone, password, city, email, address): if name != "" and phone != "" and password != "" and city != "" and address != "" and email != "" and email.count( "@") == 1 and email.count(".") > 0: self.spin_active = True thread = threading.Thread(target=self.admin_register, args=(name, phone, password, city, address, email, self.type_business)) thread.start() else: toast("something is wrong!") def admin_register(self, name, phone, password, city, address, email, business): thread = threading.Thread(target=UI.upload_data_admin, args=(UI(), name, phone, password, city, address, email, self.type_business)) thread.start() thread.join() toast("registered") self.spin_active = False self.Screen_changer("login_screen_admin") def catergory_food_spinner1(self): self.spin_active = True Clock.schedule_once(lambda x: self.add_image_food("food", "categories_food"), 2) def add_image_food(self, cat, screen): from connection_status import connect if self.food_count == 0: self.food_count = self.food_count + 1 if connect(): food = self.root.ids.food_cat from firebase_admin import credentials, initialize_app, db cred = credentials.Certificate("farmzon-abdcb-c4c57249e43b.json") default_app = initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}, name="food") store = db.reference("Categories_url", default_app).child(cat) stores = store.get() for y, x in stores.items(): self.real_source = x["url"] food_categories = category() food_categories.add_widget(Labels(text=y)) food_categories.add_widget(MDSeparator(height="1dp")) food_categories.add_widget(cat_image(source=self.real_source)) food.add_widget(food_categories) sm = self.root sm.current = screen else: sm = self.root sm.current = screen def catergory_fruit_spinner2(self): self.spin_active = True Clock.schedule_once(lambda x: self.add_image_fruit("fruit", "categories_fruit"), 2) def add_image_fruit(self, cat, screen): from connection_status import connect if self.fruit_count == 0: self.fruit_count = self.fruit_count + 1 if connect(): food = self.root.ids.fruit_cat from firebase_admin import credentials, initialize_app, db cred = credentials.Certificate("farmzon-abdcb-c4c57249e43b.json") default_app = initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}, name="fruit") store = db.reference("Categories_url", default_app).child(cat) stores = store.get() for y, x in stores.items(): self.real_source = x["url"] food_categories = category() food_categories.add_widget(Labels(text=y)) food_categories.add_widget(MDSeparator(height="1dp")) food_categories.add_widget(cat_image(source=self.real_source)) food.add_widget(food_categories) sm = self.root sm.current = screen elif self.fruit_count != 0: sm = self.root sm.current = screen def catergory_herbs_spinner3(self): self.spin_active = True Clock.schedule_once(lambda x: self.add_image_herbs("herbs", "categories_herbs"), 2) def add_image_herbs(self, cat, screen): from connection_status import connect if self.herbs_count == 0: self.herbs_count = self.herbs_count + 1 if connect(): food = self.root.ids.herb_cat from firebase_admin import credentials, initialize_app, db cred = credentials.Certificate("farmzon-abdcb-c4c57249e43b.json") default_app = initialize_app(cred, {'databaseURL': 'https://farmzon-abdcb.firebaseio.com/'}, name="herbs") store = db.reference("Categories_url", default_app).child(cat) stores = store.get() for y, x in stores.items(): self.real_source = x["url"] food_categories = category() food_categories.add_widget(Labels(text=y)) food_categories.add_widget(MDSeparator(height="1dp")) food_categories.add_widget(cat_image(source=self.real_source)) food.add_widget(food_categories) sm = self.root sm.current = screen else: sm = self.root sm.current = screen def type_active(self, checkbox, value): if value: self.type_business = "company" toast(self.type_business) else: self.type_business = "individual" toast(self.type_business) # XXX------- PRODUCTS_FUNCTION---------XXX def Product_validation(self, name, max, min, date, month, year, description): if name != "" and max != "" and min != "" and date != "" and month != "" and year != "" and description != "": self.product_name = name self.product_date = date self.product_year = year self.product_month = month self.product_max_price = max self.product_min_price = min self.products_id = datetime.now() # XXX-------FILE_MANAGER------XXX def file_manager_open(self): from android.storage import primary_external_storage_path # todo primary_ext_storage = primary_external_storage_path() # todo self.file_manager.show("/") # todo self.file_manager.show(primary_ext_storage) # output manager to the screen 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; """ self.exit_manager() toast(path) if path.lower().endswith(('.png', '.jpg', '.jpeg')): toast("correct format") image = self.root.ids.product_image image.source = path self.product_image = path else: toast("Wrong format") 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 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 build(self): self.theme_cls.theme_style = "Light" self.theme_cls.primary_palette = "Brown" self.theme_cls.accent = "Brown" # Window.size = (360, 640) print(plyer.uniqueid.id) self.size_x, self.size_y = Window.size self.title = "farmzon"
class KitchenSink(App, Screens): #variables globarl db = DataBase() theme_cls = ThemeManager() theme_cls.primary_palette = "Indigo" theme_cls.accent_palette = "Gray" previous_date = ObjectProperty() title = "GiftCard" def __init__(self, **kwargs): super().__init__(**kwargs) self.menu_items = [{ "viewclass": "MDMenuItem", "text": "Example item %d" % i, "callback": self.callback_for_menu_items, } for i in range(15)] self.Window = Window #examen articulos self.articulosCarrito = [] #region variables globales login self.loginEmail = None self.loginPwd = None # Default class instances. self.manager = None self.md_app_bar = None self.instance_menu_demo_apps = None self.instance_menu_source_code = None self.md_theme_picker = None self.long_dialog = None self.input_dialog = None self.alert_dialog = None self.ok_cancel_dialog = None self.long_dialog = None self.dialog = None self.user_card = None self.bs_menu_1 = None self.bs_menu_2 = None self.popup_screen = None self.my_snackbar = None self.dialog_load_kv_files = None self.create_stack_floating_buttons = False self.manager_open = False self.cards_created = False self._interval = 0 self.tick = 0 self.x = 0 self.y = 25 self.file_source_code = "" self.hex_primary_color = get_hex_from_color( self.theme_cls.primary_color) self.previous_text = ( f"Welcome to the application [b][color={self.hex_primary_color}]" f"GiftCard[/color][/b].\n by [b]" f"[color={self.hex_primary_color}]KivyMD[/color][/b] ") self.previous_text_end = ( f"this is a modific design to practical use\n\n" f"Author - [b][color={self.hex_primary_color}]" f"Roberto Lorenzo Aguilar Maldonado[/color][/b]\n") self.demo_apps_list = ["Shop Window"] self.list_name_icons = list(md_icons.keys())[0:15] Window.bind(on_keyboard=self.events) def build_tabs(self): for name_tab in self.list_name_icons: tab = Factory.MyTab(text=name_tab) self.data["Tabs"]["object"].ids.android_tabs.add_widget(tab) """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 callback_for_menu_items(self, *args): toast(args[0]) """Adds MDCardPost objects to the screen Cards when the screen is open.""" from kivymd.uix.card import MDCardPost def callback(instance, value): if value is None: toast("Delete post %s" % str(instance)) elif isinstance(value, int): toast("Set like in %d stars" % value) elif isinstance(value, str): toast("Repost with %s " % value) elif isinstance(value, list): toast(value[1]) if not self.cards_created: self.cards_created = True menu_items = [{ "viewclass": "MDMenuItem", "text": "Example item %d" % i, "callback": self.callback_for_menu_items, } for i in range(2)] buttons = ["facebook", "vk", "twitter"] instance_grid_card.add_widget( MDCardPost(text_post="Card with text", swipe=True, callback=callback)) instance_grid_card.add_widget( MDCardPost( right_menu=menu_items, swipe=True, text_post="Card with a button to open the menu MDDropDown", callback=callback, )) instance_grid_card.add_widget( MDCardPost( likes_stars=True, callback=callback, swipe=True, text_post="Card with asterisks for voting.", )) image_for_card = ( f"{demos_assets_path}kitten-for_card-1049129_1280-crop.png") if not os.path.exists(image_for_card): crop_image( (int(Window.width), int(dp(200))), f"{demos_assets_path}kitten-1049129_1280.png", image_for_card, ) instance_grid_card.add_widget( MDCardPost( source=image_for_card, tile_text="Little Baby", tile_font_style="H5", text_post="This is my favorite cat. He's only six months " "old. He loves milk and steals sausages :) " "And he likes to play in the garden.", with_image=True, swipe=True, callback=callback, buttons=buttons, )) """Set new label on the screen UpdateSpinner.""" def update_screen(interval): self.tick += 1 if self.tick > 2: instance.update = True self.tick = 0 self.data["Update Screen Widget"][ "object"].ids.upd_lbl.text = "New string" Clock.unschedule(update_screen) Clock.schedule_interval(update_screen, 1) main_widget = None def build(self): self.main_widget = Builder.load_string(main_widget_kv) return self.main_widget """Builds a list of icons for the screen MDIcons.""" def add_icon_item(name_icon): self.main_widget.ids.scr_mngr.get_screen( "md icons").ids.rv.data.append({ "viewclass": "MDIconItemForMdIconsList", "icon": name_icon, "text": name_icon, "callback": self.callback_for_menu_items, }) self.main_widget.ids.scr_mngr.get_screen("md icons").ids.rv.data = [] for name_icon in md_icons.keys(): if search: if text in name_icon: add_icon_item(name_icon) else: add_icon_item(name_icon) """Assigns the file_source_code attribute the file name with example code for the current screen.""" if self.main_widget.ids.scr_mngr.current == "code viewer": return has_screen = False if not has_screen: self.file_source_code = None def callback_context_menu(icon): context_menu.dismiss() if not self.file_source_code: from kivymd.uix.snackbar import Snackbar Snackbar(text="No source code for this example").show() return if icon == "source-repository": if platform in ("win", "linux", "macosx"): webbrowser.open( f"https://github.com/HeaTTheatR/KivyMD/wiki/" f"{os.path.splitext(self.file_source_code)[0]}") return elif icon == "language-python": self.main_widget.ids.scr_mngr.current = "code viewer" if self.file_source_code: with open( f"{self.directory}/KivyMD.wiki/{self.file_source_code}" ) as source_code: self.data["Source code"][ "object"].ids.code_input.text = source_code.read() menu_for_context_menu_source_code = [] data = { "Source code": "language-python", "Open in Wiki": "source-repository", } if self.main_widget.ids.scr_mngr.current == "code viewer": data = {"Open in Wiki": "source-repository"} for name_item in data.keys(): menu_for_context_menu_source_code.append({ "viewclass": "MDIconItemForMdIconsList", "text": name_item, "icon": data[name_item], "text_color": [1, 1, 1, 1], "callback": lambda x=name_item: callback_context_menu(x), }) context_menu = MDDropdownMenu( items=menu_for_context_menu_source_code, max_height=dp(260), width_mult=3, ) context_menu.open(instance.ids.right_actions.children[0]) #1 def open_menu_for_demo_apps(self, instance): """ Called when you click the "Click me" button on the start screen. Creates and opens a list of demo applications. :type instance: <kivymd.uix.button.MDRaisedButton object> """ if not self.instance_menu_demo_apps: self.show_demo_apps('Shop Window') def show_demo_apps(self, name_item): self.show_screens_demo(name_item) self.main_widget.ids.scr_mngr.current = name_item.lower() # self.instance_menu_demo_apps.dismiss() def on_pause(self): return True def on_start(self): def _load_kv_for_demo(name_screen): from demo_apps.shopwindow import ShopWindow Builder.load_string(self.data_for_demo[name_screen]["kv_string"]) self.data_for_demo[name_screen]["object"] = eval( self.data_for_demo[name_screen]["class"]) self.main_widget.ids.scr_mngr.add_widget( self.data_for_demo[name_screen]["object"]) async def load_all_kv_files(): from demo_apps.shopwindow import screen_shop_window data = {"Shop Window": screen_shop_window} for name_screen in data.keys(): await asynckivy.sleep(0) self.dialog_load_kv_files.name_kv_file = name_screen self.data_for_demo[name_screen]["kv_string"] = data[ name_screen] _load_kv_for_demo(name_screen) self.dialog_load_kv_files.dismiss() self.dialog_load_kv_files = DialogLoadKvFiles() self.dialog_load_kv_files.open() asynckivy.start(load_all_kv_files()) def on_stop(self): pass def open_settings(self, *args): return False #region funcionalidad general #configuracion de compra 10/03/20 def make_purchase(self): idUsuario = self.idUsuarioSesion if (idUsuario != 0 and idUsuario != "" and idUsuario != None): self.db.emptyCard(idUsuario) self.carritoComprasActual() toast('Successful purchase') else: toast('Please request access') pass #file open path manager_open = False manager = None def file_manager_open(self): if not self.manager: self.manager = ModalView(size_hint=(1, 1), auto_dismiss=False) self.file_manager = MDFileManager(exit_manager=self.exit_manager, select_path=self.select_path) # self.file_manager.current_path = self.directory# 12/03/20 se asocia el path de la app self.manager.add_widget(self.file_manager) self.file_manager.show( f"{demos_assets_path}") # output manager to the screen self.manager_open = True self.manager.open() pathProduct = None 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; ''' self.pathProduct = path.replace('/', '') self.exit_manager() toast(self.pathProduct) def exit_manager(self, *args): '''Called when the user reaches the root of the directory tree.''' self.manager.dismiss() self.manager_open = False 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 #end region file tipoUsuarioSesion = None idUsuarioSesion = None def login(self): self.loginEmail = loginEmail = App.get_running_app( ).main_widget.ids.scr_mngr.get_screen( "shop window").ids["menulogin"].ids["txtlogin"].text self.loginPwd = loginPwd = App.get_running_app( ).main_widget.ids.scr_mngr.get_screen( "shop window").ids["menulogin"].ids["txtpwd"].text if loginEmail != "" and loginEmail != "" and loginEmail.count( "@") == 1 and loginEmail.count(".") > 0: if self.loginPwd != "": if self.db.validate(loginEmail, loginPwd): self.tipoUsuarioSesion = self.db.validate( loginEmail, loginPwd)[0] self.idUsuarioSesion = self.db.validate( loginEmail, loginPwd)[1] if self.tipoUsuarioSesion == "admin": App.get_running_app( ).main_widget.ids.scr_mngr.get_screen( "shop window" ).ids.adminuser_screen.disabled = False App.get_running_app( ).main_widget.ids.scr_mngr.get_screen( "shop window" ).ids.adminproduct_screen.disabled = False self.pop = Popup( title="Welcome " + self.tipoUsuarioSesion, content=Label(text='user Admin privileges.'), size_hint=(None, None), size=(400, 300)) self.pop.open() else: self.disabledPriv() self.carritoComprasActual() self.pop = Popup( title="Welcome " + self.tipoUsuarioSesion, content=Label(text='user normal privileges.'), size_hint=(None, None), size=(400, 300)) self.pop.open() else: self.invalidLogin() # self.db.add_user(loginEmail,loginPwd,'nuevo') else: self.invalidForm() else: self.invalidForm() pass #carrito de compras del usuario logueado def carritoComprasActual(self): contadorTotal = 0 carritoProducto = self.db.getGiftCat(self.idUsuarioSesion) lonActualCarrito = len( App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.cart_screen.ids.rv_cart.data) for i in range(lonActualCarrito): App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.cart_screen.ids.rv_cart.data.pop() for i, val in enumerate(carritoProducto): var = App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.cart_screen.ids.rv_cart.data.append({ "viewclass": "CardItemForCart", "height": dp(150), "product_image": val.product.img, "txtCabecera": val.product.name, "description": val.product.description, "idProd": str(val.id), 'price': str(val.product.price) # "id": val.id }) contadorTotal = contadorTotal + val.product.price var = App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.cart_screen.ids["totalCompra"].text = str( contadorTotal) pass def disabledPriv(self): App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.adminuser_screen.disabled = True App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.adminproduct_screen.disabled = True def loginOut(self): self.tipoUsuarioSesion = None self.disabledPriv() self.reset() pass def reset(self): App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids["menulogin"].ids["txtpwd"].text = "" App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids["menulogin"].ids["txtlogin"].text = "" self.idUsuarioSesion = 0 self.carritoComprasActual() def invalidLogin(self): pop = Popup(title='Login Invalido', content=Label(text='Usuario o password Invalido.'), size_hint=(None, None), size=(400, 400)) pop.open() def invalidForm(self): pop = Popup( title='Invalid Form', content=Label( text='Please fill in all inputs with valid information.'), size_hint=(None, None), size=(400, 400)) pop.open() #agregar producto a la sesta #bandera def get_card(self, instance): #uid idProd = instance.idProd1 idusuario = self.idUsuarioSesion #usuario en sesion #no regitrado solo agregar pero no comprar #validacion segun el color del corazon quitar o no if idusuario != None and idusuario != 0 and idusuario != "": self.db.AgregarCarrito(idusuario, idProd) self.carritoComprasActual() else: # print('agregado virtual') product = self.db.getProductbyId(idProd) App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.cart_screen.ids.rv_cart.data.append({ "viewclass": "CardItemForCart", "height": dp(150), "product_image": product.img, "txtCabecera": product.name, "description": product.description, "idProd": str(product.id), 'price': str(product.price) # "id": val.id }) toast('Added to cart') pass long_dialog = None idProdQv = None def getViewProduct(self, instance): #uid idProd = instance.idProd1 queryProduct = self.db.getProductbyId(idProd) category = queryProduct.category description = queryProduct.description img = queryProduct.img name = queryProduct.name price = str(queryProduct.price) long_dialog = None # if not self.long_dialog: from kivymd.uix.dialog import MDDialog self.long_dialog = MDDialog( text="descripcion: " + description + "\ncategoria: \n" + category + "\nprice :\n" + price, title=name, size_hint=(0.8, 0.4), text_button_ok="Add To Card", events_callback=self.compraProducto, ) self.idProdQv = idProd # else: # self.long_dialog.text= "descripcion: "+ description + "categoria: " + "price :" + price # self.long_dialog.title= name self.long_dialog.open() pass def saveUser(self, instance): tipo = instance if tipo == '': tipo = 'admin' usrEmail = App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminuser_screen"].ids["emailUsr"].text usrPwd = loginPwd = App.get_running_app( ).main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminuser_screen"].ids["pwdUsr"].text newuser = User(type=tipo, email=usrEmail, password=usrPwd) self.db.saveUsr(newuser) App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminuser_screen"].ids["emailUsr"].text = "" App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminuser_screen"].ids["pwdUsr"].text = "" self.set_list_product() self.db.load() toast('Save in Database, restart app') pass def compraProducto(self, *args): idProd = self.idProdQv idusuario = self.idUsuarioSesion #usuario en sesion #no regitrado solo agregar pero no comprar #validacion segun el color del corazon quitar o no if idusuario != None and idusuario != 0 and idusuario != "": self.db.AgregarCarrito(idusuario, idProd) self.carritoComprasActual() else: # print('agregado virtual') product = self.db.getProductbyId(idProd) App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.cart_screen.ids.rv_cart.data.append({ "viewclass": "CardItemForCart", "height": dp(150), "product_image": product.img, "txtCabecera": product.name, "description": product.description, "idProd": str(product.id), 'price': str(product.price) # "id": val.id }) toast('Added to cart') # if instance.icon == "heart-outline": # self.articulosCarrito.append(instance.uid)instance.uid) # agregamos articulos al carrito # else: # self.articulosCarrito.remove(instance.uid) # agregamos articulos al carrito def get_cardDelete(self, instance): idProd = instance.idProd if self.db.deleteGiftCard(idProd): self.carritoComprasActual() pass #delete product def guardarProduct(self, instance): if self.pathProduct == None: toast('Path Image Required') else: name = App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminproduct_screen"].ids["nameProd"].text #actualizar si trae idprod idProdEdit = App.get_running_app( ).main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminproduct_screen"].idProd val = App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminproduct_screen"].ids category = App.get_running_app( ).main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminproduct_screen"].ids["catProd"].text description = App.get_running_app( ).main_widget.ids.scr_mngr.get_screen("shop window").ids[ "adminproduct_screen"].ids["descripProd"].text price = App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminproduct_screen"].ids["priceProd"].text newproduct = Product(name=name, description=description, img=self.pathProduct, category=category, price=price) self.db.saveProduct(newproduct, idProdEdit) self.clearEdit(self) self.set_list_product() self.SearchProduct('', self.filterByPage, self.contadorPag) def clearEdit(self, instance): idProdEdit = App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminproduct_screen"].idProd = "0" # self.carritoComprasActual() self.pathProduct = None App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminproduct_screen"].ids["nameProd"].text = "" App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminproduct_screen"].ids["catProd"].text = "" App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window" ).ids["adminproduct_screen"].ids["descripProd"].text = "" App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window" ).ids["adminproduct_screen"].ids["priceProd"].text = "" App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminproduct_screen"].ids["imgProd"].text = "" def getProduct(self, instance): #setear valores idEdit = instance.idProducto queryProduct = self.db.getProductbyId(idEdit) category = queryProduct.category description = queryProduct.description img = queryProduct.img name = queryProduct.name price = queryProduct.price edit = App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminproduct_screen"].idProd = idEdit App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window" ).ids["adminproduct_screen"].ids["nameProd"].text = name App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window" ).ids["adminproduct_screen"].ids["catProd"].text = category App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window" ).ids["adminproduct_screen"].ids["descripProd"].text = description App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window" ).ids["adminproduct_screen"].ids["priceProd"].text = str(price) App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids["adminproduct_screen"].ids["imgProd"].text = img valores = App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids #MDLabel def get_cardDeleteProduct(self, instance): idDelete = instance.idProducto self.db.deleteProduct(idDelete) self.set_list_product() #actualiza la tabla gestor producto def set_list_product(self): valor = len(App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.adminproduct_screen.ids.rv_product.data) for i in range(valor): App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.adminproduct_screen.ids.rv_product.data.pop( ) for i, val in enumerate(self.db.getProducts()): App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window" ).ids.adminproduct_screen.ids.rv_product.data.append({ "viewclass": "CardItemForCartAdmin", "height": dp(150), "product_image": val.img, "id": str(val.id), "idProducto": str(val.id), "txtCabecera": val.name, "description": val.description, "price": str(val.price) }) def incrementContadorPag(self): if self.filterByPage == 0: self.filterByPage = 2 self.contadorPag = (self.contadorPag + 1) self.SearchProduct('', self.filterByPage, self.contadorPag) def decrementContadorPag(self): if self.filterByPage == 0: self.filterByPage = 2 self.contadorPag = (self.contadorPag - 1) self.SearchProduct('', self.filterByPage, self.contadorPag) # toast(str(self.contadorPago)) contadorPag = 0 def SearchProduct(self, instance, take, contadorPage): # valores seteados # on_text: app.SearchProduct(self.text,2,0)#seteado filtro # self.filterByPage=take data = self.db.searchProduct(instance, take, contadorPage) # elimina vista actual valor = len(App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.rv_main.data) for i in range(valor): App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.rv_main.data.pop() #agrega text busqueda App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.rv_main.data.append({ "viewclass": "CardsBoxForShopWindowSearch", "text": 'kiubo' }) #agrega valores encontrados for i, val in enumerate(data): App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.rv_main.data.append({ "viewclass": "CardsBoxForShopWindow", "height": dp(300), 'name': val.name, "product_image": val.img, 'idProd1': str(val.id) }) App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.rv_main.data.append({ "viewclass": "CardsBoxForShopWindowPagNum", "text": 'pago' }) App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.rv_main.data.append({ "viewclass": "CardsBoxForShopWindowPag", "text": 'pago' }) App.get_running_app().main_widget.ids.scr_mngr.get_screen( "shop window").ids.rv_main.data.append({ "viewclass": "CardsBoxForShopWindowPagSpace", }) filterByPage = 0 def filtrado(self, take): self.filterByPage = take self.contadorPag = 0 self.SearchProduct('', self.filterByPage, self.contadorPag) #endRegion Funcionalidad text = StringProperty() path = StringProperty() effect_cls = ScrollEffect callback = ObjectProperty(lambda x: None)
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 RoadGANGUI(MDApp): title = "RoadGAN" def __init__(self, **kwargs): super().__init__(**kwargs) Window.bind(on_keyboard=self.events) self.main_win = Builder.load_string(KV) self.manager_open = False self.manager = None self.settings_open = False self.scaner = False self.input_path = None self.output_path = './' self.weather = "clear" self.day_time = "daylight" self.urban_style = "Munster" self.weather_conditions = [{ "icon": "weather-sunny", "text": "clear" }, { "icon": 'weather-fog', "text": "fog" }, { "icon": "weather-pouring", "text": 'rain' }, { "icon": "weather-snowy", "text": 'snow' }, { "icon": "weather-cloudy", "text": 'clouds' }] self.urban_styles = [{ "icon": "home-city", "text": 'Munster' }, { "icon": "home-city", "text": 'Los Angeles' }, { "icon": "home-city", "text": 'Paris' }, { "icon": "home-city", "text": 'Boston' }, { "icon": "home-city", "text": 'Beijing' }] self.day_times = [{ "icon": "weather-sunset-up", "text": 'dawn' }, { "icon": "weather-sunny", "text": 'daylight' }, { "icon": "weather-sunset", "text": 'dusk' }, { "icon": "weather-night", "text": 'night' }] self.inference_thread = Thread(target=self.launch_conversion) def build(self): self.theme_cls.primary_palette = "Amber" return self.main_win def open_settings(self): '''Create and open the settings bottom panel. This will add dropdown menus for selecting weather conditions, daylight conditions and the urban style.''' self.settings = MDCustomBottomSheet(screen=Factory.SettingsScenario()) self.weather_menu = MDDropdownMenu( caller=self.settings.screen.ids.weather_cond, items=self.weather_conditions, position="auto", callback=self.update_weather_condition, width_mult=3, ) self.urban_style_menu = MDDropdownMenu( caller=self.settings.screen.ids.urban_style, items=self.urban_styles, position="auto", callback=self.update_urban_style, width_mult=3, ) self.day_time_menu = MDDropdownMenu( caller=self.settings.screen.ids.day_time, items=self.day_times, position="auto", callback=self.update_day_time, width_mult=3, ) self.settings.screen.ids.weather_cond.set_item(self.weather) self.settings.screen.ids.day_time.set_item(self.day_time) self.settings.screen.ids.urban_style.set_item(self.urban_style) self.settings.open() def close_settings(self): '''Close the settings bottom panel.''' if self.settings: self.settings.dismiss() def on_checkbox_active(self, checkbox, value): '''Called when clicking on the segmentation checkbox. type: value: bool; param: value: active state of the checkbox; type: checkbox: MDCheckbox; param: checkbox: clicked checkbox instance; ''' self.scaner = value def update_weather_condition(self, instance): '''Set weather conditions according to the chosen item in the GUI. type: instance: MDDropDownMenuItem; param: instance: The chosen menu item;''' if instance.text != 'clear': self.weather = instance.text self.settings.screen.ids.weather_cond.set_item(instance.text) def update_day_time(self, instance): '''Set daylight conditions according to the chosen item in the GUI. type: instance: MDDropDownMenuItem; param: instance: The chosen menu item;''' self.day_time = instance.text self.settings.screen.ids.day_time.set_item(self.day_time) def update_urban_style(self, instance): '''Set urban style according to the chosen item in the GUI. type: instance: MDDropDownMenuItem; param: instance: The chosen menu item;''' self.urban_style = instance.text self.settings.screen.ids.urban_style.set_item(self.urban_style) def file_manager_open(self, output=False): '''Open a new file manager for selecting either the input segmentation video or the output location for the synthesized video. :type output: bool; :param output: If set to True, will open the file manager for selecting the output location;''' if output: func = self.select_output_path path = self.output_path else: func = self.select_input_path path = self.input_path if not self.manager_open: self.manager = MDFileManager(exit_manager=self.exit_manager, select_path=func) self.manager.ext = ['.mp4', '.avi'] self.manager.show(os.path.dirname(path) if path else '/') # output manager to the screen self.manager_open = True def select_input_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; ''' self.exit_manager() self.input_path = path toast(path) def select_output_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; ''' self.exit_manager() self.output_path = path toast(path) def exit_manager(self, *args): '''Called when the user reaches the root of the directory tree.''' self.manager.close() self.manager_open = False def process_inference(self): '''Called when the user clicks on the floating play button. Launches the conversion in a separated thread using vid2vid and HAL.''' if self.inference_thread.is_alive(): self.inference_thread.join() self.main_win.ids.spinner.active = True self.inference_thread.start() def launch_conversion(self): '''Converts the segmentation video selected in the GUI using vid2vid and HAL. It also takes into account the selected reference image and weather/daylight conditions.''' video_name = decompose_video(self.input_path, process_pal=not (self.scaner)) frame_dir_path = os.path.join(os.path.dirname(self.input_path), video_name) os.makedirs('./tmp') save_path = os.path.join('./tmp', video_name + "_converted") infer_images(frame_dir_path, os.path.abspath(self.select_style_img()), save_path, self.scaner) weather = "" if self.weather == "clear" else self.weather os.chdir('attribute_hallucination/') os.system( "export MKL_SERVICE_FORCE_INTEL=1 && python generate_style.py --video_path " + os.path.join('..', save_path) + " --attributes " + self.day_time + " " + weather) os.system( "export MKL_SERVICE_FORCE_INTEL=1 && python style_transfer.py --video_folder " + os.path.join('..', save_path)) os.chdir('..') recompose_video( './tmp/' + video_name + "_converted_stylized/", os.path.join(self.output_path, video_name + "_converted.mp4")) shutil.rmtree('./tmp') self.main_win.ids.spinner.active = False toast('Inference finished!') def select_style_img(self): '''Return the path to the style image corresponding to the scenario chosen by the user.''' style = self.urban_style.lower().replace(" ", "_") return os.path.join("inference/refs_img/images/", f"{style}_clear") def events(self, instance, keyboard, keycode, text, modifiers): '''Called when buttons are pressed on the keyboard while the file manager is open.''' if keyboard in (1001, 27): if self.manager_open: self.manager.back() return True