Adds Obsidian Canvas family tree generation #3

Merged
AlexKucera merged 6 commits from canvas into main 2025-11-02 17:58:06 +01:00
6 changed files with 1558 additions and 35 deletions

No files matched your search

+2 -2
View File
@@ -127,6 +127,6 @@ dmypy.json
examples/
output/
test_output/
output/
+18 -1
View File
@@ -85,6 +85,8 @@ python src/main.py -i family.zip -o output --flat
- `-o`, `--output DIR`: Output directory for generated notes (required)
- `--flat`: Use flat structure (all files in output root). Default creates subdirectories
- `--no-index`: Skip creating the index file
- `--canvas`: Create an Obsidian canvas file for family tree visualization
- `--root ID`: Root person for canvas. Can be a selection number (e.g., `85`) or GEDCOM ID (e.g., `@I253884714@` or `I253884714`). If not provided with `--canvas`, will prompt interactively
- `--verbose` or `-v`: Enable detailed logging
### Examples
@@ -99,7 +101,22 @@ python src/main.py -i examples/family.zip -o examples/output --verbose
python src/main.py -i examples/family.ged -o examples/output --flat --verbose
```
**Using long-form arguments:**
**Generate family tree canvas with specific root person (by selection number):**
```bash
python src/main.py -i family.ged -o output --canvas --root 85
```
**Generate canvas with specific root person (by GEDCOM ID):**
```bash
python src/main.py -i family.ged -o output --canvas --root @I253884714@
```
**Generate canvas with interactive root person selection:**
```bash
python src/main.py -i family.ged -o output --canvas
```
**Using long form arguments:**
```bash
python src/main.py --input examples/family.zip --output examples/output
```
File diff suppressed because it is too large. Load diff
+66 -1
View File
@@ -41,12 +41,21 @@ class Individual:
def get_id(self) -> str:
"""
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_pointer(self) -> str:
"""
Get the full GEDCOM pointer/ID for this individual (with @ symbols).
Returns:
str: The GEDCOM pointer (e.g., '@I123@')
"""
return self.element.get_pointer()
def get_names(self) -> Tuple[str, str]:
"""
Return the individual's first and last name with surrounding whitespace removed.
@@ -224,6 +233,62 @@ class Individual:
return families
def get_families_as_child(self) -> List[Dict]:
"""
Get all families where this person is a child (to find parents).
Returns:
List of dictionaries with family information including:
- father: str (father's GEDCOM ID) or None
- mother: str (mother's GEDCOM ID) or None
"""
families = []
# 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 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")
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,
})
return families
def get_events(self) -> List[Dict[str, str]]:
"""
Collects the individual's life events found on the GEDCOM element.
+93 -31
View File
@@ -19,38 +19,56 @@ from gedcom_parser import GedcomParser
from individual import Individual
from markdown_generator import MarkdownGenerator
from index_generator import IndexGenerator
from canvas_generator import CanvasGenerator
from person_selector import select_root_person
def setup_logging(verbose: bool = False):
"""
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.
Sets the logging level to DEBUG when `verbose` is True, otherwise to INFO
for the main module only and WARNING for other modules.
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.
verbose (bool): When True, enable DEBUG-level logging for all modules;
otherwise use INFO-level logging for main module only.
"""
level = logging.DEBUG if verbose else logging.INFO
logging.basicConfig(
level=level,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
if verbose:
# Show all logs from all modules
level = logging.DEBUG
logging.basicConfig(
level=level,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
else:
# Only show INFO from main module, WARNING+ from others
logging.basicConfig(
level=logging.WARNING,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
# Enable INFO logging for main module only
logging.getLogger(__name__).setLevel(logging.INFO)
def extract_gedzip(zip_path: Path, temp_dir: Path) -> Tuple[Path, Optional[Path]]:
"""
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.
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:
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.
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 (`.ged`) file is found in the archive.
"""
@@ -100,17 +118,30 @@ def convert_gedcom_to_markdown(
create_index: bool = True,
media_dir: Optional[Path] = None,
use_flat_structure: bool = False,
create_canvas: bool = False,
root_id: Optional[str] = None,
) -> int:
"""
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/`).
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/`).
create_canvas (bool): Whether to generate an Obsidian canvas file for
family tree visualization.
root_id (Optional[str]): Root person identifier for canvas generation.
Can be a selection number (e.g., '85') or GEDCOM ID (e.g.,
'@I253884714@' or 'I253884714'). If not provided and create_canvas
is True, will prompt interactively.
Returns:
int: 0 on success, 1 on failure.
"""
@@ -151,6 +182,19 @@ def convert_gedcom_to_markdown(
# Wrap individuals in our data model
individuals = [Individual(elem, parser.parser) for elem in individual_elements]
# Generate canvas if requested
if create_canvas:
logger.info("Canvas generation requested")
root_person_id = select_root_person(individuals, root_id)
if root_person_id:
logger.info(f"Generating canvas with root person: {root_person_id}")
canvas_gen = CanvasGenerator(individuals, str(output_dir))
canvas_path = canvas_gen.generate_canvas(root_person_id)
logger.info(f"Canvas created: {canvas_path}")
else:
logger.warning("No root person selected, skipping canvas generation")
# Generate markdown notes
logger.info(f"Generating markdown notes in: {people_dir}")
generator = MarkdownGenerator(
@@ -245,10 +289,13 @@ def convert_gedcom_to_markdown(
def main():
"""
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.
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.
"""
@@ -285,6 +332,19 @@ def main():
"--no-index", action="store_true", help="Do not create an index file"
)
parser.add_argument(
"--canvas",
action="store_true",
help="Create an Obsidian canvas file for family tree visualization",
)
parser.add_argument(
"--root",
type=str,
metavar="ID",
help="Root person for canvas. Can be a selection number (e.g., 85) or GEDCOM ID (e.g., @I253884714@). If not provided, will prompt interactively.",
)
parser.add_argument(
"-v", "--verbose", action="store_true", help="Enable verbose logging"
)
@@ -322,6 +382,8 @@ def main():
create_index=not args.no_index,
media_dir=media_dir,
use_flat_structure=args.flat,
create_canvas=args.canvas,
root_id=args.root,
)
return exit_code
@@ -334,4 +396,4 @@ def main():
if __name__ == "__main__":
sys.exit(main())
sys.exit(main())
+155
View File
@@ -0,0 +1,155 @@
"""
Interactive person selector for choosing root person in family tree.
This module provides functionality to display individuals from a GEDCOM file
in a multi-column format and allow the user to select one as the root person
for canvas generation.
"""
import logging
from typing import List, Optional
from individual import Individual
logger = logging.getLogger(__name__)
def select_root_person(individuals: List[Individual], root_id: Optional[str] = None) -> Optional[str]:
"""
Display an interactive list of individuals and let user select root person.
Args:
individuals: List of Individual objects from GEDCOM file
root_id: Optional identifier for root person. Can be either:
- A numeric index from the selection list (e.g., '85')
- A GEDCOM ID (e.g., '@I253884714@' or 'I253884714')
If provided, validates and returns it. If not provided, prompts interactively.
Returns:
The GEDCOM pointer/ID of the selected individual, or None if cancelled
"""
if not individuals:
logger.error("No individuals provided for selection")
return None
# If root_id is provided, validate it and return it
if root_id:
# Check if it's a numeric index (e.g., "85")
if root_id.isdigit():
index = int(root_id)
# Sort individuals the same way as interactive selection
sorted_individuals = sorted(
individuals,
key=lambda ind: (
ind.get_names()[1] or "", # Last name
ind.get_names()[0] or "" # First name
)
)
if 1 <= index <= len(sorted_individuals):
selected = sorted_individuals[index - 1]
first_name, last_name = selected.get_names()
full_name = f"{last_name or ''} {first_name or ''}".strip()
logger.info(f"Using root person by index #{index}: {full_name} ({selected.get_pointer()})")
print(f"\nUsing root person: {full_name} ({selected.get_pointer()})")
return selected.get_pointer()
else:
logger.error(f"Root person index '{root_id}' out of range (1-{len(sorted_individuals)})")
print(f"\nError: Root person index '{root_id}' out of range (1-{len(sorted_individuals)})")
print("Falling back to interactive selection...\n")
# Fall through to interactive selection
else:
# Treat as GEDCOM ID - normalize by adding @ symbols if not present
normalized_id = root_id if root_id.startswith('@') else f'@{root_id}@'
# Find the individual with this ID
for individual in individuals:
if individual.get_pointer() == normalized_id:
first_name, last_name = individual.get_names()
full_name = f"{last_name or ''} {first_name or ''}".strip()
logger.info(f"Using provided root person: {full_name} ({normalized_id})")
print(f"\nUsing root person: {full_name} ({normalized_id})")
return normalized_id
# ID not found
logger.error(f"Root person ID '{root_id}' not found in GEDCOM file")
print(f"\nError: Root person ID '{root_id}' not found in GEDCOM file")
print("Falling back to interactive selection...\n")
# Fall through to interactive selection
# Sort individuals by last name, then first name
sorted_individuals = sorted(
individuals,
key=lambda ind: (
ind.get_names()[1] or "", # Last name
ind.get_names()[0] or "" # First name
)
)
print("\n" + "="*80)
print("SELECT ROOT PERSON FOR FAMILY TREE CANVAS")
print("="*80)
print(f"\nTotal individuals: {len(sorted_individuals)}\n")
# Display individuals in a numbered list with columns
# Format: Index | Name | Birth | Death
print(f"{'#':<5} {'Name':<40} {'Birth':<12} {'Death':<12}")
print("-" * 80)
for idx, individual in enumerate(sorted_individuals, start=1):
first_name, last_name = individual.get_names()
full_name = f"{last_name or ''} {first_name or ''}".strip()
# Get birth and death years
birth_year = ""
death_year = ""
events = individual.get_events()
for event in events:
if event["type"] == "BIRT" and event.get("date"):
# Extract year from date string (format varies)
date_str = event["date"]
# Try to find a 4-digit year
import re
year_match = re.search(r'\b(\d{4})\b', date_str)
if year_match:
birth_year = year_match.group(1)
elif event["type"] == "DEAT" and event.get("date"):
date_str = event["date"]
import re
year_match = re.search(r'\b(\d{4})\b', date_str)
if year_match:
death_year = year_match.group(1)
print(f"{idx:<5} {full_name:<40} {birth_year:<12} {death_year:<12}")
print("-" * 80)
# Prompt for selection
while True:
try:
selection = input("\nEnter number to select root person (or 'q' to quit): ").strip()
if selection.lower() == 'q':
logger.info("User cancelled person selection")
return None
index = int(selection)
if 1 <= index <= len(sorted_individuals):
selected = sorted_individuals[index - 1]
first_name, last_name = selected.get_names()
full_name = f"{last_name or ''} {first_name or ''}".strip()
print(f"\nSelected: {full_name}")
logger.info(f"User selected root person: {full_name} ({selected.get_pointer()})")
return selected.get_pointer()
else:
print(f"Please enter a number between 1 and {len(sorted_individuals)}")
except ValueError:
print("Invalid input. Please enter a number or 'q' to quit.")
except KeyboardInterrupt:
print("\n\nSelection cancelled.")
logger.info("User cancelled person selection with Ctrl+C")
return None