Fix index not being reloaded if a subfolder was added

This commit is contained in:
Kylian Schmidt
2025-07-21 09:57:35 +02:00
parent dbd67f6039
commit 7a9275819a
3 changed files with 125 additions and 33 deletions
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
# Test template rendering
env = Environment(loader=FileSystemLoader("."))
template = env.get_template("templates/gallery.html")
# Mock data
test_items = [{
"name": "test_plot",
"pdf_href": "test_plot.pdf",
"png_href": "test_plot.png",
"metadata": {"key1": "value1", "key2": "value2"}
}]
test_config = {
"paths": {"work_dir": "/work/kschmidt/web"},
"ui": {"search_debounce_ms": 300, "max_recent_plots": 20}
}
rendered = template.render(
title="Test Gallery",
items=test_items,
subdirs=["test_subdir"],
relpath="test/path",
paths=test_config["paths"],
ui=test_config["ui"],
stats={"file_count": 1, "folder_count": 1, "total_size": "100 KB", "total_size_bytes": 100000},
folder_metadata={},
assets_path="../assets"
)
# Extract just the metadata button part
lines = rendered.split('\n')
for i, line in enumerate(lines):
if 'metadata-btn' in line:
print(f"Line {i}: {line.strip()}")
if i > 0:
print(f"Line {i-1}: {lines[i-1].strip()}")
if i < len(lines)-1:
print(f"Line {i+1}: {lines[i+1].strip()}")
break
print("\n--- Assets path in template ---")
for i, line in enumerate(lines):
if 'assets_path' in line:
print(f"Line {i}: {line.strip()}")
+25 -33
View File
@@ -15,8 +15,6 @@ Features:
import subprocess
import shutil
import os
import sys
from pathlib import Path
from typing import Dict, Any, Optional
from jinja2 import Environment, FileSystemLoader
@@ -97,7 +95,8 @@ def build_gallery(source_dir: Path, web_dir: Path,
Processes all PDF files in the source directory, converts them to PNG,
copies both to the web directory, and generates index.html files with
navigation and thumbnails. Now includes metadata support.
navigation and thumbnails. HTML files are always regenerated to ensure
that new subdirectories appear in navigation immediately.
Args:
source_dir: Source directory containing PDF files
@@ -267,46 +266,38 @@ def format_file_size(size_bytes: int) -> str:
return f"{size:.1f} {size_names[i]}"
def refresh_gallery_cgi():
"""
CGI handler to refresh the gallery from a web request.
Outputs a minimal HTTP response and triggers gallery regeneration.
"""
import traceback
print("Content-Type: text/plain\n")
try:
main()
print("Gallery refreshed successfully.")
except Exception as e:
print(f"Error refreshing gallery: {e}")
traceback.print_exc(file=sys.stdout)
def main() -> None:
def main(clean_first: bool = False) -> None:
"""
Main entry point for gallery generation.
Args:
clean_first: If True, removes and recreates the gallery directory
Processes all configured sources and generates the complete gallery
structure in the web directory. Cleans up the gallery directory
on first run to ensure consistency.
structure in the web directory. Ensures assets are available.
"""
gallery_root = Path(CONFIG.web_folder) / CONFIG.plot_root
if gallery_root.exists():
print(f"Gallery directory {gallery_root} exists, cleaning up...")
if clean_first and gallery_root.exists():
print(f"Cleaning gallery directory {gallery_root}...")
shutil.rmtree(gallery_root)
# Ensure gallery root exists
gallery_root.mkdir(parents=True, exist_ok=True)
# Copy assets folder to the gallery root
# Always ensure assets are up to date
assets_src = Path("assets")
assets_dst = gallery_root.parent / "assets"
if assets_src.exists():
if assets_dst.exists():
shutil.rmtree(assets_dst)
shutil.copytree(assets_src, assets_dst)
print(f"Copied assets from {assets_src} to {assets_dst}")
# Update assets if they don't exist or are outdated
main_css_src = assets_src / "css" / "main.css"
main_css_dst = assets_dst / "css" / "main.css"
if not assets_dst.exists() or needs_update(main_css_src, main_css_dst):
if assets_dst.exists():
shutil.rmtree(assets_dst)
shutil.copytree(assets_src, assets_dst)
print(f"Updated assets from {assets_src} to {assets_dst}")
else:
print(f"Warning: Assets directory {assets_src} not found")
@@ -400,8 +391,9 @@ def main() -> None:
if __name__ == "__main__":
# If run as CGI, call the CGI handler
if 'GATEWAY_INTERFACE' in os.environ:
refresh_gallery_cgi()
else:
main()
import argparse
parser = argparse.ArgumentParser(description='Generate gallery')
parser.add_argument('--clean', action='store_true',
help='Clean gallery directory before generation')
args = parser.parse_args()
main(clean_first=args.clean)
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""
Simple CGI script to refresh the gallery.
Just calls the main generate_gallery.py script.
"""
import subprocess
def main():
# Output HTTP headers
print("Content-Type: text/plain")
print("Cache-Control: no-cache")
print() # Empty line to end headers
try:
# Call the gallery generation script
result = subprocess.run([
"python3",
"/work/kschmidt/web/generate_gallery.py"
],
capture_output=True,
text=True,
timeout=300) # 5 minute timeout
if result.returncode == 0:
print("Gallery refresh successful!")
print("\nOutput:")
print(result.stdout)
if result.stderr:
print("\nWarnings:")
print(result.stderr)
else:
print(f"Gallery refresh failed with return code "
f"{result.returncode}")
print("\nError output:")
print(result.stderr)
if result.stdout:
print("\nStandard output:")
print(result.stdout)
except subprocess.TimeoutExpired:
print("Gallery refresh timed out after 5 minutes")
except Exception as e:
print(f"Error running gallery refresh: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()