code_utils.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import re
  2. def extract_mermaid(text: str) -> str:
  3. if not text:
  4. return ""
  5. fenced = re.findall(r"```(?:mermaid)?\s*([\s\S]*?)```", text, flags=re.IGNORECASE)
  6. if fenced:
  7. return fenced[0].strip()
  8. return text.strip()
  9. def extract_optimized_text(text: str) -> str:
  10. if not text:
  11. return ""
  12. marker_start = "【优化后规范描述】"
  13. marker_start_alt = "【优化后描述】"
  14. marker_code = "【Mermaid 流程图代码】"
  15. if marker_start in text and marker_code in text:
  16. return text.split(marker_start, 1)[1].split(marker_code, 1)[0].strip()
  17. if marker_start_alt in text and marker_code in text:
  18. return text.split(marker_start_alt, 1)[1].split(marker_code, 1)[0].strip()
  19. fenced_removed = re.sub(r"```(?:mermaid)?[\s\S]*?```", "", text, flags=re.IGNORECASE).strip()
  20. fenced_removed = fenced_removed.replace(marker_start, "").replace(marker_start_alt, "").strip()
  21. fenced_removed = fenced_removed.replace(marker_code, "").strip()
  22. return fenced_removed
  23. def prune_complexity(code: str, mode: str) -> str:
  24. if mode == "standard":
  25. return code
  26. lines = [ln.rstrip() for ln in code.splitlines() if ln.strip()]
  27. if not lines:
  28. return code
  29. head = lines[0]
  30. body = lines[1:]
  31. max_lines = 12 if mode == "standard" else 11
  32. if len(body) > max_lines:
  33. body = body[:max_lines]
  34. return "\n".join([head] + body)
  35. def apply_direction(code: str, direction: str) -> str:
  36. normalized = "LR" if str(direction).upper() == "LR" else "TD"
  37. if not code:
  38. return code
  39. lines = code.splitlines()
  40. if not lines:
  41. return code
  42. first_idx = None
  43. for idx, line in enumerate(lines):
  44. if line.strip():
  45. first_idx = idx
  46. break
  47. if first_idx is None:
  48. return code
  49. first_line = lines[first_idx].strip()
  50. if re.match(r"^(flowchart|graph)\s+(TD|LR|TB|BT|RL)\b", first_line, flags=re.IGNORECASE):
  51. lines[first_idx] = re.sub(
  52. r"^(flowchart|graph)\s+(TD|LR|TB|BT|RL)\b",
  53. rf"\1 {normalized}",
  54. lines[first_idx],
  55. flags=re.IGNORECASE,
  56. )
  57. return "\n".join(lines)
  58. if re.match(r"^(flowchart|graph)\b", first_line, flags=re.IGNORECASE):
  59. lines[first_idx] = re.sub(
  60. r"^(flowchart|graph)\b",
  61. rf"\1 {normalized}",
  62. lines[first_idx],
  63. flags=re.IGNORECASE,
  64. )
  65. return "\n".join(lines)
  66. return f"flowchart {normalized}\n{code}"