Initializes project with GEDCOM to Markdown converter
Sets up core functionality for converting genealogy GEDCOM files to Obsidian markdown notes Implements key components: - GEDCOM parsing and individual data extraction - Markdown note generation with rich metadata - Index file creation - Comprehensive test suite for robust functionality Adds initial project structure, configuration, and essential modules for genealogy data conversion
This commit is contained in:
14 files changed
+2313
-275
No files matched your search
@@ -6,7 +6,7 @@ individual and family data.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
from typing import List
|
||||
import logging
|
||||
|
||||
from gedcom.parser import Parser
|
||||
@@ -60,13 +60,13 @@ class GedcomParser:
|
||||
detects and fixes such files automatically.
|
||||
"""
|
||||
# Read first chunk to check line endings
|
||||
with open(self.file_path, 'rb') as f:
|
||||
with open(self.file_path, "rb") as f:
|
||||
sample = f.read(8192) # Read first 8KB
|
||||
|
||||
# Count different line ending types
|
||||
has_crlf = b'\r\n' in sample
|
||||
has_lf = b'\n' in sample
|
||||
has_cr = b'\r' in sample
|
||||
has_crlf = b"\r\n" in sample
|
||||
has_lf = b"\n" in sample
|
||||
has_cr = b"\r" in sample
|
||||
|
||||
# If we have CR but no LF, this is a CR-only file
|
||||
if has_cr and not has_lf and not has_crlf:
|
||||
@@ -76,14 +76,14 @@ class GedcomParser:
|
||||
)
|
||||
|
||||
# Read entire file and fix line endings
|
||||
with open(self.file_path, 'rb') as f:
|
||||
with open(self.file_path, "rb") as f:
|
||||
content = f.read()
|
||||
|
||||
# Replace CR with LF
|
||||
fixed_content = content.replace(b'\r', b'\n')
|
||||
fixed_content = content.replace(b"\r", b"\n")
|
||||
|
||||
# Write back to file
|
||||
with open(self.file_path, 'wb') as f:
|
||||
with open(self.file_path, "wb") as f:
|
||||
f.write(fixed_content)
|
||||
|
||||
logger.info("Line endings fixed successfully")
|
||||
|
||||
+9
-11
@@ -22,7 +22,7 @@ class IndexGenerator:
|
||||
The index is organized alphabetically by last name, then first name.
|
||||
"""
|
||||
|
||||
def __init__(self, output_dir: Path, people_subdir: str = ''):
|
||||
def __init__(self, output_dir: Path, people_subdir: str = ""):
|
||||
"""
|
||||
Initialize the index generator.
|
||||
|
||||
@@ -34,9 +34,7 @@ class IndexGenerator:
|
||||
self.people_subdir = people_subdir
|
||||
|
||||
def generate_index(
|
||||
self,
|
||||
individuals: List[Individual],
|
||||
index_filename: str = 'Index.md'
|
||||
self, individuals: List[Individual], index_filename: str = "Index.md"
|
||||
) -> Path:
|
||||
"""
|
||||
Generate an alphabetical index of all individuals.
|
||||
@@ -55,15 +53,15 @@ class IndexGenerator:
|
||||
# Sort individuals by last name, then first name
|
||||
sorted_individuals = sorted(
|
||||
individuals,
|
||||
key=lambda i: (i.get_names()[1].lower(), i.get_names()[0].lower())
|
||||
key=lambda i: (i.get_names()[1].lower(), i.get_names()[0].lower()),
|
||||
)
|
||||
|
||||
with open(index_path, 'w', encoding='utf-8') as f:
|
||||
with open(index_path, "w", encoding="utf-8") as f:
|
||||
f.write("# Family Tree Index\n\n")
|
||||
f.write(f"Total individuals: {len(individuals)}\n\n")
|
||||
|
||||
# Group by last name initial
|
||||
current_letter = ''
|
||||
current_letter = ""
|
||||
|
||||
for individual in sorted_individuals:
|
||||
first, last = individual.get_names()
|
||||
@@ -72,7 +70,7 @@ class IndexGenerator:
|
||||
if last:
|
||||
letter = last[0].upper()
|
||||
else:
|
||||
letter = '#' # For individuals without last name
|
||||
letter = "#" # For individuals without last name
|
||||
|
||||
if letter != current_letter:
|
||||
current_letter = letter
|
||||
@@ -84,11 +82,11 @@ class IndexGenerator:
|
||||
death_info = individual.get_death_info()
|
||||
|
||||
# Format life span
|
||||
if birth_info['year'] or death_info['date']:
|
||||
death_year = death_info['date'][:4] if death_info['date'] else ''
|
||||
if birth_info["year"] or death_info["date"]:
|
||||
death_year = death_info["date"][:4] if death_info["date"] else ""
|
||||
life_span = f" ({birth_info['year']}-{death_year})"
|
||||
else:
|
||||
life_span = ''
|
||||
life_span = ""
|
||||
|
||||
# Create WikiLink with path prefix if using subdirectories
|
||||
if self.people_subdir:
|
||||
|
||||
+118
-128
@@ -5,7 +5,7 @@ This module provides a rich data model for individuals in a family tree,
|
||||
extracting all relevant information from GEDCOM data.
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Optional, Tuple
|
||||
from typing import List, Dict, Tuple
|
||||
import logging
|
||||
|
||||
from gedcom.element.individual import IndividualElement
|
||||
@@ -37,7 +37,7 @@ class Individual:
|
||||
|
||||
def get_id(self) -> str:
|
||||
"""Get the GEDCOM ID without @ symbols."""
|
||||
return self.element.get_pointer().replace('@', '')
|
||||
return self.element.get_pointer().replace("@", "")
|
||||
|
||||
def get_names(self) -> Tuple[str, str]:
|
||||
"""
|
||||
@@ -88,9 +88,9 @@ class Individual:
|
||||
year = self.element.get_birth_year()
|
||||
|
||||
return {
|
||||
'date': date or '',
|
||||
'place': place or '',
|
||||
'year': str(year) if year != -1 else ''
|
||||
"date": date or "",
|
||||
"place": place or "",
|
||||
"year": str(year) if year != -1 else "",
|
||||
}
|
||||
|
||||
def get_death_info(self) -> Dict[str, str]:
|
||||
@@ -102,16 +102,13 @@ class Individual:
|
||||
"""
|
||||
date, place, sources = self.element.get_death_data()
|
||||
|
||||
return {
|
||||
'date': date or '',
|
||||
'place': place or ''
|
||||
}
|
||||
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 self.element.get_gender() or "U"
|
||||
|
||||
def get_parents(self) -> List['Individual']:
|
||||
def get_parents(self) -> List["Individual"]:
|
||||
"""
|
||||
Get this person's parents.
|
||||
|
||||
@@ -119,10 +116,12 @@ class Individual:
|
||||
List of Individual objects representing parents
|
||||
"""
|
||||
parent_elements = self.gedcom.get_parents(self.element)
|
||||
return [Individual(p, type('', (), {'parser': self.gedcom})())
|
||||
for p in parent_elements]
|
||||
return [
|
||||
Individual(p, type("", (), {"parser": self.gedcom})())
|
||||
for p in parent_elements
|
||||
]
|
||||
|
||||
def get_children(self) -> List['Individual']:
|
||||
def get_children(self) -> List["Individual"]:
|
||||
"""
|
||||
Get this person's children.
|
||||
|
||||
@@ -132,16 +131,15 @@ class Individual:
|
||||
children = []
|
||||
for family in self.gedcom.get_families(self.element):
|
||||
child_elements = self.gedcom.get_family_members(
|
||||
family,
|
||||
gedcom.tags.GEDCOM_TAG_CHILD
|
||||
family, gedcom.tags.GEDCOM_TAG_CHILD
|
||||
)
|
||||
for child in child_elements:
|
||||
children.append(
|
||||
Individual(child, type('', (), {'parser': self.gedcom})())
|
||||
Individual(child, type("", (), {"parser": self.gedcom})())
|
||||
)
|
||||
return children
|
||||
|
||||
def get_partners(self) -> List['Individual']:
|
||||
def get_partners(self) -> List["Individual"]:
|
||||
"""
|
||||
Get this person's spouses/partners.
|
||||
|
||||
@@ -150,18 +148,12 @@ class Individual:
|
||||
"""
|
||||
partners = []
|
||||
for family in self.gedcom.get_families(self.element):
|
||||
parent_elements = self.gedcom.get_family_members(
|
||||
family,
|
||||
'PARENTS'
|
||||
)
|
||||
parent_elements = self.gedcom.get_family_members(family, "PARENTS")
|
||||
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})()
|
||||
)
|
||||
Individual(parent, type("", (), {"parser": self.gedcom})())
|
||||
)
|
||||
return partners
|
||||
|
||||
@@ -180,42 +172,40 @@ class Individual:
|
||||
for family in self.gedcom.get_families(self.element):
|
||||
# Get partner
|
||||
partners = []
|
||||
for parent in self.gedcom.get_family_members(family, 'PARENTS'):
|
||||
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})()
|
||||
)
|
||||
Individual(parent, type("", (), {"parser": self.gedcom})())
|
||||
)
|
||||
|
||||
# Get marriage info
|
||||
marriage_date = ''
|
||||
marriage_place = ''
|
||||
marriage_date = ""
|
||||
marriage_place = ""
|
||||
for child in family.get_child_elements():
|
||||
if child.get_tag() == 'MARR':
|
||||
if child.get_tag() == "MARR":
|
||||
for subchild in child.get_child_elements():
|
||||
if subchild.get_tag() == 'DATE':
|
||||
if subchild.get_tag() == "DATE":
|
||||
marriage_date = subchild.get_value()
|
||||
elif subchild.get_tag() == 'PLAC':
|
||||
elif subchild.get_tag() == "PLAC":
|
||||
marriage_place = subchild.get_value()
|
||||
|
||||
# Get children
|
||||
children = []
|
||||
for child in self.gedcom.get_family_members(
|
||||
family,
|
||||
gedcom.tags.GEDCOM_TAG_CHILD
|
||||
family, gedcom.tags.GEDCOM_TAG_CHILD
|
||||
):
|
||||
children.append(
|
||||
Individual(child, type('', (), {'parser': self.gedcom})())
|
||||
Individual(child, type("", (), {"parser": self.gedcom})())
|
||||
)
|
||||
|
||||
families.append({
|
||||
'partner': partners[0] if partners else None,
|
||||
'marriage_date': marriage_date,
|
||||
'marriage_place': marriage_place,
|
||||
'children': children
|
||||
})
|
||||
families.append(
|
||||
{
|
||||
"partner": partners[0] if partners else None,
|
||||
"marriage_date": marriage_date,
|
||||
"marriage_place": marriage_place,
|
||||
"children": children,
|
||||
}
|
||||
)
|
||||
|
||||
return families
|
||||
|
||||
@@ -232,20 +222,20 @@ class Individual:
|
||||
tag = child.get_tag()
|
||||
|
||||
# Common event tags
|
||||
if tag in ['BIRT', 'DEAT', 'MARR', 'OCCU', 'EDUC', 'RESI', 'BURI']:
|
||||
if tag in ["BIRT", "DEAT", "MARR", "OCCU", "EDUC", "RESI", "BURI"]:
|
||||
event = {
|
||||
'type': tag,
|
||||
'date': '',
|
||||
'place': '',
|
||||
'details': child.get_value() or ''
|
||||
"type": tag,
|
||||
"date": "",
|
||||
"place": "",
|
||||
"details": child.get_value() or "",
|
||||
}
|
||||
|
||||
# Extract date and place
|
||||
for subchild in child.get_child_elements():
|
||||
if subchild.get_tag() == 'DATE':
|
||||
event['date'] = subchild.get_value()
|
||||
elif subchild.get_tag() == 'PLAC':
|
||||
event['place'] = subchild.get_value()
|
||||
if subchild.get_tag() == "DATE":
|
||||
event["date"] = subchild.get_value()
|
||||
elif subchild.get_tag() == "PLAC":
|
||||
event["place"] = subchild.get_value()
|
||||
|
||||
events.append(event)
|
||||
|
||||
@@ -261,30 +251,24 @@ class Individual:
|
||||
images = []
|
||||
|
||||
for child in self.element.get_child_elements():
|
||||
if child.get_tag() == 'OBJE':
|
||||
if child.get_tag() == "OBJE":
|
||||
# OBJE can have a reference or inline data
|
||||
reference = child.get_value()
|
||||
if reference and reference.startswith('@'):
|
||||
if reference and reference.startswith("@"):
|
||||
# Resolve the reference to get actual file info
|
||||
obje_element = self.gedcom.get_element_dictionary().get(
|
||||
reference
|
||||
)
|
||||
obje_element = self.gedcom.get_element_dictionary().get(reference)
|
||||
if obje_element:
|
||||
image_info = {
|
||||
'file': '',
|
||||
'title': '',
|
||||
'format': ''
|
||||
}
|
||||
image_info = {"file": "", "title": "", "format": ""}
|
||||
|
||||
for obje_child in obje_element.get_child_elements():
|
||||
if obje_child.get_tag() == 'FILE':
|
||||
image_info['file'] = obje_child.get_value() or ''
|
||||
elif obje_child.get_tag() == 'TITL':
|
||||
image_info['title'] = obje_child.get_value() or ''
|
||||
elif obje_child.get_tag() == 'FORM':
|
||||
image_info['format'] = obje_child.get_value() or ''
|
||||
if obje_child.get_tag() == "FILE":
|
||||
image_info["file"] = obje_child.get_value() or ""
|
||||
elif obje_child.get_tag() == "TITL":
|
||||
image_info["title"] = obje_child.get_value() or ""
|
||||
elif obje_child.get_tag() == "FORM":
|
||||
image_info["format"] = obje_child.get_value() or ""
|
||||
|
||||
if image_info['file']:
|
||||
if image_info["file"]:
|
||||
images.append(image_info)
|
||||
|
||||
return images
|
||||
@@ -299,30 +283,28 @@ class Individual:
|
||||
notes = []
|
||||
|
||||
for child in self.element.get_child_elements():
|
||||
if child.get_tag() == 'NOTE':
|
||||
note_text = child.get_value() or ''
|
||||
if child.get_tag() == "NOTE":
|
||||
note_text = child.get_value() or ""
|
||||
|
||||
# If note_text starts with @, it's a reference to a NOTE record
|
||||
if note_text.startswith('@') and note_text.endswith('@'):
|
||||
if note_text.startswith("@") and note_text.endswith("@"):
|
||||
# Resolve the reference
|
||||
note_element = self.gedcom.get_element_dictionary().get(
|
||||
note_text
|
||||
)
|
||||
note_element = self.gedcom.get_element_dictionary().get(note_text)
|
||||
if note_element:
|
||||
# Get the note text from the NOTE element
|
||||
note_text = note_element.get_value() or ''
|
||||
note_text = note_element.get_value() or ""
|
||||
|
||||
# Get continued text from the NOTE record
|
||||
for subchild in note_element.get_child_elements():
|
||||
if subchild.get_tag() in ['CONT', 'CONC']:
|
||||
note_text += '\n' + (subchild.get_value() or '')
|
||||
if subchild.get_tag() in ["CONT", "CONC"]:
|
||||
note_text += "\n" + (subchild.get_value() or "")
|
||||
else:
|
||||
# Inline note - check for continued text in subchilds
|
||||
for subchild in child.get_child_elements():
|
||||
if subchild.get_tag() in ['CONT', 'CONC']:
|
||||
note_text += '\n' + (subchild.get_value() or '')
|
||||
if subchild.get_tag() in ["CONT", "CONC"]:
|
||||
note_text += "\n" + (subchild.get_value() or "")
|
||||
|
||||
if note_text and not note_text.startswith('@'):
|
||||
if note_text and not note_text.startswith("@"):
|
||||
notes.append(note_text.strip())
|
||||
|
||||
return notes
|
||||
@@ -341,75 +323,83 @@ class Individual:
|
||||
stories = []
|
||||
|
||||
for child in self.element.get_child_elements():
|
||||
if child.get_tag() == '_STO':
|
||||
if child.get_tag() == "_STO":
|
||||
story_ref = child.get_value()
|
||||
|
||||
if story_ref and story_ref.startswith('@'):
|
||||
if story_ref and story_ref.startswith("@"):
|
||||
# Resolve the story reference
|
||||
story_element = self.gedcom.get_element_dictionary().get(
|
||||
story_ref
|
||||
)
|
||||
story_element = self.gedcom.get_element_dictionary().get(story_ref)
|
||||
if story_element:
|
||||
story = {
|
||||
'title': '',
|
||||
'description': '',
|
||||
'sections': []
|
||||
}
|
||||
story = {"title": "", "description": "", "sections": []}
|
||||
|
||||
# Get main title and metadata
|
||||
for section in story_element.get_child_elements():
|
||||
tag = section.get_tag()
|
||||
|
||||
if tag == 'TITL':
|
||||
story['title'] = section.get_value() or ''
|
||||
elif tag == 'DESC':
|
||||
story['description'] = section.get_value() or ''
|
||||
elif tag == '_STS':
|
||||
if tag == "TITL":
|
||||
story["title"] = section.get_value() or ""
|
||||
elif tag == "DESC":
|
||||
story["description"] = section.get_value() or ""
|
||||
elif tag == "_STS":
|
||||
# Story section with inline content
|
||||
# Format: "1 @12375128@ _STS"
|
||||
# Children at level 2 contain TITL, TEXT, OBJE
|
||||
section_data = {
|
||||
'subtitle': '',
|
||||
'text': '',
|
||||
'images': []
|
||||
"subtitle": "",
|
||||
"text": "",
|
||||
"images": [],
|
||||
}
|
||||
|
||||
# Extract content directly from child elements
|
||||
for sts_child in section.get_child_elements():
|
||||
if sts_child.get_tag() == 'TITL':
|
||||
section_data['subtitle'] = sts_child.get_value() or ''
|
||||
elif sts_child.get_tag() == 'TEXT':
|
||||
text = sts_child.get_value() or ''
|
||||
if sts_child.get_tag() == "TITL":
|
||||
section_data["subtitle"] = (
|
||||
sts_child.get_value() or ""
|
||||
)
|
||||
elif sts_child.get_tag() == "TEXT":
|
||||
text = sts_child.get_value() or ""
|
||||
# Get CONT lines
|
||||
for cont in sts_child.get_child_elements():
|
||||
if cont.get_tag() in ['CONT', 'CONC']:
|
||||
text += '\n' + (cont.get_value() or '')
|
||||
section_data['text'] = text
|
||||
elif sts_child.get_tag() == 'OBJE':
|
||||
if cont.get_tag() in ["CONT", "CONC"]:
|
||||
text += "\n" + (cont.get_value() or "")
|
||||
section_data["text"] = text
|
||||
elif sts_child.get_tag() == "OBJE":
|
||||
# Resolve image reference
|
||||
img_ref = sts_child.get_value()
|
||||
if img_ref and img_ref.startswith('@'):
|
||||
obje_element = self.gedcom.get_element_dictionary().get(img_ref)
|
||||
if img_ref and img_ref.startswith("@"):
|
||||
obje_element = self.gedcom.get_element_dictionary().get(
|
||||
img_ref
|
||||
)
|
||||
if obje_element:
|
||||
image_info = {
|
||||
'file': '',
|
||||
'title': '',
|
||||
'format': ''
|
||||
"file": "",
|
||||
"title": "",
|
||||
"format": "",
|
||||
}
|
||||
for obje_child in obje_element.get_child_elements():
|
||||
if obje_child.get_tag() == 'FILE':
|
||||
image_info['file'] = obje_child.get_value() or ''
|
||||
elif obje_child.get_tag() == 'TITL':
|
||||
image_info['title'] = obje_child.get_value() or ''
|
||||
elif obje_child.get_tag() == 'FORM':
|
||||
image_info['format'] = obje_child.get_value() or ''
|
||||
if image_info['file']:
|
||||
section_data['images'].append(image_info)
|
||||
for (
|
||||
obje_child
|
||||
) in obje_element.get_child_elements():
|
||||
if obje_child.get_tag() == "FILE":
|
||||
image_info["file"] = (
|
||||
obje_child.get_value() or ""
|
||||
)
|
||||
elif obje_child.get_tag() == "TITL":
|
||||
image_info["title"] = (
|
||||
obje_child.get_value() or ""
|
||||
)
|
||||
elif obje_child.get_tag() == "FORM":
|
||||
image_info["format"] = (
|
||||
obje_child.get_value() or ""
|
||||
)
|
||||
if image_info["file"]:
|
||||
section_data["images"].append(
|
||||
image_info
|
||||
)
|
||||
|
||||
if section_data['subtitle'] or section_data['text']:
|
||||
story['sections'].append(section_data)
|
||||
if section_data["subtitle"] or section_data["text"]:
|
||||
story["sections"].append(section_data)
|
||||
|
||||
if story['title'] or story['sections']:
|
||||
if story["title"] or story["sections"]:
|
||||
stories.append(story)
|
||||
|
||||
return stories
|
||||
@@ -427,7 +417,7 @@ class Individual:
|
||||
tag = child.get_tag()
|
||||
|
||||
# Physical attributes
|
||||
if tag in ['EYES', 'HAIR', 'HEIG']:
|
||||
attributes[tag.lower()] = child.get_value() or ''
|
||||
if tag in ["EYES", "HAIR", "HEIG"]:
|
||||
attributes[tag.lower()] = child.get_value() or ""
|
||||
|
||||
return attributes
|
||||
+49
-42
@@ -26,8 +26,8 @@ def setup_logging(verbose: bool = False):
|
||||
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'
|
||||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
|
||||
|
||||
@@ -49,27 +49,29 @@ def extract_gedzip(zip_path: Path, temp_dir: Path) -> Tuple[Path, Optional[Path]
|
||||
logger.info(f"Extracting ZIP archive: {zip_path}")
|
||||
|
||||
# Extract the ZIP file
|
||||
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
||||
with zipfile.ZipFile(zip_path, "r") as zip_ref:
|
||||
zip_ref.extractall(temp_dir)
|
||||
|
||||
logger.info(f"Extracted to: {temp_dir}")
|
||||
|
||||
# Find the GEDCOM file (should have .ged extension)
|
||||
gedcom_files = list(temp_dir.glob('**/*.ged'))
|
||||
gedcom_files = list(temp_dir.glob("**/*.ged"))
|
||||
|
||||
if not gedcom_files:
|
||||
raise ValueError("No GEDCOM (.ged) file found in the ZIP archive")
|
||||
|
||||
if len(gedcom_files) > 1:
|
||||
logger.warning(f"Found {len(gedcom_files)} GEDCOM files, using first: {gedcom_files[0]}")
|
||||
logger.warning(
|
||||
f"Found {len(gedcom_files)} GEDCOM files, using first: {gedcom_files[0]}"
|
||||
)
|
||||
|
||||
gedcom_file = gedcom_files[0]
|
||||
logger.info(f"Found GEDCOM file: {gedcom_file.name}")
|
||||
|
||||
# Find media directory (look for common image extensions)
|
||||
media_dir = None
|
||||
for ext in ['*.jpg', '*.jpeg', '*.png', '*.gif', '*.bmp']:
|
||||
media_files = list(temp_dir.glob(f'**/{ext}'))
|
||||
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
|
||||
@@ -84,7 +86,7 @@ def convert_gedcom_to_markdown(
|
||||
output_dir: Path,
|
||||
create_index: bool = True,
|
||||
media_dir: Optional[Path] = None,
|
||||
use_flat_structure: bool = False
|
||||
use_flat_structure: bool = False,
|
||||
) -> int:
|
||||
"""
|
||||
Convert a GEDCOM file to markdown notes.
|
||||
@@ -107,14 +109,14 @@ def convert_gedcom_to_markdown(
|
||||
people_dir = output_dir
|
||||
media_output_dir = output_dir
|
||||
stories_dir = output_dir
|
||||
media_subdir_name = ''
|
||||
stories_subdir_name = ''
|
||||
media_subdir_name = ""
|
||||
stories_subdir_name = ""
|
||||
else:
|
||||
people_dir = output_dir / 'people'
|
||||
media_output_dir = output_dir / 'media'
|
||||
stories_dir = output_dir / 'stories'
|
||||
media_subdir_name = 'media'
|
||||
stories_subdir_name = 'stories'
|
||||
people_dir = output_dir / "people"
|
||||
media_output_dir = output_dir / "media"
|
||||
stories_dir = output_dir / "stories"
|
||||
media_subdir_name = "media"
|
||||
stories_subdir_name = "stories"
|
||||
|
||||
# Create subdirectories
|
||||
people_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -134,9 +136,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) for elem in individual_elements]
|
||||
|
||||
# Generate markdown notes
|
||||
logger.info(f"Generating markdown notes in: {people_dir}")
|
||||
@@ -144,7 +144,7 @@ def convert_gedcom_to_markdown(
|
||||
people_dir,
|
||||
media_subdir=media_subdir_name,
|
||||
stories_subdir=stories_subdir_name,
|
||||
stories_dir=stories_dir
|
||||
stories_dir=stories_dir,
|
||||
)
|
||||
created_files = generator.generate_all(individuals)
|
||||
logger.info(f"Created {len(created_files)} markdown files")
|
||||
@@ -153,7 +153,16 @@ def convert_gedcom_to_markdown(
|
||||
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']:
|
||||
for ext in [
|
||||
"*.jpg",
|
||||
"*.jpeg",
|
||||
"*.png",
|
||||
"*.gif",
|
||||
"*.bmp",
|
||||
"*.JPG",
|
||||
"*.JPEG",
|
||||
"*.PNG",
|
||||
]:
|
||||
media_files.extend(media_dir.glob(ext))
|
||||
|
||||
copied_count = 0
|
||||
@@ -167,7 +176,7 @@ def convert_gedcom_to_markdown(
|
||||
# Generate index
|
||||
if create_index:
|
||||
logger.info("Generating index file")
|
||||
people_subdir_name = '' if use_flat_structure else 'people'
|
||||
people_subdir_name = "" if use_flat_structure else "people"
|
||||
index_gen = IndexGenerator(output_dir, people_subdir=people_subdir_name)
|
||||
index_path = index_gen.generate_index(individuals)
|
||||
logger.info(f"Created index file: {index_path}")
|
||||
@@ -189,42 +198,40 @@ def convert_gedcom_to_markdown(
|
||||
def main():
|
||||
"""Main entry point for the CLI."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Convert GEDCOM genealogy files to Obsidian markdown notes',
|
||||
epilog='Example: python src/main.py --input family.zip --output vault/family'
|
||||
description="Convert GEDCOM genealogy files to Obsidian markdown notes",
|
||||
epilog="Example: python src/main.py --input family.zip --output vault/family",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'-i', '--input',
|
||||
"-i",
|
||||
"--input",
|
||||
type=Path,
|
||||
required=True,
|
||||
metavar='FILE',
|
||||
help='Path to input GEDCOM (.ged) or GEDZIP (.zip) file'
|
||||
metavar="FILE",
|
||||
help="Path to input GEDCOM (.ged) or GEDZIP (.zip) file",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'-o', '--output',
|
||||
"-o",
|
||||
"--output",
|
||||
type=Path,
|
||||
required=True,
|
||||
metavar='DIR',
|
||||
help='Output directory for generated notes'
|
||||
metavar="DIR",
|
||||
help="Output directory for generated notes",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--flat',
|
||||
action='store_true',
|
||||
help='Use flat structure (all files in output root). Default creates subdirectories: people/, media/, stories/'
|
||||
"--flat",
|
||||
action="store_true",
|
||||
help="Use flat structure (all files in output root). Default creates subdirectories: people/, media/, stories/",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--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(
|
||||
'-v', '--verbose',
|
||||
action='store_true',
|
||||
help='Enable verbose logging'
|
||||
"-v", "--verbose", action="store_true", help="Enable verbose logging"
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
@@ -242,7 +249,7 @@ def main():
|
||||
args.output.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Check if input is a ZIP file
|
||||
is_zip = args.input.suffix.lower() in ['.zip', '.gedzip']
|
||||
is_zip = args.input.suffix.lower() in [".zip", ".gedzip"]
|
||||
temp_dir = None
|
||||
gedcom_file = args.input
|
||||
media_dir = None
|
||||
@@ -250,7 +257,7 @@ def main():
|
||||
try:
|
||||
if is_zip:
|
||||
# Extract ZIP file to temporary directory
|
||||
temp_dir = Path(tempfile.mkdtemp(prefix='gedcom_'))
|
||||
temp_dir = Path(tempfile.mkdtemp(prefix="gedcom_"))
|
||||
gedcom_file, media_dir = extract_gedzip(args.input, temp_dir)
|
||||
|
||||
# Convert
|
||||
@@ -259,7 +266,7 @@ def main():
|
||||
output_dir=args.output,
|
||||
create_index=not args.no_index,
|
||||
media_dir=media_dir,
|
||||
use_flat_structure=args.flat
|
||||
use_flat_structure=args.flat,
|
||||
)
|
||||
|
||||
return exit_code
|
||||
@@ -271,5 +278,5 @@ def main():
|
||||
shutil.rmtree(temp_dir)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+74
-86
@@ -26,9 +26,9 @@ class MarkdownGenerator:
|
||||
def __init__(
|
||||
self,
|
||||
output_dir: Path,
|
||||
media_subdir: str = '',
|
||||
stories_subdir: str = '',
|
||||
stories_dir: Optional[Path] = None
|
||||
media_subdir: str = "",
|
||||
stories_subdir: str = "",
|
||||
stories_dir: Optional[Path] = None,
|
||||
):
|
||||
"""
|
||||
Initialize the generator.
|
||||
@@ -63,12 +63,12 @@ class MarkdownGenerator:
|
||||
Returns:
|
||||
Path to the created markdown file
|
||||
"""
|
||||
filename = individual.get_file_name() + '.md'
|
||||
filename = individual.get_file_name() + ".md"
|
||||
file_path = self.output_dir / filename
|
||||
|
||||
logger.info(f"Generating note: {filename}")
|
||||
|
||||
with open(file_path, 'w', encoding='utf-8') as f:
|
||||
with open(file_path, "w", encoding="utf-8") as f:
|
||||
# Write all sections
|
||||
self._write_header(f, individual)
|
||||
self._write_attributes(f, individual)
|
||||
@@ -92,26 +92,26 @@ class MarkdownGenerator:
|
||||
birth = individual.get_birth_info()
|
||||
death = individual.get_death_info()
|
||||
|
||||
self._write_metadata(f, 'ID', individual.get_id())
|
||||
self._write_metadata(f, 'Name', individual.get_full_name())
|
||||
self._write_metadata(f, "ID", individual.get_id())
|
||||
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)
|
||||
self._write_metadata(f, "Lived", lived)
|
||||
|
||||
self._write_metadata(f, 'Sex', individual.get_gender())
|
||||
self._write_metadata(f, "Sex", individual.get_gender())
|
||||
|
||||
# Birth details
|
||||
if birth['date']:
|
||||
self._write_metadata(f, 'Born', birth['date'])
|
||||
if birth['place']:
|
||||
self._write_metadata(f, 'Place of birth', birth['place'])
|
||||
if birth["date"]:
|
||||
self._write_metadata(f, "Born", birth["date"])
|
||||
if birth["place"]:
|
||||
self._write_metadata(f, "Place of birth", birth["place"])
|
||||
|
||||
# Death details
|
||||
if death['date']:
|
||||
self._write_metadata(f, 'Passed away', death['date'])
|
||||
if death['place']:
|
||||
self._write_metadata(f, 'Place of death', death['place'])
|
||||
if death["date"]:
|
||||
self._write_metadata(f, "Passed away", death["date"])
|
||||
if death["place"]:
|
||||
self._write_metadata(f, "Place of death", death["place"])
|
||||
|
||||
# Physical attributes
|
||||
attrs = individual.get_attributes()
|
||||
@@ -119,15 +119,14 @@ class MarkdownGenerator:
|
||||
if value:
|
||||
self._write_metadata(f, key.capitalize(), value)
|
||||
|
||||
f.write('\n')
|
||||
f.write("\n")
|
||||
|
||||
def _write_events(self, f, individual: Individual):
|
||||
"""Write life events section."""
|
||||
events = individual.get_events()
|
||||
|
||||
# Filter out birth and death (already in attributes)
|
||||
other_events = [e for e in events
|
||||
if e['type'] not in ['BIRT', 'DEAT']]
|
||||
other_events = [e for e in events if e["type"] not in ["BIRT", "DEAT"]]
|
||||
|
||||
if not other_events:
|
||||
return
|
||||
@@ -135,27 +134,27 @@ class MarkdownGenerator:
|
||||
f.write("## Life Events\n")
|
||||
|
||||
event_names = {
|
||||
'MARR': 'Marriage',
|
||||
'OCCU': 'Occupation',
|
||||
'EDUC': 'Education',
|
||||
'RESI': 'Residence',
|
||||
'BURI': 'Burial'
|
||||
"MARR": "Marriage",
|
||||
"OCCU": "Occupation",
|
||||
"EDUC": "Education",
|
||||
"RESI": "Residence",
|
||||
"BURI": "Burial",
|
||||
}
|
||||
|
||||
for event in other_events:
|
||||
event_type = event_names.get(event['type'], event['type'])
|
||||
event_type = event_names.get(event["type"], event["type"])
|
||||
f.write(f"### {event_type}\n")
|
||||
|
||||
if event['date']:
|
||||
if event["date"]:
|
||||
f.write(f"- **Date**: {event['date']}\n")
|
||||
if event['place']:
|
||||
if event["place"]:
|
||||
f.write(f"- **Place**: {event['place']}\n")
|
||||
if event['details']:
|
||||
if event["details"]:
|
||||
f.write(f"- **Details**: {event['details']}\n")
|
||||
|
||||
f.write('\n')
|
||||
f.write("\n")
|
||||
|
||||
f.write('\n')
|
||||
f.write("\n")
|
||||
|
||||
def _write_families(self, f, individual: Individual):
|
||||
"""Write families/marriages section."""
|
||||
@@ -167,40 +166,30 @@ class MarkdownGenerator:
|
||||
f.write("## Families\n")
|
||||
|
||||
for i, family in enumerate(families, 1):
|
||||
if family['partner']:
|
||||
partner_name = family['partner'].get_file_name()
|
||||
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)
|
||||
)
|
||||
self._write_metadata_hidden(f, "Partner", self._wiki_link(partner_name))
|
||||
|
||||
if family['marriage_date']:
|
||||
if family["marriage_date"]:
|
||||
self._write_metadata_hidden(
|
||||
f,
|
||||
'Marriage date',
|
||||
family['marriage_date']
|
||||
f, "Marriage date", family["marriage_date"]
|
||||
)
|
||||
if family['marriage_place']:
|
||||
if family["marriage_place"]:
|
||||
self._write_metadata_hidden(
|
||||
f,
|
||||
'Marriage place',
|
||||
family['marriage_place']
|
||||
f, "Marriage place", family["marriage_place"]
|
||||
)
|
||||
|
||||
if family['children']:
|
||||
f.write('\n**Children:**\n')
|
||||
for child in family['children']:
|
||||
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, "Child", self._wiki_link(child.get_file_name())
|
||||
)
|
||||
|
||||
f.write('\n')
|
||||
f.write("\n")
|
||||
|
||||
f.write('\n')
|
||||
f.write("\n")
|
||||
|
||||
def _write_parents(self, f, individual: Individual):
|
||||
"""Write parents section."""
|
||||
@@ -213,12 +202,10 @@ class MarkdownGenerator:
|
||||
|
||||
for parent in parents:
|
||||
self._write_metadata_hidden(
|
||||
f,
|
||||
'Parent',
|
||||
self._wiki_link(parent.get_file_name())
|
||||
f, "Parent", self._wiki_link(parent.get_file_name())
|
||||
)
|
||||
|
||||
f.write('\n')
|
||||
f.write("\n")
|
||||
|
||||
def _write_children(self, f, individual: Individual):
|
||||
"""Write children section (if not already in families)."""
|
||||
@@ -235,12 +222,10 @@ class MarkdownGenerator:
|
||||
|
||||
for child in children:
|
||||
self._write_metadata_hidden(
|
||||
f,
|
||||
'Child',
|
||||
self._wiki_link(child.get_file_name())
|
||||
f, "Child", self._wiki_link(child.get_file_name())
|
||||
)
|
||||
|
||||
f.write('\n')
|
||||
f.write("\n")
|
||||
|
||||
def _write_images(self, f, individual: Individual):
|
||||
"""Write images section."""
|
||||
@@ -252,8 +237,8 @@ class MarkdownGenerator:
|
||||
f.write("## Images\n")
|
||||
|
||||
for image in images:
|
||||
title = image['title'] if image['title'] else 'Image'
|
||||
filename = image['file']
|
||||
title = image["title"] if image["title"] else "Image"
|
||||
filename = image["file"]
|
||||
# Add media subdirectory prefix if specified
|
||||
if self.media_subdir:
|
||||
image_path = f"{self.media_subdir}/{filename}"
|
||||
@@ -261,7 +246,7 @@ class MarkdownGenerator:
|
||||
image_path = filename
|
||||
f.write(f"\n\n")
|
||||
|
||||
f.write('\n')
|
||||
f.write("\n")
|
||||
|
||||
def _generate_story_file(self, story: dict, individual_name: str) -> str:
|
||||
"""
|
||||
@@ -274,29 +259,31 @@ class MarkdownGenerator:
|
||||
Returns:
|
||||
Filename of the generated story (for WikiLink)
|
||||
"""
|
||||
story_title = story['title'] if story['title'] else 'Untitled Story'
|
||||
story_title = story["title"] if story["title"] else "Untitled Story"
|
||||
# Create a safe filename
|
||||
safe_title = story_title.replace('/', '-').replace('\\', '-')
|
||||
safe_title = story_title.replace("/", "-").replace("\\", "-")
|
||||
filename = f"{safe_title}.md"
|
||||
file_path = self.stories_dir / filename
|
||||
|
||||
# Check if we've already generated this story
|
||||
if filename in self.generated_stories:
|
||||
return filename.replace('.md', '')
|
||||
return filename.replace(".md", "")
|
||||
|
||||
logger.debug(f"Generating story file: {filename}")
|
||||
|
||||
with open(file_path, 'w', encoding='utf-8') as f:
|
||||
with open(file_path, "w", encoding="utf-8") as f:
|
||||
# Write story header
|
||||
f.write(f"# {story_title}\n\n")
|
||||
|
||||
# Write description if available
|
||||
if story['description']:
|
||||
if story["description"]:
|
||||
f.write(f"*{story['description']}*\n\n")
|
||||
|
||||
# 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.media_subdir
|
||||
): # If using subdirs (media_subdir is set), use path prefix
|
||||
person_link = f"[[people/{individual_name}|{individual_name}]]"
|
||||
else:
|
||||
person_link = f"[[{individual_name}]]"
|
||||
@@ -305,18 +292,18 @@ class MarkdownGenerator:
|
||||
f.write("---\n\n")
|
||||
|
||||
# Write each section
|
||||
for section in story['sections']:
|
||||
if section['subtitle']:
|
||||
for section in story["sections"]:
|
||||
if section["subtitle"]:
|
||||
f.write(f"## {section['subtitle']}\n\n")
|
||||
|
||||
if section['text']:
|
||||
if section["text"]:
|
||||
f.write(f"{section['text']}\n\n")
|
||||
|
||||
# Write images for this section
|
||||
if section['images']:
|
||||
for img in section['images']:
|
||||
title = img['title'] if img['title'] else 'Image'
|
||||
filename_img = img['file']
|
||||
if section["images"]:
|
||||
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:
|
||||
image_path = f"../{self.media_subdir}/{filename_img}"
|
||||
@@ -328,7 +315,7 @@ class MarkdownGenerator:
|
||||
self.generated_stories[filename] = True
|
||||
|
||||
# Return the note name for WikiLink (without .md extension)
|
||||
return filename.replace('.md', '')
|
||||
return filename.replace(".md", "")
|
||||
|
||||
def _write_notes(self, f, individual: Individual):
|
||||
"""Write notes section."""
|
||||
@@ -354,23 +341,25 @@ class MarkdownGenerator:
|
||||
story_note_name = self._generate_story_file(story, individual_name)
|
||||
|
||||
# Create a WikiLink to the story
|
||||
story_title = story['title'] if story['title'] else 'Untitled Story'
|
||||
story_title = story["title"] if story["title"] else "Untitled Story"
|
||||
|
||||
# Use proper path prefix if using subdirectories
|
||||
if self.stories_subdir:
|
||||
story_link = f"[[{self.stories_subdir}/{story_note_name}|{story_title}]]"
|
||||
story_link = (
|
||||
f"[[{self.stories_subdir}/{story_note_name}|{story_title}]]"
|
||||
)
|
||||
else:
|
||||
story_link = f"[[{story_note_name}|{story_title}]]"
|
||||
|
||||
# Write the link with description if available
|
||||
if story['description']:
|
||||
if story["description"]:
|
||||
f.write(f"- {story_link} - *{story['description']}*\n")
|
||||
else:
|
||||
f.write(f"- {story_link}\n")
|
||||
|
||||
f.write('\n')
|
||||
f.write("\n")
|
||||
|
||||
f.write('\n')
|
||||
f.write("\n")
|
||||
|
||||
def _write_metadata(self, f, key: str, value: str):
|
||||
"""Write visible Obsidian metadata."""
|
||||
@@ -403,8 +392,7 @@ class MarkdownGenerator:
|
||||
paths.append(path)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Failed to generate note for "
|
||||
f"{individual.get_full_name()}: {e}"
|
||||
f"Failed to generate note for {individual.get_full_name()}: {e}"
|
||||
)
|
||||
|
||||
logger.info(f"Successfully generated {len(paths)} notes")
|
||||
|
||||
Reference in new issue
Block a user