aboutsummaryrefslogtreecommitdiff
path: root/src/Text/Pandoc/Writers/Ipynb.hs
blob: 38429f790755ff8640330e3049db75826f832c43 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-
Copyright (C) 2019 John MacFarlane <jgm@berkeley.edu>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-}

{- |
   Module      : Text.Pandoc.Writers.Ipynb
   Copyright   : Copyright (C) 2019 John MacFarlane
   License     : GNU GPL, version 2 or above

   Maintainer  : John MacFarlane <jgm@berkeley.edu>
   Stability   : alpha
   Portability : portable

Ipynb (Jupyter notebook JSON format) writer for pandoc.

-}
module Text.Pandoc.Writers.Ipynb ( writeIpynb )
where
import Prelude
import Control.Monad.State
import qualified Data.Map as M
import Data.Maybe (catMaybes, fromMaybe)
import Text.Pandoc.Options
import Text.Pandoc.Definition
import Data.Ipynb as Ipynb
import Text.Pandoc.Walk (walkM)
import qualified Text.Pandoc.Builder as B
import Text.Pandoc.Class
import Text.Pandoc.Logging
import Data.Text (Text)
import qualified Data.Text as T
import Data.Aeson as Aeson
import qualified Text.Pandoc.UTF8 as UTF8
import Text.Pandoc.Shared (safeRead, isURI)
import Text.Pandoc.Writers.Shared (metaToJSON')
import Text.Pandoc.Writers.Markdown (writeMarkdown)
import qualified Data.Text.Encoding as TE
import qualified Data.ByteString.Lazy as BL
import Data.Aeson.Encode.Pretty (Config(..), defConfig,
           encodePretty', keyOrder, Indent(Spaces))

writeIpynb :: PandocMonad m => WriterOptions -> Pandoc -> m Text
writeIpynb opts d = do
  notebook <- pandocToNotebook opts d
  return $ TE.decodeUtf8 . BL.toStrict . encodePretty' defConfig{
             confIndent  = Spaces 1,
             confTrailingNewline = True,
             confCompare = keyOrder
               [ "cells", "nbformat", "nbformat_minor",
                 "cell_type", "output_type",
                 "execution_count", "metadata",
                 "outputs", "source",
                 "data", "name", "text" ] }
         $ notebook

pandocToNotebook :: PandocMonad m
                 => WriterOptions -> Pandoc -> m (Notebook NbV4)
pandocToNotebook opts (Pandoc meta blocks) = do
  let blockWriter bs = writeMarkdown
           opts{ writerTemplate = Nothing } (Pandoc nullMeta bs)
  let inlineWriter ils = T.stripEnd <$> writeMarkdown
           opts{ writerTemplate = Nothing } (Pandoc nullMeta [Plain ils])
  let jupyterMeta =
        case lookupMeta "jupyter" meta of
          Just (MetaMap m) -> (Meta m <> B.deleteMeta "jupyter" meta)
          _ -> meta
  metadata' <- metaToJSON' blockWriter inlineWriter $
                 B.deleteMeta "nbformat" $
                 B.deleteMeta "nbformat_minor" $ jupyterMeta
  -- convert from a Value (JSON object) to a M.Map Text Value:
  let metadata = case fromJSON metadata' of
                   Error _ -> mempty -- TODO warning here? shouldn't happen
                   Success x -> x
  cells <- extractCells opts blocks
  return $ Notebook{
       notebookMetadata = metadata
     , notebookFormat = (4, 5)
     , notebookCells = cells }

addAttachment :: PandocMonad m
              => Inline
              -> StateT (M.Map Text MimeBundle) m Inline
addAttachment (Image attr lab (src,tit))
  | not (isURI src) = do
  (img, mbmt) <- fetchItem src
  let mt = maybe "application/octet-stream" (T.pack) mbmt
  modify $ M.insert (T.pack src)
          (MimeBundle (M.insert mt (BinaryData img) mempty))
  return $ Image attr lab ("attachment:" <> src, tit)
addAttachment x = return x

extractCells :: PandocMonad m => WriterOptions -> [Block] -> m [Cell a]
extractCells _ [] = return []
extractCells opts (Div (_id,classes,kvs) xs : bs)
  | "cell" `elem` classes
  , "markdown" `elem` classes = do
      let meta = pairsToJSONMeta kvs
      (newdoc, attachments) <-
        runStateT (walkM addAttachment (Pandoc nullMeta xs)) mempty
      source <- writeMarkdown opts{ writerTemplate = Nothing } newdoc
      (Cell{
          cellType = Markdown
        , cellSource = Source $ breakLines source
        , cellMetadata = meta
        , cellAttachments = if M.null attachments
                               then Nothing
                               else Just attachments } :)
            <$> extractCells opts bs
  | "cell" `elem` classes
  , "code" `elem` classes = do
      let (codeContent, rest) =
            case xs of
               (CodeBlock _ t : ys) -> (T.pack t, ys)
               ys                   -> (mempty, ys)
      let meta = pairsToJSONMeta kvs
      outputs <- catMaybes <$> mapM blockToOutput rest
      let exeCount = lookup "execution_count" kvs >>= safeRead
      (Cell{
          cellType = Ipynb.Code {
                codeExecutionCount = exeCount
              , codeOutputs = outputs
              }
        , cellSource = Source $ breakLines codeContent
        , cellMetadata = meta
        , cellAttachments = Nothing } :) <$> extractCells opts bs
  | "cell" `elem` classes
  , "raw" `elem` classes =
      case xs of
        [RawBlock (Format f) raw] -> do
          let format' =
                case f of
                  "html"     -> "text/html"
                  "revealjs" -> "text/html"
                  "latex"    -> "text/latex"
                  "markdown" -> "text/markdown"
                  "rst"      -> "text/x-rst"
                  _          -> f
          (Cell{
              cellType = Raw
            , cellSource = Source $ breakLines $ T.pack raw
            , cellMetadata = M.insert "format"
                             (Aeson.String $ T.pack format') mempty
            , cellAttachments = Nothing } :) <$> extractCells opts bs
        _ -> extractCells opts bs
extractCells opts (CodeBlock (_id,classes,kvs) raw : bs)
  | "code" `elem` classes = do
      let meta = pairsToJSONMeta kvs
      let exeCount = lookup "execution_count" kvs >>= safeRead
      (Cell{
          cellType = Ipynb.Code {
                codeExecutionCount = exeCount
              , codeOutputs = []
              }
        , cellSource = Source $ breakLines $ T.pack raw
        , cellMetadata = meta
        , cellAttachments = Nothing } :) <$> extractCells opts bs
extractCells opts (b:bs) = do
      let isCodeOrDiv (CodeBlock (_,cl,_) _) = "code" `elem` cl
          isCodeOrDiv (Div (_,cl,_) _)       = "cell" `elem` cl
          isCodeOrDiv _                      = False
      let (mds, rest) = break (isCodeOrDiv) bs
      extractCells opts (Div ("",["cell","markdown"],[]) (b:mds) : rest)

blockToOutput :: PandocMonad m => Block -> m (Maybe (Output a))
blockToOutput (Div (_,["output","stream",sname],_) (CodeBlock _ t:_)) =
  return $ Just
         $ Stream{ streamName = T.pack sname
               , streamText = Source (breakLines $ T.pack t) }
blockToOutput (Div (_,["output","error"],kvs) (CodeBlock _ t:_)) =
  return $ Just
         $ Err{ errName = maybe mempty T.pack (lookup "ename" kvs)
              , errValue = maybe mempty T.pack (lookup "evalue" kvs)
              , errTraceback = breakLines $ T.pack t }
blockToOutput (Div (_,["output","execute_result"],kvs) bs) = do
  (data', metadata') <- extractData bs
  return $ Just
         $ ExecuteResult{ executeCount = fromMaybe 0 $
                          lookup "execution_count" kvs >>= safeRead
                        , executeData = data'
                        , executeMetadata = pairsToJSONMeta kvs <> metadata'}
blockToOutput (Div (_,["output","display_data"],kvs) bs) = do
  (data', metadata') <- extractData bs
  return $ Just
         $ DisplayData { displayData = data'
                       , displayMetadata = pairsToJSONMeta kvs <> metadata'}
blockToOutput _ = return Nothing

extractData :: PandocMonad m => [Block] -> m (MimeBundle, JSONMeta)
extractData bs = do
  (mmap, meta) <- foldM go mempty bs
  return (MimeBundle mmap, meta)
  where
    go (mmap, meta) b@(Para [Image (_,_,kvs) _ (src,_)]) = do
      (img, mbmt) <- fetchItem src
      case mbmt of
        Just mt -> return
          (M.insert (T.pack mt) (BinaryData img) mmap,
           meta <> pairsToJSONMeta kvs)
        Nothing -> (mmap, meta) <$ report (BlockNotRendered b)
    go (mmap, meta) b@(CodeBlock (_,["json"],_) code) =
      case decode (UTF8.fromStringLazy code) of
        Just v  -> return
                    (M.insert "application/json" (JsonData v) mmap, meta)
        Nothing -> (mmap, meta) <$ report (BlockNotRendered b)
    go (mmap, meta) (CodeBlock ("",[],[]) code) =
       return (M.insert "text/plain" (TextualData (T.pack code)) mmap, meta)
    go (mmap, meta) (RawBlock (Format "html") raw) =
       return (M.insert "text/html" (TextualData (T.pack raw)) mmap, meta)
    go (mmap, meta) (RawBlock (Format "latex") raw) =
       return (M.insert "text/latex" (TextualData (T.pack raw)) mmap, meta)
    go (mmap, meta) b = (mmap, meta) <$ report (BlockNotRendered b)

pairsToJSONMeta :: [(String, String)] -> JSONMeta
pairsToJSONMeta kvs =
  M.fromList [(T.pack k, case v of
                           "true"  -> Bool True
                           "false" -> Bool False
                           _       -> case safeRead v of
                                        Just n -> Number n
                                        _      -> String (T.pack v))
             | (k,v) <- kvs , k /= "execution_count" ]