Adds Obsidian Canvas family tree generator
Introduces new functionality to create interactive family tree visualizations for Obsidian Adds: - CanvasGenerator class to generate JSON Canvas files - Interactive root person selection for canvas creation - Support for generational tree layout with nodes and edges - Handling of disconnected family trees Enhances family tree visualization by allowing users to generate an Obsidian-compatible canvas with person relationships
This commit is contained in:
4 files changed
+622
-25
No files matched your search
@@ -0,0 +1,389 @@
|
|||||||
|
"""
|
||||||
|
Canvas generator for creating Obsidian Canvas family trees.
|
||||||
|
|
||||||
|
This module generates JSON Canvas files that visualize family relationships
|
||||||
|
from GEDCOM data in a generational tree layout compatible with Obsidian.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
from typing import List, Dict, Tuple
|
||||||
|
from collections import defaultdict, deque
|
||||||
|
from individual import Individual
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class CanvasGenerator:
|
||||||
|
"""Generates Obsidian Canvas files for family tree visualization."""
|
||||||
|
|
||||||
|
# Layout constants
|
||||||
|
NODE_WIDTH = 250
|
||||||
|
NODE_BASE_HEIGHT = 60 # Base height, will grow with content
|
||||||
|
HORIZONTAL_SPACING = 100
|
||||||
|
VERTICAL_SPACING = 200
|
||||||
|
IMAGE_HEIGHT = 150 # Height for nodes with images
|
||||||
|
TREE_SPACING = 400 # Space between disconnected trees
|
||||||
|
|
||||||
|
def __init__(self, individuals: List[Individual], output_dir: str):
|
||||||
|
"""
|
||||||
|
Initialize the canvas generator.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
individuals: List of all individuals from GEDCOM
|
||||||
|
output_dir: Directory where canvas file will be saved
|
||||||
|
"""
|
||||||
|
self.individuals = individuals
|
||||||
|
self.output_dir = output_dir
|
||||||
|
|
||||||
|
# Create lookup dictionary for fast access
|
||||||
|
self.individual_map: Dict[str, Individual] = {
|
||||||
|
ind.get_pointer(): ind for ind in individuals
|
||||||
|
}
|
||||||
|
|
||||||
|
# Canvas data structures
|
||||||
|
self.nodes: List[Dict] = []
|
||||||
|
self.edges: List[Dict] = []
|
||||||
|
|
||||||
|
logger.info(f"Initialized CanvasGenerator with {len(individuals)} individuals")
|
||||||
|
|
||||||
|
def generate_canvas(self, root_person_id: str, canvas_filename: str = "Family Tree.canvas") -> str:
|
||||||
|
"""
|
||||||
|
Generate canvas file with family tree visualization.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
root_person_id: GEDCOM pointer of the root person
|
||||||
|
canvas_filename: Name of the output canvas file
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Path to the generated canvas file
|
||||||
|
"""
|
||||||
|
logger.info(f"Generating canvas with root person: {root_person_id}")
|
||||||
|
|
||||||
|
# Build family tree structure starting from root
|
||||||
|
tree_structure = self._build_tree_structure(root_person_id)
|
||||||
|
|
||||||
|
# Calculate node positions using generational layout
|
||||||
|
positioned_nodes = self._calculate_positions(tree_structure)
|
||||||
|
|
||||||
|
# Create canvas nodes and edges
|
||||||
|
self._create_canvas_elements(positioned_nodes, tree_structure)
|
||||||
|
|
||||||
|
# Find and add disconnected family trees
|
||||||
|
self._add_disconnected_trees(tree_structure)
|
||||||
|
|
||||||
|
# Write canvas file
|
||||||
|
canvas_path = os.path.join(self.output_dir, canvas_filename)
|
||||||
|
self._write_canvas_file(canvas_path)
|
||||||
|
|
||||||
|
logger.info(f"Canvas generated with {len(self.nodes)} nodes and {len(self.edges)} edges")
|
||||||
|
return canvas_path
|
||||||
|
|
||||||
|
def _build_tree_structure(self, root_id: str) -> Dict[str, Dict]:
|
||||||
|
"""
|
||||||
|
Build tree structure starting from root person using BFS.
|
||||||
|
|
||||||
|
Returns a dict mapping person_id -> {
|
||||||
|
'individual': Individual,
|
||||||
|
'generation': int,
|
||||||
|
'spouses': List[str],
|
||||||
|
'children': List[str],
|
||||||
|
'parents': List[str]
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
structure = {}
|
||||||
|
visited = set()
|
||||||
|
queue = deque([(root_id, 0)]) # (person_id, generation)
|
||||||
|
|
||||||
|
while queue:
|
||||||
|
person_id, generation = queue.popleft()
|
||||||
|
|
||||||
|
if person_id in visited or person_id not in self.individual_map:
|
||||||
|
continue
|
||||||
|
|
||||||
|
visited.add(person_id)
|
||||||
|
individual = self.individual_map[person_id]
|
||||||
|
|
||||||
|
# Initialize structure for this person
|
||||||
|
structure[person_id] = {
|
||||||
|
'individual': individual,
|
||||||
|
'generation': generation,
|
||||||
|
'spouses': [],
|
||||||
|
'children': [],
|
||||||
|
'parents': []
|
||||||
|
}
|
||||||
|
|
||||||
|
# Get families where this person is a child (to find parents)
|
||||||
|
families_as_child = individual.get_families_as_child()
|
||||||
|
for family in families_as_child:
|
||||||
|
# Add parents
|
||||||
|
if family.get('father'):
|
||||||
|
father_id = family['father']
|
||||||
|
structure[person_id]['parents'].append(father_id)
|
||||||
|
if father_id not in visited:
|
||||||
|
queue.append((father_id, generation - 1))
|
||||||
|
|
||||||
|
if family.get('mother'):
|
||||||
|
mother_id = family['mother']
|
||||||
|
structure[person_id]['parents'].append(mother_id)
|
||||||
|
if mother_id not in visited:
|
||||||
|
queue.append((mother_id, generation - 1))
|
||||||
|
|
||||||
|
# Get families where this person is a spouse (to find spouses and children)
|
||||||
|
families = individual.get_families()
|
||||||
|
for family in families:
|
||||||
|
# Add spouse
|
||||||
|
partner = family.get('partner')
|
||||||
|
if partner:
|
||||||
|
spouse_id = partner.get_pointer()
|
||||||
|
if spouse_id and spouse_id not in structure[person_id]['spouses']:
|
||||||
|
structure[person_id]['spouses'].append(spouse_id)
|
||||||
|
if spouse_id not in visited:
|
||||||
|
queue.append((spouse_id, generation))
|
||||||
|
|
||||||
|
# Add children
|
||||||
|
children = family.get('children', [])
|
||||||
|
for child in children:
|
||||||
|
child_id = child.get_pointer()
|
||||||
|
if child_id and child_id not in structure[person_id]['children']:
|
||||||
|
structure[person_id]['children'].append(child_id)
|
||||||
|
if child_id not in visited:
|
||||||
|
queue.append((child_id, generation + 1))
|
||||||
|
|
||||||
|
logger.info(f"Built tree structure with {len(structure)} people from root {root_id}")
|
||||||
|
return structure
|
||||||
|
|
||||||
|
def _calculate_positions(self, tree_structure: Dict[str, Dict]) -> Dict[str, Tuple[int, int]]:
|
||||||
|
"""
|
||||||
|
Calculate x, y positions for each person using generational layout.
|
||||||
|
|
||||||
|
Returns dict mapping person_id -> (x, y)
|
||||||
|
"""
|
||||||
|
# Group people by generation
|
||||||
|
generations: Dict[int, List[str]] = defaultdict(list)
|
||||||
|
for person_id, data in tree_structure.items():
|
||||||
|
generations[data['generation']].append(person_id)
|
||||||
|
|
||||||
|
positions = {}
|
||||||
|
min_gen = min(generations.keys()) if generations else 0
|
||||||
|
max_gen = max(generations.keys()) if generations else 0
|
||||||
|
|
||||||
|
# Calculate positions generation by generation
|
||||||
|
for gen in range(min_gen, max_gen + 1):
|
||||||
|
people_in_gen = generations.get(gen, [])
|
||||||
|
|
||||||
|
# Sort by last name for consistent positioning
|
||||||
|
people_in_gen.sort(key=lambda pid: self.individual_map[pid].get_names()[1] or "")
|
||||||
|
|
||||||
|
# Calculate Y position (vertical, based on generation)
|
||||||
|
y_pos = gen * (self.NODE_BASE_HEIGHT + self.VERTICAL_SPACING)
|
||||||
|
|
||||||
|
# Calculate X positions (horizontal, evenly spaced)
|
||||||
|
total_width = len(people_in_gen) * self.NODE_WIDTH + (len(people_in_gen) - 1) * self.HORIZONTAL_SPACING
|
||||||
|
start_x = -(total_width // 2) # Center the generation
|
||||||
|
|
||||||
|
for idx, person_id in enumerate(people_in_gen):
|
||||||
|
x_pos = start_x + idx * (self.NODE_WIDTH + self.HORIZONTAL_SPACING)
|
||||||
|
positions[person_id] = (x_pos, y_pos)
|
||||||
|
|
||||||
|
return positions
|
||||||
|
|
||||||
|
def _create_canvas_elements(self, positions: Dict[str, Tuple[int, int]], tree_structure: Dict[str, Dict]):
|
||||||
|
"""
|
||||||
|
Create canvas nodes and edges from positioned tree structure.
|
||||||
|
"""
|
||||||
|
node_ids = {} # Map person_id -> canvas node_id
|
||||||
|
|
||||||
|
# Create nodes
|
||||||
|
for person_id, (x, y) in positions.items():
|
||||||
|
individual = tree_structure[person_id]['individual']
|
||||||
|
node_id = self._create_node(individual, x, y)
|
||||||
|
node_ids[person_id] = node_id
|
||||||
|
|
||||||
|
# Create edges
|
||||||
|
for person_id, data in tree_structure.items():
|
||||||
|
from_node_id = node_ids.get(person_id)
|
||||||
|
if not from_node_id:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Create parent-child edges
|
||||||
|
for child_id in data['children']:
|
||||||
|
to_node_id = node_ids.get(child_id)
|
||||||
|
if to_node_id:
|
||||||
|
self._create_edge(from_node_id, to_node_id, "Child", "bottom", "top")
|
||||||
|
|
||||||
|
# Create spouse edges
|
||||||
|
for spouse_id in data['spouses']:
|
||||||
|
to_node_id = node_ids.get(spouse_id)
|
||||||
|
if to_node_id:
|
||||||
|
# Only create edge once (from lower ID to higher ID to avoid duplicates)
|
||||||
|
if person_id < spouse_id:
|
||||||
|
self._create_edge(from_node_id, to_node_id, "Spouse", "right", "left")
|
||||||
|
|
||||||
|
def _add_disconnected_trees(self, main_tree: Dict[str, Dict]):
|
||||||
|
"""
|
||||||
|
Find individuals not in main tree and create separate tree groups.
|
||||||
|
"""
|
||||||
|
connected_ids = set(main_tree.keys())
|
||||||
|
disconnected_ids = set(self.individual_map.keys()) - connected_ids
|
||||||
|
|
||||||
|
if not disconnected_ids:
|
||||||
|
logger.info("No disconnected family trees found")
|
||||||
|
return
|
||||||
|
|
||||||
|
logger.info(f"Found {len(disconnected_ids)} people in disconnected trees")
|
||||||
|
|
||||||
|
# Find separate tree roots (people with no parents in the disconnected set)
|
||||||
|
tree_roots = []
|
||||||
|
|
||||||
|
for person_id in disconnected_ids:
|
||||||
|
individual = self.individual_map[person_id]
|
||||||
|
families_as_child = individual.get_families_as_child()
|
||||||
|
|
||||||
|
has_parent_in_disconnected = False
|
||||||
|
for family in families_as_child:
|
||||||
|
father_id = family.get('father')
|
||||||
|
mother_id = family.get('mother')
|
||||||
|
if (father_id and father_id in disconnected_ids) or (mother_id and mother_id in disconnected_ids):
|
||||||
|
has_parent_in_disconnected = True
|
||||||
|
break
|
||||||
|
|
||||||
|
if not has_parent_in_disconnected:
|
||||||
|
tree_roots.append(person_id)
|
||||||
|
|
||||||
|
logger.info(f"Found {len(tree_roots)} disconnected tree roots")
|
||||||
|
|
||||||
|
# Calculate offset for disconnected trees
|
||||||
|
# Place them to the right of the main tree
|
||||||
|
if self.nodes:
|
||||||
|
max_x = max(node['x'] + node['width'] for node in self.nodes)
|
||||||
|
offset_x = max_x + self.TREE_SPACING
|
||||||
|
else:
|
||||||
|
offset_x = 0
|
||||||
|
|
||||||
|
# Build and position each disconnected tree
|
||||||
|
for root_id in tree_roots:
|
||||||
|
if root_id not in disconnected_ids:
|
||||||
|
continue # Already processed
|
||||||
|
|
||||||
|
# Build tree structure for this root
|
||||||
|
tree_structure = self._build_tree_structure(root_id)
|
||||||
|
|
||||||
|
# Update disconnected_ids to track what we've processed
|
||||||
|
disconnected_ids -= set(tree_structure.keys())
|
||||||
|
|
||||||
|
# Calculate positions
|
||||||
|
positions = self._calculate_positions(tree_structure)
|
||||||
|
|
||||||
|
# Offset positions
|
||||||
|
offset_positions = {
|
||||||
|
pid: (x + offset_x, y) for pid, (x, y) in positions.items()
|
||||||
|
}
|
||||||
|
|
||||||
|
# Create nodes and edges
|
||||||
|
self._create_canvas_elements(offset_positions, tree_structure)
|
||||||
|
|
||||||
|
# Update offset for next tree
|
||||||
|
if offset_positions:
|
||||||
|
max_x_in_tree = max(x + self.NODE_WIDTH for x, y in offset_positions.values())
|
||||||
|
offset_x = max_x_in_tree + self.TREE_SPACING
|
||||||
|
|
||||||
|
def _create_node(self, individual: Individual, x: int, y: int) -> str:
|
||||||
|
"""
|
||||||
|
Create a canvas node for an individual.
|
||||||
|
|
||||||
|
Returns the node ID.
|
||||||
|
"""
|
||||||
|
node_id = str(uuid.uuid4().hex[:16])
|
||||||
|
first_name, last_name = individual.get_names()
|
||||||
|
|
||||||
|
# Get filename (same logic as in markdown generator)
|
||||||
|
birth_year = ""
|
||||||
|
events = individual.get_events()
|
||||||
|
for event in events:
|
||||||
|
if event["type"] == "BIRT" and event.get("date"):
|
||||||
|
import re
|
||||||
|
year_match = re.search(r'\b(\d{4})\b', event["date"])
|
||||||
|
if year_match:
|
||||||
|
birth_year = year_match.group(1)
|
||||||
|
break
|
||||||
|
|
||||||
|
# Build filename for WikiLink
|
||||||
|
filename_parts = []
|
||||||
|
if last_name:
|
||||||
|
filename_parts.append(last_name)
|
||||||
|
if first_name:
|
||||||
|
filename_parts.append(first_name)
|
||||||
|
if birth_year:
|
||||||
|
filename_parts.append(birth_year)
|
||||||
|
filename = " ".join(filename_parts)
|
||||||
|
|
||||||
|
# Get images
|
||||||
|
images = individual.get_images()
|
||||||
|
has_image = len(images) > 0
|
||||||
|
|
||||||
|
# Build node text content
|
||||||
|
text_parts = []
|
||||||
|
|
||||||
|
# Add image if available (use first image)
|
||||||
|
if has_image:
|
||||||
|
# images is a list of dicts with 'file', 'title', 'format' keys
|
||||||
|
image_file = images[0].get('file', '')
|
||||||
|
if image_file:
|
||||||
|
text_parts.append(f"")
|
||||||
|
|
||||||
|
# Add WikiLink to person's markdown file
|
||||||
|
text_parts.append(f"[[{filename}]]")
|
||||||
|
|
||||||
|
node_text = "\n".join(text_parts)
|
||||||
|
|
||||||
|
# Calculate height based on content
|
||||||
|
height = self.IMAGE_HEIGHT if has_image else self.NODE_BASE_HEIGHT
|
||||||
|
|
||||||
|
node = {
|
||||||
|
"id": node_id,
|
||||||
|
"type": "text",
|
||||||
|
"text": node_text,
|
||||||
|
"x": x,
|
||||||
|
"y": y,
|
||||||
|
"width": self.NODE_WIDTH,
|
||||||
|
"height": height
|
||||||
|
}
|
||||||
|
|
||||||
|
self.nodes.append(node)
|
||||||
|
return node_id
|
||||||
|
|
||||||
|
def _create_edge(self, from_node: str, to_node: str, label: str,
|
||||||
|
from_side: str = "bottom", to_side: str = "top"):
|
||||||
|
"""
|
||||||
|
Create a canvas edge between two nodes.
|
||||||
|
"""
|
||||||
|
edge_id = str(uuid.uuid4().hex[:16])
|
||||||
|
|
||||||
|
edge = {
|
||||||
|
"id": edge_id,
|
||||||
|
"fromNode": from_node,
|
||||||
|
"fromSide": from_side,
|
||||||
|
"toNode": to_node,
|
||||||
|
"toSide": to_side,
|
||||||
|
"label": label
|
||||||
|
}
|
||||||
|
|
||||||
|
self.edges.append(edge)
|
||||||
|
|
||||||
|
def _write_canvas_file(self, canvas_path: str):
|
||||||
|
"""
|
||||||
|
Write canvas data to JSON file.
|
||||||
|
"""
|
||||||
|
canvas_data = {
|
||||||
|
"nodes": self.nodes,
|
||||||
|
"edges": self.edges
|
||||||
|
}
|
||||||
|
|
||||||
|
with open(canvas_path, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(canvas_data, f, indent="\t")
|
||||||
|
|
||||||
|
logger.info(f"Canvas file written to: {canvas_path}")
|
||||||
+66
-1
@@ -40,12 +40,21 @@ class Individual:
|
|||||||
def get_id(self) -> str:
|
def get_id(self) -> str:
|
||||||
"""
|
"""
|
||||||
Provide the GEDCOM identifier for this individual without surrounding '@' characters.
|
Provide the GEDCOM identifier for this individual without surrounding '@' characters.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
str: The GEDCOM identifier with all '@' characters removed.
|
str: The GEDCOM identifier with all '@' characters removed.
|
||||||
"""
|
"""
|
||||||
return self.element.get_pointer().replace('@', '')
|
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]:
|
def get_names(self) -> Tuple[str, str]:
|
||||||
"""
|
"""
|
||||||
Return the individual's first and last name with surrounding whitespace removed.
|
Return the individual's first and last name with surrounding whitespace removed.
|
||||||
@@ -225,6 +234,62 @@ class Individual:
|
|||||||
|
|
||||||
return families
|
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]]:
|
def get_events(self) -> List[Dict[str, str]]:
|
||||||
"""
|
"""
|
||||||
Collects the individual's life events found on the GEDCOM element.
|
Collects the individual's life events found on the GEDCOM element.
|
||||||
|
|||||||
+61
-24
@@ -19,17 +19,21 @@ from gedcom_parser import GedcomParser
|
|||||||
from individual import Individual
|
from individual import Individual
|
||||||
from markdown_generator import MarkdownGenerator
|
from markdown_generator import MarkdownGenerator
|
||||||
from index_generator import IndexGenerator
|
from index_generator import IndexGenerator
|
||||||
|
from canvas_generator import CanvasGenerator
|
||||||
|
from person_selector import select_root_person
|
||||||
|
|
||||||
|
|
||||||
def setup_logging(verbose: bool = False):
|
def setup_logging(verbose: bool = False):
|
||||||
"""
|
"""
|
||||||
Configure root logger formatting and level 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.
|
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.
|
Also applies a consistent message format and timestamp date format used
|
||||||
|
across the application.
|
||||||
|
|
||||||
Parameters:
|
Parameters:
|
||||||
verbose (bool): When True, enable DEBUG-level logging; otherwise use INFO-level logging.
|
verbose (bool): When True, enable DEBUG-level logging; otherwise
|
||||||
|
use INFO-level logging.
|
||||||
"""
|
"""
|
||||||
level = logging.DEBUG if verbose else logging.INFO
|
level = logging.DEBUG if verbose else logging.INFO
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
@@ -41,16 +45,18 @@ def setup_logging(verbose: bool = False):
|
|||||||
|
|
||||||
def extract_gedzip(zip_path: Path, temp_dir: Path) -> Tuple[Path, Optional[Path]]:
|
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.
|
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.
|
Searches the extracted contents for the first `.ged` file and for image
|
||||||
|
files (jpg, jpeg, png, gif, bmp) to identify a media directory.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
A tuple `(gedcom_file_path, media_directory_path)` where `gedcom_file_path` is the path to the found
|
A tuple `(gedcom_file_path, media_directory_path)` where
|
||||||
GEDCOM file and `media_directory_path` is the path to the directory containing media files or `None`
|
`gedcom_file_path` is the path to the found GEDCOM file and
|
||||||
if no media files were found.
|
`media_directory_path` is the path to the directory containing media
|
||||||
|
files or `None` if no media files were found.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: If no GEDCOM (`.ged`) file is found in the archive.
|
ValueError: If no GEDCOM (`.ged`) file is found in the archive.
|
||||||
"""
|
"""
|
||||||
@@ -96,17 +102,25 @@ def convert_gedcom_to_markdown(
|
|||||||
create_index: bool = True,
|
create_index: bool = True,
|
||||||
media_dir: Optional[Path] = None,
|
media_dir: Optional[Path] = None,
|
||||||
use_flat_structure: bool = False,
|
use_flat_structure: bool = False,
|
||||||
|
create_canvas: bool = False,
|
||||||
) -> int:
|
) -> int:
|
||||||
"""
|
"""
|
||||||
Convert a GEDCOM file into Obsidian-compatible Markdown notes organized on disk.
|
Convert a GEDCOM file into Obsidian-compatible Markdown notes organized on disk.
|
||||||
|
|
||||||
Parameters:
|
Parameters:
|
||||||
gedcom_file (Path): Path to the input GEDCOM file.
|
gedcom_file (Path): Path to the input GEDCOM file.
|
||||||
output_dir (Path): Directory where generated markdown, media, and story files will be written.
|
output_dir (Path): Directory where generated markdown, media, and
|
||||||
create_index (bool): Whether to generate an index file linking the generated person notes.
|
story files will be written.
|
||||||
media_dir (Optional[Path]): Optional source directory of media files to copy into the output media directory.
|
create_index (bool): Whether to generate an index file linking the
|
||||||
use_flat_structure (bool): If True, write all outputs directly into `output_dir`; if False, create subdirectories (`people/`, `media/`, `stories/`).
|
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.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
int: 0 on success, 1 on failure.
|
int: 0 on success, 1 on failure.
|
||||||
"""
|
"""
|
||||||
@@ -147,6 +161,19 @@ def convert_gedcom_to_markdown(
|
|||||||
# Wrap individuals in our data model
|
# Wrap individuals in our data model
|
||||||
individuals = [Individual(elem, parser) for elem in individual_elements]
|
individuals = [Individual(elem, 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)
|
||||||
|
|
||||||
|
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
|
# Generate markdown notes
|
||||||
logger.info(f"Generating markdown notes in: {people_dir}")
|
logger.info(f"Generating markdown notes in: {people_dir}")
|
||||||
generator = MarkdownGenerator(
|
generator = MarkdownGenerator(
|
||||||
@@ -206,10 +233,13 @@ def convert_gedcom_to_markdown(
|
|||||||
|
|
||||||
def main():
|
def main():
|
||||||
"""
|
"""
|
||||||
Run the command-line interface to convert a GEDCOM or GEDZIP archive into Obsidian-compatible Markdown notes.
|
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.
|
|
||||||
|
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:
|
Returns:
|
||||||
int: Exit code where `0` indicates success and `1` indicates failure.
|
int: Exit code where `0` indicates success and `1` indicates failure.
|
||||||
"""
|
"""
|
||||||
@@ -246,6 +276,12 @@ def main():
|
|||||||
"--no-index", action="store_true", help="Do not create an index file"
|
"--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(
|
parser.add_argument(
|
||||||
"-v", "--verbose", action="store_true", help="Enable verbose logging"
|
"-v", "--verbose", action="store_true", help="Enable verbose logging"
|
||||||
)
|
)
|
||||||
@@ -283,6 +319,7 @@ def main():
|
|||||||
create_index=not args.no_index,
|
create_index=not args.no_index,
|
||||||
media_dir=media_dir,
|
media_dir=media_dir,
|
||||||
use_flat_structure=args.flat,
|
use_flat_structure=args.flat,
|
||||||
|
create_canvas=args.canvas,
|
||||||
)
|
)
|
||||||
|
|
||||||
return exit_code
|
return exit_code
|
||||||
@@ -295,4 +332,4 @@ def main():
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
sys.exit(main())
|
sys.exit(main())
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
"""
|
||||||
|
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]) -> Optional[str]:
|
||||||
|
"""
|
||||||
|
Display an interactive list of individuals and let user select root person.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
individuals: List of Individual objects from GEDCOM file
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
# 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
|
||||||
Reference in new issue
Block a user