Spaces:
Running
Running
Update rag/rag_generator.py
Browse files- rag/rag_generator.py +484 -445
rag/rag_generator.py
CHANGED
|
@@ -1,446 +1,485 @@
|
|
| 1 |
-
# rag/rag_generator.py
|
| 2 |
-
# ============================================================
|
| 3 |
-
# RAG generator using
|
| 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 |
-
s = (
|
| 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 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
continue
|
| 214 |
-
|
| 215 |
-
if
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
def
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
""
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
# ------------------------------------------------------------
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
)
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 446 |
return final
|
|
|
|
| 1 |
+
# rag/rag_generator.py
|
| 2 |
+
# ============================================================
|
| 3 |
+
# RAG generator using facebook/bart-large (CPU-friendly)
|
| 4 |
+
#
|
| 5 |
+
# Evolution (confidence-aware, deterministic-first):
|
| 6 |
+
#
|
| 7 |
+
# - Confidence and escalation decisions are now made upstream in the
|
| 8 |
+
# retriever context shaper (CONFIDENCE ASSESSMENT block).
|
| 9 |
+
#
|
| 10 |
+
# - The generator now:
|
| 11 |
+
# 1) Extracts:
|
| 12 |
+
# KEY TRAITS
|
| 13 |
+
# CONFLICTS
|
| 14 |
+
# CONFIDENCE STATE
|
| 15 |
+
# RECOMMENDED ACTION
|
| 16 |
+
# 2) Selects a deterministic conclusion template
|
| 17 |
+
# 3) Optionally allows the LLM to paraphrase the conclusion
|
| 18 |
+
# while preserving the confidence state meaning
|
| 19 |
+
#
|
| 20 |
+
# - The LLM is *not allowed* to decide strength — it only
|
| 21 |
+
# rewrites the conclusion within the declared state.
|
| 22 |
+
#
|
| 23 |
+
# - If the LLM returns junk → deterministic template is used.
|
| 24 |
+
#
|
| 25 |
+
# ============================================================
|
| 26 |
+
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import os
|
| 30 |
+
import re
|
| 31 |
+
import torch
|
| 32 |
+
from transformers import BartForConditionalGeneration, BartTokenizer
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# ------------------------------------------------------------
|
| 36 |
+
# MODEL CONFIG
|
| 37 |
+
# ------------------------------------------------------------
|
| 38 |
+
|
| 39 |
+
MODEL_NAME = "facebook/bart-large"
|
| 40 |
+
|
| 41 |
+
_tokenizer: BartTokenizer | None = None
|
| 42 |
+
_model: BartForConditionalGeneration | None = None
|
| 43 |
+
|
| 44 |
+
_MAX_INPUT_TOKENS = 1020
|
| 45 |
+
_DEFAULT_MAX_NEW_TOKENS = 256
|
| 46 |
+
|
| 47 |
+
_CONTEXT_CHAR_CAP = 2400
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _get_model() -> tuple[BartTokenizer, BartForConditionalGeneration]:
|
| 51 |
+
global _tokenizer, _model
|
| 52 |
+
if _tokenizer is None or _model is None:
|
| 53 |
+
_tokenizer = BartTokenizer.from_pretrained(MODEL_NAME)
|
| 54 |
+
_model = BartForConditionalGeneration.from_pretrained(
|
| 55 |
+
MODEL_NAME,
|
| 56 |
+
device_map="auto",
|
| 57 |
+
torch_dtype=torch.float32,
|
| 58 |
+
)
|
| 59 |
+
return _tokenizer, _model
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# ------------------------------------------------------------
|
| 63 |
+
# DEBUG LOGGING (HF Space logs)
|
| 64 |
+
# ------------------------------------------------------------
|
| 65 |
+
|
| 66 |
+
RAG_GEN_LOG_INPUT = os.getenv("BACTAI_RAG_GEN_LOG_INPUT", "0").strip() == "1"
|
| 67 |
+
RAG_GEN_LOG_OUTPUT = os.getenv("BACTAI_RAG_GEN_LOG_OUTPUT", "0").strip() == "1"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _log_block(title: str, body: str) -> None:
|
| 71 |
+
print("=" * 80)
|
| 72 |
+
print(f"RAG GENERATOR DEBUG — {title}")
|
| 73 |
+
print("=" * 80)
|
| 74 |
+
print(body.strip() if body else "")
|
| 75 |
+
print()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# ------------------------------------------------------------
|
| 79 |
+
# PROMPT (LLM MAY PARAPHRASE — BUT NOT CHANGE CONFIDENCE)
|
| 80 |
+
# ------------------------------------------------------------
|
| 81 |
+
|
| 82 |
+
RAG_PROMPT = """Rewrite the conclusion for the target genus.
|
| 83 |
+
Do not change the confidence level. Do not introduce new reasoning.
|
| 84 |
+
Write 2–4 short sentences in clear, natural language.
|
| 85 |
+
|
| 86 |
+
Target genus: {genus}
|
| 87 |
+
Confidence state: {confidence_state}
|
| 88 |
+
Recommended action: {recommended_action}
|
| 89 |
+
|
| 90 |
+
Key traits that match:
|
| 91 |
+
{matches}
|
| 92 |
+
|
| 93 |
+
Conflicts:
|
| 94 |
+
{conflicts}
|
| 95 |
+
|
| 96 |
+
Rewrite the conclusion using the same meaning as the confidence state
|
| 97 |
+
and recommended action. Mention both matches and conflicts when present.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# ------------------------------------------------------------
|
| 102 |
+
# OUTPUT CLEANUP / GARBAGE DETECTION
|
| 103 |
+
# ------------------------------------------------------------
|
| 104 |
+
|
| 105 |
+
_BAD_SUBSTRINGS = (
|
| 106 |
+
"summarize:",
|
| 107 |
+
"target genus",
|
| 108 |
+
"confidence state",
|
| 109 |
+
"write a concise conclusion",
|
| 110 |
+
"conflicts:",
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
def _clean_generation(text: str) -> str:
|
| 114 |
+
s = (text or "").strip()
|
| 115 |
+
if not s:
|
| 116 |
+
return ""
|
| 117 |
+
|
| 118 |
+
s = re.sub(r"\s*\n+\s*", " ", s).strip()
|
| 119 |
+
s = re.sub(r"\s{2,}", " ", s).strip()
|
| 120 |
+
|
| 121 |
+
if len(s) > 900:
|
| 122 |
+
s = s[:900].rstrip() + "..."
|
| 123 |
+
|
| 124 |
+
return s
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _looks_like_echo_or_garbage(text: str) -> bool:
|
| 128 |
+
s = (text or "").strip()
|
| 129 |
+
if not s:
|
| 130 |
+
return True
|
| 131 |
+
if len(s) < 25:
|
| 132 |
+
return True
|
| 133 |
+
|
| 134 |
+
low = s.lower()
|
| 135 |
+
if any(bad in low for bad in _BAD_SUBSTRINGS):
|
| 136 |
+
return True
|
| 137 |
+
|
| 138 |
+
if "." not in s and "match" not in low and "conflict" not in low:
|
| 139 |
+
return True
|
| 140 |
+
|
| 141 |
+
return False
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# ------------------------------------------------------------
|
| 145 |
+
# EXTRACT KEY TRAITS + CONFLICTS
|
| 146 |
+
# ------------------------------------------------------------
|
| 147 |
+
|
| 148 |
+
_KEY_MATCHES_HEADER_RE = re.compile(r"^\s*KEY MATCHES\s*:\s*$", re.IGNORECASE)
|
| 149 |
+
_CONFLICTS_HEADER_RE = re.compile(r"^\s*CONFLICTS\b.*:\s*$", re.IGNORECASE)
|
| 150 |
+
_CONFLICTS_INLINE_NONE_RE = re.compile(
|
| 151 |
+
r"^\s*CONFLICTS\s*:\s*not specified\.?\s*$",
|
| 152 |
+
re.IGNORECASE,
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
_MATCH_LINE_RE = re.compile(
|
| 156 |
+
r"^\s*-\s*([^:]+)\s*:\s*(.+?)\s*\(matches reference:\s*(.+?)\)\s*$",
|
| 157 |
+
re.IGNORECASE,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
_CONFLICT_LINE_RE = re.compile(
|
| 161 |
+
r"^\s*-\s*([^:]+)\s*:\s*(.+?)\s*\(conflicts reference:\s*(.+?)\)\s*$",
|
| 162 |
+
re.IGNORECASE,
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
_GENERIC_BULLET_RE = re.compile(r"^\s*-\s*(.+?)\s*$")
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _extract_key_traits_and_conflicts(
|
| 169 |
+
shaped_ctx: str,
|
| 170 |
+
) -> tuple[list[str], list[str], bool]:
|
| 171 |
+
|
| 172 |
+
key_traits: list[str] = []
|
| 173 |
+
conflicts: list[str] = []
|
| 174 |
+
|
| 175 |
+
lines = (shaped_ctx or "").splitlines()
|
| 176 |
+
if not lines:
|
| 177 |
+
return key_traits, conflicts, False
|
| 178 |
+
|
| 179 |
+
in_matches = False
|
| 180 |
+
in_conflicts = False
|
| 181 |
+
saw_headers = False
|
| 182 |
+
|
| 183 |
+
for raw in lines:
|
| 184 |
+
line = raw.rstrip("\n")
|
| 185 |
+
|
| 186 |
+
if _KEY_MATCHES_HEADER_RE.match(line.strip()):
|
| 187 |
+
in_matches, in_conflicts = True, False
|
| 188 |
+
saw_headers = True
|
| 189 |
+
continue
|
| 190 |
+
|
| 191 |
+
if _CONFLICTS_INLINE_NONE_RE.match(line.strip()):
|
| 192 |
+
in_matches = in_conflicts = False
|
| 193 |
+
saw_headers = True
|
| 194 |
+
continue
|
| 195 |
+
|
| 196 |
+
if _CONFLICTS_HEADER_RE.match(line.strip()):
|
| 197 |
+
in_matches, in_conflicts = False, True
|
| 198 |
+
saw_headers = True
|
| 199 |
+
continue
|
| 200 |
+
|
| 201 |
+
if saw_headers and (line.strip().endswith(":") and not line.strip().startswith("-")):
|
| 202 |
+
if not _KEY_MATCHES_HEADER_RE.match(line.strip()) and not _CONFLICTS_HEADER_RE.match(line.strip()):
|
| 203 |
+
in_matches = in_conflicts = False
|
| 204 |
+
|
| 205 |
+
if in_matches and line.strip().startswith("-"):
|
| 206 |
+
m = _MATCH_LINE_RE.match(line.strip())
|
| 207 |
+
if m:
|
| 208 |
+
key_traits.append(f"{m.group(1).strip()}: {m.group(2).strip()}")
|
| 209 |
+
else:
|
| 210 |
+
g = _GENERIC_BULLET_RE.match(line.strip())
|
| 211 |
+
if g:
|
| 212 |
+
key_traits.append(g.group(1).strip())
|
| 213 |
+
continue
|
| 214 |
+
|
| 215 |
+
if in_conflicts and line.strip().startswith("-"):
|
| 216 |
+
c = _CONFLICT_LINE_RE.match(line.strip())
|
| 217 |
+
if c:
|
| 218 |
+
conflicts.append(f"{c.group(1).strip()}: {c.group(2).strip()}")
|
| 219 |
+
else:
|
| 220 |
+
g = _GENERIC_BULLET_RE.match(line.strip())
|
| 221 |
+
if g:
|
| 222 |
+
conflicts.append(g.group(1).strip())
|
| 223 |
+
continue
|
| 224 |
+
|
| 225 |
+
return key_traits, conflicts, saw_headers
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def _extract_matches_conflicts_legacy(shaped_ctx: str) -> tuple[list[str], list[str]]:
|
| 229 |
+
matches: list[str] = []
|
| 230 |
+
conflicts: list[str] = []
|
| 231 |
+
|
| 232 |
+
for raw in (shaped_ctx or "").splitlines():
|
| 233 |
+
line = raw.strip()
|
| 234 |
+
if not line.startswith("-"):
|
| 235 |
+
continue
|
| 236 |
+
|
| 237 |
+
m = _MATCH_LINE_RE.match(line)
|
| 238 |
+
if m:
|
| 239 |
+
matches.append(f"{m.group(1).strip()}: {m.group(2).strip()}")
|
| 240 |
+
continue
|
| 241 |
+
|
| 242 |
+
c = _CONFLICT_LINE_RE.match(line)
|
| 243 |
+
if c:
|
| 244 |
+
conflicts.append(f"{c.group(1).strip()}: {c.group(2).strip()}")
|
| 245 |
+
continue
|
| 246 |
+
|
| 247 |
+
return matches, conflicts
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _format_bullets(items: list[str], *, none_text: str) -> str:
|
| 251 |
+
if not items:
|
| 252 |
+
return none_text
|
| 253 |
+
return "\n".join(f"- {x}" for x in items)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
# ------------------------------------------------------------
|
| 257 |
+
# CONFIDENCE STATE EXTRACTOR
|
| 258 |
+
# ------------------------------------------------------------
|
| 259 |
+
|
| 260 |
+
_CONF_STATE_RE = re.compile(r"^\s*-\s*Confidence State:\s*(.+?)\s*$", re.IGNORECASE)
|
| 261 |
+
_RECOMMENDED_ACTION_RE = re.compile(r"^\s*-\s*Recommended Action:\s*(.+?)\s*$", re.IGNORECASE)
|
| 262 |
+
|
| 263 |
+
def _extract_confidence_state(shaped_ctx: str) -> tuple[str | None, str | None]:
|
| 264 |
+
confidence_state = None
|
| 265 |
+
recommended_action = None
|
| 266 |
+
|
| 267 |
+
for raw in (shaped_ctx or "").splitlines():
|
| 268 |
+
line = raw.strip()
|
| 269 |
+
|
| 270 |
+
m = _CONF_STATE_RE.match(line)
|
| 271 |
+
if m:
|
| 272 |
+
confidence_state = m.group(1).strip()
|
| 273 |
+
continue
|
| 274 |
+
|
| 275 |
+
r = _RECOMMENDED_ACTION_RE.match(line)
|
| 276 |
+
if r:
|
| 277 |
+
recommended_action = r.group(1).strip()
|
| 278 |
+
continue
|
| 279 |
+
|
| 280 |
+
return confidence_state, recommended_action
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
# ------------------------------------------------------------
|
| 284 |
+
# DETERMINISTIC TEMPLATES
|
| 285 |
+
# ------------------------------------------------------------
|
| 286 |
+
|
| 287 |
+
def _template_conclusion(
|
| 288 |
+
genus: str,
|
| 289 |
+
confidence_state: str | None,
|
| 290 |
+
key_traits: list[str],
|
| 291 |
+
conflicts: list[str],
|
| 292 |
+
recommended_action: str | None,
|
| 293 |
+
) -> str:
|
| 294 |
+
|
| 295 |
+
g = (genus or "").strip() or "Unknown"
|
| 296 |
+
rec = recommended_action or ""
|
| 297 |
+
|
| 298 |
+
m_short = ", ".join(key_traits[:3]) if key_traits else "no clearly supportive traits"
|
| 299 |
+
c_short = ", ".join(conflicts[:3]) if conflicts else None
|
| 300 |
+
|
| 301 |
+
if confidence_state is None:
|
| 302 |
+
return _deterministic_conclusion(g, key_traits, conflicts)
|
| 303 |
+
|
| 304 |
+
cs = confidence_state.lower()
|
| 305 |
+
|
| 306 |
+
if "strong" in cs:
|
| 307 |
+
return (
|
| 308 |
+
f"This phenotype is indicative of {g} with no conflicting traits observed. "
|
| 309 |
+
f"It aligns well with key genus characteristics such as {m_short}. "
|
| 310 |
+
f"{rec}".strip()
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
if "probable" in cs or "conflicts present" in cs or "cautious" in cs:
|
| 314 |
+
if c_short:
|
| 315 |
+
return (
|
| 316 |
+
f"The phenotype is consistent with {g} based on supporting traits including {m_short}; "
|
| 317 |
+
f"however, conflicting results are present ({c_short}), which reduces confidence. "
|
| 318 |
+
f"{rec}".strip()
|
| 319 |
+
)
|
| 320 |
+
else:
|
| 321 |
+
return (
|
| 322 |
+
f"The phenotype is broadly consistent with {g}, but limited conflicting information "
|
| 323 |
+
f"reduces certainty. {rec}".strip()
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
if "inconclusive" in cs or "conflicting" in cs:
|
| 327 |
+
return (
|
| 328 |
+
f"The top genus match is {g}; however, the phenotype is inconclusive due to conflicting "
|
| 329 |
+
f"test results ({c_short or 'multiple conflicting traits'}). {rec}".strip()
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
if "weak" in cs:
|
| 333 |
+
return (
|
| 334 |
+
f"The available phenotype provides weak evidence for {g}. "
|
| 335 |
+
f"Additional testing or phenotype data is recommended. {rec}".strip()
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
return _deterministic_conclusion(g, key_traits, conflicts)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
# ------------------------------------------------------------
|
| 342 |
+
# BACKSTOP DETERMINISTIC CONCLUSION
|
| 343 |
+
# ------------------------------------------------------------
|
| 344 |
+
|
| 345 |
+
def _deterministic_conclusion(genus: str, key_traits: list[str], conflicts: list[str]) -> str:
|
| 346 |
+
g = (genus or "").strip() or "Unknown"
|
| 347 |
+
m = key_traits[:4]
|
| 348 |
+
c = conflicts[:2]
|
| 349 |
+
|
| 350 |
+
if m and c:
|
| 351 |
+
return (
|
| 352 |
+
f"This is a probable match to {g} because it aligns with key traits such as "
|
| 353 |
+
f"{', '.join(m)}. However, there are conflicts ({', '.join(c)}), so treat this "
|
| 354 |
+
f"as a moderate/tentative genus-level fit and consider re-checking the conflicting tests."
|
| 355 |
+
)
|
| 356 |
+
if m and not c:
|
| 357 |
+
return (
|
| 358 |
+
f"This phenotype is consistent with {g} based on key matching traits such as "
|
| 359 |
+
f"{', '.join(m)}. No major conflicts were detected against the core genus traits, "
|
| 360 |
+
f"supporting a strong genus-level match."
|
| 361 |
+
)
|
| 362 |
+
if (not m) and c:
|
| 363 |
+
return (
|
| 364 |
+
f"This phenotype does not cleanly fit {g} because it conflicts with core traits "
|
| 365 |
+
f"({', '.join(c)}). Consider re-checking those tests or comparing against the next-ranked genera."
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
return (
|
| 369 |
+
f"Reference evidence was available for {g}, but no clear matches or conflicts could be extracted "
|
| 370 |
+
f"from the shaped context."
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def _trim_context(ctx: str) -> str:
|
| 375 |
+
s = (ctx or "").strip()
|
| 376 |
+
if not s:
|
| 377 |
+
return ""
|
| 378 |
+
if len(s) <= _CONTEXT_CHAR_CAP:
|
| 379 |
+
return s
|
| 380 |
+
return s[:_CONTEXT_CHAR_CAP].rstrip() + "\n... (truncated)"
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
# ------------------------------------------------------------
|
| 384 |
+
# PUBLIC API
|
| 385 |
+
# ------------------------------------------------------------
|
| 386 |
+
|
| 387 |
+
def generate_genus_rag_explanation(
|
| 388 |
+
phenotype_text: str,
|
| 389 |
+
rag_context: str,
|
| 390 |
+
genus: str,
|
| 391 |
+
max_new_tokens: int = _DEFAULT_MAX_NEW_TOKENS,
|
| 392 |
+
) -> str:
|
| 393 |
+
|
| 394 |
+
tokenizer, model = _get_model()
|
| 395 |
+
|
| 396 |
+
genus_clean = (genus or "").strip() or "Unknown"
|
| 397 |
+
context = _trim_context(rag_context or "")
|
| 398 |
+
|
| 399 |
+
if not context:
|
| 400 |
+
return (
|
| 401 |
+
"KEY TRAITS:\n"
|
| 402 |
+
"- Not specified.\n\n"
|
| 403 |
+
"CONFLICTS:\n"
|
| 404 |
+
"- Not specified.\n\n"
|
| 405 |
+
"CONCLUSION:\n"
|
| 406 |
+
"No reference evidence was available to evaluate this genus against the observed phenotype."
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
key_traits, conflicts, saw_headers = _extract_key_traits_and_conflicts(context)
|
| 410 |
+
|
| 411 |
+
if (not saw_headers) or (not key_traits and not conflicts):
|
| 412 |
+
legacy_matches, legacy_conflicts = _extract_matches_conflicts_legacy(context)
|
| 413 |
+
if legacy_matches or legacy_conflicts:
|
| 414 |
+
key_traits = key_traits or legacy_matches
|
| 415 |
+
conflicts = conflicts or legacy_conflicts
|
| 416 |
+
|
| 417 |
+
key_traits_text = _format_bullets(key_traits, none_text="- Not specified.")
|
| 418 |
+
conflicts_text = _format_bullets(conflicts, none_text="- Not specified.")
|
| 419 |
+
|
| 420 |
+
confidence_state, recommended_action = _extract_confidence_state(context)
|
| 421 |
+
|
| 422 |
+
template_conclusion = _template_conclusion(
|
| 423 |
+
genus_clean,
|
| 424 |
+
confidence_state,
|
| 425 |
+
key_traits,
|
| 426 |
+
conflicts,
|
| 427 |
+
recommended_action,
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
if confidence_state is None:
|
| 431 |
+
final_conclusion = template_conclusion
|
| 432 |
+
|
| 433 |
+
else:
|
| 434 |
+
prompt = RAG_PROMPT.format(
|
| 435 |
+
genus=genus_clean,
|
| 436 |
+
confidence_state=confidence_state,
|
| 437 |
+
recommended_action=recommended_action or "None",
|
| 438 |
+
matches=key_traits_text,
|
| 439 |
+
conflicts=conflicts_text,
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
if RAG_GEN_LOG_INPUT:
|
| 443 |
+
_log_block("PROMPT (CONFIDENCE-AWARE)", prompt)
|
| 444 |
+
|
| 445 |
+
inputs = tokenizer(
|
| 446 |
+
prompt,
|
| 447 |
+
return_tensors="pt",
|
| 448 |
+
truncation=True,
|
| 449 |
+
max_length=_MAX_INPUT_TOKENS,
|
| 450 |
+
).to(model.device)
|
| 451 |
+
|
| 452 |
+
output = model.generate(
|
| 453 |
+
**inputs,
|
| 454 |
+
max_new_tokens=max_new_tokens,
|
| 455 |
+
temperature=0.0,
|
| 456 |
+
num_beams=3, # BART benefits from small beam search
|
| 457 |
+
do_sample=False,
|
| 458 |
+
repetition_penalty=1.2,
|
| 459 |
+
no_repeat_ngram_size=3,
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
decoded = tokenizer.decode(output[0], skip_special_tokens=True).strip()
|
| 463 |
+
cleaned = _clean_generation(decoded)
|
| 464 |
+
|
| 465 |
+
if RAG_GEN_LOG_OUTPUT:
|
| 466 |
+
_log_block("RAW OUTPUT (CONCLUSION)", decoded)
|
| 467 |
+
_log_block("CLEANED OUTPUT", cleaned)
|
| 468 |
+
|
| 469 |
+
if _looks_like_echo_or_garbage(cleaned):
|
| 470 |
+
final_conclusion = template_conclusion
|
| 471 |
+
if RAG_GEN_LOG_OUTPUT:
|
| 472 |
+
_log_block("FALLBACK (TEMPLATE)", final_conclusion)
|
| 473 |
+
else:
|
| 474 |
+
final_conclusion = cleaned
|
| 475 |
+
|
| 476 |
+
final = (
|
| 477 |
+
"KEY TRAITS:\n"
|
| 478 |
+
f"{key_traits_text}\n\n"
|
| 479 |
+
"CONFLICTS:\n"
|
| 480 |
+
f"{conflicts_text}\n\n"
|
| 481 |
+
"CONCLUSION:\n"
|
| 482 |
+
f"{final_conclusion}"
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
return final
|