Giter Site home page Giter Site logo

md2notion's Introduction

This package is package is no longer maintained. I stopped using Notion.so some time ago and switched to Obsidian due to persistant problems with then Notion API.


build status pypi python versions cobertos

Notion.so Markdown Importer

An importer for Markdown files to Notion.so using notion-py

It provides these features over Notion.so's Markdown importer:

  • Picking a Notion.so page to upload to (instead of them all uploading to the root)
  • Code fences keep their original language (or as close as we can match it)
  • Code fences are formatted properly
  • Inline HTML is preserved
  • (Optionally) Upload images that are memtioned in the HTML <img> tags.
  • Markdown frontmatter is preserved
  • Local image references will be uploaded from relative URLs
  • Image alts are loaded as captions instead of as TextBlocks
  • Handles nested lists properly
  • Among other improvements...

Supports Python 3.6+

Usage from CLI

  • pip install md2notion
  • Then run like python -m md2notion [token_v2] [page-url] [...markdown_path_glob_or_url]
  • The markdown at the given path will be added as a new child to the Notion.so note at page-url

There are also some configuration options:

  • --clear-previous: If a child of the note at page-url has the same name as what you're uploading, it will first be removed.
  • --append: Instead of making a new child, it will append the markdown contents to the note at page-url
  • --html-img: Upload images that are memtioned in the HTML <img> tags.

Usage from script

  • pip install md2notion
  • In your Python file:
from notion.client import NotionClient
from notion.block import PageBlock
from md2notion.upload import upload

# Follow the instructions at https://github.com/jamalex/notion-py#quickstart to setup Notion.py
client = NotionClient(token_v2="<token_v2>")
page = client.get_block("https://www.notion.so/myorg/Test-c0d20a71c0944985ae96e661ccc99821")

with open("TestMarkdown.md", "r", encoding="utf-8") as mdFile:
    newPage = page.children.add_new(PageBlock, title="TestMarkdown Upload")
    upload(mdFile, newPage) #Appends the converted contents of TestMarkdown.md to newPage

If you need to process notion-py block descriptors after parsing from Markdown but before uploading, consider using convert and uploadBlock separately. Take a look at upload.py#upload() for more.

from md2notion.upload import convert, uploadBlock

rendered = convert(mdFile)

# Process the rendered array of `notion-py` block descriptors here
# (just dicts with some properties to pass to `notion-py`)

# Upload all the blocks
for blockDescriptor in rendered:
    uploadBlock(blockDescriptor, page, mdFile.name)

If you need to parse Markdown differently from the default, consider subclassing NotionPyRenderer (a BaseRenderer for mistletoe). You can then pass it to upload(..., notionPyRendererCls=NotionPyRenderer) as a parameter.

Example, Custom Hexo Importer

Here's an example that imports a Hexo blog (slghtly hacky).

import io
import os.path
import glob
from pathlib import Path
from notion.block import PageBlock
from notion.client import NotionClient
from md2notion.upload import upload

client = NotionClient(token_v2="<token_v2>")
page = client.get_block("https://www.notion.so/myorg/Test-c0d20a71c0944985ae96e661ccc99821")

for fp in glob.glob("../source/_posts/*.md", recursive=True):
    with open(fp, "r", encoding="utf-8") as mdFile:
        #Preprocess the Markdown frontmatter into yaml code fences
        mdStr = mdFile.read()
        mdChunks = mdStr.split("---")
        mdStr = \
f"""```yaml
{mdChunks[1]}
`` `

{'---'.join(mdChunks[2:])}
"""
        mdFile = io.StringIO(mdStr)
        mdFile.__dict__["name"] = fp #Set this so we can resolve images later

        pageName = os.path.basename(fp)[:40]
        newPage = page.children.add_new(PageBlock, title=pageName)
        print(f"Uploading {fp} to Notion.so at page {pageName}")
        #Get the image relative to the markdown file in the flavor that Hexo
        #stores its images (in a folder with the same name as the md file)
        def convertImagePath(imagePath, mdFilePath):
            return Path(mdFilePath).parent / Path(mdFilePath).stem / Path(imagePath)
        upload(mdFile, newPage, imagePathFunc=convertImagePath)

