Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
qtrrb committed Aug 5, 2023
0 parents commit be58312
Show file tree
Hide file tree
Showing 7 changed files with 195 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
build/
pymd.egg-info/
.venv/
.ruff_cache/
__pycache__/
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Copyright (c) 2023 Quentin Torroba

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# pymd - Python Markdown Documents

[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/qtrrb/pymd/blob/main/LICENSE)

pymd is a tool library that enables you to create Markdown documents with embedded Python code, results, and plots. Say goodbye to static documents and embrace dynamic, data-driven storytelling.

## Installation

```sh
git clone github.com/qtrrb/pymd
cd pymd
pip install .
```

## Usage

```sh
pymd example.pymd
cat example.md
```
Empty file added pymd/__init__.py
Empty file.
131 changes: 131 additions & 0 deletions pymd/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import sys
import re
import traceback
from io import StringIO
import contextlib
import os

try:
import matplotlib.pyplot as plt

PLT_IS_AVAILABLE = True
except ModuleNotFoundError:
PLT_IS_AVAILABLE = False
print(
"\033[1m\033[93m⚠ Warning: 'matplotlib' is not installed. Plotting inside code blocks won't be available.\033[0m\033[0m"
)


def execute_python_code(code_block):
"""
Executes Python code and captures its output or errors.
Also saves any plot generated by plt.show().
"""
output = StringIO()
error_message = ""

with contextlib.redirect_stdout(output):
try:
exec(code_block, globals())
except Exception:
error_message = traceback.format_exc()

return (
output.getvalue(),
error_message,
)


def compile_pymd(input_file, output_file):
"""
Compiles the pymd file by executing Python code blocks and
adding their output or errors (and saved plots) below the respective code blocks.
"""
try:
with open(input_file, "r") as f:
content = f.read()

python_blocks = re.findall(r"```python(.*?)```", content, re.DOTALL)
if not python_blocks:
print(
"\033[1m\033[93mNo Python code blocks found in the input file.\033[0m\033[0m"
)
return

output_content = content

plot_string = ""
if PLT_IS_AVAILABLE:

def save_plot_and_close(*args, **kwargs):
nonlocal plot_string
fig_title = plt.gca().get_title()
plot_name = f"{fig_title}.png"
plot_folder = "plots"
if not os.path.exists(plot_folder):
os.makedirs(plot_folder)
saved_plot_path = os.path.join(plot_folder, plot_name)
plt.savefig(saved_plot_path)
plt.close()
plot_string += f"\n![{fig_title}]({saved_plot_path})"

plt.show = save_plot_and_close

for code_block in python_blocks:
plot_string = ""
silent_mode = None
if "#silent*input" in code_block:
silent_mode = "input"
elif "#silent*output" in code_block:
silent_mode = "output"

output, error_message = execute_python_code(code_block)
if any(c.strip() for c in output) or any(c.strip() for c in error_message):
output_block = f"```\n{output}{error_message}```"
else:
output_block = ""

if silent_mode == "output":
output_content = output_content.replace(
f"```python{code_block}```", f"```python{code_block}```"
)
elif silent_mode == "input":
output_content = output_content.replace(
f"```python{code_block}```", f"{output_block}{plot_string}"
)
else:
output_content = output_content.replace(
f"```python{code_block}```",
f"```python{code_block}```\n{output_block}{plot_string}",
)

with open(output_file, "w") as f:
f.write(output_content)

print(
f"\033[1m\033[92m✔ Compilation successful. Output written to {output_file}\033[0m\033[0m"
)

except FileNotFoundError:
print("\033[1m\033[91m✖ Error: Input file not found.\033[0m\033[0m")
except Exception as e:
print(f"\033[1m\033[91m✖ Error occurred: {str(e)}\033[0m\033[0m")
traceback.print_exc()


def main():
if len(sys.argv) != 2:
print("\033[1m\033[94mUsage: python pymd.py input_file.pymd\033[0m\033[0m")
else:
input_file = sys.argv[1]
if not input_file.endswith(".pymd"):
print(
"\033[1m\033[91m✖ Error: Input file must have the '.pymd' extension.\033[0m\033[0m"
)
else:
output_file = input_file.replace(".pymd", ".md")
compile_pymd(input_file, output_file)


if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
matplotlib
18 changes: 18 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# pymd/setup.py

from setuptools import setup, find_packages

setup(
name='pymd',
version='0.1',
packages=find_packages(),
install_requires=[
'matplotlib'
],
entry_points={
'console_scripts': [
'pymd=pymd.__main__:main'
]
}
)

0 comments on commit be58312

Please sign in to comment.