math-piqa-backend / src /display /log_visualizer.py
stellaathena's picture
Initial commit: MATH & PIQA Backend
81afbdf verified
"""Log visualization utilities for the backend UI."""
from pathlib import Path
from typing import Union
from src.envs import NUM_LINES_VISUALIZE
from src.logging import log_file
def log_file_to_html_string(log_path: Union[str, Path] = log_file, reverse: bool = True) -> str:
"""
Convert log file contents to HTML string for display.
Args:
log_path: Path to the log file
reverse: If True, show newest entries first
Returns:
HTML-formatted log contents
"""
log_path = Path(log_path)
if not log_path.exists():
return "<pre>No logs yet.</pre>"
try:
with open(log_path, "r") as f:
lines = f.readlines()
# Limit number of lines
lines = lines[-NUM_LINES_VISUALIZE:]
if reverse:
lines = lines[::-1]
# Escape HTML and wrap in pre tag
content = "".join(lines)
content = content.replace("&", "&amp;")
content = content.replace("<", "&lt;")
content = content.replace(">", "&gt;")
return f"<pre style='font-size: 12px; white-space: pre-wrap;'>{content}</pre>"
except Exception as e:
return f"<pre>Error reading log file: {e}</pre>"