nursing-copilot-api / backend /fixed_output.py
MarcoLeung052's picture
Update backend/fixed_output.py
82d3540 verified
# backend/fixed_output.py
import os
import warnings
import json
BASE = os.path.dirname(os.path.abspath(__file__))
def parse_fixed_md(content: str):
lines = [line.strip() for line in content.split("\n") if line.strip()]
result = {
"type": None,
"trigger": None,
"steps": [],
"options": [],
"text": None
}
# -------------------------
# TYPE
# -------------------------
if lines[0].startswith("TYPE:"):
result["type"] = lines[0].split(":", 1)[1].strip()
lines = lines[1:]
# -------------------------
# TRIGGER
# -------------------------
if lines and lines[0].startswith("TRIGGER:"):
result["trigger"] = [
t.strip() for t in lines[0].split(":", 1)[1].split(",")
]
lines = lines[1:]
skill_type = result["type"]
# -------------------------
# multi-step-options(多步驟)
# -------------------------
if skill_type == "multi-step-options":
steps = []
current_step = None
i = 0
while i < len(lines):
line = lines[i]
if line == "[STEP]":
if current_step:
steps.append(current_step)
i += 1
label = lines[i] if i < len(lines) else ""
current_step = {"label": label, "options": []}
elif line.startswith("-") and current_step:
option = line.lstrip("-").strip()
current_step["options"].append(option)
i += 1
if current_step:
steps.append(current_step)
result["steps"] = steps
warnings.warn(json.dumps(result, ensure_ascii=False, indent=2))
return result
# -------------------------
# multi-options(單步驟多選)
# -------------------------
if skill_type == "multi-options":
result["options"] = [
line.lstrip("-").strip()
for line in lines if line.startswith("-")
]
return result
# -------------------------
# fixed-sequence(固定句子)
# -------------------------
if skill_type == "fixed-sequence":
steps = []
for line in lines:
if line.startswith("[STEP]"):
label = line.replace("[STEP]", "").strip()
steps.append({
"label": label,
"options": [label]
})
continue
if line.startswith("-"):
text = line.lstrip("-").strip()
steps.append({
"label": text,
"options": [text]
})
continue
result["steps"] = steps
return result
# -------------------------
# fallback
# -------------------------
result["raw"] = content
return result
def run_fixed_output(field_name: str):
path = os.path.join(BASE, "skills", f"{field_name}_fixed", f"{field_name}.md")
if not os.path.exists(path):
return f"[Error] 找不到固定輸出:{path}"
with open(path, "r", encoding="utf-8") as f:
content = f.read().strip()
return parse_fixed_md(content)