Voila not clearing output/dispalying new output - jupyter

I am trying to get an ipywidget button to change colour when clicked. I figured a way to do it as below
import ipywidgets as ipw
from ipywidgets import *
from IPython.display import display, HTML, clear_output
from IPython.display import display, HTML
pdf_btn = ipw.Button(description = 'Run PDF',button_style = 'danger',
layout=Layout(width='150px', height='30px'))
new_btn = ipw.Button(description = 'PDF done',button_style = 'success',
layout=Layout(width='150px', height='30px'))
HBox = ipw.HBox([pdf_btn])
HBox1 = ipw.HBox([new_btn])
def clear(b):
clear_output()
display(HBox1)
pdf_btn.on_click(clear)
display(HBox)
When inputting this code in Jupyter Notebook and rendering through Voila nothing happens.
Any ideas why ? And any suggestions ?

You can just update the button style maybe? Like so:
import ipywidgets as ipw
from ipywidgets import *
from IPython.display import display, HTML, clear_output
from IPython.display import display, HTML
pdf_btn = ipw.Button(description = 'Run PDF',button_style = 'danger',
layout=Layout(width='150px', height='30px'))
HBox = ipw.HBox([pdf_btn])
def clear(b):
pdf_btn.button_style="success"
pdf_btn.description="PDF done"
pdf_btn.on_click(clear)
display(HBox)
Note that your code fails in JupyterLab.
Voila is much more similar to JupyterLab's rendering machinery than the classic interface. For now, it is best to use JupyterLab in conjunction with developing for Voila. (Note that this will change soon as the underlying machinery for what is now the traditional Jupyter notebook interface will soon run on machinery more in line with JupyterLab, see Build Jupyter Notebook v7 off of JupyterLab components. A lot of the old code / approaches will then consistently not work and either interface will be as suitable for developing with Voila in mind.)
When your code fails in JupyterLab it logs that to the console, similar to as shown here. I suspect you could follow Jason's advice, what I reference in my reply, which is here, if you actually want the other button there. (I guess I should say if you actually want the other HBox there since for some reason you have each button in a separate HBox in your code.) In other words, you'd need to add in how to handle the output from HBox1 correctly as part of the main output. Yours is going to the JupyterLab Log console as it is now.
So one option is to add HBox1 in as a displayed item, yet hide it initially:
import ipywidgets as ipw
from ipywidgets import *
from IPython.display import display, HTML, clear_output
from IPython.display import display, HTML
pdf_btn = ipw.Button(description = 'Run PDF',button_style = 'danger',
layout=Layout(width='150px', height='30px'))
new_btn = ipw.Button(description = 'PDF done',button_style = 'success',
layout=Layout(width='150px', height='30px'))
HBox = ipw.HBox([pdf_btn])
HBox1 = ipw.HBox([new_btn])
HBox1.layout.visibility = 'hidden' #based on https://github.com/jupyter-widgets/ipywidgets/issues/674#issuecomment-234321603
def clear(b):
HBox1.layout.visibility = 'visible'
HBox.layout.display = 'none' #based on https://stackoverflow.com/a/54134344/8508004
pdf_btn.on_click(clear)
display(HBox)
display(HBox1)
You could also make an overarching vertical box for the items and then toggle which one it contains, similar to here. This is the 'cleanest' option I'll list here, other than just having one button & changing the button itself:
import ipywidgets as ipw
from ipywidgets import *
from IPython.display import display, HTML, clear_output
from IPython.display import display, HTML
pdf_btn = ipw.Button(description = 'Run PDF',button_style = 'danger',
layout=Layout(width='150px', height='30px'))
new_btn = ipw.Button(description = 'PDF done',button_style = 'success',
layout=Layout(width='150px', height='30px'))
HBox = ipw.HBox([pdf_btn])
HBox1 = ipw.HBox([new_btn])
vb = VBox(children = [HBox])
def clear(b):
vb.children = [HBox1]
pdf_btn.on_click(clear)
display(vb)
('cleanest' in regards to it not creating extra space in the output area.)
Or combine the vertical box approach with the approach of toggling off via the layout settings:
import ipywidgets as ipw
from ipywidgets import *
from IPython.display import display, HTML, clear_output
from IPython.display import display, HTML
pdf_btn = ipw.Button(description = 'Run PDF',button_style = 'danger',
layout=Layout(width='150px', height='30px'))
new_btn = ipw.Button(description = 'PDF done',button_style = 'success',
layout=Layout(width='150px', height='30px'))
HBox = ipw.HBox([pdf_btn])
HBox1 = ipw.HBox([new_btn])
HBox1.layout.visibility = 'hidden' #based on https://github.com/jupyter-widgets/ipywidgets/issues/674#issuecomment-234321603
vb = VBox(children = [HBox, HBox1])
def clear(b):
HBox1.layout.visibility = 'visible'
HBox.layout.display = 'none' #based on https://stackoverflow.com/a/54134344/8508004
pdf_btn.on_click(clear)
display(vb)
And if you want to fully leverage Jupyter's display system further, combine it with an overarching out so you can use print(), too:
import ipywidgets as ipw
from ipywidgets import *
from IPython.display import display, HTML, clear_output
from IPython.display import display, HTML
out = widgets.Output()
pdf_btn = ipw.Button(description = 'Run PDF',button_style = 'danger',
layout=Layout(width='150px', height='30px'))
new_btn = ipw.Button(description = 'PDF done',button_style = 'success',
layout=Layout(width='150px', height='30px'))
HBox = ipw.HBox([pdf_btn])
HBox1 = ipw.HBox([new_btn])
vb = VBox(children = [HBox])
def clear(b):
vb.children = [HBox1]
with out:
print('Enjoy!')
pdf_btn.on_click(clear)
with out:
display(vb)
out

