Adds Obsidian Canvas family tree generation #3

Merged
AlexKucera merged 6 commits from canvas into main 2025-11-02 17:58:06 +01:00
3 changed files with 102 additions and 11 deletions
Showing only changes of commit e0ea4a3cc4 - Show all commits

No files matched your search

+17
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) - `-o`, `--output DIR`: Output directory for generated notes (required)
- `--flat`: Use flat structure (all files in output root). Default creates subdirectories - `--flat`: Use flat structure (all files in output root). Default creates subdirectories
- `--no-index`: Skip creating the index file - `--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 - `--verbose` or `-v`: Enable detailed logging
### Examples ### Examples
@@ -99,6 +101,21 @@ 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 python src/main.py -i examples/family.ged -o examples/output --flat --verbose
``` ```
**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:** **Using long form arguments:**
```bash ```bash
python src/main.py --input examples/family.zip --output examples/output python src/main.py --input examples/family.zip --output examples/output
+35 -10
View File
@@ -27,20 +27,32 @@ 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
for the main module only and WARNING for other modules.
Also applies a consistent message format and timestamp date format used Also applies a consistent message format and timestamp date format used
across the application. across the application.
Parameters: Parameters:
verbose (bool): When True, enable DEBUG-level logging; otherwise verbose (bool): When True, enable DEBUG-level logging for all modules;
use INFO-level logging. otherwise use INFO-level logging for main module only.
""" """
level = logging.DEBUG if verbose else logging.INFO if verbose:
logging.basicConfig( # Show all logs from all modules
level=level, level = logging.DEBUG
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", logging.basicConfig(
datefmt="%Y-%m-%d %H:%M:%S", 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]]: def extract_gedzip(zip_path: Path, temp_dir: Path) -> Tuple[Path, Optional[Path]]:
@@ -103,6 +115,7 @@ def convert_gedcom_to_markdown(
media_dir: Optional[Path] = None, media_dir: Optional[Path] = None,
use_flat_structure: bool = False, use_flat_structure: bool = False,
create_canvas: bool = False, create_canvas: bool = False,
root_id: Optional[str] = None,
) -> 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.
@@ -120,6 +133,10 @@ def convert_gedcom_to_markdown(
`media/`, `stories/`). `media/`, `stories/`).
create_canvas (bool): Whether to generate an Obsidian canvas file for create_canvas (bool): Whether to generate an Obsidian canvas file for
family tree visualization. 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: Returns:
int: 0 on success, 1 on failure. int: 0 on success, 1 on failure.
@@ -164,7 +181,7 @@ def convert_gedcom_to_markdown(
# Generate canvas if requested # Generate canvas if requested
if create_canvas: if create_canvas:
logger.info("Canvas generation requested") logger.info("Canvas generation requested")
root_person_id = select_root_person(individuals) root_person_id = select_root_person(individuals, root_id)
if root_person_id: if root_person_id:
logger.info(f"Generating canvas with root person: {root_person_id}") logger.info(f"Generating canvas with root person: {root_person_id}")
@@ -282,6 +299,13 @@ def main():
help="Create an Obsidian canvas file for family tree visualization", 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( parser.add_argument(
"-v", "--verbose", action="store_true", help="Enable verbose logging" "-v", "--verbose", action="store_true", help="Enable verbose logging"
) )
@@ -320,6 +344,7 @@ def main():
media_dir=media_dir, media_dir=media_dir,
use_flat_structure=args.flat, use_flat_structure=args.flat,
create_canvas=args.canvas, create_canvas=args.canvas,
root_id=args.root,
) )
return exit_code return exit_code
+50 -1
View File
@@ -14,12 +14,16 @@ from individual import Individual
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def select_root_person(individuals: List[Individual]) -> Optional[str]: 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. Display an interactive list of individuals and let user select root person.
Args: Args:
individuals: List of Individual objects from GEDCOM file 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: Returns:
The GEDCOM pointer/ID of the selected individual, or None if cancelled The GEDCOM pointer/ID of the selected individual, or None if cancelled
@@ -28,6 +32,51 @@ def select_root_person(individuals: List[Individual]) -> Optional[str]:
logger.error("No individuals provided for selection") logger.error("No individuals provided for selection")
return None 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 # Sort individuals by last name, then first name
sorted_individuals = sorted( sorted_individuals = sorted(
individuals, individuals,