def to_mime_and_metadata(obj) -> (dict, dict): # noqa: C901 if isinstance(obj, bytes): obj = base64.b64encode(obj).decode("utf-8") return {"text/html": to_html(obj)}, {} elif isinstance(obj, str) and obj.startswith("http"): if re.match(r".*\.(gif|jpg|svg|jpeg||png)$", obj, re.I): try: return Image(obj, embed=True)._repr_mimebundle_() except TypeError: pass return {"text/html": to_html(obj)}, {} elif isinstance(obj, str) and len(obj) < 1024 and os.path.exists(obj): if re.match(r".*\.(gif|jpg|svg|jpeg||png)$", obj, re.I): try: return Image(obj, embed=True)._repr_mimebundle_() except TypeError: pass return {"text/html": to_html(obj)}, {} elif hasattr(obj, "_repr_mimebundle_"): obj.embed = True return obj._repr_mimebundle_() elif hasattr(obj, "_repr_json_"): obj.embed = True return {"application/json": obj._repr_json_()}, {} elif hasattr(obj, "_repr_html_"): obj.embed = True return {"text/html": obj._repr_html_()}, {} elif hasattr(obj, "_repr_png_"): return {"image/png": obj._repr_png_()}, {} elif hasattr(obj, "_repr_jpeg_"): return {"image/jpeg": obj._repr_jpeg_()}, {} elif hasattr(obj, "_repr_svg_"): return {"image/svg": obj._repr_svg_()}, {} try: if isinstance(obj, str): return { "text/html": f"<pre>{to_html(obj)}</pre>".replace("\\n", "\n") }, {} else: data, metadata = JSON(data=obj, expanded=True)._repr_json_() return ( { "application/json": data, "text/html": f"<pre>{to_html(obj)}</pre>" }, metadata, ) except (TypeError, JSONDecodeError): pass try: return {"text/html": to_html(obj)}, {} except TypeError: return {}, {}
def get_jupyter(self): from IPython.core.display import HTML, Image, display for b, result in self.result.items(): error = self.result[b]['else'] if 'else' in self.result[b] else None if error: display(HTML(error)) else: # Show table display(HTML(self.result[b]["Importance"]["table"])) # Show plots display(*list([Image(filename=d["figure"]) for d in self.result[b]['Marginals'].values()])) display(*list([Image(filename=d["figure"]) for d in self.result[b]['Pairwise Marginals'].values()]))
def dog_breed_algorithm(img_path): if dog_detector(img_path): print('Hello, dog!') display(Image(img_path, width=200, height=200)) print('Your predicted breed is ...\n %s' % Xception_predict_breed(img_path)) elif face_detector(img_path): print('Hello, human!') display(Image(img_path, width=200, height=200)) print('You looks like a ...\n %s' % Xception_predict_breed(img_path)) else: display(Image(img_path, width=200, height=200)) print('Could not identify a human or a dog in this image!')
def dog_breed_algorithm(img_path): if dog_detector(img_path) == 1: print("hello, dog!") display(Image(img_path,width=200,height=200)) print("Your predicted breed is ... ") return print(Xception_predict_breed(img_path)) elif face_detector(img_path) == 1: print("hello, human!") display(Image(img_path,width=200,height=200)) print("You look like a ... ") return print(Xception_predict_breed(img_path)) else: display(Image(img_path,width=200,height=200)) return print("Could not identify a human or dog in the chosen image. Please try again.")
def mapStations(stationList, zoom=8): """Return a google static map showing the location of flow and level stations. Globals: STATIONS: Pandas dataframe with HYDAT station data. Args: stationList (str): List of station codes. zoom (int): zoom level of the resulting map. Returns: Image object containing the static map. Stations are displayed as: red: flow station green: level station yellow: flow and level """ locs = ["{0},{1}".format(STATIONS.loc[s,'LATITUDE'], STATIONS.loc[s,'LONGITUDE']) \ for s in stationList] flows = [s for s in stationList if STATIONS.loc[s, 'Flow'] == True] levels = [s for s in stationList if STATIONS.loc[s, 'Level'] == True] bSet = set(levels).intersection(set(flows)) google_maps_url = \ "https://maps.googleapis.com/maps/api/staticmap?" + \ f"key={google_api_key}" + \ "&size=640x400" + \ f"&zoom={zoom}" + \ "&maptype=terrain" + \ "&markers=color:red%7Csize:mid%7Clabel:F%7C" + "|".join(["{0},{1}".format( STATIONS.loc[s,'LATITUDE'], STATIONS.loc[s,'LONGITUDE']) for s in set(flows).difference(bSet)]) + \ "&markers=color:green%7Csize:mid%7Clabel:L%7C" +"|".join(["{0},{1}".format( STATIONS.loc[s,'LATITUDE'], STATIONS.loc[s,'LONGITUDE']) for s in set(levels).difference(bSet)]) + \ "&markers=color:yellow%7Csize:mid%7Clabel:B%7C" + "|".join(["{0},{1}".format( STATIONS.loc[s,'LATITUDE'], STATIONS.loc[s,'LONGITUDE']) for s in bSet]) return Image(requests.get(google_maps_url).content)
def query_content(Limit, Medium, search_param): all_objects = [content for content in Content.query.all() if content.medium.name == Medium if content.search_param == search_param] if len(all_objects) < 1: print('No Content') else: if Medium == 'text': for i in range (0, Limit): title = all_objects[i].title link = all_objects[i].content_url image = all_objects[i].image_url source_name = all_objects[i].provider.provider_name display(HTML("<a href="+link+">"+source_name+': '+title+"</a>")) display(Image(url = image)) elif Medium == 'video': for i in range (0, Limit): title = all_objects[i].title link = all_objects[i].content_url link = link[-11:] source_name = all_objects[i].provider.provider_name display(HTML("<a href="+link+">"+source_name+': '+title+"</a>")) display(HTML('<iframe width="560" height="315" src="https://www.youtube.com/embed/'+link+'?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe>')) else: for i in range (0, Limit): link = all_objects[i].content_url display(HTML("<iframe src="+"'"+link+"'"+ "style='width:100%; height:100px;' scrolling='no' frameborder='no'></iframe>"))
def view_image(i): image = images[i] try: display(Image(filename=image)) print(image) except: print('No image found!')
def test2(): graph = { # 1. Layer 'X': ['A', 'B'], # 2. Layer 'A': ['AA', 'AB'], 'B': ['BA', 'BB'], # 3. Layer 'AA': ['AAA', 'AAB'], 'AB': ['ABA', 'ABB'], 'BA': ['BAA', 'BAB'], 'BB': ['BBA', 'BBB'], # 4. Layer 'AAA': 10, 'AAB': 8, 'ABA': 7, 'ABB': 12, 'BAA': 9, 'BAB': 6, 'BBA': 4, 'BBB': 17, } desc = alpha_beta(graph) print_pretty(desc) digraph = build_viz(graph.keys(), graph, desc, branching=2) digraph.render(filename='img/graph') display(Image(filename='img/graph.png'))
def image(self, filename="snapshot.png", group="all", color="type", diameter="type", size=None, view=None, center=None, up=None, zoom=1.0): cmd_args = [group, "image", filename, color, diameter] if size: width = size[0] height = size[1] cmd_args += ["size", width, height] if view: theta = view[0] phi = view[1] cmd_args += ["view", theta, phi] if center: flag = center[0] Cx = center[1] Cy = center[2] Cz = center[3] cmd_args += ["center", flag, Cx, Cy, Cz] if up: Ux = up[0] Uy = up[1] Uz = up[2] cmd_args += ["up", Ux, Uy, Uz] if zoom: cmd_args += ["zoom", zoom] cmd_args.append("modify backcolor white") self.write_dump(*cmd_args) from IPython.core.display import Image return Image('snapshot.png')
def jupyter_draw_nltk_tree(tree: Tree = None, directory: str = '/tmp', f_name: str = 'tmp', show_tree: bool = False): f_name = Path(directory) / f_name f_name.parent.mkdir(exist_ok=True, parents=True) cf = CanvasFrame() tc = TreeWidget(cf.canvas(), tree) tc['node_font'] = 'arial 13 bold' tc['leaf_font'] = 'arial 14' tc['node_color'] = '#005990' tc['leaf_color'] = '#3F8F57' tc['line_color'] = '#175252' cf.add_widget(tc, 20, 20) ps_file_name = f_name.with_suffix('.ps').as_posix() cf.print_to_file(ps_file_name) cf.destroy() png_file_name = f_name.with_suffix(".png").as_posix() system(f'convert {ps_file_name} {png_file_name}') if show_tree: display((Image(filename=png_file_name), )) system(f'rm {f_name}.ps') return png_file_name
def drawbubble(self, fn='bubble.png', width=1000, height=1000): self.grdevices.png(fn, width=width, height=height) robjects.r( '''plot(ruleset, method="grouped",control=list(col = rev(brewer.pal(9, "Greens")[4:9])),shading ="lift")''' ) self.grdevices.dev_off() return Image(filename=fn)
def drawnetwork(self, fn='network.png', width=800, height=800): self.grdevices.png(fn, width=width, height=height) robjects.r( '''plot(ruleset,measure="confidence",method="graph",control=list(type="items"),shading ="lift")''' ) self.grdevices.dev_off() return Image(filename=fn)
def latex2image(latex, density, export_file=None): """Compile LaTeX to PDF, and convert to PNG.""" temp_dir = tempfile.mkdtemp() try: # make a temp directory, and name temp files temp_tex = os.path.join(temp_dir, 'tikzfile.tex') temp_pdf = os.path.join(temp_dir, 'tikzfile.pdf') temp_png = os.path.join(temp_dir, 'tikzfile.png') with open(temp_tex, 'w') as out: out.write(latex) # run LaTeX to generate a PDF sh_latex(in_file=temp_tex, out_dir=temp_dir) if not os.path.isfile(temp_pdf): raise Exception('pdflatex did not produce a PDF file.') if export_file: shutil.copyfile(temp_pdf, export_file) # convert PDF to PNG sh_convert(in_file=temp_pdf, out_file=temp_png, density=density) # The Image(data=png) thing doesn't work..? # png = b64encode(open(temp_png, "rb").read()) # return Image(data=png) return Image(filename=temp_png) finally: # remove temp directory shutil.rmtree(temp_dir)
def drawscatter(self, fn='scatter.png', width=1000, height=600): self.grdevices.png(fn, width=width, height=height) robjects.r( '''plot(ruleset, control=list(jitter=2,col=rev(brewer.pal(9,"Greens")[4:9])), shading = "lift")''' ) self.grdevices.dev_off() return Image(filename=fn)
def draw_tree(classifier, feature_names): dot_buf = StringIO.StringIO() export_graphviz(classifier, out_file=dot_buf, feature_names=feature_names ) # classifier: clf_model, feature_names: df.columns graph = pydot.graph_from_dot_data(dot_buf.getvalue())[0] image = graph.create_png() return Image(image)
def latex2image(latex, density, export_file=None, debug=False): '''Compile LaTeX to PDF, and convert to PNG.''' try: # make a temp directory, and name temp files temp_dir = tempfile.mkdtemp() temp_tex = join(temp_dir, 'tikzfile.tex') temp_pdf = join(temp_dir, 'tikzfile.pdf') temp_png = join(temp_dir, 'tikzfile.png') with open(temp_tex, 'w') as t: t.write(latex) # run LaTeX to generate a PDF sh_latex(in_file=temp_tex, out_dir=temp_dir, debug=debug) if not isfile(temp_pdf): raise Exception("xelatex didn't produce a PDF file.") if export_file: shutil.copyfile(temp_pdf, export_file) # convert PDF to PNG sh_convert(in_file=temp_pdf, out_file=temp_png, density=density, debug=debug) return Image(data=open(temp_png, "rb").read()) finally: # remove temp directory shutil.rmtree(temp_dir)
def imshow(img): """Displays the image in a Jupyter Notebook Notebook. You can only call this if you're already inside a Jupyter Notebook. """ if "JPY_PARENT_PID" not in os.environ: raise RuntimeError( "_stbt.logging.imshow can only be run inside a Jupyter Notebook") from IPython.core.display import Image, display # pylint:disable=import-error if isinstance(img, basestring): display(Image(img)) else: import cv2 _, data = cv2.imencode(".png", img) display(Image(data=bytes(data.data), format="png"))
def latex2image(latex, density, export_file=None): '''Compile LaTeX to PDF, and convert to PNG.''' try: # make a temp directory, and name temp files temp_dir = tempfile.mkdtemp() temp_tex = temp_dir + '/tikzfile.tex' temp_pdf = temp_dir + '/tikzfile.pdf' temp_png = temp_dir + '/tikzfile.png' open(temp_tex, 'w').write(latex) # run LaTeX to generate a PDF sh_latex(in_file=temp_tex, out_dir=temp_dir) if not isfile(temp_pdf): raise Exception('pdflatex did not produce a PDF file.') if export_file: shutil.copyfile(temp_pdf, export_file) # convert PDF to PNG sh_convert(in_file=temp_pdf, out_file=temp_png, density=density) return Image(temp_png) finally: # remove temp directory shutil.rmtree(temp_dir)
def showdocs(uid, title=""): if uid not in DOCS: display(Markdown("No documentation found for `%s`"%uid)) return d = DOCS[uid] if len(title): title += " " display(Markdown("# %s%s" % (title, d['name']))) display(Markdown(d['desc'])) if 'fn' in d: # display the figures. files = Path(BASEDIR, 'figures').glob("%s.png" % d['fn']) for f in sorted(files,key=lambda x:x.name): #print(f.name) display(Image(filename=f)) # citations md = [] if 'refs' in d and len(d['refs']): md += ["# References"] md += ["\n".join("+ %s" % z for z in d['refs'])] display(Markdown("\n\n\n\n".join(md)))
def ggplot_notebook(gg, width=800, height=600): # adapted from: http://stackoverflow.com/a/15343186 fn = os.path.join(tempfile.gettempdir(), '{uuid}.png'.format(uuid=uuid.uuid4())) grdevices.png(fn, width=width, height=height) gg.plot() grdevices.dev_off() return Image(filename=fn)
def _(G: AnalysisGraph, *args, **kwargs): """ Visualize the analysis graph in a Jupyter notebook cell. """ return Image( to_agraph(G, *args, **kwargs).draw(format="png", prog=kwargs.get("prog", "dot")), retina=True, )
def draw_decision_tree(self, classifier): dot_buf = StringIO() export_graphviz(classifier, out_file=dot_buf, feature_names=self.train_X.columns) graph = pydot.graph_from_dot_data(dot_buf.getvalue())[0] image = graph.create_png() return Image(image)
def to_mime_and_metadata(obj) -> (dict, dict): # noqa: C901 if isinstance(obj, bytes): obj = base64.b64encode(obj).decode('utf-8') return {'text/html': to_html(obj)}, {} elif isinstance(obj, str) and obj.startswith('http'): if re.match(r'.*\.(gif|jpg|svg|jpeg||png)$', obj, re.I): try: return Image(obj, embed=True)._repr_mimebundle_() except TypeError: pass return {'text/html': to_html(obj)}, {} elif isinstance(obj, str) and len(obj) < 1024 and os.path.exists(obj): if re.match(r'.*\.(gif|jpg|svg|jpeg||png)$', obj, re.I): try: return Image(obj, embed=True)._repr_mimebundle_() except TypeError: pass return {'text/html': to_html(obj)}, {} elif hasattr(obj, '_repr_mimebundle_'): obj.embed = True return obj._repr_mimebundle_() elif hasattr(obj, '_repr_json_'): obj.embed = True return {'application/json': obj._repr_json_()}, {} elif hasattr(obj, '_repr_html_'): obj.embed = True return {'text/html': obj._repr_html_()}, {} elif hasattr(obj, '_repr_png_'): return {'image/png': obj._repr_png_()}, {} elif hasattr(obj, '_repr_jpeg_'): return {'image/jpeg': obj._repr_jpeg_()}, {} elif hasattr(obj, '_repr_svg_'): return {'image/svg': obj._repr_svg_()}, {} try: data, metadata = JSON(data=obj, expanded=True)._repr_json_() return { 'application/json': data, 'text/html': f'<pre>{to_html(obj)}</pre>', }, metadata except (TypeError, JSONDecodeError): pass try: return {'text/html': to_html(obj)}, {} except TypeError: return {}, {}
def predict_label(img_path): from IPython.core.display import Image, display if dog_detector(img_path): print('\nhello, dog') display(Image(img_path,width=200,height=200)) print("Your predicted breed is ... ") dog_name = Xception_predict_breed(img_path) return print(dog_name) elif face_detector(img_path): print('\nhello, human') display(Image(img_path,width=200,height=200)) dog_name = Xception_predict_breed(img_path) print("You look like a ... ") return print(dog_name) else: print('\n') display(Image(img_path,width=200,height=200)) return print("Sorry! Could not identify a human or dog in the chosen image. Please try again.")
def svg(self, width=6, height=4): """ Build an Ipython "Image" (requires iPython). """ with grdevices.render_to_bytesio(grdevices.svg, width=width, height=height) as b: robjects.r("print")(self) data = b.getvalue() ip_img = Image(data=data, format='svg', embed=False) return ip_img
def show_images(images, path='result.png', rows=8): save_image(images, path, nrow=rows, padding=1, pad_value=1.0, scale_each=False, normalize=False) display(Image(path))
def get_plot_as_image(self): import matplotlib.pyplot as plt from IPython.core.display import Image with io.BytesIO() as fobj: self.call_plotting_func() plt.savefig(fobj, format="png") plt.close() return Image(data=fobj.getvalue(), format="png")
def show_example(fpath="data/static/DraughtPlot_example.gif"): """ Displays a .gif demonstrating how to use the tool. Parameters: ----------- fpath : str, default="data/static/DraughtPlot_example.gif" Location of example .gif to show. """ return Image(filename=fpath)
def image_png(gg, width=800, height=400): with grdevices.render_to_bytesio(grdevices.png, type="cairo-png", width=width, height=height, antialias="subpixel") as b: robjects.r("print")(gg) data = b.getvalue() ip_img = Image(data=data, format='png', embed=True) return ip_img
def show_flowers(): print('Iris virginica') display( Image( url= 'https://upload.wikimedia.org/wikipedia/commons/thumb/9/9f/Iris_virginica.jpg/1024px-Iris_virginica.jpg' )) print('Iris setosa') display( Image( url= 'https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/Kosaciec_szczecinkowaty_Iris_setosa.jpg/450px-Kosaciec_szczecinkowaty_Iris_setosa.jpg' )) print('Iris versicolor') display( Image( url= 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Iris_versicolor_3.jpg/800px-Iris_versicolor_3.jpg' ))