Merge remote-tracking branch 'origin/initial_features' into initial_features

This commit is contained in:
AlexKucera committed 2025-11-01 14:22:11 +01:00
commit ecd9889e21
5 files changed
+283 -147

No files matched your search

+20 -22
View File
@@ -26,14 +26,14 @@ class GedcomParser:
def __init__(self, file_path: Path):
"""
Initialize the parser with a GEDCOM file.
Args:
file_path: Path to the GEDCOM file to parse
Initialize the GedcomParser with a GEDCOM file path and parse its contents.
Parameters:
file_path (Path): Path to the GEDCOM file to open and parse.
Raises:
FileNotFoundError: If the GEDCOM file doesn't exist
ValueError: If the file cannot be parsed
FileNotFoundError: If the GEDCOM file does not exist.
ValueError: If parsing the GEDCOM file fails.
"""
if not file_path.exists():
raise FileNotFoundError(f"GEDCOM file not found: {file_path}")
@@ -53,11 +53,9 @@ class GedcomParser:
def _fix_line_endings_if_needed(self):
"""
Check if GEDCOM file has CR-only line endings and fix them.
Some macOS applications export GEDCOM files with old Mac-style
CR-only line endings, which the parser cannot handle. This method
detects and fixes such files automatically.
Convert CR-only (old Mac) line endings in the GEDCOM file to LF if detected.
If the file is found to use CR-only line endings, this method replaces CR with LF in-place on disk and logs a warning before the change and an informational message after successful rewriting.
"""
# Read first chunk to check line endings
with open(self.file_path, "rb") as f:
@@ -90,10 +88,10 @@ class GedcomParser:
def get_individuals(self) -> List[IndividualElement]:
"""
Get all individuals from the GEDCOM file.
Return all IndividualElement objects extracted from the parsed GEDCOM file.
Returns:
List of IndividualElement objects representing people in the tree
List[IndividualElement]: A list of individuals found in the GEDCOM root elements.
"""
individuals = []
for element in self.parser.get_root_child_elements():
@@ -105,12 +103,12 @@ class GedcomParser:
def get_element_by_pointer(self, pointer: str):
"""
Get a GEDCOM element by its pointer/ID.
Args:
pointer: The GEDCOM pointer (e.g., '@I123@')
Retrieve a GEDCOM element by its pointer/ID.
Parameters:
pointer (str): GEDCOM pointer string (e.g., '@I123@').
Returns:
The element with the given pointer, or None if not found
The element with the given pointer, or `None` if not found.
"""
return self.parser.get_element_dictionary().get(pointer)
return self.parser.get_element_dictionary().get(pointer)
+15 -13
View File
@@ -24,11 +24,11 @@ class IndexGenerator:
def __init__(self, output_dir: Path, people_subdir: str = ""):
"""
Initialize the index generator.
Args:
output_dir: Directory where the index file will be created
people_subdir: Subdirectory where people files are stored (e.g., 'people')
Create an IndexGenerator configured with the target output directory and an optional subdirectory for individual files.
Parameters:
output_dir (Path): Directory where the generated index file will be written.
people_subdir (str): Optional subdirectory name to prepend to people file links (empty string means no subdirectory).
"""
self.output_dir = output_dir
self.people_subdir = people_subdir
@@ -37,14 +37,16 @@ class IndexGenerator:
self, individuals: List[Individual], index_filename: str = "Index.md"
) -> Path:
"""
Generate an alphabetical index of all individuals.
Args:
individuals: List of Individual objects
index_filename: Name of the index file (default: 'Index.md')
Generate an alphabetical Markdown index of individuals grouped by last-name initial.
Writes a Markdown file at self.output_dir / index_filename containing a header with the total count, section headers "## {LETTER}" for each last-name initial (uses "#" for individuals without a last name), and one wiki-style link per individual (prefixed by the instance's people_subdir when set). Each entry includes an optional life-span "(birth-death)" when birth or death information is available.
Parameters:
individuals (List[Individual]): Individuals to include in the index.
index_filename (str): Name of the index file to create (default: 'Index.md').
Returns:
Path to the created index file
Path: Path to the created index file.
"""
index_path = self.output_dir / index_filename
@@ -97,4 +99,4 @@ class IndexGenerator:
f.write(f"- {wiki_link}{life_span}\n")
logger.info(f"Index generated with {len(individuals)} individuals")
return index_path
return index_path
+89 -56
View File
@@ -26,48 +26,52 @@ class Individual:
def __init__(self, element: IndividualElement, gedcom_parser):
"""
Initialize an Individual from a GEDCOM element.
Args:
element: The GEDCOM IndividualElement
gedcom_parser: The GedcomParser instance for resolving references
Create an Individual wrapper around a GEDCOM individual element and its parser.
Stores the provided IndividualElement and the parser reference (gedcom_parser.parser) used to resolve cross-references.
Parameters:
element (IndividualElement): The GEDCOM individual element to wrap.
gedcom_parser: The GedcomParser instance whose `parser` attribute will be used for resolving references.
"""
self.element = element
self.gedcom = gedcom_parser.parser
def get_id(self) -> str:
"""Get the GEDCOM ID without @ symbols."""
return self.element.get_pointer().replace("@", "")
"""
Provide the GEDCOM identifier for this individual without surrounding '@' characters.
Returns:
str: The GEDCOM identifier with all '@' characters removed.
"""
return self.element.get_pointer().replace('@', '')
def get_names(self) -> Tuple[str, str]:
"""
Get the person's names.
Return the individual's first and last name with surrounding whitespace removed.
Returns:
Tuple of (first_name, last_name)
tuple(first_name, last_name): The person's given name and family name, both trimmed of leading and trailing whitespace.
"""
first, last = self.element.get_name()
return first.strip(), last.strip()
def get_full_name(self) -> str:
"""
Get the full name in 'FirstName LastName' format.
Return the individual's full name formatted as "First Last".
Returns:
Full name with proper capitalization
Full name string in title case (e.g., "John Doe"); empty string if no name parts exist.
"""
first, last = self.get_names()
return f"{first} {last}".strip().title()
def get_file_name(self) -> str:
"""
Get the filename for this person's note.
Format: 'FamilyName FirstName BirthYear'
If no birth year is known, year is omitted.
Build a filename-like string for the individual in the form "FamilyName FirstName" optionally followed by the birth year.
Returns:
Filename without .md extension
filename (str): The generated filename string, either "FamilyName FirstName BirthYear" or "FamilyName FirstName" when the birth year is not available; does not include a file extension.
"""
first, last = self.get_names()
name_part = f"{last} {first}".strip().title()
@@ -79,10 +83,13 @@ class Individual:
def get_birth_info(self) -> Dict[str, str]:
"""
Get birth information.
Retrieve the person's birth date, place, and year from the underlying GEDCOM element.
Returns:
Dictionary with 'date', 'place', 'year' keys
dict: A dictionary with keys:
- 'date' (str): Birth date string or '' if unavailable.
- 'place' (str): Birth place string or '' if unavailable.
- 'year' (str): Birth year as a string or '' if the year is unknown.
"""
date, place, sources = self.element.get_birth_data()
year = self.element.get_birth_year()
@@ -95,25 +102,32 @@ class Individual:
def get_death_info(self) -> Dict[str, str]:
"""
Get death information.
Provide the individual's death date and place.
Returns:
Dictionary with 'date', 'place' keys
dict: Dictionary with keys:
- date (str): Death date as a string, or '' if unknown.
- place (str): Death place as a string, or '' if unknown.
"""
date, place, sources = self.element.get_death_data()
return {"date": date or "", "place": place or ""}
def get_gender(self) -> str:
"""Get the person's gender (M/F/U)."""
return self.element.get_gender() or "U"
"""
Return the person's gender code.
Returns:
str: `'M'` for male, `'F'` for female, `'U'` if unspecified or unknown.
"""
return self.element.get_gender() or 'U'
def get_parents(self) -> List["Individual"]:
"""
Get this person's parents.
Retrieve the person's parents.
Returns:
List of Individual objects representing parents
A list of Individual objects representing the person's parents.
"""
parent_elements = self.gedcom.get_parents(self.element)
return [
@@ -123,10 +137,10 @@ class Individual:
def get_children(self) -> List["Individual"]:
"""
Get this person's children.
Retrieve the person's children as Individual objects.
Returns:
List of Individual objects representing children
children (List[Individual]): A list of Individual instances corresponding to this person's children.
"""
children = []
for family in self.gedcom.get_families(self.element):
@@ -141,10 +155,12 @@ class Individual:
def get_partners(self) -> List["Individual"]:
"""
Get this person's spouses/partners.
Retrieve this individual's spouses and partners.
Each partner is resolved to an Individual wrapper; the subject is excluded from the result.
Returns:
List of Individual objects representing partners
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):
@@ -211,10 +227,14 @@ class Individual:
def get_events(self) -> List[Dict[str, str]]:
"""
Get all life events for this person.
Collects the individual's life events found on the GEDCOM element.
Returns:
List of dictionaries with 'type', 'date', 'place' keys
List[dict]: Each dictionary represents an event with keys:
- 'type' (str): GEDCOM event tag (e.g., 'BIRT', 'DEAT', 'MARR', 'OCCU', 'EDUC', 'RESI', 'BURI').
- 'date' (str): Event date value if present, otherwise an empty string.
- 'place' (str): Event place value if present, otherwise an empty string.
- 'details' (str): The raw value of the event node (empty string if absent).
"""
events = []
@@ -243,10 +263,12 @@ class Individual:
def get_images(self) -> List[Dict[str, str]]:
"""
Get all image/media references for this person.
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 of dictionaries with 'file', 'title', 'format' keys
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.
"""
images = []
@@ -275,10 +297,12 @@ class Individual:
def get_notes(self) -> List[str]:
"""
Get all notes for this person.
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 of note texts
List[str]: Note texts with continuations and referenced NOTE content merged; empty or unresolved notes are omitted.
"""
notes = []
@@ -311,14 +335,22 @@ class Individual:
def get_stories(self) -> List[Dict]:
"""
Get stories/narratives for this person.
Some genealogy programs (like MobileFamilyTree) use custom _STO
tags for storing longer narratives and stories about individuals.
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)
- `description` (str): story-level description (or empty string)
- `sections` (List[Dict]): ordered list of sections; each section dictionary contains:
- `subtitle` (str): section title (or empty string)
- `text` (str): section text with `CONT`/`CONC` continuations concatenated (or empty string)
- `images` (List[Dict]): list of image dictionaries resolved from `OBJE` references; each image dictionary contains:
- `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 of dictionaries with 'title', 'sections' keys
Each section has 'subtitle', 'text', 'images'
List[Dict]: list of story dictionaries; empty list if no stories are found.
"""
stories = []
@@ -406,10 +438,11 @@ class Individual:
def get_attributes(self) -> Dict[str, str]:
"""
Get physical attributes and other personal details.
Collect physical attributes from the underlying GEDCOM individual element.
Returns:
Dictionary with attribute names as keys
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.
"""
attributes = {}
@@ -420,4 +453,4 @@ class Individual:
if tag in ["EYES", "HAIR", "HEIG"]:
attributes[tag.lower()] = child.get_value() or ""
return attributes
return attributes
Executable → Regular
+38 -22
View File
@@ -22,7 +22,15 @@ from index_generator import IndexGenerator
def setup_logging(verbose: bool = False):
"""Configure logging for the application."""
"""
Configure root logger formatting and level for the application.
Sets the logging level to DEBUG when `verbose` is True, otherwise to INFO.
Also applies a consistent message format and timestamp date format used across the application.
Parameters:
verbose (bool): When True, enable DEBUG-level logging; otherwise use INFO-level logging.
"""
level = logging.DEBUG if verbose else logging.INFO
logging.basicConfig(
level=level,
@@ -33,17 +41,18 @@ def setup_logging(verbose: bool = False):
def extract_gedzip(zip_path: Path, temp_dir: Path) -> Tuple[Path, Optional[Path]]:
"""
Extract a GEDZIP file and locate the GEDCOM file and media directory.
Args:
zip_path: Path to the ZIP/GEDZIP file
temp_dir: Temporary directory for extraction
Extracts a ZIP/GEDZIP archive and locates the GEDCOM file and an optional media directory.
Searches the extracted contents for the first `.ged` file and for image files (jpg, jpeg, png, gif, bmp)
to identify a media directory.
Returns:
Tuple of (gedcom_file_path, media_directory_path)
A tuple `(gedcom_file_path, media_directory_path)` where `gedcom_file_path` is the path to the found
GEDCOM file and `media_directory_path` is the path to the directory containing media files or `None`
if no media files were found.
Raises:
ValueError: If no GEDCOM file is found in the archive
ValueError: If no GEDCOM (`.ged`) file is found in the archive.
"""
logger = logging.getLogger(__name__)
logger.info(f"Extracting ZIP archive: {zip_path}")
@@ -89,17 +98,17 @@ def convert_gedcom_to_markdown(
use_flat_structure: bool = False,
) -> int:
"""
Convert a GEDCOM file to markdown notes.
Args:
gedcom_file: Path to the input GEDCOM file
output_dir: Directory for output markdown files
create_index: Whether to create an index file
media_dir: Optional directory containing media files to copy
use_flat_structure: If True, use flat structure. If False, create subdirectories.
Convert a GEDCOM file into Obsidian-compatible Markdown notes organized on disk.
Parameters:
gedcom_file (Path): Path to the input GEDCOM file.
output_dir (Path): Directory where generated markdown, media, and story files will be written.
create_index (bool): Whether to generate an index file linking the generated person notes.
media_dir (Optional[Path]): Optional source directory of media files to copy into the output media directory.
use_flat_structure (bool): If True, write all outputs directly into `output_dir`; if False, create subdirectories (`people/`, `media/`, `stories/`).
Returns:
Exit code (0 for success, non-zero for failure)
int: 0 on success, 1 on failure.
"""
logger = logging.getLogger(__name__)
@@ -196,7 +205,14 @@ def convert_gedcom_to_markdown(
def main():
"""Main entry point for the CLI."""
"""
Run the command-line interface to convert a GEDCOM or GEDZIP archive into Obsidian-compatible Markdown notes.
Parses CLI arguments, prepares input and output paths (extracting archives to a temporary directory when needed), invokes the conversion process, and cleans up any temporary files.
Returns:
int: Exit code where `0` indicates success and `1` indicates failure.
"""
parser = argparse.ArgumentParser(
description="Convert GEDCOM genealogy files to Obsidian markdown notes",
epilog="Example: python src/main.py --input family.zip --output vault/family",
@@ -279,4 +295,4 @@ def main():
if __name__ == "__main__":
sys.exit(main())
sys.exit(main())
+121 -34
View File
@@ -31,16 +31,16 @@ class MarkdownGenerator:
stories_dir: Optional[Path] = None,
):
"""
Initialize the generator.
Args:
output_dir: Directory where markdown files will be created
media_subdir: Subdirectory for media files (e.g., 'media')
stories_subdir: Subdirectory for story files (e.g., 'stories')
stories_dir: Directory where story markdown files will be created
Configure the MarkdownGenerator with paths and optional subdirectories for media and story files.
Parameters:
output_dir (Path): Directory where markdown notes will be written; must exist and be a directory.
media_subdir (str): Optional subdirectory name (relative) to prefix media/image paths in notes.
stories_subdir (str): Optional subdirectory name (relative) to use when constructing wiki links to generated story notes.
stories_dir (Optional[Path]): Optional directory where story markdown files will be created; defaults to `output_dir` when not provided.
Raises:
ValueError: If output_dir doesn't exist or isn't a directory
ValueError: If `output_dir` does not exist or is not a directory.
"""
if not output_dir.exists():
raise ValueError(f"Output directory doesn't exist: {output_dir}")
@@ -55,13 +55,13 @@ class MarkdownGenerator:
def generate_note(self, individual: Individual) -> Path:
"""
Generate a markdown note for an individual.
Args:
individual: The Individual to create a note for
Create a markdown file for the given individual containing header, attributes, events, families, parents, children, images, and notes sections.
Parameters:
individual (Individual): The individual for whom to generate the note.
Returns:
Path to the created markdown file
Path: Path to the created markdown file.
"""
filename = individual.get_file_name() + ".md"
file_path = self.output_dir / filename
@@ -82,11 +82,25 @@ class MarkdownGenerator:
return file_path
def _write_header(self, f, individual: Individual):
"""Write the note header with main name."""
"""
Write the main markdown header containing the individual's full name.
Parameters:
f (IO[str]): Open text file or writable stream to receive markdown content.
individual (Individual): Person whose full name is written as the top-level header.
"""
f.write(f"# {individual.get_full_name()}\n\n")
def _write_attributes(self, f, individual: Individual):
"""Write basic attributes section."""
"""
Write the "Attributes" section to the provided file for the given individual.
This emits visible metadata entries for ID, Name, Lived (birth–death years), Sex, birth date/place, death date/place, and any additional non-empty physical attributes provided by the individual. The section is prefixed with "## Attributes" and terminated with a blank line.
Parameters:
f: A text-mode file-like object opened for writing.
individual: An Individual instance supplying ID, name, birth/death info, gender, and additional attributes via its getter methods.
"""
f.write("## Attributes\n")
birth = individual.get_birth_info()
@@ -122,7 +136,15 @@ class MarkdownGenerator:
f.write("\n")
def _write_events(self, f, individual: Individual):
"""Write life events section."""
"""
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'.
"""
events = individual.get_events()
# Filter out birth and death (already in attributes)
@@ -157,7 +179,15 @@ class MarkdownGenerator:
f.write("\n")
def _write_families(self, f, individual: Individual):
"""Write families/marriages section."""
"""
Write the "Families" section for an individual into the provided file handle.
Emits a "## Families" header and, for each family that has a partner, a "Marriage" subsection (numbered when the individual has multiple families). For each marriage the function writes hidden metadata entries for Partner (as a wiki link), Marriage date, Marriage place (if present), and lists each Child as hidden metadata (as wiki links). Adds spacing after each marriage and a trailing blank line after the section. If the individual has no families, nothing is written.
Parameters:
f (io.TextIO): Open text file handle to write the section into.
individual (Individual): The individual whose family records will be written.
"""
families = individual.get_families()
if not families:
@@ -192,7 +222,15 @@ class MarkdownGenerator:
f.write("\n")
def _write_parents(self, f, individual: Individual):
"""Write parents section."""
"""
Write the Parents section for an individual note.
If the individual has one or more parents, writes a "## Parents" heading followed by a hidden Obsidian metadata entry for each parent containing a wiki link to the parent's note. If the individual has no parents, the function writes nothing.
Parameters:
f: A writable file-like object opened for the individual's markdown note.
individual (Individual): The individual whose parents should be written.
"""
parents = individual.get_parents()
if not parents:
@@ -208,7 +246,11 @@ class MarkdownGenerator:
f.write("\n")
def _write_children(self, f, individual: Individual):
"""Write children section (if not already in families)."""
"""
Write a "Children" section listing each child as hidden Obsidian metadata with a wiki link.
Does nothing if the individual has any families or has no children.
"""
# Skip if we already wrote families section
if individual.get_families():
return
@@ -228,7 +270,15 @@ class MarkdownGenerator:
f.write("\n")
def _write_images(self, f, individual: Individual):
"""Write images section."""
"""
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'.
"""
images = individual.get_images()
if not images:
@@ -250,14 +300,19 @@ class MarkdownGenerator:
def _generate_story_file(self, story: dict, individual_name: str) -> str:
"""
Generate a separate markdown file for a story.
Args:
story: Story dictionary with title, description, and sections
individual_name: Name of the individual this story belongs to
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.
- description (str | None): Optional short description placed under the title.
- sections (List[dict]): Ordered sections; each section may contain
'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:
Filename of the generated story (for WikiLink)
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.
"""
story_title = story["title"] if story["title"] else "Untitled Story"
# Create a safe filename
@@ -318,7 +373,15 @@ class MarkdownGenerator:
return filename.replace(".md", "")
def _write_notes(self, f, individual: Individual):
"""Write notes section."""
"""
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.
"""
notes = individual.get_notes()
stories = individual.get_stories()
@@ -362,15 +425,39 @@ class MarkdownGenerator:
f.write("\n")
def _write_metadata(self, f, key: str, value: str):
"""Write visible Obsidian metadata."""
"""
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]
"""
f.write(f"[{key}:: {value}]\n")
def _write_metadata_hidden(self, f, key: str, value: str):
"""Write hidden Obsidian metadata."""
"""
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.
value (str): Metadata value.
"""
f.write(f"({key}:: {value})\n")
def _wiki_link(self, text: str) -> str:
"""Format text as a WikiLink."""
"""
Format text as an Obsidian-style WikiLink.
Returns:
wiki_link (str): The input text wrapped in double square brackets (e.g. `[[Name]]`).
"""
return f"[[{text}]]"
def generate_all(self, individuals: List[Individual]) -> List[Path]:
@@ -396,4 +483,4 @@ class MarkdownGenerator:
)
logger.info(f"Successfully generated {len(paths)} notes")
return paths
return paths