def render(self, is_lock): bimpy.indent(10) bimpy.text('- Plane') bimpy.same_line() bimpy_tools.help_marker( 'generate with random points\n' \ '* plane random: random on whole plane\n' \ '* balanced random: balanced positive and negative samples' ) bimpy.push_item_width(140) if bimpy.begin_combo('strategy##plane_random_generator', self._select_strategy): for item in self._strategy_list: is_selected = bimpy.Bool(self._select_strategy == item) if bimpy.selectable(item, is_selected) and not is_lock: self._select_strategy = item if is_selected.value: bimpy.set_item_default_focus() bimpy.end_combo() bimpy.pop_item_width() bimpy.unindent(10)
def __init__(self): self._lr = bimpy.Float(0.001) self._betas_first = bimpy.Float(0.9) self._betas_second = bimpy.Float(0.999) self._eps = bimpy.Float(1e-8) self._weight_decay = bimpy.Float(0) self._amsgrad = bimpy.Bool(False)
def __init__(self): self._lr = bimpy.Float(0.1) self._momentum = bimpy.Float(0) self._dampening = bimpy.Float(0) self._weight_decay = bimpy.Float(0) self._nesterov = bimpy.Bool(False) self._hint_nesterov = False
def __init__(self, path): self._size = None self.opened = bimpy.Bool(True) self.click_states = defaultdict(bimpy.Bool) self.path = path self.name = '{0}##{1}'.format(path, get_next_count()) self.child_frames = [] self.tree = dict() self.load_card_data()
def render(self, is_lock): bimpy.indent(10) bimpy.text('- Linear layer init') bimpy.same_line() bimpy_tools.help_marker( 'Initializer used in torch.nn.Linear, use Kaiming uniform') bimpy.push_item_width(120) flags = bimpy.InputTextFlags.EnterReturnsTrue if is_lock: flags |= bimpy.InputTextFlags.ReadOnly if bimpy.input_float('a##sgd_optimizer', self._a, flags=flags): self._a.value = max(0.0, self._a.value) if bimpy.begin_combo('mode##linear_layer_init', self._select_mode): for item in self._mode_list: is_selected = bimpy.Bool(self._select_mode == item) if bimpy.selectable(item, is_selected) and not is_lock: self._select_mode = item if is_selected.value: bimpy.set_item_default_focus() bimpy.end_combo() if bimpy.begin_combo('nonlinearity##linear_layer_init', self._select_nonlinearity): for item in self._nonlinearity_list: is_selected = bimpy.Bool(self._select_nonlinearity == item) if bimpy.selectable(item, is_selected) and not is_lock: self._select_nonlinearity = item if is_selected.value: bimpy.set_item_default_focus() bimpy.end_combo() bimpy.pop_item_width() bimpy.unindent(10)
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 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 render(self, is_lock): bimpy.set_next_tree_node_open(True, bimpy.Condition.FirstUseEver) if not bimpy.tree_node('optimizer##optimizer_component'): return if bimpy.begin_combo('select##optimizer_component', self._select_optimizer): for item in self._optimizer_list: is_selected = bimpy.Bool(self._select_optimizer == item) if bimpy.selectable(item, is_selected) and not is_lock: self._select_optimizer = item if is_selected.value: bimpy.set_item_default_focus() bimpy.end_combo() self._optimizer_map[self._select_optimizer].render(is_lock) bimpy.tree_pop()
def render(self, is_lock): bimpy.indent(10) bimpy.text('- MSE loss') bimpy.same_line() bimpy_tools.help_marker('torch.nn.MSELoss') bimpy.push_item_width(120) if bimpy.begin_combo('reduction##mse_loss_fn', self._select_redution): for item in self._reduction_list: is_selected = bimpy.Bool(self._select_redution == item) if bimpy.selectable(item, is_selected) and not is_lock: self._select_redution = item if is_selected.value: bimpy.set_item_default_focus() bimpy.end_combo() bimpy.pop_item_width() bimpy.unindent(10)
def render(self, is_lock): bimpy.indent(10) bimpy.text('- Raw Point') bimpy.same_line() bimpy_tools.help_marker('generate with raw points') bimpy.push_item_width(120) if bimpy.begin_combo('strategy##raw_point_generator', self._select_strategy): for item in self._strategy_list: is_selected = bimpy.Bool(self._select_strategy == item) if bimpy.selectable(item, is_selected) and not is_lock: self._select_strategy = item if is_selected.value: bimpy.set_item_default_focus() bimpy.end_combo() bimpy.pop_item_width() bimpy.unindent(10)
active_annotations = {} return to_delete = [] for idx, a in active_annotations.items(): if a.idx in rect_db[old_frame]: a.next_frame(img_data, frame_idx) else: to_delete.append(idx) for idx in to_delete: del active_annotations[idx] # UI Tabs tab_video_view = bimpy.Bool(True) tab_rects = bimpy.Bool(True) tab_keyframes = bimpy.Bool(True) # Global state is_autoplay = bimpy.Bool(False) cursor_x1 = -10 cursor_y1 = -10 cursor_x2 = -10 cursor_y2 = -10 img_display_w = 0 img_display_h = 0 img_display_zero = bimpy.Vec2(0, 0) is_placing_rect = True end_rect_action = None
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))
import bimpy import time import random from win32api import GetKeyState import win32api from pynput.mouse import Button, Controller ctx = bimpy.Context() MinCPS = bimpy.Float(8.5) MaxCPS = bimpy.Float(10.9) OnlyOneHeader = bimpy.Bool(True) Toggle = 0 mouseclick = Controller() MinDelay = 1000 MaxDelay = 1000 BaseDelay = 1000 BarColor = bimpy.Vec4(0.16078431, 0.2901960, 0.47843137, 0.95) HeaderColor = bimpy.Vec4(0.25882352, 0.58823529, 0.9803921568, 0.95) HeaderHoverColor = bimpy.Vec4(0.43529411, 0.694117647, 0.9803921568, 0.95) TextColor = bimpy.Vec4(1, 1, 1, 1) SliderColor = bimpy.Vec4(0.06078431, 0.1901960, 0.47843137, 0.95) SliderActiveColor = bimpy.Vec4(0.16078431, 0.2901960, 0.47843137, 0.95) CheckMarkColor = bimpy.Vec4(0.43529411, 0.694117647, 0.9803921568, 0.95) ctx.init(520, 320, "") print("Loading...") while (not ctx.should_close()): ctx.new_frame() if True:
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()
ctx.init(1200, 768, "Spotify Collage") playlist_url = bimpy.String() b_col_count = bimpy.Int(0) refresh = False COL_COUNT = 8 saved = "" saved_time = 0 credentials = oauth2.SpotifyClientCredentials(*get_credentials()) while (not ctx.should_close()): with ctx: # bimpy.themes.set_light_theme() bimpy.set_next_window_pos(bimpy.Vec2(20, 20), bimpy.Condition.Once) bimpy.set_next_window_size(bimpy.Vec2(600, 600), bimpy.Condition.Once) bimpy.begin( "Track Listing", bimpy.Bool(True), bimpy.WindowFlags.HorizontalScrollbar | bimpy.WindowFlags.NoSavedSettings) bimpy.text('Spotify Playlist URI') bimpy.same_line() bimpy.input_text('', playlist_url, 255) if not playlist_downloading and not imgs_downloading: if bimpy.button("Fetch##Fetcher"): # data = fetch_playlist() # this blocks so let's use a thread thread = threading.Thread(target=fetch_playlist, args=(playlist_url.value.strip(), )) thread.start() elif imgs_downloading: bimpy.button("Fetching album covers...") elif playlist_downloading: bimpy.button("Fetching...")
def render(self, ctx, windows_info): # calculate autoly self.pos = bimpy.Vec2( windows_info['file_brewswer_ui']['x'] + windows_info['file_brewswer_ui']['w'] + conf.margin, conf.margin) self.size = bimpy.Vec2( ctx.width() - self.pos.x - conf.margin, ctx.height() - 3 * conf.margin - conf.meta_info_height) bimpy.set_next_window_pos(self.pos, bimpy.Condition.Always) bimpy.set_next_window_size(self.size, bimpy.Condition.Always) bimpy.begin( LANG.image_shower_ui_title, bimpy.Bool(True), bimpy.WindowFlags.NoCollapse | bimpy.WindowFlags.NoMove | bimpy.WindowFlags.NoResize | bimpy.WindowFlags.HorizontalScrollbar) ###########UI########### # modal part if self.im is not None: bimpy.set_cursor_pos(bimpy.Vec2(0.0, conf.margin * 3)) bimpy.image(self.im) # if image is loaded if self.labels is not None: for i, label in enumerate(self.labels): color = self.COLORS[self.classes.index(label)] # print((self.bbox[i][0], self.bbox[i][1] - 10)) # show on the left bottom of the picture bimpy.set_cursor_pos( bimpy.Vec2(self.bbox[i][0] + 10, self.bbox[i][3] + 10)) # set style bimpy.push_id_int(i) if conf.show_yolo_confience: bimpy.button( label + ' ' + str(format(self.confidence[i] * 100, '.2f')) + '%') else: bimpy.button(label) if bimpy.is_item_hovered(i): s = "{} ({})\n{}" label = label[0].upper() + label[1:] s = s.format( label, str(format(self.confidence[i] * 100, '.2f')) + '%', LANG.click_to_view_more) bimpy.set_tooltip(s) if bimpy.is_item_active(): self.select_label = label bimpy.pop_id() # bimpy.set_cursor_pos(bimpy.Vec2(conf.margin, self.size.y - conf.margin * 2)) bimpy.set_cursor_pos(bimpy.Vec2(conf.margin, conf.margin * 1.5)) if bimpy.button(LANG.smart_analyse) == True: self.object_detection() bimpy.same_line() bimpy.checkbox(LANG.auto, self.auto) ### Resize ### bimpy.same_line() bimpy.push_item_width(150) bimpy.drag_float(LANG.drag, self.scale, 1.0, 10, 1000) bimpy.pop_item_width() if abs(self.last_scale - self.scale.value) > 4.: xx = self.size.x * self.scale.value / 100. yy = (self.size.y - 45 - 40) * self.scale.value / 100. im = self.i_s.resize(self.raw_im, xx, yy) self.now_im = im self.set_im(im) # set to save computation self.last_scale = self.scale.value # if selected obj if self.select_label != '': # print(self.select_label) windows_info['retrival_ui'][ 'self'].select_label = self.select_label bimpy.open_popup('{}: {}'.format(LANG.retrieve, self.select_label)) # reset self.select_label = '' windows_info['retrival_ui']['self'].retrival() ######################## 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
def render(self, ctx, windows_info): # calculate autoly pos = bimpy.Vec2( windows_info['file_brewswer_ui']['x'] + windows_info['file_brewswer_ui']['w'] + conf.margin, windows_info['image_shower_ui']['y'] + windows_info['image_shower_ui']['h'] + conf.margin) size = bimpy.Vec2(ctx.width() - pos.x - conf.margin, conf.meta_info_height) bimpy.set_next_window_pos(pos, bimpy.Condition.Always) bimpy.set_next_window_size(size, bimpy.Condition.Always) bimpy.begin( "", bimpy.Bool(True), bimpy.WindowFlags.NoCollapse | bimpy.WindowFlags.NoMove | bimpy.WindowFlags.NoResize | bimpy.WindowFlags.NoTitleBar | bimpy.WindowFlags.NoScrollbar) ###########UI########### if self.meta_info is not None: ####LINE1#### self.meta_info.setdefault('ImageWidth', '') self.meta_info.setdefault('ImageLength', '') bimpy.text('{}:{}x{}'.format(LANG.meta_size, self.meta_info['ImageWidth'], self.meta_info['ImageLength'])) bimpy.same_line(size.x / 3) self.meta_info.setdefault('DateTimeOriginal', '') bimpy.text('{}:{}'.format(LANG.meta_date, self.meta_info['DateTimeOriginal'])) bimpy.same_line(size.x / 3 * 2) self.meta_info.setdefault('Make', '') self.meta_info.setdefault('Model', '') bimpy.text('{}:{} {}'.format(LANG.meta_device, self.meta_info['Make'], self.meta_info['Model'])) ####LINE2#### self.meta_info.setdefault('FocalLength', '') bimpy.text('{}:{}'.format(LANG.meta_focal_length, self.meta_info['FocalLength'])) bimpy.same_line(size.x / 3) self.meta_info.setdefault('ExposureTime', '') # truncate too high number try: x, y = self.meta_info['ExposureTime'] self.meta_info['ExposureTime'] = (x % 1000, y % 1000) except: pass bimpy.text('{}:{}'.format(LANG.meta_exposure_time, self.meta_info['ExposureTime'])) bimpy.same_line(size.x / 3 * 2) self.meta_info.setdefault('ISOSpeedRatings', '') bimpy.text('{}:{}'.format(LANG.meta_ISO_speed_ratings, self.meta_info['ISOSpeedRatings'])) ####LINE3#### bimpy.text('{}:({},{})'.format(LANG.meta_GPS, round(self.lat, 1), round(self.lon, 1))) bimpy.same_line(size.x / 3) bimpy.text('{}:{}'.format(LANG.meta_location, self.location)) ######################## 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
class image_shower_ui: i_s = image_shower() raw_im = None im = None labels = None now_im = None scale = bimpy.Float(100.0) last_scale = 100.0 auto = bimpy.Bool(False) select_label = '' def render(self, ctx, windows_info): # calculate autoly self.pos = bimpy.Vec2( windows_info['file_brewswer_ui']['x'] + windows_info['file_brewswer_ui']['w'] + conf.margin, conf.margin) self.size = bimpy.Vec2( ctx.width() - self.pos.x - conf.margin, ctx.height() - 3 * conf.margin - conf.meta_info_height) bimpy.set_next_window_pos(self.pos, bimpy.Condition.Always) bimpy.set_next_window_size(self.size, bimpy.Condition.Always) bimpy.begin( LANG.image_shower_ui_title, bimpy.Bool(True), bimpy.WindowFlags.NoCollapse | bimpy.WindowFlags.NoMove | bimpy.WindowFlags.NoResize | bimpy.WindowFlags.HorizontalScrollbar) ###########UI########### # modal part if self.im is not None: bimpy.set_cursor_pos(bimpy.Vec2(0.0, conf.margin * 3)) bimpy.image(self.im) # if image is loaded if self.labels is not None: for i, label in enumerate(self.labels): color = self.COLORS[self.classes.index(label)] # print((self.bbox[i][0], self.bbox[i][1] - 10)) # show on the left bottom of the picture bimpy.set_cursor_pos( bimpy.Vec2(self.bbox[i][0] + 10, self.bbox[i][3] + 10)) # set style bimpy.push_id_int(i) if conf.show_yolo_confience: bimpy.button( label + ' ' + str(format(self.confidence[i] * 100, '.2f')) + '%') else: bimpy.button(label) if bimpy.is_item_hovered(i): s = "{} ({})\n{}" label = label[0].upper() + label[1:] s = s.format( label, str(format(self.confidence[i] * 100, '.2f')) + '%', LANG.click_to_view_more) bimpy.set_tooltip(s) if bimpy.is_item_active(): self.select_label = label bimpy.pop_id() # bimpy.set_cursor_pos(bimpy.Vec2(conf.margin, self.size.y - conf.margin * 2)) bimpy.set_cursor_pos(bimpy.Vec2(conf.margin, conf.margin * 1.5)) if bimpy.button(LANG.smart_analyse) == True: self.object_detection() bimpy.same_line() bimpy.checkbox(LANG.auto, self.auto) ### Resize ### bimpy.same_line() bimpy.push_item_width(150) bimpy.drag_float(LANG.drag, self.scale, 1.0, 10, 1000) bimpy.pop_item_width() if abs(self.last_scale - self.scale.value) > 4.: xx = self.size.x * self.scale.value / 100. yy = (self.size.y - 45 - 40) * self.scale.value / 100. im = self.i_s.resize(self.raw_im, xx, yy) self.now_im = im self.set_im(im) # set to save computation self.last_scale = self.scale.value # if selected obj if self.select_label != '': # print(self.select_label) windows_info['retrival_ui'][ 'self'].select_label = self.select_label bimpy.open_popup('{}: {}'.format(LANG.retrieve, self.select_label)) # reset self.select_label = '' windows_info['retrival_ui']['self'].retrival() ######################## 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 def update_pic(self, f_name): # init self.scale = bimpy.Float(100.0) self.last_scale = 100.0 # resize and update pic by message im = Image.open(f_name) self.raw_im = im im = self.i_s.resize(im, self.size.x, self.size.y - 45 - 40) self.now_im = im self.set_im(im) # reset self.labels = None if self.auto.value == True: self.object_detection() def object_detection(self): img = np.asarray(self.now_im) self.bbox, self.labels, self.confidence = cv.detect_common_objects(img) self.COLORS = np.random.uniform(0, 255, size=(80, 3)) self.classes = populate_class_labels() for i, label in enumerate(self.labels): color = self.COLORS[self.classes.index(label)] if True: label += ' ' + str(format(self.confidence[i] * 100, '.2f')) + '%' cv2.rectangle(img, (self.bbox[i][0], self.bbox[i][1]), (self.bbox[i][2], self.bbox[i][3]), color, 2) # cv2.putText(img, label, # (self.bbox[i][0], self.bbox[i][1] - 10), # cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2) self.set_im(img) def set_im(self, im): self.im = bimpy.Image(im)
import bimpy import sys i = 0 a = 0 vtk = bimpy.Bool(False) stl = bimpy.Bool(False) obj = bimpy.Bool(False) ply = bimpy.Bool(False) pcd = bimpy.Bool(False) nom = bimpy.String() atx ctx = bimpy.Context() ctx.init(800, 400, "Scanner 3D") with ctx: bimpy.themes.set_light_theme() taille_cible = bimpy.Int(150) largeur_cible = bimpy.Int(150)
def edit_config(cfg): bimpy.begin("Parameters") ret = False bimpy.columns(2) bimpy.text("Stretch") bimpy.next_column() if edit_autofloat(cfg.stretch, "stretch", ps.ConfigurationInfo.stretch): ret = True bimpy.next_column() bimpy.separator() bimpy.text("Window Size") bimpy.next_column() r = ranged_slider("windowSize", cfg.windowSize, ps.ConfigurationInfo.windowSize) if r != None: cfg.windowSize = r ret = True bimpy.next_column() bimpy.separator() bimpy.text("Onset Sensitivity") bimpy.next_column() r = ranged_slider("onsetSensitivity", cfg.onsetSensitivity, ps.ConfigurationInfo.onsetSensitivity) if r != None: cfg.onsetSensitivity = r ret = True bimpy.next_column() bimpy.separator() bimpy.separator() bimpy.text("Harmonics:") #bimpy.separator() bimpy.next_column() b = bimpy.Bool(cfg.harmonics) if bimpy.checkbox("##harmonics", b): cfg.harmonics = b.value bimpy.next_column() bimpy.separator() if b.value: bimpy.text("Freq") bimpy.next_column() r = ranged_slider("hFreq", cfg.hFreq, ps.ConfigurationInfo.hFreq) if r != None: cfg.hFreq = r ret = True bimpy.next_column() bimpy.separator() bimpy.text("Bandwidth") bimpy.next_column() r = ranged_slider("hBandwidth", cfg.hBandwidth, ps.ConfigurationInfo.hBandwidth) if r != None: cfg.hBandwidth = r ret = True bimpy.next_column() bimpy.separator() bimpy.text("Count") #bimpy.separator() bimpy.next_column() # bimpy.text(str(cfg.hNumberHarm)) r = ranged_slider("hNumberHarm", cfg.hNumberHarm, ps.ConfigurationInfo.hNumberHarm) if r != None: cfg.hNumberHarm = r ret = True bimpy.next_column() bimpy.separator() bimpy.text("Gaussian") #bimpy.separator() bimpy.next_column() bimpy.text(str(cfg.hGauss)) # r = ranged_slider("hGauss",cfg.hGauss, ps.ConfigurationInfo.hGauss) # if r != None: # cfg.hGauss = r # ret = True bimpy.next_column() bimpy.separator() bimpy.separator() bimpy.text("Pitch Shift") bimpy.next_column() b = bimpy.Bool(cfg.pitchShift) if bimpy.checkbox("##pitchShift", b): cfg.pitchShift = b.value bimpy.next_column() bimpy.separator() if b.value: bimpy.text("Cents") #bimpy.separator() bimpy.next_column() # bimpy.text(str(cfg.psCents)) r = ranged_slider("psCents", cfg.psCents, ps.ConfigurationInfo.psCents) if r != None: cfg.psCents = r ret = True bimpy.next_column() bimpy.separator() bimpy.separator() bimpy.text("Freq Shift") #bimpy.separator() bimpy.next_column() b = bimpy.Bool(cfg.freqShift) if bimpy.checkbox("##freqShift", b): cfg.freqShift = b.value bimpy.next_column() bimpy.separator() if b.value: bimpy.text("Freq") #bimpy.separator() bimpy.next_column() # bimpy.text(str(cfg.fsFreq)) r = ranged_slider("fsFreq", cfg.fsFreq, ps.ConfigurationInfo.fsFreq) if r != None: cfg.fsFreq = r ret = True bimpy.next_column() bimpy.separator() bimpy.separator() bimpy.text("Filter") #bimpy.separator() bimpy.next_column() b = bimpy.Bool(cfg.filter) if bimpy.checkbox("##filter", b): cfg.filter = b.value bimpy.next_column() bimpy.separator() if b.value: bimpy.text("Freq 1") #bimpy.separator() bimpy.next_column() # bimpy.text(str(cfg.fFreq1)) r = ranged_slider("fFreq1", cfg.fFreq1, ps.ConfigurationInfo.fFreq1) if r != None: cfg.fFreq1 = r ret = True bimpy.next_column() bimpy.separator() bimpy.text("Freq 2") #bimpy.separator() bimpy.next_column() # bimpy.text(str(cfg.fFreq2)) r = ranged_slider("fFreq2", cfg.fFreq2, ps.ConfigurationInfo.fFreq2) if r != None: cfg.fFreq2 = r ret = True bimpy.next_column() bimpy.separator() bimpy.text("Arbitrary Freq") #bimpy.separator() bimpy.next_column() edit_autofloat(cfg.fFreqArbitrary, "fFreqArbitrary", ps.ConfigurationInfo.fFreqArbitrary) bimpy.next_column() bimpy.separator() bimpy.text("Bandstop") #bimpy.separator() bimpy.next_column() bimpy.text(str(cfg.fBandstop)) bimpy.next_column() bimpy.separator() bimpy.separator() bimpy.text("Tonal / Noise") #bimpy.separator() bimpy.next_column() b = bimpy.Bool(cfg.tonalNoise) if bimpy.checkbox("##tonalNoise", b): cfg.tonalNoise = b.value #bimpy.text(str(cfg.tonalNoise)) bimpy.next_column() bimpy.separator() if b.value: bimpy.text("Amount") #bimpy.separator() bimpy.next_column() # bimpy.text(str(cfg.tnAmount)) r = ranged_slider("tnAmount", cfg.tnAmount, ps.ConfigurationInfo.tnAmount) if r != None: cfg.tnAmount = r ret = True bimpy.next_column() bimpy.separator() bimpy.text("Bandwidth") #bimpy.separator() bimpy.next_column() # bimpy.text(str(cfg.tnBandwidth)) r = ranged_slider("tnBandwidth", cfg.tnBandwidth, ps.ConfigurationInfo.tnBandwidth) if r != None: cfg.tnBandwidth = r ret = True bimpy.next_column() bimpy.separator() bimpy.separator() bimpy.text("Compress") #bimpy.separator() bimpy.next_column() # bimpy.text(str(cfg.compress)) b = bimpy.Bool(cfg.compress) if bimpy.checkbox("##compress", b): cfg.compress = b.value bimpy.next_column() bimpy.separator() bimpy.separator() bimpy.text("Binaural") #bimpy.separator() bimpy.next_column() edit_autofloat(cfg.binaural, "binaural", ps.ConfigurationInfo.binaural) bimpy.next_column() bimpy.separator() bimpy.end() return ret
def view_legacy_controller(pl): bimpy.begin("Single File") bimpy.text("No file" if not ViewConfig.fileName else ViewConfig.fileName) if bimpy.button("Open File"): fn = askopenfilename(filetypes=(("WAV files", "*.wav"), ("AIFF files", "*.aif"))) if fn: _lc.OpenFile(fn) ViewConfig.fileName = fn bimpy.text("No configuration file" if not ViewConfig.configFileName else ViewConfig.configFileName) if bimpy.button("Open Configuration"): fn = askopenfilename(filetypes=(("JSON files", "*.ps.json"), ("All files", "*.*"))) if bimpy.button("Save Configuration"): pass bimpy.separator() vcfg = bimpy.Bool(ViewConfig.showParameters) if bimpy.checkbox("Edit Configuration", vcfg): ViewConfig.showParameters = vcfg.value bimpy.separator() if (not _lc.IsPlaying()): if bimpy.button("Play"): _lc.Play() bimpy.same_line() if (_lc.IsPlaying()): if bimpy.button("Stop"): _lc.Stop() bimpy.same_line() f = bimpy.Float(_lc.GetSeek()) if bimpy.slider_float("##seek", f, 0, 1): if (not _lc.IsPlaying()): _lc.Seek(f.value) #bimpy.text(str(_lc.GetSeek())); bimpy.separator() bimpy.slider_float("Start##region_start", bimpy.Float(0), 0, 1) bimpy.slider_float("End##region_end", bimpy.Float(1), 0, 1) if bimpy.button("Render file (default)"): path = os.path.abspath(__file__) output_file = os.path.dirname(path) + "/render.wav" _lc.RenderToFile(output_file) # bimpy.text("render: "+str(_lc.GetRenderPercent())) # if bimpy.button("Cancel"): # _lc.CancelRender() # if bimpy.button("Render async (default)"): # path = os.path.abspath(__file__) # output_file = os.path.dirname(path)+"/render_async.wav" # _lc.RenderToFileAsync(output_file) # bimpy.text(str(_lc.GetRenderPercent())) # bimpy.button("Cancel Render") # # if bimpy.button("Render Task"): # if not ViewConfig.renderTask: # path = os.path.abspath(__file__) # input_file = os.path.dirname(path)+"/test_file.wav" # output_file = os.path.dirname(path)+"/render-task.wav" # # ViewConfig.renderTask = ps.LegacyRenderTask(input_file, output_file, _lc.RenderRange(), _lc.Parameters()); # ViewConfig.renderTask.StartRender() # if ViewConfig.renderTask: # bimpy.text(str(ViewConfig.renderTask.GetRenderPercent())) # bimpy.button("Cancel Render") # bimpy.end() # if ViewConfig.showParameters: #cfg = _lc.Parameters() if edit_config(_parameters) == True: _lc.SetParameters(_parameters) print("edit") pass
import bimpy import pkg_resources print(pkg_resources.get_distribution("bimpy").version) ctx = bimpy.Context() ctx.init(1200, 1200, "Hello") with ctx: bimpy.themes.set_light_theme() opened = bimpy.Bool(True) a = 0.0 mylist = ["aaa", "bbb", "ccc"] selectedItem = bimpy.Int() vals = [0., 0.1, 0.2, 0.1, 0.4, 0.2] while (not ctx.should_close()): ctx.new_frame() 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")
def value(self, val): self._value = val[0] for key, pos in self.bitmap.items(): self.bitmap_values[key] = bimpy.Bool(self._test_bit(pos))
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 from bimpy.utils import help_marker check = bp.Bool(True) e = bp.Int(0) clicked = 0 counter = 0 item_current = bp.Int(0) str0 = bp.String("Hello, world!") buf = bp.String("\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e") 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"):
def __init__(self): self._size = None self.opened = bimpy.Bool(True) self.click_states = defaultdict(bimpy.Bool)
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