Download components/level0_utils.py from TRuCAL-Labs/TRuCAL: direct link, hf CLI and curl.
- Browser
- Download file 2.71 kB
-
https://huggingface.co/datasets/TRuCAL-Labs/TRuCAL/resolve/main/components/level0_utils.py
- Command line
-
hf download hf://datasets/TRuCAL-Labs/TRuCAL/components/level0_utils.py
-
curl -L -o level0_utils.py https://huggingface.co/datasets/TRuCAL-Labs/TRuCAL/resolve/main/components/level0_utils.py
2.71 kB
| """ | |
| Level-0 Summary Utilities for TRuCAL. | |
| Provides raw evidence summarization for transparent AI reasoning. | |
| """ | |
| from typing import List, Dict, Optional | |
| import json | |
| from pathlib import Path | |
| import logging | |
| import time | |
| logger = logging.getLogger(__name__) | |
| class Level0Summary: | |
| """Handles Level-0 evidence collection and summarization.""" | |
| def __init__(self, log_dir: str = "logs"): | |
| """Initialize with logging directory.""" | |
| self.log_dir = Path(log_dir) | |
| self.log_dir.mkdir(exist_ok=True) | |
| self.audit_log = self.log_dir / "level0_audit.jsonl" | |
| def summarize(self, query: str, sources: List[str], metadata: Optional[Dict] = None) -> str: | |
| """ | |
| Generate a Level-0 summary with raw evidence. | |
| Args: | |
| query: The original user query | |
| sources: List of source texts or evidence | |
| metadata: Optional metadata for auditing | |
| Returns: | |
| Formatted Level-0 summary string | |
| """ | |
| if not query or not sources: | |
| return "" | |
| header = f"# Level-0 Summary\n" | |
| header += f"**Query:** {query}\n\n" | |
| header += "## Raw Evidence\n\n" | |
| evidence_sections = [] | |
| for i, src in enumerate(sources, 1): | |
| if not src or not src.strip(): | |
| continue | |
| evidence_sections.append(f"### Source {i}\n{src.strip()}\n") | |
| if not evidence_sections: | |
| return f"{header}*No valid evidence sources provided.*" | |
| summary = header + "\n".join(evidence_sections) | |
| # Log the summary for auditing | |
| self._log_summary(query, sources, summary, metadata) | |
| return summary | |
| def _log_summary(self, query: str, sources: List[str], summary: str, metadata: Optional[Dict] = None): | |
| """Log the summary to the audit log.""" | |
| try: | |
| log_entry = { | |
| "timestamp": time.time(), | |
| "query": query, | |
| "source_count": len(sources), | |
| "summary": summary, | |
| "metadata": metadata or {} | |
| } | |
| with open(self.audit_log, "a", encoding="utf-8") as f: | |
| f.write(json.dumps(log_entry) + "\n") | |
| except Exception as e: | |
| logger.error(f"Failed to log Level-0 summary: {str(e)}") | |
| # Singleton instance for easy import | |
| level0_summarizer = Level0Summary() | |
| def get_level0_summary(query: str, sources: List[str], metadata: Optional[Dict] = None) -> str: | |
| """Convenience function to get a Level-0 summary.""" | |
| return level0_summarizer.summarize(query, sources, metadata) | |