示例#1
0
    def do_execute(self, code, silent=False, store_history=True, user_expressions=None, allow_stdin=True):
        """Called when the user inputs code"""
        self.shell.get_ipython().set_next_input("Hi")
        messages = self.GFRepl.handle_input(code)
        graphs = []
        trees = []
        for msg in messages:
            if msg['trees']:
                trees = msg['trees']
            if msg['message']:
                self.send_response(
                    self.iopub_socket, 'display_data', to_display_data(msg['message']))

            elif msg['graph']:
                graphs.append(msg['graph'])

        if len(graphs) > 1:
            dd = widgets.Dropdown(
                layout={'width': 'max-content'},
                options=trees,
                value=trees[0],
                description='Tree of:',
                disabled=False,
            )
            file_name = self.GFRepl.convert_to_png(graphs[0])
            with open(file_name, "rb") as f:
                img = f.read()
            image = widgets.Image(value=img, format='png')
            self.send_response(
                    self.iopub_socket, 'display_data', to_display_data('%s graphs generated' % (len(graphs))))

            def on_value_change(change):
                file_index = trees.index(change['new'])
                file_name = self.GFRepl.convert_to_png(graphs[file_index])
                with open(file_name, "rb") as f:
                    img = f.read()
                image.value = img

            dd.observe(on_value_change, names='value')
            display(dd, image)
        elif len(graphs) == 1:
            file_name = self.GFRepl.convert_to_png(graphs[0])
            try:
                with open(file_name, "rb") as f:
                    img = f.read()
                display(widgets.Image(value=img, format='png'))
            except:
                self.send_response(self.iopub_socket, 'display_data', to_display_data(
                    "There is no tree to show!"))

        return {'status': 'ok',
                # The base class increments the execution count
                'payload': [],
                'execution_count': self.execution_count,
                'user_expressions': {},
                }
示例#2
0
    def do_execute(self,
                   code,
                   silent=False,
                   store_history=True,
                   user_expressions=None,
                   allow_stdin=True):
        """Called when the user inputs code"""
        # img_data = Image.open('/home/kai/gf_content/out.png','r')
        messages = self.GFRepl.handle_input(code)
        for msg in messages:
            if msg['file']:
                file_name = msg['file']
                try:
                    with open(file_name, "rb") as f:
                        img = f.read()
                    display(widgets.Image(value=img, format='png'))
                except:
                    self.send_response(
                        self.iopub_socket, 'display_data',
                        to_display_data("There is no tree to show!"))

            elif msg['message']:
                self.send_response(self.iopub_socket, 'display_data',
                                   to_display_data(msg['message']))

            elif msg['trees']:
                dd = widgets.Dropdown(
                    layout={'width': 'max-content'},
                    options=msg['trees'],
                    value=msg['trees'][0],
                    description='Tree of:',
                    disabled=False,
                )
                file_name = self.GFRepl.handle_single_view(
                    "%s %s" % (msg['tree_type'], msg['trees'][0]))
                with open(file_name, "rb") as f:
                    img = f.read()
                image = widgets.Image(value=img, format='png')

                def on_value_change(change):
                    file_name = self.GFRepl.handle_single_view(
                        "%s %s" % (msg['tree_type'], change['new']))
                    with open(file_name, "rb") as f:
                        img = f.read()
                    image.value = img

                dd.observe(on_value_change, names='value')
                display(dd, image)

        return {
            'status': 'ok',
            # The base class increments the execution count
            'payload': [],
            'execution_count': self.execution_count,
            'user_expressions': {},
        }
示例#3
0
 def make_img(self, file_path, height='250px', width='300px', format='jpg'):
     "Returns an image widget for specified file name."
     with open(file_path, 'rb') as opened:
         read_file = opened.read()
         return widgets.Image(value=read_file,
                              format=format,
                              layout=Layout(width=width, height=height))
示例#4
0
 def display_images_widgets(self, fnames: list) -> None:
     "Display a few preview images in the notebook"
     imgs = [
         widgets.Image(value=open(f, 'rb').read(), width='200px')
         for f in fnames
     ]
     self._img_pane.children = tuple(imgs)
示例#5
0
 def __init__(self, rl_ch=12, ud_ch=13, bus=1):
     self.sg = ServoGroup(rl_ch=rl_ch, ud_ch=ud_ch, bus=bus)
     self.sg.reset()  #Pan and tilt go to default position
     #Setup various widgets
     self.panel_step_move = NineButton(
         button_list=['↖', '↑', '↗', '←', 'reset', '→', '↙', '↓', '↘'])
     self.panel_far_move = NineButton(
         button_list=['◤', '▲', '◥', '◄', 'reset', '►', '◣', '▼', '◢'])
     self.image_widget = widgets.Image(
         format='jpeg', width=400, height=300)  #Display resolution setting
     self.snap_count = widgets.IntText(description='count:',
                                       layout=widgets.Layout(width='140px'),
                                       value=0)
     self.rl_textbox = widgets.IntText(layout=widgets.Layout(width='140px'),
                                       value=self.sg.read()[0],
                                       description='rl:')
     self.ud_textbox = widgets.IntText(layout=widgets.Layout(width='140px'),
                                       value=self.sg.read()[1],
                                       description='ud:')
     self.rl_slider = widgets.FloatSlider(min=-1,
                                          max=1,
                                          value=0,
                                          step=0.02,
                                          description='rl')
     self.ud_slider = widgets.FloatSlider(min=-1,
                                          max=1,
                                          value=0,
                                          step=0.02,
                                          description='ud')
     self.snap_dir = 'snap'  #Folder name for saving snapshot
     self.camera_link = None
     self.press_count = 0
示例#6
0
 def __init__(self, g=nx.DiGraph()):
     self.graph=g
     self.add_nodew=widgets.Text(placeholder='Type label of new state')
     self.add_node_buttonw=widgets.Button(description='Add state')
     self.del_node_buttonw=widgets.Button(description='Del state')
            
     self.node_box=VBox([self.add_nodew, 
                         HBox([self.add_node_buttonw, self.del_node_buttonw])
                         ])
     
     self.select_nodew=widgets.Dropdown(description='Select state')
     
     self.add_node_attr_labelw=widgets.Text(placeholder='Type label of new state attribute')
     self.add_node_attr_valuew=widgets.Text(placeholder='Type value of new state attribute')
     self.add_node_attr_buttonw=widgets.Button(description='Add attribute to state')
     self.del_node_attr_buttonw=widgets.Button(description='Del attribute from state')
     
     self.node_attr_box=VBox([self.select_nodew, 
                              VBox([self.add_node_attr_labelw, self.add_node_attr_valuew]), 
                              HBox([self.add_node_attr_buttonw, self.del_node_attr_buttonw])
                              ])
     
     self.from_nodew = widgets.Dropdown(description='From state', options=[])
     self.to_nodew = widgets.Dropdown(description='To state', options=[])
     self.from_to_pw=widgets.Text(placeholder = 'Type probability', description = 'Probability', value='0')
     self.add_edge_buttonw=widgets.Button(description='Add edge')
     self.del_edge_buttonw=widgets.Button(description='Del edge')
     
     self.edge_box=VBox([VBox([self.from_nodew, self.to_nodew]),
                         self.from_to_pw,                                     
                         HBox([self.add_edge_buttonw, self.del_edge_buttonw])
                         ])
     
     self.add_edge_attr_labelw=widgets.Text(placeholder='Type label of new edge attribute')
     self.add_edge_attr_valuew=widgets.Text(placeholder='Type value of new edge attribute')
     self.add_edge_attr_buttonw=widgets.Button(description='Add attribute to edge')
     self.del_edge_attr_buttonw=widgets.Button(description='Del attribute from edge')
     
     self.edge_attr_box=VBox([VBox([self.add_edge_attr_labelw, self.add_edge_attr_valuew]), 
                                 HBox([self.add_edge_attr_buttonw, self.del_edge_attr_buttonw])])     
                              
     self.graphw=widgets.Image()
                              
     self.left_menu = VBox([self.node_box,
                            self.node_attr_box,
                            self.edge_box,
                            self.edge_attr_box])
 
     self.box=HBox([self.left_menu, self.graphw])
     
     display(self.box)
     
     self.add_nodew.on_submit(self.add_node)
     self.del_node_buttonw.on_click(self.del_node)
     self.add_edge_buttonw.on_click(self.add_edge)
     self.del_edge_buttonw.on_click(self.del_edge)
     
     self.add_node_attr_buttonw.on_click(self.add_node_attr)
     self.add_edge_attr_buttonw.on_click(self.add_edge_attr)
