Giter Club home page Giter Club logo

brythonmagic's Introduction

Brythonmagic

Brython magic for the Jupyter notebook.

The brythonmagic provides you a cell magic, %%brython, to run brython code and show the results in a html div tag below the code cell. Best way to start with Brython is to check the Brython docs in their home page.

Tested on

The master branch of brythonmagic extension has been tested on:

  • Jupyter notebook >= 6.1.4

  • Python version >= 3.6

  • Brython versions <= 3.6.x

Installation

You should have Jupyter (notebook) already installed in order to use Brythonmagic. In case you don't have Jupyter installed you can follow the instructions on the Jupyter official page.

Method 1) - Download this repo and on the brythonmagic downloaded folder type:

python setup.py install

Method 2) - Use pip (you will need to install git):

python -m pip install git+https://github.com/kikocorreoso/brythonmagic.git

Then, load the extension in the notebook:

```python
%load_ext brythonmagic

And, finally, load a stable brython js lib in the notebook using the following code:

from brythonmagic import load_brython_stable
load_brython_stable()

If you have any problem with the installation, please, open an issue.

WARNING

In order to load javascript libraries in a safety way you should try to use https instead of http when possible (read more here). If you don't trust the source and/or the source cannot be loaded using https then you could download the javascript library and load it from a local location.

Brythonmagic doesn't load any javascript library and the user should take care about the security and should use trusted sources.

You can load third party javascript libraries using the following code:

from brythonmagic import load_js_lib
load_js_lib("https://url/to/your/lib.js")

Usage

example:

%%brython -c zone
# First of all, the import of some libraries
from browser import document, html

# All the elements will be inserted in the div with the "zone" id
zone = document['zone']

# We create a new div element
newdiv = html.DIV(Id = "new-div")
# Now we add some style
newdiv.style = {"padding": "5px", 
           "backgroundColor": "#ADD8E6"}

# We create a new link and add the link to a string
blink = html.A('brython',href="http://brython.info")
text = "Brython is really cool, look at "+ blink + " for more"

# Now we add the text to the div with id="new-div"
newdiv <= html.DIV(text)

# Finally, we add the newdiv to the outer div with id="zone"
zone <= newdiv

You can use several options:

  • -p, --print: will show you the generated html code below the results obtained from the brython code.

  • -c, --container: you can define the name of the div container in case you want to 'play' with it in other cell. If you don't define an output the div will have an id with the following format 'brython-container-[random number between 0 and 999999]'. Just one container name is accepted. If you pass more than one only the first one will be used and a warning will raise.

  • -i, --input: you can pass variables defined in the Python namespace separated by whitespaces. If you pass a python list it will be converted to a brython list, a python tuple will be converted to a brython tuple, a python dict will be converted to a brython dict, a python string will be converted to a brython string.

  • -h, --html: you can pass a string with html markup code. This html code will be inserted inside the div container. In this way you can avoid the generation of HTML markup code via a Brython script so you can separate the layout from the 'action'. Just one html markup code string name is accepted. If you pass more than one only the first one will be used and a warning will raise.

  • -s, --script: Use this option to provide an id to the script defined in the Brython code cell. Also, this value could be used to run the code of this cell in other brython cells. Just one script name is accepted. If you pass more than one only the first one will be used and a warning will raise.

  • -S, --scripts: Use this option to run code previously defined in other Brython code cells. The values should be the provided values in the -s/--script option in other Brython code cells.

[WARNING] This options may change as the brythonmagic depending the development of Brython and/or Jupyter.

To see some examples download the notebooks available in the repository and run it locally or see it in the nbviewer (you will loose the interactivity if you choose the second option). Also, you can take a look on the following video: http://youtu.be/adQzjuUX0kw

Example notebooks (some options will not work due to changes in APIs)

Support

If you need Brython support, please, ask here: https://groups.google.com/forum/?fromgroups=#!forum/brython

If you need IPython support, please, ask here: http://mail.scipy.org/mailman/listinfo/ipython-dev

If you find a bug or want to propose a new feature open a new issue here: https://github.com/kikocorreoso/brythonmagic/issues

If you want to improve the code, fork, commit and send a PR ;·D

IDEAS

Add an option to include *.py scripts? These *.py scripts should be Brython compatible. ✔ (this could be made via imports with the py script in the same folder as the notebook)

Add an option to include a HTML structure so you don't have to create the structure via Brython code? ✔ (did it)

Add an option to run more than one Brython script in a code cell? Right now, if you run a Brython code cell, the code in other cells will not work anymore. ✔ (did it)

Make it python 2.7 compatible. ✔ (did it)

Create a setup.py to make it available via pip. ✔ (did it)

CONTRIBUTORS

  • Kikocorreoso (pybonacci blog, twitter)
  • baoboa (github) for some insightful comments and code.
  • Roger Veciana (github, twitter) for the review of the Openlayers tutorial.
  • Pierre Quentel and all the Brython committers for their work and their invaluable suggestions and help.

brythonmagic's People

Contributors

kikocorreoso avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

brythonmagic's Issues

-f example with alert does not work

I guess something changed in jupyter, I tried running the alert example and it wasn't happy at all.

I'm running it on localhost:8000 on ubuntu 20.04:

> %%brython -f
> from browser import alert
> alert('hello world from jsfiddle!')
> 
---------------------------------------------------------------------------
HTTPError                                 Traceback (most recent call last)
<ipython-input-14-0e6b058d9c8d> in <module>
----> 1 get_ipython().run_cell_magic('brython', '-f', "from browser import alert\nalert('hello world from jsfiddle!')\n")

~/.local/lib/python3.8/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
   2379             with self.builtin_trap:
   2380                 args = (magic_arg_s, cell)
-> 2381                 result = fn(*args, **kwargs)
   2382             return result
   2383 

<decorator-gen-126> in brython(self, line, cell, local_ns)

~/.local/lib/python3.8/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/.local/lib/python3.8/site-packages/brythonmagic.py in brython(self, line, cell, local_ns)
    344         # If fiddle is selected then create a gist and a fiddle
    345         if args.fiddle or args.embedfiddle:
--> 346             gist_url, jsf_url = _create_gist_fiddle(code_tmp)
    347             gist_html = """<br><a href="{}" target="_blank">gist link</a>\n"""
    348             code += gist_html.format(gist_url)

~/.local/lib/python3.8/site-packages/brythonmagic.py in _create_gist_fiddle(input)
    128     dataj = json.dumps(data)
    129 
--> 130     req = urlopen('https://api.github.com/gists',
    131                                  dataj.encode('utf8'))
    132 

/usr/lib/python3.8/urllib/request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    220     else:
    221         opener = _opener
--> 222     return opener.open(url, data, timeout)
    223 
    224 def install_opener(opener):

/usr/lib/python3.8/urllib/request.py in open(self, fullurl, data, timeout)
    529         for processor in self.process_response.get(protocol, []):
    530             meth = getattr(processor, meth_name)
--> 531             response = meth(req, response)
    532 
    533         return response

/usr/lib/python3.8/urllib/request.py in http_response(self, request, response)
    638         # request was successfully received, understood, and accepted.
    639         if not (200 <= code < 300):
--> 640             response = self.parent.error(
    641                 'http', request, response, code, msg, hdrs)
    642 

/usr/lib/python3.8/urllib/request.py in error(self, proto, *args)
    567         if http_err:
    568             args = (dict, 'default', 'http_error_default') + orig_args
--> 569             return self._call_chain(*args)
    570 
    571 # XXX probably also want an abstract factory that knows when it makes

/usr/lib/python3.8/urllib/request.py in _call_chain(self, chain, kind, meth_name, *args)
    500         for handler in handlers:
    501             func = getattr(handler, meth_name)
--> 502             result = func(*args)
    503             if result is not None:
    504                 return result

/usr/lib/python3.8/urllib/request.py in http_error_default(self, req, fp, code, msg, hdrs)
    647 class HTTPDefaultErrorHandler(BaseHandler):
    648     def http_error_default(self, req, fp, code, msg, hdrs):
--> 649         raise HTTPError(req.full_url, code, msg, hdrs, fp)
    650 
    651 class HTTPRedirectHandler(BaseHandler):

HTTPError: HTTP Error 401: Unauthorized

brython.js version >= 3.7.x is not working

Since Brython version >= 3.7.x I'm getting the following error:

ReferenceError: $locals___main__ is not defined
    <anonymous> brython.js:4
    _run_scripts brython.js:4911
    brython brython.js:4758
    <anonymous> Brython usage in the IPython notebook-Copy1.ipynb:1
    jQuery 3
    _safe_append outputarea.js:459
    append_display_data outputarea.js:666
    append_output outputarea.js:346
    handle_output outputarea.js:257
    output codecell.js:399
    _handle_output_message kernel.js:1198
    i jQuery
    _handle_iopub_message kernel.js:1238
    _finish_ws_message kernel.js:1017
    _msg_queue kernel.js:1008
    promise callback*Kernel.prototype._handle_ws_message kernel.js:1008
    i jQuery
    start_channels kernel.js:517
    _kernel_created kernel.js:412
    on_success kernel.js:317
    _on_success kernel.js:380
    jQuery 6
    ajax utils.js:797
    restart kernel.js:332
    restart_and_resolve notebook.js:2408
    click notebook.js:2435
    jQuery 10
    modal dialog.js:95
    _restart_kernel notebook.js:2439
    restart_kernel notebook.js:2394
    handler actions.js:127
    <anonymous> actions.js:917
    call actions.js:1019
    fun toolbar.js:116

So brython versions >= 3.7.0 could not be used at this moment.

Question

I'm a little confused, whilst brython looks to be an excellent way of bridging the JS/Python space, I thought that iPython Notebooks natively ? So I'm just curious as to whether this integration with HighCharts can be achieve without brython ?

I would love to get this stuff clarified as I've already wasted loads of time trying to get HC working using the native JS support - without much success.

Javascript Errors in HighCharts tutorial

Hi,

I was running through the Highcharts tutorials but I'm getting the following errors when I run some of the examples:

Javascript error adding output!
Error
See your browser Javascript console for more details.

Here's the console output:

GET http://localhost:8888/static/notebook/js/Lib/site-packages/__random.py?v=2 404 (Not Found)
Error 404 means that Python module __random was not found at url http://localhost:8888/static/notebook/js/Lib/site-packages/__random.py
GET http://localhost:8888/static/notebook/js/Lib/site-packages/__random/__init__.py?v=3 404 (Not Found)
Error 404 means that Python module __random was not found at url http://localhost:8888/static/notebook/js/Lib/site-packages/__random/__init__.py
GET http://localhost:8888/notebooks/__random.py?v=4 404 (Not Found)
Error 404 means that Python module __random was not found at url http://localhost:8888/notebooks/__random.py
GET http://localhost:8888/notebooks/__random/__init__.py?v=5 404 (Not Found)
Error 404 means that Python module __random was not found at url http://localhost:8888/notebooks/__random/__init__.py
ImportError: cannot import __random
Traceback (most recent call last):
  module 142103 line 3
    from __random import randrange
Error
    at Error (native)
    at Object._b_.ImportError (eval at $make_exc (http://www.brython.info/src/brython_dist.js?_=1434489102511:6801:11), <anonymous>:79:497)
    at Object.$B.$import (http://www.brython.info/src/brython_dist.js?_=1434489102511:7672:11)
    at Object.$B.$import_from (http://www.brython.info/src/brython_dist.js?_=1434489102511:7687:24)
    at eval (eval at brython (http://www.brython.info/src/brython_dist.js?_=1434489102511:4505:6), <anonymous>:24:4)
    at brython (http://www.brython.info/src/brython_dist.js?_=1434489102511:4505:1)
    at eval (eval at <anonymous> (http://localhost:8888/static/components/jquery/jquery.min.js?v=20150616221030:4:4231), <anonymous>:1:1)
    at eval (native)
    at Function.x.extend.globalEval (http://localhost:8888/static/components/jquery/jquery.min.js?v=20150616221030:4:4231)
    at x.fn.extend.domManip (http://localhost:8888/static/components/jquery/jquery.min.js?v=20150616221030:5:21416)

I'm using iPython 3.1

Thanks for the good work.

not compatible with ipython 2.0

oups!

i did update to ipython 2.0, unfortunately it did break %%brython magic

Javascript error adding output!
ReferenceError: brython is not defined
See your browser Javascript console for more details.
<script id="178606" type="text/python">
from browser import doc, html
doc['output_123'] <= html.P('Hello World!!')
</script>
<script type="text/javascript">brython({debug:1, ipy_id: ["178606"]});</script>
<div id="'output_123'"></div>

the ipython install change the default directory to ~/.ipython
i did create again ~/.ipython/profile_default/static/custom/brython/
and did copy the js files

and now

%%brython -c 'output_123' 
from browser import doc, html
doc['output_123'] <= html.P('Hello World!!')

give an error as

Javascript error adding output!
Error: output_123
See your browser Javascript console for more details.

and if i do that ( without quote )

%%brython -c output_123 
from browser import doc, html
doc['output_123'] <= html.P('Hello World!!')

it work but it's sometimes very slow
and every time a brython magic is used , previous declaration are re-executed
( after using %%brython on multiple cell i got multiple "Hello world !!" in the same output_123 div )

how to use Highstocks with brythonmagic?

Hi,

After reading the excellent Highcharts tutorial, I tried to use Highstocks to build a simple interactive time series plots in the notebook. However, I could not get the 'StockChart' to display properly, only a regular 'Chart' object. Specifically, I was attempting to reproduce the StockChart demo from here.

My attempt is linked in this gist. Any advice for how to get Highstocks to work with brythonmagic? I would very much appreciate the help.

js lib is not loaded when brython script is executed

Sometimes, if you load a heavy js lib, it is possible that the brython script in a code cell will be executed before the js lib is loaded.

It will raise an error because brython is not able to find the needed name in the namespace.

broken package?

I was trying out the open layers example on a recent version of jupyter and python 3.7 and I only see the script outputs in the cells not the interactive maps.

http -> https

The doc/readme suggest to publish a script tag with http:// instead of https://, the js is availlable over https but the certificat id not recognized.

I would suggest still, to move to https:// otherwise you expose users to remote code execution.

Highchart graphs not displaying

Hello,

I've tried to reproduce the Monthly average temperature graph from the HC Notebook but no chart is displayed in the jupyter notebook (tried on both jupyterlab and notebook).

Could you please have a look?

Thanks!

I'm using notebook 6.4.3, jupyterlab 3.1.7, brython 3.6.2, python 3.6.5

Also, this part from the HC notebook:

from brythonmagic import load_brython_dev
load_brython_dev() 

doesn't work as it seems it has been commented in the last version of brythonmagic.py. The error message is: cannot import name 'load_brython_dev'

Input

%load_ext brythonmagic

from brythonmagic import load_js_lib
load_js_lib("https://cdnjs.cloudflare.com/ajax/libs/highcharts/5.0.7/highcharts.js")

html = """<div id="hc_ex1" style="width: 700px; height: 300px;"></div>"""

%%brython -h html -p
from browser import window

Highcharts = window.Highcharts

hc = Highcharts.Chart.new

config = {
    'chart':{
        'renderTo': 'hc_ex1'
    },
    'title': {
        'text': 'Monthly Average Temperature',
        'x': -20 #center
    },
    'subtitle': {
        'text': 'Source: WorldClimate.com',
        'x': -20
    },
    'xAxis': {
        'categories': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },
    'yAxis': {
        'title': {
            'text': 'Temperature (°C)'
        },
        'plotLines': [{
            'value': 0,
            'width': 1,
            'color': '#808080'
        }]
    },
    'tooltip': {
        'valueSuffix': '°C'
    },
    'legend': {
        'layout': 'vertical',
        'align': 'right',
        'verticalAlign': 'middle',
        'borderWidth': 0
    },
    'series': [{
        'name': 'Tokyo',
        'data': [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
    }]
}

hc(config)

Output: (only script but not plot)

  <script id="353830" type="text/python">
from browser import window

Highcharts = window.Highcharts

hc = Highcharts.Chart.new

config = {
    'chart':{
        'renderTo': 'hc_ex1'
    },
    'title': {
        'text': 'Monthly Average Temperature',
        'x': -20 #center
    },
    'subtitle': {
        'text': 'Source: WorldClimate.com',
        'x': -20
    },
    'xAxis': {
        'categories': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },
    'yAxis': {
        'title': {
            'text': 'Temperature (°C)'
        },
        'plotLines': [{
            'value': 0,
            'width': 1,
            'color': '#808080'
        }]
    },
    'tooltip': {
        'valueSuffix': '°C'
    },
    'legend': {
        'layout': 'vertical',
        'align': 'right',
        'verticalAlign': 'middle',
        'borderWidth': 0
    },
    'series': [{
        'name': 'Tokyo',
        'data': [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
    }]
}

hc(config)

  </script>
  <div id="brython_container_353830"><div id="hc_ex1" style="width: 700px; height: 300px;"></div></div>
  <script type="text/javascript">brython({debug:1, static_stdlib_import: false, ipy_id: ["353830"]});</script>

DeprecationWarning: `should_run_async` will not call `transform_cell`

Jupyter complains trying to use this extension, when you run each cell

/home/stu/.local/lib/python3.8/site-packages/ipykernel/ipkernel.py:287: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.
  and should_run_async(code)

brythonmagic can't import brython modules

Brython version 2.1.0 introduces a new option for the brython() function. If the following

static_stdlib_import: false

is not added explicitly to the brython() function options the import mechanism will be looking for some folders that doesn't exist if we use brython_dist.js, as brythonmagic does.

Does print() work ?

I was expecting to be able to do something like

print(1)

And see the output in the cell, are my expectations incorrect (I guess maybe I'm after a brython kernel ?)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.