Spaces:
Sleeping
Sleeping
Rajan Sharma
commited on
Update scenario_planner.py
Browse files- scenario_planner.py +84 -13
scenario_planner.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
from typing import Dict, Any
|
| 2 |
from pydantic import ValidationError
|
| 3 |
import json
|
| 4 |
from schema import ScenarioPlan, TaskPlan
|
|
@@ -21,9 +21,7 @@ If you cannot infer a field/column name, leave it as-is; the executor will attem
|
|
| 21 |
Output STRICT JSON only with keys: tasks, notes. DO NOT include explanations outside JSON."""
|
| 22 |
|
| 23 |
def build_parser_prompt(scenario_text: str, dataset_catalog: Dict[str, list]) -> str:
|
| 24 |
-
cat_lines = []
|
| 25 |
-
for k, cols in dataset_catalog.items():
|
| 26 |
-
cat_lines.append(f"- {k}: {', '.join(cols)}")
|
| 27 |
catalog_str = "\n".join(cat_lines) if cat_lines else "- (no files uploaded yet)"
|
| 28 |
return f"""{_PARSER_PROMPT}
|
| 29 |
|
|
@@ -34,17 +32,90 @@ def build_parser_prompt(scenario_text: str, dataset_catalog: Dict[str, list]) ->
|
|
| 34 |
{scenario_text}
|
| 35 |
"""
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
def parse_to_plan(scenario_text: str, dataset_catalog: Dict[str, list]) -> ScenarioPlan:
|
| 38 |
prompt = build_parser_prompt(scenario_text, dataset_catalog)
|
| 39 |
-
raw =
|
| 40 |
if not raw:
|
| 41 |
-
return
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
raw = raw[start:end+1]
|
| 46 |
try:
|
| 47 |
-
obj = json.loads(
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
| 49 |
except (json.JSONDecodeError, ValidationError):
|
| 50 |
-
return
|
|
|
|
| 1 |
+
from typing import Dict, Any, List
|
| 2 |
from pydantic import ValidationError
|
| 3 |
import json
|
| 4 |
from schema import ScenarioPlan, TaskPlan
|
|
|
|
| 21 |
Output STRICT JSON only with keys: tasks, notes. DO NOT include explanations outside JSON."""
|
| 22 |
|
| 23 |
def build_parser_prompt(scenario_text: str, dataset_catalog: Dict[str, list]) -> str:
|
| 24 |
+
cat_lines = [f"- {k}: {', '.join(cols)}" for k, cols in dataset_catalog.items()]
|
|
|
|
|
|
|
| 25 |
catalog_str = "\n".join(cat_lines) if cat_lines else "- (no files uploaded yet)"
|
| 26 |
return f"""{_PARSER_PROMPT}
|
| 27 |
|
|
|
|
| 32 |
{scenario_text}
|
| 33 |
"""
|
| 34 |
|
| 35 |
+
def _llm_parse(prompt: str) -> str | None:
|
| 36 |
+
return cohere_chat(prompt) or open_fallback_chat(prompt)
|
| 37 |
+
|
| 38 |
+
def _safe_json_slice(raw: str) -> str | None:
|
| 39 |
+
raw = (raw or "").strip()
|
| 40 |
+
i, j = raw.find("{"), raw.rfind("}")
|
| 41 |
+
if i == -1 or j == -1: return None
|
| 42 |
+
return raw[i:j+1]
|
| 43 |
+
|
| 44 |
+
def _make_safety_net_plan(scenario_text: str, dataset_catalog: Dict[str, list]) -> ScenarioPlan:
|
| 45 |
+
csvs = list(dataset_catalog.keys())
|
| 46 |
+
wt = next((k for k in csvs if "wait" in k.lower()), (csvs[0] if csvs else None))
|
| 47 |
+
fac = next((k for k in csvs if "facility" in k.lower() or "hospital" in k.lower()), wt)
|
| 48 |
+
|
| 49 |
+
tasks: List[TaskPlan] = []
|
| 50 |
+
text = scenario_text.lower()
|
| 51 |
+
wants_map = "map" in text or "geographic distribution" in text or "geographic" in text
|
| 52 |
+
wants_reco = "recommend" in text or "allocation" in text or "plan" in text
|
| 53 |
+
|
| 54 |
+
tasks.append(TaskPlan(
|
| 55 |
+
title="Top facilities by average surgery wait",
|
| 56 |
+
data_key=wt, format="table",
|
| 57 |
+
group_by=["Facility","Zone"],
|
| 58 |
+
agg=["avg(Surgery_Median)","avg(Surgery_90th)","count(*)"],
|
| 59 |
+
sort_by="avg_Surgery_Median", sort_dir="desc", top=5,
|
| 60 |
+
fields=["Facility","Zone","avg_Surgery_Median","avg_Surgery_90th","count"],
|
| 61 |
+
number_format={"avg_Surgery_Median":"0", "avg_Surgery_90th":"0"}
|
| 62 |
+
))
|
| 63 |
+
|
| 64 |
+
tasks.append(TaskPlan(
|
| 65 |
+
title="Top specialties by average surgery wait",
|
| 66 |
+
data_key=wt, format="table",
|
| 67 |
+
group_by=["Specialty"],
|
| 68 |
+
agg=["avg(Surgery_Median)","avg(Consult_Median)","count(*)"],
|
| 69 |
+
sort_by="avg_Surgery_Median", sort_dir="desc", top=5,
|
| 70 |
+
fields=["Specialty","avg_Surgery_Median","avg_Consult_Median","count"],
|
| 71 |
+
number_format={"avg_Surgery_Median":"0", "avg_Consult_Median":"0"}
|
| 72 |
+
))
|
| 73 |
+
|
| 74 |
+
tasks.append(TaskPlan(
|
| 75 |
+
title="Zone-level surgery wait comparison",
|
| 76 |
+
data_key=wt, format="table",
|
| 77 |
+
group_by=["Zone"], agg=["avg(Surgery_Median)","count(*)"],
|
| 78 |
+
sort_by="avg_Surgery_Median", sort_dir="desc",
|
| 79 |
+
fields=["Zone","avg_Surgery_Median","count"],
|
| 80 |
+
number_format={"avg_Surgery_Median":"0"}
|
| 81 |
+
))
|
| 82 |
+
|
| 83 |
+
if wants_map and fac:
|
| 84 |
+
tasks.append(TaskPlan(
|
| 85 |
+
title="Geographic distribution of high-wait facilities",
|
| 86 |
+
data_key=wt, format="map",
|
| 87 |
+
group_by=["Facility","Zone"], agg=["avg(Surgery_Median)"],
|
| 88 |
+
sort_by="avg_Surgery_Median", sort_dir="desc", top=5,
|
| 89 |
+
joins=[{"right_key": fac, "left_on": "Facility", "right_on": "facility_name", "how": "left"}],
|
| 90 |
+
fields=["Facility","Zone","city","latitude","longitude","avg_Surgery_Median"],
|
| 91 |
+
number_format={"avg_Surgery_Median":"0"}
|
| 92 |
+
))
|
| 93 |
+
|
| 94 |
+
if wants_reco:
|
| 95 |
+
tasks.append(TaskPlan(
|
| 96 |
+
title="Recommendations (inputs for narrative)",
|
| 97 |
+
data_key=wt, format="narrative",
|
| 98 |
+
group_by=["Facility","Zone"], agg=["avg(Surgery_Median)","count(*)"],
|
| 99 |
+
sort_by="avg_Surgery_Median", sort_dir="desc", top=10,
|
| 100 |
+
fields=["Facility","Zone","avg_Surgery_Median","count"],
|
| 101 |
+
number_format={"avg_Surgery_Median":"0"}
|
| 102 |
+
))
|
| 103 |
+
|
| 104 |
+
return ScenarioPlan(tasks=tasks, notes="Safety-net plan (LLM planner failed).")
|
| 105 |
+
|
| 106 |
def parse_to_plan(scenario_text: str, dataset_catalog: Dict[str, list]) -> ScenarioPlan:
|
| 107 |
prompt = build_parser_prompt(scenario_text, dataset_catalog)
|
| 108 |
+
raw = _llm_parse(prompt)
|
| 109 |
if not raw:
|
| 110 |
+
return _make_safety_net_plan(scenario_text, dataset_catalog)
|
| 111 |
+
js = _safe_json_slice(raw)
|
| 112 |
+
if not js:
|
| 113 |
+
return _make_safety_net_plan(scenario_text, dataset_catalog)
|
|
|
|
| 114 |
try:
|
| 115 |
+
obj = json.loads(js)
|
| 116 |
+
plan = ScenarioPlan(**obj)
|
| 117 |
+
if not plan.tasks or (len(plan.tasks) == 1 and plan.tasks[0].format == "narrative"):
|
| 118 |
+
return _make_safety_net_plan(scenario_text, dataset_catalog)
|
| 119 |
+
return plan
|
| 120 |
except (json.JSONDecodeError, ValidationError):
|
| 121 |
+
return _make_safety_net_plan(scenario_text, dataset_catalog)
|