示例#7
0
 def make_img_widget(self,
                     img,
                     height='250px',
                     width='300px',
                     format='jpg'):
     "Returns an image widget for specified file name."
     return widgets.Image(value=img,
                          format=format,
                          layout=Layout(width=width, height=height))
示例#8
0
    def how_to_combine(self):
        _file = open("__docs/combine_images/geometric_mean.png", 'rb')
        _geo_image = _file.read()
        geo_box = widgets.HBox([widgets.Label("Geometric Mean",
                                              layout=widgets.Layout(width='20%')),
                                widgets.Image(value=_geo_image,
                                              format='png')])
        _file = open("__docs/combine_images/algebric_mean.png", 'rb')
        _alge_image = _file.read()
        alge_box = widgets.HBox([widgets.Label("Arithmetic Mean",
                                              layout=widgets.Layout(width='20%')),
                                widgets.Image(value=_alge_image,
                                              format='png')])

        self.combine_method = widgets.RadioButtons(options=['add', 'arithmetic mean', 'geometric mean'],
                                                   value='arithmetic mean')

        vertical = widgets.VBox([alge_box, geo_box, self.combine_method])
        display(vertical)
示例#9
0
    def __init__(self, text, correct, *wrong, inst=single):
        choices = list(wrong)
        choices.append(correct)
        choices.sort()
        pic_num = []
        for i, pic in enumerate(choices, 1):
            pic_num.append((pic, i))

        def on_button_clicked(b):
            choice = b.description
            b.style.button_color = 'lightgreen' if choice == self.correct else 'red'

            if self.answered:
                return
            self.answered = True

            # textbox.layout.border = "2px solid lightgreen" if choice == self.correct else "2px solid red"

        textbox = widgets.HTML(
            value='<h4 style="font-size:14px;">{}</h4>'.format(text),
            layout=widgets.Layout(justify_content="center"))
        instbox = widgets.HTML(value='<i>{}</i>'.format(inst),
                               layout=widgets.Layout(justify_content="center"))
        imagebox = []
        for (p, n) in pic_num:
            file = open(p, "rb")
            image = file.read()
            pic = widgets.Image(value=image,
                                format='png',
                                width=300,
                                height=200)
            if p == correct:
                self.correct = str(n)

            but = widgets.Button(description=str(n),
                                 layout=widgets.Layout(width="250px"))
            but.on_click(on_button_clicked)

            picbox = widgets.VBox(children=[pic, but])
            imagebox.append(picbox)

        allpng = []
        while not imagebox == []:
            if len(imagebox) > 2:
                allpng.append(
                    widgets.HBox(children=[imagebox[0], imagebox[1]]))
                imagebox.pop(0)
                imagebox.pop(0)
            else:
                allpng.append(widgets.HBox(children=imagebox))
                break

        super().__init__(children=[textbox, instbox] + allpng)
        self.answered = False
示例#10
0
def display_results(image_path, results):
    hbox = HBox(
        [
            VBox(
                [
                    widgets.Label(f"{distance:.2f} {image_name}"),
                    widgets.Image(value=open(f"{image_path}/{image_name}.jpeg", "rb").read()),
                ]
            )
            for distance, image_name in results
        ]
    )
    display(hbox)
示例#11
0
    def _create_ui(self):
        """Create and initialize widgets"""

        # ------------
        # Callbacks + logic
        # ------------
        def button_pressed(obj):
            self.query_im_index = int(obj.value)
            self.update()

        # ------------
        # UI - image grid
        # ------------
        self.w_imgs = []
        self.w_buttons = []
        w_img_buttons = []

        for i in range(self.rows * self.cols):
            # Initialize images
            w_img = widgets.Image(description="", width=180)
            self.w_imgs.append(w_img)

            # Initialize buttons
            w_button = widgets.Button(description="", value=i)
            w_button.on_click(button_pressed)
            if i == 0:
                w_button.button_style = "primary"
            else:
                w_button.button_style = "warning"
            self.w_buttons.append(w_button)

            # combine into image+button widget
            w_img_button = widgets.VBox(children=[w_button, w_img])
            w_img_buttons.append(w_img_button)

        # Image grid
        w_grid_HBoxes = []
        for r in range(self.rows):
            hbox = widgets.HBox(children=[
                w_img_buttons[r * self.cols + c] for c in range(self.cols)
            ])
            hbox.layout.padding = "10px"
            w_grid_HBoxes.append(hbox)
        w_img_grid = widgets.VBox(w_grid_HBoxes)

        # Create tab
        self.ui = widgets.Tab(children=[w_img_grid])
        self.ui.set_title(0, "Image retrieval viewer")

        # Fill UI with content
        self.update()
示例#12
0
def get_images_and_cameras(image_width=640, image_height=480, fps=5):
    image = widgets.Image(format='jpeg',
                          width=image_width,
                          height=image_height)
    camera = CSICamera(capture_width=3264,
                       capture_height=2464,
                       image_width=image_width,
                       image_height=image_height,
                       fps=fps)
    traitlets.dlink(
        (camera, 'value'),
        (image, 'value'),
        transform=lambda x: bgr8_to_jpeg(x),
    )
    return image, camera
示例#13
0
        def __init__(self):

            self._handle = ImageDrawHandle(sequence.frame(0).image())

            self._button_restart = widgets.Button(description='Restart')
            self._button_next = widgets.Button(description='Next')
            self._button_play = widgets.Button(description='Run')
            self._frame = widgets.Label(value="")
            self._frame.layout.display = "none"
            self._frame_feedback = widgets.Label(value="")
            self._image = widgets.Image(value="", format="png", width=sequence.size[0] * 2, height=sequence.size[1] * 2)

            state = dict(frame=0, auto=False, alive=True, region=None)
            condition = Condition()

            self._buttons = widgets.HBox(children=(frame, self._button_restart, self._button_next, button_play, frame2))
