def mock_servers(self): server_board = OneUIMockServerBoard() bottom_sheet_menu = MDCustomBottomSheet(screen=server_board) server_board.bind(close=lambda: bottom_sheet_menu.dismiss()) server_board.bind(current=lambda _, x: self.selected_server( x, lambda: bottom_sheet_menu.dismiss())) bottom_sheet_menu.open()
class MyApp(MDApp): dialog = None deposit_sheet = None def __init__(self, **kwargs): super().__init__(**kwargs) self.theme_cls.theme_style = db.get_config()[1] self.currency = db.get_config()[2] def toggle_theme(self, switch, value): if value: self.theme_cls.theme_style = "Dark" else: self.theme_cls.theme_style = "Light" db.set_config(self.theme_cls.theme_style, 'usd') # todo define later def change_screen(self, screen_name, direction='left'): screen_manager = self.root.ids['screen_manager'] if screen_name == 'History' and screen_manager.current == 'Setting': direction = 'right' screen_manager.transition.direction = direction screen_manager.current = screen_name def show_deposit_sheet(self): self.deposit_sheet = MDCustomBottomSheet(screen=Factory.DepositSheet()) self.deposit_sheet.open()
class DemoApp(MDApp): def build(self): screen = Screen() self.help_str = Builder.load_string(helper_string) screen.add_widget(self.help_str) return screen def show_example_custom_bottom_sheet(self): self.custom_sheet = MDCustomBottomSheet(screen=Factory.CustomSheet()) self.custom_sheet.open()
class DemoApp(MDApp): def build(self): screen = Screen() self.helper_text = Builder.load_string(KV) screen.add_widget(self.helper_text) return screen def call_Back(self,x): toast(x) def bottom_layer(self): self.custom = MDCustomBottomSheet(screen=Factory.Customsheet()) self.custom.open() def open(self): webbrowser.open("https://google.com")
class DemoApp(MDApp): screen_traversed = [ "homescreen", ] def __init__(self, *args): self.root = RootClass() Window.bind(on_keyboard=self.back_btn) super().__init__(*args) def back_btn(self, window, key, *args): if key == 27: if len(self.screen_traversed) == 1: return False self.go_backwards() return True def go_forwards(self, scrn): self.screen_traversed.append(scrn) self.root.transition = SlideTransition(direction="left") self.root.current = scrn def go_backwards(self): self.screen_traversed.pop() self.root.transition = SlideTransition(direction="right") self.root.current = self.screen_traversed[-1] def open_payment_layout(self, sku): pml = PaymentMethodLayout() self.product_id = sku self.custom_sheet = MDCustomBottomSheet(screen=pml) self.custom_sheet.open() def initiate_purchase(self, method_name): if method_name == "gplay": if self.billing.isConsumable( self.product_id ) and self.product_id in self.billing.consumed.keys( ) and self.billing.consumed[self.product_id]: self.billing.consume(self.product_id) else: self.billing.purchase(self.product_id) else: show_toast("Payment method not implemented") def check_purchase(self, *args): # Check stuffs like whether the product has already been consumed # make buttons disabled if it's already consumed # do other stuffs based on if the product is monthly/annually consumable etc. pass def on_start(self): primary_clr = self.theme_cls.primary_color hex_color = '#%02x%02x%02x' % (int( primary_clr[0] * 200), int( primary_clr[1] * 200), int(primary_clr[2] * 200)) set_statusbar_color(hex_color) def build(self): self.billing = oiabilling.Billing([ PROD_ONETIME, PROD_MONTHLY_1, PROD_MONTHLY_2, PROD_MONTHLY_3, PROD_ANNUAL_1, PROD_ANNUAL_2 ], 'com.example.billingapp.Config') #gets consumed every month self.billing.setConsumable(PROD_MONTHLY_1) self.billing.setConsumable(PROD_MONTHLY_2) self.billing.setConsumable(PROD_MONTHLY_3) #gets consumed every year self.billing.setConsumable(PROD_ANNUAL_1) self.billing.setConsumable(PROD_ANNUAL_2) self.billing.bind(consumed=self.check_purchase) return Builder.load_string(kv) def on_resume(self): return True
class Sports(MDApp): dialog = None #sm.add_widget(HomeScreen(name='home')) #sm.add_widget(NScreen(name='stats')) #def remove_item(self, instance): #self.screen.ids.InfoCard.remove_widget(instance) def build(self): self.sm = ScrManage() return Builder.load_string(kv) def callback_for_menu_items(self, *args): print(args[0]) def show_example_custom_bottom_sheet(self): self.custom_sheet = MDCustomBottomSheet( screen=Factory.ContentCustomSheet()) self.custom_sheet.open() def showAddPlayer_Dialog(self): if not self.dialog: self.dialog = MDDialog( title="Add Player:", type="custom", content_cls=AddPlayerContent(), size_hint=[.8, .8], buttons=[ MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color, on_release=self.on_cancel), MDFlatButton(text="OK", text_color=self.theme_cls.primary_color, on_release=self.on_save), ], ) self.dialog.open() def on_save(self, obj): print("save") sqliteConnection = sqlite3.connect('demo.db') cursor = sqliteConnection.cursor() print("Successfully Connected to SQLite") PlayerName = self.dialog.content_cls.ids.playerNametxt.text game_date = self.dialog.content_cls.ids.date_picker_label.text against = self.dialog.content_cls.ids.Againsttxt.text gurnsey = self.dialog.content_cls.ids.SliderJumpertxt.text sqlite_insert_query = """INSERT INTO users (Username, GameDate, Vers, Jumper) VALUES (?, ?, ?, ?)""" count = cursor.execute( "INSERT INTO users (Username, GameDate, Vers, Jumper) VALUES (?, ?, ?, ?)", (PlayerName, game_date, against, gurnsey)) sqliteConnection.commit() print("Record inserted successfully into SqliteDb_developers table ", cursor.rowcount) cursor.close() #sm = ScreenManager() print(self.sm.screen_names) #self.sm.remove_widget(self.sm.get_screen('stats')) #ScreenManager.remove_widget(ScreenManager.get_screen('stats')) self.dialog.dismiss() def show_alert_dialog(self): self.dialog = MDDialog( text="Delete Player?", size_hint=[.8, .8], buttons=[ MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color, on_release=self.close_dialog), MDFlatButton( text="DELETE", text_color=self.theme_cls.primary_color, ), ], ) self.dialog.open() def close_dialog(self, obj): self.dialog.dismiss() def on_cancel(self, obj): self.dialog.dismiss()
class MainApp(MDApp): def build(self): self.theme_cls.theme_style = 'Dark' self.theme_cls.primary_palette = 'LightBlue' self.theme_cls.primay_hue = '200' self.title = 'Blue Physics v.10.0' self.icon = 'images/logoonlyspheretransparent.png' self.graphchs = MyGraph(ylabel='Volts (V)') self.graphtemp = MyGraph(ylabel='Temp. (C)', ymin=24, ymax=26, y_ticks_major=0.1, y_ticks_minor=5) self.graphPS = MyGraph(ylabel='PS (V)', ymin=56.55, ymax=56.75, y_ticks_major=0.05, y_ticks_minor=5) self.graph5V = MyGraph(ylabel='5V (V)') self.graphminus15V = MyGraph(ylabel='-15V (V)') self.graphrefV = MyGraph(ylabel='ref. (V)', ymin=1.27, ymax=1.26, y_ticks_major=0.01, y_ticks_minor=5) self.measlayout = self.root.ids.measurescreenlayout self.measlayout.add_widget(self.graphchs) #List of all the graphs #useful to change xmin xmax ymin ymax all at once self.allgraphs = [ self.graphtemp, self.graph5V, self.graphPS, self.graphminus15V, self.graphrefV, self.graphchs ] #Dictionary with all the graphs voltages #needed for switching graphs self.graphvolts = { 'Temp': self.graphtemp, 'PS': self.graphPS, 'refV': self.graphrefV, '-15V': self.graphminus15V, '5V': self.graph5V } # Lista ch plots self.lchplots = [ MeshLinePlot(color=get_color_from_hex(mcolors[i])) for i in range(number_of_channels) ] for plot in self.lchplots: self.graphchs.add_plot(plot) self.tempplot = MeshLinePlot(color=get_color_from_hex(mcolors[8])) self.PSplot = MeshLinePlot(color=get_color_from_hex(mcolors[1])) self.v5Vplot = MeshLinePlot(color=get_color_from_hex(mcolors[4])) self.minus15Vplot = MeshLinePlot(color=get_color_from_hex(mcolors[3])) self.refVplot = MeshLinePlot(color=get_color_from_hex(mcolors[2])) #Lista al plots self.allplots = [ self.tempplot, self.v5Vplot, self.PSplot, self.minus15Vplot, self.refVplot ] + self.lchplots self.graphtemp.add_plot(self.tempplot) self.graphPS.add_plot(self.PSplot) self.graph5V.add_plot(self.v5Vplot) self.graphminus15V.add_plot(self.minus15Vplot) self.graphrefV.add_plot(self.refVplot) self.contentsheet = Factory.ContentCustomSheet() #This is a fuction to be executed before standard measuring #to calculate baselines and initial margins of graphs #It is supposed to be excuted before light signal or Linac is received def beforemeasuring(self): labefore = [] device = list( serial.tools.list_ports.grep('Adafruit ItsyBitsy M4'))[0].device serbefore = serial.Serial(device, 115200, timeout=1) serbefore.reset_input_buffer() serbefore.reset_output_buffer() serbefore.write(b't') while len(labefore) < 429 * 3: if serbefore.in_waiting: inbytes = serbefore.read(22) count = int.from_bytes(inbytes[:4], 'big') mytime = int.from_bytes(inbytes[4:8], 'big') temp = int.from_bytes(inbytes[8:10], 'big') v5 = int.from_bytes(inbytes[10:12], 'big') PS = int.from_bytes(inbytes[12:14], 'big') vminus15 = int.from_bytes(inbytes[14:16], 'big') vref = int.from_bytes(inbytes[16:18], 'big') lmeas = [ int.from_bytes(inbytes[18 + 2 * i:20 + 2 * i], 'big') for i in range(number_of_channels) ] labefore.append([count, mytime, temp, v5, PS, vminus15, vref] + lmeas) serbefore.close() listofchsc = ['ch%sc' % i for i in range(number_of_channels)] listofchsv = ['ch%sV' % i for i in range(number_of_channels)] dfb = pd.DataFrame( labefore, columns=[ 'counts', 'time', 'temp', 'c5V', 'cPS', 'cminus15V', 'cref' ] + listofchsc) dfb['tempC'] = (dfb.temp & 0xFFF) / 16 dfb[listofchsv] = dfb.loc[:, listofchsc] * -24.576 / 65535 + 12.288 dfb['v5V'] = dfb.c5V * 0.1875 / 1000 dfb['vPS'] = dfb.cPS * 0.1875 * 16.39658 / 1000 dfb['vminus15V'] = dfb.cminus15V * 0.1875 * -4.6887 / 1000 dfb['vref'] = dfb.cref * 0.0625 / 1000 #set the maximum signal of dark current without light #to findout the pulses #max value is going to be set up with a buffer of 5% maxchs = dfb.loc[10:, listofchsv].max().max() self.maxvalueatnolight = maxchs + 0.05 * abs(maxchs) #new zerovalue for channels at not ligth #This will be used to reset the zero value of the measurements self.newminvalueatnolight = dfb.loc[10:, listofchsv].min().min() #set the maximuns and minimuns of graphs self.graphchs.ymax = float(maxchs + 0.005 * abs(maxchs)) minchs = dfb.loc[10:, listofchsv].min().min() self.graphchs.ymin = float(minchs - 0.005 * abs(minchs)) maxtemp = dfb.loc[10:, 'tempC'].max() self.graphtemp.ymax = float(maxtemp + 0.005 * abs(maxtemp)) mintemp = dfb.loc[10:, 'tempC'].min() self.graphtemp.ymin = float(mintemp - 0.005 * abs(mintemp)) maxPS = dfb.loc[10:, 'vPS'].max() self.graphPS.ymax = float(maxPS + 0.003 * abs(maxPS)) minPS = dfb.loc[10:, 'vPS'].min() self.graphPS.ymin = float(minPS + 0.001 * abs(minPS)) max5V = dfb.loc[10:, 'v5V'].max() self.graph5V.ymax = float(max5V + 0.005 * abs(max5V)) min5V = dfb.loc[10:, 'v5V'].min() self.graph5V.ymin = float(min5V - 0.005 * abs(min5V)) maxminus15V = dfb.loc[10:, 'vminus15V'].max() self.graphminus15V.ymax = float(maxminus15V + 0.005 * abs(maxminus15V)) minminus15V = dfb.loc[10:, 'vminus15V'].min() self.graphminus15V.ymin = float(minminus15V - 0.005 * abs(minminus15V)) #maxrefV = dfb.loc[10:,'vref'].max() #self.graphrefV.ymax = float(maxrefV + 0.005 * abs(maxrefV)) #minrefV = dfb.loc[10:,'vref'].min() #self.graphrefV.ymin = float(minrefV - 0.005 * abs(minrefV)) def start(self): global stop_thread #emulator #self.sender_thread = Thread(target=sender) #self.sender_thread.daemon = True #self.sender_thread.start() stop_thread = False self.root.ids.checkboxlevel1.disabled = True self.root.ids.checkboxlevel2.disabled = True self.root.ids.checkboxlevel3.disabled = True self.root.ids.checkboxlevel4.disabled = True #Routine to execute before measuring #This is to calculate base lines and initial plot margins self.beforemeasuring() self.receiver_thread = Thread(target=receiver) self.receiver_thread.daemon = True self.receiver_thread.start() time.sleep(1) self.plotpulses = self.contentsheet.ids.mypulsescheckbox.active if (not self.plotpulses): for graph in self.allgraphs: graph.xmin = 0 graph.xmax = 60 self.graphchs.ymin = -10 self.graphchs.ymax = 1000 self.acum = np.zeros((1, 7 + number_of_channels)) self.event1 = Clock.schedule_interval(self.updategraphs, 0.3) else: self.graphchs.ymin = -12 self.graphchs.ymax = 12 self.plotcounter = 0 self.event1 = Clock.schedule_interval(self.updategraphpulses, 0.3) #emulator #self.ser = Serial('/dev/pts/5', 115200, timeout=1) def stop(self): #emulator global stop_thread self.root.ids.checkboxlevel1.disabled = False self.root.ids.checkboxlevel2.disabled = False self.root.ids.checkboxlevel3.disabled = False self.root.ids.checkboxlevel4.disabled = False #emulator stop_thread = True #self.sender_thread.join() Clock.unschedule(self.event1) #emulator #print('sender_thread kiled') for graph in self.allgraphs: graph.xmaxorig = graph.xmax graph.xminorig = graph.xmin graph.ymaxorig = graph.ymax graph.yminorig = graph.ymin def updategraphs(self, dt): aa = np.ndarray((len(da) // 22, 22), np.uint8, da) ac = np.column_stack( (aa[:, [0, 4]] * 2**24 + aa[:, [1, 5]] * 2**16 + aa[:, [2, 6]] * 2**8 + aa[:, [3, 7]], 2**8 + aa[:, 9], aa[:, 10::2] * 2**8 + aa[:, 11::2])) av = (ac * arrmultip + arrsum)[-429:] if self.contentsheet.ids.mycleanpulses.active: av = cleanpulses(av, self.maxvalueatnolight) countnow = av[0, 0] tempnow = av[0, 2] tnow = av[0, 1] datacum = av[:, 7:].sum(axis=0) voltcum = av[:, 3:7].mean(axis=0) datatoadd = np.hstack((countnow, tnow, tempnow, voltcum, datacum)) self.acum = np.vstack((self.acum, datatoadd)) self.acumtosend = self.acum[1:] if tnow > 60: self.acumtosend = self.acum[1::2] for graph in self.allgraphs: graph.xmax = float(tnow) self.tempplot.points = self.acumtosend[:, [1, 2]] self.v5Vplot.points = self.acumtosend[:, [1, 3]] self.PSplot.points = self.acumtosend[:, [1, 4]] self.minus15Vplot.points = self.acumtosend[:, [1, 5]] self.refVplot.points = self.acumtosend[:, [1, 6]] for i in range(number_of_channels): self.lchplots[i].points = self.acumtosend[:, [1, 7 + i]] def updategraphpulses(self, dt): aa = np.ndarray((len(da) // 22, 22), np.uint8, da) ac = np.column_stack( (aa[:, [0, 4]] * 2**24 + aa[:, [1, 5]] * 2**16 + aa[:, [2, 6]] * 2**8 + aa[:, [3, 7]], 2**8 + aa[:, 9], aa[:, 10::2] * 2**8 + aa[:, 11::2])) av = (ac * arrmultip + arrsum)[-429:] if self.contentsheet.ids.mycleanpulses.active: av = cleanpulses(av, self.maxvalueatnolight) for graph in self.allgraphs: graph.xmin = float(av[0, 1]) graph.xmax = float(av[-1, 1]) self.tempplot.points = av[:, [1, 2]] self.v5Vplot.points = av[:, [1, 3]] self.PSplot.points = av[:, [1, 4]] self.minus15Vplot.points = av[:, [1, 5]] self.refVplot.points = av[:, [1, 6]] for i in range(number_of_channels): self.lchplots[i].points = av[:, [1, 7 + i]] def bottomsheet(self): self.custom_sheet = MDCustomBottomSheet(screen=self.contentsheet, radius_from='top') self.custom_sheet.open() def addremoveplot(self, intext, checkbox, value): if value: self.graphchs.add_plot(self.lchplots[int(intext[-1])]) else: self.graphchs.remove_plot(self.lchplots[int(intext[-1])]) def addremovegraph(self, intext, checkbox, value): #print (intext, checkbox, value) if intext != 'None': if value: self.measlayout.add_widget(self.graphvolts[intext]) else: self.measlayout.remove_widget(self.graphvolts[intext]) def callback(self): print('oido') def onofflevel(self, intext, switch): print('Rango:', intext[-1]) device = list( serial.tools.list_ports.grep('Adafruit ItsyBitsy M4'))[0].device ser = serial.Serial(device, 115200, timeout=1) ser.write(('c%s,' % intext[-1]).encode()) ser.close()
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