def render(self, is_running): bimpy.set_next_tree_node_open(True, bimpy.Condition.FirstUseEver) if not bimpy.tree_node('progress##train_phase_component'): return self._is_trainning_start = False self._is_trainning_stop = False if self._is_trainning: if bimpy.button('stop##train_phase_component'): # print('stop') self._is_trainning = False self._is_trainning_stop = True if not is_running: # print('run over stop') self._is_trainning = False self._is_trainning_stop = True else: if bimpy.button('start##train_phase_component'): # print('start {}'.format(is_running)) if not is_running: self._is_trainning = True self._is_trainning_start = True if self._trainning_progress is not None: bimpy.text('epoch: {} / {}'.format( self._trainning_progress['epoch_now'], self._trainning_progress['epoch_all'], )) bimpy.tree_pop()
def main(): global CTX ctx = bimpy.Context() ctx.init(1200, 1200, "Image") with ctx: bimpy.themes.set_light_theme() socket_thread = threading.Thread(target = thread_socket_func, args = (8883, )) socket_thread.start() message_thread = threading.Thread(target = message_thread_func) message_thread.start() previous_n_points = 0 clear_flag = False while not ctx.should_close(): with ctx: bimpy.set_next_window_pos(bimpy.Vec2(120, 120), bimpy.Condition.Once) bimpy.set_next_window_size(bimpy.Vec2(400, 400), bimpy.Condition.Once) bimpy.begin("Window #1") bimpy.text("This is text!") if bimpy.button("Send A Lot Of Messages"): temp_messages = [make_message_text("log", "Message #" + str(i)) for i in range(560)] send_messages(CTX.message_pipeline, temp_messages) if bimpy.button("Send A Lot Of Random Points"): temp_messages = [make_message_point("point", (random.randrange(400 + i), random.randrange(400 + i))) for i in range(20)] send_messages(CTX.message_pipeline, temp_messages) if bimpy.button("Clear Flag"): clear_flag = not clear_flag bimpy.text("Text from events:\n%s" % (CTX.data.text)) bimpy.end() draw_window_drawing(ctx, 400, 400, "Sample Drawing", CTX.data.points) log("Exited rendering thread") log("Sending exit to message_thread") send_message_text(CTX.message_pipeline, "exit", "") log("Waiting for message_thread") message_thread.join() CTX.server_socket_running = False if CTX.server_socket: for c, info in CTX.server_socket.connections: c.send(b'exit') log("Waiting for socket_thread") socket_thread.join() log("Bye")
def drawPathFinder(columns_count=7, lines_count=5): bimpy.columns(columns_count, None, borders_vertical) i = 0 while i != columns_count: i += 1 if borders_horizontal and bimpy.get_column_index == 0: bimpy.separator() #bimpy.text("{}".format("a")) bimpy.button("Auto Path", bimpy.Vec2(100,100)) bimpy.next_column() bimpy.columns(1) if borders_horizontal: bimpy.separator()
def scene_tree(self): if bimpy.button("New Node"): self.new_node() bimpy.same_line() if bimpy.button("Delete Node"): if self.selected_node is not None: def rem(l): if self.selected_node in l: l.remove(self.selected_node) self.walk(self.root_nodes, rem) def pnodes(l): remove_n = None for n in l: node_flags = bimpy.OpenOnArrow | bimpy.OpenOnDoubleClick | bimpy.DefaultOpen if n == self.selected_node: node_flags |= bimpy.Selected if len(n.children) == 0: node_flags |= bimpy.Leaf | bimpy.NoTreePushOnOpen node_open = bimpy.tree_node_ex(n.id, node_flags, n.name) if bimpy.is_item_clicked(): if self.selected_node == n: self.selected_node = None else: self.selected_node = n if self.selected_node is not None and self.selected_node == n and self.ctrl_x: self.copied_node = n self.selected_node = None remove_n = n if node_open and len(n.children) != 0: pnodes(n.children) bimpy.tree_pop() if remove_n is not None: l.remove(remove_n) if self.copied_node is not None and self.selected_node is not None and self.ctrl_v: self.selected_node.children.append(self.copied_node) self.copied_node = None pnodes(self.root_nodes)
def main(): selected_compiler = bimpy.Int() ctx = bimpy.Context() ctx.init(WIDTH, HEIGHT, "Virtual enviroment manager") environments = getAvailableEnviroments() compilers_list = list(data.compilers.keys()) show_new_env_menu = False while (not ctx.should_close()): with ctx: bimpy.set_next_window_pos(bimpy.Vec2(0, 0), bimpy.Condition.Once) bimpy.set_next_window_size(bimpy.Vec2(WIDTH, HEIGHT), bimpy.Condition.Once) bimpy.begin("Enviroments",bimpy.Bool(True), \ bimpy.WindowFlags.NoCollapse and bimpy.WindowFlags.NoResize) bimpy.text(sys.version) bimpy.columns(2) for enviroment in environments: if bimpy.button(enviroment): compiler = list(data.compilers.values())[ selected_compiler. value] if selected_compiler.value != 0 else "" subprocess.call( ['start', environments[enviroment], compiler], shell=True) bimpy.next_column() if bimpy.button("O##" + enviroment): subprocess.Popen(r'explorer /select,' + os.path.dirname(environments[enviroment])) #os.startfile(os.path.realpath(os.path.dirname(environments[enviroment]))) bimpy.next_column() bimpy.columns(1) if bimpy.combo("Compiler", selected_compiler, compilers_list): pass # if bimpy.button("Add new enviroment"): # new_env_ctx = BimpyContext(WIDTH, HEIGHT, "New enviroment menu") # while(not new_env_ctx.ctx.should_close()): # with new_env_ctx.ctx: # bimpy.begin("dsad") # bimpy.text("d") # bimpy.end() # if bimpy.button("Create new enviroment"): bimpy.end()
def retrival(self): ###########UI########### size = bimpy.Vec2(500, 750) bimpy.set_next_window_size(size, bimpy.Condition.Once) if bimpy.begin_popup_modal('{}: {}'.format(LANG.retrieve, self.select_label)) \ and self.select_label != '' and self.first_init: for idx, file in enumerate( self.r.label2pic[self.select_label.lower()]): if idx != 0: bimpy.separator() img = self.r.get_thumbnail(file) bimpy.text(file) bimpy.image(img) bimpy.separator() if bimpy.button(LANG.retrieve_close): bimpy.clode_current_popup() bimpy.end_popup() ######################## t = { 'x': bimpy.get_window_pos().x, 'y': bimpy.get_window_pos().y, 'w': bimpy.get_window_size().x, 'h': bimpy.get_window_size().y, 'self': self, } return t
def drawMainTab(columns_count=7, lines_count=5): bimpy.columns(columns_count, None, borders_vertical) i = 0 col_c = 0 while col_c > lines_count: col_c += 1 while i != columns_count: if borders_horizontal and bimpy.get_column_index == 0: bimpy.separator() #bimpy.text("{}".format("a")) bimpy.button(field_names[i], bimpy.Vec2(100,100)) bimpy.next_column() i += 1 columns_count = 0 bimpy.columns(1) if borders_horizontal: bimpy.separator()
def on_update(self): bp.text("Hello, world!") if bp.button("OK"): print(self.string.value) bp.input_text('string', self.string, 256) bp.slider_float("float", self.f, 0, 1)
def ranged_slider(name, value, range_info): f = bimpy.Float(value) ret = None rng = (range_info.max - range_info.min) spd = .0025 * rng if rng > 0 else .1 if bimpy.drag_float("##v_" + name, f, spd, range_info.min, range_info.max): ret = ps.ConfigurationInfo.ClampFloat(range_info, f.value) bimpy.same_line() if bimpy.button("init##b_" + name): ret = range_info.initial return ret
def visualize(self): bimpy.begin(type(self).__name__ + " - " + str(id(self)), bimpy.Bool(True)) bimpy.input_text("Text", self.__state["text"], 256) button_pressed = bimpy.button("Plot", bimpy.Vec2(40, 20)) if button_pressed or self.__state["toggle"]: if button_pressed: self.__state["toggle"] ^= True if len(self.__state["text"].value) > 0: bimpy.plot_lines("Graph", self.encode(self.__state["text"].value.encode())) bimpy.end()
def render(self, is_lock): bimpy.set_next_tree_node_open(True, bimpy.Condition.FirstUseEver) if not bimpy.tree_node('convex points##convex_component'): return bimpy.same_line() bimpy_tools.help_marker('Convex points should be presented in counter-clockwise order') flags = bimpy.InputTextFlags.EnterReturnsTrue if is_lock: flags |= bimpy.InputTextFlags.ReadOnly last_convex_number_value = self._convex_number.value if bimpy.input_int('number##convex_component', self._convex_number, 1, 1, flags): self._convex_number.value = max(3, self._convex_number.value) if last_convex_number_value > self._convex_number.value: self._convex_data = self._convex_data[:self._convex_number.value] # cut back points else: self._convex_data.extend([ [bimpy.Float(0), bimpy.Float(0)] for _ in range(last_convex_number_value, self._convex_number.value) ]) # show convex value setting bimpy.set_next_tree_node_open(self._convex_number.value < 10, bimpy.Condition.FirstUseEver) if bimpy.tree_node('convex value ({})##convex_component'.format(self._convex_number.value)): for index in range(self._convex_number.value): bimpy.push_item_width(210) bimpy.input_float2( '{:<3d}'.format(index), self._convex_data[index][0], self._convex_data[index][1], flags=flags ) bimpy.pop_item_width() bimpy.tree_pop() # draw part bimpy.new_line() if bimpy.button('draw convex##convex_component') and not is_lock: self._convex_data_backup = [[item[0].value, item[1].value] for item in self._convex_data] self._convex_draw_flag = True self._convex_data = [] self._convex_number.value = 0 bimpy.tree_pop()
def view_batch(bp): bimpy.begin("Batch") bimpy.button("Open files...") bimpy.button("Open configurations...") bimpy.separator() bimpy.text("Regions:") bimpy.separator() bimpy.button("Render Files") bimpy.end()
def show(self, ctx): # Add a layer to the MLP bimpy.push_item_width(80) bimpy.input_int("nr neurons", self.ui.nr_neurons) bimpy.same_line() bimpy.combo("transfer", self.ui.transfer, self.ui.transfer_names) if (self.ui.nr_neurons.value > 0): bimpy.same_line() if (bimpy.button("add layer")): transfer = self.ui.transfer_names[self.ui.transfer.value] self.model.add_layer(transfer, self.ui.nr_neurons.value) bimpy.pop_item_width() self.model.show(ctx) show_io_plot(self.ui.input, self.model)
def render(self): if not self._size: self._size = bimpy.Vec2(400, 600) bimpy.set_next_window_size(self._size) if bimpy.begin(self.name, self.opened, flags=bimpy.WindowFlags.NoCollapse | bimpy.WindowFlags.MenuBar): if bimpy.begin_menu_bar(): bimpy.menu_item('Reload', 'Cmd+R', self.click_states['reload']) bimpy.end_menu_bar() for folder_name, folder_files in self.tree.items(): if bimpy.collapsing_header(folder_name): for item, button_name in folder_files: if bimpy.button(button_name): item_path = '{0}/{1}'.format(folder_name, item) try: new_savegame = SaveGameFrame( PS2WrappedBinBackend, item_path, self) self.child_frames.append(new_savegame) except KeyboardInterrupt as e: raise e except Exception as e: print(e) bimpy.same_line() bimpy.text(item) bimpy.end() for child_frame in self.child_frames: child_frame.render()
import bimpy as bp context = bp.Context() context.init(600, 600, "Hello, Bimpy!") label_content = bp.String() spinner_content = bp.Float() while not context.should_close(): with context: bp.text("Hello, Bimpy!") if bp.button("Ok"): print("Hello!") bp.input_text("string", label_content, 256) bp.slider_float("float", spinner_content, 0.0, 1.0)
res = ((current_time) - (g_last_timestamp)) g_last_timestamp = current_time return res def fail(msg): print(((bcolors.FAIL) + ("{:8d} FAIL ".format(milli_since_last())) + (msg) + (bcolors.ENDC))) sys.stdout.flush() def plog(msg): print(((bcolors.OKGREEN) + ("{:8d} LOG ".format(milli_since_last())) + (msg) + (bcolors.ENDC))) sys.stdout.flush() args = docopt.docopt(__doc__, version="0.0.1") if (args["--verbose"]): print(args) ctx = b.Context() ctx.init(600, 600, "Hello") str = b.String() f = b.Float() while (not (ctx.should_close())): with ctx: b.text("hello world") if (b.button("OK")): print(str.value) b.input_text("string", str, 256) b.slider_float("float", f, (0.0e+0), (1.e+0))
import bimpy ctx = bimpy.Context() ctx.init(600, 600, "Hello") str = bimpy.String() f = bimpy.Float(); while(not ctx.should_close()): with ctx: bimpy.text("Hello, world!") if bimpy.button("OK"): print(str.value) bimpy.input_text('string', str, 256) bimpy.slider_float("float", f, 0.0, 1.0)
bimpy.add_circle_filled(point * m + center, 5, 0xAF000000 + colors[i], 100) axis_ = np.matmul(axis, S * 2.0) axis_ = np.matmul(axis_, R) + P bimpy.add_line(center + bimpy.Vec2(axis_[0, 0], axis_[0, 1]) * m, center + bimpy.Vec2(axis_[1, 0], axis_[1, 1]) * m, 0xFFFF0000, 1) bimpy.add_line(center + bimpy.Vec2(axis_[2, 0], axis_[2, 1]) * m, center + bimpy.Vec2(axis_[3, 0], axis_[3, 1]) * m, 0xFFFF0000, 1) bimpy.end() bimpy.set_next_window_pos(bimpy.Vec2(20, 640), bimpy.Condition.Once) bimpy.set_next_window_size(bimpy.Vec2(800, 140), bimpy.Condition.Once) bimpy.begin("Controls") bimpy.input_int("Data points count", DATA_POINTS) bimpy.input_int("Clasters count", CLASTERS) bimpy.slider_float("std", std, 0.0, 3.0) if bimpy.button("Generate data"): generate_fake_data() bimpy.end() ctx.render()
if opened.value: if bimpy.begin("Hello!", opened=opened): bimpy.columns(4, "mycolumns") bimpy.separator() bimpy.text("Some text") bimpy.next_column() bimpy.text("Some text") bimpy.next_column() bimpy.text("Some text") bimpy.next_column() bimpy.text("Some text") bimpy.separator() bimpy.columns(1) if bimpy.button("Some button"): a = 0 print("!!!") bimpy.progress_bar(a) bimpy.combo("Combo!", selectedItem, mylist) bimpy.push_item_width(-10.0) bimpy.plot_lines("Some plot", vals, graph_size=bimpy.Vec2(0, 300)) bimpy.pop_item_width() a += 0.01 bimpy.end() if bimpy.begin("Hello2!",
import sys import os if os.path.exists("../cmake-build-debug/"): print('Running Debugging session!') sys.path.insert(0, "../cmake-build-debug/") import bimpy as bp ctx = bp.Context() ctx.init(600, 600, "Hello") str = bp.String() f = bp.Float() while not ctx.should_close(): with ctx: bp.begin_root("") bp.text("Hello, world!") if bp.button("OK"): print(str.value) bp.input_text('string', str, 256) bp.slider_float("float", f, 0.0, 1.0) bp.end()
def sample(cfg, logger): model = Model( startf=cfg.MODEL.START_CHANNEL_COUNT, layer_count= cfg.MODEL.LAYER_COUNT, maxf=cfg.MODEL.MAX_CHANNEL_COUNT, latent_size=cfg.MODEL.LATENT_SPACE_SIZE, truncation_psi=cfg.MODEL.TRUNCATIOM_PSI, truncation_cutoff=cfg.MODEL.TRUNCATIOM_CUTOFF, mapping_layers=cfg.MODEL.MAPPING_LAYERS, channels=3) model.eval() logger.info("Trainable parameters generator:") count_parameters(model.generator) model_dict = { 'generator_s': model.generator, 'mapping_fl_s': model.mapping, 'dlatent_avg': model.dlatent_avg, } checkpointer = Checkpointer(cfg, model_dict, logger=logger, save=True) checkpointer.load() ctx = bimpy.Context() remove = bimpy.Bool(False) layers = bimpy.Int(8) ctx.init(1800, 1600, "Styles") rnd = np.random.RandomState(5) latents = rnd.randn(1, cfg.MODEL.LATENT_SPACE_SIZE) sample = torch.tensor(latents).float().cuda() def update_image(sample): with torch.no_grad(): torch.manual_seed(0) model.eval() x_rec = model.generate(layers.value, remove.value, z=sample) #model.generator.set(l.value, c.value) resultsample = ((x_rec * 0.5 + 0.5) * 255).type(torch.long).clamp(0, 255) resultsample = resultsample.cpu()[0, :, :, :] return resultsample.type(torch.uint8).transpose(0, 2).transpose(0, 1) with torch.no_grad(): save_image(model.generate(8, True, z=sample) * 0.5 + 0.5, 'sample.png') im = bimpy.Image(update_image(sample)) while(not ctx.should_close()): with ctx: bimpy.set_window_font_scale(2.0) if bimpy.checkbox('REMOVE BLOB', remove): im = bimpy.Image(update_image(sample)) if bimpy.button('NEXT'): latents = rnd.randn(1, cfg.MODEL.LATENT_SPACE_SIZE) sample = torch.tensor(latents).float().cuda() im = bimpy.Image(update_image(sample)) if bimpy.slider_int("Layers", layers, 0, 8): im = bimpy.Image(update_image(sample)) bimpy.image(im, bimpy.Vec2(1024, 1024))
if (pinNumber.value > 13): pinNumber = bimpy.Int(13) if (minPWM.value > 255): minPWM = bimpy.Int(255) if (minPWM.value < 0): minPWM = bimpy.Int(0) if (maxPWM.value > 255): maxPWM = bimpy.Int(255) if (maxPWM.value < 1): maxPWM = bimpy.Int(1) if (minPWM.value > maxPWM.value): minPWM = bimpy.Int(maxPWM.value) bimpy.input_float('Light interval (seconds)', maxInterval, 0.100000000000000) if (maxInterval.value < 0.100000000): maxInterval = bimpy.Float(0.100000000000000) if bimpy.button(textToggleButton,bimpy.Vec2(208,0)): toggleLight = not toggleLight if (toggleLight == True): plot_values = array('f',[]) textToggleButton = 'Stop flashing LED' threading.Thread(target=flashLED, args=()).start() if (toggleLight == False): textToggleButton = 'Start flashing LED' if (checkPWM() == 1): bimpy.input_int('PWM Min',minPWM,1) bimpy.input_int('PWM Max',maxPWM,1) bimpy.plot_lines("",plot_values,0,'(' + str(pinNumber.value) + ')',0,1,bimpy.Vec2(0,50)) if bimpy.button('Exit',bimpy.Vec2(208,0)): currentBoard.exit() exit() bimpy.end()
def sample(cfg, logger): torch.cuda.set_device(0) model = Model(startf=cfg.MODEL.START_CHANNEL_COUNT, layer_count=cfg.MODEL.LAYER_COUNT, maxf=cfg.MODEL.MAX_CHANNEL_COUNT, latent_size=cfg.MODEL.LATENT_SPACE_SIZE, truncation_psi=cfg.MODEL.TRUNCATIOM_PSI, truncation_cutoff=cfg.MODEL.TRUNCATIOM_CUTOFF, mapping_layers=cfg.MODEL.MAPPING_LAYERS, channels=cfg.MODEL.CHANNELS, generator=cfg.MODEL.GENERATOR, encoder=cfg.MODEL.ENCODER) model.cuda(0) model.eval() model.requires_grad_(False) decoder = model.decoder encoder = model.encoder mapping_tl = model.mapping_d mapping_fl = model.mapping_f dlatent_avg = model.dlatent_avg logger.info("Trainable parameters generator:") count_parameters(decoder) logger.info("Trainable parameters discriminator:") count_parameters(encoder) arguments = dict() arguments["iteration"] = 0 model_dict = { 'discriminator_s': encoder, 'generator_s': decoder, 'mapping_tl_s': mapping_tl, 'mapping_fl_s': mapping_fl, 'dlatent_avg': dlatent_avg } checkpointer = Checkpointer(cfg, model_dict, {}, logger=logger, save=False) extra_checkpoint_data = checkpointer.load() model.eval() layer_count = cfg.MODEL.LAYER_COUNT def encode(x): Z, _ = model.encode(x, layer_count - 1, 1) Z = Z.repeat(1, model.mapping_f.num_layers, 1) return Z def decode(x): layer_idx = torch.arange(2 * layer_count)[np.newaxis, :, np.newaxis] ones = torch.ones(layer_idx.shape, dtype=torch.float32) coefs = torch.where(layer_idx < model.truncation_cutoff, ones, ones) # x = torch.lerp(model.dlatent_avg.buff.data, x, coefs) return model.decoder(x, layer_count - 1, 1, noise=True) path = 'dataset_samples/faces/realign1024x1024' paths = list(os.listdir(path)) paths.sort() paths_backup = paths[:] randomize = bimpy.Bool(True) current_file = bimpy.String("") ctx = bimpy.Context() attribute_values = [bimpy.Float(0) for i in indices] W = [ torch.tensor(np.load("principal_directions/direction_%d.npy" % i), dtype=torch.float32) for i in indices ] rnd = np.random.RandomState(5) def loadNext(): img = np.asarray(Image.open(path + '/' + paths[0])) current_file.value = paths[0] paths.pop(0) if len(paths) == 0: paths.extend(paths_backup) if img.shape[2] == 4: img = img[:, :, :3] im = img.transpose((2, 0, 1)) x = torch.tensor(np.asarray(im, dtype=np.float32), device='cpu', requires_grad=True).cuda() / 127.5 - 1. if x.shape[0] == 4: x = x[:3] needed_resolution = model.decoder.layer_to_resolution[-1] while x.shape[2] > needed_resolution: x = F.avg_pool2d(x, 2, 2) if x.shape[2] != needed_resolution: x = F.adaptive_avg_pool2d(x, (needed_resolution, needed_resolution)) img_src = ((x * 0.5 + 0.5) * 255).type(torch.long).clamp( 0, 255).cpu().type(torch.uint8).transpose(0, 2).transpose(0, 1).numpy() latents_original = encode(x[None, ...].cuda()) latents = latents_original[0, 0].clone() latents -= model.dlatent_avg.buff.data[0] for v, w in zip(attribute_values, W): v.value = (latents * w).sum() for v, w in zip(attribute_values, W): latents = latents - v.value * w return latents, latents_original, img_src def loadRandom(): latents = rnd.randn(1, cfg.MODEL.LATENT_SPACE_SIZE) lat = torch.tensor(latents).float().cuda() dlat = mapping_fl(lat) layer_idx = torch.arange(2 * layer_count)[np.newaxis, :, np.newaxis] ones = torch.ones(layer_idx.shape, dtype=torch.float32) coefs = torch.where(layer_idx < model.truncation_cutoff, ones, ones) dlat = torch.lerp(model.dlatent_avg.buff.data, dlat, coefs) x = decode(dlat)[0] img_src = ((x * 0.5 + 0.5) * 255).type(torch.long).clamp( 0, 255).cpu().type(torch.uint8).transpose(0, 2).transpose(0, 1).numpy() latents_original = dlat latents = latents_original[0, 0].clone() latents -= model.dlatent_avg.buff.data[0] for v, w in zip(attribute_values, W): v.value = (latents * w).sum() for v, w in zip(attribute_values, W): latents = latents - v.value * w return latents, latents_original, img_src latents, latents_original, img_src = loadNext() ctx.init(1800, 1600, "Styles") def update_image(w, latents_original): with torch.no_grad(): w = w + model.dlatent_avg.buff.data[0] w = w[None, None, ...].repeat(1, model.mapping_f.num_layers, 1) layer_idx = torch.arange(model.mapping_f.num_layers)[np.newaxis, :, np.newaxis] cur_layers = (7 + 1) * 2 mixing_cutoff = cur_layers styles = torch.where(layer_idx < mixing_cutoff, w, latents_original) x_rec = decode(styles) resultsample = ((x_rec * 0.5 + 0.5) * 255).type(torch.long).clamp( 0, 255) resultsample = resultsample.cpu()[0, :, :, :] return resultsample.type(torch.uint8).transpose(0, 2).transpose(0, 1) im_size = 2**(cfg.MODEL.LAYER_COUNT + 1) im = update_image(latents, latents_original) print(im.shape) im = bimpy.Image(im) display_original = True seed = 0 while not ctx.should_close(): with ctx: new_latents = latents + sum( [v.value * w for v, w in zip(attribute_values, W)]) if display_original: im = bimpy.Image(img_src) else: im = bimpy.Image(update_image(new_latents, latents_original)) bimpy.begin("Principal directions") bimpy.columns(2) bimpy.set_column_width(0, im_size + 20) bimpy.image(im) bimpy.next_column() for v, label in zip(attribute_values, labels): bimpy.slider_float(label, v, -40.0, 40.0) bimpy.checkbox("Randomize noise", randomize) if randomize.value: seed += 1 torch.manual_seed(seed) if bimpy.button('Next'): latents, latents_original, img_src = loadNext() display_original = True if bimpy.button('Display Reconstruction'): display_original = False if bimpy.button('Generate random'): latents, latents_original, img_src = loadRandom() display_original = False if bimpy.input_text( "Current file", current_file, 64) and os.path.exists(path + '/' + current_file.value): paths.insert(0, current_file.value) latents, latents_original, img_src = loadNext() bimpy.end()
if True: if bimpy.begin("", flags=(bimpy.WindowFlags.NoSavedSettings | bimpy.WindowFlags.NoMove | bimpy.WindowFlags.NoResize)): bimpy.text("NeX") bimpy.push_style_var(bimpy.Style.Alpha, 255) bimpy.set_window_size("", bimpy.Vec2(450, 250)) bimpy.text("") #bimpy.set_style(bimpy.GuiStyle.alpha) if MinCPS.value > MaxCPS.value: MinCPS = bimpy.Float(MaxCPS.value) if bimpy.collapsing_header("AutoClicker"): bimpy.slider_float("CPS Min", MinCPS, 5.0, 25.0) bimpy.slider_float("CPS Max", MaxCPS, 5.0, 25.0) if bimpy.button("Toggle"): Toggle = not Toggle if bimpy.collapsing_header("Colors"): bimpy.color_edit("Main Bar", BarColor) bimpy.color_edit("Headers", HeaderColor) bimpy.color_edit("Hovered Header", HeaderHoverColor) bimpy.color_edit("Text", TextColor) bimpy.color_edit("Slider Thumbs", SliderColor) bimpy.color_edit("Activated Thumbs", SliderActiveColor) bimpy.color_edit("CheckBox Marks", CheckMarkColor) bimpy.push_style_color(bimpy.Colors.TitleBgActive, BarColor) bimpy.push_style_color(bimpy.Colors.Header, HeaderColor) bimpy.push_style_color(bimpy.Colors.HeaderHovered, HeaderHoverColor) bimpy.push_style_color(bimpy.Colors.Text, TextColor) bimpy.push_style_color(bimpy.Colors.SliderGrab, SliderColor)
def sample(cfg, logger): model = Model(startf=cfg.MODEL.START_CHANNEL_COUNT, layer_count=cfg.MODEL.LAYER_COUNT, maxf=cfg.MODEL.MAX_CHANNEL_COUNT, latent_size=cfg.MODEL.LATENT_SPACE_SIZE, truncation_psi=cfg.MODEL.TRUNCATIOM_PSI, truncation_cutoff=cfg.MODEL.TRUNCATIOM_CUTOFF, mapping_layers=cfg.MODEL.MAPPING_LAYERS, channels=3) del model.discriminator model.eval() #torch.cuda.manual_seed_all(110) logger.info("Trainable parameters generator:") count_parameters(model.generator) if False: model_dict = { 'generator': model.generator, 'mapping': model.mapping, 'dlatent_avg': model.dlatent_avg, } else: model_dict = { 'generator_s': model.generator, 'mapping_s': model.mapping, 'dlatent_avg': model.dlatent_avg, } checkpointer = Checkpointer(cfg, model_dict, logger=logger, save=True) file_name = 'karras2019stylegan-ffhq' # file_name = 'results/model_final' checkpointer.load(file_name=file_name + '.pth') # checkpointer.save('final_stripped') #sample_b = torch.randn(1, cfg.MODEL.LATENT_SPACE_SIZE).view(-1, cfg.MODEL.LATENT_SPACE_SIZE) # for i in range(100): # if i % 20 == 0: # sample_a = sample_b # sample_b = torch.randn(1, cfg.MODEL.LATENT_SPACE_SIZE).view(-1, cfg.MODEL.LATENT_SPACE_SIZE) # x = (i % 20) / 20.0 # sample = sample_a * (1.0 - x) + sample_b * x # save_sample(model, sample, i) print(model.generator.get_statistics(8)) # print(model.discriminator.get_statistics(8)) ctx = bimpy.Context() ctx.init(1800, 1600, "Styles") rnd = np.random.RandomState(5) latents = rnd.randn(1, cfg.MODEL.LATENT_SPACE_SIZE) sample = torch.tensor(latents).float().cuda() def update_image(sample): with torch.no_grad(): model.eval() x_rec = model.generate(model.generator.layer_count - 1, 1, z=sample) resultsample = ((x_rec * 0.5 + 0.5) * 255).type(torch.long).clamp( 0, 255) resultsample = resultsample.cpu()[0, :, :, :] return resultsample.type(torch.uint8).transpose(0, 2).transpose(0, 1) im = update_image(sample) print(im.shape) im = bimpy.Image(im) while (not ctx.should_close()): with ctx: im = bimpy.Image(update_image(sample)) bimpy.image(im) # if bimpy.button('Ok'): if bimpy.button('NEXT'): latents = rnd.randn(1, cfg.MODEL.LATENT_SPACE_SIZE) sample = torch.tensor(latents).float().cuda() # im = bimpy.Image(update_image(sample)) #bimpy.set_window_font_scale(2.0) exit() rnd = np.random.RandomState(111011) latents = rnd.randn(1, cfg.MODEL.LATENT_SPACE_SIZE) sample = torch.tensor(latents).float().cuda( ) # torch.randn(16, cfg.MODEL.LATENT_SPACE_SIZE).view(-1, cfg.MODEL.LATENT_SPACE_SIZE) save_sample(model, sample, 0) im_count = 16 canvas = np.zeros([3, im_size * (im_count + 2), im_size * (im_count + 2)]) cut_layer_b = 0 cut_layer_e = 2 styles = model.mapping(sample) styles = list(styles.split(1, 1)) for i in range(im_count): torch.cuda.manual_seed_all(110) style = [x[i] for x in styles] style = torch.cat(style, dim=0)[None, ...] rec = model.generator.decode(style, cfg.MODEL.LAYER_COUNT - 1, 0.7) place(canvas, rec[0], 1, 2 + i) place(canvas, rec[0], 2 + i, 1) for i in range(im_count): for j in range(im_count): style_a = [x[i] for x in styles[:cut_layer_b]] style_b = [x[j] for x in styles[cut_layer_b:cut_layer_e]] style_c = [x[i] for x in styles[cut_layer_e:]] style = style_a + style_b + style_c torch.cuda.manual_seed_all(110) style = torch.cat(style, dim=0)[None, ...] rec = model.generator.decode(style, cfg.MODEL.LAYER_COUNT - 1, 0.7) place(canvas, rec[0], 2 + i, 2 + j) save_image(torch.Tensor(canvas), 'reconstruction.png')
bimpy.themes.set_light_theme() taille_cible = bimpy.Int(150) largeur_cible = bimpy.Int(150) while not ctx.should_close(): ctx.new_frame() bimpy.set_next_window_pos(bimpy.Vec2(0, 0), bimpy.Condition.Once) bimpy.set_next_window_size(bimpy.Vec2(800, 400), bimpy.Condition.Once) bimpy.begin("Controls") bimpy.input_text("Nom du fichier", nom, 15) if bimpy.button("Visualisation"): while (i < 1000000): num = i / 1000000 bimpy.progress_bar(num) bimpy.end() ctx.render() i = i + 1 if bimpy.button("Debut du Scan"): a = 2 if bimpy.button("Visualisation du resultat"): a = 3 bimpy.text("Choix des formats de sortie") bimpy.checkbox("VTK", vtk) bimpy.checkbox("STL", stl)
def render(self, ctx, windows_info): pos = bimpy.Vec2(conf.margin, conf.margin) size_min = bimpy.Vec2(conf.min_file_browser_width, ctx.height() - 2 * conf.margin) size_max = bimpy.Vec2(conf.max_file_browser_width, ctx.height() - 2 * conf.margin) bimpy.set_next_window_pos(pos, bimpy.Condition.Once) bimpy.set_next_window_size_constraints(size_min, size_max) bimpy.begin(LANG.file_brewswer_ui_title, bimpy.Bool(True), bimpy.WindowFlags.NoCollapse | bimpy.WindowFlags.NoMove) ###########UI########### if bimpy.button(LANG.file_brewswer_ui_refresh) == True: self.fb.refresh_file_list() bimpy.same_line() if bimpy.button(LANG.about) == True: bimpy.open_popup(LANG.about) # call render about ui # print(dir(windows_info['about_ui'])) windows_info['about_ui']['self'].about() for idx, f_name in enumerate(self.fb.file_list): # print(self.selected.value) if bimpy.selectable( f_name.split('\\')[-1], self.selected.value == idx): self.selected.value = idx if self.selected.value != -1 and self.selected.value != self.preidx: self.preidx = self.selected.value windows_info['image_shower_ui']['self'].update_pic(f_name) windows_info['meta_info_ui']['self'].update_meta_info( f_name) # progress bar if not self.fb.q.empty(): self.process = self.fb.q.get() f, d = self.process[-2], self.process[-1] # update if new if d != {}: self.fb.pp.yolo_res[f] = d self.process = (self.process[0] + 1, self.process[1]) if self.process[0] == self.process[1]: with open('yolo_res', 'wb') as f: pickle.dump(self.fb.pp.yolo_res, f) # build retrieval index windows_info['retrival_ui']['self'].init = False sz = bimpy.get_window_size() bimpy.set_cursor_pos(bimpy.Vec2(conf.margin, sz.y - conf.margin * 2)) bimpy.push_item_width(sz.x - conf.margin * 3 - 60) process = self.process bimpy.progress_bar(process[0] / float(process[1]), bimpy.Vec2(0.0, 0.0), "{}/{}".format(process[0], process[1])) bimpy.same_line() if bimpy.button(LANG.reindex) == True and process[0] == process[1]: self.fb.refresh() ######################## t = { 'x': bimpy.get_window_pos().x, 'y': bimpy.get_window_pos().y, 'w': bimpy.get_window_size().x, 'h': bimpy.get_window_size().y, 'self': self, } bimpy.end() return t
c = b.Context() c.init(1200, 1200, "bimpy test") img = Image.new( "RGBA", (512, 512), ) px = img.load() for x in range(512): for y in range(512): r = int(255.0 * float(x) / 512.0) g = int(255.0 * float(y) / 512.0) px[x, y] = (r, g, max(255 - r - g, 0), 255) b_img = b.Image(img) b_f1 = b.Float() b_f2 = b.Float() b_f3 = b.Float() while not c.should_close(): with c: b.text("hi") if b.button("cat"): print("mew") b.input_float("float1", b_f1, 0.0, 1.0) b.image(b_img) b.slider_float3("float", b_f1, b_f2, b_f3, 0.0, 1.0)
if bimpy.begin_main_menu_bar(): if bimpy.menu_item('Save', ''): save_data(args.save_path) if bimpy.menu_item('Load', ''): load_data(args.save_path) bimpy.end_main_menu_bar( ) # According to bimpy docs, this is a special case where end is called inside the if. if bimpy.begin("Video", opened=tab_video_view): is_placing_rect = True s = bimpy.text(args.base_path_video) b_i = bimpy.Int(display_frame) bimpy.slider_int("Frame", b_i, 0, video_len, "%d") if bimpy.button(" < Prev (z) ") or bimpy.is_key_released(ord('Z')): b_i.value -= 1 bimpy.same_line() bimpy.checkbox("Autoplay (c to stop)", is_autoplay) if bimpy.is_key_down(ord('C')): is_autoplay.value = False bimpy.same_line() if bimpy.button(" Next > (x) ") or bimpy.is_key_released( ord('X')) or is_autoplay.value: b_i.value += 1 if display_frame != b_i.value: simulate_to_frame(b_i.value) bimpy.combo('Label used for annotation', current_label_idx, all_labels)
def __buttons_window(self): bimpy.set_next_window_pos(bimpy.Vec2(5, 635), bimpy.Condition.Once) bimpy.set_next_window_size(bimpy.Vec2(1005, 128), bimpy.Condition.Once) bimpy.begin("Exercise Control", flags=bimpy.WindowFlags(4) | bimpy.WindowFlags(1) | bimpy.WindowFlags(2)) bimpy.push_font(self.fonts.fonts[16]["cond"]) bimpy.text_colored(bimpy.Vec4(1, 0, 0, 1), "Controls") bimpy.separator() bimpy.pop_font() bimpy.push_font(self.fonts.fonts[16]["cond"]) bimpy.text("") bimpy.same_line(0, 150) if self.pause_button_state == 1: bimpy.push_style_color(bimpy.Colors(0), bimpy.Vec4(0, 0, 0, 1)) bimpy.push_style_color(bimpy.Colors(21), bimpy.Vec4(0.8, 0.8, 0, 1)) bimpy.push_style_color(bimpy.Colors(22), bimpy.Vec4(1, 1, 0, 1)) bimpy.push_style_color(bimpy.Colors(23), bimpy.Vec4(0.5, 0.5, 0, 1)) pause_button_text = "Pause Exercise" elif self.pause_button_state == 0: bimpy.push_style_color(bimpy.Colors(0), bimpy.Vec4(0, 0, 0, 1)) bimpy.push_style_color(bimpy.Colors(21), bimpy.Vec4(0.0, 0.8, 0.0, 1)) bimpy.push_style_color(bimpy.Colors(22), bimpy.Vec4(0.0, 1, 0.0, 1)) bimpy.push_style_color(bimpy.Colors(23), bimpy.Vec4(0.0, 0.5, 0.0, 1)) pause_button_text = "Resume Exercise" elif self.pause_button_state == -1: bimpy.push_style_color(bimpy.Colors(0), bimpy.Vec4(0, 0, 0, 1)) bimpy.push_style_color(bimpy.Colors(21), bimpy.Vec4(0.4, 0.4, 0.4, 1)) bimpy.push_style_color(bimpy.Colors(22), bimpy.Vec4(0.4, 0.4, 0.4, 1)) bimpy.push_style_color(bimpy.Colors(23), bimpy.Vec4(0.4, 0.4, 0.4, 1)) pause_button_text = "------ -------" if bimpy.button(pause_button_text, bimpy.Vec2(250, 75)): if self.pause_button_state == 1: self.pause_button_state = 0 self.data.is_exercising = False elif self.pause_button_state == 0: self.pause_button_state = 1 self.data.is_exercising = True bimpy.pop_style_color() bimpy.pop_style_color() bimpy.pop_style_color() bimpy.pop_style_color() bimpy.same_line(450, 150) if self.stop_button_enabled: bimpy.push_style_color(bimpy.Colors(0), bimpy.Vec4(0, 0, 0, 1)) bimpy.push_style_color(bimpy.Colors(21), bimpy.Vec4(0.8, 0, 0, 1)) bimpy.push_style_color(bimpy.Colors(22), bimpy.Vec4(1, 0, 0, 1)) bimpy.push_style_color(bimpy.Colors(23), bimpy.Vec4(0.5, 0, 0, 1)) else: bimpy.push_style_color(bimpy.Colors(0), bimpy.Vec4(0, 0, 0, 1)) bimpy.push_style_color(bimpy.Colors(21), bimpy.Vec4(0.4, 0.4, 0.4, 1)) bimpy.push_style_color(bimpy.Colors(22), bimpy.Vec4(0.4, 0.4, 0.4, 1)) bimpy.push_style_color(bimpy.Colors(23), bimpy.Vec4(0.4, 0.4, 0.4, 1)) self.pause_button_state = -1 if bimpy.button("Stop Exercise", bimpy.Vec2(250, 75)): self.data.is_exercising = False self.stop_button_enabled = False bimpy.pop_style_color() bimpy.pop_style_color() bimpy.pop_style_color() bimpy.pop_style_color() bimpy.pop_font() bimpy.end()
def show_demo_window(): bp.begin_root(menu=True) # Menu Bar if bp.begin_menu_bar(): if bp.begin_menu("Menu"): bp.end_menu() if bp.begin_menu("Examples"): bp.end_menu() if bp.begin_menu("Tools"): bp.end_menu() bp.end_menu_bar() global clicked if bp.button("Button"): clicked += 1 if clicked & 1: bp.same_line() bp.text("Thanks for clicking me!") bp.checkbox("checkbox", check) bp.radio_button("radio a", e, 0) bp.same_line() bp.radio_button("radio b", e, 1) bp.same_line() bp.radio_button("radio c", e, 2) # Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. for i in range(7): if i > 0: bp.same_line() bp.push_id_int(i) bp.push_style_color(bp.Colors.Button, bp.Vec4(i / 7.0, 0.6, 0.6, 1.0)) bp.push_style_color(bp.Colors.ButtonHovered, bp.Vec4(i / 7.0, 0.7, 0.7, 1.0)) bp.push_style_color(bp.Colors.ButtonActive, bp.Vec4(i / 7.0, 0.8, 0.8, 1.0)) bp.button("Click") bp.pop_style_color(3) bp.pop_id() # Use AlignTextToFramePadding() to align text baseline to the baseline of framed elements (otherwise a Text+SameLine+Button sequence will have the text a little too high by default) bp.align_text_to_frame_padding() bp.text("Hold to repeat:") bp.same_line() # Arrow buttons with Repeater spacing = bp.get_style().item_inner_spacing.x bp.push_button_repeat(True) global counter if bp.arrow_button("##left", bp.Direction.Left): counter -= 1 bp.same_line(0.0, spacing) if bp.arrow_button("##right", bp.Direction.Right): counter += 1 bp.pop_button_repeat() bp.same_line() bp.text("%d" % counter) bp.text("Hover over me") if bp.is_item_hovered(): bp.set_tooltip("I am a tooltip") bp.same_line() bp.text("- or me") if bp.is_item_hovered(): bp.begin_tooltip() bp.text("I am a fancy tooltip") arr = [0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2] bp.plot_lines("Curve", arr) bp.end_tooltip() bp.separator() bp.label_text("label", "Value") # Using the _simplified_ one-liner Combo() api here # See "Combo" section for examples of how to use the more complete BeginCombo()/EndCombo() api. items = [ "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" ] bp.combo("combo", item_current, items) bp.same_line() help_marker( "Refer to the \"Combo\" section below for an explanation of the full BeginCombo/EndCombo API, and demonstration of various flags.\n" ) # To wire InputText() with std::string or any other custom string type, # see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. bp.input_text("input text", str0, 128) bp.same_line() help_marker( "USER:\nHold SHIFT or use mouse to select text.\n" "CTRL+Left/Right to word jump.\n" "CTRL+A or double-click to select all.\n" "CTRL+X,CTRL+C,CTRL+V clipboard.\n" "CTRL+Z,CTRL+Y undo/redo.\n" "ESCAPE to revert.\n\nPROGRAMMER:\nYou can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated in imgui_demo.cpp)." ) bp.end()