"""
3. Graph. Capture the resulting mermaid string and visualize it
To do
- create the custom gradio look
- explore making it look better
- get a better model — Qwen 30b coder
- use zerogpu
"""
from huggingface_hub import hf_hub_download
from llama_cpp import Llama
import gradio as gr
from gradio import Server
from fastapi.responses import HTMLResponse # serve the custom frontend from a route
from typing import Any, cast # to resolve PyLance freaking out over llama-cpp-python in the generate_flowchart function
from textwrap import dedent
import re # remove thinking tag from response
# ----- Get Model ----- #
# Download Q4_K_M GGUF file from the repo
model_path = hf_hub_download(
repo_id="unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF",
filename="Qwen3-Coder-30B-A3B-Instruct-UD-Q3_K_XL.gguf" # fallback: Q2_K_XL
)
# Initialize llama.cpp with the local cached path
# ----- Init App ----- #
app = gr.Server(title="Code-to-Flowchart Generator")
# ----- Functions ----- #
# This is a cleaning function to resolve common syntax errors.
def quote_labels(text: str) -> str:
# Mermaid node labels can't hold raw code characters, so quote-wrap each label body
# A label's real closing bracket is followed by a Mermaid connector, edge-label, pipe, statement end, or EOL
# operators after a subscript (== < <= > >= != %) are never mistaken for a close.
END = r'(?=\s*(?:[-<][-.>xo]|==[>=xo]|\||;|$))'
def esc(body: str) -> str:
return (body.replace('"', "'")
.replace('[', '[').replace(']', ']')
.replace('{', '{').replace('}', '}'))
out = []
for line in text.split('\n'):
line = re.sub(r'(?<=\w)\[(.*?)\]' + END, lambda m: '["' + esc(m.group(1)) + '"]', line)
line = re.sub(r'(?<=\w)\{(.*?)\}' + END, lambda m: '{"' + esc(m.group(1)) + '"}', line)
out.append(line)
return '\n'.join(out)
@app.api(name="generate_flowchart")
def generate_flowchart(src_code: str) -> str:
# check if src_code is empty
if not src_code.strip(): return ""
# Set system prompt
system_prompt = dedent("""
## Role/Persona
You are a senior staff software architect and compiler engineer specializing in visual control-flow mapping. Your philosophy is pure utility: you translate raw execution logic into highly accurate, scannable, structural diagrams without any conversational filler, meta-commentary, or stylistic fluff.
## Context/Objective
The user will provide source code files or logic snippets. Your sole objective is to parse the syntax and output a corresponding, valid Mermaid.js flowchart graph. This graph will be rendered natively in a production UI to help developers audit execution paths at a glance.
## Strict Constraints
graph TD
A[Paste Code] --> B[Click Generate]