Skip to content

Instantly share code, notes, and snippets.

@agentreno
Last active September 3, 2022 13:38
Show Gist options
  • Save agentreno/4ca3e98e0f5bac0f4c7f2d97e77736d2 to your computer and use it in GitHub Desktop.
Save agentreno/4ca3e98e0f5bac0f4c7f2d97e77736d2 to your computer and use it in GitHub Desktop.
"""
Converts https://www.languagereactor.com/saved-items words JSON export to
Mochi cards via their REST API: https://app.mochi.cards/
Corresponding Mochi template:
<< Image1 >> << Image2 >>
<< FormattedSentence >>
<speech lang="ja"> << Sentence >> </speech>
---
<< Word >> = <translate from="ja" to="en"> << Word >> </translate>
"""
import json
import random
import string
import sys
import uuid
import requests
API_TOKEN="yourtokenhere"
def get_random_string(length):
letters = string.ascii_letters + string.digits
return ''.join(random.choice(letters) for i in range(length))
def get_card_payload(word, sentence, formatted_sentence, image1, image2):
image1_filename = get_random_string(12)
image2_filename = get_random_string(12)
return {
"content": "",
"deck-id": "kZkVb4jY",
"template-id": "jqWfavT7",
"fields": {
"name": {
"id": "name",
"value": word
},
"vj1r6VO5": {
"id": "vj1r6VO5",
"value": sentence
},
"Bsn5c6Sg": {
"id": "Bsn5c6Sg",
"value": formatted_sentence
},
"SrgBlVDQ": {
"id": "SrgBlVDQ",
"value": f"![](@media/{image1_filename}.jpeg)"
},
"UV6fGMiC": {
"id": "UV6fGMiC",
"value": f"![](@media/{image2_filename}.jpeg)"
}
},
"attachments": [
{
"file-name": f"{image1_filename}.jpeg",
"content-type": "image/jpeg",
"data": image1
},
{
"file-name": f"{image2_filename}.jpeg",
"content-type": "image/jpeg",
"data": image2
}
]
}
def create_card(payload):
base_url = "https://app.mochi.cards/api"
resp = requests.post(
f"{base_url}/cards",
auth=(API_TOKEN, ""),
json=payload
)
resp.raise_for_status()
if __name__ == "__main__":
with open(sys.argv[1]) as f:
data = json.load(f)
for item in data:
sentence = item['context']['phrase']['subtitles']['1'].replace("\n", "")
if item['context']['phrase']['thumb_prev'] is None or \
item['context']['phrase']['thumb_next'] is None:
print(f"Skipping item {item['word']['text']} due to missing thumbnails")
continue
payload = get_card_payload(
word=item['word']['text'],
sentence=sentence,
formatted_sentence=sentence.replace(
item['word']['text'],
f"<span style='color:red'>{item['word']['text']}</span>"
),
image1=item['context']['phrase']['thumb_prev']['dataURL'].split(',')[1],
image2=item['context']['phrase']['thumb_next']['dataURL'].split(',')[1]
)
create_card(payload)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment