예제 #1
0
def Viewer(nburl=None, showcode=False, render='html'):

    from IPython.nbformat import reader as nbformat
    from IPython.nbconvert import exporters

    # Get url or file path
    if nburl:

        if nburl.startswith("http"):
            import requests
            response = requests.get(nburl)
            notebook = nbformat.reads_json(response.content)

        else:
            notebook = nbformat.read(fp=file(nburl))

    else:
        notebook = ''

# Get rendering template
    if showcode:

        if render == 'html':
            template = 'full'

    else:

        if render == 'html':
            template = 'full2'

    import IPython.nbconvert
    from IPython.config import Config
    from IPython.nbconvert import HTMLExporter

    ## I use `basic` here to have less boilerplate and headers in the HTML.
    ## we'll see later how to pass config to exporters.
    exportHtml = HTMLExporter(
        config=Config({'HTMLExporter': {
            'template_file': template
        }}))

    (body, resources) = exportHtml.from_filename(nburl)

    return body
예제 #2
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import glob

from IPython.config import Config
from IPython.nbconvert import HTMLExporter

c = Config({'ExecutePreprocessor': {'enabled': True}})

exporter = HTMLExporter(config=c)

for filename in glob.glob("example-notebooks/*.ipynb"):
    print(filename)
    exporter.from_filename(filename)
예제 #3
0
def publish(notebook_name,
            url_path,
            page_title,
            page_description,
            ignore_last_n_cells=2,
            uses_plotly_offline=False,
            thumbnail=DEFAULT_THUMBNAIL_URL,
            **kwargs):
    '''
    Convert an IPython notebook into an HTML file that can be consumed
    by GitHub pages in plotly's documentation repo.

    Arguments:
    - notebook_name: The name of the notebook to convert.
                     Used as input arg to nbconvert, nowhere else.
    - url_path: e.g. /python/offline
    - page_title: The <title> of the page.
    - page_description: So, what's this page about?
                        Sell it in 160 characters or less.
                        This is the <meta name="description"> tag.
    - ignore_last_n_cells: When converting to HTML, don't convert the
                           ignore_last_n_cells number of cells.
                           This is usually the cell that runs this `publish`
                           command and the blank output cell that is always
                           included.
    - uses_plotly_offline: If this was created with plotly.offline, then set
                           this to True. This will include an extra lib
                           (jquery) that is included in ipython notebook,
                           but not included in gh-pages
    - thumbnail: Used as a thumbnail image on the notebook splash
                     (if applicable) and as the image when sharing the
                     notebook as a tweet, a facebook post, etc.
                     Can be relative to the repo, eg '/images/static-image'
                     or absolute, e.g. http://i.imgur.com/j0Uiy0n.jpg
    - language: Not sure what this is used for.

    Example:
    publish('Plotly Offline',
            '/python/offline',
            'Plotly Offline for IPython Notebooks',
            'How to use Plotly offline inside IPython notebooks with Plotly Offline',
             uses_plotly_offline=True)
    '''
    # backwards compatability
    if 'thumbnail_url' in kwargs and kwargs[
            'thumbnail'] == DEFAULT_THUMBNAIL_URL:
        kwargs['thumbnail'] = kwargs['thumbnail_url']

    warnings.warn('Did you "Save" this notebook before running this command? '
                  'Remember to save, always save.')

    parts = url_path.split('/')
    if len(parts) > 3:
        warnings.warn('Your URL has more than 2 parts... are you sure?')
    if url_path[-1] == '/':
        url_path = url_path[:-1]
    if len(page_description) > 160:
        raise Exception("Shorten up that page_description! "
                        "Your description was {} characters, "
                        "and it's gotta be <= than 160.".format(
                            len(page_description)))

    if thumbnail == DEFAULT_THUMBNAIL_URL:
        has_thumbnail = 'false'
    else:
        has_thumbnail = 'true'

    if '.ipynb' not in notebook_name:
        notebook_name += '.ipynb'
    fn = notebook_name
    tmpfn = 'temp-{}'.format(fn)
    nbjson = json.load(open(fn))
    if 'cells' in nbjson:
        nbjson['cells'] = nbjson['cells'][:-ignore_last_n_cells]
    elif 'worksheets' in nbjson:
        if len(nbjson['worksheets']) != 1:
            raise Exception('multiple worksheets?')
        elif 'cells' in nbjson['worksheets'][0]:
            nbjson['worksheets'][0]['cells'] = nbjson['worksheets'][0][
                'cells'][:-ignore_last_n_cells]
        else:
            raise Exception('cells not in worksheets[0]?')
    else:
        raise Exception('unknown ipython notebook format')
    with open(tmpfn, 'w') as f:
        f.write(json.dumps(nbjson))

    exporter = HTMLExporter(template_file='basic')
    html = exporter.from_filename(tmpfn)[0]

    kwargs.setdefault('layout', 'user-guide')
    kwargs.setdefault('page_type', 'u-guide')
    kwargs.setdefault('language', 'python')

    with open('2015-06-30-' + fn.replace('.ipynb', '.html'), 'w') as f:
        f.write('\n'.join([
            ''
            '---', 'permalink: ' + url_path,
            'description: ' + page_description.replace(':', '&#58;'),
            'name: ' + page_title.replace(':', '&#58;'),
            'has_thumbnail: ' + has_thumbnail, 'thumbnail: ' + thumbnail,
            '\n'.join(['{}: {}'.format(k, v)
                       for k, v in kwargs.iteritems()]), '---', '{% raw %}'
        ]))
        if uses_plotly_offline:
            f.write(
                '<script type="text/javascript" '
                '        src="https://code.jquery.com/jquery-2.1.4.min.js">'
                '</script>')
        f.write(html.encode('utf8'))
        f.write('{% endraw %}')
    os.remove(tmpfn)
예제 #4
0
def post(args, debug=False):
    """
  Inserts a file as a post to a blog.
  """

    title, suffix = os.path.splitext(os.path.basename(args.file))

    # Need to add mathJax header in front of html
    mathJaxFile = os.path.join(os.path.dirname(__file__), 'mathJax.html')
    with open(mathJaxFile, 'r') as htmlFile:
        mathJax = htmlFile.read()

    # Read file to post
    if suffix in ('.html', '.htm'):
        with open(args.file, 'r') as htmlFile:
            html = mathJax + htmlFile.read()
    elif suffix in '.ipynb':
        exportHtml = HTMLExporter(template_file='basic')
        html = mathJax + exportHtml.from_filename(args.file)[0]
    else:
        print args.file, 'has an unrecognized suffix. Stopping.'
        return

    # Labels for post
    if args.label is None: labels = None
    else: labels = args.label

    if args.title is not None: title = args.title

    # Start communications with blogger
    service, http = authenticate(args)

    # Retrieve the list of Blogs this user has write privileges on
    blogs = service.blogs()
    if debug: print 'blogs =', blogs

    # Find blog by URL
    request = blogs.getByUrl(url=args.url)
    if debug: print 'blogs.getByUrl(url=args.url) =', request.to_json()
    response = request.execute()
    if debug: print 'response =', json.dumps(response, indent=2)
    #response = blogs.getByUrl(url=args.url).execute()

    # Get blogId
    blogId = response['id']
    if debug: print 'blogId =', blogId

    # posts instance
    posts = service.posts()
    if debug: print 'posts =', posts

    # Build body of post

    # Check post doesn't already exist
    existingPost = getPostByTitle(posts,
                                  blogId,
                                  title,
                                  status='draft',
                                  debug=False)
    if existingPost == None:
        existingPost = getPostByTitle(posts,
                                      blogId,
                                      title,
                                      status='scheduled',
                                      debug=False)
    if existingPost == None:
        existingPost = getPostByTitle(posts,
                                      blogId,
                                      title,
                                      status='live',
                                      debug=False)

    if existingPost != None:
        if args.update:
            existingPost['content'] = html
            if labels != None: existingPost['labels'] = labels
            postId = existingPost['id']
            request = posts.update(blogId=blogId,
                                   postId=postId,
                                   body=existingPost)
            if debug: print 'posts().update() =', request.to_json()
            response = request.execute()
            if debug: print 'response =', json.dumps(response, indent=2)
        else:
            print 'Post "' + title + '" already exists!'
    else:
        # Insert new post
        body = {}
        body['kind'] = 'blogger#post'
        body['title'] = title
        body['content'] = html
        body['blog'] = {'id': blogId}
        body['labels'] = labels
        request = posts.insert(blogId=blogId, body=body, isDraft=True)
        if debug: print 'posts().insert() =', request.to_json()
        response = request.execute()
        if debug: print 'response =', json.dumps(response, indent=2)
예제 #5
0
def post(args, debug=False):
  """
  Inserts a file as a post to a blog.
  """

  title, suffix = os.path.splitext( os.path.basename(args.file) )

  # Need to add mathJax header in front of html
  mathJaxFile = os.path.join(os.path.dirname(__file__),'mathJax.html')
  with open (mathJaxFile, 'r') as htmlFile:
    mathJax = htmlFile.read()

  # Read file to post
  if suffix in ('.html','.htm'):
    with open (args.file, 'r') as htmlFile:
      html = mathJax + htmlFile.read()
  elif suffix in '.ipynb':
    exportHtml = HTMLExporter(template_file='basic')
    html = mathJax + exportHtml.from_filename(args.file)[0]
  else:
    print args.file,'has an unrecognized suffix. Stopping.'
    return

  # Labels for post
  if args.label is None: labels = None
  else: labels = args.label

  if args.title is not None: title = args.title

  # Start communications with blogger
  service, http = authenticate(args)

  # Retrieve the list of Blogs this user has write privileges on
  blogs = service.blogs()
  if debug: print 'blogs =',blogs

  # Find blog by URL
  request = blogs.getByUrl(url=args.url)
  if debug: print 'blogs.getByUrl(url=args.url) =',request.to_json()
  response = request.execute()
  if debug: print 'response =',json.dumps(response, indent=2)
  #response = blogs.getByUrl(url=args.url).execute()

  # Get blogId
  blogId = response['id']
  if debug: print 'blogId =',blogId

  # posts instance
  posts = service.posts()
  if debug: print 'posts =',posts

  # Build body of post

  # Check post doesn't already exist
  existingPost = getPostByTitle(posts, blogId, title, status='draft', debug=False)
  if existingPost == None:
    existingPost = getPostByTitle(posts, blogId, title, status='scheduled', debug=False)
  if existingPost == None:
    existingPost = getPostByTitle(posts, blogId, title, status='live', debug=False)

  if existingPost != None:
    if args.update:
      existingPost['content'] = html
      if labels != None: existingPost['labels'] = labels
      postId = existingPost['id']
      request = posts.update(blogId=blogId, postId=postId, body=existingPost)
      if debug: print 'posts().update() =',request.to_json()
      response = request.execute()
      if debug: print 'response =',json.dumps(response, indent=2)
    else:
      print 'Post "'+title+'" already exists!'
  else:
    # Insert new post
    body = {}
    body['kind'] = 'blogger#post'
    body['title'] = title
    body['content'] = html
    body['blog'] = {'id': blogId}
    body['labels'] = labels
    request = posts.insert(blogId=blogId, body=body, isDraft=True)
    if debug: print 'posts().insert() =',request.to_json()
    response = request.execute()
    if debug: print 'response =',json.dumps(response, indent=2)
예제 #6
0
def publish(notebook_name, url_path, page_title, page_description,
            ignore_last_n_cells=2, uses_plotly_offline=False,
            thumbnail=DEFAULT_THUMBNAIL_URL, **kwargs):
    '''
    Convert an IPython notebook into an HTML file that can be consumed
    by GitHub pages in plotly's documentation repo.

    Arguments:
    - notebook_name: The name of the notebook to convert.
                     Used as input arg to nbconvert, nowhere else.
    - url_path: e.g. /python/offline
    - page_title: The <title> of the page.
    - page_description: So, what's this page about?
                        Sell it in 160 characters or less.
                        This is the <meta name="description"> tag.
    - ignore_last_n_cells: When converting to HTML, don't convert the
                           ignore_last_n_cells number of cells.
                           This is usually the cell that runs this `publish`
                           command and the blank output cell that is always
                           included.
    - uses_plotly_offline: If this was created with plotly.offline, then set
                           this to True. This will include an extra lib
                           (jquery) that is included in ipython notebook,
                           but not included in gh-pages
    - thumbnail: Used as a thumbnail image on the notebook splash
                     (if applicable) and as the image when sharing the
                     notebook as a tweet, a facebook post, etc.
                     Can be relative to the repo, eg '/images/static-image'
                     or absolute, e.g. http://i.imgur.com/j0Uiy0n.jpg
    - language: Not sure what this is used for.

    Example:
    publish('Plotly Offline',
            '/python/offline',
            'Plotly Offline for IPython Notebooks',
            'How to use Plotly offline inside IPython notebooks with Plotly Offline',
             uses_plotly_offline=True)
    '''
    # backwards compatability
    if 'thumbnail_url' in kwargs and kwargs['thumbnail'] == DEFAULT_THUMBNAIL_URL:
        kwargs['thumbnail'] = kwargs['thumbnail_url']

    warnings.warn('Did you "Save" this notebook before running this command? '
                  'Remember to save, always save.')

    parts = url_path.split('/')
    if len(parts) > 3:
        warnings.warn('Your URL has more than 2 parts... are you sure?')
    #if url_path[-1] == '/':
    #    url_path = url_path[:-1]
    if len(page_description) > 160:
        raise Exception("Shorten up that page_description! "
                        "Your description was {} characters, "
                        "and it's gotta be <= than 160."
                        .format(len(page_description)))

    if thumbnail == DEFAULT_THUMBNAIL_URL:
        has_thumbnail = 'false'
    else:
        has_thumbnail = 'true'

    if '.ipynb' not in notebook_name:
        notebook_name += '.ipynb'
    fn = notebook_name
    tmpfn = 'temp-{}'.format(fn)
    nbjson = json.load(open(fn))
    if 'cells' in nbjson:
        nbjson['cells'] = nbjson['cells'][:-ignore_last_n_cells]
    elif 'worksheets' in nbjson:
        if len(nbjson['worksheets']) != 1:
            raise Exception('multiple worksheets?')
        elif 'cells' in nbjson['worksheets'][0]:
            nbjson['worksheets'][0]['cells'] = nbjson['worksheets'][0]['cells'][:-ignore_last_n_cells]
        else:
            raise Exception('cells not in worksheets[0]?')
    else:
        raise Exception('unknown ipython notebook format')
    with open(tmpfn, 'w') as f:
        f.write(json.dumps(nbjson))

    exporter = HTMLExporter(template_file='basic')
    html = exporter.from_filename(tmpfn)[0]

    kwargs.setdefault('layout', 'user-guide')
    kwargs.setdefault('page_type', 'u-guide')
    kwargs.setdefault('language', 'python')

    with open('2015-06-30-' + fn.replace('.ipynb', '.html'), 'w') as f:
        f.write('\n'.join([''
                           '---',
                           'permalink: ' + url_path,
                           'description: ' + page_description.replace(':', '&#58;'),
                           'name: ' + page_title.replace(':', '&#58;'),
                           'has_thumbnail: ' + has_thumbnail,
                           'thumbnail: ' + thumbnail,
                           '\n'.join(['{}: {}'.format(k, v) for k, v in kwargs.iteritems()]),
                           '---',
                           '{% raw %}'
                           ]))
        if uses_plotly_offline:
            f.write(
                '<script type="text/javascript" '
                '        src="https://code.jquery.com/jquery-2.1.4.min.js">'
                '</script>'
            )
        f.write(html.encode('utf8'))
        f.write('{% endraw %}')
    os.remove(tmpfn)