Created
April 4, 2023 07:40
-
-
Save abdullahkhalids/142f0d28d4acf2c4c7e00e4675e101ca to your computer and use it in GitHub Desktop.
notebook2blogpost
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!python | |
import shutil | |
import os | |
import sys | |
import subprocess | |
from datetime import date | |
import re | |
def main(filepath): | |
nbpath = os.path.dirname(filepath) | |
nbfilename = os.path.basename(filepath) | |
(base, ext) = os.path.splitext(nbfilename) | |
today = date.today().isoformat() | |
# change to notebook directory | |
os.chdir(nbpath) | |
# First export the file | |
subprocess.run(['jupyter', 'nbconvert', | |
'--to', 'markdown', | |
'--template=path/to/template', | |
'--RegexRemovePreprocessor.patterns=\s*\Z', | |
'--TagRemovePreprocessor.enabled=True', | |
'--TagRemovePreprocessor.remove_cell_tags', | |
'remove_cell', | |
nbfilename]) | |
# now rename the export directory | |
newfoldername = today + ' ' + base | |
shutil.rmtree(newfoldername, ignore_errors=True) | |
os.rename('export', newfoldername) | |
# Next open the md file | |
mdfilepath = os.path.join(newfoldername, base+'.md') | |
# replace any contents needed | |
with open(mdfilepath, 'r') as f: | |
filedata = f.read() | |
filedata = filedata.replace('[png](', '[code output]({attach}') | |
#filedata = re.sub(r'\$\\displaystyle ((\n|.)*?)\$', r'$$\1$$', filedata) | |
displaymath_regex = r"(?P<prefix>\$\\displaystyle\s+?)(?P<math>.+?)(?P<suffix>(?<!\s)\$)" | |
filedata = re.sub(displaymath_regex, r"$$\2$$", filedata, flags=re.S) | |
with open(mdfilepath, 'w') as file: | |
file.write(filedata) | |
# rename file with date | |
newmdfilepath = os.path.join(newfoldername, today + ' ' + base+'.md') | |
os.rename(mdfilepath, newmdfilepath) | |
# remove any existing entries | |
print(os.path.join( | |
'path/to/staticsitegenerateor/content', | |
newfoldername)) | |
if __name__ == "__main__": | |
filepath = sys.argv[1] | |
main(filepath) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment