A custom Home Assistant integration that indexes media files (images and videos) from local folders, extracts EXIF/metadata, provides geocoding, and offers services for random media selection, favorites management, and file operations. Specifically designed for the Home Assistant Media Card, but can easily be used by any other card, integration or automation/script through Home Assistant Actions (Services) or WebSocket API calls.
- Automatic scanning of configured media folders
- File type detection for images (JPG, PNG, HEIC, etc.) and videos (MP4, MOV, AVI, etc.)
- Real-time monitoring with file system watcher for instant updates
- EXIF metadata extraction for images (GPS, date taken, camera info)
- Video metadata extraction for MP4/MOV files (creation date, GPS coordinates - see installation prerequisites below)
- Reverse geocoding of GPS coordinates to location names
- Smart caching to minimize API calls (Nominatim)
- Progressive geocoding during scans
- Location hierarchy: name → city → state → country
- Star ratings (0-5 stars) extracted from EXIF/XMP metadata
- Automatic favoriting of 5-star rated files
- Rating persistence:
- ✅ Images: Writes back to EXIF/XMP metadata
⚠️ Videos: Database-only (file writes disabled - see limitations below)
- Database tracking of favorite status
- Smart random selection with exclusion tracking
- Ordered selection by date, path, filename ascending or descending
- Filter by folder, file type, date range, favorites
- Anniversary mode for "Through the Years" features - find photos from the same date across all years
- Session management to avoid repetition within slideshow sessions
- Efficient querying from SQLite database
- Time-based burst detection - find photos taken within ±N seconds of a reference photo (default ±2 minutes)
- GPS-based filtering - match photos by location proximity using Haversine distance (default 50 meters)
- Automatic fallback to time-only matching when GPS data unavailable
- Burst metadata persistence - save favorite selections and burst counts to file metadata
- Historical tracking - burst review data persists even if files are deleted
- Delete media - moves files to
_Junkfolder - Mark for editing - moves files to
_Editfolder - Database cleanup - automatically removes deleted files from index
For Video Metadata Extraction (GPS, Date):
The integration uses pymediainfo (Python package) which requires the libmediainfo system library. You have two options:
-
Automatic Installation (Recommended for Home Assistant OS/Supervised): Enable the
auto_install_libmediainfooption in integration configuration. The integration will automatically install the library during setup if it's missing - no restart or reload needed! Video metadata extraction is available immediately when the integration finishes loading.⚠️ Note: After each Home Assistant core upgrade, the library will be automatically reinstalled during the next restart (the option stays enabled). -
Manual Installation: Install
libmediainfoyourself (instructions below). After installation, manually reload the integration in Settings → Devices & Services → Media Index → ⋮ → Reload.
Home Assistant OS/Supervised (Docker):
# SSH into your Home Assistant container or use the [Advanced SSH & Web Terminal](https://github.com/hassio-addons/addon-ssh) add-on available in Home Assistant OS
docker exec -it homeassistant bash
# Install libmediainfo
apk add libmediainfo
# Exit and restart Home Assistant
exitHome Assistant Core (Manual Install):
# Debian/Ubuntu
sudo apt-get install libmediainfo-dev
# Fedora/RHEL
sudo dnf install libmediainfo-devel
# macOS
brew install media-infoNote: If libmediainfo is not installed, video metadata extraction will be limited (no GPS or date extraction from videos). Image metadata extraction is unaffected.
or
- Open HACS in Home Assistant
- Click "Integrations"
- Search for 'Media Index'
- Click "Install"
- Install libmediainfo (see Prerequisites above if you need video metadata)
- Restart Home Assistant
- Copy the
custom_components/media_indexfolder to your Home Assistantcustom_componentsdirectory - Install libmediainfo (see Prerequisites above if you need video metadata)
- Restart Home Assistant
- Go to Settings → Devices & Services
- Click Add Integration
- Search for "Media Index"
- Enter your base media folder path (e.g.,
/media/Photos) - If your Media folders in the front end media browse dialogs are not prefixed by 'media-source://media_source/media', then copy and paste the full media-source:// URI (from the HA Media Card config) that points to the same place as the base media folder you specified in the previous step. It is critical that these both point to the same folder structure, e.g.:
- base media folder: /config/www/local
- media source URI: media-source://media_source/local
- Configure optional settings (watched folders, EXIF extraction, geocoding)
💡 Multi-Instance Support: You can add multiple instances with different base folders (e.g., one for Photos, one for Videos) by repeating this process with different folder paths.
Watched folders allow you to limit file system monitoring to specific subfolders within your base folder. If left empty, the entire base folder is watched.
Format: Comma-separated list of relative folder paths
Example:
If your base folder is: /media/Photo/OneDrive
And you want to watch:
/media/Photo/OneDrive/Mark-Pictures/Samsung Gallery/DCIM/Camera/media/Photo/OneDrive/Tanya-Pictures/Samsung Gallery/DCIM/Camera
✅ CORRECT Configuration:
Mark-Pictures/Samsung Gallery/DCIM/Camera, Tanya-Pictures/Samsung Gallery/DCIM/Camera
❌ INCORRECT - Do NOT use absolute paths:
/media/Photo/OneDrive/Mark-Pictures/Samsung Gallery/DCIM/Camera
This will fail because os.path.join() treats paths starting with / as absolute and ignores the base folder.
❌ INCORRECT - Do NOT include base folder in path:
media/Photo/OneDrive/Mark-Pictures/Samsung Gallery/DCIM/Camera
This will create an invalid path like /media/Photo/OneDrive/media/Photo/OneDrive/...
Notes:
- Paths are relative to your base folder
- Spaces in folder names are supported
- Leading/trailing whitespace is automatically trimmed
- Quotes are not needed (they're stripped automatically)
- The integration scans the entire base folder regardless, but watches only specified folders for real-time updates
After setup, you can reconfigure options via: Settings → Devices & Services → Media Index → Configure
⭐ Most Important Service - Move files from _Edit folder back to their original locations after editing.
When you use the Media Card's "Mark for Edit" button, files are moved to an _Edit folder for correction. After making your edits, run this service to restore them to their original locations.
Usage:
service: media_index.restore_edited_filesRecommendation: Run this service periodically (weekly/monthly) as part of your media management workflow.
The integration provides additional services for advanced use cases and Media Card integration. See SERVICES.md for complete documentation of all available services including:
get_random_items- Random media selection with anniversary mode support (used by Media Card)get_related_files- Find related photos by date/time or burst detection modeupdate_burst_metadata- Save burst review session data to file metadatamark_favorite- Toggle favorite statusdelete_media- Move files to_Junkfoldermark_for_edit- Move files to_Editfolderget_file_metadata- Get detailed metadatageocode_file- Force geocodingscan_folder- Manual folder scanning
The integration creates the following sensors for each configured entry:
State: Total number of files in database
Attributes:
scan_status: Current scan status (idle, scanning, error)last_scan_time: Timestamp of last scantotal_folders: Number of watched foldersgeocoded_files: Number of files with location datafavorited_files: Number of favorited files
The Media Index integration runs in the background to keep your media organized and accessible:
When first set up, the integration scans your configured folders and:
- Discovers all media files (images and videos) in your folders
- Extracts metadata like date taken, GPS coordinates, camera settings, and star ratings
- Stores everything in a local database for fast access during slideshows
After initial setup, the integration watches for changes:
- New files added → Automatically indexed and added to database
- Files moved/deleted → Database updated to reflect changes
- Files edited → Re-scanned to pick up metadata changes
For photos with GPS coordinates, the integration gradually adds location names:
- Rate limited to 1 request per second to respect Nominatim API limits
- Works progressively during scans - doesn't slow down initial indexing
- Caches results to avoid repeated API calls for the same coordinates
- Provides location hierarchy from specific place names to country level
- Language support: Uses Home Assistant's configured language by default
- Location names are cached permanently once geocoded
- Existing files keep their original language
- Only new files or manual
geocode_fileservice calls get the current language setting - To update all files to a new language: Use
geocode_fileservice individually or clear database and re-scan
The integration uses an optimized SQLite database that:
- Responds instantly to random media requests from your slideshow cards
- Tracks exclusions to avoid showing the same photos repeatedly
- Maintains favorites and ratings with both database and file metadata
- Grows efficiently as your media collection expands
This background processing means your Media Cards can display random photos instantly without scanning folders every time!
Media Index is designed to work seamlessly with the Home Assistant Media Card:
- Instant slideshow loading - No waiting for folder scans
- Smart random selection - Avoids repetition within slideshow sessions
- Rich metadata display - Shows location names, ratings, and EXIF data
- Interactive controls - Favorite, delete, and mark for editing directly from the card
- Background updates - New photos appear automatically without restart
- SQLite database for fast queries
- Geocoding cache reduces API calls by 90%+
- File watcher provides instant updates without full rescans
- Indexed queries for sub-millisecond random selection
- Exclusion tracking prevents repetition in 100+ item slideshows
Check Home Assistant logs for media_index errors:
Settings → System → Logs
Filter for media_index component.
No files found after scan:
- Verify folder paths are accessible from HA container
- Check file permissions
- Ensure folder paths don't have trailing slashes
Geocoding not working:
- Check internet connectivity
- Verify Nominatim API is accessible
- Review rate limiting (max 1 request/second)
File watcher not detecting changes:
- Ensure
enable_watcheris enabled in config - Check that watchdog library is installed
- Network shares may not support file system events
Database file: config/.storage/media_index_{entry_id}.db
To reset the database, delete this file and trigger a rescan.
✅ Full multi-instance support with target selectors
You can configure multiple integration instances (e.g., separate folders for Photos and Videos) and services will work with all instances using target selectors:
Usage:
service: media_index.restore_edited_files
target:
entity_id: sensor.media_index_photos_total_filesBenefits:
- Separate instances for different media collections
- Independent configuration per instance (different watched folders, settings)
- Services can target specific instances or all instances
Why?
exiftool(required for Windows-compatible rating tags) is not accessible in Home Assistant's executor thread contextmutagenlibrary can corrupt MP4 files when writing custom metadata tags- Safe MP4 metadata writes with
exiftoolrequire re-encoding the entire video (too resource-intensive)
Workaround:
- Video favorites/ratings persist in the SQLite database
- Use the planned export/import services (see Future Enhancements) to backup ratings
✅ Image ratings ARE written to EXIF/XMP metadata using piexif and work reliably.
Export all ratings to a portable JSON/CSV file for backup or migration.
Use cases:
- Backup before database reset
- Migrate to another Home Assistant instance
- Share rating data with external applications
Import ratings from an exported file and apply to matching files.
Features:
- Match files by path or hash
- Merge with existing ratings
- Update database and EXIF (for images)
For developers creating cards or integrations that consume Media Index services:
- Service Documentation: See SERVICES.md for complete API reference
- WebSocket API: See docs/DEVELOPER_API.md for WebSocket usage
- Multi-Instance Support: All services support target selectors for multiple instances
Contributions welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Test thoroughly
- Submit a pull request
MIT License - see LICENSE file
- Geocoding: Nominatim OpenStreetMap
- EXIF Extraction: piexif
- Video Metadata: mutagen
- File Watching: watchdog
- Issues: GitHub Issues
- Discussions: GitHub Discussions