### Example Usage of BASIC_AND_REVERSED_CARD_MODEL
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/builtin_models.md
Shows how to create a deck and add multiple notes using the BASIC_AND_REVERSED_CARD_MODEL, then package them into an Anki file.
```python
import genanki
deck = genanki.Deck(2059400110, 'Vocabulary')
# Learning Spanish: French word / Spanish word
notes = [
('Bonjour', 'Hola'),
('Merci', 'Gracias'),
]
for front, back in notes:
note = genanki.Note(
model=genanki.BASIC_AND_REVERSED_CARD_MODEL,
fields=[front, back]
)
deck.add_note(note)
package = genanki.Package(deck)
package.write_to_file('vocab_reversed.apkg')
```
--------------------------------
### Deterministic GUID Generation Example
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/utilities.md
Demonstrates that the `guid_for` function is deterministic, always producing the same GUID for the same input. This is crucial for reproducible deck generation.
```python
# Same input always produces same GUID
for _ in range(100):
guid = genanki.guid_for('Paris', 'France')
print(guid) # Always 'abc123' (example)
```
--------------------------------
### Example Template Configurations in Genanki
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/configuration.md
Provides examples of defining card templates for Genanki, specifying the question and answer formatting using Mustache syntax and optional browser display formats.
```python
templates = [
{
'name': 'Card 1',
'qfmt': '{{Front}}',
'afmt': '{{FrontSide}}
{{Back}}',
},
{
'name': 'Card 2',
'qfmt': '{{Back}}',
'afmt': '{{FrontSide}}
{{Front}}',
'bqfmt': '{{Back}} ← {{Front}}',
'bafmt': '{{Back}} → {{Front}}',
},
]
```
--------------------------------
### Create and Export Anki Package
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/INDEX.md
This example demonstrates how to create a basic Anki note, add it to a deck, and then package and export the deck to an .apkg file.
```python
import genanki
# Realistic usage
model = genanki.BASIC_MODEL
note = genanki.Note(model=model, fields=['Q', 'A'])
deck = genanki.Deck(2059400110, 'My Deck')
deck.add_note(note)
genanki.Package(deck).write_to_file('output.apkg')
```
--------------------------------
### Create an Anki Deck with Media Files
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/INDEX.md
This example shows how to include media files, such as images, in an Anki deck. The media files are specified when creating the genanki.Package object.
```python
deck = genanki.Deck(2059400110, 'Images')
note = genanki.Note(model=model, fields=['
', 'Caption'])
deck.add_note(note)
package = genanki.Package(deck, media_files=['path/to/pic.jpg'])
package.write_to_file('output.apkg')
```
--------------------------------
### Example Usage of BASIC_MODEL
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/builtin_models.md
Demonstrates how to create a deck, add a note using BASIC_MODEL, and write it to an Anki package file.
```python
import genanki
deck = genanki.Deck(2059400110, 'Vocabulary')
note = genanki.Note(
model=genanki.BASIC_MODEL,
fields=['Bonjour', 'Hello (French greeting)']
)
deck.add_note(note)
package = genanki.Package(deck)
package.write_to_file('vocab.apkg')
```
--------------------------------
### Note GUID Generation and Setting
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/note.md
Illustrates the automatic generation of a note's GUID based on field values and how to explicitly set a custom GUID. Custom GUIDs are useful for maintaining note identity across updates.
```python
note1 = genanki.Note(model=genanki.BASIC_MODEL, fields=['Question', 'Answer'])
print(note1.guid) # Auto-generated from fields
note2 = genanki.Note(
model=genanki.BASIC_MODEL,
fields=['Question', 'Answer'],
guid='my-custom-guid'
)
print(note2.guid) # 'my-custom-guid'
```
--------------------------------
### Example Usage: Cloze Deletion Model
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/builtin_models.md
Illustrates creating Anki notes with cloze deletions using the `CLOZE_MODEL`. This example shows a note with multiple cloze deletions, generating a card for each.
```python
import genanki
deck = genanki.Deck(2059400110, 'Geography')
# Note with multiple cloze deletions
note = genanki.Note(
model=genanki.CLOZE_MODEL,
fields=[
'The capital of {{c1::France}} is {{c2::Paris}}, located in {{c3::Europe}}.',
'France is a major European country.'
]
)
# Generates 3 cards (one for each cloze)
deck.add_note(note)
package = genanki.Package(deck)
package.write_to_file('cloze.apkg')
```
--------------------------------
### Example Field Configurations in Genanki
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/configuration.md
Illustrates how to define a list of fields for a Genanki model, specifying properties such as name, font, size, and right-to-left text direction.
```python
fields = [
{
'name': 'Front',
'font': 'Arial',
'size': 18,
},
{
'name': 'Back',
'font': 'Times New Roman',
'size': 16,
'rtl': False,
},
{
'name': 'Image',
'font': 'Arial',
'size': 12,
'media': ['image1.jpg', 'image2.jpg'],
},
{
'name': 'Notes',
'sticky': True, # Preserve between notes
},
]
```
--------------------------------
### Example Field Dictionary Usage
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/types.md
Demonstrates how to create a list of field dictionaries to be used when initializing a Genanki Model. Shows common configurations for 'name', 'font', 'size', and 'sticky' properties.
```python
fields = [
{
'name': 'Front',
'font': 'Arial',
'size': 18,
'sticky': False,
},
{
'name': 'Back',
'font': 'Arial',
'size': 18,
},
]
model = genanki.Model(1607392319, 'My Model', fields=fields, templates=[...])
```
--------------------------------
### Simple Two-Field Model Configuration
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/configuration.md
Example of creating a basic genanki Model with two fields, 'Front' and 'Back', and a standard card template.
```python
import genanki
model = genanki.Model(
1607392319,
'Simple',
fields=[
{'name': 'Front'},
{'name': 'Back'},
],
templates=[
{
'name': 'Card 1',
'qfmt': '{{Front}}',
'afmt': '{{FrontSide}}
{{Back}}'
}
]
)
```
--------------------------------
### Note Constructor Signature
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/note.md
The constructor for the Note class accepts model, fields, sort_field, tags, guid, and due date as parameters. The 'model' parameter defines the note's structure, 'fields' are the content, 'tags' are for categorization, 'guid' is a unique identifier, and 'due' sets the initial due date.
```python
def __init__(self, model=None, fields=None, sort_field=None, tags=None, guid=None, due=0)
```
--------------------------------
### Create a Genanki Model with Custom CSS
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/model.md
Instantiate a Model with custom CSS to style the cards. This example applies font size, family, and color to the cards.
```python
import genanki
# Model with custom CSS
model_with_css = genanki.Model(
1607392320,
'Styled Model',
fields=[
{'name': 'Front'},
{'name': 'Back'},
],
templates=[
{
'name': 'Card 1',
'qfmt': '{{Front}}',
'afmt': '{{FrontSide}}
{{Back}}',
},
],
css='.card { font-size: 24px; font-family: Arial; color: blue; }'
)
```
--------------------------------
### Create an Anki Deck with a Custom Model
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/INDEX.md
This example demonstrates how to create an Anki deck using a custom model with multiple fields and templates. It requires defining the model's structure and then adding notes accordingly.
```python
model = genanki.Model(1607392319, 'Custom', fields=[...], templates=[...])
deck = genanki.Deck(2059400110, 'My Deck')
note = genanki.Note(model=model, fields=[...])
deck.add_note(note)
genanki.Package(deck).write_to_file('output.apkg')
```
--------------------------------
### Add Tags and Custom GUIDs to Notes
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/README.md
Explains how to add tags to Anki notes for organization and how to specify custom GUIDs for notes to ensure correct re-import matching.
```python
import genanki
deck = genanki.Deck(2059400110, 'Taxonomy')
model = genanki.BASIC_MODEL
# Note with tags
note = genanki.Note(
model=model,
fields=['Canis lupus familiaris', 'Dog'],
tags=['animals', 'mammals', 'canidae'],
guid='dog-001' # Custom GUID for re-import matching
)
deck.add_note(note)
genanki.Package(deck).write_to_file('animals.apkg')
```
--------------------------------
### Example Usage: Basic Type-in-the-Answer Model
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/builtin_models.md
Demonstrates how to create Anki notes using the `BASIC_TYPE_IN_THE_ANSWER_MODEL`. This involves creating a deck, defining notes with questions and answers, adding them to the deck, and writing the package to a file.
```python
import genanki
deck = genanki.Deck(2059400110, 'Spanish Spelling')
notes = [
('Translate "hello"', 'hola'),
('Translate "goodbye"', 'adiós'),
('Translate "thank you"', 'gracias'),
]
for question, answer in notes:
note = genanki.Note(
model=genanki.BASIC_TYPE_IN_THE_ANSWER_MODEL,
fields=[question, answer]
)
deck.add_note(note)
package = genanki.Package(deck)
package.write_to_file('type_in.apkg')
```
--------------------------------
### Creating Basic Genanki Notes
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/note.md
Demonstrates how to create genanki Note objects with different configurations. This includes basic notes with fields, notes with tags, notes with custom sort fields and GUIDs, and notes with custom due dates.
```python
import genanki
model = genanki.BASIC_MODEL
# Basic note
note1 = genanki.Note(
model=model,
fields=['What is 2+2?', '4']
)
# Note with tags
note2 = genanki.Note(
model=model,
fields=['Paris', 'France'],
tags=['geography', 'capitals']
)
# Note with custom sort field and GUID
note3 = genanki.Note(
model=model,
fields=['Rome', 'Italy'],
sort_field='Italy',
guid='custom-guid-12345'
)
# Note with custom due date (due in 5 days)
note4 = genanki.Note(
model=model,
fields=['Tokyo', 'Japan'],
due=5
)
```
--------------------------------
### Create Custom Genanki Model
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/builtin_models.md
Demonstrates how to create a custom Genanki model by copying and modifying a built-in model. This example customizes the CSS for larger font sizes.
```python
custom_model = genanki.Model(
1607392319, # Different ID
'Large Print Basic',
fields=[{'name': 'Front'}, {'name': 'Back'}],
templates=[
{
'name': 'Card 1',
'qfmt': '{{Front}}',
'afmt': '{{FrontSide}}
{{Back}}'
}
],
css='.card { font-family: arial; font-size: 32px; }' # Larger font
)
deck = genanki.Deck(2059400110, 'Large Print')
note = genanki.Note(model=custom_model, fields=['Q', 'A'])
deck.add_note(note)
```
--------------------------------
### Handling Corrupted APKG File Errors
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/errors.md
Catch zipfile.BadZipFile if the generated .apkg file is corrupted. This example demonstrates how to verify the created package.
```python
import genanki
try:
package = genanki.Package(deck)
package.write_to_file('output.apkg')
# Verify the file was created
import zipfile
with zipfile.ZipFile('output.apkg', 'r') as z:
z.testzip() # Raises BadZipFile if corrupted
except Exception as e:
print(f'Package creation failed: {e}')
```
--------------------------------
### Example Usage of Optional Reversed Card Model
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/builtin_models.md
Demonstrates how to create notes using the BASIC_OPTIONAL_REVERSED_CARD_MODEL. One note includes a value in the 'Add Reverse' field to generate a reversed card, while the other leaves it empty.
```python
import genanki
deck = genanki.Deck(2059400110, 'Vocabulary')
# Note with reversed card
note1 = genanki.Note(
model=genanki.BASIC_OPTIONAL_REVERSED_CARD_MODEL,
fields=['Cat', 'Gato', 'yes'] # Will generate 2 cards
)
deck.add_note(note1)
# Note without reversed card
note2 = genanki.Note(
model=genanki.BASIC_OPTIONAL_REVERSED_CARD_MODEL,
fields=['Red', 'Rojo', ''] # Will generate only 1 card
)
deck.add_note(note2)
package = genanki.Package(deck)
package.write_to_file('vocab_optional.apkg')
```
--------------------------------
### Customizing Card Generation with a Subclass
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/card.md
Illustrates how to customize card generation by subclassing the `Note` class and overriding the `_front_back_cards` method. This example shows how to suspend every other generated card.
```python
class CustomNote(genanki.Note):
def _front_back_cards(self):
"""Override to customize card generation"""
cards = super()._front_back_cards()
# Suspend every other card
for i, card in enumerate(cards):
if i % 2 == 1:
card.suspend = True
return cards
# Usage
note = CustomNote(model=model, fields=['Q', 'A'])
# Cards with odd ordinals (1, 3, 5...) will be suspended
```
--------------------------------
### Model with Custom CSS
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/configuration.md
Demonstrates creating a genanki Model with custom CSS applied to the cards for styling purposes. This example sets a larger font size and specific colors.
```python
model = genanki.Model(
1607392319,
'Large Print',
fields=[
{'name': 'Front'},
{'name': 'Back'},
],
templates=[
{
'name': 'Card 1',
'qfmt': '{{Front}}',
'afmt': '{{FrontSide}}
{{Back}}'
}
],
css='''
.card {
font-family: Arial;
font-size: 24px;
color: #333;
background-color: #fff;
}
'''
)
```
--------------------------------
### Genanki Cloze Deletion Example
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/types.md
Demonstrates how to create a note with multiple cloze deletions using the genanki library. Each unique cloze number generates a separate card.
```python
cloze_note = genanki.Note(
model=genanki.CLOZE_MODEL,
fields=[
'The {{c1::Eiffel Tower}} is located in {{c2::Paris}}, {{c3::France}}.',
'Extra information'
]
)
# Generates 3 cards:
# Card 1: "The _____ is located in Paris, France."
# Card 2: "The Eiffel Tower is located in _____, France."
# Card 3: "The Eiffel Tower is located in Paris, _____."
```
--------------------------------
### Create Bidirectional Genanki Model
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/types.md
Example of creating a Genanki Model with two bidirectional card templates. Ensure all required fields like 'name', 'qfmt', and 'afmt' are provided for each template.
```python
templates = [
{
'name': 'Card 1',
'qfmt': '{{Front}}',
'afmt': '{{FrontSide}}
{{Back}}',
'bqfmt': '{{Front}}',
'bafmt': '{{Front}} \u2192 {{Back}}',
},
{
'name': 'Card 2',
'qfmt': '{{Back}}',
'afmt': '{{FrontSide}}
{{Front}}',
},
]
model = genanki.Model(
1607392319,
'Bidirectional',
fields=[...],
templates=templates
)
```
--------------------------------
### Create Simple Two-Field Notes with Genanki
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/utilities.md
Use this pattern to create basic question-answer notes. GUIDs are automatically generated based on the note's fields, allowing Anki to match and update notes on re-import.
```python
import genanki
deck = genanki.Deck(2059400110, 'Vocabulary')
for question, answer in [('Q1', 'A1'), ('Q2', 'A2')]:
# GUID is auto-generated from both fields
note = genanki.Note(
model=genanki.BASIC_MODEL,
fields=[question, answer]
)
deck.add_note(note)
# Re-importing the same deck will update existing notes
# (because GUIDs match)
```
--------------------------------
### Cloze Deletion Model Example
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/model.md
Demonstrates how to create a Cloze deletion model using genanki. This model includes 'Text' and 'Extra' fields and uses Mustache syntax for cloze formatting. Usage with a note is also shown, generating multiple cards based on cloze definitions.
```python
cloze_model = genanki.Model(
1550428389,
'Cloze Deletion',
model_type=genanki.Model.CLOZE,
fields=[
{'name': 'Text'},
{'name': 'Extra'},
],
templates=[
{
'name': 'Cloze',
'qfmt': '{{cloze:Text}}',
'afmt': '{{cloze:Text}}
{{Extra}}',
},
]
)
# Usage with note
note = genanki.Note(
model=cloze_model,
fields=['The capital of {{c1::France}} is {{c2::Paris}}', 'Extra info']
)
# Generates 2 cards (one for each cloze)
```
--------------------------------
### guid
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/note.md
Gets or sets the globally unique identifier (GUID) for the note. If not explicitly set, it is auto-generated.
```APIDOC
## Property: guid
### Description
Gets or sets the note's globally unique identifier (GUID). If not explicitly set, the GUID is auto-generated.
### Getter
```python
@property
def guid(self) -> str
```
**Returns:** `str` — The GUID (auto-generated from field values if not explicitly set)
### Setter
```python
@guid.setter
def guid(self, val: str)
```
**Behavior:**
- If not set, GUID is computed as a base-91 encoded SHA256 hash of the field values separated by `__`
- The auto-generated GUID allows Anki to match notes on re-import to update existing notes
- Custom GUIDs are useful when you want to change field values but keep the same note identity
**Example:**
```python
note1 = genanki.Note(model=genanki.BASIC_MODEL, fields=['Question', 'Answer'])
print(note1.guid) # Auto-generated from fields
note2 = genanki.Note(
model=genanki.BASIC_MODEL,
fields=['Question', 'Answer'],
guid='my-custom-guid'
)
print(note2.guid) # 'my-custom-guid'
```
```
--------------------------------
### Create genanki Package with Media Files
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/package.md
Instantiate a Package with a Deck and a list of media file paths. Ensure the paths are correct for your media.
```python
import genanki
# Create a deck
deck = genanki.Deck(2059400110, 'Country Capitals')
model = genanki.BASIC_MODEL
note = genanki.Note(model=model, fields=['France', 'Paris'])
deck.add_note(note)
# Create package with media files
package = genanki.Package(deck, media_files=['path/to/image.jpg', 'path/to/audio.mp3'])
```
--------------------------------
### Typical Card Generation Workflow
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/card.md
Demonstrates the standard process of creating a note, which automatically generates cards based on the associated model. Shows how to access and print information about the generated cards, and then how to add the note to a deck and write the package.
```python
import genanki
# 1. Create a model
model = genanki.BASIC_MODEL
# 2. Create a note (cards auto-generated)
note = genanki.Note(model=model, fields=['Question', 'Answer'])
# 3. Access generated cards
print(f'Generated {len(note.cards)} card(s)')
for card in note.cards:
print(f' Card ord={card.ord}, suspend={card.suspend}')
# 4. Add note to deck and write package
deck = genanki.Deck(2059400110, 'My Deck')
deck.add_note(note)
package = genanki.Package(deck)
package.write_to_file('output.apkg')
```
--------------------------------
### Create Notes with Explicit UUIDs in Genanki
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/utilities.md
Use this pattern when you need precise control over note GUIDs, for example, by using UUIDs. Be aware that manually setting GUIDs can break Anki's automatic matching and updating behavior on re-import if not managed carefully.
```python
import genanki
import uuid
# For cases where you want explicit control
def create_note_with_uuid(front, back):
return genanki.Note(
model=genanki.BASIC_MODEL,
fields=[front, back],
guid=str(uuid.uuid4())[:8] # First 8 chars of UUID
)
# WARNING: This breaks Anki's matching on re-import
# Only use if you understand the implications
```
--------------------------------
### Basic Usage
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/README.md
Demonstrates the fundamental steps to create an Anki deck using genanki: defining a model, creating notes, adding them to a deck, and writing the deck to an .apkg file.
```APIDOC
## Basic Usage
### Description
Demonstrates the fundamental steps to create an Anki deck using genanki: defining a model, creating notes, adding them to a deck, and writing the deck to an .apkg file.
### Method
```python
import genanki
# Create a model (card template)
model = genanki.BASIC_MODEL
# Create a note
note = genanki.Note(
model=model,
fields=['What is the capital of France?', 'Paris']
)
# Create a deck
deck = genanki.Deck(
2059400110,
'Country Capitals'
)
deck.add_note(note)
# Write to file
genanki.Package(deck).write_to_file('output.apkg')
```
```
--------------------------------
### Assign Explicit Custom GUID to a Note
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/utilities.md
Demonstrates how to manually assign a specific GUID to a Genanki note during its creation. This bypasses the automatic GUID generation based on fields.
```python
import genanki
note = genanki.Note(
model=genanki.BASIC_MODEL,
fields=['Question', 'Answer'],
guid='my-custom-guid-12345'
)
print(note.guid) # 'my-custom-guid-12345'
```
--------------------------------
### Create a Genanki Note with Custom GUID
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/configuration.md
Creates a Genanki note with a manually specified globally unique identifier (GUID). If not provided, a GUID is auto-generated from the note's fields.
```python
note = genanki.Note(
model=genanki.BASIC_MODEL,
fields=['Question', 'Answer'],
guid='custom-guid-12345'
)
```
--------------------------------
### Build and Upload genanki Package to PyPI
Source: https://github.com/kerrickstaley/genanki/blob/main/README.md
Run these commands from the root of the genanki repository to build the source distribution and wheel, and then upload them to PyPI. This process directly uploads to the production PyPI.
```bash
rm -rf dist/*
python3 setup.py sdist bdist_wheel
python3 -m twine upload dist/*
```
--------------------------------
### Auto-generate GUID for a Note
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/utilities.md
Demonstrates how Genanki automatically generates a unique GUID for a note based on its model and field values. Creating a note with identical fields will result in the same GUID.
```python
import genanki
model = genanki.BASIC_MODEL
note = genanki.Note(model=model, fields=['Paris', 'France'])
# GUID is auto-generated from field values
print(note.guid) # e.g., 'abc123def'
# Create the same note with same fields -> same GUID
note2 = genanki.Note(model=model, fields=['Paris', 'France'])
print(note.guid == note2.guid) # True
```
--------------------------------
### Custom Note GUID Implementation
Source: https://github.com/kerrickstaley/genanki/blob/main/README.md
Implement a custom GUID for notes by subclassing genanki.Note and defining a guid property. This allows hashing only specific fields to maintain stable note identities.
```python
class MyNote(genanki.Note):
@property
def guid(self):
return genanki.guid_for(self.fields[0], self.fields[1])
```
--------------------------------
### Create a Deck with Media Files
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/README.md
Demonstrates how to include media files, such as images, in Anki notes and packages. Ensure the media files are specified in the `media_files` argument when creating the `Package`.
```python
import genanki
model = genanki.BASIC_MODEL
deck = genanki.Deck(2059400110, 'Picture Vocabulary')
note = genanki.Note(
model=model,
fields=['
', 'A red fruit']
)
deck.add_note(note)
package = genanki.Package(deck, media_files=['path/to/apple.jpg'])
package.write_to_file('images.apkg')
```
--------------------------------
### Create a Simple Package
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/configuration.md
Create a genanki.Package with a single deck and write it to an .apkg file. This is the most basic way to package your Anki decks.
```python
import genanki
deck = genanki.Deck(2059400110, 'My Deck')
package = genanki.Package(deck)
package.write_to_file('output.apkg')
```
--------------------------------
### Generate GUID for Note Fields
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/utilities.md
Use `guid_for` to create a stable GUID from note field values. This ensures that notes with identical content will have the same GUID, allowing Anki to update existing notes upon re-import instead of creating duplicates. It accepts any number of arguments, which are converted to strings and joined before hashing.
```python
import genanki
# Generate GUID from field values
guid1 = genanki.guid_for('Paris', 'France')
guid2 = genanki.guid_for('Paris', 'France')
print(guid1 == guid2) # True (same values, same GUID)
# Different values produce different GUIDs
guid3 = genanki.guid_for('London', 'England')
print(guid1 == guid3) # False
# Can use any number of values
guid4 = genanki.guid_for('Question', 'Answer', 'Tag')
# Works with integers and other types (converted to strings)
guid5 = genanki.guid_for(1, 2, 3)
```
--------------------------------
### Configure Genanki from Environment Variables
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/configuration.md
Set deck ID, name, output file, and media directory using environment variables. Defaults are provided if variables are not set.
```python
import os
import genanki
# Example: configure from environment
DECK_ID = int(os.getenv('GENANKI_DECK_ID', '2059400110'))
DECK_NAME = os.getenv('GENANKI_DECK_NAME', 'My Deck')
OUTPUT_FILE = os.getenv('GENANKI_OUTPUT', 'output.apkg')
MEDIA_DIR = os.getenv('GENANKI_MEDIA', '')
deck = genanki.Deck(DECK_ID, DECK_NAME)
# Add notes...
media_files = []
if MEDIA_DIR and os.path.isdir(MEDIA_DIR):
media_files = [
os.path.join(MEDIA_DIR, f)
for f in os.listdir(MEDIA_DIR)
]
package = genanki.Package(deck, media_files=media_files)
package.write_to_file(OUTPUT_FILE)
```
--------------------------------
### Performance Test for GUID Generation
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/utilities.md
Measures the time taken to generate 100,000 GUIDs using `genanki.guid_for`. The function is designed to be fast, typically completing this task within a second.
```python
import time
import genanki
start = time.time()
for i in range(100000):
guid = genanki.guid_for(f'field1_{i}', f'field2_{i}')
elapsed = time.time() - start
print(f'{elapsed:.3f} seconds for 100k GUIDs') # ~0.5-1 second
```
--------------------------------
### Create a Simple Basic Anki Deck
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/INDEX.md
This snippet shows the recommended way to create a basic Anki deck with a simple question-and-answer note. It imports the genanki library, defines a deck and a basic model, adds a note, and writes the package to a file.
```python
import genanki
deck = genanki.Deck(2059400110, 'My Deck')
model = genanki.BASIC_MODEL
note = genanki.Note(model=model, fields=['Q', 'A'])
deck.add_note(note)
genanki.Package(deck).write_to_file('output.apkg')
```
--------------------------------
### Package Constructor
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/package.md
Initializes a new Package object, which can contain one or more decks and associated media files.
```APIDOC
## Class: Package
Represents an Anki package containing decks and media files.
### Constructor
```python
def __init__(self, deck_or_decks=None, media_files=None)
```
#### Parameters
- **deck_or_decks** (`Deck` or `list[Deck]`) - Optional - A single `Deck` or a list of `Deck` objects to include in the package. If a single `Deck` is provided, it is wrapped in a list internally.
- **media_files** (`list[str]`) - Optional - File paths (relative or absolute) to media files to include. Duplicates are automatically removed.
### Instance Attributes
- `decks` (`list[Deck]`): List of decks in this package (always a list, even if initialized with a single Deck)
- `media_files` (`list[str]`): List of media file paths (duplicates removed)
### Example
```python
import genanki
# Create a deck
deck = genanki.Deck(2059400110, 'Country Capitals')
model = genanki.BASIC_MODEL
note = genanki.Note(model=model, fields=['France', 'Paris'])
deck.add_note(note)
# Create package with single deck
package = genanki.Package(deck)
# Create package with media files
package = genanki.Package(deck, media_files=['path/to/image.jpg', 'path/to/audio.mp3'])
# Create package with multiple decks
deck2 = genanki.Deck(2059400111, 'US States')
package = genanki.Package([deck, deck2])
```
```
--------------------------------
### Configure and Write Genanki Package
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/README.md
Create a Genanki package, associating it with one or more decks and including media files. Write the package to an APKG file with a specified timestamp.
```python
package = genanki.Package(
deck_or_decks=deck,
media_files=['path/to/image.jpg']
)
package.write_to_file(
'output.apkg',
timestamp=time.time() # Or fixed timestamp
)
```
--------------------------------
### Generate Base-91 Encoded GUID
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/utilities.md
Illustrates the use of genanki.guid_for() to generate a GUID by hashing field values and encoding the result using Anki's custom base-91 scheme. The output is a compact, unique identifier.
```python
import genanki
# SHA256 of "field1__field2" encoded as base-91
guid = genanki.guid_for('field1', 'field2')
# Result is typically 8-12 characters like: "aB3cDeFg"
```
--------------------------------
### Create a Package with Media Files
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/configuration.md
Instantiate a genanki.Package including a list of media file paths. These files will be included in the generated Anki package.
```python
import genanki
deck = genanki.Deck(2059400110, 'My Deck')
package = genanki.Package(deck, media_files=[
'images/image1.jpg',
'images/image2.jpg',
'audio/sound.mp3'
])
package.write_to_file('output.apkg')
```
--------------------------------
### tags
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/note.md
Gets or sets the tags for the note. Tags are validated to ensure they do not contain spaces.
```APIDOC
## Property: tags
### Description
Gets or sets the note's tags. The setter validates that tags contain no spaces.
### Getter
```python
@property
def tags(self) -> _TagList
```
**Returns:** `_TagList` — A list-like object that validates tags contain no spaces
### Setter
```python
@tags.setter
def tags(self, val: list[str])
```
**Raises:** `ValueError` if any tag contains a space character
**Example:**
```python
note = genanki.Note(model=genanki.BASIC_MODEL, fields=['Q', 'A'])
# Add tags
note.tags = ['tag1', 'tag2']
note.tags.append('tag3')
# This raises ValueError: tag contains space
note.tags = ['invalid tag'] # ERROR
# Iterate tags
for tag in note.tags:
print(tag)
```
```
--------------------------------
### Triggering Invalid HTML Tag Warning
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/errors.md
This example demonstrates how a field with special characters like '&' can trigger the UserWarning if not properly HTML-encoded.
```python
import genanki
# Field contains special characters that should be HTML-encoded
note = genanki.Note(
model=genanki.BASIC_MODEL,
fields=['AT&T Company', 'American telephone company']
)
deck = genanki.Deck(2059400110, 'Test')
deck.add_note(note)
package = genanki.Package(deck)
package.write_to_file('output.apkg')
# UserWarning: Field contained the following invalid HTML tags...
```
--------------------------------
### sort_field
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/note.md
Gets or sets the sort field for the note, which Anki uses to order notes in the browse interface. By default, it uses the first field.
```APIDOC
## Property: sort_field
### Description
Gets or sets the sort field value. Used by Anki to order notes in the browse interface.
### Getter
```python
@property
def sort_field(self) -> str
```
**Returns:** `str` — The sort field value (defaults to the first field)
### Setter
```python
@sort_field.setter
def sort_field(self, val: str)
```
**Example:**
```python
note = genanki.Note(model=genanki.BASIC_MODEL, fields=['Q', 'A'])
print(note.sort_field) # 'Q' (first field by default)
note.sort_field = 'Custom Sort Value'
print(note.sort_field) # 'Custom Sort Value'
```
```
--------------------------------
### Initialize Card Object
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/card.md
Create a basic card instance. Use `suspend=True` to create a suspended card.
```python
import genanki
# Create a basic card
card1 = genanki.Card(0) # First card, not suspended
# Create a suspended card
card2 = genanki.Card(1, suspend=True) # Second card, suspended
```
--------------------------------
### Generate SHA-256 Hash for GUID
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/utilities.md
Computes the first 8 bytes of a SHA-256 hash from a joined string of values. Ensure values are strings before joining.
```python
import hashlib
hash_str = '__'.join(str(val) for val in values)
m = hashlib.sha256()
m.update(hash_str.encode('utf-8'))
hash_bytes = m.digest()[:8] # First 8 bytes
hash_int = int.from_bytes(hash_bytes, byteorder='big')
```
--------------------------------
### Create a Genanki Deck from Environment Variables
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/configuration.md
Initializes a Genanki deck using deck ID and name values fetched from environment variables, with fallback defaults. Ensure the deck ID is globally unique.
```python
import os
import genanki
deck_id = int(os.getenv('DECK_ID', '2059400110'))
deck_name = os.getenv('DECK_NAME', 'Default Deck')
deck = genanki.Deck(deck_id, deck_name)
```
--------------------------------
### Create and Export a Simple Anki Deck
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/_START_HERE.txt
This snippet demonstrates how to create a basic Anki deck with a single note and export it to an .apkg file. Ensure the genanki library is imported before use.
```python
import genanki
# Create a simple deck
deck = genanki.Deck(2059400110, 'My Deck')
model = genanki.BASIC_MODEL
note = genanki.Note(model=model, fields=['Question', 'Answer'])
deck.add_note(note)
# Export to .apkg file
genanki.Package(deck).write_to_file('output.apkg')
```
--------------------------------
### Convert Deck to JSON Representation
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/deck.md
Use this method to get a JSON representation of the deck for database storage. It returns a dictionary containing deck metadata.
```python
def to_json(self)
```
```python
deck = genanki.Deck(2059400110, 'My Deck', description='Test')
json_data = deck.to_json()
print(json_data['id']) # 2059400110
print(json_data['name']) # 'My Deck'
print(json_data['desc']) # 'Test'
```
--------------------------------
### Create and Add to a Deck
Source: https://github.com/kerrickstaley/genanki/blob/main/README.md
Instantiate a Deck with a unique ID and name, then add notes to it. Ensure the deck ID is generated once and hardcoded.
```python
my_deck = genanki.Deck(
2059400110,
'Country Capitals')
my_deck.add_note(my_note)
```
--------------------------------
### Initialize Genanki Deck
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/deck.md
Create a new Genanki deck instance with a unique ID, name, and optional description. The deck ID should be a unique integer, recommended to be generated randomly.
```python
import genanki
# Create a deck with required parameters
deck = genanki.Deck(
deck_id=2059400110,
name='Country Capitals',
description='Learn capital cities around the world'
)
# Deck ID generation command
# python3 -c "import random; print(random.randrange(1 << 30, 1 << 31))"
```
--------------------------------
### Write Deck to APKG File
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/deck.md
Use this convenience method to write the current deck directly to an `.apkg` file. Specify the desired file path as a string argument.
```python
deck = genanki.Deck(2059400110, 'My Deck')
model = genanki.BASIC_MODEL
note = genanki.Note(model=model, fields=['Q', 'A'])
deck.add_note(note)
# Write directly to file
deck.write_to_file('output.apkg')
```
--------------------------------
### Configure Genanki Note
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/README.md
Instantiate a Genanki note, associating it with a model and providing field values. Supports custom sort fields, tags, GUIDs, and due dates.
```python
note = genanki.Note(
model=model,
fields=['Q', 'A'],
sort_field='Custom sort',
tags=['tag1', 'tag2'],
guid='custom-guid',
due=5 # Days from now
)
```
--------------------------------
### Generate Cards for Front/Back Model
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/card.md
Demonstrates how to create a Front/Back model and generate cards from a note. The number of cards generated depends on the templates and whether required fields are present.
```python
model = genanki.Model(
1607392319,
'Model',
fields=[{'name': 'Front'}, {'name': 'Back'}],
templates=[
{'name': 'Card 1', 'qfmt': '{{Front}}', 'afmt': '{{Back}}'},
{'name': 'Card 2', 'qfmt': '{{Back}}', 'afmt': '{{Front}}'},
]
)
note = genanki.Note(model=model, fields=['Q', 'A'])
print(len(note.cards)) # 2 (one per template, both have required fields)
# If a field is empty, the card may not be generated (depends on template)
note2 = genanki.Note(model=model, fields=['Q', ''])
# Cards depend on template requirements
```
--------------------------------
### Write Deck to Package File
Source: https://github.com/kerrickstaley/genanki/blob/main/README.md
Create a Package from a Deck and write it to an .apkg file for Anki import. This file can then be loaded into Anki.
```python
genanki.Package(my_deck).write_to_file('output.apkg')
```
--------------------------------
### Cloze Deletion Model Configuration
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/configuration.md
Example of configuring a genanki Model for cloze deletion cards. This model uses the 'CLOZE' type and defines 'Text' and 'Extra' fields.
```python
model = genanki.Model(
1550428389,
'Cloze Deletion',
fields=[
{'name': 'Text'},
{'name': 'Extra'},
],
templates=[
{
'name': 'Cloze',
'qfmt': '{{cloze:Text}}',
'afmt': '{{cloze:Text}}
{{Extra}}'
}
],
model_type=genanki.Model.CLOZE
)
```
--------------------------------
### Configure Genanki Deck
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/README.md
Create a Genanki deck with a unique ID and a name. Optionally, provide a description for the deck.
```python
deck = genanki.Deck(
deck_id=2059400110,
name='My Deck',
description='Description text'
)
```
--------------------------------
### guid_for
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/utilities.md
Generates a globally unique identifier (GUID) for a note based on provided field values. This function is crucial for Anki's note matching and updating mechanism during imports.
```APIDOC
## Function: guid_for
### Description
Generates a globally unique identifier (GUID) for a note based on field values. This function is essential for Anki's note matching and updating mechanism during imports.
### Signature
```python
def guid_for(*values) -> str
```
### Parameters
#### `*values`
- Type: `str` or convertible to `str`
- Description: Variable number of values to hash into the GUID.
### Returns
- Type: `str`
- Description: A base-91 encoded GUID (typically 8-12 characters).
### Behavior
1. Converts all values to strings.
2. Joins them with `__` separator.
3. Computes SHA256 hash of the resulting string.
4. Takes the first 8 bytes of the hash.
5. Encodes as a base-91 number (Anki's custom encoding).
6. Returns as a string.
### Example
```python
import genanki
# Generate GUID from field values
guid1 = genanki.guid_for('Paris', 'France')
guid2 = genanki.guid_for('Paris', 'France')
print(guid1 == guid2) # True (same values, same GUID)
# Different values produce different GUIDs
guid3 = genanki.guid_for('London', 'England')
print(guid1 == guid3) # False
# Can use any number of values
guid4 = genanki.guid_for('Question', 'Answer', 'Tag')
# Works with integers and other types (converted to strings)
guid5 = genanki.guid_for(1, 2, 3)
```
```
--------------------------------
### Create a Genanki Deck with Description
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/configuration.md
Configures a Genanki deck including a descriptive text that will be visible in Anki's deck browser. The deck ID must be globally unique.
```python
deck = genanki.Deck(
2059400110,
'Spanish Vocabulary',
description='Essential Spanish words for beginner learners'
)
```
--------------------------------
### Anki Deck JSON Structure
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/deck.md
Example of the JSON representation of a deck as stored in the Anki database. This structure includes fields like deck ID, name, and learning progress.
```json
{
"collapsed": false,
"conf": 1,
"desc": "Learn capital cities around the world",
"dyn": 0,
"extendNew": 0,
"extendRev": 50,
"id": 2059400110,
"lrnToday": [163, 2],
"mod": 1425278051,
"name": "Country Capitals",
"newToday": [163, 2],
"revToday": [163, 0],
"timeToday": [163, 23598],
"usn": -1
}
```
--------------------------------
### Triggering CLOZE_MODEL Single Field DeprecationWarning
Source: https://github.com/kerrickstaley/genanki/blob/main/_autodocs/errors.md
This example demonstrates how to trigger the DeprecationWarning by using CLOZE_MODEL with only one field. This warning is raised during Note.write_to_db() for compatibility with older genanki versions.
```python
import genanki
import warnings
# This produces a DeprecationWarning
note = genanki.Note(
model=genanki.CLOZE_MODEL,
fields=['{{c1::answer}}'] # Only 1 field!
)
deck = genanki.Deck(2059400110, 'Test')
deck.add_note(note)
package = genanki.Package(deck)
package.write_to_file('output.apkg')
# DeprecationWarning: Using CLOZE_MODEL with a single field is deprecated...
```