|
| 1 | +"""Log adapters — convert external framework results to hb-firewall format. |
| 2 | +
|
| 3 | +Auto-detects format from file structure. Add new adapters by creating a module |
| 4 | +with SIGNATURES (list of keys to match) and convert(data) → list[dict]. |
| 5 | +""" |
| 6 | + |
| 7 | +import json |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | +from . import promptfoo, pyrit |
| 11 | + |
| 12 | +_ADAPTERS = { |
| 13 | + "promptfoo": promptfoo, |
| 14 | + "pyrit": pyrit, |
| 15 | +} |
| 16 | + |
| 17 | + |
| 18 | +def detect_format(data: dict) -> str: |
| 19 | + """Auto-detect framework from file structure.""" |
| 20 | + for name, adapter in _ADAPTERS.items(): |
| 21 | + sigs = getattr(adapter, "SIGNATURES", []) |
| 22 | + if sigs and all(k in data for k in sigs): |
| 23 | + return name |
| 24 | + return "" |
| 25 | + |
| 26 | + |
| 27 | +def convert_file(file_path: str, format_tag: str = "") -> list[dict]: |
| 28 | + """Convert an external log file to hb-firewall standard format. |
| 29 | +
|
| 30 | + Args: |
| 31 | + file_path: path to JSON file |
| 32 | + format_tag: explicit format (e.g. "promptfoo", "pyrit"). Auto-detects if empty. |
| 33 | +
|
| 34 | + Returns: |
| 35 | + list of logs in standard format: |
| 36 | + [{"conversation": [...], "result": "pass"|"fail", "test_category": "...", |
| 37 | + "fail_category": "...", "severity": float, "confidence": float}, ...] |
| 38 | + """ |
| 39 | + path = Path(file_path) |
| 40 | + |
| 41 | + if path.suffix == ".jsonl": |
| 42 | + with open(path) as f: |
| 43 | + lines = [json.loads(line) for line in f if line.strip()] |
| 44 | + # JSONL: treat as list of individual results |
| 45 | + data = {"_jsonl_entries": lines} |
| 46 | + else: |
| 47 | + with open(path) as f: |
| 48 | + data = json.load(f) |
| 49 | + |
| 50 | + tag = format_tag or detect_format(data) |
| 51 | + if not tag: |
| 52 | + available = ", ".join(_ADAPTERS.keys()) |
| 53 | + raise ValueError( |
| 54 | + f"Unrecognized format in '{file_path}'. " |
| 55 | + f"Specify format: --import {file_path}:<format> " |
| 56 | + f"(available: {available})") |
| 57 | + |
| 58 | + if tag not in _ADAPTERS: |
| 59 | + available = ", ".join(_ADAPTERS.keys()) |
| 60 | + raise ValueError(f"Unknown format '{tag}'. Available: {available}") |
| 61 | + |
| 62 | + return _ADAPTERS[tag].convert(data) |
| 63 | + |
| 64 | + |
| 65 | +def list_formats() -> list[str]: |
| 66 | + return list(_ADAPTERS.keys()) |
0 commit comments