Skip to content

Commit

Permalink
feat: use the deck name for the file
Browse files Browse the repository at this point in the history
  • Loading branch information
aalemayhu committed Sep 1, 2024
1 parent 061b17f commit 71b1727
Showing 1 changed file with 48 additions and 17 deletions.
65 changes: 48 additions & 17 deletions helpers/write_apkg.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,60 @@
"""
Write APKG file to disk
"""

import os
import sys

import re
from genanki import Deck, Package

"""
This module provides functionality to write a new Anki package file (.apkg) using provided deck payloads and media files.
"""

def sanitize_filename(filename):
"""
Sanitize the filename by removing any character that is not alphanumeric, a space, or a hyphen.
Replace spaces with hyphens.
"""
sanitized = re.sub(
r'[^\w\s\-\U0001F600-\U0001F64F]', '', filename, flags=re.UNICODE
)
sanitized = sanitized.replace(' ', '-')
return sanitized

def _write_new_apkg(payload, media_files):
first_id = ""
def _write_new_apkg(deck_payloads, media_files):
"""
Write a new Anki package file (.apkg) using the provided deck payloads and media files.
The filename is sanitized and truncated to ensure it is a safe Linux filename and does not exceed 255 characters.
"""
first_deck_id = ""
decks = []

for deck_payload in payload:
deck = Deck(deck_id=deck_payload["id"], name=deck_payload["name"],
description=deck_payload["desc"])
if not first_id:
first_id = deck_payload["id"]
for deck_payload in deck_payloads:
deck = Deck(
deck_id=deck_payload["id"],
name=deck_payload["name"],
description=deck_payload["desc"]
)

if not first_deck_id:
first_deck_id = str(deck_payload["id"]) # Convert to string

for note in deck_payload["notes"]:
deck.add_note(note)

decks.append(deck)

pkg = Package(decks)
pkg.media_files = media_files
fout_anki = f'{first_id}.apkg'
package = Package(decks)
package.media_files = media_files

# Ensure deck_payload is defined before using it
if deck_payloads:
sanitized_name = sanitize_filename(deck_payloads[0]["name"])
else:
sanitized_name = "default"

max_name_length = 255 - len(first_deck_id) - len('.apkg') - 1
truncated_name = sanitized_name[:max_name_length]

output_filename = f'{truncated_name}-{first_deck_id}.apkg'

package.write_to_file(output_filename)

pkg.write_to_file(fout_anki)
sys.stdout.write(os.getcwd() + "/" + fout_anki)
sys.stdout.write(os.getcwd() + "/" + output_filename)

0 comments on commit 71b1727

Please sign in to comment.