gpt_generate.py
Go to the documentation of this file.
1 """
2 GTSAM Copyright 2010-2025, Georgia Tech Research Corporation,
3 Atlanta, Georgia 30332-0415
4 All Rights Reserved
5 
6 See LICENSE for the license information
7 
8 Author: Porter Zach
9 
10 This script generates interactive Python notebooks (.ipynb) that document GTSAM
11 header files. Since inserting the text of the file directly into the prompt
12 might be too many tokens, it retrieves the header file content from the GTSAM
13 GitHub repository. It then sends it to OpenAI's API for processing, and saves
14 the generated documentation as a Jupyter notebook.
15 
16 Functions:
17  is_url_valid(url: str) -> bool:
18  Verifies that the supplied URL does not return a 404.
19 
20  save_ipynb(text: str, file_path: str) -> str:
21  Saves the provided text to a single Markdown cell in a new .ipynb file.
22 
23  generate_ipynb(file_path: str, openai_client):
24  Generates an interactive Python notebook for the given GTSAM header file
25  by sending a request to OpenAI's API and saving the response.
26 
27 Usage:
28  Run the script with paths to GTSAM header files as arguments. For example:
29  python gpt_generate.py gtsam/geometry/Pose3.h
30 """
31 
32 import os
33 import time
34 import requests
35 import argparse
36 import nbformat as nbf
37 from openai import OpenAI
38 
39 _output_folder = "output"
40 _gtsam_gh_base = "https://raw.githubusercontent.com/borglab/gtsam/refs/heads/develop/"
41 _asst_id = "asst_na7wYBtXyGU0x5t2RdcnpxzP"
42 _request_text = "Document the file found at {}."
43 
44 
45 def is_url_valid(url):
46  """Verify that the supplied URL does not return a 404."""
47  try:
48  response = requests.head(url, allow_redirects=True)
49  return response.status_code != 404
50  except requests.RequestException:
51  return False
52 
53 
54 def save_ipynb(text: str, file_path: str):
55  """Save text to a single Markdown cell in a new .ipynb file."""
56  script_dir = os.path.dirname(os.path.abspath(__file__))
57  output_dir = os.path.join(script_dir, _output_folder)
58  os.makedirs(output_dir, exist_ok=True)
59  output_file = os.path.splitext(os.path.basename(file_path))[0] + ".ipynb"
60  output_full_path = os.path.join(output_dir, output_file)
61 
62  nb = nbf.v4.new_notebook()
63  new_cell = nbf.v4.new_markdown_cell(text)
64  nb['cells'].append(new_cell)
65 
66  with open(output_full_path, 'w', encoding='utf-8') as file:
67  nbf.write(nb, file)
68 
69  return output_file
70 
71 
72 def generate_ipynb(file_path: str, openai_client):
73  """Generate an interactive Python notebook for the given GTSAM header file.
74 
75  Args:
76  file_path (str): The fully-qualified path from the root of the gtsam
77  repository to the header file that will be documented.
78  openai_client (openai.OpenAI): The OpenAI client to use.
79  """
80  # Create the URL to get the header file from.
81  url = _gtsam_gh_base + file_path
82 
83  if not is_url_valid(url):
84  print(f"{url} was not found on the server, or an error occurred.")
85  return
86 
87  print(f"Sending request to OpenAI to document {url}.")
88 
89  # Create a new thread and send the request
90  thread = openai_client.beta.threads.create()
91  openai_client.beta.threads.messages.create(
92  thread_id=thread.id, role="user", content=_request_text.format(url))
93 
94  run = openai_client.beta.threads.runs.create(thread_id=thread.id,
95  assistant_id=_asst_id)
96 
97  print("Waiting for the assistant to process the request...")
98 
99  # Wait for request to be processed
100  while True:
101  run_status = openai_client.beta.threads.runs.retrieve(
102  thread_id=thread.id, run_id=run.id)
103  if run_status.status == "completed":
104  break
105  time.sleep(2)
106 
107  print("Request processed. Retrieving response...")
108 
109  # Fetch messages
110  messages = openai_client.beta.threads.messages.list(thread_id=thread.id)
111  # Retrieve response text and strip ```markdown ... ```
112  text = messages.data[0].content[0].text.value.strip('`').strip('markdown')
113 
114  # Write output to file
115  output_filename = save_ipynb(text, file_path)
116 
117  print(f"Response retrieved. Find output in {output_filename}.")
118 
119 
120 if __name__ == "__main__":
121  parser = argparse.ArgumentParser(
122  prog="gpt_generate",
123  description=
124  "Generates .ipynb documentation files given paths to GTSAM header files."
125  )
126  parser.add_argument(
127  "file_paths",
128  nargs='+',
129  help=
130  "The paths to the header files from the root gtsam directory, e.g. 'gtsam/geometry/Pose3.h'."
131  )
132  args = parser.parse_args()
133 
134  # Retrieves API key from environment variable OPENAI_API_KEY
135  client = OpenAI()
136 
137  for file_path in args.file_paths:
138  generate_ipynb(file_path, client)
Eigen::internal::print
EIGEN_STRONG_INLINE Packet4f print(const Packet4f &a)
Definition: NEON/PacketMath.h:3115
gpt_generate.save_ipynb
def save_ipynb(str text, str file_path)
Definition: gpt_generate.py:54
gpt_generate.is_url_valid
def is_url_valid(url)
Definition: gpt_generate.py:45
gpt_generate.generate_ipynb
def generate_ipynb(str file_path, openai_client)
Definition: gpt_generate.py:72


gtsam
Author(s):
autogenerated on Fri Apr 25 2025 03:01:25