示例#14
0
文件: threejs.py 项目: TreeerT/pymor
    def _gen_sprite(self):
        from PIL import Image, ImageFont, ImageDraw
        # upsacle to pow2
        sprite_size = (self.render_size[0], self.render_size[1])
        image = Image.new('RGBA', sprite_size, color=(255, 255, 255, 255))
        draw = ImageDraw.Draw(image)
        ttf = '/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf'
        font_size = 12
        font = ImageFont.truetype(ttf, font_size)
        bar_width = 25
        bar_padding = font_size // 2
        bar_height = sprite_size[1] - (2 * bar_padding)
        # we have to flip the Y coord cause PIL's coordinate system is different from OGL
        for i in range(bar_height):
            cl = tuple((np.array(self.color_map(bar_height - i)) * 255).astype(
                np.int_))
            draw.line([(0, bar_padding + i), (bar_width, bar_padding + i)],
                      cl,
                      width=1)

        text_x = bar_width + 4
        text_color = (0, 0, 0, 255)
        text_fmt = '{:+1.3e}'
        draw.text((text_x, 0),
                  text_fmt.format(self.vmax),
                  font=font,
                  fill=text_color)
        draw.text((text_x, (bar_height - bar_padding) // 2),
                  text_fmt.format((self.vmax + self.vmin) / 2),
                  font=font,
                  fill=text_color)
        draw.text((text_x, bar_height - bar_padding),
                  text_fmt.format(self.vmin),
                  font=font,
                  fill=text_color)

        of = BytesIO()
        image.save(of, format='png')
        of.seek(0)
        return widgets.Image(
            value=of.read(),
            format='png',
            width=self.render_size[0],
            height=self.render_size[1],
        )
示例#15
0
    def __init__(self,
                 on_interact=None,
                 output=None,
                 overwrite_previous_output=True,
                 feedback=False,
                 run=True,
                 action_kws={},
                 *args,
                 **kwargs):
        super().__init__(on_interact=on_interact,
                         output=output,
                         overwrite_previous_output=overwrite_previous_output,
                         feedback=feedback,
                         action_kws=action_kws)

        self.widget = widgets.Image(*args, **kwargs)

        if run:
            self.run()
示例#16
0
    def __init__(self, fns, opts=(), height=128, width=128):
        self.fns = fns
        box_layout = dict(width='100%',
                          height='',
                          overflow='scroll hidden',
                          flex_flow='row',
                          display='flex')
        img_layout = dict(height=f'{height}px', object_fit='contain')

        v = [
            VBox([
                widgets.Image(value=Image.open(fn).to_thumb(
                    height, width).to_bytes_format(),
                              layout=img_layout),
                Dropdown(options=('<Keep>', '<Delete>') + tuple(opts),
                         layout={'width': 'max-content'})
            ],
                 layout={'min_width': f'{width}px'}) for fn in fns
        ]
        self.widget = Box(children=v, layout=box_layout)
示例#17
0
    def show_graphs(self, items):
        assert items.items
        label2item = {}
        origidcount = {}
        labels = []
        for i in items.items:
            if i.original_id not in origidcount:
                origidcount[i.original_id] = 0

            ast = i.content[Repr.AST] if Repr.AST in i.content else '[no AST]'
            label = f'{i.original_id}.{origidcount[i.original_id]}. {ast}'
            label2item[label] = i
            labels.append(label)
            origidcount[i.original_id] += 1

        dropdown = widgets.Dropdown(
            layout={'width': 'max-content'},
            options=labels,
            value=labels[0],
            description='',
            disabled=False,
        )

        image = widgets.Image(format='svg+xml')

        def show_graph(label):
            item = label2item[label]
            if Repr.GRAPH_SVG not in item.content:
                r = utils.dot2svg(item.content[Repr.GRAPH_DOT].encode())
                if r.success:
                    item.content[Repr.GRAPH_SVG] = r.value
                else:
                    self.html_response(
                        f'<span class="glif-stderr">Failed to produce graph:<br/>{html_escape(r.logs)}</span>')
                    return
            image.value = item.content[Repr.GRAPH_SVG]

        show_graph(labels[0])
        dropdown.observe(lambda bunch: show_graph(bunch['new']), names='value')
        display(dropdown, image)
示例#18
0
    def display(self):

        if self.grid is None:
            print("The grid has been removed. Try initiate this object again.")
            return

        start_idx = len(self.corrected_mask)
        if start_idx >= len(self.dataset):
            correct_num = np.sum(self.corrected_mask)
            self.on_finish_button_clicked(widget=self.finish_button)
            print(
                f"Finished validating the whole dataset. {correct_num} / {len(self.corrected_mask)} are correct."
            )
        else:
            for wid in range(10):
                self.grid[0, wid] = widgets.Image(
                    value=self.get_image(start_idx + wid),
                    format="png",
                    indent=False)
                self.checkboxes[wid].value = True
            clear_output()
            display(self.grid)
示例#19
0
                                  orientation='vertical')
right_slider = widgets.FloatSlider(description='right',
                                   min=-1.0,
                                   max=1.0,
                                   step=0.01,
                                   orientation='vertical')
left_link = traitlets.link((left_slider, 'value'), (robot.left_motor, 'value'))
right_link = traitlets.link((right_slider, 'value'),
                            (robot.right_motor, 'value'))

# In[31]:

width = 224
height = 224
camera = Camera.instance()
input_image = widgets.Image(format='jpeg', width=width, height=height)
result1 = widgets.Image(format='jpeg', width=width, height=height)
result2 = widgets.Image(format='jpeg', width=width, height=height)

# In[32]:

image_box = widgets.HBox(
    [input_image, result1, result2, left_slider, right_slider],
    layout=widgets.Layout(align_self='center'))

# In[33]:

display(image_box)

