Skip to content

Commit

Permalink
Merge pull request #3 from Krande/dev
Browse files Browse the repository at this point in the history
Update to README and CI version consistency and an example using equation compiling from functions
  • Loading branch information
Krande committed Aug 27, 2021
2 parents cb26de5 + d93adf4 commit 6444280
Show file tree
Hide file tree
Showing 10 changed files with 119 additions and 31 deletions.
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ jobs:
conda-build -c krande -c conda-forge conda --python=${{ matrix.pyver.distver }} --token=$ANACONDA_TOKEN --user krande --override-channels
- name: build and test conda package
if: github.event_name == 'push' && github.ref != 'refs/heads/main'
shell: bash -l {0}
run: |
conda-build -c krande -c conda-forge conda --python=${{ matrix.pyver.distver }} --override-channels
Expand Down
24 changes: 21 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,25 @@
# Paradoc
A python library for parametric documentation

This is still very early in development so expect things to break.
[![Anaconda-Server Badge](https://anaconda.org/krande/paradoc/badges/version.svg)](https://anaconda.org/krande/paradoc)
[![Anaconda-Server Badge](https://anaconda.org/krande/paradoc/badges/latest_release_date.svg)](https://anaconda.org/krande/paradoc)
[![Anaconda-Server Badge](https://anaconda.org/krande/paradoc/badges/platforms.svg)](https://anaconda.org/krande/paradoc)
[![Anaconda-Server Badge](https://anaconda.org/krande/paradoc/badges/downloads.svg)](https://anaconda.org/krande/paradoc)

A python library for parametric documentation based on markdown and pandoc. `paradoc` brings
some additional functionality to ensure improved end-formatting for .docx exports and integrating
variable substitution. Use `{{__variable__}}` in your markdown files to insert any text prior to running pandoc.

Install using

```
conda install -c krande -c conda-forge paradoc
```

Note! This is still very early in development so expect things to break.


## Usage



## For developers
Expand All @@ -11,7 +29,7 @@ make a fork, experiment and create a pull request when you have something you
would like to add/change/remove.

Before making a pull request you need to lint with, isort, flake8 and black.
Assuming you have a cmd terminal open in the adapy package directory you can
Assuming you have a cmd terminal open in the repo directory you can
run

````
Expand Down
4 changes: 2 additions & 2 deletions conda/meta.yaml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{% set name = "paradoc" %}
{% set version = "0.0.1" %}
{% set data = load_setup_py_data() %}

package:
name: "{{ name|lower }}"
version: "{{ version }}"
version: {{ data.get('version') }}

source:
path: ../
Expand Down
11 changes: 11 additions & 0 deletions files/doc_math/00-main/00-intro.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
# A List of functions

Here is a basic function

{{__my_equation__}}

And here is a small edit of that function

{{__my_equation_2__}}

And here is a table from running the equation in a for loop:

From Equation 1

{{__results__}}

From Equation 2

{{__results_2__}}
1 change: 0 additions & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
[metadata]
name=paradoc
version=0.0.2
author = Kristoffer H. Andersen
author_email = kristoffer_andersen@outlook.com
description = A Python library for Parametric Documentation
Expand Down
3 changes: 3 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from setuptools import setup

setup(version="0.0.2")
16 changes: 6 additions & 10 deletions src/paradoc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def __init__(
self.export_format = export_format
self.variables = dict()
self.tables = dict()
self.functions = dict()
self.equations = dict()

# Style info: https://python-docx.readthedocs.io/en/latest/user/styles-using.html
self.table_format = kwargs.get("table_format", "Grid Table 1 Light")
Expand Down Expand Up @@ -132,6 +132,8 @@ def compile(self, output_name, auto_open=False, metadata_file=None):
:param auto_open:
:param metadata_file:
"""
from .utils import variable_sub

dest_file = (self.dist_dir / output_name).with_suffix(f".{self.export_format}").resolve().absolute()

logging.debug(f'Compiling report to "{dest_file}"')
Expand All @@ -145,15 +147,9 @@ def compile(self, output_name, auto_open=False, metadata_file=None):
# Substitute parameters/tables in the creation of the document
with open(md_file, "r") as f:
tmp_md_doc = f.read()
for key, table in self.tables.items():
key_str = f"{{{{__{key}__}}}}"
if key_str in tmp_md_doc:
tmp_md_doc = tmp_md_doc.replace(key_str, table)

for key, value in self.variables.items():
key_str = f"{{{{__{key}__}}}}"
if key_str in tmp_md_doc:
tmp_md_doc = tmp_md_doc.replace(key_str, str(value))
tmp_md_doc = variable_sub(tmp_md_doc, self.tables)
tmp_md_doc = variable_sub(tmp_md_doc, self.variables)
tmp_md_doc = variable_sub(tmp_md_doc, self.equations)

with open(mdf.build_file, "w") as f:
f.write(tmp_md_doc)
Expand Down
63 changes: 51 additions & 12 deletions src/paradoc/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import os
import pathlib
import re
import traceback

import pypandoc
from docx import Document
Expand Down Expand Up @@ -557,12 +558,27 @@ def fix_headers_after_compose(doc):


def open_word_win32():
import sys

if sys.platform != "win32":
return

try:
import win32com.client

word = win32com.client.DispatchEx("Word.Application")
except (ModuleNotFoundError, ImportError):
logging.error(
"Ensure you have you have win32com installed. "
'Use "conda install -c conda-forge pywin32" to install. '
f"{traceback.format_exc()}"
)
return None
except BaseException as e:
logging.error(f"Unable to find COM connection to Word application. Is Word installed? {e}")
logging.error(
"Probably unable to find COM connection to Word application. "
f"Is Word installed? {traceback.format_exc()}, {e}"
)
return None
return word

Expand Down Expand Up @@ -627,18 +643,41 @@ def get_list_of_files(dir_path, file_ext=None, strict=False):
return all_files


def equation_compiler(f, print_latex=False, print_formula=False):
def basic_equation_compiler(f, print_latex=False, print_formula=False):
from inspect import getsourcelines

try:
import pytexit
except ModuleNotFoundError as e:
raise ModuleNotFoundError(
"To use the equation compiler you will need to install pytexit first.\n"
'Use "pip install pytexit"\n\n'
f'Original error message: "{e}"'
)
import pytexit

lines = getsourcelines(f)
final_line = lines[0][-1]
return pytexit.py2tex(final_line.replace("return ", ""), print_latex=print_latex, print_formula=print_formula)
eq_latex = ""
matches = ("def", "return", '"')
dots = 0
for line in lines[0]:
if any(x in line for x in matches):
dots += line.count('"')
dots += line.count("'")
continue
if dots >= 6 or dots == 0:
eq_latex += pytexit.py2tex(line, print_latex=print_latex, print_formula=print_formula) + "\n"

return eq_latex


def variable_sub(md_doc_str, variable_dict):
for key, value in variable_dict.items():
key_str = f"{{{{__{key}__}}}}"
if key_str in md_doc_str:
md_doc_str = md_doc_str.replace(key_str, str(value))
return md_doc_str


def make_df(inputs, header, func):
import pandas as pd

res_matrix = [header]
for var in inputs:
res_matrix.append((*var, func(*var)))
df = pd.DataFrame(res_matrix)
df.columns = df.iloc[0]
df = df.drop(df.index[0])
return df
13 changes: 12 additions & 1 deletion tests/ex_funcs.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,13 @@
def my_calc_example_1(a, b):
return a * b
"""A calculation with doc stub"""
V_x = a + 1 * (0.3 + a * b) ** 2
return V_x


def my_calc_example_2(a, b):
"""
A calculation with a longer doc stub
"""
V_n = a + 1 * (0.16 + a * b) ** 2
V_x = V_n * 0.98
return V_x
14 changes: 12 additions & 2 deletions tests/test_doc_math.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
import unittest

from common import files_dir, test_dir
from ex_funcs import my_calc_example_1
from ex_funcs import my_calc_example_1, my_calc_example_2

from paradoc import OneDoc
from paradoc.utils import basic_equation_compiler, make_df


class MathDocTests(unittest.TestCase):
def test_math_doc(self):
report_dir = files_dir / "doc_math"

inputs = [(0, 0), (1, 1), (2, 1), (2, 2)]
df1 = make_df(inputs, ("a", "b", "V_x"), my_calc_example_1)
df2 = make_df(inputs, ("a", "b", "V_x"), my_calc_example_2)

one = OneDoc(report_dir, work_dir=test_dir / "doc_math")
one.functions["my_equation"] = my_calc_example_1

one.equations["my_equation"] = basic_equation_compiler(my_calc_example_1)
one.equations["my_equation_2"] = basic_equation_compiler(my_calc_example_2)
one.tables["results"] = df1.to_markdown(index=False, tablefmt="grid")
one.tables["results_2"] = df2.to_markdown(index=False, tablefmt="grid")

one.compile("MathDoc")


Expand Down

0 comments on commit 6444280

Please sign in to comment.