Related

unable to get repr for <class 'albumentations.core.composition.compose'>

I am trying to run a code repository downloaded from GitHub as it is mentioned in the instruction of that but getting following error.
TypeError: init() missing 1 required positional argument: 'image_paths'
I am having this error at the code line 63 (preprocessing = preprocessing).
When I srat the program in debug mode I shows following error
unable to get repr for <class 'albumentations.core.composition.compose'>
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import torch
from skimage import io
from utils import adjust_sar_contrast, compute_building_score, plot_images
sys.path.append('/home/salman/Downloads/SpaceNet_SAR_Buildings_Solutions-master/4-motokimura/tmp/work')
from spacenet6_model.configs.load_config import get_config_with_previous_experiment
from spacenet6_model.datasets import SpaceNet6TestDataset
from spacenet6_model.models import get_model
from spacenet6_model.transforms import get_augmentation, get_preprocess
# select previous experiment to load
exp_id = 14
exp_log_dir = "/home/salman/Downloads/SpaceNet_SAR_Buildings_Solutions-master/4-motokimura/tmp/logs" # None: use default
# select device to which the model is loaded
cuda = True
if cuda:
device = 'cuda'
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
else:
device = 'cpu'
os.environ['CUDA_VISIBLE_DEVICES'] = ''
# overwrite default config with previous experiment
config = get_config_with_previous_experiment(exp_id=exp_id, exp_log_dir=exp_log_dir)
# overwrite additional hyper parameters
config.MODEL.DEVICE = device
config.WEIGHT_ROOT = "/home/salman/Downloads/SpaceNet_SAR_Buildings_Solutions-master/4-motokimura/tmp/weights/"
config.MODEL.WEIGHT = f"/home/salman/Downloads/SpaceNet_SAR_Buildings_Solutions-master/4-motokimura/tmp/weights/exp_{exp_id:04d}/model_best.pth"
config.INPUT.MEAN_STD_DIR = "/home/salman/Downloads/SpaceNet_SAR_Buildings_Solutions-master/4-motokimura/tmp/work/models/image_mean_std/"
config.INPUT.TEST_IMAGE_DIR = "/home/salman/data/SN6_buildings_AOI_11_Rotterdam_test_public/test_public/AOI_11_Rotterdam/SAR-Intensity"
config.INPUT.SAR_ORIENTATION="/home/salman/Downloads/SpaceNet_SAR_Buildings_Solutions-master/4-motokimura/tmp/work/static/SAR_orientations.txt"
config.TRAIN_VAL_SPLIT_DIR="/home/salman/Downloads/data/spacenet6/split"
config.PREDICTION_ROOT="/home/salman/Downloads/data/spacenet6/predictions"
config.POLY_CSV_ROOT="/home/salman/Downloads/data/spacenet6/polygons"
config.CHECKPOINT_ROOT="/home/salman/Downloads/data/spacenet6/ceckpoints"
config.POLY_OUTPUT_PATH="/home/salman/Downloads/data/spacenet6/val_polygons"
config.freeze()
print(config)
model = get_model(config)
model.eval();
from glob import glob
image_paths = glob(os.path.join(config.INPUT.TEST_IMAGE_DIR, "*.tif"))
#print(image_paths)
preprocessing = get_preprocess(config, is_test=True)
augmentation = get_augmentation(config, is_train=False)
test_dataset = SpaceNet6TestDataset(
config,
augmentation=augmentation,
preprocessing=preprocessing
)
test_dataset_vis = SpaceNet6TestDataset(
config,
augmentation=augmentation,
preprocessing=None
)
channel_footprint = config.INPUT.CLASSES.index('building_footprint')
channel_boundary = config.INPUT.CLASSES.index('building_boundary')
score_thresh = 0.5
alpha = 1.0
start_index = 900
N = 20
for i in range(start_index, start_index + N):
image_vis = test_dataset_vis[i]['image']
image = test_dataset[i]['image']
x_tensor = image.unsqueeze(0).to(config.MODEL.DEVICE)
pr_score = model.module.predict(x_tensor)
pr_score = pr_score.squeeze().cpu().numpy()
pr_score_building = compute_building_score(
pr_score[channel_footprint],
pr_score[channel_boundary],
alpha=alpha
)
pr_mask = pr_score_building > score_thresh
rotated = test_dataset[i]['rotated']
if rotated:
image_vis = np.flipud(np.fliplr(image_vis))
pr_mask = np.flipud(np.fliplr(pr_mask))
plot_images(
SAR_intensity_0=(adjust_sar_contrast(image_vis[:, :, 0]), 'gray'),
building_mask_pr=(pr_mask, 'viridis')
)
The function which this code calls is given below:
def get_spacenet6_preprocess(config, is_test):
"""
"""
mean_path = os.path.join(
config.INPUT.MEAN_STD_DIR,
config.INPUT.IMAGE_TYPE,
'mean.npy'
)
mean = np.load(mean_path)
mean = mean[np.newaxis, np.newaxis, :]
std_path = os.path.join(
config.INPUT.MEAN_STD_DIR,
config.INPUT.IMAGE_TYPE,
'std.npy'
)
std = np.load(std_path)
std = std[np.newaxis, np.newaxis, :]
if is_test:
to_tensor = albu.Lambda(
image=functools.partial(_to_tensor)
)
else:
to_tensor = albu.Lambda(
image=functools.partial(_to_tensor),
mask=functools.partial(_to_tensor)
)
preprocess = [
albu.Lambda(
image=functools.partial(
_normalize_image,
mean=mean,
std=std
)
),
to_tensor,
]
return albu.Compose(preprocess)