Contributing

See CONTRIBUTING.md

md2notion's People

Contributors

cobertos avatar dependabot[bot] avatar egordm avatar jheddings avatar prurph avatar satyendrabanjare avatar wongsingfo 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  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

md2notion's Issues

Does it work with python 3.11 or not? Help me

Traceback (most recent call last):
File "c:\Users\OD\3D Objects\Programas\Notion_Import\fromnotion.py", line 6, in
client = NotionClient(token_v2="")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\OD\AppData\Local\Programs\Python\Python311\Lib\site-packages\notion\client.py", line 77, in init
self.session = create_session(client_specified_retry)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\OD\AppData\Local\Programs\Python\Python311\Lib\site-packages\notion\client.py", line 39, in create_session
retry = Retry(
^^^^^^
TypeError: Retry.init() got an unexpected keyword argument 'method_whitelist'
PS C:\Users\OD\3D Objects\Programas\Notion_Import>

html blocks from jupyter notebook md not rendered into database

When i use the standard import feature of notion for importing a jupyter notebook already converted into md, the html table block are rendered into a database block.

When i use md2notion, the html block are rendered into html code.

It would be great to have the choice

Could you please append an option ?

Support for checkbox.

I cannot find conversion for a checkbox block. It renders as a normal bulleted list.

requests.exceptions.HTTPError: Something went wrong. (400)

Initializing Notion.so client...
Getting target PageBlock...
Traceback (most recent call last):
File "/opt/anaconda3/lib/python3.9/runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/opt/anaconda3/lib/python3.9/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/opt/anaconda3/lib/python3.9/site-packages/md2notion/main.py", line 5, in
cli(sys.argv[1:])
File "/opt/anaconda3/lib/python3.9/site-packages/md2notion/upload.py", line 199, in cli
page = client.get_block(args.page_url)
File "/opt/anaconda3/lib/python3.9/site-packages/notion/client.py", line 169, in get_block
block = self.get_record_data("block", block_id, force_refresh=force_refresh)
File "/opt/anaconda3/lib/python3.9/site-packages/notion/client.py", line 162, in get_record_data
return self._store.get(table, id, force_refresh=force_refresh)
File "/opt/anaconda3/lib/python3.9/site-packages/notion/store.py", line 184, in get
self.call_load_page_chunk(id)
File "/opt/anaconda3/lib/python3.9/site-packages/notion/store.py", line 286, in call_load_page_chunk
recordmap = self._client.post("loadPageChunk", data).json()["recordMap"]
File "/opt/anaconda3/lib/python3.9/site-packages/notion/client.py", line 260, in post
raise HTTPError(
requests.exceptions.HTTPError: Something went wrong. (400)

[Question] Is is possible to using Notion v3 API to clip a page to Notion database?

Is is possible to using Notion v3 API to clip a page to Notion database? I know this question may be notion-py's part, but maybe you know anything about this? How can I use post or get method based on Notion v3 API to clip a page content? I use your repo and Mercury API for page clip, but I found lot of info missed when Mercury API get HTML or when HTML to Markdown, or even Markdown to Notion page😪

Hope you can answer and feedback.

Best

Does not handle collapsible sections

This is an example of a markdown collapsible section:

<details>
<summary>Title</summary>

body

</details>

Which should turn into this in notion:

image

Instead it's turning into this:

image

cannot import name 'EmbedOrUploadBlock' from 'notion.block'

I'm getting the following error on both mac and windows trying to run this thing

Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "/opt/homebrew/lib/python3.11/site-packages/md2notion/__main__.py", line 2, in <module> from .upload import cli File "/opt/homebrew/lib/python3.11/site-packages/md2notion/upload.py", line 11, in <module> from notion.block import EmbedOrUploadBlock, CollectionViewBlock, PageBlock ImportError: cannot import name 'EmbedOrUploadBlock' from 'notion.block' (/opt/homebrew/lib/python3.11/site-packages/notion/block/__init__.py)

Import as database entry, not page?

Hi

I am new to notion and am trying to use your incredible tool to import my markdown files to notion, I love how well it works with images, of which i have many in my notes!

I was wondering whether it's possible to import each md file as an entry, not a page. Maybe i'm just misunderstanding how to use the tool, as I am new to notion.

Thanks so much

Markdown links with hyphens (-) are turned into triple em-dashes

When I upload a document which contains a link with hyphens, e.g.:

- [G Suite User Configuration](https://wiki.blah.com/books/aws-access/page/g-suite-user-configuration)

The resulting link URL is:

https://wiki.blah.com/books/aws%E2%B8%BBaccess/page/g%E2%B8%BBsuite%E2%B8%BBuser%E2%B8%BBconfiguration

%E2%B8%BB == the triple em-dash symbol. Its breaking all my wiki links :(

Confusingly, if right click the link in Notion and choose "copy link", I get the correct hyphenated version out instead of the em-dash one. But if I just click the link, no such luck.

FWIW If I upload the Markdown file directly through Notion's UI, the bug does not occur.

I have checked with hexdump that the Markdown file I am importing from truly contains an ASCII hyphen, and it does:

> hexdump -cb "./013-Single Sign-On--AWS Federated Access.md"
...
00005a0   s   s   /   p   a   g   e   /   a   w   s   -   c   o   n   s
00005a0 163 163 057 160 141 147 145 057 141 167 163 055 143 157 156 163
...

LaTeX equation parsing error

I use this code to upload my file:

with open("a.md", "r", encoding="utf-8") as mdFile:
    newPage = page.children.add_new(PageBlock, title="TestMarkdown Upload")
    upload(mdFile, newPage, notionPyRendererCls=addLatexExtension(NotionPyRenderer))

And my file a.md is that:

$\phi\left(v_{i, l}\right)=\mathbf{R}_{i} v_{i, l}+t_{i}$


$$
P\left(v_{i, l}\right)=\sum_{j \neq i}^{M} \frac{1}{M^{\prime}} \mathcal{N}\left(\mathbf{R}_{i} v_{i, l}+t_{i} ; \mathbf{R}_{j} v_{j, c(j, l)}+t_{j}, \Sigma\right)
$$

It shows in typora:
image

But in Notion, the subscript _ seems to be parsed as * or null
image

Math equation is broken

### Linear Models and Least Squares

Given a vector of inputs $X^T=(X_1, X_2, \ldots, X_p)$, we predict output $Y$ via the model
$$
\hat{Y} = \hat{\beta}_0 + \sum_{j=1}^p X_j \hat{\beta}_j
$$
The term $\hat{\beta}_0$ is the intercept, also known as the *bias* in machine learning. Often it is convenient to include the constant variable 1 in $X$, include $\hat{\beta_0}$ in the vector of coefficients $\hat{\beta}$, and then write the linear model in vector form as an inner product
$$
\hat{Y} = X^T \hat{\beta}
$$
where $X^T$ denotes vector or matrix transpose ($X$ being a column vector). Here we are modeling a single output, so $\hat{Y}$ is a scalar; in general $\hat{Y}$ can be a $K$-vector, in which case $\beta$ would be a $p \times K$ matrix of coefficients. In the $(p+1)$-dimensional input-output space, $(X, \hat{Y})$ represents a hyperplane. If the constant is included in $X$, then the hyperplane includes the origin and is a subspace; if not; it is an affine set cutting the $Y$-axis at the point $(0, \hat{\beta}_0)$. From now on we assume that the intercept is included in $\hat{\beta}$.

In typora:
图片

with open('temp.md', "r", encoding="utf-8") as mdFile:
    newPage = page.children.add_new(PageBlock, title=mdFile.name)
    
    txt = mdFile.read()
    txt_list = re.split(pattern, txt)
    for i, string in enumerate(txt_list):
        if string == '':
            txt_list[i] = '\n'
    new_txt = ''.join(txt_list)

    rendered = convert(new_txt,addLatexExtension(NotionPyRenderer))
    for blockDescriptor in rendered:
        uploadBlock(blockDescriptor, newPage, mdFile.name)

The equation is broken
图片

Upload images in wikilinks format?

I'm using Obsidian and the images referenced tend to be of the format

![[47B4F8ED-06FC-4F17-8B47-85A95082B1A9.png]]

Right now they don't work with the --html-img option :(

HTTPError: 429 Client Error: Too Many Requests for url

Hi, I keep getting this error when running this program. even through i add time.sleep(120) ....

from notion.client import NotionClient
from notion.block import PageBlock
from md2notion.upload import upload
from md2notion.NotionPyRenderer import NotionPyRenderer,addHtmlImgTagExtension,addLatexExtension
from md2notion.upload import convert, uploadBlock
import time

client = NotionClient(token_v2=xxx)
page = client.get_block("https://www.notion.so/2ef891ab83c54b6f8081fa9169b2e91f")

notionPyRendererCls = NotionPyRenderer
notionPyRendererCls = addHtmlImgTagExtension(notionPyRendererCls)
notionPyRendererCls = addLatexExtension(notionPyRendererCls)

with open("D:\BaiduNetdiskDownload\Basic.md", "r", encoding="utf-8") as mdFile:
    rendered = convert(mdFile,notionPyRendererCls=notionPyRendererCls)

for blockDescriptor in rendered:
    uploadBlock(blockDescriptor, page, mdFile.name)
    time.sleep(120)

complete output :

h4 not supported in Notion.so, converting to h3
Code block language python3 has no corresponding syntax in Notion.so
Code block language python3 has no corresponding syntax in Notion.so
h4 not supported in Notion.so, converting to h3
Uploading file 'D:\BaiduNetdiskDownload\Basic.assets\image-20220509203014475.png'
Uploading file 'D:\BaiduNetdiskDownload\Basic.assets\watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xvdmVwMQ==,size_16,color_FFFFFF,t_70-16520977311302.png'
Uploading file 'D:\BaiduNetdiskDownload\Basic.assets\311436_1552801230080_095961B16BE2B8C2E508F4A1AB257B7D.png'
Uploading file 'D:\BaiduNetdiskDownload\Basic.assets\image-20220510122123499.png'
Traceback (most recent call last):
  File "C:\Users\tangxiaqiang\PycharmProjects\tmp\tmp.py", line 20, in <module>
    uploadBlock(blockDescriptor, page, mdFile.name)
  File "C:\Users\tangxiaqiang\Anaconda3\lib\site-packages\md2notion\upload.py", line 91, in uploadBlock
    newBlock.upload_file(str(imgSrc))
  File "C:\Users\tangxiaqiang\Anaconda3\lib\site-packages\notion\block.py", line 652, in upload_file
    self.display_source = data["url"]
  File "C:\Users\tangxiaqiang\Anaconda3\lib\site-packages\notion\maps.py", line 50, in fset
    self.set(path, python_to_api(value, **kwargs))
  File "C:\Users\tangxiaqiang\Anaconda3\lib\site-packages\notion\records.py", line 115, in set
    self._client.submit_transaction(
  File "C:\Users\tangxiaqiang\Anaconda3\lib\site-packages\notion\client.py", line 290, in submit_transaction
    self.post("submitTransaction", data)
  File "C:\Users\tangxiaqiang\Anaconda3\lib\site-packages\notion\client.py", line 265, in post
    response.raise_for_status()
  File "C:\Users\tangxiaqiang\Anaconda3\lib\site-packages\requests\models.py", line 960, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 429 Client Error: Too Many Requests for url: https://www.notion.so/api/v3/submitTransaction

doesn't support block equation

The latex equation in mardown file is $$, which should be a block equation in notion.
image
But when I import this to notion, it is a Inline Equation.
image
Here is my code. It seems the code will tranform the single $ into double $$

from notion.client import NotionClient
from notion.block import PageBlock
import itertools
from md2notion.upload import upload, convert, uploadBlock
from md2notion.NotionPyRenderer import NotionPyRenderer, addLatexExtension
from tqdm.notebook import tqdm
import os

os.environ["http_proxy"] = "http://127.0.0.1:7890"
os.environ["https_proxy"] = "http://127.0.0.1:7890"
# Follow the instructions at https://github.com/jamalex/notion-py#quickstart to setup Notion.py
client = NotionClient(
    token_v2="")
page = client.get_block(
    "")
with open("text.md", "r", encoding="utf-8") as mdFile:
    newPage = page.children.add_new(PageBlock, title="XGBoost")
    lines = mdFile.readlines()


    rendered = convert(lines, addLatexExtension(NotionPyRenderer))
for blockDescriptor in tqdm(rendered):

   
    uploadBlock(blockDescriptor, newPage, mdFile.name)

Getting error around finding files

Hi, newbie here

When I run the command I get this error:
RuntimeError: No file found for glob C:\Users\user\Desktop\folder

I'm structuring the path like this:
C:\Users\user\Desktop\folder*.md

Inside the folder are just the .md files.

Any ideas? Tanx

'list' object has no attribute 'add_new'

I am using a custom uploader for the blocks and I give a parent page after determining a collection view page is the object to add a task, event, or etc to.

new_page = parent_page.collection.add_row(title=subject) #this gets created
uploadCustom(markdown_to_upload, new_page) #this sometimes does work but sometimes doesn't because many users are accessing and uploading things to their notion from my app so I don't always know what is getting uploaded.

I receive this whenever editing a collection view and attempt to add a new task. I'm happy to elaborate on the issue if this is not enough info! (This is my first issue made ever on github 😅)

in uploadCustom
uploadBlock(blockDescriptor, notionPage, mdFile, imagePathFunc)
File "/python/lib/python3.6/site-packages/md2notion/upload.py", line 72, in uploadBlock
newBlock = blockParent.children.add_new(blockClass, **blockDescriptor)
AttributeError: 'list' object has no attribute 'add_new'

Any suggestions?

Connection refused

requests.exceptions.ConnectionError: SOCKSHTTPSConnectionPool(host='www.notion.so', port=443): Max retries exceeded with url: /api/v3/loadUserContent (Caused by NewConnectionError('<urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x7fc9bbc3f5f8>: Failed to establish a new connection: [Errno 111] Connection refused'))

`>` and other kinds of "Blocks"?

Hi Cobertos and thanks for md2notion!
As I don't know Python well enough to use notion-py, I piggybacked on your skills and wrote a quick zsh wrapper around this script, so I can use Notion as a place to dump various system logs. Basically I take whatever comes on stdin, dumps that to file and hands it to md2notion who does a great job.
However, I'd love for somehow to be able to add "toggle" Blocks in Notion.
You know the ones that start with > in Notion, but isn't a QuoteBlock?
Possible somehow?

Issue with big README file

I have the following issue:

`Uploading README.md to Notion.so at page README.md
Traceback (most recent call last):
File "/usr/local/anaconda3/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"main", mod_spec)
File "/usr/local/anaconda3/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/upload.py", line 93, in
upload(mdFile, newPage)
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/upload.py", line 60, in upload
rendered = convert(mdFile, notionPyRendererCls)
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/upload.py", line 45, in convert
return mistletoe.markdown(mdFile, notionPyRendererCls)
File "/usr/local/anaconda3/lib/python3.7/site-packages/mistletoe/init.py", line 19, in markdown
return renderer.render(Document(iterable))
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/NotionPyRenderer.py", line 53, in render
rendered = self.render_maptoken.class.name
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/NotionPyRenderer.py", line 106, in render_document
return self.renderMultiple(token.children)
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/NotionPyRenderer.py", line 61, in renderMultiple
rendered = list(flatten([self.render(t) for t in tokens]))
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/NotionPyRenderer.py", line 61, in
rendered = list(flatten([self.render(t) for t in tokens]))
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/NotionPyRenderer.py", line 53, in render
rendered = self.render_maptoken.class.name
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/NotionPyRenderer.py", line 218, in render_list
return self.renderMultiple(token.children, passthrough=True)
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/NotionPyRenderer.py", line 61, in renderMultiple
rendered = list(flatten([self.render(t) for t in tokens]))
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/NotionPyRenderer.py", line 61, in
rendered = list(flatten([self.render(t) for t in tokens]))
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/NotionPyRenderer.py", line 53, in render
rendered = self.render_maptoken.class.name
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/NotionPyRenderer.py", line 247, in render_list_item
'title': self.renderMultipleToString(token.children)
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/NotionPyRenderer.py", line 103, in renderMultipleToString
return "".join([toString(t) for t in tokens])
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/NotionPyRenderer.py", line 103, in
return "".join([toString(t) for t in tokens])
File "/usr/local/anaconda3/lib/python3.7/site-packages/md2notion/NotionPyRenderer.py", line 100, in toString
raise RuntimeError(f"Can't render to string: {tokenType} inside inline element @ \n{parseStack}")
RuntimeError: Can't render to string: List inside inline element @
Document.children[30]

✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,✓,List.children[1]
✓,ListItem.children[2]
`

I've attached the file. Unfortunately I'm unable to debug the error. It looks like the RuntimeError is not showing the value of the variables involved.

I got the file from here: https://github.com/trimstray/test-your-sysadmin-skills/blob/master/README.md and I deleted the tables and any h4, h5 and h6.

readme.zip

Does this module stiil works?

I paste my page url in the example code:

from notion.client import NotionClient

# Obtain the `token_v2` value by inspecting your browser cookies on a logged-in (non-guest) session on Notion.so
client = NotionClient(token_v2={my token})


# Replace this URL with the URL of the page you want to edit
page = client.get_block("https://www.notion.so/{my_url_id}")

print("The old title is:", page.title)

# Note: You can use Markdown! We convert on-the-fly to Notion's internal formatted text data structure.
page.title = "The title has now changed, and has *live-updated* in the browser!"

running the code above give me a bug that warn me I have a invalid input?
the url in client.get_block isn't the url of my page?

HTML copying and no-formatting

image

For some reasons this library gets a full copy of html, not only markdown and don't formatting it in Notion

I use this command:
python -m md2notion [my_token_v2_here] https://www.notion.so/onepix/Frontend-b989decf3ad846f5aaca6cb010441171 https://github.com/saimon322/reglaments/blob/master/README.md --append --html-img

Ability to import folders / directories

Hey 👋 Thank you first of all for the great work you've done with this tool!

I managed to get it to work, but it lacked something which is quite particular to my use case, that is, I've markdown files distributed in a folder structure (like a tree structure), so when I try to import, I get an error stating that I'm specifying a directory.

Question then is: is there a way I could import a directory?

An example structure:

  • main folder
    • file1.md
    • file2.md
    • sub-folder
      • file3.md
      • sub-folder
        • file4.md

Upload PDFs and other files

Right now, MD files including images are nicely uploaded as Image blocks.

However, any references to local files such as PDF's or other files are not uploaded as file. They are uploaded as a link to a block.

Links to files on my local filesystem are broken once uploaded to Notion.

Would it be possible to have it upload local files as attachment blocks, perhaps with a parameter such as --local-files?

Uploading markdown with tables fails

Uploading a markdown file with a table throws an error. I tried a variety of formatting ---, :---, etc and got the same results.

# Great README

| Table Example | Simple |
| ------------- | ------ |
| Lorem         | true   |

Error:

Uploading CollectionViewBlock, 1/1 (100.0%)Traceback (most recent call last):
  File "./bin/upload.py", line 79, in <module>
    upload(markdown, current_page)
  File "/usr/local/lib/python3.7/site-packages/md2notion/upload.py", line 95, in upload
    uploadBlock(blockDescriptor, notionPage, mdFile.name, imagePathFunc)
  File "/usr/local/lib/python3.7/site-packages/md2notion/upload.py", line 48, in uploadBlock
    newBlock.collection = client.get_collection(

Rewrite with official Notion API

It would be nice to use notion-sdk-py to rewrite this to target the official API.

Notion API needs to support:

  • Creating new pages
    • Creating new pages at root
    • Creating new pages elsewhere
  • Creating blocks of type
    • CodeBlock
      • Setting language
    • TextBlock
    • DividerBlock
    • HeaderBlock, SubheaderBlock, SubsubheaderBlock
    • QuoteBlock
    • NumberedListBlock
    • TodoBlock
    • BulletedListBlock
    • CollectionViewBlock
      • and add all rows
      • add titles
    • ImageBlock
      • Uploading image data from URL (or image data, we can fetch it ourselves)
    • EquationBlock

TODO: Gotta fill these in

Relative images not found

Thanks for writing this script. I can successfully import text Markdown files with it. However, in testing this it's failing to locate relative images.

I have a directory structure on Mac ~/Desktop/test/ where the contents of test are a file Favorite tweet – PizzoniGiada – June 17, 2020 at 0901AM.md and a folder Favorite tweet – PizzoniGiada – June 17, 2020 at 0901AM which contains a single image image_1.jpeg.

Running using Python 3.8.3 and the latest version of md2notion installed via pip3 install md2notion, I am getting the following:

ELSLABM-155961:Desktop stratfordm$ python3 -m md2notion {token_2} https://www.notion.so/Test-0192acd694d443ec924a2a5de270c90d /Users/stratfordm/Desktop/test/Favorite\ tweet\ – PizzoniGiada\ –\ June\ 17\,\ 2020\ at\ 0901AM.md 
Initializing Notion.so client...
Getting target PageBlock...
Uploading /Users/stratfordm/Desktop/test/Favorite tweet – PizzoniGiada – June 17, 2020 at 0901AM.md to Notion.so at page Favorite tweet – PizzoniGiada – June 17, 2020 at 0901AM.md...
Uploading ImageBlock, 4/7 (57.1%)ERROR: Local image '/Users/stratfordm/Desktop/test/Favorite%20tweet%20%E2%80%93%C2%A0PizzoniGiada%20%E2%80%93%20June%2017,%202020%20at%200901AM/image_1.jpeg' not found to upload. Skipping...
Uploading TextBlock, 7/7 (100.0%)EL

The end result is a note created but without the image attachment.

Hope this helps.

HTTPError - Invalid Input

Hi, I keep getting this error when running this program. Through a Python file and the cli.

noah@Noahs-MBP ~ % python3 -m md2notion "***" "https://www.notion.so/***/Test-***" "/Users/noah/Documents/test.md" 
Initializing Notion.so client...
Getting target PageBlock...
Traceback (most recent call last):
  File "/opt/homebrew/Cellar/[email protected]/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/opt/homebrew/Cellar/[email protected]/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/opt/homebrew/lib/python3.9/site-packages/md2notion/__main__.py", line 5, in <module>
    cli(sys.argv[1:])
  File "/opt/homebrew/lib/python3.9/site-packages/md2notion/upload.py", line 199, in cli
    page = client.get_block(args.page_url)
  File "/opt/homebrew/lib/python3.9/site-packages/notion/client.py", line 169, in get_block
    block = self.get_record_data("block", block_id, force_refresh=force_refresh)
  File "/opt/homebrew/lib/python3.9/site-packages/notion/client.py", line 162, in get_record_data
    return self._store.get(table, id, force_refresh=force_refresh)
  File "/opt/homebrew/lib/python3.9/site-packages/notion/store.py", line 184, in get
    self.call_load_page_chunk(id)
  File "/opt/homebrew/lib/python3.9/site-packages/notion/store.py", line 286, in call_load_page_chunk
    recordmap = self._client.post("loadPageChunk", data).json()["recordMap"]
  File "/opt/homebrew/lib/python3.9/site-packages/notion/client.py", line 260, in post
    raise HTTPError(
requests.exceptions.HTTPError: Invalid input.

Any reason for this? Thanks :)

Upload creates new blocks on subsequent runs

Running the upload command against a PageBlock results in duplicate files on subsequent runs.

python -m md2notion.upload [token_v2] [page-url] ./docs/*.md

Results in:

  • doc-1.md
  • doc-2.md

Running it again, will append additional files instead of updating the existing ones.

python -m md2notion.upload [token_v2] [page-url] ./docs/*.md

Results in:

  • doc-1.md
  • doc-2.md
  • doc-1.md
  • doc-2.md

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.