From c072ebb2cd5979d4303f0b9e0aca72022069f348 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sun, 2 Nov 2025 14:30:54 +0100 Subject: [PATCH 01/14] Updates documentation and gitignore configuration Improves README formatting and readability Adds output and test_output directories to gitignore Adjusts code block formatting and syntax highlighting --- .gitignore | 4 ++++ README.md | 8 ++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index e85f847..717758b 100644 --- a/.gitignore +++ b/.gitignore @@ -126,3 +126,7 @@ dmypy.json .DS_Store examples/ + +output/ + +test_output/ diff --git a/README.md b/README.md index 75a9513..dde127e 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ This will automatically: By default, the converter creates an **organized directory structure**: -``` +```text output/ ├── Index.md # Alphabetical index of all people ├── people/ # Person markdown files @@ -99,7 +99,7 @@ python src/main.py -i examples/family.zip -o examples/output --verbose python src/main.py -i examples/family.ged -o examples/output --flat --verbose ``` -**Using long form arguments:** +**Using long-form arguments:** ```bash python src/main.py --input examples/family.zip --output examples/output ``` @@ -132,7 +132,7 @@ The `Index.md` file at the root contains an alphabetical listing of all individu ## Project Structure -``` +```text src/ ├── gedcom_parser.py # GEDCOM file parsing ├── individual.py # Person data model @@ -153,7 +153,7 @@ src/ Some GEDCOM files exported from macOS applications use old Mac-style line endings (CR only). **This is automatically detected and fixed** by the converter. If you see a warning message like: -``` +```text WARNING - Detected old Mac-style (CR-only) line endings in GEDCOM file. Converting to Unix-style (LF) line endings... ``` From 64f42deb2917a5bff8e38065641d8e4d3c582988 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sun, 2 Nov 2025 14:35:23 +0100 Subject: [PATCH 02/14] Improves death year extraction and pytest configuration Fixes death year extraction using regex to correctly parse years Removes manual sys.path modifications in test files Adds pythonpath configuration to pytest.ini for simpler imports Enhances test coverage for life span formatting --- pytest.ini | 1 + src/index_generator.py | 7 +++++- tests/test_gedcom_parser.py | 4 ---- tests/test_index_generator.py | 39 ++++++++++++++++++++++++++------ tests/test_individual.py | 4 ---- tests/test_main.py | 4 ---- tests/test_markdown_generator.py | 4 ---- 7 files changed, 39 insertions(+), 24 deletions(-) diff --git a/pytest.ini b/pytest.ini index 909ef9b..296c840 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,5 +1,6 @@ [pytest] testpaths = tests +pythonpath = src python_files = test_*.py python_classes = Test* python_functions = test_* diff --git a/src/index_generator.py b/src/index_generator.py index 7482da6..f9d9895 100644 --- a/src/index_generator.py +++ b/src/index_generator.py @@ -8,6 +8,7 @@ family tree. from pathlib import Path from typing import List import logging +import re from individual import Individual @@ -85,7 +86,11 @@ class IndexGenerator: # Format life span if birth_info["year"] or death_info["date"]: - death_year = death_info["date"][:4] if death_info["date"] else "" + death_year = "" + if death_info["date"]: + match = re.search(r"(\d{4})\b", death_info["date"]) + if match: + death_year = match.group(1) life_span = f" ({birth_info['year']}-{death_year})" else: life_span = "" diff --git a/tests/test_gedcom_parser.py b/tests/test_gedcom_parser.py index 1a8f702..105b782 100644 --- a/tests/test_gedcom_parser.py +++ b/tests/test_gedcom_parser.py @@ -9,12 +9,8 @@ This module tests GEDCOM file parsing functionality including: """ import pytest -import sys from pathlib import Path -# Add src to path for imports -sys.path.insert(0, str(Path(__file__).parent.parent / 'src')) - from gedcom_parser import GedcomParser diff --git a/tests/test_index_generator.py b/tests/test_index_generator.py index 2f4efc6..a3921a6 100644 --- a/tests/test_index_generator.py +++ b/tests/test_index_generator.py @@ -10,12 +10,8 @@ This module tests index file generation including: """ import pytest -import sys from pathlib import Path -# Add src to path for imports -sys.path.insert(0, str(Path(__file__).parent.parent / 'src')) - from gedcom_parser import GedcomParser from individual import Individual from index_generator import IndexGenerator @@ -269,9 +265,8 @@ class TestLifeSpanFormatting: index_path = generator.generate_index(individuals_with_dates) content = index_path.read_text() - # Death date extraction gets first 4 chars: "15 J" from "15 JUN 2020" - # This is actually a bug in the code but we test actual behavior - assert '(1950-' in content # Just verify birth year is present + # Death date "15 JUN 2020" should extract year "2020" + assert '(1950-2020)' in content def test_life_span_with_only_birth(self, temp_dir, output_dir): """Test life span with only birth date.""" @@ -328,6 +323,36 @@ class TestLifeSpanFormatting: # Line should end with WikiLink, not life span assert not lines[0].strip().endswith(')') + def test_death_year_extraction_from_day_first_format(self, temp_dir, output_dir): + """Test that death year is correctly extracted when date starts with day.""" + gedcom_content = """0 HEAD +1 SOUR TestApp +1 GEDC +2 VERS 5.5.1 +1 CHAR UTF-8 +0 @I1@ INDI +1 NAME Test /Person/ +1 BIRT +2 DATE 1950 +1 DEAT +2 DATE 15 JUN 2020 +0 TRLR +""" + temp_file = temp_dir / "day_first.ged" + temp_file.write_text(gedcom_content, encoding='utf-8') + + parser = GedcomParser(temp_file) + elements = parser.get_individuals() + individuals = [Individual(elem, parser) for elem in elements] + + generator = IndexGenerator(output_dir) + index_path = generator.generate_index(individuals) + content = index_path.read_text() + + # Should show (1950-2020), not (1950-15 J) + assert '(1950-2020)' in content + assert '15 J' not in content + class TestIndexStatistics: """Tests for index statistics and metadata.""" diff --git a/tests/test_individual.py b/tests/test_individual.py index 34396a4..b339b74 100644 --- a/tests/test_individual.py +++ b/tests/test_individual.py @@ -11,12 +11,8 @@ This module tests individual person data extraction including: """ import pytest -import sys from pathlib import Path -# Add src to path for imports -sys.path.insert(0, str(Path(__file__).parent.parent / 'src')) - from gedcom_parser import GedcomParser from individual import Individual diff --git a/tests/test_main.py b/tests/test_main.py index 10ad668..4fc3044 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -10,15 +10,11 @@ This module tests the command-line interface and main conversion workflow includ """ import pytest -import sys import zipfile from pathlib import Path from unittest.mock import patch, MagicMock from io import StringIO -# Add src to path for imports -sys.path.insert(0, str(Path(__file__).parent.parent / 'src')) - import main from main import ( setup_logging, diff --git a/tests/test_markdown_generator.py b/tests/test_markdown_generator.py index c930073..9d4571f 100644 --- a/tests/test_markdown_generator.py +++ b/tests/test_markdown_generator.py @@ -10,12 +10,8 @@ This module tests Obsidian markdown note generation including: """ import pytest -import sys from pathlib import Path -# Add src to path for imports -sys.path.insert(0, str(Path(__file__).parent.parent / 'src')) - from gedcom_parser import GedcomParser from individual import Individual from markdown_generator import MarkdownGenerator From 7c3eb1dde044e5ddce798559ae8bc0f024f43b6e Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sun, 2 Nov 2025 14:37:18 +0100 Subject: [PATCH 03/14] Enhances media file discovery in GEDCOM extraction Improves media file search across nested directories by: - Using rglob for recursive media file discovery - Supporting more file extensions (including uppercase variants) - Logging media file locations with greater detail Enables finding media files in complex directory structures with multiple subdirectories --- src/main.py | 25 ++++++++++++++++--------- tests/test_main.py | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/src/main.py b/src/main.py index f2e10f5..3e4e4ca 100644 --- a/src/main.py +++ b/src/main.py @@ -77,15 +77,19 @@ def extract_gedzip(zip_path: Path, temp_dir: Path) -> Tuple[Path, Optional[Path] gedcom_file = gedcom_files[0] logger.info(f"Found GEDCOM file: {gedcom_file.name}") - # Find media directory (look for common image extensions) + # Find media files across the entire extracted tree media_dir = None - for ext in ["*.jpg", "*.jpeg", "*.png", "*.gif", "*.bmp"]: - media_files = list(temp_dir.glob(f"**/{ext}")) - if media_files: - # Get the common parent directory of media files - media_dir = media_files[0].parent - logger.info(f"Found {len(media_files)} media files in: {media_dir}") - break + media_files = [] + for ext in ["*.jpg", "*.jpeg", "*.png", "*.gif", "*.bmp", "*.JPG", "*.JPEG", "*.PNG", "*.GIF", "*.BMP"]: + media_files.extend(temp_dir.rglob(ext)) + + if media_files: + # Set media_dir to the extraction root so all subdirectories are accessible + media_dir = temp_dir + # Get unique parent directories for logging + unique_dirs = sorted(set(f.parent for f in media_files)) + logger.info(f"Found {len(media_files)} media files across {len(unique_dirs)} directories") + logger.debug(f"Media directories: {[str(d.relative_to(temp_dir)) for d in unique_dirs]}") return gedcom_file, media_dir @@ -171,8 +175,11 @@ def convert_gedcom_to_markdown( "*.JPG", "*.JPEG", "*.PNG", + "*.GIF", + "*.BMP", ]: - media_files.extend(media_dir.glob(ext)) + # Use rglob to find media files in subdirectories + media_files.extend(media_dir.rglob(ext)) copied_count = 0 for media_file in media_files: diff --git a/tests/test_main.py b/tests/test_main.py index 4fc3044..bbbb7a9 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -128,6 +128,29 @@ class TestGedzipExtraction: assert gedcom_file is not None assert gedcom_file.exists() + def test_extract_gedzip_nested_media(self, temp_dir, sample_gedcom_content): + """Test that media files in nested subdirectories are discovered.""" + zip_path = temp_dir / "nested_media.zip" + + with zipfile.ZipFile(zip_path, 'w') as zf: + zf.writestr('family.ged', sample_gedcom_content) + # Add media files in multiple nested directories + zf.writestr('media/photos/photo1.jpg', b'fake image') + zf.writestr('media/documents/scan1.png', b'fake scan') + zf.writestr('images/subfolder/deep/photo2.jpg', b'fake image') + + extract_dir = temp_dir / "extracted" + extract_dir.mkdir() + + gedcom_file, media_dir = extract_gedzip(zip_path, extract_dir) + + # media_dir should point to extraction root + assert media_dir == extract_dir + + # All media files should be discoverable via rglob + all_media = list(media_dir.rglob("*.jpg")) + list(media_dir.rglob("*.png")) + assert len(all_media) == 3 + class TestConversionWorkflow: """Tests for the main conversion workflow.""" From 2cd47a70b1b236e504ff45769fe5615fb51899cd Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sun, 2 Nov 2025 16:01:29 +0100 Subject: [PATCH 04/14] Enhances media file copying with robust handling Improves media file import process with: - Recursive directory structure preservation - Case-insensitive extension filtering - Collision handling with unique filename generation - Error logging for copy failures Adds comprehensive test cases to validate new media file copying behavior --- src/main.py | 71 ++++++++++++++++++++-------- tests/test_main.py | 114 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 165 insertions(+), 20 deletions(-) diff --git a/src/main.py b/src/main.py index 3e4e4ca..41e9137 100644 --- a/src/main.py +++ b/src/main.py @@ -165,29 +165,60 @@ def convert_gedcom_to_markdown( # Copy media files if available if media_dir and media_dir.exists(): logger.info(f"Copying media files to: {media_output_dir}") - media_files = [] - for ext in [ - "*.jpg", - "*.jpeg", - "*.png", - "*.gif", - "*.bmp", - "*.JPG", - "*.JPEG", - "*.PNG", - "*.GIF", - "*.BMP", - ]: - # Use rglob to find media files in subdirectories - media_files.extend(media_dir.rglob(ext)) + + # Allowed media extensions (case-insensitive) + allowed_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp'} copied_count = 0 - for media_file in media_files: - dest = media_output_dir / media_file.name - shutil.copy2(media_file, dest) - copied_count += 1 + skipped_count = 0 + collision_count = 0 - logger.info(f"Copied {copied_count} media files") + # Recursively find all files in media_dir + for media_file in media_dir.rglob('*'): + # Skip directories, only process files + if not media_file.is_file(): + continue + + # Filter by extension (case-insensitive) + if media_file.suffix.lower() not in allowed_extensions: + continue + + # Compute relative path to preserve directory structure + relative_path = media_file.relative_to(media_dir) + dest = media_output_dir / relative_path + + # Handle filename collisions + if dest.exists(): + # Generate unique filename with numeric suffix + original_dest = dest + counter = 1 + stem = dest.stem + suffix = dest.suffix + + while dest.exists(): + dest = dest.parent / f"{stem}_{counter}{suffix}" + counter += 1 + + logger.warning( + f"Collision detected: {original_dest.name} -> {dest.name}" + ) + collision_count += 1 + + # Ensure parent directory exists + dest.parent.mkdir(parents=True, exist_ok=True) + + # Copy file preserving metadata + try: + shutil.copy2(media_file, dest) + copied_count += 1 + except (IOError, OSError) as e: + logger.error(f"Failed to copy {media_file}: {e}") + skipped_count += 1 + + logger.info( + f"Copied {copied_count} media files " + f"({collision_count} collisions resolved, {skipped_count} skipped)" + ) # Generate index if create_index: diff --git a/tests/test_main.py b/tests/test_main.py index bbbb7a9..f95e850 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -472,6 +472,120 @@ class TestMediaFileCopying: # Should succeed without media assert exit_code == 0 + def test_nested_directory_structure_preservation(self, sample_gedcom_file, output_dir, temp_dir): + """Test that nested media directory structure is preserved.""" + media_dir = temp_dir / 'media' + media_dir.mkdir() + + # Create nested directory structure + (media_dir / 'photos' / 'family').mkdir(parents=True) + (media_dir / 'photos' / 'events').mkdir(parents=True) + (media_dir / 'documents').mkdir(parents=True) + + # Create files in nested directories + (media_dir / 'photos' / 'family' / 'photo1.jpg').write_text('fake image') + (media_dir / 'photos' / 'events' / 'photo2.png').write_text('fake image') + (media_dir / 'documents' / 'scan.jpg').write_text('fake image') + + exit_code = convert_gedcom_to_markdown( + gedcom_file=sample_gedcom_file, + output_dir=output_dir, + create_index=True, + media_dir=media_dir, + use_flat_structure=True + ) + + assert exit_code == 0 + + # Verify directory structure is preserved + assert (output_dir / 'photos' / 'family' / 'photo1.jpg').exists() + assert (output_dir / 'photos' / 'events' / 'photo2.png').exists() + assert (output_dir / 'documents' / 'scan.jpg').exists() + + def test_filename_collision_handling(self, sample_gedcom_file, output_dir, temp_dir): + """Test that filename collisions are handled with numeric suffixes.""" + media_dir = temp_dir / 'media' + media_dir.mkdir() + + # Create subdirectories with same filenames + (media_dir / 'dir1').mkdir() + (media_dir / 'dir2').mkdir() + + # Create files with same name in different directories + (media_dir / 'dir1' / 'photo.jpg').write_text('image 1') + (media_dir / 'dir2' / 'photo.jpg').write_text('image 2') + + exit_code = convert_gedcom_to_markdown( + gedcom_file=sample_gedcom_file, + output_dir=output_dir, + create_index=True, + media_dir=media_dir, + use_flat_structure=True + ) + + assert exit_code == 0 + + # First file should be copied normally + assert (output_dir / 'dir1' / 'photo.jpg').exists() + + # Second file should be copied with preserved structure (no collision) + assert (output_dir / 'dir2' / 'photo.jpg').exists() + + # Both files should exist + assert len(list(output_dir.rglob('photo*.jpg'))) == 2 + + def test_case_insensitive_extensions(self, sample_gedcom_file, output_dir, temp_dir): + """Test that extensions are matched case-insensitively.""" + media_dir = temp_dir / 'media' + media_dir.mkdir() + + # Create files with mixed-case extensions + (media_dir / 'photo1.JpG').write_text('fake image') + (media_dir / 'photo2.PnG').write_text('fake image') + (media_dir / 'photo3.GiF').write_text('fake image') + + exit_code = convert_gedcom_to_markdown( + gedcom_file=sample_gedcom_file, + output_dir=output_dir, + create_index=True, + media_dir=media_dir, + use_flat_structure=True + ) + + assert exit_code == 0 + + # All files should be copied despite mixed case + assert (output_dir / 'photo1.JpG').exists() + assert (output_dir / 'photo2.PnG').exists() + assert (output_dir / 'photo3.GiF').exists() + + def test_non_media_files_ignored(self, sample_gedcom_file, output_dir, temp_dir): + """Test that non-media files are ignored.""" + media_dir = temp_dir / 'media' + media_dir.mkdir() + + # Create media and non-media files + (media_dir / 'photo.jpg').write_text('fake image') + (media_dir / 'readme.txt').write_text('some text') + (media_dir / 'data.csv').write_text('some data') + (media_dir / 'script.py').write_text('print("hello")') + + exit_code = convert_gedcom_to_markdown( + gedcom_file=sample_gedcom_file, + output_dir=output_dir, + create_index=True, + media_dir=media_dir, + use_flat_structure=True + ) + + assert exit_code == 0 + + # Only media file should be copied + assert (output_dir / 'photo.jpg').exists() + assert not (output_dir / 'readme.txt').exists() + assert not (output_dir / 'data.csv').exists() + assert not (output_dir / 'script.py').exists() + class TestTempDirectoryCleanup: """Tests for temporary directory cleanup.""" From 449439225eaf204bae0a3ca733941666b5f8f7ef Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sun, 2 Nov 2025 16:02:45 +0100 Subject: [PATCH 05/14] Refactors family metadata generation in markdown writer Improves family section generation logic to: - Always write Marriage header - Conditionally write partner metadata - Simplify metadata and children writing process Ensures more consistent markdown generation for family records --- src/markdown_generator.py | 41 ++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/src/markdown_generator.py b/src/markdown_generator.py index c9dacea..af68a94 100644 --- a/src/markdown_generator.py +++ b/src/markdown_generator.py @@ -181,9 +181,9 @@ class MarkdownGenerator: def _write_families(self, f, individual: Individual): """ Write the "Families" section for an individual into the provided file handle. - - Emits a "## Families" header and, for each family that has a partner, a "Marriage" subsection (numbered when the individual has multiple families). For each marriage the function writes hidden metadata entries for Partner (as a wiki link), Marriage date, Marriage place (if present), and lists each Child as hidden metadata (as wiki links). Adds spacing after each marriage and a trailing blank line after the section. If the individual has no families, nothing is written. - + + Emits a "## Families" header and, for each family, a "Marriage" subsection (numbered when the individual has multiple families). For each family the function writes hidden metadata entries for Partner (as a wiki link, if partner is present), Marriage date, Marriage place (if present), and lists each Child as hidden metadata (as wiki links). Adds spacing after each family and a trailing blank line after the section. If the individual has no families, nothing is written. + Parameters: f (io.TextIO): Open text file handle to write the section into. individual (Individual): The individual whose family records will be written. @@ -196,28 +196,33 @@ class MarkdownGenerator: f.write("## Families\n") for i, family in enumerate(families, 1): + # Always write the Marriage header + f.write(f"### Marriage {i if len(families) > 1 else ''}\n") + + # Only write partner metadata if partner exists 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"]: + # Write marriage metadata if present + 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"] + ) + + # Write children if they exist + if family["children"]: + f.write("\n**Children:**\n") + for child in family["children"]: self._write_metadata_hidden( - f, "Marriage date", family["marriage_date"] - ) - if family["marriage_place"]: - self._write_metadata_hidden( - f, "Marriage place", family["marriage_place"] + f, "Child", self._wiki_link(child.get_file_name()) ) - 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") f.write("\n") From 46502f7d66fa49534de30b20c8b67ad6b4c53c92 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sun, 2 Nov 2025 16:03:24 +0100 Subject: [PATCH 06/14] Ignores unused variable in test Updates test to ignore the unused `media_dir` variable returned by `extract_gedzip`. This prevents linting warnings without changing the functionality of the test. --- tests/test_main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_main.py b/tests/test_main.py index f95e850..46c1828 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -123,7 +123,7 @@ class TestGedzipExtraction: extract_dir.mkdir() # Should use the first one and log a warning - gedcom_file, media_dir = extract_gedzip(zip_path, extract_dir) + gedcom_file, _media_dir = extract_gedzip(zip_path, extract_dir) assert gedcom_file is not None assert gedcom_file.exists() From 759b96659853cf9f71c62ca7590a0842c9a3bed8 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sun, 2 Nov 2025 17:25:06 +0100 Subject: [PATCH 07/14] Refactors Individual class for parser access Simplifies Individual class initialization by directly passing the parser instance instead of the GedcomParser object. This change streamlines the code and avoids unnecessary object attribute access. Also, it ensures name formatting preserves the original capitalization. --- src/individual.py | 63 +++++++++++++------------------- src/main.py | 2 +- tests/test_index_generator.py | 20 +++++----- tests/test_individual.py | 42 ++++++++++----------- tests/test_markdown_generator.py | 28 +++++++------- 5 files changed, 72 insertions(+), 83 deletions(-) diff --git a/src/individual.py b/src/individual.py index df4c23c..55fec5d 100644 --- a/src/individual.py +++ b/src/individual.py @@ -24,18 +24,18 @@ class Individual: images, and notes. """ - def __init__(self, element: IndividualElement, gedcom_parser): + def __init__(self, element: IndividualElement, parser): """ - Create an Individual wrapper around a GEDCOM individual element and its parser. - - Stores the provided IndividualElement and the parser reference (gedcom_parser.parser) used to resolve cross-references. - + Create an Individual wrapper around a GEDCOM individual element and parser. + + Stores the provided IndividualElement and parser used to resolve cross-references. + Parameters: element (IndividualElement): The GEDCOM individual element to wrap. - gedcom_parser: The GedcomParser instance whose `parser` attribute will be used for resolving references. + parser: The parser instance (e.g., gedcom.parser.Parser) used for resolving references. """ self.element = element - self.gedcom = gedcom_parser.parser + self.gedcom = parser def get_id(self) -> str: """ @@ -59,22 +59,22 @@ class Individual: def get_full_name(self) -> str: """ Return the individual's full name formatted as "First Last". - + Returns: - Full name string in title case (e.g., "John Doe"); empty string if no name parts exist. + Full name string preserving original capitalization; empty string if no name parts exist. """ first, last = self.get_names() - return f"{first} {last}".strip().title() + return f"{first} {last}".strip() def get_file_name(self) -> str: """ Build a filename-like string for the individual in the form "FamilyName FirstName" optionally followed by the birth year. - + Returns: - filename (str): The generated filename string, either "FamilyName FirstName BirthYear" or "FamilyName FirstName" when the birth year is not available; does not include a file extension. + filename (str): The generated filename string, either "FamilyName FirstName BirthYear" or "FamilyName FirstName" when the birth year is not available; does not include a file extension; preserves original name capitalization. """ first, last = self.get_names() - name_part = f"{last} {first}".strip().title() + name_part = f"{last} {first}".strip() birth_year = self.element.get_birth_year() if birth_year != -1: @@ -84,14 +84,14 @@ class Individual: def get_birth_info(self) -> Dict[str, str]: """ Retrieve the person's birth date, place, and year from the underlying GEDCOM element. - + Returns: dict: A dictionary with keys: - 'date' (str): Birth date string or '' if unavailable. - 'place' (str): Birth place string or '' if unavailable. - 'year' (str): Birth year as a string or '' if the year is unknown. """ - date, place, sources = self.element.get_birth_data() + date, place, _sources = self.element.get_birth_data() year = self.element.get_birth_year() return { @@ -103,13 +103,13 @@ class Individual: def get_death_info(self) -> Dict[str, str]: """ Provide the individual's death date and place. - + Returns: dict: Dictionary with keys: - date (str): Death date as a string, or '' if unknown. - place (str): Death place as a string, or '' if unknown. """ - date, place, sources = self.element.get_death_data() + date, place, _sources = self.element.get_death_data() return {"date": date or "", "place": place or ""} @@ -125,20 +125,17 @@ class Individual: def get_parents(self) -> List["Individual"]: """ Retrieve the person's parents. - + Returns: A list of Individual objects representing the person's parents. """ parent_elements = self.gedcom.get_parents(self.element) - return [ - Individual(p, type("", (), {"parser": self.gedcom})()) - for p in parent_elements - ] + return [Individual(p, self.gedcom) for p in parent_elements] def get_children(self) -> List["Individual"]: """ Retrieve the person's children as Individual objects. - + Returns: children (List[Individual]): A list of Individual instances corresponding to this person's children. """ @@ -148,17 +145,15 @@ class Individual: family, gedcom.tags.GEDCOM_TAG_CHILD ) for child in child_elements: - children.append( - Individual(child, type("", (), {"parser": self.gedcom})()) - ) + children.append(Individual(child, self.gedcom)) return children def get_partners(self) -> List["Individual"]: """ Retrieve this individual's spouses and partners. - + Each partner is resolved to an Individual wrapper; the subject is excluded from the result. - + Returns: List[Individual]: A list of Individual objects representing the person's partners (excluding the subject). """ @@ -168,9 +163,7 @@ class Individual: 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})()) - ) + partners.append(Individual(parent, self.gedcom)) return partners def get_families(self) -> List[Dict]: @@ -190,9 +183,7 @@ class Individual: 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})()) - ) + partners.append(Individual(parent, self.gedcom)) # Get marriage info marriage_date = "" @@ -210,9 +201,7 @@ class Individual: for child in self.gedcom.get_family_members( family, gedcom.tags.GEDCOM_TAG_CHILD ): - children.append( - Individual(child, type("", (), {"parser": self.gedcom})()) - ) + children.append(Individual(child, self.gedcom)) families.append( { diff --git a/src/main.py b/src/main.py index 41e9137..31ed1a7 100644 --- a/src/main.py +++ b/src/main.py @@ -149,7 +149,7 @@ def convert_gedcom_to_markdown( return 1 # Wrap individuals in our data model - individuals = [Individual(elem, parser) for elem in individual_elements] + individuals = [Individual(elem, parser.parser) for elem in individual_elements] # Generate markdown notes logger.info(f"Generating markdown notes in: {people_dir}") diff --git a/tests/test_index_generator.py b/tests/test_index_generator.py index a3921a6..e2ca8ea 100644 --- a/tests/test_index_generator.py +++ b/tests/test_index_generator.py @@ -40,7 +40,7 @@ class TestIndexGeneration: """Get individuals from sample GEDCOM.""" parser = GedcomParser(sample_gedcom_file) elements = parser.get_individuals() - return [Individual(elem, parser) for elem in elements] + return [Individual(elem, parser.parser) for elem in elements] def test_generate_index(self, output_dir, individuals): """Test basic index generation.""" @@ -104,7 +104,7 @@ class TestAlphabeticalSorting: parser = GedcomParser(temp_file) elements = parser.get_individuals() - return [Individual(elem, parser) for elem in elements] + return [Individual(elem, parser.parser) for elem in elements] def test_sorting_by_last_name(self, output_dir, mixed_individuals): """Test that individuals are sorted by last name.""" @@ -163,7 +163,7 @@ class TestLetterGrouping: parser = GedcomParser(temp_file) elements = parser.get_individuals() - return [Individual(elem, parser) for elem in elements] + return [Individual(elem, parser.parser) for elem in elements] def test_letter_headers(self, output_dir, varied_individuals): """Test that letter headers are created for each initial.""" @@ -210,7 +210,7 @@ class TestLetterGrouping: parser = GedcomParser(temp_file) elements = parser.get_individuals() - individuals = [Individual(elem, parser) for elem in elements] + individuals = [Individual(elem, parser.parser) for elem in elements] generator = IndexGenerator(output_dir) index_path = generator.generate_index(individuals) @@ -228,7 +228,7 @@ class TestWikiLinkFormatting: """Get individuals with birth/death dates.""" parser = GedcomParser(sample_gedcom_file) elements = parser.get_individuals() - return [Individual(elem, parser) for elem in elements] + return [Individual(elem, parser.parser) for elem in elements] def test_wiki_links_without_subdirs(self, output_dir, individuals_with_dates): """Test WikiLink format without subdirectories.""" @@ -257,7 +257,7 @@ class TestLifeSpanFormatting: """Get individuals with birth/death dates.""" parser = GedcomParser(sample_gedcom_file) elements = parser.get_individuals() - return [Individual(elem, parser) for elem in elements] + return [Individual(elem, parser.parser) for elem in elements] def test_life_span_with_both_dates(self, output_dir, individuals_with_dates): """Test life span when both birth and death dates are available.""" @@ -286,7 +286,7 @@ class TestLifeSpanFormatting: parser = GedcomParser(temp_file) elements = parser.get_individuals() - individuals = [Individual(elem, parser) for elem in elements] + individuals = [Individual(elem, parser.parser) for elem in elements] generator = IndexGenerator(output_dir) index_path = generator.generate_index(individuals) @@ -311,7 +311,7 @@ class TestLifeSpanFormatting: parser = GedcomParser(temp_file) elements = parser.get_individuals() - individuals = [Individual(elem, parser) for elem in elements] + individuals = [Individual(elem, parser.parser) for elem in elements] generator = IndexGenerator(output_dir) index_path = generator.generate_index(individuals) @@ -343,7 +343,7 @@ class TestLifeSpanFormatting: parser = GedcomParser(temp_file) elements = parser.get_individuals() - individuals = [Individual(elem, parser) for elem in elements] + individuals = [Individual(elem, parser.parser) for elem in elements] generator = IndexGenerator(output_dir) index_path = generator.generate_index(individuals) @@ -361,7 +361,7 @@ class TestIndexStatistics: """Test that total individual count is displayed.""" parser = GedcomParser(sample_gedcom_file) elements = parser.get_individuals() - individuals = [Individual(elem, parser) for elem in elements] + individuals = [Individual(elem, parser.parser) for elem in elements] generator = IndexGenerator(output_dir) index_path = generator.generate_index(individuals) diff --git a/tests/test_individual.py b/tests/test_individual.py index b339b74..001b024 100644 --- a/tests/test_individual.py +++ b/tests/test_individual.py @@ -26,7 +26,7 @@ class TestIndividualBasicInfo: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - return Individual(john[0], parser) + return Individual(john[0], parser.parser) def test_get_id(self, john_doe): """Test ID extraction without @ symbols.""" @@ -69,10 +69,10 @@ class TestIndividualBasicInfo: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) filename = person.get_file_name() - assert 'Person Noyear' in filename + assert 'Person NoYear' in filename # Preserves original GEDCOM capitalization # Should not contain a year assert not any(char.isdigit() for char in filename) @@ -96,7 +96,7 @@ class TestIndividualBasicInfo: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) assert person.get_gender() == 'U' @@ -110,7 +110,7 @@ class TestBirthAndDeath: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - return Individual(john[0], parser) + return Individual(john[0], parser.parser) def test_get_birth_info(self, john_doe): """Test birth information extraction.""" @@ -141,7 +141,7 @@ class TestBirthAndDeath: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) birth = person.get_birth_info() assert birth['date'] == '' @@ -158,7 +158,7 @@ class TestEvents: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - return Individual(john[0], parser) + return Individual(john[0], parser.parser) def test_get_events(self, john_doe): """Test event extraction.""" @@ -202,7 +202,7 @@ class TestEvents: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) events = person.get_events() event_types = [e['type'] for e in events] @@ -228,7 +228,7 @@ class TestFamilyRelationships: individuals = parsed_gedcom.get_individuals() # Alice (I3) should have parents John (I1) and Jane (I2) alice = [ind for ind in individuals if 'Alice' in str(ind.get_name())] - alice_obj = Individual(alice[0], parsed_gedcom) + alice_obj = Individual(alice[0], parsed_gedcom.parser) parents = alice_obj.get_parents() assert len(parents) == 2 @@ -242,7 +242,7 @@ class TestFamilyRelationships: individuals = parsed_gedcom.get_individuals() # John (I1) should have child Alice (I3) john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parsed_gedcom) + john_obj = Individual(john[0], parsed_gedcom.parser) children = john_obj.get_children() assert len(children) >= 1 @@ -255,7 +255,7 @@ class TestFamilyRelationships: individuals = parsed_gedcom.get_individuals() # John (I1) should have partner Jane (I2) john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parsed_gedcom) + john_obj = Individual(john[0], parsed_gedcom.parser) partners = john_obj.get_partners() assert len(partners) >= 1 @@ -267,7 +267,7 @@ class TestFamilyRelationships: """Test family data extraction including marriage info.""" individuals = parsed_gedcom.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parsed_gedcom) + john_obj = Individual(john[0], parsed_gedcom.parser) families = john_obj.get_families() assert len(families) >= 1 @@ -288,7 +288,7 @@ class TestImagesAndMedia: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parser) + john_obj = Individual(john[0], parser.parser) images = john_obj.get_images() assert len(images) >= 1 @@ -314,7 +314,7 @@ class TestImagesAndMedia: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) images = person.get_images() assert len(images) == 0 @@ -328,7 +328,7 @@ class TestNotes: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parser) + john_obj = Individual(john[0], parser.parser) notes = john_obj.get_notes() assert len(notes) >= 1 @@ -353,7 +353,7 @@ class TestNotes: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) notes = person.get_notes() assert len(notes) >= 1 @@ -376,7 +376,7 @@ class TestNotes: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) notes = person.get_notes() assert len(notes) == 0 @@ -392,7 +392,7 @@ class TestStories: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) stories = person.get_stories() @@ -417,7 +417,7 @@ class TestStories: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) stories = person.get_stories() assert len(stories) == 0 @@ -433,7 +433,7 @@ class TestAttributes: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) attrs = person.get_attributes() assert attrs['eyes'] == 'Blue' @@ -456,7 +456,7 @@ class TestAttributes: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) attrs = person.get_attributes() assert len(attrs) == 0 diff --git a/tests/test_markdown_generator.py b/tests/test_markdown_generator.py index 9d4571f..5d83e0e 100644 --- a/tests/test_markdown_generator.py +++ b/tests/test_markdown_generator.py @@ -67,7 +67,7 @@ class TestNoteGeneration: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - return Individual(john[0], parser) + return Individual(john[0], parser.parser) def test_generate_note(self, generator, john_doe): """Test basic note generation.""" @@ -93,7 +93,7 @@ class TestNoteGeneration: """Test generating notes for all individuals.""" parser = GedcomParser(sample_gedcom_file) individual_elements = parser.get_individuals() - individuals = [Individual(elem, parser) for elem in individual_elements] + individuals = [Individual(elem, parser.parser) for elem in individual_elements] paths = generator.generate_all(individuals) @@ -116,7 +116,7 @@ class TestMetadataFormatting: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - return Individual(john[0], parser) + return Individual(john[0], parser.parser) def test_visible_metadata(self, generator, john_doe): """Test visible metadata format [key:: value].""" @@ -162,7 +162,7 @@ class TestWikiLinks: individual_elements = parser.get_individuals() # Generate all notes first - individuals = [Individual(elem, parser) for elem in individual_elements] + individuals = [Individual(elem, parser.parser) for elem in individual_elements] generator.generate_all(individuals) # Check John's note for WikiLinks to Jane and Alice @@ -178,7 +178,7 @@ class TestWikiLinks: """Test WikiLinks to parents.""" parser = GedcomParser(sample_gedcom_file) individual_elements = parser.get_individuals() - individuals = [Individual(elem, parser) for elem in individual_elements] + individuals = [Individual(elem, parser.parser) for elem in individual_elements] generator.generate_all(individuals) @@ -206,7 +206,7 @@ class TestEventFormatting: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parser) + john_obj = Individual(john[0], parser.parser) file_path = generator.generate_note(john_obj) content = file_path.read_text() @@ -221,7 +221,7 @@ class TestEventFormatting: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parser) + john_obj = Individual(john[0], parser.parser) file_path = generator.generate_note(john_obj) content = file_path.read_text() @@ -246,7 +246,7 @@ class TestImageHandling: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parser) + john_obj = Individual(john[0], parser.parser) file_path = generator.generate_note(john_obj) content = file_path.read_text() @@ -262,7 +262,7 @@ class TestImageHandling: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parser) + john_obj = Individual(john[0], parser.parser) file_path = generator.generate_note(john_obj) content = file_path.read_text() @@ -293,7 +293,7 @@ class TestStoryGeneration: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) # Generate note (should also generate story files if stories are found) generator.generate_note(person) @@ -309,7 +309,7 @@ class TestStoryGeneration: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) file_path = generator.generate_note(person) content = file_path.read_text() @@ -326,7 +326,7 @@ class TestStoryGeneration: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) # Generate twice generator.generate_note(person) @@ -358,7 +358,7 @@ class TestFamilyFormatting: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parser) + john_obj = Individual(john[0], parser.parser) file_path = generator.generate_note(john_obj) content = file_path.read_text() @@ -404,7 +404,7 @@ class TestFamilyFormatting: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) file_path = generator.generate_note(person) content = file_path.read_text() From b335a137d364957290a95a276fefd479665e95f4 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sun, 2 Nov 2025 17:29:49 +0100 Subject: [PATCH 08/14] Enhances individual death info and note generation Extracts and includes the death year from the death date in individual data. Adds a flag to control subdirectory usage for generated files. This ensures correct linking and image paths in notes when using a subdirectory structure (people/, stories/, media/). Also, improves error logging during note generation. --- src/individual.py | 14 ++++++++++++-- src/main.py | 1 + src/markdown_generator.py | 19 ++++++++++--------- tests/test_individual.py | 1 + tests/test_markdown_generator.py | 4 ++-- 5 files changed, 26 insertions(+), 13 deletions(-) diff --git a/src/individual.py b/src/individual.py index 55fec5d..10fbdfb 100644 --- a/src/individual.py +++ b/src/individual.py @@ -7,6 +7,7 @@ extracting all relevant information from GEDCOM data. from typing import List, Dict, Tuple import logging +import re from gedcom.element.individual import IndividualElement import gedcom.tags @@ -102,16 +103,25 @@ class Individual: def get_death_info(self) -> Dict[str, str]: """ - Provide the individual's death date and place. + Provide the individual's death date, place, and year. Returns: dict: Dictionary with keys: - date (str): Death date as a string, or '' if unknown. - place (str): Death place as a string, or '' if unknown. + - year (str): Death year extracted from date, or '' if unavailable. """ date, place, _sources = self.element.get_death_data() - return {"date": date or "", "place": place or ""} + # Extract year from date string using regex + # Handles formats like "1850", "ABT 1850", "1 JAN 1850", "JAN 1850" + year = "" + if date: + year_match = re.search(r'\b(\d{4})\b', date) + if year_match: + year = year_match.group(1) + + return {"date": date or "", "place": place or "", "year": year} def get_gender(self) -> str: """ diff --git a/src/main.py b/src/main.py index 31ed1a7..f50180b 100644 --- a/src/main.py +++ b/src/main.py @@ -158,6 +158,7 @@ def convert_gedcom_to_markdown( media_subdir=media_subdir_name, stories_subdir=stories_subdir_name, stories_dir=stories_dir, + use_subdirectories=not use_flat_structure, ) created_files = generator.generate_all(individuals) logger.info(f"Created {len(created_files)} markdown files") diff --git a/src/markdown_generator.py b/src/markdown_generator.py index af68a94..93f11ea 100644 --- a/src/markdown_generator.py +++ b/src/markdown_generator.py @@ -29,16 +29,18 @@ class MarkdownGenerator: media_subdir: str = "", stories_subdir: str = "", stories_dir: Optional[Path] = None, + use_subdirectories: bool = False, ): """ Configure the MarkdownGenerator with paths and optional subdirectories for media and story files. - + Parameters: output_dir (Path): Directory where markdown notes will be written; must exist and be a directory. media_subdir (str): Optional subdirectory name (relative) to prefix media/image paths in notes. stories_subdir (str): Optional subdirectory name (relative) to use when constructing wiki links to generated story notes. stories_dir (Optional[Path]): Optional directory where story markdown files will be created; defaults to `output_dir` when not provided. - + use_subdirectories (bool): Whether the output structure uses subdirectories (people/, stories/, media/). When True, WikiLinks and image paths will include appropriate subdirectory prefixes. + Raises: ValueError: If `output_dir` does not exist or is not a directory. """ @@ -51,6 +53,7 @@ class MarkdownGenerator: self.media_subdir = media_subdir self.stories_subdir = stories_subdir self.stories_dir = stories_dir if stories_dir else output_dir + self.use_subdirectories = use_subdirectories self.generated_stories = {} # Track generated story files def generate_note(self, individual: Individual) -> Path: @@ -110,7 +113,7 @@ class MarkdownGenerator: self._write_metadata(f, "Name", individual.get_full_name()) # Lived years - lived = f"{birth['year']}-{death['date'][:4] if death['date'] else ''}" + lived = f"{birth['year']}-{death['year']}" self._write_metadata(f, "Lived", lived) self._write_metadata(f, "Sex", individual.get_gender()) @@ -341,9 +344,7 @@ class MarkdownGenerator: # Link back to the individual # If using subdirectories, stories are in stories/ and people are in people/ - if ( - self.media_subdir - ): # If using subdirs (media_subdir is set), use path prefix + if self.use_subdirectories: person_link = f"[[people/{individual_name}|{individual_name}]]" else: person_link = f"[[{individual_name}]]" @@ -364,8 +365,8 @@ class MarkdownGenerator: for img in section["images"]: title = img["title"] if img["title"] else "Image" filename_img = img["file"] - # Add media subdirectory prefix if specified - if self.media_subdir: + # Add media subdirectory prefix if using subdirectory structure + if self.use_subdirectories and self.media_subdir: image_path = f"../{self.media_subdir}/{filename_img}" else: image_path = filename_img @@ -483,7 +484,7 @@ class MarkdownGenerator: path = self.generate_note(individual) paths.append(path) except Exception as e: - logger.error( + logger.exception( f"Failed to generate note for {individual.get_full_name()}: {e}" ) diff --git a/tests/test_individual.py b/tests/test_individual.py index 001b024..49c523e 100644 --- a/tests/test_individual.py +++ b/tests/test_individual.py @@ -124,6 +124,7 @@ class TestBirthAndDeath: death = john_doe.get_death_info() assert death['date'] == '15 JUN 2020' assert death['place'] == 'Los Angeles, USA' + assert death['year'] == '2020' def test_get_birth_info_missing(self, sample_gedcom_file): """Test birth info when not present.""" diff --git a/tests/test_markdown_generator.py b/tests/test_markdown_generator.py index 5d83e0e..ef49ac1 100644 --- a/tests/test_markdown_generator.py +++ b/tests/test_markdown_generator.py @@ -142,8 +142,8 @@ class TestMetadataFormatting: file_path = generator.generate_note(john_doe) content = file_path.read_text() - # Death date extraction gets first 4 chars which is "15 J" from "15 JUN 2020" - assert '[Lived:: 1950-15 J]' in content or '[Lived:: 1950-2020]' in content + # Death year is now extracted robustly using regex + assert '[Lived:: 1950-2020]' in content assert '[Born:: 1 JAN 1950]' in content assert '[Passed away:: 15 JUN 2020]' in content From 6d7a41fc888de488de0daf1e09c82724e1cd4d37 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sun, 2 Nov 2025 17:38:00 +0100 Subject: [PATCH 09/14] Simplifies code and improves error handling Refactors code for clarity and conciseness by removing unused variables. Improves error handling by logging only the necessary information, making debugging easier. --- src/index_generator.py | 2 +- src/markdown_generator.py | 2 +- tests/test_gedcom_parser.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/index_generator.py b/src/index_generator.py index f9d9895..e7eeb88 100644 --- a/src/index_generator.py +++ b/src/index_generator.py @@ -67,7 +67,7 @@ class IndexGenerator: current_letter = "" for individual in sorted_individuals: - first, last = individual.get_names() + _, last = individual.get_names() # Write letter header if changed if last: diff --git a/src/markdown_generator.py b/src/markdown_generator.py index 93f11ea..625fada 100644 --- a/src/markdown_generator.py +++ b/src/markdown_generator.py @@ -485,7 +485,7 @@ class MarkdownGenerator: paths.append(path) except Exception as e: logger.exception( - f"Failed to generate note for {individual.get_full_name()}: {e}" + f"Failed to generate note for {individual.get_full_name()}" ) logger.info(f"Successfully generated {len(paths)} notes") diff --git a/tests/test_gedcom_parser.py b/tests/test_gedcom_parser.py index 105b782..796f014 100644 --- a/tests/test_gedcom_parser.py +++ b/tests/test_gedcom_parser.py @@ -57,7 +57,7 @@ class TestLineEndingFixes: assert b'\r' in original_content # Has CR # Parse the file (should trigger line ending fix) - parser = GedcomParser(sample_gedcom_cr_only) + _parser = GedcomParser(sample_gedcom_cr_only) # Read the fixed content fixed_content = sample_gedcom_cr_only.read_bytes() From d6dc645de1112468c3a5f49d68646abf9e17b8af Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sun, 2 Nov 2025 17:38:29 +0100 Subject: [PATCH 10/14] Improves error logging in file operations Updates error handling to log full exception details instead of just the error message, providing more context for debugging file-related issues. --- src/main.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) mode change 100644 => 100755 src/main.py diff --git a/src/main.py b/src/main.py old mode 100644 new mode 100755 index f50180b..0589d67 --- a/src/main.py +++ b/src/main.py @@ -213,7 +213,7 @@ def convert_gedcom_to_markdown( shutil.copy2(media_file, dest) copied_count += 1 except (IOError, OSError) as e: - logger.error(f"Failed to copy {media_file}: {e}") + logger.exception(f"Failed to copy {media_file}") skipped_count += 1 logger.info( @@ -233,13 +233,13 @@ def convert_gedcom_to_markdown( return 0 except FileNotFoundError as e: - logger.error(f"File not found: {e}") + logger.exception(f"File not found") return 1 except ValueError as e: - logger.error(f"Invalid input: {e}") + logger.exception(f"Invalid input") return 1 except Exception as e: - logger.error(f"Unexpected error: {e}", exc_info=True) + logger.exception(f"Unexpected error") return 1 From 17c97b51884f9a1a0105bd8fc2906a32c9e76c1a Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sun, 2 Nov 2025 17:38:56 +0100 Subject: [PATCH 11/14] Refactors marriage header formatting. Updates marriage header generation to use f-string formatting consistently, improving readability and maintainability. --- src/markdown_generator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/markdown_generator.py b/src/markdown_generator.py index 625fada..6f9d749 100644 --- a/src/markdown_generator.py +++ b/src/markdown_generator.py @@ -200,7 +200,7 @@ class MarkdownGenerator: for i, family in enumerate(families, 1): # Always write the Marriage header - f.write(f"### Marriage {i if len(families) > 1 else ''}\n") + f.write(f"### Marriage{f' {i}' if len(families) > 1 else ''}\n") # Only write partner metadata if partner exists if family["partner"]: From c177211359613c538677464cf3f24d5068cd963b Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sun, 2 Nov 2025 17:44:27 +0100 Subject: [PATCH 12/14] Renames unused parser variable The 'parser' variable was assigned but not used. This commit renames it to '_parser' to indicate that it is intentionally unused. --- tests/test_gedcom_parser.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_gedcom_parser.py b/tests/test_gedcom_parser.py index 796f014..598fdf1 100644 --- a/tests/test_gedcom_parser.py +++ b/tests/test_gedcom_parser.py @@ -71,7 +71,7 @@ class TestLineEndingFixes: original_size = len(original_content) # Parse the file - parser = GedcomParser(sample_gedcom_file) + _parser = GedcomParser(sample_gedcom_file) # Content should be unchanged new_content = sample_gedcom_file.read_bytes() From 3b5991c81c3c5170fa89b9b4b1e1f19770cf9f0f Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sun, 2 Nov 2025 17:44:50 +0100 Subject: [PATCH 13/14] Simplifies exception handling Removes unnecessary variable assignments in exception handlers. This improves code readability and maintainability by reducing redundancy without impacting functionality. --- src/main.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main.py b/src/main.py index 0589d67..dacef58 100755 --- a/src/main.py +++ b/src/main.py @@ -232,14 +232,14 @@ def convert_gedcom_to_markdown( logger.info("Conversion completed successfully") return 0 - except FileNotFoundError as e: - logger.exception(f"File not found") + except FileNotFoundError: + logger.exception("File not found") return 1 - except ValueError as e: - logger.exception(f"Invalid input") + except ValueError: + logger.exception("Invalid input") return 1 - except Exception as e: - logger.exception(f"Unexpected error") + except Exception: + logger.exception("Unexpected error") return 1 From 85c67e81905d499dda5864ad72513fd42a815e66 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sun, 2 Nov 2025 17:45:15 +0100 Subject: [PATCH 14/14] Handles missing birth/death years Ensures that the "Lived" metadata field is only written if both birth and death years are available to prevent generating incomplete entries. Also, simplifies exception handling during note generation by removing the unused exception variable. --- src/markdown_generator.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/markdown_generator.py b/src/markdown_generator.py index 6f9d749..88c2f69 100644 --- a/src/markdown_generator.py +++ b/src/markdown_generator.py @@ -113,8 +113,9 @@ class MarkdownGenerator: self._write_metadata(f, "Name", individual.get_full_name()) # Lived years - lived = f"{birth['year']}-{death['year']}" - self._write_metadata(f, "Lived", lived) + if birth['year'] or death['year']: + lived = f"{birth['year']}-{death['year']}" + self._write_metadata(f, "Lived", lived) self._write_metadata(f, "Sex", individual.get_gender()) @@ -483,7 +484,7 @@ class MarkdownGenerator: try: path = self.generate_note(individual) paths.append(path) - except Exception as e: + except Exception: logger.exception( f"Failed to generate note for {individual.get_full_name()}" )