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.
This commit is contained in:
AlexKucera committed 2025-11-02 17:29:49 +01:00
1 parent 759b966598
commit b335a137d3
5 files changed
+26 -13

No files matched your search

+12 -2
View File
@@ -7,6 +7,7 @@ extracting all relevant information from GEDCOM data.
from typing import List, Dict, Tuple from typing import List, Dict, Tuple
import logging import logging
import re
from gedcom.element.individual import IndividualElement from gedcom.element.individual import IndividualElement
import gedcom.tags import gedcom.tags
@@ -102,16 +103,25 @@ class Individual:
def get_death_info(self) -> Dict[str, str]: 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: Returns:
dict: Dictionary with keys: dict: Dictionary with keys:
- date (str): Death date as a string, or '' if unknown. - date (str): Death date as a string, or '' if unknown.
- place (str): Death place 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() 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: def get_gender(self) -> str:
""" """
+1
View File
@@ -158,6 +158,7 @@ def convert_gedcom_to_markdown(
media_subdir=media_subdir_name, media_subdir=media_subdir_name,
stories_subdir=stories_subdir_name, stories_subdir=stories_subdir_name,
stories_dir=stories_dir, stories_dir=stories_dir,
use_subdirectories=not use_flat_structure,
) )
created_files = generator.generate_all(individuals) created_files = generator.generate_all(individuals)
logger.info(f"Created {len(created_files)} markdown files") logger.info(f"Created {len(created_files)} markdown files")
+10 -9
View File
@@ -29,16 +29,18 @@ class MarkdownGenerator:
media_subdir: str = "", media_subdir: str = "",
stories_subdir: str = "", stories_subdir: str = "",
stories_dir: Optional[Path] = None, stories_dir: Optional[Path] = None,
use_subdirectories: bool = False,
): ):
""" """
Configure the MarkdownGenerator with paths and optional subdirectories for media and story files. Configure the MarkdownGenerator with paths and optional subdirectories for media and story files.
Parameters: Parameters:
output_dir (Path): Directory where markdown notes will be written; must exist and be a directory. 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. 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_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. 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: Raises:
ValueError: If `output_dir` does not exist or is not a directory. ValueError: If `output_dir` does not exist or is not a directory.
""" """
@@ -51,6 +53,7 @@ class MarkdownGenerator:
self.media_subdir = media_subdir self.media_subdir = media_subdir
self.stories_subdir = stories_subdir self.stories_subdir = stories_subdir
self.stories_dir = stories_dir if stories_dir else output_dir self.stories_dir = stories_dir if stories_dir else output_dir
self.use_subdirectories = use_subdirectories
self.generated_stories = {} # Track generated story files self.generated_stories = {} # Track generated story files
def generate_note(self, individual: Individual) -> Path: def generate_note(self, individual: Individual) -> Path:
@@ -110,7 +113,7 @@ class MarkdownGenerator:
self._write_metadata(f, "Name", individual.get_full_name()) self._write_metadata(f, "Name", individual.get_full_name())
# Lived years # 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, "Lived", lived)
self._write_metadata(f, "Sex", individual.get_gender()) self._write_metadata(f, "Sex", individual.get_gender())
@@ -341,9 +344,7 @@ class MarkdownGenerator:
# Link back to the individual # Link back to the individual
# If using subdirectories, stories are in stories/ and people are in people/ # If using subdirectories, stories are in stories/ and people are in people/
if ( if self.use_subdirectories:
self.media_subdir
): # If using subdirs (media_subdir is set), use path prefix
person_link = f"[[people/{individual_name}|{individual_name}]]" person_link = f"[[people/{individual_name}|{individual_name}]]"
else: else:
person_link = f"[[{individual_name}]]" person_link = f"[[{individual_name}]]"
@@ -364,8 +365,8 @@ class MarkdownGenerator:
for img in section["images"]: for img in section["images"]:
title = img["title"] if img["title"] else "Image" title = img["title"] if img["title"] else "Image"
filename_img = img["file"] filename_img = img["file"]
# Add media subdirectory prefix if specified # Add media subdirectory prefix if using subdirectory structure
if self.media_subdir: if self.use_subdirectories and self.media_subdir:
image_path = f"../{self.media_subdir}/{filename_img}" image_path = f"../{self.media_subdir}/{filename_img}"
else: else:
image_path = filename_img image_path = filename_img
@@ -483,7 +484,7 @@ class MarkdownGenerator:
path = self.generate_note(individual) path = self.generate_note(individual)
paths.append(path) paths.append(path)
except Exception as e: except Exception as e:
logger.error( logger.exception(
f"Failed to generate note for {individual.get_full_name()}: {e}" f"Failed to generate note for {individual.get_full_name()}: {e}"
) )
+1
View File
@@ -124,6 +124,7 @@ class TestBirthAndDeath:
death = john_doe.get_death_info() death = john_doe.get_death_info()
assert death['date'] == '15 JUN 2020' assert death['date'] == '15 JUN 2020'
assert death['place'] == 'Los Angeles, USA' assert death['place'] == 'Los Angeles, USA'
assert death['year'] == '2020'
def test_get_birth_info_missing(self, sample_gedcom_file): def test_get_birth_info_missing(self, sample_gedcom_file):
"""Test birth info when not present.""" """Test birth info when not present."""
+2 -2
View File
@@ -142,8 +142,8 @@ class TestMetadataFormatting:
file_path = generator.generate_note(john_doe) file_path = generator.generate_note(john_doe)
content = file_path.read_text() content = file_path.read_text()
# Death date extraction gets first 4 chars which is "15 J" from "15 JUN 2020" # Death year is now extracted robustly using regex
assert '[Lived:: 1950-15 J]' in content or '[Lived:: 1950-2020]' in content assert '[Lived:: 1950-2020]' in content
assert '[Born:: 1 JAN 1950]' in content assert '[Born:: 1 JAN 1950]' in content
assert '[Passed away:: 15 JUN 2020]' in content assert '[Passed away:: 15 JUN 2020]' in content