Beispiel #1
0
    def _show(self, ctx):
        # Show/adjust the weights
        if (not self.mlp.layers):
            bimpy.text("Warning: you need at least one layer")
            return

        # Select layer
        names = ["{ix} {str}".format(ix=ix, str=str(layer)) for ix,layer in enumerate(self.mlp.layers)]
        if (bimpy.combo("Layer", self.ui.layer_ix, names)):
            self.ui.neuron_ix.value = 0
        layer_ix = self.ui.layer_ix.value
        if (layer_ix < len(self.mlp.layers)):
            layer = self.mlp.layers[layer_ix]
            # Select neuron
            names = ["{ix}".format(ix=ix) for ix,neuron in enumerate(layer.neurons)]
            bimpy.combo("Neuron", self.ui.neuron_ix, names)
            neuron_ix = self.ui.neuron_ix.value
            if (neuron_ix < len(layer.neurons)):
                neuron = layer.neurons[neuron_ix]
                weights = [bimpy.Float(self.weights[neuron.weight_offset+ix]) for ix,_ in enumerate(neuron.input_ixs)]
                for ix,weight in enumerate(weights):
                    bimpy.slider_float("Weight {ix}".format(ix=ix), weight, *util.mm)
                    self.weights[neuron.weight_offset+ix] = weight.value

        if (self.mlp.layers[-1].nr_neurons != 1):
            bimpy.text("Warning: last layer should have only one output")
            return

        if (not self.setup()):
            return
Beispiel #2
0
    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)
Beispiel #3
0
    def _show(self, ctx):
        uif = bimpy.Float()

        uif.value = self.weight
        bimpy.slider_float("Weight", uif, *util.mm)
        self.weight = uif.value

        uif.value = self.bias
        bimpy.slider_float("Bias", uif, *util.mm)
        self.bias = uif.value
Beispiel #4
0
def show_io_plot(ui_input, model):
    if (not model.simulator):
        return
    bimpy.slider_float("Input", ui_input, *util.mm)

    outputs = model.compute_outputs(util.x_ary())
    bimpy.plot_lines("", outputs, 0, "", -1.0, 1.0, bimpy.Vec2(0,100))

    bimpy.same_line()

    output = bimpy.Float(model.compute_output(ui_input.value))
    bimpy.v_slider_float("Output", bimpy.Vec2(40,100), output, -1.0, 1.0)
Beispiel #5
0
def draw_window_drawing(ctx, w, h, name, points):

	bimpy.set_next_window_pos(bimpy.Vec2(w + 20, h + 20), bimpy.Condition.Once)
	bimpy.set_next_window_size(bimpy.Vec2(w, h), bimpy.Condition.Once)
	bimpy.begin(name)
	
	window_zero = bimpy.get_window_pos() + bimpy.Vec2(100 + temp_separation_test.value, 100 + temp_separation_test.value)
	window_one = bimpy.get_window_pos() + bimpy.Vec2(w - 100 - temp_separation_test.value, h - 100 - temp_separation_test.value)
	
	bimpy.add_circle_filled(window_zero, 5.0, 0xFF000000 + 0xc88200, 100)
	bimpy.add_circle_filled(window_one, 5.0, 0xFF000000 + 0x4bb43c, 100)

	for x,y in points:
		point = bimpy.get_window_pos() + bimpy.Vec2(x, y)
		bimpy.add_circle_filled(point, 5.0, 0xFF000000 + 0x4bb43c, 100)


	bimpy.slider_float("separation", temp_separation_test, 0.0, 100.0)

	bimpy.end()
Beispiel #6
0
    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))
Beispiel #7
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()
Beispiel #8
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)
Beispiel #9
0
    ctx.new_frame()

    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)
Beispiel #10
0
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()
Beispiel #11
0
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()
Beispiel #12
0
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)
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
Beispiel #14
0
    def draw_gui(self, config_server):

        frames = []

        if bimpy.button("Load Profile"):
            with open('config.txt', 'r') as f:
                lines = f.readlines()
                for index, server in enumerate(servers):
                    items = lines[index].split(' ')
                    server.orientation = int(items[0])
                    server.process = int(items[1])
        bimpy.same_line()

        if bimpy.button("Save Profile"):
            with open('config.txt', 'w') as f:
                for server in servers:
                    f.write('%d %d\n' % (server.orientation, server.process))
        bimpy.same_line()

        if bimpy.button("Identify"):
            self.identify = not self.identify
        bimpy.same_line()

        if bimpy.button("Print ports"):
            print(available_ports)

        bimpy.slider_float("Min Aspect Ratio", self.min_aspect_ratio, 0.0,
                           10.0)
        bimpy.new_line()

        for server in servers:
            bimpy.slider_float("Stream Width %d" % server.cam_id,
                               server.stream_width, 0, 640)
            bimpy.slider_float("Stream Height %d" % server.cam_id,
                               server.stream_height, 0, 480)

            if bimpy.button("Update %d" % server.cam_id):
                server.update_settings()
            bimpy.same_line()

            if bimpy.button("Add Processing %d" % server.cam_id):
                server.process = True
            bimpy.same_line()

            if bimpy.button("Remove Processing %d" % server.cam_id):
                server.process = False

            if bimpy.button("Rotate 90 %d" % server.cam_id):
                server.orientation += 90
            bimpy.same_line()

            if bimpy.button("Rotate -90 %d" % server.cam_id):
                server.orientation -= 90
            bimpy.same_line()

            if bimpy.button("Rotate 180 %d" % server.cam_id):
                server.orientation += 180
            '''
			if bimpy.button("V+ %d" % server.cam_id):
				server.V += 1
			bimpy.same_line()

			if bimpy.button("V- %d" % server.cam_id):
				server.V -= 1
			bimpy.same_line()

			if bimpy.button("H+ %d" % server.cam_id):
				server.H += 1
			bimpy.same_line()

			if bimpy.button("H- %d" % server.cam_id):
				server.H -= 1
			'''

            bimpy.new_line()
            bimpy.new_line()