diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..dced677 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,137 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +This is a Python-based GEDCOM (genealogical data) parser that converts family tree data into Obsidian-compatible Markdown notes with WikiLinks. The project extracts comprehensive genealogical data including relationships, events, images, and long-form narratives. + +## Core Architecture + +The codebase follows a clean modular architecture in `src/`: + +1. **GedcomParser** (`gedcom_parser.py`): GEDCOM file parser + - Wraps the `python-gedcom` library with error handling + - Parses GEDCOM files and extracts individuals + - Provides element lookup by pointer/ID + - Handles line ending issues (CR vs LF) + +2. **Individual** (`individual.py`): Rich person data model + - Comprehensive data extraction: names, dates, relationships, events + - Resolves GEDCOM references (notes, images, stories) + - Supports multiple marriages and families + - Extracts physical attributes (eyes, hair, height) + - Handles custom tags like `_STO` (stories from MobileFamilyTree) + - Generates proper filenames: "FamilyName FirstName BirthYear" + +3. **MarkdownGenerator** (`markdown_generator.py`): Obsidian note creation + - Generates notes with proper WikiLinks format + - Sections: Attributes, Events, Families, Parents, Children, Images, Notes + - Uses Obsidian metadata: `[key:: value]` (visible) and `(key:: value)` (hidden) + - Handles multiple marriages with proper formatting + +4. **IndexGenerator** (`index_generator.py`): Global index creation + - Creates alphabetical index by last name + - Groups individuals by first letter + - Includes life spans where available + +5. **main.py**: CLI entry point + - Argument parsing with argparse + - Logging configuration + - Orchestrates parsing, generation, and indexing + +## Development Environment Setup + +```sh +# Install dependencies +pip install -r requirements.txt + +# The main script is directly executable +python src/main.py +``` + +## Running the Converter + +### Basic Usage +```sh +python src/main.py examples/Stammbaum_Kucera.ged output/ +``` + +### With Options +```sh +# Verbose logging +python src/main.py input.ged output/ --verbose + +# Skip index creation +python src/main.py input.ged output/ --no-index +``` + +**Important**: Output directory must exist before running. + +## Key Implementation Details + +### File Naming Convention +- Format: "FamilyName FirstName BirthYear.md" +- Birth year omitted if unknown +- Example: "Kucera Alexander Maximilian 1980.md" + +### Obsidian Metadata Format +- Visible metadata: `[key:: value]` - displays in note +- Hidden metadata: `(key:: value)` - indexed but not displayed +- WikiLinks: `[[Note Name]]` - links to other notes + +### Data Extraction Strategy +The Individual class extracts data through several methods: +- `get_names()`: Returns (first_name, last_name) tuple +- `get_families()`: Returns list of marriages with partners and children +- `get_events()`: Extracts BIRT, DEAT, OCCU, EDUC, RESI, BURI events +- `get_notes()`: Resolves NOTE references and inline notes +- `get_stories()`: Extracts custom `_STO` story records +- `get_images()`: Extracts OBJE media references + +### Reference Resolution +GEDCOM uses pointers (`@ID@`) to reference other records. The Individual class resolves: +- NOTE references to actual note text +- Story references (`_STO`) to narrative text +- Family references to spouse and children data + +### Multiple Marriages +Families are extracted with full context: +- Partner information with WikiLinks +- Marriage date and place +- Children grouped by marriage +- All marriages numbered if more than one + +## Common Issues + +### Line Ending Problem +Some GEDCOM files (especially from macOS apps) use CR line endings which the parser can't handle. Symptoms: +- Parser reports 0 individuals +- No output files created + +**Fix**: Convert line endings before parsing (see README.md) + +### Empty Notes +If NOTE records exist but appear empty, they may be placeholder records without content. This is valid GEDCOM. + +### Story Tags +The `_STO` tag is a custom extension used by MobileFamilyTree. Other genealogy programs may use different custom tags for stories. + +## Dependencies + +- `python-gedcom==1.0.0`: GEDCOM parsing library +- Python 3.7+ + +Update dependencies: +```sh +pip install +pip freeze > requirements.txt +``` + +## Code Style + +- Follow PEP 8 +- Use type hints for all function signatures +- Docstrings for all public functions and classes +- Logging for important operations +- Proper error handling with specific exceptions diff --git a/README.md b/README.md index 08bf4ff..6f6ec1b 100644 --- a/README.md +++ b/README.md @@ -1 +1,79 @@ -# gedcom-to-markdown +# GEDCOM to Markdown Converter + +Convert GEDCOM genealogy files to Obsidian-compatible markdown notes with WikiLinks. + +## Features + +- **Complete Individual Notes**: Generates detailed markdown notes for each person +- **WikiLinks**: All relationships use `[[WikiLinks]]` format for Obsidian +- **Comprehensive Data**: Captures births, deaths, marriages, events, physical attributes, images, and notes +- **Multiple Marriages**: Supports individuals with multiple spouses +- **Life Stories**: Extracts long-form narratives and stories +- **Global Index**: Creates an alphabetical index of all individuals +- **Proper Naming**: Files named as "FamilyName FirstName BirthYear.md" + +## Installation + +```bash +pip install -r requirements.txt +``` + +## Usage + +```bash +python src/main.py path/to/family.ged output/directory +``` + +### Options + +- `--no-index`: Skip creating the index file +- `--verbose` or `-v`: Enable detailed logging + +### Example + +```bash +python src/main.py examples/Stammbaum_Kucera.ged examples/files --verbose +``` + +This will create: +- One markdown file per person in `examples/files/` +- An `Index.md` file with alphabetical listing + +## Output Format + +Each person gets a markdown note with sections for: +- **Attributes**: Name, birth, death, physical characteristics +- **Life Events**: Occupations, education, residences, etc. +- **Families**: Marriages with dates, places, and children +- **Parents**: Links to parent notes +- **Images**: Media references from GEDCOM +- **Notes**: Long-form stories and narratives + +## Project Structure + +``` +src/ +├── gedcom_parser.py # GEDCOM file parsing +├── individual.py # Person data model +├── markdown_generator.py # Note generation +├── index_generator.py # Index file creation +└── main.py # CLI entry point +``` + +## Requirements + +- Python 3.7+ +- python-gedcom==1.0.0 + +## Line Ending Issue + +**Important**: Some GEDCOM files exported from macOS applications may use old Mac-style line endings (CR only). If the parser finds 0 individuals, convert line endings first: + +```bash +python -c " +with open('file.ged', 'rb') as f: + content = f.read() +with open('file.ged', 'wb') as f: + f.write(content.replace(b'\r', b'\n')) +" +``` diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..22b8473 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +python-gedcom==1.0.0 diff --git a/src/gedcom_parser.py b/src/gedcom_parser.py new file mode 100644 index 0000000..708f55e --- /dev/null +++ b/src/gedcom_parser.py @@ -0,0 +1,75 @@ +""" +GEDCOM file parser module. + +This module provides a clean interface to parse GEDCOM files and extract +individual and family data. +""" + +from pathlib import Path +from typing import List, Optional +import logging + +from gedcom.parser import Parser +from gedcom.element.individual import IndividualElement + + +logger = logging.getLogger(__name__) + + +class GedcomParser: + """ + Parser for GEDCOM genealogy files. + + This class wraps the python-gedcom library and provides a clean interface + for parsing GEDCOM files and extracting individual data. + """ + + def __init__(self, file_path: Path): + """ + Initialize the parser with a GEDCOM file. + + Args: + file_path: Path to the GEDCOM file to parse + + Raises: + FileNotFoundError: If the GEDCOM file doesn't exist + ValueError: If the file cannot be parsed + """ + if not file_path.exists(): + raise FileNotFoundError(f"GEDCOM file not found: {file_path}") + + self.file_path = file_path + self.parser = Parser() + + try: + logger.info(f"Parsing GEDCOM file: {file_path}") + self.parser.parse_file(str(file_path)) + except Exception as e: + raise ValueError(f"Failed to parse GEDCOM file: {e}") from e + + def get_individuals(self) -> List[IndividualElement]: + """ + Get all individuals from the GEDCOM file. + + Returns: + List of IndividualElement objects representing people in the tree + """ + individuals = [] + for element in self.parser.get_root_child_elements(): + if isinstance(element, IndividualElement): + individuals.append(element) + + logger.info(f"Found {len(individuals)} individuals") + return individuals + + def get_element_by_pointer(self, pointer: str): + """ + Get a GEDCOM element by its pointer/ID. + + Args: + pointer: The GEDCOM pointer (e.g., '@I123@') + + Returns: + The element with the given pointer, or None if not found + """ + return self.parser.get_element_dictionary().get(pointer) diff --git a/src/index_generator.py b/src/index_generator.py new file mode 100644 index 0000000..c7adad3 --- /dev/null +++ b/src/index_generator.py @@ -0,0 +1,94 @@ +""" +Index file generator for family tree notes. + +This module generates an alphabetical index of all individuals in the +family tree. +""" + +from pathlib import Path +from typing import List +import logging + +from individual import Individual + + +logger = logging.getLogger(__name__) + + +class IndexGenerator: + """ + Generates an index file linking to all individual notes. + + The index is organized alphabetically by last name, then first name. + """ + + def __init__(self, output_dir: Path): + """ + Initialize the index generator. + + Args: + output_dir: Directory where the index file will be created + """ + self.output_dir = output_dir + + def generate_index( + self, + individuals: List[Individual], + index_filename: str = 'Index.md' + ) -> Path: + """ + Generate an alphabetical index of all individuals. + + Args: + individuals: List of Individual objects + index_filename: Name of the index file (default: 'Index.md') + + Returns: + Path to the created index file + """ + index_path = self.output_dir / index_filename + + logger.info(f"Generating index file: {index_filename}") + + # Sort individuals by last name, then first name + sorted_individuals = sorted( + individuals, + key=lambda i: (i.get_names()[1].lower(), i.get_names()[0].lower()) + ) + + with open(index_path, 'w', encoding='utf-8') as f: + f.write("# Family Tree Index\n\n") + f.write(f"Total individuals: {len(individuals)}\n\n") + + # Group by last name initial + current_letter = '' + + for individual in sorted_individuals: + first, last = individual.get_names() + + # Write letter header if changed + if last: + letter = last[0].upper() + else: + letter = '#' # For individuals without last name + + if letter != current_letter: + current_letter = letter + f.write(f"\n## {current_letter}\n\n") + + # Write individual link with life span + filename = individual.get_file_name() + birth_info = individual.get_birth_info() + death_info = individual.get_death_info() + + # Format life span + if birth_info['year'] or death_info['date']: + death_year = death_info['date'][:4] if death_info['date'] else '' + life_span = f" ({birth_info['year']}-{death_year})" + else: + life_span = '' + + f.write(f"- [[{filename}]]{life_span}\n") + + logger.info(f"Index generated with {len(individuals)} individuals") + return index_path diff --git a/src/individual.py b/src/individual.py new file mode 100644 index 0000000..c3f56db --- /dev/null +++ b/src/individual.py @@ -0,0 +1,372 @@ +""" +Individual person data model. + +This module provides a rich data model for individuals in a family tree, +extracting all relevant information from GEDCOM data. +""" + +from typing import List, Dict, Optional, Tuple +import logging + +from gedcom.element.individual import IndividualElement +import gedcom.tags + + +logger = logging.getLogger(__name__) + + +class Individual: + """ + Represents an individual person in the family tree. + + This class wraps the GEDCOM IndividualElement and provides convenient + access to all person data including names, dates, relationships, events, + images, and notes. + """ + + def __init__(self, element: IndividualElement, gedcom_parser): + """ + Initialize an Individual from a GEDCOM element. + + Args: + element: The GEDCOM IndividualElement + gedcom_parser: The GedcomParser instance for resolving references + """ + self.element = element + self.gedcom = gedcom_parser.parser + + def get_id(self) -> str: + """Get the GEDCOM ID without @ symbols.""" + return self.element.get_pointer().replace('@', '') + + def get_names(self) -> Tuple[str, str]: + """ + Get the person's names. + + Returns: + Tuple of (first_name, last_name) + """ + first, last = self.element.get_name() + return first.strip(), last.strip() + + def get_full_name(self) -> str: + """ + Get the full name in 'FirstName LastName' format. + + Returns: + Full name with proper capitalization + """ + first, last = self.get_names() + return f"{first} {last}".strip().title() + + def get_file_name(self) -> str: + """ + Get the filename for this person's note. + + Format: 'FamilyName FirstName BirthYear' + If no birth year is known, year is omitted. + + Returns: + Filename without .md extension + """ + first, last = self.get_names() + name_part = f"{last} {first}".strip().title() + + birth_year = self.element.get_birth_year() + if birth_year != -1: + return f"{name_part} {birth_year}" + return name_part + + def get_birth_info(self) -> Dict[str, str]: + """ + Get birth information. + + Returns: + Dictionary with 'date', 'place', 'year' keys + """ + date, place, sources = self.element.get_birth_data() + year = self.element.get_birth_year() + + return { + 'date': date or '', + 'place': place or '', + 'year': str(year) if year != -1 else '' + } + + def get_death_info(self) -> Dict[str, str]: + """ + Get death information. + + Returns: + Dictionary with 'date', 'place' keys + """ + date, place, sources = self.element.get_death_data() + + return { + 'date': date or '', + 'place': place or '' + } + + def get_gender(self) -> str: + """Get the person's gender (M/F/U).""" + return self.element.get_gender() or 'U' + + def get_parents(self) -> List['Individual']: + """ + Get this person's parents. + + Returns: + List of Individual objects representing parents + """ + parent_elements = self.gedcom.get_parents(self.element) + return [Individual(p, type('', (), {'parser': self.gedcom})()) + for p in parent_elements] + + def get_children(self) -> List['Individual']: + """ + Get this person's children. + + Returns: + List of Individual objects representing children + """ + children = [] + for family in self.gedcom.get_families(self.element): + child_elements = self.gedcom.get_family_members( + family, + gedcom.tags.GEDCOM_TAG_CHILD + ) + for child in child_elements: + children.append( + Individual(child, type('', (), {'parser': self.gedcom})()) + ) + return children + + def get_partners(self) -> List['Individual']: + """ + Get this person's spouses/partners. + + Returns: + List of Individual objects representing partners + """ + partners = [] + for family in self.gedcom.get_families(self.element): + parent_elements = self.gedcom.get_family_members( + family, + 'PARENTS' + ) + for parent in parent_elements: + # Don't include self + if parent.get_pointer() != self.element.get_pointer(): + partners.append( + Individual( + parent, + type('', (), {'parser': self.gedcom})() + ) + ) + return partners + + def get_families(self) -> List[Dict]: + """ + Get all families this person is part of (as spouse). + + Returns: + List of dictionaries with family information including: + - partner: Individual object + - marriage_date: str + - marriage_place: str + - children: List of Individual objects + """ + families = [] + for family in self.gedcom.get_families(self.element): + # Get partner + partners = [] + for parent in self.gedcom.get_family_members(family, 'PARENTS'): + if parent.get_pointer() != self.element.get_pointer(): + partners.append( + Individual( + parent, + type('', (), {'parser': self.gedcom})() + ) + ) + + # Get marriage info + marriage_date = '' + marriage_place = '' + for child in family.get_child_elements(): + if child.get_tag() == 'MARR': + for subchild in child.get_child_elements(): + if subchild.get_tag() == 'DATE': + marriage_date = subchild.get_value() + elif subchild.get_tag() == 'PLAC': + marriage_place = subchild.get_value() + + # Get children + children = [] + for child in self.gedcom.get_family_members( + family, + gedcom.tags.GEDCOM_TAG_CHILD + ): + children.append( + Individual(child, type('', (), {'parser': self.gedcom})()) + ) + + families.append({ + 'partner': partners[0] if partners else None, + 'marriage_date': marriage_date, + 'marriage_place': marriage_place, + 'children': children + }) + + return families + + def get_events(self) -> List[Dict[str, str]]: + """ + Get all life events for this person. + + Returns: + List of dictionaries with 'type', 'date', 'place' keys + """ + events = [] + + for child in self.element.get_child_elements(): + tag = child.get_tag() + + # Common event tags + if tag in ['BIRT', 'DEAT', 'MARR', 'OCCU', 'EDUC', 'RESI', 'BURI']: + event = { + 'type': tag, + 'date': '', + 'place': '', + 'details': child.get_value() or '' + } + + # Extract date and place + for subchild in child.get_child_elements(): + if subchild.get_tag() == 'DATE': + event['date'] = subchild.get_value() + elif subchild.get_tag() == 'PLAC': + event['place'] = subchild.get_value() + + events.append(event) + + return events + + def get_images(self) -> List[str]: + """ + Get all image/media references for this person. + + Returns: + List of image reference IDs + """ + images = [] + + for child in self.element.get_child_elements(): + if child.get_tag() == 'OBJE': + # OBJE can have a reference or inline data + reference = child.get_value() + if reference: + images.append(reference) + + return images + + def get_notes(self) -> List[str]: + """ + Get all notes for this person. + + Returns: + List of note texts + """ + notes = [] + + for child in self.element.get_child_elements(): + if child.get_tag() == 'NOTE': + note_text = child.get_value() or '' + + # If note_text starts with @, it's a reference to a NOTE record + if note_text.startswith('@') and note_text.endswith('@'): + # Resolve the reference + note_element = self.gedcom.get_element_dictionary().get( + note_text + ) + if note_element: + # Get the note text from the NOTE element + note_text = note_element.get_value() or '' + + # Get continued text from the NOTE record + for subchild in note_element.get_child_elements(): + if subchild.get_tag() in ['CONT', 'CONC']: + note_text += '\n' + (subchild.get_value() or '') + else: + # Inline note - check for continued text in subchilds + for subchild in child.get_child_elements(): + if subchild.get_tag() in ['CONT', 'CONC']: + note_text += '\n' + (subchild.get_value() or '') + + if note_text and not note_text.startswith('@'): + notes.append(note_text.strip()) + + return notes + + def get_stories(self) -> List[Dict[str, str]]: + """ + Get stories/narratives for this person. + + Some genealogy programs (like MobileFamilyTree) use custom _STO + tags for storing longer narratives and stories about individuals. + + Returns: + List of dictionaries with 'title' and 'text' keys + """ + stories = [] + + for child in self.element.get_child_elements(): + if child.get_tag() == '_STO': + story_ref = child.get_value() + + if story_ref and story_ref.startswith('@'): + # Resolve the story reference + story_element = self.gedcom.get_element_dictionary().get( + story_ref + ) + if story_element: + story = { + 'title': '', + 'text': '' + } + + # Get title and text sections + for section in story_element.get_child_elements(): + if section.get_tag() == 'TITL': + story['title'] = section.get_value() or '' + elif section.get_tag() in ['_STS', 'TEXT']: + # Get text content + for text_part in section.get_child_elements(): + if text_part.get_tag() == 'TEXT': + story['text'] = text_part.get_value() or '' + # Check for CONT lines + for cont in text_part.get_child_elements(): + if cont.get_tag() in ['CONT', 'CONC']: + story['text'] += '\n' + (cont.get_value() or '') + + if story['title'] or story['text']: + stories.append(story) + + return stories + + def get_attributes(self) -> Dict[str, str]: + """ + Get physical attributes and other personal details. + + Returns: + Dictionary with attribute names as keys + """ + attributes = {} + + for child in self.element.get_child_elements(): + tag = child.get_tag() + + # Physical attributes + if tag in ['EYES', 'HAIR', 'HEIG']: + attributes[tag.lower()] = child.get_value() or '' + + return attributes diff --git a/src/main.py b/src/main.py new file mode 100755 index 0000000..fd67a71 --- /dev/null +++ b/src/main.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +""" +GEDCOM to Markdown converter. + +This script converts GEDCOM genealogy files into Obsidian-compatible +markdown notes with WikiLinks. +""" + +import argparse +import logging +import sys +from pathlib import Path + +from gedcom_parser import GedcomParser +from individual import Individual +from markdown_generator import MarkdownGenerator +from index_generator import IndexGenerator + + +def setup_logging(verbose: bool = False): + """Configure logging for the application.""" + level = logging.DEBUG if verbose else logging.INFO + logging.basicConfig( + level=level, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + datefmt='%Y-%m-%d %H:%M:%S' + ) + + +def convert_gedcom_to_markdown( + gedcom_file: Path, + output_dir: Path, + create_index: bool = True +) -> int: + """ + Convert a GEDCOM file to markdown notes. + + Args: + gedcom_file: Path to the input GEDCOM file + output_dir: Directory for output markdown files + create_index: Whether to create an index file + + Returns: + Exit code (0 for success, non-zero for failure) + """ + logger = logging.getLogger(__name__) + + try: + # Parse GEDCOM file + logger.info(f"Parsing GEDCOM file: {gedcom_file}") + parser = GedcomParser(gedcom_file) + + # Get all individuals + individual_elements = parser.get_individuals() + logger.info(f"Found {len(individual_elements)} individuals") + + if not individual_elements: + logger.warning("No individuals found in GEDCOM file") + return 1 + + # Wrap individuals in our data model + individuals = [ + Individual(elem, parser) for elem in individual_elements + ] + + # Generate markdown notes + logger.info(f"Generating markdown notes in: {output_dir}") + generator = MarkdownGenerator(output_dir) + created_files = generator.generate_all(individuals) + logger.info(f"Created {len(created_files)} markdown files") + + # Generate index + if create_index: + logger.info("Generating index file") + index_gen = IndexGenerator(output_dir) + index_path = index_gen.generate_index(individuals) + logger.info(f"Created index file: {index_path}") + + logger.info("Conversion completed successfully") + return 0 + + except FileNotFoundError as e: + logger.error(f"File not found: {e}") + return 1 + except ValueError as e: + logger.error(f"Invalid input: {e}") + return 1 + except Exception as e: + logger.error(f"Unexpected error: {e}", exc_info=True) + return 1 + + +def main(): + """Main entry point for the CLI.""" + parser = argparse.ArgumentParser( + description='Convert GEDCOM genealogy files to Obsidian markdown notes' + ) + + parser.add_argument( + 'gedcom_file', + type=Path, + help='Path to the input GEDCOM file' + ) + + parser.add_argument( + 'output_dir', + type=Path, + help='Directory for output markdown files' + ) + + parser.add_argument( + '--no-index', + action='store_true', + help='Do not create an index file' + ) + + parser.add_argument( + '-v', '--verbose', + action='store_true', + help='Enable verbose logging' + ) + + args = parser.parse_args() + + # Setup logging + setup_logging(args.verbose) + logger = logging.getLogger(__name__) + + # Validate inputs + if not args.gedcom_file.exists(): + logger.error(f"GEDCOM file not found: {args.gedcom_file}") + return 1 + + if not args.output_dir.exists(): + logger.error(f"Output directory not found: {args.output_dir}") + logger.info("Please create the output directory first") + return 1 + + # Convert + exit_code = convert_gedcom_to_markdown( + gedcom_file=args.gedcom_file, + output_dir=args.output_dir, + create_index=not args.no_index + ) + + return exit_code + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/src/markdown_generator.py b/src/markdown_generator.py new file mode 100644 index 0000000..84e6365 --- /dev/null +++ b/src/markdown_generator.py @@ -0,0 +1,306 @@ +""" +Markdown note generator for Obsidian. + +This module generates Obsidian-compatible markdown notes for individuals +in the family tree. +""" + +from pathlib import Path +from typing import List +import logging + +from individual import Individual + + +logger = logging.getLogger(__name__) + + +class MarkdownGenerator: + """ + Generates Obsidian markdown notes for individuals. + + This class handles formatting individual data into Obsidian-compatible + markdown with WikiLinks and metadata. + """ + + def __init__(self, output_dir: Path): + """ + Initialize the generator. + + Args: + output_dir: Directory where markdown files will be created + + Raises: + ValueError: If output_dir doesn't exist or isn't a directory + """ + if not output_dir.exists(): + raise ValueError(f"Output directory doesn't exist: {output_dir}") + if not output_dir.is_dir(): + raise ValueError(f"Output path is not a directory: {output_dir}") + + self.output_dir = output_dir + + def generate_note(self, individual: Individual) -> Path: + """ + Generate a markdown note for an individual. + + Args: + individual: The Individual to create a note for + + Returns: + Path to the created markdown file + """ + filename = individual.get_file_name() + '.md' + file_path = self.output_dir / filename + + logger.info(f"Generating note: {filename}") + + with open(file_path, 'w', encoding='utf-8') as f: + # Write all sections + self._write_header(f, individual) + self._write_attributes(f, individual) + self._write_events(f, individual) + self._write_families(f, individual) + self._write_parents(f, individual) + self._write_children(f, individual) + self._write_images(f, individual) + self._write_notes(f, individual) + + return file_path + + def _write_header(self, f, individual: Individual): + """Write the note header with main name.""" + f.write(f"# {individual.get_full_name()}\n\n") + + def _write_attributes(self, f, individual: Individual): + """Write basic attributes section.""" + f.write("## Attributes\n") + + birth = individual.get_birth_info() + death = individual.get_death_info() + + self._write_metadata(f, 'ID', individual.get_id()) + self._write_metadata(f, 'Name', individual.get_full_name()) + + # Lived years + lived = f"{birth['year']}-{death['date'][:4] if death['date'] else ''}" + self._write_metadata(f, 'Lived', lived) + + self._write_metadata(f, 'Sex', individual.get_gender()) + + # Birth details + if birth['date']: + self._write_metadata(f, 'Born', birth['date']) + if birth['place']: + self._write_metadata(f, 'Place of birth', birth['place']) + + # Death details + if death['date']: + self._write_metadata(f, 'Passed away', death['date']) + if death['place']: + self._write_metadata(f, 'Place of death', death['place']) + + # Physical attributes + attrs = individual.get_attributes() + for key, value in attrs.items(): + if value: + self._write_metadata(f, key.capitalize(), value) + + f.write('\n') + + def _write_events(self, f, individual: Individual): + """Write life events section.""" + events = individual.get_events() + + # Filter out birth and death (already in attributes) + other_events = [e for e in events + if e['type'] not in ['BIRT', 'DEAT']] + + if not other_events: + return + + f.write("## Life Events\n") + + event_names = { + 'MARR': 'Marriage', + 'OCCU': 'Occupation', + 'EDUC': 'Education', + 'RESI': 'Residence', + 'BURI': 'Burial' + } + + for event in other_events: + event_type = event_names.get(event['type'], event['type']) + f.write(f"### {event_type}\n") + + if event['date']: + f.write(f"- **Date**: {event['date']}\n") + if event['place']: + f.write(f"- **Place**: {event['place']}\n") + if event['details']: + f.write(f"- **Details**: {event['details']}\n") + + f.write('\n') + + f.write('\n') + + def _write_families(self, f, individual: Individual): + """Write families/marriages section.""" + families = individual.get_families() + + if not families: + return + + f.write("## Families\n") + + for i, family in enumerate(families, 1): + if family['partner']: + partner_name = family['partner'].get_file_name() + f.write(f"### Marriage {i if len(families) > 1 else ''}\n") + self._write_metadata_hidden( + f, + 'Partner', + self._wiki_link(partner_name) + ) + + if family['marriage_date']: + self._write_metadata_hidden( + f, + 'Marriage date', + family['marriage_date'] + ) + if family['marriage_place']: + self._write_metadata_hidden( + f, + 'Marriage place', + family['marriage_place'] + ) + + if family['children']: + f.write('\n**Children:**\n') + for child in family['children']: + self._write_metadata_hidden( + f, + 'Child', + self._wiki_link(child.get_file_name()) + ) + + f.write('\n') + + f.write('\n') + + def _write_parents(self, f, individual: Individual): + """Write parents section.""" + parents = individual.get_parents() + + if not parents: + return + + f.write("## Parents\n") + + for parent in parents: + self._write_metadata_hidden( + f, + 'Parent', + self._wiki_link(parent.get_file_name()) + ) + + f.write('\n') + + def _write_children(self, f, individual: Individual): + """Write children section (if not already in families).""" + # Skip if we already wrote families section + if individual.get_families(): + return + + children = individual.get_children() + + if not children: + return + + f.write("## Children\n") + + for child in children: + self._write_metadata_hidden( + f, + 'Child', + self._wiki_link(child.get_file_name()) + ) + + f.write('\n') + + def _write_images(self, f, individual: Individual): + """Write images section.""" + images = individual.get_images() + + if not images: + return + + f.write("## Images\n") + + for image_ref in images: + f.write(f"- {image_ref}\n") + + f.write('\n') + + def _write_notes(self, f, individual: Individual): + """Write notes section.""" + notes = individual.get_notes() + stories = individual.get_stories() + + if not notes and not stories: + return + + f.write("## Notes\n") + + # Write regular notes + for note in notes: + f.write(f"{note}\n\n") + + # Write stories with titles + for story in stories: + if story['title']: + f.write(f"### {story['title']}\n\n") + + if story['text']: + f.write(f"{story['text']}\n\n") + + f.write('\n') + + def _write_metadata(self, f, key: str, value: str): + """Write visible Obsidian metadata.""" + f.write(f"[{key}:: {value}]\n") + + def _write_metadata_hidden(self, f, key: str, value: str): + """Write hidden Obsidian metadata.""" + f.write(f"({key}:: {value})\n") + + def _wiki_link(self, text: str) -> str: + """Format text as a WikiLink.""" + return f"[[{text}]]" + + def generate_all(self, individuals: List[Individual]) -> List[Path]: + """ + Generate notes for all individuals. + + Args: + individuals: List of Individual objects + + Returns: + List of paths to created files + """ + logger.info(f"Generating notes for {len(individuals)} individuals") + + paths = [] + for individual in individuals: + try: + path = self.generate_note(individual) + paths.append(path) + except Exception as e: + logger.error( + f"Failed to generate note for " + f"{individual.get_full_name()}: {e}" + ) + + logger.info(f"Successfully generated {len(paths)} notes") + return paths