feat: add source parsing and linking #8

Open
jaredhowland wants to merge 9 commits from jaredhowland/add-source-parsing into main
pull from: jaredhowland/add-source-parsing
4 changed files with 986 additions and 150 deletions
Showing only changes of commit 2108325252 - Show all commits

No files matched your search

+213 -144
View File
@@ -5,7 +5,7 @@ This module provides a rich data model for individuals in a family tree,
extracting all relevant information from GEDCOM data. extracting all relevant information from GEDCOM data.
""" """
from typing import List, Dict, Tuple from typing import List, Dict, Tuple, Optional
import logging import logging
import re import re
@@ -15,6 +15,7 @@ import gedcom.tags
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
EVENT_TAGS = {"BIRT", "DEAT", "MARR", "OCCU", "EDUC", "RESI", "BURI"}
class Individual: class Individual:
""" """
@@ -100,44 +101,52 @@ class Individual:
def get_birth_info(self) -> Dict[str, str]: def get_birth_info(self) -> Dict[str, str]:
""" """
Retrieve the person's birth date, place, and year from the underlying GEDCOM element. Retrieve the person's birth date, place, year, and optional coordinates from the underlying GEDCOM element.
Returns: Returns:
dict: A dictionary with keys: dict: A dictionary with keys:
- 'date' (str): Birth date string or '' if unavailable. - 'date' (str): Birth date string or '' if unavailable.
- 'place' (str): Birth place 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. - 'year' (str): Birth year as a string or '' if the year is unknown.
- 'lat' (str): Latitude string if present, else ''
- 'long' (str): Longitude string if present, else ''
""" """
date, place, _sources = self.element.get_birth_data() birth_date, birth_place, lat, long = self._get_event_info("BIRT")
# Fallback to helper methods for year if available
year = self.element.get_birth_year() year = self.element.get_birth_year()
birth_year = str(year) if year != -1 else ""
return { return {
"date": date or "", "date": birth_date or "",
"place": place or "", "place": birth_place or "",
"year": str(year) if year != -1 else "", "year": birth_year,
"lat": lat,
"long": long,
} }
def get_death_info(self) -> Dict[str, str]: def get_death_info(self) -> Dict[str, str]:
""" """
Provide the individual's death date, place, and year. Provide the individual's death date, place, year, and optional coordinates.
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. - year (str): Death year extracted from date, or '' if unavailable.
- lat (str): Latitude if present, else ''
- long (str): Longitude if present, else ''
""" """
date, place, _sources = self.element.get_death_data() death_date, death_place, lat, long = self._get_event_info("DEAT")
year = self._extract_year(death_date)
# Extract year from date string using regex return {
# Handles formats like "1850", "ABT 1850", "1 JAN 1850", "JAN 1850" "date": death_date or "",
year = "" "place": death_place or "",
if date: "year": year,
year_match = re.search(r'\b(\d{4})\b', date) "lat": lat,
if year_match: "long": long,
year = year_match.group(1) }
return {"date": date or "", "place": place or "", "year": year}
def get_gender(self) -> str: def get_gender(self) -> str:
""" """
@@ -165,14 +174,13 @@ class Individual:
Returns: Returns:
children (List[Individual]): A list of Individual instances corresponding to this person's children. children (List[Individual]): A list of Individual instances corresponding to this person's children.
""" """
children = [] return [
for family in self.gedcom.get_families(self.element): Individual(child, self.gedcom)
child_elements = self.gedcom.get_family_members( for family in self.gedcom.get_families(self.element)
for child in self.gedcom.get_family_members(
family, gedcom.tags.GEDCOM_TAG_CHILD family, gedcom.tags.GEDCOM_TAG_CHILD
) )
for child in child_elements: ]
children.append(Individual(child, self.gedcom))
return children
def get_partners(self) -> List["Individual"]: def get_partners(self) -> List["Individual"]:
""" """
@@ -183,14 +191,13 @@ class Individual:
Returns: Returns:
List[Individual]: A list of Individual objects representing the person's partners (excluding the subject). List[Individual]: A list of Individual objects representing the person's partners (excluding the subject).
""" """
partners = [] self_pointer = self.element.get_pointer()
for family in self.gedcom.get_families(self.element): return [
parent_elements = self.gedcom.get_family_members(family, "PARENTS") Individual(parent, self.gedcom)
for parent in parent_elements: for family in self.gedcom.get_families(self.element)
# Don't include self for parent in self.gedcom.get_family_members(family, "PARENTS")
if parent.get_pointer() != self.element.get_pointer(): if parent.get_pointer() != self_pointer
partners.append(Individual(parent, self.gedcom)) ]
return partners
def get_families(self) -> List[Dict]: def get_families(self) -> List[Dict]:
""" """
@@ -206,34 +213,33 @@ class Individual:
families = [] families = []
for family in self.gedcom.get_families(self.element): for family in self.gedcom.get_families(self.element):
# Get partner # Get partner
partners = [] self_pointer = self.element.get_pointer()
for parent in self.gedcom.get_family_members(family, "PARENTS"): partners = [
if parent.get_pointer() != self.element.get_pointer(): Individual(parent, self.gedcom)
partners.append(Individual(parent, self.gedcom)) for parent in self.gedcom.get_family_members(family, "PARENTS")
if parent.get_pointer() != self_pointer
]
# Get marriage info # Get marriage info
marriage_date = "" marriage_date, marriage_place, marriage_lat, marriage_long = (
marriage_place = "" self._get_event_info("MARR", family)
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 # Get children
children = [] children = [
for child in self.gedcom.get_family_members( Individual(child, self.gedcom)
family, gedcom.tags.GEDCOM_TAG_CHILD for child in self.gedcom.get_family_members(
): family, gedcom.tags.GEDCOM_TAG_CHILD
children.append(Individual(child, self.gedcom)) )
]
families.append( families.append(
{ {
"partner": partners[0] if partners else None, "partner": partners[0] if partners else None,
"marriage_date": marriage_date, "marriage_date": marriage_date,
"marriage_place": marriage_place, "marriage_place": marriage_place,
"marriage_lat": marriage_lat,
"marriage_long": marriage_long,
"children": children, "children": children,
} }
) )
@@ -250,49 +256,19 @@ class Individual:
- mother: str (mother's GEDCOM ID) or None - mother: str (mother's GEDCOM ID) or None
""" """
families = [] families = []
self_pointer = self.element.get_pointer()
# Use the python-gedcom method to get parents
# Then find the family record that connects them
parent_elements = self.gedcom.get_parents(self.element)
# Get all family records
for family in self.gedcom.get_root_child_elements(): for family in self.gedcom.get_root_child_elements():
if family.get_tag() == gedcom.tags.GEDCOM_TAG_FAMILY: if family.get_tag() != gedcom.tags.GEDCOM_TAG_FAMILY:
# Check if this person is a child in this family continue
children = self.gedcom.get_family_members(family, gedcom.tags.GEDCOM_TAG_CHILD)
child_pointers = [c.get_pointer() for c in children]
if self.element.get_pointer() in child_pointers: children = self.gedcom.get_family_members(family, gedcom.tags.GEDCOM_TAG_CHILD)
# This person is a child in this family, get the parents if not any(child.get_pointer() == self_pointer for child in children):
parents = self.gedcom.get_family_members(family, "PARENTS") continue
father_id = None parents = self.gedcom.get_family_members(family, "PARENTS")
mother_id = None father_id, mother_id = self._resolve_parent_ids(parents)
families.append({"father": father_id, "mother": mother_id})
for parent in parents:
# Determine gender to assign father/mother
# Check gender tag
gender = None
for child_elem in parent.get_child_elements():
if child_elem.get_tag() == "SEX":
gender = child_elem.get_value()
break
if gender == "M":
father_id = parent.get_pointer()
elif gender == "F":
mother_id = parent.get_pointer()
else:
# If no gender specified, assign to father if empty, else mother
if not father_id:
father_id = parent.get_pointer()
elif not mother_id:
mother_id = parent.get_pointer()
families.append({
"father": father_id,
"mother": mother_id,
})
return families return families
@@ -313,25 +289,141 @@ class Individual:
tag = child.get_tag() tag = child.get_tag()
# Common event tags # Common event tags
if tag in ["BIRT", "DEAT", "MARR", "OCCU", "EDUC", "RESI", "BURI"]: if tag in EVENT_TAGS:
event = { event = {
"type": tag, "type": tag,
"date": "", "date": "",
"place": "", "place": "",
"details": child.get_value() or "", "details": child.get_value() or "",
"lat": "",
"long": "",
} }
# Extract date and place # Extract date, place, and optional coordinates from any event node.
for subchild in child.get_child_elements(): event["date"], event["place"], event["lat"], event["long"] = (
if subchild.get_tag() == "DATE": self._extract_date_place_and_coords(child)
event["date"] = subchild.get_value() )
elif subchild.get_tag() == "PLAC":
event["place"] = subchild.get_value()
events.append(event) events.append(event)
return events return events
def _extract_year(self, value: str) -> str:
"""Extract the first four-digit year from a string, if present."""
if not value:
return ""
year_match = re.search(r"\b(\d{4})\b", value)
return year_match.group(1) if year_match else ""
def _resolve_parent_ids(self, parents) -> Tuple[Optional[str], Optional[str]]:
"""Resolve father/mother pointers from a list of parent elements."""
father_id = None
mother_id = None
for parent in parents:
pointer = parent.get_pointer()
gender = self._get_element_gender(parent)
if gender == "M":
father_id = pointer
elif gender == "F":
mother_id = pointer
elif not father_id:
father_id = pointer
elif not mother_id:
mother_id = pointer
return father_id, mother_id
def _get_element_gender(self, element) -> str:
"""Get gender value from a GEDCOM element's SEX child tag."""
for child in element.get_child_elements():
if child.get_tag() == "SEX":
return child.get_value() or ""
return ""
def _get_event_info(
self, event_tag: str, parent_node=None
) -> Tuple[str, str, str, str]:
"""
Find the first child event by tag and extract (date, place, lat, long).
Parameters:
event_tag (str): GEDCOM event tag to search for (for example "BIRT").
parent_node: Optional node whose children are searched. Defaults to
the wrapped individual element.
"""
node = parent_node if parent_node is not None else self.element
for child in node.get_child_elements():
if child.get_tag() == event_tag:
return self._extract_date_place_and_coords(child)
return "", "", "", ""
def _extract_date_place_and_coords(self, event_node) -> Tuple[str, str, str, str]:
"""
Extract DATE, PLAC, and PLAC coordinates from an event-like GEDCOM node.
Returns:
copilot-pull-request-reviewer[bot] commented 2026-04-17 21:49:54 +02:00 (Migrated from github.com)
Review

Pointer detection for SOUR @X@ should match the stricter pattern used elsewhere (startswith('@') and endswith('@')). Using only startswith('@') can misclassify inline values that happen to begin with '@', and can lead to failed lookups in the element dictionary.

            if src_ref and src_ref.startswith("@") and src_ref.endswith("@"):
Pointer detection for `SOUR @X@` should match the stricter pattern used elsewhere (`startswith('@') and endswith('@')`). Using only `startswith('@')` can misclassify inline values that happen to begin with '@', and can lead to failed lookups in the element dictionary. ```suggestion if src_ref and src_ref.startswith("@") and src_ref.endswith("@"): ```
Tuple[str, str, str, str]: (date, place, latitude, longitude), with
missing values returned as empty strings.
"""
date_value = ""
place_value = ""
lati = ""
longi = ""
for child in event_node.get_child_elements():
if child.get_tag() == "DATE":
date_value = child.get_value() or ""
elif child.get_tag() == "PLAC":
place_value = child.get_value() or ""
lati, longi = self._extract_lat_long_from_plac(child)
return date_value, place_value, lati, longi
def _extract_lat_long_from_plac(self, plac_node) -> Tuple[str, str]:
"""
Extract latitude and longitude values from a PLAC node if present.
The function looks for a MAP child beneath the PLAC node and then for
LATI and LONG tags. It also accepts LATI/LONG directly under PLAC.
Returns a tuple (latitude, longitude) where missing values are empty strings.
"""
return self._extract_lat_long_from_node(plac_node)
def _extract_lat_long_from_node(self, node) -> Tuple[str, str]:
"""
Recursively extract LATI/LONG values from any GEDCOM node subtree.
This supports coordinates directly under PLAC, under MAP, or in deeper
custom nesting used by some exports.
"""
lati = ""
longi = ""
for child in node.get_child_elements():
tag = child.get_tag()
if tag == "LATI" and not lati:
lati = child.get_value() or ""
elif tag == "LONG" and not longi:
longi = child.get_value() or ""
if lati and longi:
return lati, longi
nested_lati, nested_longi = self._extract_lat_long_from_node(child)
if nested_lati and not lati:
lati = nested_lati
if nested_longi and not longi:
longi = nested_longi
if lati and longi:
return lati, longi
return lati, longi
def get_images(self) -> List[Dict[str, str]]: def get_images(self) -> List[Dict[str, str]]:
""" """
Return image/media entries referenced by this individual's OBJE nodes. Return image/media entries referenced by this individual's OBJE nodes.
@@ -345,24 +437,9 @@ class Individual:
for child in self.element.get_child_elements(): for child in self.element.get_child_elements():
if child.get_tag() == "OBJE": if child.get_tag() == "OBJE":
# OBJE can have a reference or inline data image_info = self._get_obje_info(child.get_value())
reference = child.get_value() if image_info:
if reference and reference.startswith("@"): images.append(image_info)
# Resolve the reference to get actual file info
obje_element = self.gedcom.get_element_dictionary().get(reference)
if obje_element:
image_info = {"file": "", "title": "", "format": ""}
for obje_child in obje_element.get_child_elements():
if obje_child.get_tag() == "FILE":
image_info["file"] = obje_child.get_value() or ""
elif obje_child.get_tag() == "TITL":
image_info["title"] = obje_child.get_value() or ""
elif obje_child.get_tag() == "FORM":
image_info["format"] = obje_child.get_value() or ""
if image_info["file"]:
images.append(image_info)
return images return images
@@ -467,37 +544,9 @@ class Individual:
text += "\n" + (cont.get_value() or "") text += "\n" + (cont.get_value() or "")
section_data["text"] = text section_data["text"] = text
elif sts_child.get_tag() == "OBJE": elif sts_child.get_tag() == "OBJE":
# Resolve image reference image_info = self._get_obje_info(sts_child.get_value())
img_ref = sts_child.get_value() if image_info:
if img_ref and img_ref.startswith("@"): section_data["images"].append(image_info)
obje_element = self.gedcom.get_element_dictionary().get(
img_ref
)
if obje_element:
image_info = {
"file": "",
"title": "",
"format": "",
}
for (
obje_child
) in obje_element.get_child_elements():
if obje_child.get_tag() == "FILE":
image_info["file"] = (
obje_child.get_value() or ""
)
elif obje_child.get_tag() == "TITL":
image_info["title"] = (
obje_child.get_value() or ""
)
elif obje_child.get_tag() == "FORM":
image_info["format"] = (
obje_child.get_value() or ""
)
if image_info["file"]:
section_data["images"].append(
image_info
)
if section_data["subtitle"] or section_data["text"]: if section_data["subtitle"] or section_data["text"]:
story["sections"].append(section_data) story["sections"].append(section_data)
@@ -507,6 +556,26 @@ class Individual:
return stories return stories
def _get_obje_info(self, reference: str) -> Optional[Dict[str, str]]:
"""Resolve an OBJE reference and return file metadata, or None if unavailable."""
if not reference or not reference.startswith("@"):
return None
obje_element = self.gedcom.get_element_dictionary().get(reference)
if not obje_element:
return None
image_info = {"file": "", "title": "", "format": ""}
for obje_child in obje_element.get_child_elements():
if obje_child.get_tag() == "FILE":
image_info["file"] = obje_child.get_value() or ""
elif obje_child.get_tag() == "TITL":
image_info["title"] = obje_child.get_value() or ""
elif obje_child.get_tag() == "FORM":
image_info["format"] = obje_child.get_value() or ""
return image_info if image_info["file"] else None
def get_attributes(self) -> Dict[str, str]: def get_attributes(self) -> Dict[str, str]:
""" """
Collect physical attributes from the underlying GEDCOM individual element. Collect physical attributes from the underlying GEDCOM individual element.
+29
View File
@@ -57,6 +57,17 @@ class MarkdownGenerator:
self.generated_stories = {} # Track generated story files self.generated_stories = {} # Track generated story files
self.filename_map = {} # Map from individual ID to actual filename used self.filename_map = {} # Map from individual ID to actual filename used
def _coordinate_values(
self, data: dict, lat_key: str = "lat", long_key: str = "long"
) -> List[str]:
"""Return non-empty coordinate values from a mapping in latitude/longitude order."""
coords = []
if data.get(lat_key):
coords.append(data.get(lat_key))
if data.get(long_key):
coords.append(data.get(long_key))
return coords
def _get_unique_filename(self, base_name: str, individual_id: str) -> str: def _get_unique_filename(self, base_name: str, individual_id: str) -> str:
""" """
Get a unique filename for an individual, handling duplicates by adding (1), (2), etc. Get a unique filename for an individual, handling duplicates by adding (1), (2), etc.
@@ -139,12 +150,20 @@ class MarkdownGenerator:
f.write(f"Born: {birth['date']}\n") f.write(f"Born: {birth['date']}\n")
if birth["place"]: if birth["place"]:
f.write(f"Place of birth: {birth['place']}\n") f.write(f"Place of birth: {birth['place']}\n")
# Birth coordinates if available
birth_coords = self._coordinate_values(birth)
if birth_coords:
f.write(f"Birth coordinates: {', '.join(birth_coords)}\n")
# Death details # Death details
if death["date"]: if death["date"]:
f.write(f"Passed away: {death['date']}\n") f.write(f"Passed away: {death['date']}\n")
if death["place"]: if death["place"]:
f.write(f"Place of death: {death['place']}\n") f.write(f"Place of death: {death['place']}\n")
# Death coordinates if available
death_coords = self._coordinate_values(death)
if death_coords:
f.write(f"Death coordinates: {', '.join(death_coords)}\n")
# Physical attributes # Physical attributes
attrs = individual.get_attributes() attrs = individual.get_attributes()
@@ -200,6 +219,10 @@ class MarkdownGenerator:
f.write(f"- **Date**: {event['date']}\n") f.write(f"- **Date**: {event['date']}\n")
if event["place"]: if event["place"]:
f.write(f"- **Place**: {event['place']}\n") f.write(f"- **Place**: {event['place']}\n")
# If coordinates were extracted, write them below the place line
coords = self._coordinate_values(event)
if coords:
f.write(f"- **Coordinates**: {', '.join(coords)}\n")
if event["details"]: if event["details"]:
f.write(f"- **Details**: {event['details']}\n") f.write(f"- **Details**: {event['details']}\n")
@@ -238,6 +261,12 @@ class MarkdownGenerator:
f.write(f"* Marriage date: {family['marriage_date']}\n") f.write(f"* Marriage date: {family['marriage_date']}\n")
if family["marriage_place"]: if family["marriage_place"]:
f.write(f"* Marriage place: {family['marriage_place']}\n") f.write(f"* Marriage place: {family['marriage_place']}\n")
# Marriage coordinates if available on family record
mcoords = self._coordinate_values(
family, "marriage_lat", "marriage_long"
)
if mcoords:
f.write(f"* Marriage coordinates: {', '.join(mcoords)}\n")
# Write children if they exist # Write children if they exist
if family["children"]: if family["children"]:
4
+716 -6
View File
@@ -17,6 +17,26 @@ from gedcom_parser import GedcomParser
from individual import Individual from individual import Individual
class TestIndividualBasicInfo:
"""Tests for basic individual information extraction."""
@pytest.fixture
def john_doe(self, sample_gedcom_file):
"""Get the John Doe individual from sample GEDCOM."""
parser = GedcomParser(sample_gedcom_file)
individuals = parser.get_individuals()
"""
Tests for the Individual data model.
This module tests individual person data extraction including:
- Names and IDs
- Birth and death information
- Events and attributes
- Family relationships
- Images and notes
- Custom story tags
"""
class TestIndividualBasicInfo: class TestIndividualBasicInfo:
"""Tests for basic individual information extraction.""" """Tests for basic individual information extraction."""
@@ -205,15 +225,134 @@ class TestEvents:
individuals = parser.get_individuals() individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser) person = Individual(individuals[0], parser.parser)
events = person.get_events()
event_types = [e["type"] for e in events]
assert "BIRT" in event_types
assert "DEAT" in event_types
assert "OCCU" in event_types
assert "EDUC" in event_types
assert "RESI" in event_types
assert "BURI" in event_types
def test_get_events_with_coords(self, temp_dir):
"""Test extraction of place coordinates from MAP -> LATI/LONG under PLAC."""
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 RESI
2 PLAC Newplace
3 MAP
4 LATI 40.7128
4 LONG -74.0060
0 TRLR
"""
temp_file = temp_dir / "coords.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
events = person.get_events()
resi = [e for e in events if e["type"] == "RESI"][0]
assert resi["place"] == "Newplace"
assert resi["lat"] == "40.7128"
assert resi["long"] == "-74.0060"
def test_get_events_coords_direct_children(self, temp_dir):
"""Test PLAC with LATI/LONG directly under PLAC (not within MAP)."""
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 RESI
2 PLAC Somewhere
3 LATI 12.34
3 LONG 56.78
0 TRLR
"""
temp_file = temp_dir / "coords_direct.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
events = person.get_events()
resi = [e for e in events if e["type"] == "RESI"][0]
assert resi["place"] == "Somewhere"
assert resi["lat"] == "12.34"
assert resi["long"] == "56.78"
def test_get_events_coords_missing_lat(self, temp_dir):
"""Test MAP present with only LONG value; LATI missing."""
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 RESI
2 PLAC Coastal
3 MAP
4 LONG -3.1415
0 TRLR
"""
temp_file = temp_dir / "coords_missing_lat.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
events = person.get_events()
resi = [e for e in events if e["type"] == "RESI"][0]
assert resi["place"] == "Coastal"
assert resi["lat"] == ""
assert resi["long"] == "-3.1415"
def test_get_events_coords_nested_structure(self, temp_dir):
"""Test LATI/LONG extraction from nested nodes under PLAC."""
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 RESI
2 PLAC Deepplace
3 MAP
4 META
5 LATI 48.8566
5 LONG 2.3522
0 TRLR
"""
temp_file = temp_dir / "coords_nested.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
events = person.get_events() events = person.get_events()
event_types = [e['type'] for e in events] event_types = [e['type'] for e in events]
assert 'BIRT' in event_types assert resi['place'] == 'Deepplace'
assert 'DEAT' in event_types assert resi['lat'] == '48.8566'
assert 'OCCU' in event_types assert resi['long'] == '2.3522'
assert 'EDUC' in event_types
assert 'RESI' in event_types
assert 'BURI' in event_types
class TestFamilyRelationships: class TestFamilyRelationships:
@@ -424,6 +563,577 @@ class TestStories:
assert len(stories) == 0 assert len(stories) == 0
class TestAttributes:
"""Tests for physical attribute extraction."""
def test_get_attributes(self, temp_dir, sample_gedcom_with_attributes):
"""Test physical attribute extraction."""
temp_file = temp_dir / "attributes.ged"
temp_file.write_text(sample_gedcom_with_attributes, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
attrs = person.get_attributes()
assert attrs["eyes"] == "Blue"
assert attrs["hair"] == "Blonde"
assert attrs["heig"] == "170 cm"
def test_get_attributes_empty(self, temp_dir):
"""Test attribute extraction when no attributes are present."""
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/
0 TRLR
"""
temp_file = temp_dir / "no_attrs.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
attrs = person.get_attributes()
assert len(attrs) == 0
return Individual(john[0], parser.parser)
def test_get_id(self, john_doe):
"""Test ID extraction without @ symbols."""
id_value = john_doe.get_id()
assert id_value == "I1"
assert "@" not in id_value
def test_get_names(self, john_doe):
"""Test name extraction as tuple."""
first, last = john_doe.get_names()
assert first == "John"
assert last == "Doe"
def test_get_full_name(self, john_doe):
"""Test full name formatting."""
full_name = john_doe.get_full_name()
assert full_name == "John Doe"
def test_get_file_name_with_birth_year(self, john_doe):
"""Test filename generation with birth year."""
filename = john_doe.get_file_name()
assert "Doe John" in filename
assert "1950" in filename
def test_get_file_name_without_birth_year(self, sample_gedcom_file):
"""Test filename generation without birth year."""
# Create a person without birth year
gedcom_content = """0 HEAD
1 SOUR TestApp
1 GEDC
2 VERS 5.5.1
1 CHAR UTF-8
0 @I1@ INDI
1 NAME NoYear /Person/
1 SEX M
0 TRLR
"""
temp_file = sample_gedcom_file.parent / "no_year.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
filename = person.get_file_name()
assert "Person NoYear" in filename # Preserves original GEDCOM capitalization
# Should not contain a year
assert not any(char.isdigit() for char in filename)
def test_get_gender(self, john_doe):
"""Test gender extraction."""
assert john_doe.get_gender() == "M"
def test_get_gender_default_unknown(self, sample_gedcom_file):
"""Test that missing gender defaults to 'U'."""
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/
0 TRLR
"""
temp_file = sample_gedcom_file.parent / "no_gender.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
assert person.get_gender() == "U"
class TestBirthAndDeath:
"""Tests for birth and death information extraction."""
@pytest.fixture
def john_doe(self, sample_gedcom_file):
"""Get the John Doe individual from sample GEDCOM."""
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.parser)
def test_get_birth_info(self, john_doe):
"""Test birth information extraction."""
birth = john_doe.get_birth_info()
assert birth["date"] == "1 JAN 1950"
assert birth["place"] == "New York, USA"
assert birth["year"] == "1950"
def test_get_death_info(self, john_doe):
"""Test death information extraction."""
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."""
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/
0 TRLR
"""
temp_file = sample_gedcom_file.parent / "no_birth.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
birth = person.get_birth_info()
assert birth["date"] == ""
assert birth["place"] == ""
assert birth["year"] == ""
class TestEvents:
"""Tests for event extraction."""
@pytest.fixture
def john_doe(self, sample_gedcom_file):
"""Get the John Doe individual from sample GEDCOM."""
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.parser)
def test_get_events(self, john_doe):
"""Test event extraction."""
events = john_doe.get_events()
# Should include BIRT, DEAT, and OCCU
assert len(events) >= 3
# Find occupation event
occu_events = [e for e in events if e["type"] == "OCCU"]
assert len(occu_events) >= 1
occu = occu_events[0]
assert occu["details"] == "Engineer"
assert occu["date"] == "1975"
def test_get_events_with_all_types(self, temp_dir):
"""Test extraction of various event types."""
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 1980
1 DEAT
2 DATE 2050
1 OCCU Teacher
2 DATE 2000
1 EDUC University
2 DATE 1998
1 RESI
2 PLAC New York
1 BURI
2 PLAC Cemetery
0 TRLR
"""
temp_file = temp_dir / "events.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
events = person.get_events()
event_types = [e["type"] for e in events]
assert "BIRT" in event_types
assert "DEAT" in event_types
assert "OCCU" in event_types
assert "EDUC" in event_types
assert "RESI" in event_types
assert "BURI" in event_types
def test_get_events_with_coords(self, temp_dir):
"""Test extraction of place coordinates from MAP -> LATI/LONG under PLAC."""
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 RESI
2 PLAC Newplace
3 MAP
4 LATI 40.7128
4 LONG -74.0060
0 TRLR
"""
temp_file = temp_dir / "coords.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
events = person.get_events()
resi = [e for e in events if e["type"] == "RESI"][0]
assert resi["place"] == "Newplace"
assert resi["lat"] == "40.7128"
assert resi["long"] == "-74.0060"
def test_get_events_coords_direct_children(self, temp_dir):
"""Test PLAC with LATI/LONG directly under PLAC (not within MAP)."""
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 RESI
2 PLAC Somewhere
3 LATI 12.34
3 LONG 56.78
0 TRLR
"""
temp_file = temp_dir / "coords_direct.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
events = person.get_events()
resi = [e for e in events if e["type"] == "RESI"][0]
assert resi["place"] == "Somewhere"
assert resi["lat"] == "12.34"
assert resi["long"] == "56.78"
def test_get_events_coords_missing_lat(self, temp_dir):
"""Test MAP present with only LONG value; LATI missing."""
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 RESI
2 PLAC Coastal
3 MAP
4 LONG -3.1415
0 TRLR
"""
temp_file = temp_dir / "coords_missing_lat.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
events = person.get_events()
resi = [e for e in events if e["type"] == "RESI"][0]
assert resi["place"] == "Coastal"
assert resi["lat"] == ""
assert resi["long"] == "-3.1415"
def test_get_events_coords_nested_structure(self, temp_dir):
"""Test LATI/LONG extraction from nested nodes under PLAC."""
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 RESI
2 PLAC Deepplace
3 MAP
4 META
5 LATI 48.8566
5 LONG 2.3522
0 TRLR
"""
temp_file = temp_dir / "coords_nested.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
events = person.get_events()
resi = [e for e in events if e["type"] == "RESI"][0]
assert resi["place"] == "Deepplace"
assert resi["lat"] == "48.8566"
assert resi["long"] == "2.3522"
class TestFamilyRelationships:
"""Tests for family relationship extraction."""
@pytest.fixture
def parsed_gedcom(self, sample_gedcom_file):
"""Get parsed GEDCOM with family relationships."""
return GedcomParser(sample_gedcom_file)
def test_get_parents(self, parsed_gedcom):
"""Test parent extraction for a child."""
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.parser)
parents = alice_obj.get_parents()
assert len(parents) == 2
parent_names = [p.get_full_name() for p in parents]
assert any("John" in name for name in parent_names)
assert any("Jane" in name for name in parent_names)
def test_get_children(self, parsed_gedcom):
"""Test children extraction for a parent."""
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.parser)
children = john_obj.get_children()
assert len(children) >= 1
child_names = [c.get_full_name() for c in children]
assert any("Alice" in name for name in child_names)
def test_get_partners(self, parsed_gedcom):
"""Test partner/spouse extraction."""
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.parser)
partners = john_obj.get_partners()
assert len(partners) >= 1
partner_names = [p.get_full_name() for p in partners]
assert any("Jane" in name for name in partner_names)
def test_get_families(self, parsed_gedcom):
"""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.parser)
families = john_obj.get_families()
assert len(families) >= 1
family = families[0]
assert family["partner"] is not None
assert "Jane" in family["partner"].get_full_name()
assert family["marriage_date"] == "20 JUN 1975"
assert family["marriage_place"] == "New York, USA"
assert len(family["children"]) >= 1
def test_get_families_marriage_coords_not_leaked(self, temp_dir):
"""Ensure marriage coordinates do not leak between multiple families."""
gedcom_content = """0 HEAD
1 SOUR TestApp
1 GEDC
2 VERS 5.5.1
1 CHAR UTF-8
0 @I1@ INDI
1 NAME Parent /One/
1 SEX M
1 FAMS @F1@
1 FAMS @F2@
0 @I2@ INDI
1 NAME Partner /One/
1 SEX F
1 FAMS @F1@
0 @I3@ INDI
1 NAME Partner /Two/
1 SEX F
1 FAMS @F2@
0 @F1@ FAM
1 HUSB @I1@
1 WIFE @I2@
1 MARR
2 DATE 1 JAN 2000
2 PLAC Place One
3 MAP
4 LATI 11.11
4 LONG 22.22
0 @F2@ FAM
1 HUSB @I1@
1 WIFE @I3@
1 MARR
2 DATE 1 JAN 2010
2 PLAC Place Two
0 TRLR
"""
temp_file = temp_dir / "family_coords_leak.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
parent = [ind for ind in individuals if ind.get_pointer() == "@I1@"][0]
parent_obj = Individual(parent, parser.parser)
families = parent_obj.get_families()
assert len(families) == 2
family_one = [f for f in families if f["marriage_place"] == "Place One"][0]
family_two = [f for f in families if f["marriage_place"] == "Place Two"][0]
assert family_one["marriage_lat"] == "11.11"
assert family_one["marriage_long"] == "22.22"
assert family_two["marriage_lat"] == ""
assert family_two["marriage_long"] == ""
class TestImagesAndMedia:
"""Tests for image and media extraction."""
def test_get_images(self, sample_gedcom_file):
"""Test image extraction."""
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.parser)
notes = john_obj.get_notes()
assert len(notes) >= 1
assert 'test note' in notes[0].lower()
assert 'great engineer' in notes[0].lower()
def test_get_notes_inline(self, temp_dir):
"""Test inline note extraction."""
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 NOTE This is an inline note.
2 CONT It has multiple lines.
0 TRLR
"""
temp_file = temp_dir / "inline_notes.ged"
temp_file.write_text(gedcom_content, encoding='utf-8')
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
notes = person.get_notes()
assert len(notes) >= 1
assert 'inline note' in notes[0].lower()
assert 'multiple lines' in notes[0].lower()
def test_get_notes_empty(self, temp_dir):
"""Test note extraction when no notes are present."""
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/
0 TRLR
"""
temp_file = temp_dir / "no_notes.ged"
temp_file.write_text(gedcom_content, encoding='utf-8')
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
notes = person.get_notes()
assert len(notes) == 0
class TestStories:
"""Tests for custom story tag extraction."""
def test_get_stories(self, temp_dir, sample_gedcom_with_stories):
"""Test story extraction from custom _STO tags."""
temp_file = temp_dir / "stories.ged"
temp_file.write_text(sample_gedcom_with_stories, encoding='utf-8')
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
stories = person.get_stories()
# Story extraction is complex and depends on exact GEDCOM structure
# The test data may not match the exact format the code expects
# We just verify the method runs without error
assert isinstance(stories, list)
def test_get_stories_empty(self, temp_dir):
"""Test story extraction when no stories are present."""
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/
0 TRLR
"""
temp_file = temp_dir / "no_stories.ged"
temp_file.write_text(gedcom_content, encoding="utf-8")
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
stories = person.get_stories()
assert len(stories) == 0
class TestAttributes: class TestAttributes:
"""Tests for physical attribute extraction.""" """Tests for physical attribute extraction."""
+28
View File
@@ -236,6 +236,34 @@ class TestEventFormatting:
# Birth should not appear as a separate event # Birth should not appear as a separate event
assert 'Birth' not in life_events_section or 'Marriage' in content assert 'Birth' not in life_events_section or 'Marriage' in content
def test_coordinates_written(self, generator, temp_dir):
"""Ensure that coordinates extracted from PLAC/MAP are written into notes."""
gedcom_content = """0 HEAD
1 SOUR TestApp
1 GEDC
2 VERS 5.5.1
1 CHAR UTF-8
0 @I1@ INDI
1 NAME Locator /Person/
1 RESI
2 PLAC Mapville
3 MAP
4 LATI 51.5074
4 LONG -0.1278
0 TRLR
"""
temp_file = temp_dir / "coords_note.ged"
temp_file.write_text(gedcom_content, encoding='utf-8')
parser = GedcomParser(temp_file)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
file_path = generator.generate_note(person)
content = file_path.read_text()
assert '- **Coordinates**: 51.5074, -0.1278' in content
class TestImageHandling: class TestImageHandling:
"""Tests for image embedding in notes.""" """Tests for image embedding in notes."""