Merge branch 'main' into canvas

This commit is contained in:
AlexKucera authored and GitHub committed 2025-11-02 17:49:36 +01:00
commit 5fd41a8e06
11 files changed
+376 -178

No files matched your search

+7 -2
View File
@@ -8,6 +8,7 @@ family tree.
from pathlib import Path
from typing import List
import logging
import re
from individual import Individual
@@ -66,7 +67,7 @@ class IndexGenerator:
current_letter = ""
for individual in sorted_individuals:
first, last = individual.get_names()
_, last = individual.get_names()
# Write letter header if changed
if last:
@@ -85,7 +86,11 @@ class IndexGenerator:
# Format life span
if birth_info["year"] or death_info["date"]:
death_year = death_info["date"][:4] if death_info["date"] else ""
death_year = ""
if death_info["date"]:
match = re.search(r"(\d{4})\b", death_info["date"])
if match:
death_year = match.group(1)
life_span = f" ({birth_info['year']}-{death_year})"
else:
life_span = ""
+38 -39
View File
@@ -7,6 +7,7 @@ extracting all relevant information from GEDCOM data.
from typing import List, Dict, Tuple
import logging
import re
from gedcom.element.individual import IndividualElement
import gedcom.tags
@@ -24,18 +25,18 @@ class Individual:
images, and notes.
"""
def __init__(self, element: IndividualElement, gedcom_parser):
def __init__(self, element: IndividualElement, parser):
"""
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.
Create an Individual wrapper around a GEDCOM individual element and parser.
Stores the provided IndividualElement and 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.
parser: The parser instance (e.g., gedcom.parser.Parser) used for resolving references.
"""
self.element = element
self.gedcom = gedcom_parser.parser
self.gedcom = parser
def get_id(self) -> str:
"""
@@ -68,22 +69,22 @@ class Individual:
def get_full_name(self) -> str:
"""
Return the individual's full name formatted as "First Last".
Returns:
Full name string in title case (e.g., "John Doe"); empty string if no name parts exist.
Full name string preserving original capitalization; empty string if no name parts exist.
"""
first, last = self.get_names()
return f"{first} {last}".strip().title()
return f"{first} {last}".strip()
def get_file_name(self) -> str:
"""
Build a filename-like string for the individual in the form "FamilyName FirstName" optionally followed by the birth year.
Returns:
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.
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; preserves original name capitalization.
"""
first, last = self.get_names()
name_part = f"{last} {first}".strip().title()
name_part = f"{last} {first}".strip()
birth_year = self.element.get_birth_year()
if birth_year != -1:
@@ -93,14 +94,14 @@ class Individual:
def get_birth_info(self) -> Dict[str, str]:
"""
Retrieve the person's birth date, place, and year 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.
"""
date, place, sources = self.element.get_birth_data()
date, place, _sources = self.element.get_birth_data()
year = self.element.get_birth_year()
return {
@@ -111,16 +112,25 @@ class Individual:
def get_death_info(self) -> Dict[str, str]:
"""
Provide the individual's death date and place.
Provide the individual's death date, place, and year.
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.
"""
date, place, sources = self.element.get_death_data()
date, place, _sources = self.element.get_death_data()
return {"date": date or "", "place": place or ""}
# 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}
def get_gender(self) -> str:
"""
@@ -134,20 +144,17 @@ class Individual:
def get_parents(self) -> List["Individual"]:
"""
Retrieve the person's parents.
Returns:
A list of Individual objects representing the person's parents.
"""
parent_elements = self.gedcom.get_parents(self.element)
return [
Individual(p, type("", (), {"parser": self.gedcom})())
for p in parent_elements
]
return [Individual(p, self.gedcom) for p in parent_elements]
def get_children(self) -> List["Individual"]:
"""
Retrieve the person's children as Individual objects.
Returns:
children (List[Individual]): A list of Individual instances corresponding to this person's children.
"""
@@ -157,17 +164,15 @@ class Individual:
family, gedcom.tags.GEDCOM_TAG_CHILD
)
for child in child_elements:
children.append(
Individual(child, type("", (), {"parser": self.gedcom})())
)
children.append(Individual(child, self.gedcom))
return children
def get_partners(self) -> List["Individual"]:
"""
Retrieve this individual's spouses and partners.
Each partner is resolved to an Individual wrapper; the subject is excluded from the result.
Returns:
List[Individual]: A list of Individual objects representing the person's partners (excluding the subject).
"""
@@ -177,9 +182,7 @@ class Individual:
for parent in parent_elements:
# Don't include self
if parent.get_pointer() != self.element.get_pointer():
partners.append(
Individual(parent, type("", (), {"parser": self.gedcom})())
)
partners.append(Individual(parent, self.gedcom))
return partners
def get_families(self) -> List[Dict]:
@@ -199,9 +202,7 @@ class Individual:
partners = []
for parent in self.gedcom.get_family_members(family, "PARENTS"):
if parent.get_pointer() != self.element.get_pointer():
partners.append(
Individual(parent, type("", (), {"parser": self.gedcom})())
)
partners.append(Individual(parent, self.gedcom))
# Get marriage info
marriage_date = ""
@@ -219,9 +220,7 @@ class Individual:
for child in self.gedcom.get_family_members(
family, gedcom.tags.GEDCOM_TAG_CHILD
):
children.append(
Individual(child, type("", (), {"parser": self.gedcom})())
)
children.append(Individual(child, self.gedcom))
families.append(
{
Regular → Executable
+71 -32
View File
@@ -95,15 +95,19 @@ def extract_gedzip(zip_path: Path, temp_dir: Path) -> Tuple[Path, Optional[Path]
gedcom_file = gedcom_files[0]
logger.info(f"Found GEDCOM file: {gedcom_file.name}")
# Find media directory (look for common image extensions)
# Find media files across the entire extracted tree
media_dir = None
for ext in ["*.jpg", "*.jpeg", "*.png", "*.gif", "*.bmp"]:
media_files = list(temp_dir.glob(f"**/{ext}"))
if media_files:
# Get the common parent directory of media files
media_dir = media_files[0].parent
logger.info(f"Found {len(media_files)} media files in: {media_dir}")
break
media_files = []
for ext in ["*.jpg", "*.jpeg", "*.png", "*.gif", "*.bmp", "*.JPG", "*.JPEG", "*.PNG", "*.GIF", "*.BMP"]:
media_files.extend(temp_dir.rglob(ext))
if media_files:
# Set media_dir to the extraction root so all subdirectories are accessible
media_dir = temp_dir
# Get unique parent directories for logging
unique_dirs = sorted(set(f.parent for f in media_files))
logger.info(f"Found {len(media_files)} media files across {len(unique_dirs)} directories")
logger.debug(f"Media directories: {[str(d.relative_to(temp_dir)) for d in unique_dirs]}")
return gedcom_file, media_dir
@@ -176,7 +180,7 @@ def convert_gedcom_to_markdown(
return 1
# Wrap individuals in our data model
individuals = [Individual(elem, parser) for elem in individual_elements]
individuals = [Individual(elem, parser.parser) for elem in individual_elements]
# Generate canvas if requested
if create_canvas:
@@ -198,6 +202,7 @@ def convert_gedcom_to_markdown(
media_subdir=media_subdir_name,
stories_subdir=stories_subdir_name,
stories_dir=stories_dir,
use_subdirectories=not use_flat_structure,
)
created_files = generator.generate_all(individuals)
logger.info(f"Created {len(created_files)} markdown files")
@@ -205,26 +210,60 @@ def convert_gedcom_to_markdown(
# Copy media files if available
if media_dir and media_dir.exists():
logger.info(f"Copying media files to: {media_output_dir}")
media_files = []
for ext in [
"*.jpg",
"*.jpeg",
"*.png",
"*.gif",
"*.bmp",
"*.JPG",
"*.JPEG",
"*.PNG",
]:
media_files.extend(media_dir.glob(ext))
# Allowed media extensions (case-insensitive)
allowed_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp'}
copied_count = 0
for media_file in media_files:
dest = media_output_dir / media_file.name
shutil.copy2(media_file, dest)
copied_count += 1
skipped_count = 0
collision_count = 0
logger.info(f"Copied {copied_count} media files")
# Recursively find all files in media_dir
for media_file in media_dir.rglob('*'):
# Skip directories, only process files
if not media_file.is_file():
continue
# Filter by extension (case-insensitive)
if media_file.suffix.lower() not in allowed_extensions:
continue
# Compute relative path to preserve directory structure
relative_path = media_file.relative_to(media_dir)
dest = media_output_dir / relative_path
# Handle filename collisions
if dest.exists():
# Generate unique filename with numeric suffix
original_dest = dest
counter = 1
stem = dest.stem
suffix = dest.suffix
while dest.exists():
dest = dest.parent / f"{stem}_{counter}{suffix}"
counter += 1
logger.warning(
f"Collision detected: {original_dest.name} -> {dest.name}"
)
collision_count += 1
# Ensure parent directory exists
dest.parent.mkdir(parents=True, exist_ok=True)
# Copy file preserving metadata
try:
shutil.copy2(media_file, dest)
copied_count += 1
except (IOError, OSError) as e:
logger.exception(f"Failed to copy {media_file}")
skipped_count += 1
logger.info(
f"Copied {copied_count} media files "
f"({collision_count} collisions resolved, {skipped_count} skipped)"
)
# Generate index
if create_index:
@@ -237,14 +276,14 @@ def convert_gedcom_to_markdown(
logger.info("Conversion completed successfully")
return 0
except FileNotFoundError as e:
logger.error(f"File not found: {e}")
except FileNotFoundError:
logger.exception("File not found")
return 1
except ValueError as e:
logger.error(f"Invalid input: {e}")
except ValueError:
logger.exception("Invalid input")
return 1
except Exception as e:
logger.error(f"Unexpected error: {e}", exc_info=True)
except Exception:
logger.exception("Unexpected error")
return 1
+37 -30
View File
@@ -29,16 +29,18 @@ class MarkdownGenerator:
media_subdir: str = "",
stories_subdir: str = "",
stories_dir: Optional[Path] = None,
use_subdirectories: bool = False,
):
"""
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.
use_subdirectories (bool): Whether the output structure uses subdirectories (people/, stories/, media/). When True, WikiLinks and image paths will include appropriate subdirectory prefixes.
Raises:
ValueError: If `output_dir` does not exist or is not a directory.
"""
@@ -51,6 +53,7 @@ class MarkdownGenerator:
self.media_subdir = media_subdir
self.stories_subdir = stories_subdir
self.stories_dir = stories_dir if stories_dir else output_dir
self.use_subdirectories = use_subdirectories
self.generated_stories = {} # Track generated story files
def generate_note(self, individual: Individual) -> Path:
@@ -110,8 +113,9 @@ class MarkdownGenerator:
self._write_metadata(f, "Name", individual.get_full_name())
# Lived years
lived = f"{birth['year']}-{death['date'][:4] if death['date'] else ''}"
self._write_metadata(f, "Lived", lived)
if birth['year'] or death['year']:
lived = f"{birth['year']}-{death['year']}"
self._write_metadata(f, "Lived", lived)
self._write_metadata(f, "Sex", individual.get_gender())
@@ -181,9 +185,9 @@ class MarkdownGenerator:
def _write_families(self, f, individual: Individual):
"""
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.
Emits a "## Families" header and, for each family, a "Marriage" subsection (numbered when the individual has multiple families). For each family the function writes hidden metadata entries for Partner (as a wiki link, if partner is present), Marriage date, Marriage place (if present), and lists each Child as hidden metadata (as wiki links). Adds spacing after each family 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.
@@ -196,28 +200,33 @@ class MarkdownGenerator:
f.write("## Families\n")
for i, family in enumerate(families, 1):
# Always write the Marriage header
f.write(f"### Marriage{f' {i}' if len(families) > 1 else ''}\n")
# Only write partner metadata if partner exists
if family["partner"]:
partner_name = family["partner"].get_file_name()
f.write(f"### Marriage {i if len(families) > 1 else ''}\n")
self._write_metadata_hidden(f, "Partner", self._wiki_link(partner_name))
if family["marriage_date"]:
# Write marriage metadata if present
if family["marriage_date"]:
self._write_metadata_hidden(
f, "Marriage date", family["marriage_date"]
)
if family["marriage_place"]:
self._write_metadata_hidden(
f, "Marriage place", family["marriage_place"]
)
# Write children if they exist
if family["children"]:
f.write("\n**Children:**\n")
for child in family["children"]:
self._write_metadata_hidden(
f, "Marriage date", family["marriage_date"]
)
if family["marriage_place"]:
self._write_metadata_hidden(
f, "Marriage place", family["marriage_place"]
f, "Child", self._wiki_link(child.get_file_name())
)
if family["children"]:
f.write("\n**Children:**\n")
for child in family["children"]:
self._write_metadata_hidden(
f, "Child", self._wiki_link(child.get_file_name())
)
f.write("\n")
f.write("\n")
f.write("\n")
@@ -336,9 +345,7 @@ class MarkdownGenerator:
# Link back to the individual
# If using subdirectories, stories are in stories/ and people are in people/
if (
self.media_subdir
): # If using subdirs (media_subdir is set), use path prefix
if self.use_subdirectories:
person_link = f"[[people/{individual_name}|{individual_name}]]"
else:
person_link = f"[[{individual_name}]]"
@@ -359,8 +366,8 @@ class MarkdownGenerator:
for img in section["images"]:
title = img["title"] if img["title"] else "Image"
filename_img = img["file"]
# Add media subdirectory prefix if specified
if self.media_subdir:
# Add media subdirectory prefix if using subdirectory structure
if self.use_subdirectories and self.media_subdir:
image_path = f"../{self.media_subdir}/{filename_img}"
else:
image_path = filename_img
@@ -477,9 +484,9 @@ class MarkdownGenerator:
try:
path = self.generate_note(individual)
paths.append(path)
except Exception as e:
logger.error(
f"Failed to generate note for {individual.get_full_name()}: {e}"
except Exception:
logger.exception(
f"Failed to generate note for {individual.get_full_name()}"
)
logger.info(f"Successfully generated {len(paths)} notes")