High‐Level Flowchart of main → extract → save/replace

flowchart TD A[main()] --> B[setup_file_logging()] A --> C[extract_save_and_replace_diagrams()] C --> D[Open input HTML and parse with BeautifulSoup] D --> E{Found
tags?} E -- No --> F[Write (unmodified) HTML to output] E -- Yes --> G[For each Mermaid
] G --> H[Extract diagram code & caption] H --> I[Sanitize caption → base filename] I --> J[Write .mmd file] J --> K{executable provided?} K -- No --> L[Skip rendering (leave HTML unchanged)] K -- Yes --> M[run_external_executable_with_ai_retry()] M -- Success --> N[Replace
with ] M -- Failure --> O[Leave
intact] N --> P[Count +1 success] L & O --> P P --> Q[After loop: write modified HTML to output] Q --> R[End]

Detailed sub-flow of run_external_executable_with_ai_retry

flowchart TB Start(["Start run_external_executable_with_ai_retry"]) Start --> ReadMMD["Read original .mmd into current_code"] ReadMMD --> LoopAttempt{"attempt_num ≤ max_ai_attempts?"} LoopAttempt -- No --> FailAll["Revert to original .mmd\nreturn False"] LoopAttempt -- Yes --> WriteMMD["Write current_code to .mmd file"] WriteMMD --> BuildCmd["Build command_parts & cwd"] BuildCmd --> Exec["subprocess.run(...)"] Exec -->|exit 0 + PNG exists| Success["return True"] Exec -->|exit 0 but no PNG| CollectErr["mark failure + collect stderr/stdout"] Exec -->|CalledProcessError| CollectErr CollectErr --> CheckAI{"attempt_num < max_ai?"} CheckAI -- No --> FailAll CheckAI -- Yes --> AIcall["call_openai_to_fix_mermaid_iteratively"] AIcall -->|new code| UpdateCode["current_code ← suggestion"] UpdateCode --> LoopAttempt AIcall -->|no suggestion| FailAll

Sequence diagram of the AI‐correction call

sequenceDiagram participant Script participant OpenAI Script->>Script: prepare prompt (code + error + history) Script->>OpenAI: send prompt via chat or completion API OpenAI-->>Script: raw response (possibly with ```mermaid fences) Script->>Script: strip fences & whitespace alt cleaned code valid Script-->Script: return cleaned Mermaid code else no useful fix or “cannot fix” Script-->Script: return None end