Skip to content

Instantly share code, notes, and snippets.

@mikka2061
Created December 14, 2021 11:15
Show Gist options
  • Save mikka2061/070c0266f0054c1e8aff5da02208f95e to your computer and use it in GitHub Desktop.
Save mikka2061/070c0266f0054c1e8aff5da02208f95e to your computer and use it in GitHub Desktop.
Tagify Obsidian for use in Blot
#!/usr/bin/env python3
import frontmatter
import os, sys
from glob import glob
import re
from io import BytesIO
import uuid
if len(sys.argv) < 2:
print ("Usage: {} <directory>".format(sys.argv[0]))
exit()
dir = sys.argv[1]
result = [y for x in os.walk(dir) for y in glob(os.path.join(x[0], '*.md'))]
# Hardcoded for now. You should probably change this to your needs,
# drafts/ is always a bad idea, but _templates/ is the directory I
# save my Obsidian templates in, which should not be parsed, either.
result = [x for x in result if not ('_templates' in x or 'drafts/' in x)]
for mdfile in result:
with open(mdfile, "r") as f:
meta_tags = list()
post = frontmatter.load(f)
print (mdfile)
if 'Tags' in post.keys() and post["Tags"]:
meta_tags = [x.strip() for x in post["Tags"].split(',')]
meta_tags = [each_tag.lower() for each_tag in meta_tags]
text_tags = re.findall(r" #(\w+)", post.content)
text_tags = [each_tag.lower() for each_tag in text_tags]
meta_tags.extend(x for x in text_tags if x not in meta_tags)
post["Tags"] = ", ".join(meta_tags)
# make a UUID. Might not be completely unique (thanks to slicing) but good enough
# if it duplicates, I'll know.
if not 'UUID' in post.keys():
post['UUID'] = uuid.uuid4().hex[:5]
## post['Tags'] = post["Tags"] + ", {}".format(post['UUID'])
## let's not clutter the tags
f.close()
with open(mdfile, "w") as f:
fc = BytesIO()
frontmatter.dump(post, fc)
fx = fc.getvalue().decode('utf-8')
f.write(fx)
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment