Initializes GEDCOM to Markdown converter project #1

Merged
AlexKucera merged 29 commits from initial_features into main 2025-11-02 17:47:20 +01:00
3 changed files with 176 additions and 21 deletions
Showing only changes of commit 02b27409d8 - Show all commits

No files matched your search

+55 -13
View File
@@ -4,11 +4,14 @@ Convert GEDCOM genealogy files to Obsidian-compatible markdown notes with WikiLi
## Features ## Features
- **GEDZIP Support**: Automatically extracts and processes ZIP archives with media files
- **Automatic Line Ending Fix**: Detects and corrects Mac-style line endings
- **Complete Individual Notes**: Generates detailed markdown notes for each person - **Complete Individual Notes**: Generates detailed markdown notes for each person
- **WikiLinks**: All relationships use `[[WikiLinks]]` format for Obsidian - **WikiLinks**: All relationships use `[[WikiLinks]]` format for Obsidian
- **Comprehensive Data**: Captures births, deaths, marriages, events, physical attributes, images, and notes - **Comprehensive Data**: Captures births, deaths, marriages, events, physical attributes, images, and notes
- **Multiple Marriages**: Supports individuals with multiple spouses - **Multiple Marriages**: Supports individuals with multiple spouses
- **Life Stories**: Extracts long-form narratives and stories - **Life Stories**: Extracts long-form narratives and stories with embedded images
- **Media Management**: Automatically copies and organizes image files
- **Global Index**: Creates an alphabetical index of all individuals - **Global Index**: Creates an alphabetical index of all individuals
- **Proper Naming**: Files named as "FamilyName FirstName BirthYear.md" - **Proper Naming**: Files named as "FamilyName FirstName BirthYear.md"
@@ -20,24 +23,49 @@ pip install -r requirements.txt
## Usage ## Usage
### Basic Usage
```bash ```bash
python src/main.py path/to/family.ged output/directory python src/main.py path/to/family.ged output/directory
``` ```
### GEDZIP Support (Recommended)
For best results, **export your genealogy data as a GEDZIP (ZIP) file** which includes both the GEDCOM data and all media files:
```bash
python src/main.py path/to/family.zip output/directory --media-subdir images
```
This will automatically:
- Extract the ZIP file
- Find and process the GEDCOM file
- Copy all media files to the output directory
- Fix line endings if needed
- Clean up temporary files
### Options ### Options
- `--no-index`: Skip creating the index file - `--no-index`: Skip creating the index file
- `--verbose` or `-v`: Enable detailed logging - `--verbose` or `-v`: Enable detailed logging
- `--media-subdir <name>`: Place media files in a subdirectory (e.g., "images")
### Example ### Examples
**With GEDZIP file (includes media):**
```bash ```bash
python src/main.py examples/Stammbaum_Kucera.ged examples/files --verbose python src/main.py examples/family.zip examples/output --media-subdir images --verbose
```
**With plain GEDCOM file:**
```bash
python src/main.py examples/family.ged examples/output --verbose
``` ```
This will create: This will create:
- One markdown file per person in `examples/files/` - One markdown file per person in the output directory
- An `Index.md` file with alphabetical listing - An `Index.md` file with alphabetical listing
- Media files in `output/images/` (if GEDZIP and --media-subdir used)
## Output Format ## Output Format
@@ -69,16 +97,15 @@ src/
### Line Ending Issue ### Line Ending Issue
**Important**: Some GEDCOM files exported from macOS applications may use old Mac-style line endings (CR only). If the parser finds 0 individuals, convert line endings first: Some GEDCOM files exported from macOS applications use old Mac-style line endings (CR only). **This is automatically detected and fixed** by the converter.
```bash If you see a warning message like:
python -c "
with open('file.ged', 'rb') as f:
content = f.read()
with open('file.ged', 'wb') as f:
f.write(content.replace(b'\r', b'\n'))
"
``` ```
WARNING - Detected old Mac-style (CR-only) line endings in GEDCOM file.
Converting to Unix-style (LF) line endings...
```
This is normal and the file will be automatically corrected. No manual intervention is needed.
### GEDCOM Version Compatibility ### GEDCOM Version Compatibility
@@ -86,4 +113,19 @@ This tool works best with **GEDCOM version 5.5.x or 5.x**. If you're using GEDCO
1. Choose GEDCOM version 5.5.1 or 5.1.0 if available 1. Choose GEDCOM version 5.5.1 or 5.1.0 if available
2. Avoid GEDCOM version 7.0+ for better compatibility 2. Avoid GEDCOM version 7.0+ for better compatibility
3. After export, check and fix line endings if needed (see above) 3. **Export as GEDZIP (ZIP)** to include media files automatically
### Exporting GEDZIP from Your Genealogy Software
Most genealogy applications support exporting to GEDZIP format:
- **Family Tree Maker**: File → Export → GEDCOM Package (includes media)
- **MobileFamilyTree**: Share → GEDCOM Package → Include Media
- **Ancestry**: Export family tree → Include media files → Download as ZIP
- **Gramps**: Family Trees → Export → GEDCOM with Media
The GEDZIP format is a standard ZIP archive containing:
- A `.ged` file with your family tree data
- All referenced media files (photos, documents, etc.)
This is the **recommended export format** for use with this converter.
+106 -5
View File
2
@@ -9,7 +9,11 @@ markdown notes with WikiLinks.
import argparse import argparse
import logging import logging
import sys import sys
import tempfile
import zipfile
import shutil
from pathlib import Path from pathlib import Path
from typing import Tuple, Optional
from gedcom_parser import GedcomParser from gedcom_parser import GedcomParser
from individual import Individual from individual import Individual
@@ -27,10 +31,60 @@ def setup_logging(verbose: bool = False):
) )
def extract_gedzip(zip_path: Path, temp_dir: Path) -> Tuple[Path, Optional[Path]]:
"""
Extract a GEDZIP file and locate the GEDCOM file and media directory.
Args:
zip_path: Path to the ZIP/GEDZIP file
temp_dir: Temporary directory for extraction
Returns:
Tuple of (gedcom_file_path, media_directory_path)
Raises:
ValueError: If no GEDCOM file is found in the archive
"""
logger = logging.getLogger(__name__)
logger.info(f"Extracting ZIP archive: {zip_path}")
# Extract the ZIP file
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'))
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]}")
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}'))
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
return gedcom_file, media_dir
def convert_gedcom_to_markdown( def convert_gedcom_to_markdown(
gedcom_file: Path, gedcom_file: Path,
output_dir: Path, output_dir: Path,
create_index: bool = True create_index: bool = True,
media_dir: Optional[Path] = None,
media_subdir: str = ''
) -> int: ) -> int:
""" """
Convert a GEDCOM file to markdown notes. Convert a GEDCOM file to markdown notes.
@@ -39,6 +93,8 @@ def convert_gedcom_to_markdown(
gedcom_file: Path to the input GEDCOM file gedcom_file: Path to the input GEDCOM file
output_dir: Directory for output markdown files output_dir: Directory for output markdown files
create_index: Whether to create an index file create_index: Whether to create an index file
media_dir: Optional directory containing media files to copy
media_subdir: Subdirectory name for media files (e.g., 'images')
Returns: Returns:
Exit code (0 for success, non-zero for failure) Exit code (0 for success, non-zero for failure)
@@ -65,10 +121,28 @@ def convert_gedcom_to_markdown(
# Generate markdown notes # Generate markdown notes
logger.info(f"Generating markdown notes in: {output_dir}") logger.info(f"Generating markdown notes in: {output_dir}")
generator = MarkdownGenerator(output_dir) generator = MarkdownGenerator(output_dir, media_subdir=media_subdir)
created_files = generator.generate_all(individuals) created_files = generator.generate_all(individuals)
logger.info(f"Created {len(created_files)} markdown files") logger.info(f"Created {len(created_files)} markdown files")
# Copy media files if available
if media_dir and media_dir.exists():
media_output_dir = output_dir / media_subdir if media_subdir else output_dir
media_output_dir.mkdir(parents=True, exist_ok=True)
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))
copied_count = 0
for media_file in media_files:
dest = media_output_dir / media_file.name
shutil.copy2(media_file, dest)
copied_count += 1
logger.info(f"Copied {copied_count} media files")
# Generate index # Generate index
if create_index: if create_index:
logger.info("Generating index file") logger.info("Generating index file")
@@ -99,7 +173,7 @@ def main():
parser.add_argument( parser.add_argument(
'gedcom_file', 'gedcom_file',
type=Path, type=Path,
help='Path to the input GEDCOM file' help='Path to the input GEDCOM (.ged) or GEDZIP (.zip) file'
) )
parser.add_argument( parser.add_argument(
@@ -120,6 +194,13 @@ def main():
help='Enable verbose logging' help='Enable verbose logging'
) )
parser.add_argument(
'--media-subdir',
type=str,
default='',
help='Subdirectory for media files (e.g., "images"). If not specified, media files are placed in output_dir.'
)
args = parser.parse_args() args = parser.parse_args()
# Setup logging # Setup logging
@@ -136,15 +217,35 @@ def main():
logger.info("Please create the output directory first") logger.info("Please create the output directory first")
return 1 return 1
# Check if input is a ZIP file
is_zip = args.gedcom_file.suffix.lower() in ['.zip', '.gedzip']
temp_dir = None
gedcom_file = args.gedcom_file
media_dir = None
try:
if is_zip:
# Extract ZIP file to temporary directory
temp_dir = Path(tempfile.mkdtemp(prefix='gedcom_'))
gedcom_file, media_dir = extract_gedzip(args.gedcom_file, temp_dir)
# Convert # Convert
exit_code = convert_gedcom_to_markdown( exit_code = convert_gedcom_to_markdown(
gedcom_file=args.gedcom_file, gedcom_file=gedcom_file,
output_dir=args.output_dir, output_dir=args.output_dir,
create_index=not args.no_index create_index=not args.no_index,
media_dir=media_dir,
media_subdir=args.media_subdir
) )
return exit_code return exit_code
finally:
# Clean up temporary directory
if temp_dir and temp_dir.exists():
logger.debug(f"Cleaning up temporary directory: {temp_dir}")
shutil.rmtree(temp_dir)
if __name__ == '__main__': if __name__ == '__main__':
sys.exit(main()) sys.exit(main())
+15 -3
View File
2
@@ -23,12 +23,13 @@ class MarkdownGenerator:
markdown with WikiLinks and metadata. markdown with WikiLinks and metadata.
""" """
def __init__(self, output_dir: Path): def __init__(self, output_dir: Path, media_subdir: str = ''):
""" """
Initialize the generator. Initialize the generator.
Args: Args:
output_dir: Directory where markdown files will be created output_dir: Directory where markdown files will be created
media_subdir: Subdirectory for media files (e.g., 'images')
Raises: Raises:
ValueError: If output_dir doesn't exist or isn't a directory ValueError: If output_dir doesn't exist or isn't a directory
@@ -39,6 +40,7 @@ class MarkdownGenerator:
raise ValueError(f"Output path is not a directory: {output_dir}") raise ValueError(f"Output path is not a directory: {output_dir}")
self.output_dir = output_dir self.output_dir = output_dir
self.media_subdir = media_subdir
def generate_note(self, individual: Individual) -> Path: def generate_note(self, individual: Individual) -> Path:
""" """
@@ -241,7 +243,12 @@ class MarkdownGenerator:
for image in images: for image in images:
title = image['title'] if image['title'] else 'Image' title = image['title'] if image['title'] else 'Image'
filename = image['file'] filename = image['file']
f.write(f"![{title}]({filename})\n\n") # Add media subdirectory prefix if specified
if self.media_subdir:
image_path = f"{self.media_subdir}/{filename}"
else:
image_path = filename
f.write(f"![{title}]({image_path})\n\n")
f.write('\n') f.write('\n')
@@ -280,7 +287,12 @@ class MarkdownGenerator:
for img in section['images']: for img in section['images']:
title = img['title'] if img['title'] else 'Image' title = img['title'] if img['title'] else 'Image'
filename = img['file'] filename = img['file']
f.write(f"![{title}]({filename})\n\n") # Add media subdirectory prefix if specified
if self.media_subdir:
image_path = f"{self.media_subdir}/{filename}"
else:
image_path = filename
f.write(f"![{title}]({image_path})\n\n")
f.write('\n') f.write('\n')