# In[105]:
    def create_submission_panel(self):
        def assign_file_types(filename):
            """ assign file types based on file name and extension """
            fname, extension = os.path.splitext(filename)
            if extension == '.txt':
                filetype = 'text/plain'
            else:
                filetype = 'application/unknown'
            return filetype

        def checkloginNSG(_):
            username = username_widget.value
            password = password_widget.value
            headers = {'cipres-appkey': self.KEY}
            URL = 'https://nsgr.sdsc.edu:8443/cipresrest/v1/job/' + username
            r = requests.get(URL,
                             auth=(username, password),
                             headers=headers,
                             verify=False)
            root = xml.etree.ElementTree.fromstring(r.text)
            a = 0
            for child in root:
                if child.tag == 'displayMessage':
                    a = 1
                    msg = child.text
            if a == 0:
                msg = 'Authenticated successfully'
                msg_widget.disabled = True
                buttonlogin.disabled = True
                username_widget.disabled = True
                password_widget.disabled = True
            msg_widget.value = msg
            msg_widget.layout.display = ''
            RunSNSG.disabled = False

        def runNSG(RunSNSG):
            if msg_widget.value == 'Authenticated successfully':
                self.RBHPC.disabled = True
                self.RBM.disabled = True
                TR.disabled = True
                TT.disabled = True
                TSK.disabled = True
                ND.disabled = True
                WT.disabled = True
                myboxUNSG.children[0].disabled = True
                runningUNSG = True
                IU.layout.display = ''
                username = username_widget.value
                password = password_widget.value
                CRA_USER = username
                PASSWORD = password
                URL = 'https://nsgr.sdsc.edu:8443/cipresrest/v1'

                create_zip_nsg()

                headers = {'cipres-appkey': self.KEY}
                if TT.value == '':
                    jobname = 'NSG_Job'
                else:
                    jobname = unicodedata.normalize('NFC', TT.value)
                nrcores = unicodedata.normalize('NFC', TSK.value)
                nrnodes = unicodedata.normalize('NFC', ND.value)
                runtime = unicodedata.normalize('NFC', WT.value)
                payload = {'tool' : self.TOOL,\
                           'metadata.statusEmail' : 'false',
                           'vparam.pythonoption_' : '1',
                           'metadata.clientJobId': jobname,
                           'vparam.number_cores_' : nrcores,
                           'vparam.number_nodes_' : nrnodes,
                           'vparam.runtime_' : float(runtime),
                           'vparam.filename_': 'start.py'}
                files = {'input.infile_': open('transfer.zip', 'rb')}

                r = requests.post('{}/job/{}'.format(URL, CRA_USER),
                                  auth=(CRA_USER, PASSWORD),
                                  data=payload,
                                  headers=headers,
                                  files=files,
                                  verify=False)
                root = xml.etree.ElementTree.fromstring(r.text)
                global outputuri, selfuri
                for child in root:
                    if child.tag == 'resultsUri':
                        for urlchild in child:
                            if urlchild.tag == 'url':
                                outputuri = urlchild.text
                    if child.tag == 'selfUri':
                        for urlchild in child:
                            if urlchild.tag == 'url':
                                selfuri = urlchild.text
                myboxUNSG.children[1].layout.display = ''
            else:
                runningUNSG = False
                CheckSNSG.layout.display = 'none'
                myboxConf.children[1].layout.display = 'none'
                myboxConf.layout.display = ''
                myboxUNSG.children[0].disabled = True

        def checksimnsg(CheckSNSG):
            headers = {'cipres-appkey': self.KEY}
            username = username_widget.value
            password = password_widget.value
            CRA_USER = username
            PASSWORD = password
            r = requests.get(selfuri,
                             auth=(CRA_USER, PASSWORD),
                             headers=headers,
                             verify=False)
            root = xml.etree.ElementTree.fromstring(r.text)
            job_submissiontime = root.find('dateSubmitted').text
            job_name = root.find('metadata').find('entry').find('value').text
            for child in root:
                if child.tag == 'jobStage':
                    STN.layout.display = ''
                    STN.value=job_name+' '+child.text+' '+\
                    dateutil.parser.parse(job_submissiontime).\
                    astimezone(pytz.timezone('CET')).strftime("%d/%m/%Y %H:%M:%S")
                    jobstage = child.text
                if child.tag == 'terminalStage':
                    jobstatus = child.text
            if (jobstatus == 'true'):
                if (jobstage == 'COMPLETED'):
                    IU.layout.display = 'none'
                    CheckSNSG.disabled = True
                    r = requests.get(outputuri,
                                     headers=headers,
                                     auth=(CRA_USER, PASSWORD),
                                     verify=False)
                    globaldownloadurilist = []
                    lengths = []
                    root = xml.etree.ElementTree.fromstring(r.text)
                    for child in root:
                        if child.tag == 'jobfiles':
                            for jobchild in child:
                                if jobchild.tag == 'jobfile':
                                    for downloadchild in jobchild:
                                        if downloadchild.tag == 'downloadUri':
                                            for attchild in downloadchild:
                                                if attchild.tag == 'url':
                                                    globaldownloadurilist.append(
                                                        attchild.text)
                                        if downloadchild.tag == 'length':
                                            lengths.append(downloadchild.text)
                    r = requests.get(selfuri,
                                     auth=(CRA_USER, PASSWORD),
                                     headers=headers,
                                     verify=False)
                    root = xml.etree.ElementTree.fromstring(r.text)
                    for child in root:
                        if child.tag == 'messages':
                            for childs in child:
                                texts = []
                                for childss in childs:
                                    texts.append(childss.text)
                                if texts[1] == 'SUBMITTED':
                                    subname = texts[2]
                    os.chdir("..")
                    storeto_path = 'resultsNSG'
                    if not os.path.exists(storeto_path):
                        os.mkdir(storeto_path)
                    storeto = str(os.path.join(storeto_path,TT.value+'_fitting_'+\
                                               dateutil.parser.parse(job_submissiontime).\
                                               astimezone(pytz.timezone('CET')).\
                                               strftime("%d%m%Y%H%M%S")))
                    os.mkdir(storeto)
                    os.chdir(storeto)
                    for downloaduri in globaldownloadurilist:
                        if float(lengths[globaldownloadurilist.index(
                                downloaduri)]) <= 5048000:
                            r = requests.get(downloaduri,
                                             auth=(CRA_USER, PASSWORD),
                                             headers=headers,
                                             verify=False)
                            d = r.headers['content-disposition']
                            filename_list = re.findall('filename=(.+)', d)
                            for filename in filename_list:
                                download_file_nsg(filename, r)
                    runningUNSG = False
                    os.chdir("../../GUI")
                else:
                    IU.layout.display = 'none'
                    CheckSNSG.layout.display = 'none'
                    myboxConf.layout.display = ''
                    runningUNSG = False
                    myboxUNSG.children[0].disabled = False

        def run_service_account_on_nsg(RunSNSG_SA):
            self.RBHPC.disabled = True
            self.RBM.disabled = True
            TR.disabled = True
            TT.disabled = True
            TSK.disabled = True
            ND.disabled = True
            WT.disabled = True
            myboxUNSG_SA.children[0].disabled = True
            runningUNSG = True
            IU.layout.display = ''

            create_zip_nsg()

            POST_JOB_URL = 'https://bspsa.cineca.it/jobs/nsg/'

            nrcores = unicodedata.normalize('NFC', TSK.value)
            nrnodes = unicodedata.normalize('NFC', ND.value)
            runtime = unicodedata.normalize('NFC', WT.value)
            if TT.value == '':
                title = 'ServiceAccount_Job'
            else:
                title = unicodedata.normalize('NFC', TT.value)

            payload = {
                'tool': self.TOOL,
                'python_option': '1',
                'core_number': nrcores,
                'node_number': nrnodes,
                'runtime': float(runtime),
                'init_file': 'start.py',
                'title': title,
                'uc': ' synaptic_events_fitting'
            }

            files = {'input.infile_': open('transfer.zip', 'rb')}

            headers = unicore_api.get_oidc_auth()
            headers.update(
                {'Content-Disposition': 'attachment;filename=transfer.zip'})
            headers.update({'payload': json.dumps(payload)})

            r = requests.post(url=POST_JOB_URL, headers=headers, files=files)
            if r.status_code == 201:
                global jobid
                jobid = r.json()['job_id']
                myboxUNSG_SA.children[1].layout.display = ''
            else:
                runningUNSG = False
                myboxConf.children[1].layout.display = 'none'
                myboxConf.layout.display = ''
                myboxUNSG_SA.children[0].disabled = True

        def check_job_on_service_account(CheckSNSG):
            headers = unicore_api.get_oidc_auth()
            GET_JOB_URL = 'https://bspsa.cineca.it/jobs/nsg/bsp_nsg_01/' + jobid + '/'
            DOWNLOAD_OUTPUT_FILE = 'https://bspsa.cineca.it/files/nsg/bsp_nsg_01/' + jobid + '/'

            r = requests.get(url=GET_JOB_URL, headers=headers)
            if r.status_code == 200:
                job = r.json()

                job_submissiontime = job['init_date']
                job_stage = job['stage']
                job_terminal_stage = job['terminal_stage']

                STN.layout.display = ''
                job_title = job['title']
                if job_title == "":
                    jobname = jobid
                else:
                    jobname = job_title
                STN.value = job_title + ' ' + job['stage'] + ' ' + \
                                dateutil.parser.parse(job_submissiontime).astimezone(pytz.timezone('CET')).strftime("%d/%m/%Y %H:%M:%S")

                if job_terminal_stage and job_stage == 'COMPLETED':
                    IU.layout.display = 'none'
                    CheckSNSG_SA.disabled = True
                    r = requests.get(url=DOWNLOAD_OUTPUT_FILE, headers=headers)
                    if r.status_code == 200:
                        file_list = r.json()
                        os.chdir("..")
                        storeto_path = 'resultsNSG-SA'
                        if not os.path.exists(storeto_path):
                            os.mkdir(storeto_path)
                        os.chdir(storeto_path)
                        storeto = TT.value + '_fitting_' + dateutil.parser.parse(
                            job_submissiontime).astimezone(
                                pytz.timezone('CET')).strftime("%d%m%Y%H%M%S")
                        if not os.path.exists(storeto_path):
                            os.mkdir(storeto)
                        os.chdir(storeto)
                        for f in file_list:
                            filename = f['filename']
                            r = requests.get(
                                url=DOWNLOAD_OUTPUT_FILE + f['fileid'] + '/',
                                headers=unicore_api.get_oidc_auth())
                            if r.status_code == 200:
                                download_file_nsg(filename, r)
                        os.chdir("../../GUI")
                    runningUNSG = False
            else:
                IU.layout.display = 'none'
                CheckSNSG_SA.layout.display = 'none'
                myboxConf.layout.display = ''
                runningUNSG = False
                myboxUNSG_SA.children[0].disabled = False

        def create_zip_nsg():
            with open(os.path.join('transfer', 'start.py'), 'w') as f:
                tt = self.RB.value
                valRB = tt[tt.find('CA1'):len(tt)]
                expf = 'exp' + valRB[valRB.find('(') +
                                     1:valRB.find(')')] + '.txt'
                if self.RB1.value == 'local':
                    conff = 'config.txt'
                else:
                    conff = expf.replace("exp", "config")
                f.write('import fitting')
                f.write('\n')
                if self.RB1.value == 'local':
                    if self.RBM.value == 'all_traces':
                        f.write('fitting.fitting('+'\''+conff+'\','+'\''+expf+'\','+'\''+\
                                list(self.file_widget.value.keys())[0]+\
                                '\','+'\''+'True'+'\','+'\''+'False'+'\','+'\''+'False'+'\','+'3)\n')
                    else:
                        if self.RBM.value == 'singletrace':
                            f.write('fitting.fitting('+'\''+conff+'\','+'\''+expf+'\','+'\''+\
                                    list(self.file_widget.value.keys())[0]+\
                                    '\','+'\''+'False'+'\','+'\''+'True'+'\','+'\''+'False'+'\','+\
                                    '\''+unicodedata.normalize('NFC', TR.value)+'\')\n')
                        else:
                            f.write('fitting.fitting('+'\''+conff+'\','+'\''+expf+'\','+'\''+\
                                    list(self.file_widget.value.keys())[0]+\
                                    '\','+'\''+'False'+'\','+'\''+'False'+'\','+'\''+'True'+'\','+\
                                    '\''+unicodedata.normalize('NFC', TR.value)+'\')\n')
                else:
                    if self.RBM.value == 'all_traces':
                        f.write('fitting.fitting('+'\''+conff+'\','+'\''+expf+'\','+'\''+\
                                'ProbGABAAB_EMS_GEPH_g.mod'+\
                                '\','+'\''+'True'+'\','+'\''+'False'+'\','+'\''+'False'+'\','+'3)\n')
                    else:
                        if self.RBM.value == 'singletrace':
                            f.write('fitting.fitting('+'\''+conff+'\','+'\''+expf+'\','+'\''+\
                                    'ProbGABAAB_EMS_GEPH_g.mod'+\
                                    '\','+'\''+'False'+'\','+'\''+'True'+'\','+'\''+'False'+'\','+\
                                    '\''+unicodedata.normalize('NFC', TR.value)+'\')\n')
                        else:
                            f.write('fitting.fitting('+'\''+conff+'\','+'\''+expf+'\','+'\''+\
                                    'ProbGABAAB_EMS_GEPH_g.mod'+\
                                    '\','+'\''+'False'+'\','+'\''+'False'+'\','+'\''+'True'+'\','+\
                                    '\''+unicodedata.normalize('NFC', TR.value)+'\')\n')
                f.write('\n')
            f.close()
            if self.RB1.value == 'local':
                os.chdir('..')
                f = open('fitness.py', 'r')
                lines = f.readlines()
                lines[241] = "\n"
                lines[242] = "\n"
                lines[243] = "\n"
                lines[244] = "\n"
                lines[245] = "\n"
                f.close()
                f = open('fitness.py', 'w')
                f.writelines(lines)
                f.close()
                os.chdir('GUI')
            else:
                shutil.copy2(os.path.join("..", "data", 'config_files', conff),
                             'transfer')

            zfName = 'transfer.zip'
            foo = zipfile.ZipFile(zfName, 'w')
            for root, dirs, files in os.walk('./transfer'):
                for f in files:
                    foo.write(os.path.join(root, f))
            foo.close()

        def download_file_nsg(filename, r):
            if filename == 'output.tar.gz' or filename == 'STDOUT' or filename == 'STDERR':
                with open(filename, 'wb') as fd:
                    for chunk in r.iter_content():
                        fd.write(chunk)
                if filename == 'output.tar.gz':
                    ff = tarfile.open("output.tar.gz")
                    ff.extractall('OUTPUT')
                    ff.close()
                    os.remove('output.tar.gz')
                    for filename in os.listdir(
                            os.path.join('OUTPUT', 'transfer')):
                        if filename.endswith("txt") or\
                        (filename.endswith("mod") and not(filename.startswith("netstims"))) or\
                        filename in ['test.csv', 'start.py']:
                            shutil.copy2(
                                os.path.join('OUTPUT', 'transfer', filename),
                                '.')
                    shutil.rmtree('OUTPUT')

        def runmethod(change):
            if self.RBM.value == 'all_traces':
                TR.value = '3'
                TR.layout.display = 'none'
            else:
                TR.value = '3'
                TR.layout.display = ''

        def RBHPCclick(_):
            STU.layout.display = 'none'
            IU.layout.display = 'none'
            if self.RBHPC.value == 'NSG':
                formMNSG.layout.display = ''
                myboxConf.children[0].layout.display = ''
                myboxUNSG.children[0].layout.display = ''
                RunSNSG_SA.layout.display = 'none'
                CheckSNSG_SA.layout.display = 'none'
                if runningUNSG:
                    myboxUNSG.children[1].layout.display = ''
            elif self.RBHPC.value == 'Service Account - NSG':
                formMNSG.layout.display = 'none'
                myboxConf.children[0].layout.display = 'none'
                myboxUNSG_SA.children[0].layout.display = ''
                RunSNSG.layout.display = 'none'
                CheckSNSG.layout.display = 'none'
                if runningUNSG:
                    myboxUNSG_SA.children[1].layout.display = ''

            myboxConf.children[0].layout.display = ''
            myboxConf.children[1].value = '24'
            myboxConf.children[2].value = '2'
            myboxConf.children[3].value = '0.5'
            if runningUNSG:
                STN.layout.display = ''
                IU.layout.display = ''

        file = open("../data/img/Work-in-progress3.png", "rb")
        image = file.read()
        IU = widgets.Image(value=image, format='png', width=400)
        IU.layout.display = 'none'
        STU = widgets.Text()
        STU.description = 'status'
        STU.value = ''
        STU.disabled = True
        STU.layout.width = '70%'
        STU.layout.display = 'none'
        STN = widgets.Text()
        STN.description = 'status'
        STN.value = ''
        STN.disabled = True
        STN.layout.width = '70%'
        STN.layout.display = 'none'
        username_widget = widgets.Text(description='Username:'******'249px'
        password_widget = widgets.Password(description='Password:'******'Login NSG'
        buttonlogin.background_color = 'gainsboro'
        buttonlogin.border_color = 'black'
        buttonlogin.layout.width = '25%'
        buttonlogin.on_click(checkloginNSG)
        msg_widget = widgets.Text(layout=widgets.Layout(width='40%'))
        msg_widget.layout.display = 'none'

        display(self.RBHPC)
        display(self.RBM)
        self.RBM.observe(runmethod, names='value')
        formMNSG = widgets.VBox(children=[
            username_widget, password_widget, buttonlogin, msg_widget
        ])
        formMNSG.layout.display = ''
        display(formMNSG)
        TR = widgets.Text()
        TR.description = 'Trace:'
        TR.layout.display = 'none'
        display(TR)
        TT = widgets.Text()
        TT.description = 'Title:'
        WT = widgets.Text()
        WT.description = 'Walltime:'
        ND = widgets.Text()
        ND.description = 'N. of nodes'
        TSK = widgets.Text()
        TSK.description = 'N. of CPUs'
        myboxConf = widgets.VBox(children=[TT, TSK, ND, WT])
        myboxConf.children[1].value = '24'
        myboxConf.children[2].value = '2'
        myboxConf.children[3].value = '0.5'
        myboxConf.layout.display = ''
        display(myboxConf)

        RunSNSG = widgets.Button()
        RunSNSG.description = 'Run NSG simulation'
        RunSNSG.background_color = 'gainsboro'
        RunSNSG.border_color = 'black'
        RunSNSG.layout = widgets.Layout(width='25%')
        RunSNSG.on_click(runNSG)
        RunSNSG.disabled = True
        CheckSNSG = widgets.Button()
        CheckSNSG.description = 'Check NSG simulation'
        CheckSNSG.background_color = 'gainsboro'
        CheckSNSG.border_color = 'black'
        CheckSNSG.layout = widgets.Layout(width='25%')
        CheckSNSG.on_click(checksimnsg)
        buttonSNSG = [RunSNSG, CheckSNSG]
        myboxUNSG = widgets.HBox(children=buttonSNSG)
        myboxUNSG.children[0].layout.display = ''
        myboxUNSG.children[1].layout.display = 'none'

        RunSNSG_SA = widgets.Button()
        RunSNSG_SA.description = 'Run NSG simulation'
        RunSNSG_SA.background_color = 'gainsboro'
        RunSNSG_SA.border_color = 'black'
        RunSNSG_SA.layout = widgets.Layout(width='25%')
        RunSNSG_SA.on_click(run_service_account_on_nsg)
        CheckSNSG_SA = widgets.Button()
        CheckSNSG_SA.description = 'Check NSG simulation'
        CheckSNSG_SA.background_color = 'gainsboro'
        CheckSNSG_SA.border_color = 'black'
        CheckSNSG_SA.layout = widgets.Layout(width='25%')
        CheckSNSG_SA.on_click(check_job_on_service_account)
        buttonSNSG_SA = [RunSNSG_SA, CheckSNSG_SA]
        myboxUNSG_SA = widgets.HBox(children=buttonSNSG_SA)
        myboxUNSG_SA.children[0].layout.display = 'none'
        myboxUNSG_SA.children[1].layout.display = 'none'

        display(STU)
        display(STN)
        display(myboxUNSG)
        display(myboxUNSG_SA)
        display(IU)

        runningU = False
        runningUNSG = False

        self.RBHPC.on_trait_change(RBHPCclick, 'value')
示例#21
0
 def make_img_widget(cls, img, layout=Layout(), format='jpg'):
     "Returns an image widget for specified file name `img`."
     return widgets.Image(value=img, format=format, layout=layout)
示例#22
0
def init(*args, **kwargs):
    global flag, downflag, shiftflag

    w = widgets.Image(value=m.system.image_data(), width=600)
    d = Event(source=w,
              watched_events=[
                  'mousedown', 'mouseup', 'mousemove', 'keyup', 'keydown',
                  'wheel'
              ])
    no_drag = Event(source=w,
                    watched_events=['dragstart'],
                    prevent_default_action=True)
    d.on_dom_event(listen_mouse)
    run = widgets.ToggleButton(
        value=False,
        description='Run',
        disabled=False,
        button_style='',  # 'success', 'info', 'warning', 'danger' or ''
        tooltip='run the simulation',
        icon='play')
    pause = widgets.ToggleButton(
        value=False,
        description='Pause',
        disabled=False,
        button_style='',  # 'success', 'info', 'warning', 'danger' or ''
        tooltip='pause the simulation',
        icon='pause')

    reset = widgets.ToggleButton(
        value=False,
        description='Reset',
        disabled=False,
        button_style='',  # 'success', 'info', 'warning', 'danger' or ''
        tooltip='reset the simulation',
        icon='stop')

    def onToggleRun(b):
        global flag
        if run.value:
            run.button_style = 'success'
            pause.value = False
            pause.button_style = ''
            reset.value = False
            reset.button_style = ''
            flag = True
        else:
            run.button_style = ''
            flag = False

    def onTogglePause(b):
        global flag
        if pause.value:
            pause.button_style = 'success'
            run.value = False
            run.button_style = ''
            reset.value = False
            reset.button_style = ''
            flag = False
        else:
            pause.button_style = ''
            flag = True

    def onToggleReset(b):
        global flag
        if reset.value:
            reset.button_style = 'success'
            pause.value = False
            pause.button_style = ''
            run.value = False
            run.button_style = ''
            flag = False
            m.Universe.reset()
        else:
            reset.button_style = ''
            #w = create_simulation()

    buttons = widgets.HBox([run, pause, reset])
    run.observe(onToggleRun, 'value')
    pause.observe(onTogglePause, 'value')
    reset.observe(onToggleReset, 'value')

    box = widgets.VBox([w, buttons])
    display(box)

    def background_threading():
        global flag
        while True:
            m.Simulator.context_make_current()
            if flag:
                m.step()
            w.value = m.system.image_data()
            m.Simulator.context_release()
            time.sleep(0.01)

    t = threading.Thread(target=background_threading)
    t.start()
示例#23
0
        frames = example[:10 + i + 1, ...]
        new_prediction = model.predict(np.expand_dims(frames, axis=0))
        new_prediction = np.squeeze(new_prediction, axis=0)
        predicted_frame = np.expand_dims(new_prediction[-1, ...], axis=0)

        # Extend the set of prediction frames.
        new_predictions[i] = predicted_frame

    # Create and save GIFs for each of the ground truth/prediction images.
    for frame_set in [original_frames, new_predictions]:
        # Construct a GIF from the selected video frames.
        current_frames = np.squeeze(frame_set)
        current_frames = current_frames[..., np.newaxis] * np.ones(3)
        current_frames = (current_frames * 255).astype(np.uint8)
        current_frames = list(current_frames)

        # Construct a GIF from the frames.
        with io.BytesIO() as gif:
            imageio.mimsave(gif, current_frames, "GIF", fps=5)
            predicted_videos.append(gif.getvalue())

# Display the videos.
print(" Truth\tPrediction")
for i in range(0, len(predicted_videos), 2):
    # Construct and display an `HBox` with the ground truth and prediction.
    box = HBox([
        widgets.Image(value=predicted_videos[i]),
        widgets.Image(value=predicted_videos[i + 1]),
    ])
    display(box)
示例#24
0
def final_output(days, final):
    time = ['MORNING', 'EVENING']
    fields = ['NAME', 'CATEGORY', 'LOCATION', 'PRICE', 'RATING']
    recommendations = ['Recommendation 1:', 'Recommendation 2:']

    box_layout = Layout(
        justify_content='space-between',
        display='flex',
        flex_flow='row',
        align_items='stretch',
    )
    column_layout = Layout(
        justify_content='space-between',
        width='75%',
        display='flex',
        flex_flow='column',
    )
    tab = []
    for i in range(days):
        images = final['image'][i * 4:(i + 1) * 4]
        images = [open(i, "rb").read() for i in images]
        name = [
            re.sub('_', ' ', i).capitalize()
            for i in final['name'][i * 4:(i + 1) * 4]
        ]
        category = [
            re.sub('_', ' ', i).capitalize()
            for i in final['category'][i * 4:(i + 1) * 4]
        ]
        location = [
            "(" + str(i[0]) + "," + str(i[1]) + ")"
            for i in final['location'][i * 4:(i + 1) * 4]
        ]
        price = [str(i) for i in final['price'][i * 4:(i + 1) * 4]]
        rating = [str(i) for i in final['rating'][i * 4:(i + 1) * 4]]
        tab.append(
            VBox(children=[
                HBox(children=[
                    VBox(children=[
                        widgets.HTML(
                            value=f"<b><font color='orange'>{time[0]}</b>"),
                        widgets.HTML(
                            value=
                            f"<b><font color='purple'>{recommendations[0]}</b>"
                        ),
                        widgets.Image(value=images[0],
                                      format='jpg',
                                      width=300,
                                      height=400),
                        widgets.HTML(
                            description=fields[0],
                            value=f"<b><font color='black'>{name[0]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[1],
                            value=f"<b><font color='black'>{category[0]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[2],
                            value=f"<b><font color='black'>{location[0]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[3],
                            value=f"<b><font color='black'>{price[0]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[4],
                            value=f"<b><font color='black'>{rating[0]}</b>",
                            disabled=True)
                    ],
                         layout=column_layout),
                    VBox(children=[
                        widgets.HTML(
                            value=f"<b><font color='orange'>{time[1]}</b>"),
                        widgets.HTML(
                            value=
                            f"<b><font color='purple'>{recommendations[0]}</b>"
                        ),
                        widgets.Image(value=images[2],
                                      format='jpg',
                                      width=300,
                                      height=400),
                        widgets.HTML(
                            description=fields[0],
                            value=f"<b><font color='black'>{name[2]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[1],
                            value=f"<b><font color='black'>{category[2]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[2],
                            value=f"<b><font color='black'>{location[2]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[3],
                            value=f"<b><font color='black'>{price[2]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[4],
                            value=f"<b><font color='black'>{rating[2]}</b>",
                            disabled=True)
                    ],
                         layout=column_layout)
                ],
                     layout=box_layout),
                HBox(children=[
                    VBox(children=[
                        widgets.HTML(
                            value=
                            f"<b><font color='purple'>{recommendations[1]}</b>"
                        ),
                        widgets.Image(value=images[1],
                                      format='jpg',
                                      width=300,
                                      height=400),
                        widgets.HTML(
                            description=fields[0],
                            value=f"<b><font color='black'>{name[1]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[1],
                            value=f"<b><font color='black'>{category[1]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[2],
                            value=f"<b><font color='black'>{location[1]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[3],
                            value=f"<b><font color='black'>{price[1]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[4],
                            value=f"<b><font color='black'>{rating[1]}</b>",
                            disabled=True)
                    ],
                         layout=column_layout),
                    VBox(children=[
                        widgets.HTML(
                            value=
                            f"<b><font color='purple'>{recommendations[1]}</b>"
                        ),
                        widgets.Image(value=images[3],
                                      format='jpg',
                                      width=300,
                                      height=400),
                        widgets.HTML(
                            description=fields[0],
                            value=f"<b><font color='black'>{name[3]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[1],
                            value=f"<b><font color='black'>{category[3]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[2],
                            value=f"<b><font color='black'>{location[3]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[3],
                            value=f"<b><font color='black'>{price[3]}</b>",
                            disabled=True),
                        widgets.HTML(
                            description=fields[4],
                            value=f"<b><font color='black'>{rating[3]}</b>",
                            disabled=True)
                    ],
                         layout=column_layout),
                ],
                     layout=box_layout)
            ]))

    tab_recc = widgets.Tab(children=tab)
    for i in range(len(tab_recc.children)):
        tab_recc.set_title(i, str('Day ' + str(i + 1)))
    return tab_recc
示例#25
0
 def get_hangman_image(self):
     """Builds a widget to display the hangman image."""
     self.hangman_image = widgets.Image(
         value=self.image.get_encoded_image())
示例#26
0
 def make_img_widget(img: bytes,
                     layout=Layout(height='250px', width='300px'),
                     format='jpg') -> widgets.Image:
     "Returns an image widget for specified file name `img`."
     return widgets.Image(value=img, format=format, layout=layout)
示例#27
0
# Great! We've now defined our pre-processing function which can convert images from the camera format to the neural network input format.
#
# Now, let's start and display our camera.  You should be pretty familiar with this by now.  We'll also create a slider that will display the
# probability that the robot is blocked.

# In[5]:

print('16 second traitlets')
import traitlets
from IPython.display import display
import ipywidgets.widgets as widgets
from jetbot import Camera, bgr8_to_jpeg

camera = Camera.instance(width=224, height=224)
image = widgets.Image(format='jpeg', width=224, height=224)
blocked_slider = widgets.FloatSlider(description='blocked',
                                     min=0.0,
                                     max=1.0,
                                     orientation='vertical')
#DMF Added Next Line
gpu_slider = widgets.FloatSlider(description="GPU%",
                                 min=0.0,
                                 max=1.0,
                                 orientation='vertical')

camera_link = traitlets.dlink((camera, 'value'), (image, 'value'),
                              transform=bgr8_to_jpeg)

display(widgets.HBox([image, blocked_slider, gpu_slider]))
#16 seconds
示例#28
0
    def visualize_tracker(tracker: "Tracker", sequence: "Sequence"):
        from IPython.display import display
        from ipywidgets import widgets
        from vot.utilities.draw import ImageDrawHandle

        def encode_image(handle):
            with io.BytesIO() as output:
                handle.snapshot.save(output, format="PNG")
                return output.getvalue()

        handle = ImageDrawHandle(sequence.frame(0).image())

        button_restart = widgets.Button(description='Restart')
        button_next = widgets.Button(description='Next')
        button_play = widgets.Button(description='Run')
        frame = widgets.Label(value="")
        frame.layout.display = "none"
        frame2 = widgets.Label(value="")
        image = widgets.Image(value=encode_image(handle), format="png", width=sequence.size[0] * 2, height=sequence.size[1] * 2)

        state = dict(frame=0, auto=False, alive=True, region=None)
        condition = Condition()

        buttons = widgets.HBox(children=(frame, button_restart, button_next, button_play, frame2))

        image.value = encode_image(handle)

        def run():

            runtime = tracker.runtime()

            while state["alive"]:

                if state["frame"] == 0:
                    state["region"], _, _ = runtime.initialize(sequence.frame(0), sequence.groundtruth(0))
                else:
                    state["region"], _, _ = runtime.update(sequence.frame(state["frame"]))

                update_image()

                with condition:
                    condition.wait()

                    if state["frame"] == sequence.length:
                        state["alive"] = False
                        continue

                    state["frame"] = state["frame"] + 1


        def update_image():
            handle.image(sequence.frame(state["frame"]).image())
            handle.style(color="green").region(sequence.frame(state["frame"]).groundtruth())
            if state["region"]:
                handle.style(color="red").region(state["region"])
            image.value = encode_image(handle)
            frame.value = "Frame: " + str(state["frame"] - 1)

        def on_click(button):
            if button == button_next:
                with condition:
                    state["auto"] = False
                    condition.notify()
            if button == button_restart:
                with condition:
                    state["frame"] = 0
                    condition.notify()
            if button == button_play:
                with condition:
                    state["auto"] = not state["auto"]
                    button.description = "Stop" if state["auto"] else "Run"
                    condition.notify()

        button_next.on_click(on_click)
        button_restart.on_click(on_click)
        button_play.on_click(on_click)
        widgets.jslink((frame, "value"), (frame2, "value"))

        def on_update(_):
            with condition:
                if state["auto"]:
                    condition.notify()

        frame2.observe(on_update, names=("value", ))

        thread = Thread(target=run)
        display(widgets.Box([widgets.VBox(children=(image, buttons))]))
        thread.start()
    def createUI(self):

        # ------------
        # Callbacks
        # ------------
        # Callback for image label dropdown menu
        def dropdown_changed(obj):
            # Note that updating the dropdown label in code (e.g. in the updateUI() function)
            # also triggers this change event. Hence need to check if self.boUpdatingUI is False.
            if obj['type'] == 'change' and obj[
                    'name'] == 'value' and not self.boUpdatingUI:
                imgIndex = int(obj['owner'].description[6:])
                imgObj = self.dataset.images[imgIndex]
                newLabelName = obj['owner'].value
                oldLabelName = imgObj.label

                # physically move image to sub-directory of the new label
                imgObj.label = newLabelName
                imgPathSrc = os.path.join(self.imgOrigDir, oldLabelName,
                                          imgObj.filename)
                imgPathDst = os.path.join(self.imgOrigDir, newLabelName,
                                          imgObj.filename)
                if os.path.exists(imgPathDst):
                    raise Exception(
                        "Cannot more image from {} to {} since the destination already exists."
                        .format(imgPathSrc, imgPathDst))
                shutil.move(imgPathSrc, imgPathDst)
                print("Moved image file from {} to {}.".format(
                    imgPathSrc, imgPathDst))

        # Callback for "zoom" button
        def img_button_pressed(obj):
            imgIndex = int(obj.value)
            imgObj = self.dataset.images[imgIndex]
            self.updateZoomUI(imgObj)

        # Callback for "next images" or "previous images" buttons
        def page_button_pressed(obj):
            self.pageIndex += int(obj.value)
            self.pageIndex = max(0, self.pageIndex)
            self.pageIndex = min(self.pageIndex, len(self.pageImgIndices) - 1)
            self.updateUI()

        # Callback for "image page" slider
        def page_slider_changed(obj):
            try:
                self.pageIndex = int(obj['new']['value'])
                self.updateUI()
            except Exception as e:
                pass

        # Init
        self.boUpdatingUI = False

        # ------------
        # UI - image grid
        # ------------
        self.wImgs = []
        self.wLabels = []
        self.wButtons = []
        wImgLabelButtons = []

        for i in range(self.gridSize[0] * self.gridSize[1]):
            # Initialize images
            wImg = widgets.Image(width=150, description="")
            #wImg = widgets.Image(height=400, description="")
            self.wImgs.append(wImg)

            # Initialize dropdown menus
            wLabel = widgets.Dropdown(options=self.labels,
                                      value=self.labels[0],
                                      text="Image 0",
                                      description="Image 0")
            wLabel.layout.width = '200px'
            wLabel.observe(dropdown_changed, names='value')
            self.wLabels.append(wLabel)

            # Initialize zoom buttons
            wButton = widgets.Button(description="Image id: ", value="")
            wButton.layout.width = "100px"
            wButton.button_style = 'warning'
            wButton.on_click(img_button_pressed)
            self.wButtons.append(wButton)

            # combine into image grid widget
            wImgLabelButton = widgets.VBox(children=[wButton, wImg, wLabel])
            wImgLabelButton.width = '230px'
            wImgLabelButtons.append(wImgLabelButton)

        # Image grid widget
        wGridHBoxes = []
        for r in range(self.gridSize[0]):
            hbox = widgets.HBox(children=[
                wImgLabelButtons[r * self.gridSize[1] + c]
                for c in range(self.gridSize[1])
            ])
            hbox.layout.padding = '10px'
            wGridHBoxes.append(hbox)
        wImgGrid = widgets.VBox(wGridHBoxes)

        # ------------
        # UI - zoom window
        # ------------
        wNextPageButton = widgets.Button(description="Next images", value="1")
        wNextPageButton.value = "1"  # should not be necessary but bug on some jupyter versions otherwise
        wNextPageButton.layout.width = '120px'
        wNextPageButton.button_style = 'primary'
        wNextPageButton.on_click(page_button_pressed)

        wPreviousPageButton = widgets.Button(description="Previous images",
                                             value="-1",
                                             layout=Layout(
                                                 color='white',
                                                 background_color='lightblue'))
        wPreviousPageButton.value = "-1"
        wPreviousPageButton.layout.width = '120px'
        wPreviousPageButton.button_style = 'primary'
        wPreviousPageButton.on_click(page_button_pressed)

        self.wPageSlider = IntSlider(min=0,
                                     max=len(self.pageImgIndices) - 1,
                                     step=1,
                                     value=self.pageIndex,
                                     continuous_update=False,
                                     description='Image page:')
        self.wPageSlider.observe(page_slider_changed)

        self.wZoomHeader = widgets.Text("")
        self.wZoomHeader.layout.width = "100px"
        self.wZoomHeader.layout.color = 'white'
        self.wZoomHeader.layout.background_color = 'orange'
        self.wZoomImg = widgets.Image()
        self.wZoomImg.layout.width = str(self.wZoomImgWidth) + 'px'
        self.wZoomTextArea = widgets.Textarea()
        self.wZoomTextArea.layout.width = '500px'
        self.wZoomTextArea.layout.height = '100px'

        #wZoomButtonSlider = widgets.HBox([widgets.VBox([wNextPageButton, wPreviousPageButton]),
        #                                  self.wPageSlider])  # self.wZoomHeader
        wZoomButtonSlider = widgets.VBox(
            [wNextPageButton, wPreviousPageButton, self.wPageSlider])
        wZoomButtonSlider.layout.width = str(self.wZoomImgWidth +
                                             20) + 'px'  # '420px'

        # ------------
        # UI - final
        # ------------
        annotationUI = widgets.HBox(children=[
            widgets.VBox(children=[
                wZoomButtonSlider, self.wZoomImg, self.wZoomTextArea
            ],
                         width=520), wImgGrid
        ])
        annotationUI.layout.border_color = 'black'
        annotationUI.layout.border_style = 'solid'
        tabsUI = widgets.Tab(children=[annotationUI])
        tabsUI.set_title(0, 'Image Annotation')

        # Update UI with actual images
        self.updateUI()
        return (tabsUI)
    def create_ui(self):

        # ------------
        # Callbacks
        # ------------
        # Callback for image label dropdown menu
        def dropdown_changed(obj):
            # Note that updating the dropdown label in code (e.g. in the update_ui() function)
            # also triggers this change event. Hence need to check if self.bo_updating_ui is False.
            if obj['type'] == 'change' and obj[
                    'name'] == 'value' and not self.bo_updating_ui:
                img_index = int(obj['owner'].description[6:])
                new_label = obj['owner'].value
                self.dataset.change_label_for_image(
                    self.dataset.images[img_index], new_label)

        # Callback for "zoom" button
        def img_button_pressed(obj):
            img_index = int(obj.value)
            img_obj = self.dataset.images[img_index]
            self.update_zoom_ui(img_obj, img_index)

        # Callback for "next images" or "previous images" buttons
        def page_button_pressed(obj):
            self.page_index += int(obj.value)
            self.page_index = max(0, self.page_index)
            self.page_index = min(self.page_index,
                                  len(self.page_img_indices) - 1)
            self.update_ui()

        # Callback for "image page" slider
        def page_slider_changed(obj):
            try:
                self.page_index = int(obj['new']['value'])
                self.update_ui()
            except Exception as e:
                pass

        # Init
        self.bo_updating_ui = False

        # ------------
        # UI - image grid
        # ------------
        self.w_imgs = []
        self.w_labels = []
        self.w_buttons = []
        w_img_label_buttons = []

        for i in range(self.grid_size[0] * self.grid_size[1]):
            # Initialize images
            w_img = widgets.Image(width=200, description="")
            self.w_imgs.append(w_img)

            # Initialize dropdown menus
            w_label = widgets.Dropdown(
                options=self.label_options,
                value=self.label_options[self.labels[0].name],
                text="Image 0",
                description="Image 0")
            w_label.layout.width = '200px'
            w_label.observe(dropdown_changed, names='value')
            self.w_labels.append(w_label)

            # Initialize zoom buttons
            w_button = widgets.Button(description="Image id: ", value="")
            w_button.layout.width = "100px"
            w_button.button_style = 'warning'
            w_button.on_click(img_button_pressed)
            self.w_buttons.append(w_button)

            # combine into image grid widget
            w_img_label_button = widgets.VBox(
                children=[w_button, w_img, w_label])
            w_img_label_button.width = '230px'
            w_img_label_buttons.append(w_img_label_button)

        # Image grid widget
        w_grid_HBoxes = []
        for r in range(self.grid_size[0]):
            hbox = widgets.HBox(children=[
                w_img_label_buttons[r * self.grid_size[1] + c]
                for c in range(self.grid_size[1])
            ])
            hbox.layout.padding = '10px'
            w_grid_HBoxes.append(hbox)
        w_img_grid = widgets.VBox(w_grid_HBoxes)

        # ------------
        # UI - zoom window
        # ------------
        w_next_page_button = widgets.Button(description="Next images",
                                            value="1")
        w_next_page_button.value = "1"  # should not be necessary but bug on some jupyter versions otherwise
        w_next_page_button.layout.width = '120px'
        w_next_page_button.button_style = 'primary'
        w_next_page_button.on_click(page_button_pressed)

        w_previous_page_button = widgets.Button(
            description="Previous images",
            value="-1",
            layout=Layout(color='white', background_color='lightblue'))
        w_previous_page_button.value = "-1"
        w_previous_page_button.layout.width = '120px'
        w_previous_page_button.button_style = 'primary'
        w_previous_page_button.on_click(page_button_pressed)

        self.w_page_slider = IntSlider(min=0,
                                       max=len(self.page_img_indices) - 1,
                                       step=1,
                                       value=self.page_index,
                                       continuous_update=False,
                                       description='Image page:')
        self.w_page_slider.observe(page_slider_changed)

        self.w_zoom_header = widgets.Text("")
        self.w_zoom_header.layout.width = "100px"
        self.w_zoom_header.layout.color = 'white'
        self.w_zoom_header.layout.background_color = 'orange'
        self.w_zoom_img = widgets.Image()
        self.w_zoom_img.layout.width = '500px'
        self.w_zoom_text_area = widgets.Textarea()
        self.w_zoom_text_area.layout.width = '500px'
        self.w_zoom_text_area.layout.height = '100px'

        w_zoom_button_slider = widgets.HBox([
            widgets.VBox([w_next_page_button, w_previous_page_button]),
            self.w_page_slider
        ])  # self.w_zoom_header
        w_zoom_button_slider.layout.width = '420px'

        # ------------
        # UI - final
        # ------------
        annotation_ui = widgets.HBox(children=[
            widgets.VBox(children=[
                w_zoom_button_slider, self.w_zoom_img, self.w_zoom_text_area
            ],
                         width=520), w_img_grid
        ])
        annotation_ui.layout.border_color = 'black'
        annotation_ui.layout.border_style = 'solid'
        tabs_ui = widgets.Tab(children=[annotation_ui])
        tabs_ui.set_title(0, 'Image Annotation')

        # Update UI with actual images
        self.update_ui()
        return (tabs_ui)