Skip to content

Instantly share code, notes, and snippets.

@danieltomasz
Last active June 9, 2021 15:36
Show Gist options
  • Save danieltomasz/151d0fa20a1e88c7822d8c0f65334aa3 to your computer and use it in GitHub Desktop.
Save danieltomasz/151d0fa20a1e88c7822d8c0f65334aa3 to your computer and use it in GitHub Desktop.
This Python script will replace html with Zotero annotation with more Obsidian friendly that display the color in the preview
#!/usr/bin/env python
# # -*- coding: utf-8 -*-
# %%
import urllib, json
import json
import re
import urllib.parse
from colormap import hex2rgb
import argparse
from pathlib import Path
import sys
def substitute_line(line):
# extract what is needed
data_annotation = re.search(r'data-annotation="(.*?)"', line).group(1)
annotation = json.loads(urllib.parse.unquote(data_annotation))
data_citation = re.search(r'data-citation="(.*?)"', line).group(1)
citation_text = re.findall('\(.*?\)',line)[-1]
# make text nice
citation = json.loads(urllib.parse.unquote(data_citation))
rgba = hex2rgb(annotation["color"])
output_text = f'>#quote <span style="background-color: rgba({rgba[0]},{rgba[1]},{rgba[2]},.75);">' + annotation["text"] + '</span>'
# Make citation nice
citation_locator = citation['citationItems'][0]['locator']
citation_uris = citation['citationItems'][0]['uris'][0].split("/")[-1]
output_citation = f'[{citation_text}](zotero://open-pdf/library/items/{citation_uris}?page={citation_locator})'
return(output_text + output_citation)
def search_and_replace_file(filename):
#open file in read mode
file = open(filename, "r")
replaced_content = ""
#looping through the file
for line in file:
#stripping line break
line = line.strip()
#replacing the texts
if "data-annotation=" in line:
new_line = substitute_line(line)
else:
new_line = line
#concatenate the new string and add an end-line break
replaced_content = replaced_content + new_line + "\n"
#close the file
file.close()
#Open file in write mode
write_file = open(filename, "w")
#overwriting the old file contents with the new/replaced content
write_file.write(replaced_content)
#close the file
write_file.close()
# %%
if __name__ == "__main__":
filename = sys.argv[1]
search_and_replace_file(filename)
# %%
# pellegrino2019 - Annotations (672021, 125900 PM).md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment