colors, argparse

master
michael 2022-12-07 01:17:40 -08:00
parent da74e67ecd
commit 2ac921d7a7
4 changed files with 101 additions and 74 deletions

View File

@ -1,40 +1,44 @@
#!/usr/bin/env python3
import json import json
import yaml import yaml
from yaml import CLoader, CDumper from yaml import CLoader, CDumper
from revChatGPT.revChatGPT import Chatbot from revChatGPT.revChatGPT import Chatbot
import os import os
from sys import argv from sys import argv
import fmtutil
from parse import py from parse import py
from argparse import ArgumentParser
# from argparse import ArgumentParser argparser = ArgumentParser(
# prog="docugen",
description="generate docs with le AI(tm)",
epilog="https://github.com/turtlebasket/docugen"
)
# argparser = ArgumentParser( argparser.add_argument("filename")
# prog="docugen", argparser.add_argument("-o", dest="output directory", help="directory to write docs to")
# description="generate docs with le AI(tm)", argparser.add_argument("-m", dest="model", help="model to use to generate documentation", choices=["chatgpt"])
# epilog="https://docugen.com" argparser.add_argument("-f", dest="format", help="formatting of output documentation", choices=["md"])
# ) args = argparser.parse_args()
# argparser.add_argument("file", required=True)
file_path = os.path.dirname(os.path.realpath(__file__)) file_path = os.path.dirname(os.path.realpath(__file__))
with open(f"{file_path}/config.yaml", "r") as file: with open(f"{file_path}/config.yaml", "r") as file:
config = yaml.load(file, Loader=CLoader) config = yaml.load(file, Loader=CLoader)
infile = open(argv[1], "r") infile = open(args.filename, "r")
# print(infile)
# top level functions only for now # python & top level functions only for now
functions = py.find_toplevel_funcs(infile) functions = py.find_toplevel_funcs(infile)
print(f"Found {len(functions)} functions.") print(f"Found {len(functions)} functions.")
if len(functions) >= 3:
print(f"Grab a cup of coffee, this could take a while.")
doc_prompt_head = "Explain what this function does in one short sentence, then give example code that uses the function:\n" doc_prompt_head = "Explain what this function does in one short sentence, then give example code that uses the function:\n"
# doc_prompt_example = "Return only example code using this function:\n" # doc_prompt_example = "Return only example code using this function:\n"
# for function in functions:
# print(function["content"])
# print("------------------")
bot = Chatbot({ bot = Chatbot({
'Authorization': config['Authorization'], 'Authorization': config['Authorization'],
'session_token': config['session_token'], 'session_token': config['session_token'],
@ -42,12 +46,12 @@ bot = Chatbot({
bot.refresh_session() bot.refresh_session()
with open(f"{argv[1].split('.')[0]}-doc.md", "w") as outfile: with open(f"{args.filename.split('.')[0]}-doc.md", "w") as outfile:
outfile.write(f"# Documentation for `{argv[1]}`\n\n") outfile.write(f"# Documentation for `{argv[1]}`\n\n")
for function in functions: for function in functions:
head_ask = doc_prompt_head + function["content"] head_ask = doc_prompt_head + function["content"]
resp = bot.get_chat_response(head_ask, output="text") resp = bot.get_chat_response(head_ask, output="text")
print(f'Generated documentation for {function["head"]}.') print(f'Generated documentation for {function["head"]}.')
# append results to doc # append results to doc
output = f"## `{function['head']}`\n" + resp['message'] + "\n\n" output = f"### `{function['head']}`\n" + fmtutil.highlight_multiline_code_md(resp['message'], "python") + "\n\n"
outfile.write(output) outfile.write(output)

View File

@ -1,101 +1,94 @@
# Documentation for `example/example_code.py` # Documentation for `example/example_code.py`
## `remove_dirt(image)` ### `remove_dirt(image)`
This function removes small elements from an image using area closing morphological operation. The `remove_dirt` function removes small objects from the input image using area closing. Here is an example of how to use the `remove_dirt` function:
Example: ```python
import skimage.morphology as morphology
``` # Load an image using some library (e.g. Pillow, OpenCV, etc.)
# Import the required module image = ...
from skimage import morphology
# Load the image # Remove small objects from the image
image = skimage.io.imread('image.jpg')
# Apply the function to remove small elements from the image
image = remove_dirt(image) image = remove_dirt(image)
# Show the result
skimage.io.imshow(image)
``` ```
## `calculate_area(countour)`
This function calculates the area of a contour in an image.
Example: ### `calculate_area(countour)`
The `calculate_area` function calculates the area of a contour in an image using OpenCV. Here is an example of how to use the `calculate_area` function:
``` ```python
# Import the required modules
import cv2 as cv
import numpy as np import numpy as np
import cv2 as cv
# Load the image and find the contours # Load an image using some library (e.g. Pillow, OpenCV, etc.)
image = cv.imread('image.jpg') image = ...
contours, _ = cv.findContours(image, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
# Iterate over the contours and calculate their areas # Find contours in the image using OpenCV
contours = cv.findContours(image, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
# Calculate the area of each contour
for contour in contours: for contour in contours:
area = calculate_area(contour) area = calculate_area(contour)
print('Area of contour:', area) print(area)
``` ```
## `center_of_mass(X)`
This function calculates the center of mass of a set of points.
Example: ### `center_of_mass(X)`
The `center_of_mass` function calculates the center of mass of a 2D shape defined by a set of points. Here is an example of how to use the `center_of_mass` function:
``` ```python
import numpy as np import numpy as np
# Define a set of points # Define a set of points that define a shape
X = np.array([[1,2], [3,4], [5,6]]) X = np.array([[0,0], [0,1], [1,1], [1,0]])
# Calculate the center of mass of the points # Calculate the center of mass of the shape
center = center_of_mass(X) com = center_of_mass(X)
# Print the result # Print the center of mass
print('Center of mass:', center) print(com)
``` ```
The output will be `Center of mass: [3. 4.]`. In this example, the output would be `[0.5, 0.5]`, which is the center of the square defined by the points `X`.
## `center_of_mass(X)`
This function calculates the center of mass of a set of points.
Example: ### `center_of_mass(X)`
The `center_of_mass` function calculates the center of mass of a 2D shape defined by a set of points. Here is an example of how to use the `center_of_mass` function:
``` ```python
import numpy as np import numpy as np
# Define a set of points # Define a set of points that define a shape
X = np.array([[1,2], [3,4], [5,6]]) X = np.array([[0,0], [0,1], [1,1], [1,0]])
# Calculate the center of mass of the points # Calculate the center of mass of the shape
center = center_of_mass(X) com = center_of_mass(X)
# Print the result # Print the center of mass
print('Center of mass:', center) print(com)
``` ```
The output will be `Center of mass: [3. 4.]`. In this example, the output would be `[0.5, 0.5]`, which is the center of the square defined by the points `X`.
## `rg_ratio_normalize(imgarr)`
This function normalizes the temperature values in an image array using the RG ratio and a pyrometry calibration formula.
Example: ### `rg_ratio_normalize(imgarr)`
The `rg_ratio_normalize` function applies a normalization function to the red and green channels of a 2D image, then applies a camera calibration formula to the resulting normalized values and returns the resulting image. Here is an example of how to use the `rg_ratio_normalize` function:
``` ```python
# Import the required modules
import numpy as np import numpy as np
# Load the image array # Load an image using some library (e.g. Pillow, OpenCV, etc.)
imgarr = np.array(...) image = ...
# Normalize the temperature values in the image # Convert the image to a NumPy array
imgarr = np.array(image)
# Apply the normalization and calibration to the image
imgnew, tmin, tmax = rg_ratio_normalize(imgarr) imgnew, tmin, tmax = rg_ratio_normalize(imgarr)
# Print the resulting minimum and maximum temperature values # Print the minimum and maximum temperature values in the image
print('Minimum temperature:', tmin) print(tmin, tmax)
print('Maximum temperature:', tmax)
``` ```

29
fmtutil/__init__.py Normal file
View File

@ -0,0 +1,29 @@
import re
ext_lang_map = {
"py": "python",
"java": "java",
"js": "javascript",
"cpp": "cpp",
"cxx": "cpp",
"hpp": "cpp",
}
def highlight_multiline_code_md(md_text: str, language_str: str) -> str:
"""
Highlight markdown-embedded code blocks.
"""
out = ""
in_code_block = False
for line in md_text.split("\n"):
if not in_code_block and re.search("^```(.*)$", line):
in_code_block = True
if line.strip() == "```":
line = f"```{language_str}"
elif in_code_block and line.strip() == "```":
in_code_block = False
out += line + "\n"
return out

1
parse/js.py Normal file
View File

@ -0,0 +1 @@
# add later