├── .gitignore ├── MANIFEST.in ├── README.md ├── code2flowchart ├── __init__.py ├── agents │ └── __init__.py ├── config.json ├── constants.py ├── generators.py ├── main.py ├── playground.py ├── templates │ ├── __init__.py │ ├── flowchart_prompt.py │ └── prompt.py ├── tools │ ├── CodeExplanationTool.py │ ├── FlowchartGenTool.py │ └── __init__.py └── utils │ ├── __init__.py │ ├── asyncllm │ ├── AbstractAsyncLLM.py │ ├── AsyncFlowGenerator.py │ ├── __init__.py │ └── helpers.py │ ├── extractors │ ├── __init__.py │ └── githubextractor.py │ └── flowchart │ ├── __init__.py │ └── mermaid.py ├── requirements.txt ├── setup.py └── utils ├── __pycache__ ├── __init__.cpython-311.pyc └── mermaid.cpython-311.pyc └── asyncllm └── __pycache__ ├── AbstractAsyncLLM.cpython-311.pyc └── __init__.cpython-311.pyc /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include code2flowchart * -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Code2Flowchart 2 | 3 | Code2Flowchart is a Python package that generates a flowchart from a given code in any programming language. With Code2Flowchart, you can easily visualize the control flow of your code and identify any potential issues. 4 | 5 | ## Usage 6 | 7 | To use Code2Flowchart, you will need to set your personal GitHub access token and OpenAI API key as environment variables. Once you have done this, you can run the `main.py` file and update it to be adapted to the GitHub repo you want to generate flowcharts from. The output will be a flowchart for every file you have in your repo. 8 | 9 | If you want to directly inject a piece of code instead of giving a repo, you can run `playground.py`, which will run a Streamlit playground to add your code and generate a flowchart from it. 10 | 11 | To get started, make sure you have installed all the dependencies by running: 12 | 13 | `pip install -r requirements.txt` 14 | 15 | ## Environment Variables 16 | 17 | You will need to set the following environment variables before using Code2Flowchart: 18 | 19 | - `GITHUB_ACCESS_TOKEN`: Your GitHub access token, which you can obtain from your GitHub account settings. 20 | - `OPENAI_API_KEY`: Your OpenAI API key, which you can obtain from the OpenAI website. 21 | 22 | ## Contributing 23 | 24 | Contributions are welcome! If you have any suggestions or issues, please open an issue or pull request on the GitHub repo. 25 | 26 | ## License 27 | 28 | Code2Flowchart is licensed under the MIT License. See the `LICENSE` file for more information. -------------------------------------------------------------------------------- /code2flowchart/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IyadhKhalfallah/Code2Flowchart/7aab7d569944084f071e2c90b4ab80d4aefce9f0/code2flowchart/__init__.py -------------------------------------------------------------------------------- /code2flowchart/agents/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IyadhKhalfallah/Code2Flowchart/7aab7d569944084f071e2c90b4ab80d4aefce9f0/code2flowchart/agents/__init__.py -------------------------------------------------------------------------------- /code2flowchart/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "email": "email@example.org", 3 | "password": "xxx" 4 | } -------------------------------------------------------------------------------- /code2flowchart/constants.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | GITHUB_ACCESS_TOKEN = 'GITHUB_TOKEN' 4 | OPENAI_API_KEY = 'OPENAI_KEY' 5 | 6 | os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY 7 | 8 | from tools.FlowchartGenTool import FlowchartGenTool 9 | from tools.CodeExplanationTool import CodeExplanationTool 10 | 11 | TOOLS = [ 12 | { 13 | 'tool': FlowchartGenTool, 14 | 'summary': 'Generates a flowchart from a given context', 15 | 'include': True 16 | }, 17 | { 18 | 'tool': CodeExplanationTool, 19 | 'summary': 'Explains code, in any language.', 20 | 'include': True 21 | }, 22 | ] 23 | -------------------------------------------------------------------------------- /code2flowchart/generators.py: -------------------------------------------------------------------------------- 1 | from langchain.llms import OpenAI 2 | 3 | from code2flowchart.utils.flowchart.mermaid import generate_flowchart 4 | from code2flowchart.templates.prompt import flowchart_template 5 | 6 | 7 | def generate_output(code): 8 | llm = OpenAI(temperature=0.9) 9 | 10 | prompt = flowchart_template( 11 | f""" 12 | {code} 13 | """) 14 | res = llm(prompt) 15 | return generate_flowchart(res.replace('```', '').replace('mermaid', '')) 16 | 17 | 18 | async def async_generate_output(file_name, code): 19 | llm = OpenAI(temperature=0.9) 20 | 21 | prompt = flowchart_template( 22 | f""" 23 | {code} 24 | """) 25 | res = await llm.agenerate([prompt]) 26 | return generate_flowchart(file_name, res.generations[0][0].text.replace('```', '')) 27 | 28 | 29 | -------------------------------------------------------------------------------- /code2flowchart/main.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from code2flowchart.utils.asyncllm.AsyncFlowGenerator import AsyncFlowGenerator 3 | 4 | 5 | def run(): 6 | async_llm = AsyncFlowGenerator(0) 7 | loop = asyncio.get_event_loop() 8 | tasks = [ 9 | loop.create_task(async_llm.generate_concurrently('IyadhKhalfallah', 'aws-lambda_terraform')), 10 | ] 11 | loop.run_until_complete(asyncio.wait(tasks)) 12 | loop.close() 13 | 14 | 15 | if __name__ == '__main__': 16 | run() 17 | -------------------------------------------------------------------------------- /code2flowchart/playground.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | 3 | from langchain.memory import ConversationBufferMemory 4 | from langchain.llms import OpenAI 5 | from langchain.agents import initialize_agent 6 | 7 | from code2flowchart.constants import TOOLS 8 | from code2flowchart.utils.flowchart.mermaid import generate_flowchart 9 | from code2flowchart.templates.prompt import flowchart_template 10 | 11 | 12 | llm = OpenAI(temperature=0) 13 | 14 | 15 | def generate_output(code): 16 | llm = OpenAI(temperature=0.9) 17 | 18 | prompt = flowchart_template( 19 | f""" 20 | {code} 21 | """) 22 | res = llm(prompt) 23 | return generate_flowchart(res.replace('```', '')) 24 | 25 | 26 | def run_agent(code): 27 | tools = [tool['tool']() for tool in TOOLS if tool['include'] is True] 28 | 29 | memory = ConversationBufferMemory(memory_key="chat_history", output_key='output') 30 | 31 | agent = initialize_agent(tools, llm, agent="conversational-react-description", memory=memory, verbose=True) 32 | 33 | prompt = flowchart_template( 34 | f""" 35 | {code} 36 | """) 37 | 38 | agent.run(prompt) 39 | agent.run("Generate a correct mermaid.js flowchart syntax from the explanation you provided") 40 | 41 | 42 | def main(): 43 | st.title("Flowchart generator from code") 44 | 45 | # Add a text input box for the Python code 46 | code = st.text_area("Enter your Python code here:", max_chars=5000) 47 | # Add a submit button 48 | if st.button("Run Code"): 49 | # Run the Python code and display the output 50 | output = generate_output(code) 51 | st.image(output, caption="Generated Image", use_column_width=True) 52 | 53 | 54 | main() 55 | -------------------------------------------------------------------------------- /code2flowchart/templates/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IyadhKhalfallah/Code2Flowchart/7aab7d569944084f071e2c90b4ab80d4aefce9f0/code2flowchart/templates/__init__.py -------------------------------------------------------------------------------- /code2flowchart/templates/flowchart_prompt.py: -------------------------------------------------------------------------------- 1 | # "After you explained the code, generate a correct mermaid.js flowchart syntax to explain what every component of this code does." 2 | from langchain import PromptTemplate 3 | 4 | 5 | template = """ 6 | I want you to act as a flowchart expert. 7 | 8 | Generate a correct mermaid.js flowchart syntax to explain the below code explanation: 9 | CONTEXT_START 10 | {code} 11 | CONTEXT_END 12 | 13 | the output of this should be only the mermaid.js flowchart syntax. 14 | """ 15 | 16 | 17 | def flowchart_template(code): 18 | prompt = PromptTemplate( 19 | input_variables=["code"], 20 | template=template, 21 | ) 22 | 23 | return prompt.format(code=code) -------------------------------------------------------------------------------- /code2flowchart/templates/prompt.py: -------------------------------------------------------------------------------- 1 | from langchain import PromptTemplate 2 | 3 | 4 | template = """ 5 | I want you to act as a senior code analyst. 6 | Explain the code below in details: 7 | {code} 8 | After you explained the code, generate a correct mermaid.js flowchart syntax to explain what every component of this code does. 9 | Output only the mermaid.js flowchart syntax. 10 | """ 11 | 12 | 13 | def flowchart_template(code): 14 | prompt = PromptTemplate( 15 | input_variables=["code"], 16 | template=template, 17 | ) 18 | 19 | return prompt.format(code=code) -------------------------------------------------------------------------------- /code2flowchart/tools/CodeExplanationTool.py: -------------------------------------------------------------------------------- 1 | from langchain.tools import BaseTool 2 | from langchain.llms import OpenAI 3 | 4 | 5 | class CodeExplanationTool(BaseTool): 6 | name = "Explain code" 7 | description = ( 8 | "A text generator from code, which acts like a code analyst to explain a code in details." 9 | "Input should be a valid code in any programming language, found between CONTEXT_START and CONTEXT_END." 10 | "" 11 | ) 12 | llm = OpenAI(temperature=0.9) 13 | 14 | def _run(self, query: str) -> str: 15 | """Use the tool.""" 16 | return self.llm(query) 17 | 18 | async def _arun(self, query: str) -> str: 19 | """Use the tool asynchronously.""" 20 | raise NotImplementedError("CodeExplanationTool does not support async") -------------------------------------------------------------------------------- /code2flowchart/tools/FlowchartGenTool.py: -------------------------------------------------------------------------------- 1 | from langchain.tools import BaseTool 2 | from langchain.llms import OpenAI 3 | 4 | from code2flowchart.utils.flowchart.mermaid import generate_flowchart 5 | from code2flowchart.templates.flowchart_prompt import flowchart_template 6 | 7 | 8 | class FlowchartGenTool(BaseTool): 9 | name = "Generate flowchart" 10 | description = ( 11 | "A flowchart generator, which generates a flowchart out of some text explaining a code process." 12 | "Input should be a valid a detailed text explaining a process." 13 | "" 14 | ) 15 | llm = OpenAI(temperature=0.9) 16 | 17 | def _run(self, query: str) -> str: 18 | """Use the tool.""" 19 | code = self.llm(flowchart_template(query)) 20 | return generate_flowchart(code.replace('`', '')) 21 | 22 | async def _arun(self, query: str) -> str: 23 | """Use the tool asynchronously.""" 24 | raise NotImplementedError("CodeExplanationTool does not support async") -------------------------------------------------------------------------------- /code2flowchart/tools/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IyadhKhalfallah/Code2Flowchart/7aab7d569944084f071e2c90b4ab80d4aefce9f0/code2flowchart/tools/__init__.py -------------------------------------------------------------------------------- /code2flowchart/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IyadhKhalfallah/Code2Flowchart/7aab7d569944084f071e2c90b4ab80d4aefce9f0/code2flowchart/utils/__init__.py -------------------------------------------------------------------------------- /code2flowchart/utils/asyncllm/AbstractAsyncLLM.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | 3 | 4 | class AbstractAsyncLLM(ABC): 5 | def __init__(self, temperature): 6 | self.temperature = temperature 7 | 8 | @abstractmethod 9 | async def async_generate(self): 10 | pass 11 | 12 | async def generate_concurrently(self): 13 | pass 14 | -------------------------------------------------------------------------------- /code2flowchart/utils/asyncllm/AsyncFlowGenerator.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import os 3 | from code2flowchart.utils.asyncllm.AbstractAsyncLLM import AbstractAsyncLLM 4 | from code2flowchart.utils.extractors.githubextractor import get_github_files 5 | from code2flowchart.generators import async_generate_output 6 | 7 | os.environ['OPENAI_API_KEY'] = 'OPENAI_KEY' 8 | 9 | 10 | class AsyncFlowGenerator(AbstractAsyncLLM): 11 | def __init__(self, temperature): 12 | super().__init__(temperature) 13 | 14 | async def async_generate(self, file_name, code): 15 | await async_generate_output(file_name, code) 16 | 17 | async def generate_concurrently(self, owner, repo): 18 | git_files = get_github_files(owner, repo) 19 | tasks = [self.async_generate(file_name, code) for file_name, code in git_files.items()] 20 | await asyncio.gather(*tasks) 21 | -------------------------------------------------------------------------------- /code2flowchart/utils/asyncllm/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IyadhKhalfallah/Code2Flowchart/7aab7d569944084f071e2c90b4ab80d4aefce9f0/code2flowchart/utils/asyncllm/__init__.py -------------------------------------------------------------------------------- /code2flowchart/utils/asyncllm/helpers.py: -------------------------------------------------------------------------------- 1 | import time 2 | import asyncio 3 | 4 | from langchain.llms import OpenAI 5 | 6 | 7 | async def async_generate(llm): 8 | resp = await llm.agenerate(["Hello, how are you?"]) 9 | print(resp.generations[0][0].text) 10 | 11 | 12 | async def generate_concurrently(): 13 | llm = OpenAI(temperature=0.9) 14 | tasks = [async_generate(llm) for _ in range(10)] 15 | await asyncio.gather(*tasks) 16 | 17 | -------------------------------------------------------------------------------- /code2flowchart/utils/extractors/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IyadhKhalfallah/Code2Flowchart/7aab7d569944084f071e2c90b4ab80d4aefce9f0/code2flowchart/utils/extractors/__init__.py -------------------------------------------------------------------------------- /code2flowchart/utils/extractors/githubextractor.py: -------------------------------------------------------------------------------- 1 | import os 2 | import requests 3 | from github import Github 4 | 5 | 6 | g = Github(os.environ['GITHUB_ACCESS_TOKEN']) 7 | 8 | 9 | def get_github_files(owner, repo): 10 | repo = g.get_repo(f'{owner}/{repo}') 11 | contents = repo.get_contents("") 12 | 13 | files_dict = {} 14 | 15 | for content in contents: 16 | if content.type == "file": 17 | # Getting the file content using the raw URL 18 | file_content = requests.get(content.download_url).text 19 | files_dict[content.name] = file_content 20 | 21 | return files_dict 22 | -------------------------------------------------------------------------------- /code2flowchart/utils/flowchart/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IyadhKhalfallah/Code2Flowchart/7aab7d569944084f071e2c90b4ab80d4aefce9f0/code2flowchart/utils/flowchart/__init__.py -------------------------------------------------------------------------------- /code2flowchart/utils/flowchart/mermaid.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import requests, io 3 | from PIL import Image 4 | import logging 5 | 6 | 7 | def generate_flowchart(file_name, code): 8 | graph = f""" 9 | {code} 10 | """ 11 | print(graph) 12 | graphbytes = graph.encode("ascii") 13 | 14 | base64_bytes = base64.b64encode(graphbytes) 15 | base64_string = base64_bytes.decode("ascii") 16 | 17 | try: 18 | img = Image.open(io.BytesIO(requests.get('https://mermaid.ink/img/' + base64_string).content)) 19 | img.save(f"{file_name}.png") 20 | return img 21 | except: 22 | logging.error(f"Failed to download flowchart image") 23 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | langchain==0.0.113 2 | Pillow==9.4.0 3 | PyGithub==1.58.0 4 | requests==2.28.2 5 | setuptools==66.1.1 6 | streamlit==1.20.0 7 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | setup( 3 | name='code2flowchart', 4 | packages=find_packages(include=['code2flowchart']), 5 | version='0.1.0', 6 | description='Transform your code to a simple explanatory flowchart.', 7 | author='Iyadh Khalfallah', 8 | license='MIT', 9 | install_requires=['langchain', 'Pillow', 'PyGithub', 'requests', 'setuptools', 'streamlit'], 10 | ) 11 | -------------------------------------------------------------------------------- /utils/__pycache__/__init__.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IyadhKhalfallah/Code2Flowchart/7aab7d569944084f071e2c90b4ab80d4aefce9f0/utils/__pycache__/__init__.cpython-311.pyc -------------------------------------------------------------------------------- /utils/__pycache__/mermaid.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IyadhKhalfallah/Code2Flowchart/7aab7d569944084f071e2c90b4ab80d4aefce9f0/utils/__pycache__/mermaid.cpython-311.pyc -------------------------------------------------------------------------------- /utils/asyncllm/__pycache__/AbstractAsyncLLM.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IyadhKhalfallah/Code2Flowchart/7aab7d569944084f071e2c90b4ab80d4aefce9f0/utils/asyncllm/__pycache__/AbstractAsyncLLM.cpython-311.pyc -------------------------------------------------------------------------------- /utils/asyncllm/__pycache__/__init__.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IyadhKhalfallah/Code2Flowchart/7aab7d569944084f071e2c90b4ab80d4aefce9f0/utils/asyncllm/__pycache__/__init__.cpython-311.pyc --------------------------------------------------------------------------------