From 21083252524afcc342e54a1d0797aaf62e4eae05 Mon Sep 17 00:00:00 2001 From: Jared Howland Date: Thu, 16 Apr 2026 22:16:34 -0600 Subject: [PATCH 1/8] feat: extract place lat/long coordinates * Show coordinates for any place that has them * Add tests for coordinates --- src/individual.py | 375 +++++++++------- src/markdown_generator.py | 53 ++- tests/test_individual.py | 722 ++++++++++++++++++++++++++++++- tests/test_markdown_generator.py | 28 ++ 4 files changed, 1007 insertions(+), 171 deletions(-) diff --git a/src/individual.py b/src/individual.py index d37c2dd..3d61b46 100644 --- a/src/individual.py +++ b/src/individual.py @@ -5,7 +5,7 @@ This module provides a rich data model for individuals in a family tree, extracting all relevant information from GEDCOM data. """ -from typing import List, Dict, Tuple +from typing import List, Dict, Tuple, Optional import logging import re @@ -15,6 +15,7 @@ import gedcom.tags logger = logging.getLogger(__name__) +EVENT_TAGS = {"BIRT", "DEAT", "MARR", "OCCU", "EDUC", "RESI", "BURI"} class Individual: """ @@ -100,49 +101,57 @@ class Individual: 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: 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. + - '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() + birth_year = str(year) if year != -1 else "" return { - "date": date or "", - "place": place or "", - "year": str(year) if year != -1 else "", + "date": birth_date or "", + "place": birth_place or "", + "year": birth_year, + "lat": lat, + "long": long, } 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: 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. + - 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 - # 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} + return { + "date": death_date or "", + "place": death_place or "", + "year": year, + "lat": lat, + "long": long, + } def get_gender(self) -> str: """ Return the person's gender code. - + Returns: str: `'M'` for male, `'F'` for female, `'U'` if unspecified or unknown. """ @@ -165,14 +174,13 @@ class Individual: Returns: children (List[Individual]): A list of Individual instances corresponding to this person's children. """ - children = [] - for family in self.gedcom.get_families(self.element): - child_elements = self.gedcom.get_family_members( + return [ + Individual(child, self.gedcom) + for family in self.gedcom.get_families(self.element) + for child in self.gedcom.get_family_members( 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"]: """ @@ -183,14 +191,13 @@ class Individual: Returns: List[Individual]: A list of Individual objects representing the person's partners (excluding the subject). """ - partners = [] - for family in self.gedcom.get_families(self.element): - parent_elements = self.gedcom.get_family_members(family, "PARENTS") - for parent in parent_elements: - # Don't include self - if parent.get_pointer() != self.element.get_pointer(): - partners.append(Individual(parent, self.gedcom)) - return partners + self_pointer = self.element.get_pointer() + return [ + Individual(parent, self.gedcom) + for family in self.gedcom.get_families(self.element) + for parent in self.gedcom.get_family_members(family, "PARENTS") + if parent.get_pointer() != self_pointer + ] def get_families(self) -> List[Dict]: """ @@ -206,34 +213,33 @@ class Individual: families = [] for family in self.gedcom.get_families(self.element): # Get partner - partners = [] - for parent in self.gedcom.get_family_members(family, "PARENTS"): - if parent.get_pointer() != self.element.get_pointer(): - partners.append(Individual(parent, self.gedcom)) + self_pointer = self.element.get_pointer() + partners = [ + Individual(parent, self.gedcom) + for parent in self.gedcom.get_family_members(family, "PARENTS") + if parent.get_pointer() != self_pointer + ] # Get marriage info - marriage_date = "" - marriage_place = "" - for child in family.get_child_elements(): - if child.get_tag() == "MARR": - for subchild in child.get_child_elements(): - if subchild.get_tag() == "DATE": - marriage_date = subchild.get_value() - elif subchild.get_tag() == "PLAC": - marriage_place = subchild.get_value() + marriage_date, marriage_place, marriage_lat, marriage_long = ( + self._get_event_info("MARR", family) + ) # Get children - children = [] - for child in self.gedcom.get_family_members( - family, gedcom.tags.GEDCOM_TAG_CHILD - ): - children.append(Individual(child, self.gedcom)) + children = [ + Individual(child, self.gedcom) + for child in self.gedcom.get_family_members( + family, gedcom.tags.GEDCOM_TAG_CHILD + ) + ] families.append( { "partner": partners[0] if partners else None, "marriage_date": marriage_date, "marriage_place": marriage_place, + "marriage_lat": marriage_lat, + "marriage_long": marriage_long, "children": children, } ) @@ -250,56 +256,26 @@ class Individual: - mother: str (mother's GEDCOM ID) or None """ 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(): - if family.get_tag() == gedcom.tags.GEDCOM_TAG_FAMILY: - # Check if this person is a child in this family - children = self.gedcom.get_family_members(family, gedcom.tags.GEDCOM_TAG_CHILD) - child_pointers = [c.get_pointer() for c in children] + if family.get_tag() != gedcom.tags.GEDCOM_TAG_FAMILY: + continue - if self.element.get_pointer() in child_pointers: - # This person is a child in this family, get the parents - parents = self.gedcom.get_family_members(family, "PARENTS") + children = self.gedcom.get_family_members(family, gedcom.tags.GEDCOM_TAG_CHILD) + if not any(child.get_pointer() == self_pointer for child in children): + continue - father_id = None - mother_id = None - - 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, - }) + parents = self.gedcom.get_family_members(family, "PARENTS") + father_id, mother_id = self._resolve_parent_ids(parents) + families.append({"father": father_id, "mother": mother_id}) return families def get_events(self) -> List[Dict[str, str]]: """ Collects the individual's life events found on the GEDCOM element. - + Returns: List[dict]: Each dictionary represents an event with keys: - 'type' (str): GEDCOM event tag (e.g., 'BIRT', 'DEAT', 'MARR', 'OCCU', 'EDUC', 'RESI', 'BURI'). @@ -313,31 +289,147 @@ class Individual: tag = child.get_tag() # Common event tags - if tag in ["BIRT", "DEAT", "MARR", "OCCU", "EDUC", "RESI", "BURI"]: + if tag in EVENT_TAGS: event = { "type": tag, "date": "", "place": "", "details": child.get_value() or "", + "lat": "", + "long": "", } - # Extract date and place - for subchild in child.get_child_elements(): - if subchild.get_tag() == "DATE": - event["date"] = subchild.get_value() - elif subchild.get_tag() == "PLAC": - event["place"] = subchild.get_value() + # Extract date, place, and optional coordinates from any event node. + event["date"], event["place"], event["lat"], event["long"] = ( + self._extract_date_place_and_coords(child) + ) events.append(event) 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: + 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]]: """ Return image/media entries referenced by this individual's OBJE nodes. Resolves OBJE references to their records and extracts FILE, TITL, and FORM values; entries without a FILE value are omitted. - + Returns: List[Dict[str, str]]: A list of dictionaries each containing the keys 'file', 'title', and 'format'. The 'file' value is non-empty for all returned entries. """ @@ -345,33 +437,18 @@ class Individual: for child in self.element.get_child_elements(): if child.get_tag() == "OBJE": - # OBJE can have a reference or inline data - reference = child.get_value() - if reference and reference.startswith("@"): - # 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) + image_info = self._get_obje_info(child.get_value()) + if image_info: + images.append(image_info) return images def get_notes(self) -> List[str]: """ Return the person's notes with inline continuations and referenced NOTE records resolved. - + This resolves NOTE cross-references (values like `@X@`), appends `CONT`/`CONC` continuations, trims whitespace, and omits empty or unresolved references. - + Returns: List[str]: Note texts with continuations and referenced NOTE content merged; empty or unresolved notes are omitted. """ @@ -407,7 +484,7 @@ class Individual: def get_stories(self) -> List[Dict]: """ Extract story and narrative records referenced by custom `_STO` tags for this individual. - + Scans `_STO` child entries, resolves referenced story elements, and assembles structured story data. Each story dictionary contains: - `title` (str): story title (or empty string) @@ -419,7 +496,7 @@ class Individual: - `file` (str): file path or name (required for inclusion) - `title` (str): image title (or empty string) - `format` (str): image format (or empty string) - + Returns: List[Dict]: list of story dictionaries; empty list if no stories are found. """ @@ -467,37 +544,9 @@ class Individual: text += "\n" + (cont.get_value() or "") section_data["text"] = text elif sts_child.get_tag() == "OBJE": - # Resolve image reference - img_ref = sts_child.get_value() - if img_ref and img_ref.startswith("@"): - 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 - ) + image_info = self._get_obje_info(sts_child.get_value()) + if image_info: + section_data["images"].append(image_info) if section_data["subtitle"] or section_data["text"]: story["sections"].append(section_data) @@ -507,10 +556,30 @@ class Individual: 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]: """ Collect physical attributes from the underlying GEDCOM individual element. - + Returns: Dict[str, str]: A dictionary with keys 'eyes', 'hair', and 'heig' (lowercase). Each value is the corresponding attribute string or an empty string if absent. @@ -524,4 +593,4 @@ class Individual: if tag in ["EYES", "HAIR", "HEIG"]: attributes[tag.lower()] = child.get_value() or "" - return attributes \ No newline at end of file + return attributes diff --git a/src/markdown_generator.py b/src/markdown_generator.py index 7c4cb91..fba321d 100644 --- a/src/markdown_generator.py +++ b/src/markdown_generator.py @@ -57,6 +57,17 @@ class MarkdownGenerator: self.generated_stories = {} # Track generated story files 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: """ 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") if birth["place"]: 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 if death["date"]: f.write(f"Passed away: {death['date']}\n") if death["place"]: 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 attrs = individual.get_attributes() @@ -167,9 +186,9 @@ class MarkdownGenerator: def _write_events(self, f, individual: Individual): """ Write the "Life Events" section for an individual into the open file. - + Writes a "Life Events" header and a subsection for each event other than birth or death. For each event, emits Date, Place, and Details lines when those values are present. Maps common GEDCOM-like event codes to readable names (e.g., 'MARR' -> Marriage, 'OCCU' -> Occupation, 'EDUC' -> Education, 'RESI' -> Residence, 'BURI' -> Burial). If the individual has no other events, nothing is written. - + Parameters: f: A writable text file object positioned where the section should be written. individual (Individual): An object providing event data via get_events(), where each event is a dict containing at least 'type', 'date', 'place', and 'details'. @@ -200,6 +219,10 @@ class MarkdownGenerator: f.write(f"- **Date**: {event['date']}\n") if event["place"]: 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"]: f.write(f"- **Details**: {event['details']}\n") @@ -238,6 +261,12 @@ class MarkdownGenerator: f.write(f"* Marriage date: {family['marriage_date']}\n") if family["marriage_place"]: 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 if family["children"]: @@ -296,9 +325,9 @@ class MarkdownGenerator: def _write_images(self, f, individual: Individual): """ Write an "Images" section to the open file for all images returned by the individual. - + If the individual has no images, nothing is written. Each image is written as a Markdown image reference (![title](path)). If an image has no title, the literal "Image" is used. When the generator was configured with a media subdirectory, that subdirectory is prefixed to the image filename. - + Parameters: f: A writable file-like object positioned where the section should be emitted. individual (Individual): The individual whose images are written. Expects items from individual.get_images() to be dicts with keys 'file' (filename) and optional 'title'. @@ -325,7 +354,7 @@ class MarkdownGenerator: def _generate_story_file(self, story: dict, individual_name: str) -> str: """ Generate a separate markdown file for a story and return the story note name. - + Parameters: story (dict): Story data containing keys: - title (str | None): Story title; "Untitled Story" used if empty. @@ -334,7 +363,7 @@ class MarkdownGenerator: 'subtitle' (str | None), 'text' (str | None), and 'images' (List[dict]). Images should be dicts with 'file' (str) and optional 'title' (str). individual_name (str): Full name of the individual the story relates to; used for a back-link. - + Returns: str: The generated story note name (filename without the ".md" extension). If a story file with the same filename was already created, returns the existing note name. """ @@ -399,7 +428,7 @@ class MarkdownGenerator: Write the "Notes" section for an individual, including inline notes and links to separate story files. If the individual has no notes and no stories, nothing is written. For each regular note, writes the note text into the section. For each story, generates or reuses a story markdown file via the generator, then writes a WikiLink to that story (prefixed with the configured stories subdirectory when present) and includes the story's description on the same line if provided. - + Parameters: f: A writable text file object opened for the individual's markdown note. individual (Individual): The individual whose notes and stories will be rendered. @@ -449,12 +478,12 @@ class MarkdownGenerator: def _write_metadata(self, f, key: str, value: str): """ Write a visible Obsidian metadata line for the given key and value. - + Parameters: f: A text file-like object to write the metadata line to. key (str): Metadata key to appear before the separator. value (str): Metadata value to appear after the separator. - + Description: Emits metadata in the Obsidian visible format: [Key:: Value] """ @@ -463,9 +492,9 @@ class MarkdownGenerator: def _write_metadata_hidden(self, f, key: str, value: str): """ Write a hidden Obsidian metadata line to the provided file. - + Writes a single line in the form "(Key:: Value)" followed by a newline to the file-like object `f`. - + Parameters: f: A writable file-like object to which the metadata line will be written. key (str): Metadata key. @@ -520,4 +549,4 @@ class MarkdownGenerator: ) logger.info(f"Successfully generated {len(paths)} notes") - return paths \ No newline at end of file + return paths diff --git a/tests/test_individual.py b/tests/test_individual.py index 49c523e..ea8cb73 100644 --- a/tests/test_individual.py +++ b/tests/test_individual.py @@ -17,6 +17,26 @@ from gedcom_parser import GedcomParser 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: """Tests for basic individual information extraction.""" @@ -205,15 +225,134 @@ class TestEvents: 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() 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 + assert resi['place'] == 'Deepplace' + assert resi['lat'] == '48.8566' + assert resi['long'] == '2.3522' class TestFamilyRelationships: @@ -424,6 +563,577 @@ class TestStories: 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: """Tests for physical attribute extraction.""" diff --git a/tests/test_markdown_generator.py b/tests/test_markdown_generator.py index 7127748..dfa4c0e 100644 --- a/tests/test_markdown_generator.py +++ b/tests/test_markdown_generator.py @@ -236,6 +236,34 @@ class TestEventFormatting: # Birth should not appear as a separate event 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: """Tests for image embedding in notes.""" -- 2.36.6 From 747175fcef6942703f529e3eaf9d587d9cb299f4 Mon Sep 17 00:00:00 2001 From: Jared Howland Date: Thu, 16 Apr 2026 22:51:45 -0600 Subject: [PATCH 2/8] fix: cache subject pointer; tidy up tests Cache the subject pointer in Individual.get_families by calling self.element.get_pointer() once outside the loop to avoid repeated calls and add a clarifying comment. Clean up tests: remove a duplicated TestIndividualBasicInfo fixture/block comment, drop redundant assertions about residence coordinates, and remove an unnecessary return in TestAttributes. --- src/individual.py | 3 ++- tests/test_individual.py | 26 -------------------------- 2 files changed, 2 insertions(+), 27 deletions(-) diff --git a/src/individual.py b/src/individual.py index 3d61b46..ca71f44 100644 --- a/src/individual.py +++ b/src/individual.py @@ -211,9 +211,10 @@ class Individual: - children: List of Individual objects """ families = [] + # Cache the subject pointer once; it doesn't change across families. + self_pointer = self.element.get_pointer() for family in self.gedcom.get_families(self.element): # Get partner - self_pointer = self.element.get_pointer() partners = [ Individual(parent, self.gedcom) for parent in self.gedcom.get_family_members(family, "PARENTS") diff --git a/tests/test_individual.py b/tests/test_individual.py index ea8cb73..992ae52 100644 --- a/tests/test_individual.py +++ b/tests/test_individual.py @@ -17,26 +17,6 @@ from gedcom_parser import GedcomParser 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: """Tests for basic individual information extraction.""" @@ -350,10 +330,6 @@ class TestEvents: events = person.get_events() event_types = [e['type'] for e in events] - assert resi['place'] == 'Deepplace' - assert resi['lat'] == '48.8566' - assert resi['long'] == '2.3522' - class TestFamilyRelationships: """Tests for family relationship extraction.""" @@ -601,8 +577,6 @@ class TestAttributes: 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() -- 2.36.6 From 0ba00d0ef781ab953b6f97e7a19939e10e6aad90 Mon Sep 17 00:00:00 2001 From: Jared Howland Date: Thu, 16 Apr 2026 23:02:49 -0600 Subject: [PATCH 3/8] fix: lat/long extraction and emit coordinates Rename returned long variable to lon and tighten lat/long extraction to avoid recursing into LATI/LONG leaf nodes and to return early when both values are found. Refactor MarkdownGenerator._coordinate_values and change output logic so coordinates are written even when place fields are empty (birth, death, marriage, and events). Update and reorganize tests to match the corrected behavior and improve stability (use next() instead of list indexing, consolidate fixtures, adjust assertions and quoting). --- src/individual.py | 20 +- src/markdown_generator.py | 45 +-- tests/test_individual.py | 639 +++++--------------------------------- 3 files changed, 122 insertions(+), 582 deletions(-) diff --git a/src/individual.py b/src/individual.py index ca71f44..746a0d1 100644 --- a/src/individual.py +++ b/src/individual.py @@ -111,7 +111,7 @@ class Individual: - 'lat' (str): Latitude string if present, else '' - 'long' (str): Longitude string if present, else '' """ - birth_date, birth_place, lat, long = self._get_event_info("BIRT") + birth_date, birth_place, lat, lon = self._get_event_info("BIRT") # Fallback to helper methods for year if available year = self.element.get_birth_year() @@ -122,7 +122,7 @@ class Individual: "place": birth_place or "", "year": birth_year, "lat": lat, - "long": long, + "long": lon, } def get_death_info(self) -> Dict[str, str]: @@ -137,7 +137,7 @@ class Individual: - lat (str): Latitude if present, else '' - long (str): Longitude if present, else '' """ - death_date, death_place, lat, long = self._get_event_info("DEAT") + death_date, death_place, lat, lon = self._get_event_info("DEAT") year = self._extract_year(death_date) return { @@ -145,7 +145,7 @@ class Individual: "place": death_place or "", "year": year, "lat": lat, - "long": long, + "long": lon, } def get_gender(self) -> str: @@ -408,12 +408,18 @@ class Individual: if tag == "LATI" and not lati: lati = child.get_value() or "" + if lati and longi: + return lati, longi + # Don't recurse into LATI leaf nodes + continue elif tag == "LONG" and not longi: longi = child.get_value() or "" + if lati and longi: + return lati, longi + # Don't recurse into LONG leaf nodes + continue - if lati and longi: - return lati, longi - + # Recurse into other child nodes to find nested LATI/LONG nested_lati, nested_longi = self._extract_lat_long_from_node(child) if nested_lati and not lati: lati = nested_lati diff --git a/src/markdown_generator.py b/src/markdown_generator.py index fba321d..45cf4f7 100644 --- a/src/markdown_generator.py +++ b/src/markdown_generator.py @@ -62,10 +62,12 @@ class MarkdownGenerator: ) -> 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)) + lat_val = data.get(lat_key) + long_val = data.get(long_key) + if lat_val: + coords.append(lat_val) + if long_val: + coords.append(long_val) return coords def _get_unique_filename(self, base_name: str, individual_id: str) -> str: @@ -150,20 +152,20 @@ class MarkdownGenerator: f.write(f"Born: {birth['date']}\n") if birth["place"]: 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") + # Birth coordinates should be emitted even if place is empty + birth_coords = self._coordinate_values(birth) + if birth_coords: + f.write(f"Birth coordinates: {', '.join(birth_coords)}\n") # Death details if death["date"]: f.write(f"Passed away: {death['date']}\n") if death["place"]: 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") + # Death coordinates should be emitted even if place is empty + death_coords = self._coordinate_values(death) + if death_coords: + f.write(f"Death coordinates: {', '.join(death_coords)}\n") # Physical attributes attrs = individual.get_attributes() @@ -217,12 +219,13 @@ class MarkdownGenerator: if event["date"]: f.write(f"- **Date**: {event['date']}\n") + + # Always compute coordinates, emit regardless of whether place is present + coords = self._coordinate_values(event) if event["place"]: 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 coords: + f.write(f"- **Coordinates**: {', '.join(coords)}\n") if event["details"]: f.write(f"- **Details**: {event['details']}\n") @@ -261,12 +264,10 @@ class MarkdownGenerator: f.write(f"* Marriage date: {family['marriage_date']}\n") if family["marriage_place"]: 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") + # Marriage coordinates should be emitted regardless of whether place is present + mcoords = self._coordinate_values(family, "marriage_lat", "marriage_long") + if mcoords: + f.write(f"* Marriage coordinates: {', '.join(mcoords)}\n") # Write children if they exist if family["children"]: diff --git a/tests/test_individual.py b/tests/test_individual.py index 992ae52..d6ef5e4 100644 --- a/tests/test_individual.py +++ b/tests/test_individual.py @@ -17,6 +17,7 @@ from gedcom_parser import GedcomParser from individual import Individual + class TestIndividualBasicInfo: """Tests for basic individual information extraction.""" @@ -101,554 +102,6 @@ class TestIndividualBasicInfo: 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() - event_types = [e['type'] for e in events] - - -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 - - -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) - - images = john_obj.get_images() - assert len(images) >= 1 - - image = images[0] - assert image['file'] == 'john_photo.jpg' - assert image['title'] == 'Photo of John' - assert image['format'] == 'jpeg' - - def test_get_images_empty(self, temp_dir): - """Test image extraction when no images 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_images.ged" - temp_file.write_text(gedcom_content, encoding='utf-8') - - parser = GedcomParser(temp_file) - individuals = parser.get_individuals() - person = Individual(individuals[0], parser.parser) - - images = person.get_images() - assert len(images) == 0 - - -class TestNotes: - """Tests for notes extraction.""" - - def test_get_notes_with_reference(self, sample_gedcom_file): - """Test note extraction via reference.""" - 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: - """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 - - 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.""" @@ -699,6 +152,7 @@ class TestBirthAndDeath: assert birth["year"] == "" + class TestEvents: """Tests for event extraction.""" @@ -755,7 +209,7 @@ class TestEvents: person = Individual(individuals[0], parser.parser) 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 "DEAT" in event_types @@ -764,6 +218,15 @@ class TestEvents: assert "RESI" in event_types assert "BURI" in event_types + resi = next(e for e in events if e["type"] == "RESI") + assert resi['place'] == 'New York' + assert resi['lat'] == '' + assert resi['long'] == '' + + 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 @@ -788,7 +251,7 @@ class TestEvents: person = Individual(individuals[0], parser.parser) events = person.get_events() - resi = [e for e in events if e["type"] == "RESI"][0] + resi = next(e for e in events if e["type"] == "RESI") assert resi["place"] == "Newplace" assert resi["lat"] == "40.7128" @@ -817,7 +280,7 @@ class TestEvents: person = Individual(individuals[0], parser.parser) events = person.get_events() - resi = [e for e in events if e["type"] == "RESI"][0] + resi = next(e for e in events if e["type"] == "RESI") assert resi["place"] == "Somewhere" assert resi["lat"] == "12.34" @@ -846,7 +309,7 @@ class TestEvents: person = Individual(individuals[0], parser.parser) events = person.get_events() - resi = [e for e in events if e["type"] == "RESI"][0] + resi = next(e for e in events if e["type"] == "RESI") assert resi["place"] == "Coastal" assert resi["lat"] == "" @@ -877,13 +340,14 @@ class TestEvents: person = Individual(individuals[0], parser.parser) events = person.get_events() - resi = [e for e in events if e["type"] == "RESI"][0] + resi = next(e for e in events if e["type"] == "RESI") assert resi["place"] == "Deepplace" assert resi["lat"] == "48.8566" assert resi["long"] == "2.3522" + class TestFamilyRelationships: """Tests for family relationship extraction.""" @@ -1005,6 +469,7 @@ class TestFamilyRelationships: assert family_two["marriage_long"] == "" + class TestImagesAndMedia: """Tests for image and media extraction.""" @@ -1015,6 +480,72 @@ class TestImagesAndMedia: john = [ind for ind in individuals if 'John' in str(ind.get_name())] john_obj = Individual(john[0], parser.parser) + images = john_obj.get_images() + assert len(images) >= 1 + + image = images[0] + assert image['file'] == 'john_photo.jpg' + assert image['title'] == 'Photo of John' + assert image['format'] == 'jpeg' + + 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 TestNotes: + """Tests for notes extraction.""" + + def test_get_notes_with_reference(self, sample_gedcom_file): + """Test note extraction via reference.""" + 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() @@ -1067,6 +598,7 @@ class TestImagesAndMedia: assert len(notes) == 0 + class TestStories: """Tests for custom story tag extraction.""" @@ -1108,6 +640,7 @@ class TestStories: assert len(stories) == 0 + class TestAttributes: """Tests for physical attribute extraction.""" -- 2.36.6 From 2071c01317b6aad2f55d88dae77ae4b39fb2f553 Mon Sep 17 00:00:00 2001 From: Jared Howland Date: Thu, 16 Apr 2026 23:07:13 -0600 Subject: [PATCH 4/8] fix: clarify parent GEDCOM pointer format Update docstring in src/individual.py to specify that the `father` and `mother` fields are GEDCOM pointers including the surrounding '@' characters (e.g. '@I1@', '@I2@'), removing ambiguity about the expected identifier format. --- src/individual.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/individual.py b/src/individual.py index 746a0d1..adf2a53 100644 --- a/src/individual.py +++ b/src/individual.py @@ -253,8 +253,8 @@ class Individual: Returns: List of dictionaries with family information including: - - father: str (father's GEDCOM ID) or None - - mother: str (mother's GEDCOM ID) or None + - father: str (father's GEDCOM pointer, including surrounding '@' characters, e.g. '@I1@') or None + - mother: str (mother's GEDCOM pointer, including surrounding '@' characters, e.g. '@I2@') or None """ families = [] self_pointer = self.element.get_pointer() -- 2.36.6 From 1f48292e6094218652bcc587fb4cdad72f0ab370 Mon Sep 17 00:00:00 2001 From: Jared Howland Date: Thu, 16 Apr 2026 23:47:53 -0600 Subject: [PATCH 5/8] feat: add FamilySearch ID to frontmatter Add get_fs_id() to Individual to extract the _FSFTID tag (returns empty string if missing). Update MarkdownGenerator to include a "FamilySearch ID" line in output when present. Update test fixtures and add assertions: include _FSFTID in sample GEDCOM, add unit test for get_fs_id (presence and absence), and check the generated markdown contains the FamilySearch ID. Ensures FS Tree IDs are surfaced without breaking behavior when tag is absent. --- src/individual.py | 12 ++++++++++++ src/markdown_generator.py | 3 +++ tests/conftest.py | 1 + tests/test_individual.py | 9 +++++++++ tests/test_markdown_generator.py | 1 + 5 files changed, 26 insertions(+) diff --git a/src/individual.py b/src/individual.py index adf2a53..af6fa34 100644 --- a/src/individual.py +++ b/src/individual.py @@ -57,6 +57,18 @@ class Individual: """ return self.element.get_pointer() + def get_fs_id(self) -> str: + """ + Return the FamilySearch Tree ID (`_FSFTID`) if present. + + Returns: + str: FamilySearch Tree ID value, or an empty string when not available. + """ + for child in self.element.get_child_elements(): + if child.get_tag() == "_FSFTID": + return child.get_value() or "" + return "" + def get_names(self) -> Tuple[str, str]: """ Return the individual's first and last name with surrounding whitespace removed. diff --git a/src/markdown_generator.py b/src/markdown_generator.py index 45cf4f7..2aee2d6 100644 --- a/src/markdown_generator.py +++ b/src/markdown_generator.py @@ -136,8 +136,11 @@ class MarkdownGenerator: birth = individual.get_birth_info() death = individual.get_death_info() + fs_id = individual.get_fs_id() f.write(f"ID: {individual.get_id()}\n") + if fs_id: + f.write(f"FamilySearch ID: {fs_id}\n") f.write(f"Name: {individual.get_full_name()}\n") # Lived years diff --git a/tests/conftest.py b/tests/conftest.py index fe3b1da..4db8cd7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -41,6 +41,7 @@ def sample_gedcom_content(): 1 NAME John /Doe/ 2 GIVN John 2 SURN Doe +1 _FSFTID G123-ABC 1 SEX M 1 BIRT 2 DATE 1 JAN 1950 diff --git a/tests/test_individual.py b/tests/test_individual.py index d6ef5e4..11f62e2 100644 --- a/tests/test_individual.py +++ b/tests/test_individual.py @@ -81,6 +81,15 @@ class TestIndividualBasicInfo: """Test gender extraction.""" assert john_doe.get_gender() == 'M' + def test_get_fs_id(self, john_doe, sample_gedcom_file): + """Test FamilySearch Tree ID extraction from _FSFTID tag.""" + assert john_doe.get_fs_id() == 'G123-ABC' + parser = GedcomParser(sample_gedcom_file) + individuals = parser.get_individuals() + jane = [ind for ind in individuals if 'Jane' in str(ind.get_name())] + jane_doe = Individual(jane[0], parser.parser) + assert jane_doe.get_fs_id() == '' + def test_get_gender_default_unknown(self, sample_gedcom_file): """Test that missing gender defaults to 'U'.""" gedcom_content = """0 HEAD diff --git a/tests/test_markdown_generator.py b/tests/test_markdown_generator.py index dfa4c0e..f29a240 100644 --- a/tests/test_markdown_generator.py +++ b/tests/test_markdown_generator.py @@ -129,6 +129,7 @@ class TestMetadataFormatting: # Check for YAML frontmatter metadata assert 'ID: I1' in content + assert 'FamilySearch ID: G123-ABC' in content assert 'Name: John Doe' in content assert 'Sex: M' in content -- 2.36.6 From 6259bfffd6253846b705b0be6660e9bcdfdcb9bd Mon Sep 17 00:00:00 2001 From: Jared Howland <1877384+jaredhowland@users.noreply.github.com> Date: Fri, 17 Apr 2026 13:42:04 -0600 Subject: [PATCH 6/8] feat: add source parsing and linking - Respect GEDCOM CONC vs CONT semantics (concatenate vs newline) - Generate global sources index once (avoid O(N*S) stall) - Repair broken HTML tags spanning GEDCOM lines for whitelist tags - Escape markdown emphasis characters in notes to prevent formatting leakage - Consistent handling of CONT/CONC; skip empty CONT lines; handle trailing spaces for hard breaks - Added tests covering CONT/CONC and source index --- src/individual.py | 134 +++++++++++++---- src/markdown_generator.py | 274 +++++++++++++++++++++++++++++++++- tests/test_notes_cont_conc.py | 110 ++++++++++++++ tests/test_sources.py | 104 +++++++++++++ 4 files changed, 586 insertions(+), 36 deletions(-) create mode 100644 tests/test_notes_cont_conc.py create mode 100644 tests/test_sources.py diff --git a/src/individual.py b/src/individual.py index d37c2dd..4654684 100644 --- a/src/individual.py +++ b/src/individual.py @@ -366,44 +366,112 @@ class Individual: return images + def _collapse_preserve_lines(self, text: str) -> str: + """Collapse whitespace within each line but preserve line breaks.""" + if not text: + return "" + return "\n".join(" ".join(line.split()) for line in text.splitlines()).strip() + + def _resolve_gedcom_text(self, value: str, element=None) -> str: + """Resolve a GEDCOM text value which may be a pointer to another element or inline text. + + Appends CONT/CONC child lines (skipping empty ones) separated by single newlines. + """ + if not value: + return "" + + # Pointer/reference to another element (e.g., NOTE record) + if value.startswith("@") and value.endswith("@"): + target = self.gedcom.get_element_dictionary().get(value) + if not target: + return "" + text = target.get_value() or "" + # Respect CONT vs CONC semantics: CONT => newline, CONC => concatenate + for sub in target.get_child_elements(): + tag = sub.get_tag() + val = (sub.get_value() or "") + if not val: + continue + if tag == "CONC": + # concatenate directly + text += val + elif tag == "CONT": + text += "\n" + val + return text + + # Inline text with possible CONT/CONC children + text = value or "" + if element is not None: + for sub in element.get_child_elements(): + tag = sub.get_tag() + val = (sub.get_value() or "") + if not val: + continue + if tag == "CONC": + text += val + elif tag == "CONT": + text += "\n" + val + return text + def get_notes(self) -> List[str]: - """ - Return the person's notes with inline continuations and referenced NOTE records resolved. - - This resolves NOTE cross-references (values like `@X@`), appends `CONT`/`CONC` continuations, trims whitespace, and omits empty or unresolved references. - - Returns: - List[str]: Note texts with continuations and referenced NOTE content merged; empty or unresolved notes are omitted. - """ + """Return the person's notes with continuations resolved and extraneous whitespace collapsed per-line.""" notes = [] - for child in self.element.get_child_elements(): - if child.get_tag() == "NOTE": - note_text = child.get_value() or "" - - # If note_text starts with @, it's a reference to a NOTE record - if note_text.startswith("@") and note_text.endswith("@"): - # Resolve the reference - note_element = self.gedcom.get_element_dictionary().get(note_text) - if note_element: - # Get the note text from the NOTE element - note_text = note_element.get_value() or "" - - # Get continued text from the NOTE record - for subchild in note_element.get_child_elements(): - if subchild.get_tag() in ["CONT", "CONC"]: - note_text += "\n" + (subchild.get_value() or "") - else: - # Inline note - check for continued text in subchilds - for subchild in child.get_child_elements(): - if subchild.get_tag() in ["CONT", "CONC"]: - note_text += "\n" + (subchild.get_value() or "") - - if note_text and not note_text.startswith("@"): - notes.append(note_text.strip()) - + if child.get_tag() != "NOTE": + continue + raw = child.get_value() or "" + text = self._resolve_gedcom_text(raw, child) + if text and not text.startswith("@"): + notes.append(self._collapse_preserve_lines(text)) return notes + def get_sources(self) -> List[Dict[str, str]]: + """ + Extract SOUR references for this individual and return normalized entries. + Each entry is a dict: {"title": str, "publ": str, "note": str} with internal whitespace collapsed. + + Handles both referenced SOURCE pointers (SOUR @X@) and inline SOURCE blocks under the individual. + """ + def _collapse_single_line(text: str) -> str: + return " ".join(text.split()).strip() if text else "" + + sources = [] + for child in self.element.get_child_elements(): + if child.get_tag() != "SOUR": + continue + + title = "" + publ = "" + note_text = "" + + # child may be a pointer to a SOURCE record or an inline SOURCE element + src_ref = child.get_value() or "" + if src_ref and src_ref.startswith("@"): + elem_to_scan = self.gedcom.get_element_dictionary().get(src_ref) or child + else: + elem_to_scan = child + + for sc in elem_to_scan.get_child_elements(): + tag = sc.get_tag() + if tag == "TITL": + title = sc.get_value() or "" + elif tag == "PUBL": + publ = sc.get_value() or "" + elif tag == "NOTE": + raw_note = sc.get_value() or "" + note_text = self._resolve_gedcom_text(raw_note, sc) + + # Normalize whitespace for title/publ but preserve line breaks in notes + title = _collapse_single_line(title) + publ = _collapse_single_line(publ) + + note_text = self._collapse_preserve_lines(note_text) + + if title or publ or note_text: + sources.append({"title": title, "publ": publ, "note": note_text}) + + return sources + def get_stories(self) -> List[Dict]: """ Extract story and narrative records referenced by custom `_STO` tags for this individual. diff --git a/src/markdown_generator.py b/src/markdown_generator.py index 7c4cb91..fe301ac 100644 --- a/src/markdown_generator.py +++ b/src/markdown_generator.py @@ -8,6 +8,7 @@ in the family tree. from pathlib import Path from typing import List, Optional import logging +import re from individual import Individual @@ -56,6 +57,7 @@ class MarkdownGenerator: self.use_subdirectories = use_subdirectories self.generated_stories = {} # Track generated story files self.filename_map = {} # Map from individual ID to actual filename used + self._sources_index_generated = False # Ensure global sources index is created only once def _get_unique_filename(self, base_name: str, individual_id: str) -> str: """ @@ -108,6 +110,19 @@ class MarkdownGenerator: self._write_children(f, individual) self._write_images(f, individual) self._write_notes(f, individual) + # Write Sources section (if any) + self._write_sources(f, individual) + + # Generate global sources index once if not already generated. This preserves the behavior + # expected by callers that invoke generate_note() directly (unit tests), while avoiding + # O(N^2) behavior when multiple notes are generated via generate_all(). + if not getattr(self, '_sources_index_generated', False): + parser = getattr(individual, 'gedcom', None) + if parser: + try: + self._generate_sources_index(parser) + except Exception: + logger.exception('Failed to generate sources index') return file_path @@ -397,9 +412,9 @@ class MarkdownGenerator: def _write_notes(self, f, individual: Individual): """ Write the "Notes" section for an individual, including inline notes and links to separate story files. - + If the individual has no notes and no stories, nothing is written. For each regular note, writes the note text into the section. For each story, generates or reuses a story markdown file via the generator, then writes a WikiLink to that story (prefixed with the configured stories subdirectory when present) and includes the story's description on the same line if provided. - + Parameters: f: A writable text file object opened for the individual's markdown note. individual (Individual): The individual whose notes and stories will be rendered. @@ -414,7 +429,13 @@ class MarkdownGenerator: # Write regular notes for note in notes: - f.write(f"{note}\n\n") + # Repair broken HTML tags that may span lines, then split into lines + repaired = self._repair_broken_html_tags(note) + lines = repaired.splitlines() + # Escape markdown in each line to avoid accidental emphasis, then write + esc_lines = [self._escape_markdown(ln) for ln in lines] + self._write_multiline_note_block(f, esc_lines, nested=False) + f.write("\n") # Generate separate story files and link to them if stories: @@ -446,6 +467,239 @@ class MarkdownGenerator: f.write("\n") + def _collapse_single_line(self, text: str) -> str: + """Collapse runs of whitespace into single spaces and strip the result.""" + return " ".join(text.split()).strip() if text else "" + + def _collapse_preserve_lines(self, text: str) -> str: + """Collapse runs of whitespace within each line but preserve line breaks. + + Returns a string where each original line has internal whitespace collapsed + but newline boundaries between CONT/CONC lines are preserved. + """ + if not text: + return "" + return "\n".join(" ".join(line.split()) for line in text.splitlines()).strip() + + def _format_source_entry(self, title: str, publ: str) -> str: + """Return a formatted markdown line for a source entry. + + If title and publ are present, title is rendered as a link to publ. + If only title present, render plain title. If only publ present, use the URL as link text. + """ + title = self._collapse_single_line(title) + publ = self._collapse_single_line(publ) + + if title and publ: + return f"[{title}]({publ})" + if title: + return title + if publ: + return f"[{publ}]({publ})" + return "(Unknown source)" + + def _write_sources(self, f, individual: Individual): + """ + Write the "Sources" section for an individual as a numbered list. + + Each source will include the formatted title/publication on the numbered line + and, if present, the source's NOTE text will be written indented beneath it + (formatted in italic to match the generated index). + """ + sources = individual.get_sources() + if not sources: + return + + f.write("## Sources\n\n") + for i, src in enumerate(sources, 1): + line = self._format_source_entry(src.get("title", ""), src.get("publ", "")) + f.write(f"{i}. {line}\n") + note_text = src.get("note", "") + if note_text: + # Repair broken HTML tags spanning lines and escape markdown + note_text = self._repair_broken_html_tags(note_text) + lines = [self._escape_markdown(ln) for ln in note_text.splitlines()] + self._write_multiline_note_block(f, lines, nested=True) + f.write("\n") + + def _generate_sources_index(self, parser): + """ + Generate a summary Index.md in a sources/ subdirectory listing all SOURCE records found in the GEDCOM element dictionary. + """ + try: + elem_dict = parser.get_element_dictionary() + except Exception: + return + + sources = [] + for elem in elem_dict.values(): + try: + if elem.get_tag() != "SOUR": + continue + except Exception: + continue + + title = "" + publ = "" + note_text = "" + + for sc in elem.get_child_elements(): + tag = sc.get_tag() + if tag == "TITL": + title = sc.get_value() or "" + elif tag == "PUBL": + publ = sc.get_value() or "" + elif tag == "NOTE": + note_val = sc.get_value() or "" + if note_val.startswith("@") and note_val.endswith("@"): + n_elem = elem_dict.get(note_val) + if n_elem: + note_text = n_elem.get_value() or "" + for sub in n_elem.get_child_elements(): + tag_sub = sub.get_tag() + val_sub = (sub.get_value() or "") + if not val_sub: + continue + if tag_sub == "CONC": + note_text += val_sub + elif tag_sub == "CONT": + note_text += "\n" + val_sub + else: + note_text = note_val + for sub in sc.get_child_elements(): + tag_sub = sub.get_tag() + val_sub = (sub.get_value() or "") + if not val_sub: + continue + if tag_sub == "CONC": + note_text += val_sub + elif tag_sub == "CONT": + note_text += "\n" + val_sub + + title = self._collapse_single_line(title) + publ = self._collapse_single_line(publ) + note_text = self._collapse_preserve_lines(note_text) + + if title or publ or note_text: + sources.append({"title": title, "publ": publ, "note": note_text}) + + if not sources: + return + + # Prefer a global 'sources' directory at the top-level output when using + # the organized subdirectory layout (people/, stories/, media/). The + # generator's output_dir is typically the people/ directory in that + # case, so use its parent as the global output root. + if self.use_subdirectories and self.output_dir and self.output_dir.parent: + sources_dir = self.output_dir.parent / "sources" + else: + sources_dir = self.output_dir / "sources" + + sources_dir.mkdir(parents=True, exist_ok=True) + index_file = sources_dir / "Index.md" + + with open(index_file, "w", encoding="utf-8") as f: + f.write("# Sources Index\n\n") + for i, src in enumerate(sources, 1): + entry = self._format_source_entry(src.get("title", ""), src.get("publ", "")) + f.write(f"{i}. {entry}\n") + note_text = src.get("note", "") + if note_text: + # Repair broken HTML tags and escape markdown + note_text = self._repair_broken_html_tags(note_text) + lines = [self._escape_markdown(ln) for ln in note_text.splitlines()] + self._write_multiline_note_block(f, lines, nested=True) + f.write("\n") + + # Mark that the global sources index has been generated so we don't do this again + self._sources_index_generated = True + + def _escape_markdown(self, text: str) -> str: + """Escape markdown emphasis characters in text to prevent accidental formatting. + + Escapes: backslash, asterisk, underscore, backtick, and tilde. + Does not escape bracket characters so links still render. + """ + if not text: + return "" + # Escape backslash first + text = text.replace("\\", "\\\\") + # Escape characters that trigger emphasis or code spans + for ch in ('*', '_', '`', '~'): + text = text.replace(ch, f"\\{ch}") + return text + + def _repair_broken_html_tags(self, text: str) -> str: + """Repair HTML tags that were broken across lines for a small whitelist of tags. + + Strategy: + - Find all substrings that look like tags (<...>), possibly spanning lines. + - For each tag, remove newlines inside the tag only if the tag name (after + removing newlines) is in a safe whitelist. This joins broken tag names + like "" into "
" while leaving other tags alone. + """ + if not text or '<' not in text: + return text + + WHITELIST = {"br", "b", "i", "strong", "em", "a", "span", "div", "p", "ul", "li"} + + def repl(m: re.Match) -> str: + raw = m.group(0) + content = raw[1:-1] # inside <...> + # Remove newline and carriage returns to inspect tag name + content_no_nl = content.replace('\n', '').replace('\r', '') + # Extract tag name (skip leading '/') + name_m = re.match(r"\s*/?\s*([A-Za-z0-9]+)", content_no_nl) + if name_m and name_m.group(1).lower() in WHITELIST: + # Rebuild tag with newlines removed but preserve other spaces + repaired = '<' + content_no_nl + '>' + return repaired + return raw + + return re.sub(r'<[^>]*>', repl, text, flags=re.DOTALL) + + def _write_multiline_note_block(self, f, lines: List[str], nested: bool = True) -> None: + """Write a multi-line note block. + + - If nested is True, writes a nested list bullet (3 spaces + '-') for the first + line and indented continuation lines for the rest. All lines except the + last will end with two trailing spaces to force a hard line break; the + final CONT line is written without the trailing spaces to avoid an extra + blank line after the block. + - If nested is False, writes plain lines; trailing two spaces are added to + all but the last non-empty line. + """ + if not lines: + return + + total = len(lines) + if nested: + indent = " " + cont_indent = " " + # First line as a nested bullet; add two spaces if there are continuation lines + if total > 1: + f.write(f"{indent}- {lines[0]} \n") + else: + f.write(f"{indent}- {lines[0]}\n") + + for idx, cont in enumerate(lines[1:], start=1): + # For continuation lines, add two spaces except for the last line + if idx < total - 1: + f.write(f"{cont_indent}{cont} \n") + else: + f.write(f"{cont_indent}{cont}\n") + else: + # Non-nested: add two spaces to all non-empty lines except the last non-empty + non_empty = [ln for ln in lines if ln.strip()] + last_non_empty = non_empty[-1] if non_empty else None + for ln in lines: + if not ln.strip(): + f.write("\n") + elif ln == last_non_empty: + f.write(f"{ln}\n") + else: + f.write(f"{ln} \n") + def _write_metadata(self, f, key: str, value: str): """ Write a visible Obsidian metadata line for the given key and value. @@ -520,4 +774,18 @@ class MarkdownGenerator: ) logger.info(f"Successfully generated {len(paths)} notes") + + # Generate global sources index once (expensive) using the first available parser + if not self._sources_index_generated: + parser = None + for ind in individuals: + parser = getattr(ind, 'gedcom', None) + if parser: + break + + if parser: + try: + self._generate_sources_index(parser) + except Exception: + logger.exception('Failed to generate sources index') return paths \ No newline at end of file diff --git a/tests/test_notes_cont_conc.py b/tests/test_notes_cont_conc.py new file mode 100644 index 0000000..b919df9 --- /dev/null +++ b/tests/test_notes_cont_conc.py @@ -0,0 +1,110 @@ +from pathlib import Path + +from src.gedcom_parser import GedcomParser +from src.individual import Individual +from src.markdown_generator import MarkdownGenerator + + +def _make_output_dir(tmp_path): + out = tmp_path / "output" + out.mkdir() + return out + + +class TestNotesContConc: + def test_note_cont_and_conc_inline(self, tmp_path): + gedcom = """0 HEAD +1 SOUR TestApp +1 GEDC +2 VERS 5.5.1 +1 CHAR UTF-8 +0 @N1@ NOTE +1 CONT First line +1 CONC -continued +1 CONT Next paragraph +0 @I1@ INDI +1 NAME John /Doe/ +1 NOTE @N1@ +0 TRLR +""" + f = tmp_path / "note.ged" + f.write_text(gedcom, encoding='utf-8') + + parser = GedcomParser(f) + individuals = parser.get_individuals() + person = Individual(individuals[0], parser.parser) + + out = _make_output_dir(tmp_path) + gen = MarkdownGenerator(out) + note = gen.generate_note(person) + content = note.read_text() + + # Ensure CONC concatenated without newline + assert "First line-continued" in content + # Ensure CONT produced a newline (rendered as separate paragraph / hard break) + assert "Next paragraph" in content + + def test_note_reference_to_note_with_cont_conc(self, tmp_path): + gedcom = """0 HEAD +1 SOUR TestApp +1 GEDC +2 VERS 5.5.1 +1 CHAR UTF-8 +0 @N1@ NOTE +1 CONT Line one +1 CONC continued +1 CONT Line two +0 @I1@ INDI +1 NAME Jane /Smith/ +1 NOTE @N1@ +0 TRLR +""" + f = tmp_path / "note_ref.ged" + f.write_text(gedcom, encoding='utf-8') + + parser = GedcomParser(f) + individuals = parser.get_individuals() + person = Individual(individuals[0], parser.parser) + + out = _make_output_dir(tmp_path) + gen = MarkdownGenerator(out) + note = gen.generate_note(person) + content = note.read_text() + + assert "Line onecontinued" in content + assert "Line two" in content + + def test_source_note_cont_conc_and_index(self, tmp_path): + gedcom = """0 HEAD +1 SOUR TestApp +1 GEDC +2 VERS 5.5.1 +1 CHAR UTF-8 +0 @N1@ NOTE +1 CONT Source line +1 CONC -more +0 @S1@ SOUR +1 TITL Example Source +1 NOTE @N1@ +0 @I1@ INDI +1 NAME Alpha /Beta/ +1 SOUR @S1@ +0 TRLR +""" + f = tmp_path / "sources.ged" + f.write_text(gedcom, encoding='utf-8') + + parser = GedcomParser(f) + individuals = parser.get_individuals() + person = Individual(individuals[0], parser.parser) + + out = _make_output_dir(tmp_path) + gen = MarkdownGenerator(out) + # generate a person note which should also trigger sources index generation + gen.generate_note(person) + + index = out / 'sources' / 'Index.md' + assert index.exists() + content = index.read_text() + # Ensure concatenation in source note + assert 'Source line-more' in content diff --git a/tests/test_sources.py b/tests/test_sources.py new file mode 100644 index 0000000..1d6f762 --- /dev/null +++ b/tests/test_sources.py @@ -0,0 +1,104 @@ +import pytest + +from gedcom_parser import GedcomParser +from individual import Individual +from markdown_generator import MarkdownGenerator + + +def _make_output_dir(tmp_path): + out = tmp_path / "output" + out.mkdir() + return out + + +class TestSourcesSection: + def test_sources_happy_path_with_publ_and_title(self, tmp_path): + gedcom = """0 HEAD +1 SOUR TestApp +1 GEDC +2 VERS 5.5.1 +1 CHAR UTF-8 +0 @S1@ SOUR +1 TITL Overland Travels Pioneer Detail +1 PUBL http://history.example/pioneer?id=6262 +0 @I1@ INDI +1 NAME John /Doe/ +1 SOUR @S1@ +0 TRLR +""" + f = tmp_path / "sources.ged" + f.write_text(gedcom, encoding='utf-8') + + parser = GedcomParser(f) + individuals = parser.get_individuals() + person = Individual(individuals[0], parser.parser) + + out = _make_output_dir(tmp_path) + gen = MarkdownGenerator(out) + note = gen.generate_note(person) + content = note.read_text() + + assert '## Sources' in content + # Whitespace in title should be collapsed + assert '1. [Overland Travels Pioneer Detail](http://history.example/pioneer?id=6262)' in content + # Also an Index file should be created in sources/Index.md + index = out / 'sources' / 'Index.md' + assert index.exists() + idx_content = index.read_text() + assert '[Overland Travels Pioneer Detail](http://history.example/pioneer?id=6262)' in idx_content + + def test_sources_title_only_no_publ(self, tmp_path): + gedcom = """0 HEAD +1 SOUR TestApp +1 GEDC +2 VERS 5.5.1 +1 CHAR UTF-8 +0 @S2@ SOUR +1 TITL Local Archive Record +0 @I1@ INDI +1 NAME Jane /Smith/ +1 SOUR @S2@ +0 TRLR +""" + f = tmp_path / "sources2.ged" + f.write_text(gedcom, encoding='utf-8') + + parser = GedcomParser(f) + individuals = parser.get_individuals() + person = Individual(individuals[0], parser.parser) + + out = _make_output_dir(tmp_path) + gen = MarkdownGenerator(out) + note = gen.generate_note(person) + content = note.read_text() + + assert '## Sources' in content + assert '1. Local Archive Record' in content + + def test_sources_publ_but_no_title_uses_url_as_text(self, tmp_path): + gedcom = """0 HEAD +1 SOUR TestApp +1 GEDC +2 VERS 5.5.1 +1 CHAR UTF-8 +0 @S3@ SOUR +1 PUBL https://example.org/doc/123 +0 @I1@ INDI +1 NAME Alice /Doe/ +1 SOUR @S3@ +0 TRLR +""" + f = tmp_path / "sources3.ged" + f.write_text(gedcom, encoding='utf-8') + + parser = GedcomParser(f) + individuals = parser.get_individuals() + person = Individual(individuals[0], parser.parser) + + out = _make_output_dir(tmp_path) + gen = MarkdownGenerator(out) + note = gen.generate_note(person) + content = note.read_text() + + assert '## Sources' in content + assert '1. [https://example.org/doc/123](https://example.org/doc/123)' in content -- 2.36.6 From 96da61c1ff10cdfa53e816f5a820eda85899486c Mon Sep 17 00:00:00 2001 From: Jared Howland <1877384+jaredhowland@users.noreply.github.com> Date: Fri, 17 Apr 2026 14:06:54 -0600 Subject: [PATCH 7/8] fix: implement suggestions of coderabbit and copilot - Tighten exception handling when retrieving GEDCOM element dictionary; log failures and avoid repeated scans - Use shared resolve_gedcom_text() and collapse_single_line() helpers to remove duplication - Ensure inline NOTE continuations under INDI are resolved when NOTE has no immediate value (process CONT/CONC children) - Make sources index generation robust and streaming to avoid large memory use - Deterministic handling of last non-empty lines when writing note blocks - Expanded and clarified docstrings for GEDCOM resolver, collapse helper, and markdown generator helpers --- src/individual.py | 176 ++++++++++++++++++------- src/markdown_generator.py | 236 ++++++++++++++++++++-------------- tests/test_notes_cont_conc.py | 17 ++- 3 files changed, 280 insertions(+), 149 deletions(-) diff --git a/src/individual.py b/src/individual.py index 4654684..bc87e6b 100644 --- a/src/individual.py +++ b/src/individual.py @@ -16,6 +16,97 @@ import gedcom.tags logger = logging.getLogger(__name__) +def collapse_single_line(text: str) -> str: + """Normalize whitespace on a single logical line. + + This helper collapses runs of whitespace (spaces, tabs) into single spaces + and trims leading/trailing whitespace. It is intended for short metadata + fields such as titles, publication strings, or other single-line values + where internal spacing should be normalized but line breaks must be + preserved elsewhere. + + Examples: + >>> collapse_single_line(" Overland Travels Pioneer Detail ") + 'Overland Travels Pioneer Detail' + + Returns an empty string when passed a false-y value. + """ + return " ".join(text.split()).strip() if text else "" + + +def resolve_gedcom_text(parser, value: str, element=None) -> str: + """Resolve a GEDCOM text value including CONT/CONC continuations. + + GEDCOM continuation rules: + - CONC: concatenate to previous line (no newline inserted) + - CONT: start a new line (insert a newline in the output) + + This helper handles both pointer-style NOTE references (e.g. "@N1@") and + inline NOTE bodies (where the parent element contains CONT/CONC children). + + Parameters + ---------- + parser: + The GEDCOM parser instance used to resolve pointer targets via + parser.get_element_dictionary(). + value (str): + The immediate value of the tag. May be a pointer ("@N1@") or plain + text. When it's a pointer, the referenced element is resolved and its + child CONT/CONC lines are applied. + element: + Optional element whose child CONT/CONC children should be read when + resolving inline NOTE content. Provide this when `value` is an inline + value and the continuations are stored on the element itself. + + Returns + ------- + str + Resolved text with CONC concatenated directly and CONT lines separated + by a single newline. Empty CONT/CONC values are skipped. + + Examples + -------- + Given a referenced NOTE element with: + 0 @N1@ NOTE + 1 CONT First line + 1 CONC -continued + 1 CONT Second para + Calling resolve_gedcom_text(parser, "@N1@") returns: + "First line-continued\nSecond para" + """ + # Pointer/reference to another element (e.g., NOTE record) + if value and value.startswith("@") and value.endswith("@"): + target = parser.get_element_dictionary().get(value) + if not target: + return "" + text = target.get_value() or "" + # Respect CONT vs CONC semantics: CONT => newline, CONC => concatenate + for sub in target.get_child_elements(): + tag = sub.get_tag() + val = (sub.get_value() or "") + if not val: + continue + if tag == "CONC": + text += val + elif tag == "CONT": + text += "\n" + val + return text + + # Inline text with possible CONT/CONC children + text = value or "" + if element is not None: + for sub in element.get_child_elements(): + tag = sub.get_tag() + val = (sub.get_value() or "") + if not val: + continue + if tag == "CONC": + text += val + elif tag == "CONT": + text += "\n" + val + return text + + class Individual: """ Represents an individual person in the family tree. @@ -373,45 +464,25 @@ class Individual: return "\n".join(" ".join(line.split()) for line in text.splitlines()).strip() def _resolve_gedcom_text(self, value: str, element=None) -> str: - """Resolve a GEDCOM text value which may be a pointer to another element or inline text. + """Instance-level wrapper for the module resolve_gedcom_text helper. - Appends CONT/CONC child lines (skipping empty ones) separated by single newlines. + This method forwards to the module-level resolve_gedcom_text function + passing the parser instance bound to this Individual. It exists to keep + call sites on the Individual instance simple while centralizing the + continuation resolution logic in one place. + + Parameters + ---------- + value (str): The immediate tag value (may be a pointer like "@N1@" + or inline text). + element: Optional element to read CONT/CONC children from when resolving + inline note content. + + Returns + ------- + str: Resolved note/text with CONT/CONC applied. """ - if not value: - return "" - - # Pointer/reference to another element (e.g., NOTE record) - if value.startswith("@") and value.endswith("@"): - target = self.gedcom.get_element_dictionary().get(value) - if not target: - return "" - text = target.get_value() or "" - # Respect CONT vs CONC semantics: CONT => newline, CONC => concatenate - for sub in target.get_child_elements(): - tag = sub.get_tag() - val = (sub.get_value() or "") - if not val: - continue - if tag == "CONC": - # concatenate directly - text += val - elif tag == "CONT": - text += "\n" + val - return text - - # Inline text with possible CONT/CONC children - text = value or "" - if element is not None: - for sub in element.get_child_elements(): - tag = sub.get_tag() - val = (sub.get_value() or "") - if not val: - continue - if tag == "CONC": - text += val - elif tag == "CONT": - text += "\n" + val - return text + return resolve_gedcom_text(self.gedcom, value, element) def get_notes(self) -> List[str]: """Return the person's notes with continuations resolved and extraneous whitespace collapsed per-line.""" @@ -426,15 +497,25 @@ class Individual: return notes def get_sources(self) -> List[Dict[str, str]]: - """ - Extract SOUR references for this individual and return normalized entries. - Each entry is a dict: {"title": str, "publ": str, "note": str} with internal whitespace collapsed. + """Extract source references associated with this individual. - Handles both referenced SOURCE pointers (SOUR @X@) and inline SOURCE blocks under the individual. - """ - def _collapse_single_line(text: str) -> str: - return " ".join(text.split()).strip() if text else "" + Each source entry returned is a dictionary with keys: + - "title": The source title (single-line whitespace collapsed) + - "publ": The publication or URL (single-line whitespace collapsed) + - "note": The NOTE text for the source with original line breaks preserved + (CONT produces a newline, CONC concatenates). Empty continuation + lines are skipped. + The method handles two forms of source associations: + 1. Pointer-style references (1 SOUR @S1@) where @S1@ points to a separate + SOURCE record elsewhere in the GEDCOM file. In this case the referenced + SOURCE element's TITL/PUBL/NOTE children are resolved. + 2. Inline SOURCE blocks nested under the individual (1 SOUR ... with + sub-tags at level 2). These are read directly from the child's children. + + Notes are resolved via the shared resolve_gedcom_text helper so pointer + references and inline NOTE children are handled consistently. + """ sources = [] for child in self.element.get_child_elements(): if child.get_tag() != "SOUR": @@ -446,7 +527,8 @@ class Individual: # child may be a pointer to a SOURCE record or an inline SOURCE element src_ref = child.get_value() or "" - if src_ref and src_ref.startswith("@"): + # Treat as a pointer only if it both starts and ends with '@' (e.g., @S1@) + if src_ref and src_ref.startswith("@") and src_ref.endswith("@"): elem_to_scan = self.gedcom.get_element_dictionary().get(src_ref) or child else: elem_to_scan = child @@ -462,8 +544,8 @@ class Individual: note_text = self._resolve_gedcom_text(raw_note, sc) # Normalize whitespace for title/publ but preserve line breaks in notes - title = _collapse_single_line(title) - publ = _collapse_single_line(publ) + title = collapse_single_line(title) + publ = collapse_single_line(publ) note_text = self._collapse_preserve_lines(note_text) diff --git a/src/markdown_generator.py b/src/markdown_generator.py index fe301ac..94c2850 100644 --- a/src/markdown_generator.py +++ b/src/markdown_generator.py @@ -10,7 +10,7 @@ from typing import List, Optional import logging import re -from individual import Individual +from individual import Individual, collapse_single_line, resolve_gedcom_text logger = logging.getLogger(__name__) @@ -468,8 +468,15 @@ class MarkdownGenerator: f.write("\n") def _collapse_single_line(self, text: str) -> str: - """Collapse runs of whitespace into single spaces and strip the result.""" - return " ".join(text.split()).strip() if text else "" + """Normalize a single-line string's internal whitespace. + + This is a thin adapter that delegates to the shared collapse_single_line + helper located in the individual module. It is kept on the generator + class for convenience and to match the previous API; callers should use + this method when normalizing titles and publication strings that must + not contain extra internal whitespace. + """ + return collapse_single_line(text) def _collapse_preserve_lines(self, text: str) -> str: """Collapse runs of whitespace within each line but preserve line breaks. @@ -503,8 +510,8 @@ class MarkdownGenerator: Write the "Sources" section for an individual as a numbered list. Each source will include the formatted title/publication on the numbered line - and, if present, the source's NOTE text will be written indented beneath it - (formatted in italic to match the generated index). + and, if present, the source's NOTE text will be written as an indented + escaped note block beneath it (nested, non-italicized) to avoid accidental Markdown emphasis. """ sources = individual.get_sources() if not sources: @@ -523,94 +530,104 @@ class MarkdownGenerator: f.write("\n") def _generate_sources_index(self, parser): - """ - Generate a summary Index.md in a sources/ subdirectory listing all SOURCE records found in the GEDCOM element dictionary. + """Generate a global sources Index.md from the GEDCOM element dictionary. + + This method scans the parser's element dictionary for SOURCE (SOUR) + records and writes a single streamed Index.md file inside the output + 'sources/' directory. To avoid using excessive memory when many source + records exist, entries are written to disk as they are discovered rather + than being accumulated in memory. + + The created Index.md contains a numbered list of sources; if a source + has associated NOTE text, the NOTE is written as a nested, escaped + indented block beneath the numbered entry. The function repairs certain + HTML tags that may have been split across GEDCOM CONT lines and escapes + markdown emphasis characters in NOTE lines to avoid accidental + formatting. + + The method sets the generator's _sources_index_generated flag on success + or when encountering unrecoverable errors so that subsequent calls avoid + re-scanning the element dictionary. """ try: elem_dict = parser.get_element_dictionary() + except (AttributeError, ValueError) as e: + logger.exception("Failed to retrieve GEDCOM element dictionary for sources index: %s", e) + # Prevent repeated attempts on failure + self._sources_index_generated = True + return except Exception: + # Unexpected failure type: log at debug and mark generated to avoid retry storms + logger.exception("Unexpected error retrieving GEDCOM element dictionary for sources index") + self._sources_index_generated = True return - sources = [] - for elem in elem_dict.values(): - try: - if elem.get_tag() != "SOUR": - continue - except Exception: - continue - - title = "" - publ = "" - note_text = "" - - for sc in elem.get_child_elements(): - tag = sc.get_tag() - if tag == "TITL": - title = sc.get_value() or "" - elif tag == "PUBL": - publ = sc.get_value() or "" - elif tag == "NOTE": - note_val = sc.get_value() or "" - if note_val.startswith("@") and note_val.endswith("@"): - n_elem = elem_dict.get(note_val) - if n_elem: - note_text = n_elem.get_value() or "" - for sub in n_elem.get_child_elements(): - tag_sub = sub.get_tag() - val_sub = (sub.get_value() or "") - if not val_sub: - continue - if tag_sub == "CONC": - note_text += val_sub - elif tag_sub == "CONT": - note_text += "\n" + val_sub - else: - note_text = note_val - for sub in sc.get_child_elements(): - tag_sub = sub.get_tag() - val_sub = (sub.get_value() or "") - if not val_sub: - continue - if tag_sub == "CONC": - note_text += val_sub - elif tag_sub == "CONT": - note_text += "\n" + val_sub - - title = self._collapse_single_line(title) - publ = self._collapse_single_line(publ) - note_text = self._collapse_preserve_lines(note_text) - - if title or publ or note_text: - sources.append({"title": title, "publ": publ, "note": note_text}) - - if not sources: - return - - # Prefer a global 'sources' directory at the top-level output when using - # the organized subdirectory layout (people/, stories/, media/). The - # generator's output_dir is typically the people/ directory in that - # case, so use its parent as the global output root. + # Stream sources to the Index.md file as we discover them to avoid + # accumulating a potentially very large in-memory list. if self.use_subdirectories and self.output_dir and self.output_dir.parent: sources_dir = self.output_dir.parent / "sources" else: sources_dir = self.output_dir / "sources" + written_any = False + i = 0 + + # Prepare the directory but delay creating the file until we have at least + # one source entry to write. We'll open the file and stream entries as we + # find them. sources_dir.mkdir(parents=True, exist_ok=True) index_file = sources_dir / "Index.md" with open(index_file, "w", encoding="utf-8") as f: f.write("# Sources Index\n\n") - for i, src in enumerate(sources, 1): - entry = self._format_source_entry(src.get("title", ""), src.get("publ", "")) - f.write(f"{i}. {entry}\n") - note_text = src.get("note", "") - if note_text: - # Repair broken HTML tags and escape markdown - note_text = self._repair_broken_html_tags(note_text) - lines = [self._escape_markdown(ln) for ln in note_text.splitlines()] - self._write_multiline_note_block(f, lines, nested=True) + + for elem in elem_dict.values(): + try: + if elem.get_tag() != "SOUR": + continue + except (AttributeError, ValueError) as e: + logger.debug("Skipping non-source element or malformed element during sources scan: %s", e) + continue + + title = "" + publ = "" + note_text = "" + + for sc in elem.get_child_elements(): + tag = sc.get_tag() + if tag == "TITL": + title = sc.get_value() or "" + elif tag == "PUBL": + publ = sc.get_value() or "" + elif tag == "NOTE": + note_val = sc.get_value() or "" + # Use shared resolver to handle pointer vs inline NOTE with CONT/CONC semantics + note_text = resolve_gedcom_text(parser, note_val, sc) + + title = self._collapse_single_line(title) + publ = self._collapse_single_line(publ) + note_text = self._collapse_preserve_lines(note_text) + + if title or publ or note_text: + i += 1 + entry = self._format_source_entry(title, publ) + f.write(f"{i}. {entry}\n") + if note_text: + # Repair broken HTML tags and escape markdown + note_text = self._repair_broken_html_tags(note_text) + lines = [self._escape_markdown(ln) for ln in note_text.splitlines()] + self._write_multiline_note_block(f, lines, nested=True) + written_any = True + f.write("\n") + # If nothing was actually written, remove the empty index file + if not written_any and index_file.exists(): + try: + index_file.unlink() + except Exception: + pass + # Mark that the global sources index has been generated so we don't do this again self._sources_index_generated = True @@ -630,13 +647,23 @@ class MarkdownGenerator: return text def _repair_broken_html_tags(self, text: str) -> str: - """Repair HTML tags that were broken across lines for a small whitelist of tags. + """Repair a small set of HTML tags that may have been split across GEDCOM lines. - Strategy: - - Find all substrings that look like tags (<...>), possibly spanning lines. - - For each tag, remove newlines inside the tag only if the tag name (after - removing newlines) is in a safe whitelist. This joins broken tag names - like "" into "
" while leaving other tags alone. + Some GEDCOM exports break existing HTML fragments across CONT/CONC lines, + which can cause HTML tags (e.g. "
") to be split such that Markdown + or HTML rendering becomes corrupted (for example "" becoming a + literal ""). This function attempts a conservative + repair for a safe whitelist of simple tags by removing newline and + carriage return characters that occur inside a single tag token. + + Notes: + - This is intentionally conservative: it does not attempt to join broken + attributes or complex tags, and it only acts on a small whitelist of + tag names commonly used in source text (br, b, i, strong, em, a, + span, div, p, ul, li). + - The function preserves all other tag-like text unchanged. + + Returns the (possibly repaired) text. """ if not text or '<' not in text: return text @@ -659,15 +686,34 @@ class MarkdownGenerator: return re.sub(r'<[^>]*>', repl, text, flags=re.DOTALL) def _write_multiline_note_block(self, f, lines: List[str], nested: bool = True) -> None: - """Write a multi-line note block. + """Write a multi-line NOTE block into the open file. - - If nested is True, writes a nested list bullet (3 spaces + '-') for the first - line and indented continuation lines for the rest. All lines except the - last will end with two trailing spaces to force a hard line break; the - final CONT line is written without the trailing spaces to avoid an extra - blank line after the block. - - If nested is False, writes plain lines; trailing two spaces are added to - all but the last non-empty line. + This helper emits a block representing multi-line note text in a way that + is maximally compatible with common Markdown renderers used by editors + like Obsidian, BBEdit, and Nova. Two behaviors are supported: + + - nested=True: Emit a nested list item. The first line is written as a + nested bullet (" - first line"). Continuation lines are indented + and written beneath the bullet. All continuation lines except the + final one are suffixed with two spaces to generate an explicit + hard-break (
) in Markdown renderers. The final line is written + without trailing spaces so the block does not create an extra blank + paragraph after it. + + - nested=False: Emit plain lines (no list bullet). All non-empty lines + except the last non-empty line are suffixed with two spaces. Empty + input lines are preserved as blank lines. + + Parameters: + f: file-like writable object opened with utf-8 encoding. + lines: list of text lines (already escaped if required). + nested: whether to render the block as a nested list under a parent + list item (True) or as a flat paragraph/list of lines (False). + + Rationale: + Trailing two spaces are used to force
behavior in many Markdown + renderers. The special handling of the final line avoids producing an + extra blank paragraph after the note block. """ if not lines: return @@ -690,12 +736,16 @@ class MarkdownGenerator: f.write(f"{cont_indent}{cont}\n") else: # Non-nested: add two spaces to all non-empty lines except the last non-empty - non_empty = [ln for ln in lines if ln.strip()] - last_non_empty = non_empty[-1] if non_empty else None - for ln in lines: + # Determine the index of the last non-empty line to make the decision + # deterministic even when the same line text appears multiple times. + last_non_empty_idx = next( + (idx for idx in range(len(lines) - 1, -1, -1) if lines[idx].strip()), + None, + ) + for idx, ln in enumerate(lines): if not ln.strip(): f.write("\n") - elif ln == last_non_empty: + elif idx == last_non_empty_idx: f.write(f"{ln}\n") else: f.write(f"{ln} \n") diff --git a/tests/test_notes_cont_conc.py b/tests/test_notes_cont_conc.py index b919df9..e524ed6 100644 --- a/tests/test_notes_cont_conc.py +++ b/tests/test_notes_cont_conc.py @@ -1,8 +1,8 @@ from pathlib import Path -from src.gedcom_parser import GedcomParser -from src.individual import Individual -from src.markdown_generator import MarkdownGenerator +from gedcom_parser import GedcomParser +from individual import Individual +from markdown_generator import MarkdownGenerator def _make_output_dir(tmp_path): @@ -12,19 +12,18 @@ def _make_output_dir(tmp_path): class TestNotesContConc: - def test_note_cont_and_conc_inline(self, tmp_path): + def test_note_cont_and_conc_inline_in_indi(self, tmp_path): gedcom = """0 HEAD 1 SOUR TestApp 1 GEDC 2 VERS 5.5.1 1 CHAR UTF-8 -0 @N1@ NOTE -1 CONT First line -1 CONC -continued -1 CONT Next paragraph 0 @I1@ INDI 1 NAME John /Doe/ -1 NOTE @N1@ +1 NOTE +2 CONT First line +2 CONC -continued +2 CONT Next paragraph 0 TRLR """ f = tmp_path / "note.ged" -- 2.36.6 From c68264978de73f6b588ed88eeca6f7998887c46d Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 18 Apr 2026 04:07:32 +0000 Subject: [PATCH 8/8] fix: apply code review feedback on CONT handling, retry guard, title escaping, lazy file open, and 4-space indent Agent-Logs-Url: https://github.com/jaredhowland/gedcom-to-markdown/sessions/6c8ce2c8-7699-47a3-99f1-909cfa5ac7cd Co-authored-by: jaredhowland <1877384+jaredhowland@users.noreply.github.com> --- src/individual.py | 17 +++++++------- src/markdown_generator.py | 47 +++++++++++++++++++++------------------ 2 files changed, 34 insertions(+), 30 deletions(-) diff --git a/src/individual.py b/src/individual.py index cccb3d6..80a61c2 100644 --- a/src/individual.py +++ b/src/individual.py @@ -81,28 +81,29 @@ def resolve_gedcom_text(parser, value: str, element=None) -> str: if not target: return "" text = target.get_value() or "" - # Respect CONT vs CONC semantics: CONT => newline, CONC => concatenate + # Respect CONT vs CONC semantics: CONT => newline, CONC => concatenate. + # An empty CONT line represents a blank line in GEDCOM and must still + # contribute a newline so paragraph breaks are preserved. for sub in target.get_child_elements(): tag = sub.get_tag() val = (sub.get_value() or "") - if not val: - continue if tag == "CONC": - text += val + if val: + text += val elif tag == "CONT": text += "\n" + val return text - # Inline text with possible CONT/CONC children + # Inline text with possible CONT/CONC children. + # Same rule: empty CONC is a no-op, but empty CONT preserves a blank line. text = value or "" if element is not None: for sub in element.get_child_elements(): tag = sub.get_tag() val = (sub.get_value() or "") - if not val: - continue if tag == "CONC": - text += val + if val: + text += val elif tag == "CONT": text += "\n" + val return text diff --git a/src/markdown_generator.py b/src/markdown_generator.py index 0d8fbfb..69b849c 100644 --- a/src/markdown_generator.py +++ b/src/markdown_generator.py @@ -136,6 +136,8 @@ class MarkdownGenerator: self._generate_sources_index(parser) except Exception: logger.exception('Failed to generate sources index') + # Prevent repeated expensive retries on persistent failures (e.g., IO/permissions) + self._sources_index_generated = True return file_path @@ -526,14 +528,16 @@ class MarkdownGenerator: If title and publ are present, title is rendered as a link to publ. If only title present, render plain title. If only publ present, use the URL as link text. + Title text is escaped to prevent markdown emphasis characters from triggering formatting. """ title = self._collapse_single_line(title) publ = self._collapse_single_line(publ) + escaped_title = self._escape_markdown(title) if title and publ: - return f"[{title}]({publ})" + return f"[{escaped_title}]({publ})" if title: - return title + return escaped_title if publ: return f"[{publ}]({publ})" return "(Unknown source)" @@ -602,18 +606,13 @@ class MarkdownGenerator: else: sources_dir = self.output_dir / "sources" - written_any = False i = 0 - - # Prepare the directory but delay creating the file until we have at least - # one source entry to write. We'll open the file and stream entries as we - # find them. - sources_dir.mkdir(parents=True, exist_ok=True) index_file = sources_dir / "Index.md" - with open(index_file, "w", encoding="utf-8") as f: - f.write("# Sources Index\n\n") - + # Delay creating the file and directory until the first source is found so + # that no empty Index.md is left behind when there are no SOUR records. + f = None + try: for elem in elem_dict.values(): try: if elem.get_tag() != "SOUR": @@ -642,6 +641,11 @@ class MarkdownGenerator: note_text = self._collapse_preserve_lines(note_text) if title or publ or note_text: + if f is None: + # First source found: create directory and open file + sources_dir.mkdir(parents=True, exist_ok=True) + f = open(index_file, "w", encoding="utf-8") + f.write("# Sources Index\n\n") i += 1 entry = self._format_source_entry(title, publ) f.write(f"{i}. {entry}\n") @@ -650,16 +654,12 @@ class MarkdownGenerator: note_text = self._repair_broken_html_tags(note_text) lines = [self._escape_markdown(ln) for ln in note_text.splitlines()] self._write_multiline_note_block(f, lines, nested=True) - written_any = True - f.write("\n") - - # If nothing was actually written, remove the empty index file - if not written_any and index_file.exists(): - try: - index_file.unlink() - except Exception: - pass + if f is not None: + f.write("\n") + finally: + if f is not None: + f.close() # Mark that the global sources index has been generated so we don't do this again self._sources_index_generated = True @@ -753,8 +753,11 @@ class MarkdownGenerator: total = len(lines) if nested: - indent = " " - cont_indent = " " + # Use 4-space indent so nested content is correctly parsed as continuation + # of the parent ordered list item even for multi-digit list numbers (e.g. "10.") + # in CommonMark-compliant renderers. + indent = " " + cont_indent = " " # First line as a nested bullet; add two spaces if there are continuation lines if total > 1: f.write(f"{indent}- {lines[0]} \n") -- 2.36.6