Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions apps/jupyter-kernel/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
BSD 3-Clause License

Copyright (c) 2017, Project Jupyter Contributors
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2 changes: 2 additions & 0 deletions apps/jupyter-kernel/MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
include README.rst
recursive-include universalpython/languages *.yaml
39 changes: 39 additions & 0 deletions apps/jupyter-kernel/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
universalpython_kernel
===========

> Run UniversalPython code in Jupyter Notebook

``universalpython_kernel`` is a simple wrapper over Jupyter's IPython kernel. It simply translates the code from human language to English before passing it on to IPython.

You can learn more about wrapper kernels here:

http://jupyter-client.readthedocs.io/en/latest/wrapperkernels.html

Installation
------------
To install ``universalpython_kernel`` from this repository::

git clone <LINK TO THIS REPO>
cd universalpython_kernel
pip install -e .
python setup.py install
python -m universal_python.install

Using the UniversalPython kernel
---------------------
**Notebook**: The *New* menu in the notebook should show an option for an UniversalPython notebook.

**Console frontends**: To use it with the console frontends, add ``--kernel universalpython`` to
their command line arguments.

How to select a human language
------------------------------
You can specify the language for your code by adding a special comment at the top of your file or cell:

# language: ur

or

# language: hi

If no language is specified, Urdu (`ur`) will be used by default.
28 changes: 28 additions & 0 deletions apps/jupyter-kernel/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from distutils.core import setup

with open('README.rst') as f:
readme = f.read()

import os

setup(
name='universal_python',
version='1.1',
packages=['universal_python',],
description='UniversalPython kernel for Jupyter',
long_description=readme,
author='Saad Bazaz',
author_email='saadbazaz@hotmail.com',
url='https://github.com/UniversalPython/UniversalPython',
install_requires=[
'jupyter_client',
'IPython',
'ipykernel',
'universalpython'
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3',
],
)
5 changes: 5 additions & 0 deletions apps/jupyter-kernel/universal_python/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""An example Jupyter kernel"""

__version__ = '1.1'

from .kernel import UniversalPythonKernel
4 changes: 4 additions & 0 deletions apps/jupyter-kernel/universal_python/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from ipykernel.kernelapp import IPKernelApp
from . import UniversalPythonKernel

IPKernelApp.launch_instance(kernel_class=UniversalPythonKernel)
50 changes: 50 additions & 0 deletions apps/jupyter-kernel/universal_python/install.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import argparse
import json
import os
import sys

from jupyter_client.kernelspec import KernelSpecManager
from IPython.utils.tempdir import TemporaryDirectory

kernel_json = {
"argv": [sys.executable, "-m", "universal_python", "-f", "{connection_file}"],
"display_name": "UniversalPython",
"language": "text",
}

def install_my_kernel_spec(user=True, prefix=None):
with TemporaryDirectory() as td:
os.chmod(td, 0o755) # Starts off as 700, not user readable
with open(os.path.join(td, 'kernel.json'), 'w') as f:
json.dump(kernel_json, f, sort_keys=True)
# TODO: Copy any resources

print('Installing Jupyter kernel spec')
KernelSpecManager().install_kernel_spec(td, 'universalpython', user=user, replace=True, prefix=prefix)

def _is_root():
try:
return os.geteuid() == 0
except AttributeError:
return False # assume not an admin on non-Unix platforms

def main(argv=None):
ap = argparse.ArgumentParser()
ap.add_argument('--user', action='store_true',
help="Install to the per-user kernels registry. Default if not root.")
ap.add_argument('--sys-prefix', action='store_true',
help="Install to sys.prefix (e.g. a virtualenv or conda env)")
ap.add_argument('--prefix',
help="Install to the given prefix. "
"Kernelspec will be installed in {PREFIX}/share/jupyter/kernels/")
args = ap.parse_args(argv)

if args.sys_prefix:
args.prefix = sys.prefix
if not args.prefix and not _is_root():
args.user = True

install_my_kernel_spec(user=args.user, prefix=args.prefix)

if __name__ == '__main__':
main()
83 changes: 83 additions & 0 deletions apps/jupyter-kernel/universal_python/kernel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
from ipykernel.kernelbase import Kernel

from ipykernel.ipkernel import IPythonKernel

from universalpython import run_module

import traceback

from io import StringIO
import sys
class UniversalPythonKernel(IPythonKernel):
implementation = 'UniversalPython'
implementation_version = '1.1'
# language_version = '0.1'
language_info = {
'name': 'python',
'version': sys.version.split()[0],
'mimetype': 'text/x-python',
'file_extension': '.py',
}
banner = "UniversalPython kernel"

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.current_language = ""

def get_language_and_code(self, code):
lines = code.splitlines()
lang = self.current_language
if lines and lines[0].strip().startswith("# language:"):
lang_flag = lines[0].strip().split(":", 1)[-1].strip()
if lang_flag:
lang = lang_flag
self.current_language = lang # persist for future cells
code = "\n".join(lines[1:]) # Remove the flag line
return lang

def do_execute(self, code, silent, store_history=True, user_expressions=None,
allow_stdin=False):
error_thrown = False

compiled_code = ""
lang = self.get_language_and_code(code)

try:
compiled_code = run_module("lex", code, args = {
'translate': True,
'reverse': False,
'dictionary': '',
'source_language': lang,
'keep': False,
'keep_only': False,
'return': True,
'file': '',
'suppress_warnings': True, # Suppress warnings during compilation
})
except Exception as e:
error_thrown = True
error_message = "Error while compiling code: " + str(e)
print (error_message)

return super(UniversalPythonKernel, self).do_execute(compiled_code, silent, store_history, user_expressions,
allow_stdin)


def do_complete(self, code, cursor_pos):
error_thrown = False

lang = self.get_language_and_code(code)

compiled_code = run_module("lex", code, args = {
'translate': True,
'reverse': False,
'dictionary': '',
'source_language': lang,
'keep': False,
'keep_only': False,
'return': True,
'file': '',
'suppress_warnings': True, # Suppress warnings during compilation
})

return super(UniversalPythonKernel, self).do_complete(compiled_code, cursor_pos)
4 changes: 4 additions & 0 deletions apps/jupyter-kernel/universal_python/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
notebook<7
jupyter
rise
cryostasis