This commit is contained in:
eddiesoehnel committed 2026-08-12 13:34:45 -06:00
1 parent f5aebfaf77
commit 87cc362513
1541 files changed
+25537 -2

No files matched your search

+12
View File
@@ -9,3 +9,15 @@ python scripts/audit_repository.py . --profile documentation-guide
```
The audit checks the required documentation/guide profile paths, manifest and repository-variable alignment, version alignment, declared entry points, and indexed content paths.
## Future Map Insights Hub
[`future-map-insights-hub/`](future-map-insights-hub/) contains the publisher that copies all Personal Organization JSON records tagged exactly `Future Map`, copies associated local media, and generates a browsable Markdown digest.
Run manually:
```text
python scripts/future-map-insights-hub/publish_future_map_insights.py
```
See [`future-map-insights-hub/README.md`](future-map-insights-hub/README.md) for daily scheduling and output details.
+48
View File
@@ -0,0 +1,48 @@
# Future Map Insights Hub Publisher
This workflow is adapted from `insights-hub-posts-last-6-months.py` in the Eddie Soehnel Portable Identity Document repository.
## Selection Rule
A source JSON record is included when its `HubTags` value contains the exact tag `Future Map`. Records may have additional tags. There is no date cutoff.
The loader accepts legacy literal control characters inside JSON strings so all otherwise valid tagged records are included. Copied JSON files remain byte-for-byte source copies.
## Source
- Hrecords: `C:\Users\edsoe\My Drive\Personal Organization\JSON_Database\hrecords`
- Media: `C:\Users\edsoe\My Drive\Personal Organization\JSON_Database\files`
## Outputs
- `data/insights-hub/hrecords/`: matching source JSON records
- `data/insights-hub/files/`: locally referenced `File` and `Image` assets
- `data/insights-hub/future-map-insights.md`: reverse-chronological Markdown digest with inline images
These directories are generated outputs. Do not edit generated JSON, media, or digest content manually; make source changes in the Personal Organization database and rerun the publisher.
Each run synchronizes the generated folders to the current exact-tag selection. Stale generated JSON and media copies are removed when they are no longer selected or referenced. They remain recoverable from the authoritative source database or by rerunning the publisher after restoring the source tag/reference.
## Run Manually
```text
python scripts/future-map-insights-hub/publish_future_map_insights.py
```
Or use the same runner used by Task Scheduler:
```text
powershell -NoProfile -ExecutionPolicy Bypass -File scripts/future-map-insights-hub/run_daily.ps1
```
Daily logs are written to the ignored repository-root `logs/` directory.
## Install the Daily Task
The default task name is `FutureMap-InsightsHub-Daily`, running every day at 6:00 AM local time:
```text
powershell -NoProfile -ExecutionPolicy Bypass -File scripts/future-map-insights-hub/install_daily_task.ps1
```
The task refreshes the local repository only. It does not stage, commit, push, or publish changes to Gitea.
@@ -0,0 +1,16 @@
param(
[string]$TaskName = "FutureMap-InsightsHub-Daily",
[string]$StartTime = "06:00"
)
$ErrorActionPreference = "Stop"
$scriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
$runner = Join-Path $scriptDirectory "run_daily.ps1"
$taskCommand = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File "' + $runner + '"'
& schtasks.exe /Create /TN $TaskName /SC DAILY /ST $StartTime /TR $taskCommand /F
if ($LASTEXITCODE -ne 0) {
throw "Unable to create scheduled task $TaskName."
}
& schtasks.exe /Query /TN $TaskName /V /FO LIST
@@ -0,0 +1,291 @@
#!/usr/bin/env python3
"""Publish all Insights Hub records tagged exactly ``Future Map``.
What it does:
1. Scans the Personal Organization JSON hrecords database.
2. Selects every record whose HubTags contains the exact value ``Future Map``.
3. Copies matching JSON files into ``data/insights-hub/hrecords``.
4. Copies referenced File/Image assets into ``data/insights-hub/files``.
5. Builds ``data/insights-hub/future-map-insights.md`` from all matching
records, sorted most recent first.
This script intentionally has no date cutoff. Run it manually or through the
included daily PowerShell runner.
"""
from __future__ import annotations
import json
import shutil
from datetime import date, datetime
from pathlib import Path
from typing import Any, Iterable
# -----------------------------
# CONFIG
# -----------------------------
SOURCE_HRECORDS_DIR = Path(
r"C:\Users\edsoe\My Drive\Personal Organization\JSON_Database\hrecords"
)
SOURCE_FILES_DIR = Path(
r"C:\Users\edsoe\My Drive\Personal Organization\JSON_Database\files"
)
REPOSITORY_ROOT = Path(__file__).resolve().parents[2]
TARGET_BASE_DIR = REPOSITORY_ROOT / "data" / "insights-hub"
TARGET_HRECORDS_DIR = TARGET_BASE_DIR / "hrecords"
TARGET_FILES_DIR = TARGET_BASE_DIR / "files"
OUTPUT_MD_FILE = TARGET_BASE_DIR / "future-map-insights.md"
REQUIRED_TAG = "Future Map"
# -----------------------------
# HELPERS
# -----------------------------
def parse_record_date(value: Any) -> date | None:
"""Parse common date formats found in hrecord JSON files."""
if not value:
return None
text = str(value).strip()
formats = [
"%m/%d/%Y",
"%Y-%m-%d",
"%Y/%m/%d",
"%m-%d-%Y",
"%B %d, %Y",
"%b %d, %Y",
]
for fmt in formats:
try:
return datetime.strptime(text, fmt).date()
except ValueError:
pass
return None
def normalize_to_list(value: Any) -> list[str]:
"""Accept strings, lists, or empty values and return clean strings."""
if value is None:
return []
if isinstance(value, list):
return [str(item).strip() for item in value if str(item).strip()]
if isinstance(value, str):
text = value.strip()
return [text] if text else []
text = str(value).strip()
return [text] if text else []
def has_required_tag(record: dict[str, Any]) -> bool:
"""Match exact tag membership, while allowing other tags on the record."""
return REQUIRED_TAG in normalize_to_list(record.get("HubTags"))
def safe_asset_names(record: dict[str, Any]) -> list[str]:
"""Return local File/Image references; ignore remote URLs."""
names: list[str] = []
for key in ("File", "Image"):
for item in normalize_to_list(record.get(key)):
if item.startswith(("http://", "https://")):
continue
names.append(item)
seen: set[str] = set()
cleaned: list[str] = []
for name in names:
if name not in seen:
cleaned.append(name)
seen.add(name)
return cleaned
def copy_file_if_exists(source: Path, target: Path) -> bool:
target.parent.mkdir(parents=True, exist_ok=True)
if not source.exists():
return False
shutil.copy2(source, target)
return True
def load_json_file(path: Path) -> dict[str, Any] | None:
try:
with path.open("r", encoding="utf-8-sig") as file_handle:
# Some legacy source records contain literal control characters
# inside JSON strings. Python's non-strict mode preserves those
# records without changing the copied source file.
data = json.load(file_handle, strict=False)
if isinstance(data, dict):
return data
print(f"SKIP non-object JSON: {path}")
return None
except Exception as exc:
print(f"SKIP unreadable JSON: {path} | {exc}")
return None
def markdown_text(value: Any) -> str:
"""Keep summaries intact so their existing Markdown remains usable."""
if value is None:
return ""
return str(value).strip()
def build_image_markdown(record: dict[str, Any]) -> str:
lines: list[str] = []
for image_name in normalize_to_list(record.get("Image")):
if image_name.startswith(("http://", "https://")):
image_src = image_name
else:
image_src = f"files/{Path(image_name).name}"
alt = markdown_text(record.get("Title")) or Path(image_name).stem
lines.append(f"![{alt}]({image_src})")
return "\n\n".join(lines)
def iter_json_files(folder: Path) -> Iterable[Path]:
yield from sorted(folder.glob("*.json"), key=lambda path: path.name)
def remove_stale_generated_files(folder: Path, expected_names: set[str]) -> int:
"""Remove generated copies no longer selected by the current source scan."""
removed = 0
for path in folder.iterdir():
if path.is_file() and path.name not in expected_names:
path.unlink()
removed += 1
return removed
# -----------------------------
# MAIN
# -----------------------------
def main() -> None:
TARGET_HRECORDS_DIR.mkdir(parents=True, exist_ok=True)
TARGET_FILES_DIR.mkdir(parents=True, exist_ok=True)
if not SOURCE_HRECORDS_DIR.exists():
raise FileNotFoundError(f"Source hrecords folder not found: {SOURCE_HRECORDS_DIR}")
if not SOURCE_FILES_DIR.exists():
print(f"WARNING: Source files folder not found: {SOURCE_FILES_DIR}")
print("JSON files will still be copied, but assets cannot be copied.")
matched_records: list[dict[str, Any]] = []
copied_json_count = 0
copied_asset_count = 0
missing_asset_count = 0
expected_json_names: set[str] = set()
expected_asset_names: set[str] = set()
for json_path in iter_json_files(SOURCE_HRECORDS_DIR):
record = load_json_file(json_path)
if not record or not has_required_tag(record):
continue
record_date = parse_record_date(record.get("Date"))
record["_json_filename"] = json_path.name
record["_parsed_date"] = record_date
matched_records.append(record)
expected_json_names.add(json_path.name)
if copy_file_if_exists(json_path, TARGET_HRECORDS_DIR / json_path.name):
copied_json_count += 1
for asset_name in safe_asset_names(record):
source_asset = SOURCE_FILES_DIR / asset_name
target_asset = TARGET_FILES_DIR / Path(asset_name).name
expected_asset_names.add(target_asset.name)
if copy_file_if_exists(source_asset, target_asset):
copied_asset_count += 1
else:
missing_asset_count += 1
print(f"MISSING asset referenced by {json_path.name}: {source_asset}")
removed_json_count = remove_stale_generated_files(
TARGET_HRECORDS_DIR, expected_json_names
)
removed_asset_count = remove_stale_generated_files(
TARGET_FILES_DIR, expected_asset_names
)
matched_records.sort(
key=lambda record: (
record.get("_parsed_date") or date.min,
str(record.get("HubID", "")),
),
reverse=True,
)
today = date.today()
md_lines = [
"# Future Map Insights Hub",
"",
f"Generated: {today.isoformat()}",
"",
f"Source tag: `{REQUIRED_TAG}`",
"",
f"Published records: {len(matched_records)}",
"",
"---",
"",
]
for record in matched_records:
title = markdown_text(record.get("Title")) or "Untitled"
summary = markdown_text(record.get("Summary"))
record_date = record.get("_parsed_date")
date_text = record_date.isoformat() if record_date else markdown_text(record.get("Date"))
md_lines.append(f"## {title}")
md_lines.append("")
if date_text:
md_lines.append(f"**Date:** {date_text}")
md_lines.append("")
if summary:
md_lines.append(summary)
md_lines.append("")
image_md = build_image_markdown(record)
if image_md:
md_lines.append(image_md)
md_lines.append("")
md_lines.append("---")
md_lines.append("")
OUTPUT_MD_FILE.write_text("\n".join(md_lines), encoding="utf-8")
print("DONE")
print(f"Required tag: {REQUIRED_TAG}")
print(f"Matched records: {len(matched_records)}")
print(f"Records in Markdown: {len(matched_records)}")
print(f"Copied JSON files: {copied_json_count}")
print(f"Copied assets: {copied_asset_count}")
print(f"Missing assets: {missing_asset_count}")
print(f"Removed stale JSON files: {removed_json_count}")
print(f"Removed stale assets: {removed_asset_count}")
print(f"Markdown output: {OUTPUT_MD_FILE}")
if __name__ == "__main__":
main()
@@ -0,0 +1,26 @@
param(
[string]$PythonExecutable = "C:\Users\edsoe\AppData\Local\Programs\Python\Python313\python.exe"
)
$ErrorActionPreference = "Stop"
$scriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
$repositoryRoot = (Resolve-Path (Join-Path $scriptDirectory "..\..")).Path
$publisher = Join-Path $scriptDirectory "publish_future_map_insights.py"
$logDirectory = Join-Path $repositoryRoot "logs"
$logFile = Join-Path $logDirectory ("future-map-insights-hub-" + (Get-Date -Format "yyyy-MM-dd") + ".log")
New-Item -ItemType Directory -Path $logDirectory -Force | Out-Null
$started = Get-Date -Format "yyyy-MM-dd HH:mm:ss zzz"
"[$started] Starting Future Map Insights Hub publication." | Set-Content -LiteralPath $logFile -Encoding utf8
$publisherOutput = & $PythonExecutable $publisher 2>&1
$exitCode = $LASTEXITCODE
$publisherOutput | Add-Content -LiteralPath $logFile -Encoding utf8
$finished = Get-Date -Format "yyyy-MM-dd HH:mm:ss zzz"
"[$finished] Finished with exit code $exitCode." | Add-Content -LiteralPath $logFile -Encoding utf8
if ($exitCode -ne 0) {
throw "Future Map Insights Hub publication failed with exit code $exitCode. See $logFile"
}