CallBack Error updating graph.figure - DASH

New here and to the world of python.
Generating a histogram plot where it changes color when a postcode is selected.
Now I have the main histogram but when the postcode is selected from the dropdown it gives the error. Unable to figure out how to resolve this. I have provided my full code below.
Let me know if more info is required to figure out the error. Something to do with input
import pandas as pd
import plotly.express as px
from dash import Dash, html, dcc, Input, Output
app = Dash(__name__)
app.title = "EGMs in NSW"
# Load your data : br = .....
datalist=pd.read_excel('premises-list-Aug-2022.xlsx',skiprows=[0,1,2])
datalist['Licence type'] = datalist['Licence type'].str.split(" - ").str.get(1)
datalist['Licence type'] = datalist['Licence type'].str.title()
postcode = datalist['Postcode']
postcode = postcode.sort_values(ascending=True)
postcode=list(dict.fromkeys(postcode))
pd.Series(datalist['Postcode'].unique()).sort_values(ascending=True)
def make_histogram_plot():
# Create scatter plot
fig=px.histogram(
data_frame = datalist,
x='Licence type',y='EGMs',color='Postcode',title='EGMs by Licence Type in NSW',
histfunc='avg'
)
fig.update_traces(marker=dict(color="#002664"))
fig.update_layout(
plot_bgcolor='#EAEDF4',
xaxis_title=None,
yaxis_title='Average EGMs'
)
return fig
app.layout = html.Div(children=[
html.Div([
dcc.Dropdown(postcode,value=[], placeholder="Select postcodes", multi=True, id='postcodes')
]),
dcc.Graph(id = 'graph',figure = make_histogram_plot())
])
#app.callback(
Output('graph','figure'),
Input('postcodes','value')
)
def dropdown_changed(postcodes):
if postcodes==[]:
fig = make_histogram_plot()
else:
datalist2 = datalist[datalist['Postcode'].isin(postcodes)],
# Create scatter plot
fig=px.histogram(
data_frame = datalist2,
x='Licence type',y='EGMs',color='Postcode',title='EGMs by Licence Type in NSW',
histfunc='avg'
)
fig.update_traces(marker=dict(color="#002664"))
fig.update_layout(
plot_bgcolor='#EAEDF4',
xaxis_title=None,
yaxis_title='Average EGMs'
)
return fig
# Start the server
if __name__ == '__main__':
app.run_server(debug=True)

Jupyter Importing Ipynb files Error: no module named 'mynotebook'

