File size: 7,530 Bytes
c0e3412 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | """Phase V: Presentation and arrangement of the final solution.
Provides structured output formatters for different audiences
(executive, technical, public). Each produces a complete document
with summary, findings, recommendations, evidence, and confidence.
"""
from __future__ import annotations
import re
from typing import Dict, Optional
# ---------------------------------------------------------------------------
# Core presentation function
# ---------------------------------------------------------------------------
def arrange_solution_simple(
text: str,
context: str = "technical",
confidence: Optional[float] = None,
attribution: Optional[str] = None,
counterfactual: Optional[str] = None,
) -> str:
"""Format the solution for a target audience.
Args:
text: Raw solution text (final synthesis + external context).
context: One of {"executive", "technical", "public"}.
confidence: Optional confidence score [0,1] to include.
attribution: Optional attribution explanation text.
counterfactual: Optional counterfactual analysis text.
"""
parts = _split_sections(text)
template = {
"executive": _format_executive,
"technical": _format_technical,
"public": _format_public,
}
formatter = template.get(context, _format_technical)
return formatter(parts, confidence, attribution, counterfactual)
# ---------------------------------------------------------------------------
# Extraction helpers
# ---------------------------------------------------------------------------
def _split_sections(text: str) -> Dict[str, str]:
"""Split raw text into logical sections: summary, findings, evidence."""
lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
text_flat = " ".join(lines) if not lines else "\n".join(lines)
# Try to split on [label] markers from Phase IV synthesis
sections: Dict[str, str] = {"summary": "", "findings": "", "evidence": ""}
if "[Web]" in text_flat or "[DeepSeek]" in text_flat:
# Structured synthesis β split by source labels
source_blocks = re.split(r'\[(\w+)\]', text_flat)
# source_blocks: [empty?] label1, content1, label2, content2, ...
findings_parts = []
evidence_parts = []
for i in range(1, len(source_blocks) - 1, 2):
label = source_blocks[i]
content = source_blocks[i + 1].strip()
if label in ("Web", "Science"):
evidence_parts.append(f"- [{label}] {content}")
else:
findings_parts.append(f"- [{label}] {content}")
sections["findings"] = "\n".join(findings_parts) if findings_parts else ""
sections["evidence"] = "\n".join(evidence_parts) if evidence_parts else ""
sections["summary"] = text_flat[:200] if len(text_flat) > 200 else text_flat
else:
# Flat text β split by length
words = text_flat.split()
if len(words) > 100:
sections["summary"] = " ".join(words[:30])
sections["findings"] = " ".join(words[30:70])
sections["evidence"] = " ".join(words[70:])
else:
sections["summary"] = text_flat
return sections
def extract_key_points(text: str) -> str:
"""Extract key points: first 3 substantive sentences."""
parts = [p.strip() for p in text.replace("\n", " ").split(".") if p.strip() and not p.isdigit()]
points = []
for p in parts:
if len(p.split()) > 3: # skip fragments
points.append(p)
if len(points) >= 3:
break
return "\n".join(f"- {p}" for p in (points or ["No key points extracted"]))
def extract_actions(text: str) -> str:
"""Extract action items from imperative-like phrases."""
action_verbs = {
"implement", "reduce", "evaluate", "deploy", "monitor", "develop",
"create", "establish", "optimize", "integrate", "design", "build",
"test", "validate", "scale", "improve", "expand", "launch",
}
candidates = []
for token in text.split():
if token.lower() in action_verbs:
candidates.append(token)
if not candidates:
return "- Define next steps\n- Assign owners\n- Set timeline\n- Monitor outcomes"
return "\n".join(f"- {c.title()} key measures" for c in candidates[:4])
def extract_conclusion(text: str) -> str:
"""Extract conclusion preferring last substantive paragraph."""
lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
if lines:
return lines[-1]
parts = [p.strip() for p in text.replace("\n", " ").split(".") if p.strip()]
parts = [p for p in parts if not p.isdigit() and len(p.split()) > 3]
return parts[-1] if parts else text
# ---------------------------------------------------------------------------
# Audience-specific formatters
# ---------------------------------------------------------------------------
def _format_executive(
parts: Dict[str, str],
confidence: Optional[float] = None,
attribution: Optional[str] = None,
counterfactual: Optional[str] = None,
) -> str:
"""Executive summary format β brevity and action."""
lines = [
"## Executive Summary",
"",
parts.get("summary", "No summary available."),
"",
"### Key Points",
extract_key_points(parts.get("findings", parts.get("summary", ""))),
"",
"### Recommended Actions",
extract_actions(parts.get("findings", "")),
]
if confidence is not None:
bar = "β" * int(confidence * 20) + "β" * (20 - int(confidence * 20))
lines += ["", f"### Confidence: {confidence:.0%}", f"`{bar}` {confidence:.0%}"]
if attribution:
lines += ["", "### Attribution", attribution[:300]]
return "\n".join(lines)
def _format_technical(
parts: Dict[str, str],
confidence: Optional[float] = None,
attribution: Optional[str] = None,
counterfactual: Optional[str] = None,
) -> str:
"""Technical report format β structured and detailed."""
lines = [
"## Solution Report",
"",
"### Summary",
parts.get("summary", "No summary available."),
"",
"### Analysis & Findings",
parts.get("findings", "No findings extracted."),
"",
"### Supporting Evidence",
parts.get("evidence", "No evidence available."),
"",
"### Conclusion",
extract_conclusion(parts.get("summary", "")),
]
if confidence is not None:
lines += ["", f"### Confidence Score\n{confidence:.1%}"]
if attribution:
lines += ["", "### Attribution\n" + attribution]
if counterfactual:
lines += ["", "### Counterfactual Analysis\n" + counterfactual]
lines += ["", "### Key Points", extract_key_points(parts.get("summary", ""))]
return "\n".join(lines)
def _format_public(
parts: Dict[str, str],
confidence: Optional[float] = None,
attribution: Optional[str] = None,
counterfactual: Optional[str] = None,
) -> str:
"""Public-facing format β accessible and clear."""
lines = [
"## Solution Overview",
"",
parts.get("summary", "We found a solution to the problem."),
"",
"### What We Found",
extract_key_points(parts.get("findings", parts.get("summary", ""))),
"",
"### What To Do Next",
extract_actions(parts.get("findings", "")),
]
return "\n".join(lines)
|