I need to import different ipynb files, so I tried this:
https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Importing%20Notebooks.html
But I get no module named 'mynotebook' found. (I even tried it with other notebooks names, which definitely exist, but still not working)
Do you have any ideas about what I could do?
import io, os, sys, types
from IPython import get_ipython
from nbformat import read
from IPython.core.interactiveshell import InteractiveShell
def find_notebook(fullname, path=None):
name = fullname.rsplit('.', 1)[-1]
if not path:
path = ['']
for d in path:
nb_path = os.path.join(d, name + ".ipynb")
if os.path.isfile(nb_path):
return nb_path
# let import Notebook_Name find "Notebook Name.ipynb"
nb_path = nb_path.replace("_", " ")
if os.path.isfile(nb_path):
return nb_path
class NotebookLoader(object):
def __init__(self, path=None):
self.shell = InteractiveShell.instance()
self.path = path
def load_module(self, fullname):
"""import a notebook as a module"""
path = find_notebook(fullname, self.path)
print ("importing Jupyter notebook from %s" % path)
# load the notebook object
with io.open(path, 'r', encoding='utf-8') as f:
nb = read(f, 4)
# create the module and add it to sys.modules
# if name in sys.modules:
# return sys.modules[name]
mod = types.ModuleType(fullname)
mod.__file__ = path
mod.__loader__ = self
mod.__dict__['get_ipython'] = get_ipython
sys.modules[fullname] = mod
# extra work to ensure that magics that would affect the user_ns
# actually affect the notebook module's ns
save_user_ns = self.shell.user_ns
self.shell.user_ns = mod.__dict__
try:
for cell in nb.cells:
if cell.cell_type == 'code':
# transform the input to executable Python
code = self.shell.input_transformer_manager.transform_cell(cell.source)
# run the code in themodule
exec(code, mod.__dict__)
finally:
self.shell.user_ns = save_user_ns
return mod
class NotebookFinder(object):
def __init__(self):
self.loaders = {}
def find_module(self, fullname, path=None):
nb_path = find_notebook(fullname, path)
if not nb_path:
return
key = path
if path:
# lists aren't hashable
key = os.path.sep.join(path)
if key not in self.loaders:
self.loaders[key] = NotebookLoader(path)
return self.loaders[key]
sys.meta_path.append(NotebookFinder())
import mynotebook
I just want to import the code of another jupyter file
WOW, i also face this problem. I create a new env and after open jupyter, it can't find nbformat in my new installed env, so just:
pip install nbformat

How to Fix unident does not match for any outer indentation level

i have tried to make a desktop assistant as voice recognizer and do as i say
but i get this error every time i try to run that: unindent does not match with any outer indentation level. can someone please help me!
it is somehow copied from YouTube video
gtts import gTTS
import speech_recognition as sr
import os
import webbrowser
import smtplib
def talktome(audio):
print(audio)
tts = gTTS(text=audio, lang='eng')
tts.save('audio.mp3')
os.system('mpg123 audio.mp3')
def myCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print('hello')
r.pause_threshold = 1
r.adjust_for_ambient_noise(source, duration = 1)
audio = r.listen(source)
try:
command = r.recognize_google(audio)
print('you said: ' + command + '/n')
except sr.UnknownValueError:
assistant(myCommand())
return command
def assistant(command):
if 'open reddit python' in command:
chrome_pathchrome_path = '/Program Files (x86)/google/Chrome/Application/chrome.exe'
webbrowser.get(chrome_path).open(url)
if 'what\'s up' in command:
talkToMe('i am a bit busy')
if 'email' in command:
talkToMe('who is the recipient?')
recipient = myCommand()
if 'john' in recipient:
talkToMe('what should i say?')
content - myCommand()
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('username', 'password')
mail.sendmail('persion name', 'email address#whatever.com'. content)
mail.close()
talkToMe('email sent')
talkToMe('i am ready for your sound')
while true: assistant(myCommand())

Is there a way to use mss and pytesseract witchout saving and open?

Need to use mss witchout saving and open images in order to "optimize" this task here is mine code and sorry my bad english.
from PIL import Image
import pytesseract
import mss
import mss.tools
with mss.mss() as sct:
monitor = {'top': 171, 'left': 1090, 'width': 40, 'height': 17}
output = 'capture.png'.format(**monitor)
sct_img = sct.grab(monitor)
mss.tools.to_png(sct_img.rgb, sct_img.size, output=output)
text = pytesseract.image_to_string(Image.open('capture.png'))
print(text)
Do you mind using Numpy?
import mss
import numpy
import pytesseract
monitor = {'top': 171, 'left': 1090, 'width': 40, 'height': 17}
with mss.mss() as sct:
im = numpy.array(sct.grab(monitor), dtype=numpy.uint8)
im = numpy.flip(im[:, :, :3], 2) # BGRA -> RGB conversion
text = pytesseract.image_to_string(im)
print(text)
A simple one shot time comparison gives me:
MSS.tools + PIL: 0.00988 s
MSS + Numpy : 0.00222 s