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|
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import io
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
import google.generativeai as genai
|
| 6 |
+
from openai import OpenAI
|
| 7 |
+
import gradio as gr
|
| 8 |
+
|
| 9 |
+
# Load environment variables
|
| 10 |
+
load_dotenv()
|
| 11 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
| 12 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 13 |
+
|
| 14 |
+
# Configure APIs
|
| 15 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 16 |
+
openai = OpenAI(api_key=OPENAI_API_KEY)
|
| 17 |
+
|
| 18 |
+
# Model names
|
| 19 |
+
GEMINI_MODEL = "gemini-2.0-flash" # Gemini model
|
| 20 |
+
OPENAI_MODEL = "gpt-4o-mini" # OpenAI model (you can use "gpt-3.5-turbo" if needed)
|
| 21 |
+
|
| 22 |
+
def create_system_prompt():
|
| 23 |
+
"""Create the system prompt for the model."""
|
| 24 |
+
system_message = "You are an assistant that adds high-quality docstrings and comments to Python code. "
|
| 25 |
+
system_message += "Your task is to analyze the code and add appropriate documentation following PEP 257 conventions. "
|
| 26 |
+
system_message += "Add function/class/module docstrings and inline comments where helpful. "
|
| 27 |
+
system_message += "Don't change the functionality of the code, only add documentation. "
|
| 28 |
+
system_message += "Use descriptive docstrings that explain parameters, return values, and exceptions raised."
|
| 29 |
+
return system_message
|
| 30 |
+
|
| 31 |
+
def create_user_prompt(code):
|
| 32 |
+
"""Create the user prompt with the code to be documented."""
|
| 33 |
+
user_prompt = "Please add appropriate docstrings and comments to the following Python code. "
|
| 34 |
+
user_prompt += "Follow PEP 257 style for docstrings. Add comments only where they add value. "
|
| 35 |
+
user_prompt += "Don't change the functionality of the code.\n\n"
|
| 36 |
+
user_prompt += code
|
| 37 |
+
return user_prompt
|
| 38 |
+
|
| 39 |
+
def document_code_with_gemini(code):
|
| 40 |
+
"""Generate documentation for the provided code using Gemini."""
|
| 41 |
+
system_prompt = create_system_prompt()
|
| 42 |
+
user_prompt = create_user_prompt(code)
|
| 43 |
+
|
| 44 |
+
# Use Gemini to generate documentation
|
| 45 |
+
model = genai.GenerativeModel(GEMINI_MODEL)
|
| 46 |
+
response = model.generate_content(
|
| 47 |
+
f"{system_prompt}\n\n{user_prompt}",
|
| 48 |
+
generation_config=genai.GenerationConfig(
|
| 49 |
+
temperature=0.7,
|
| 50 |
+
max_output_tokens=2048,
|
| 51 |
+
),
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
# Clean up the response
|
| 55 |
+
documented_code = response.text.replace("```python", "").replace("```", "").strip()
|
| 56 |
+
return documented_code
|
| 57 |
+
|
| 58 |
+
def document_code_with_openai(code):
|
| 59 |
+
"""Generate documentation for the provided code using OpenAI."""
|
| 60 |
+
system_prompt = create_system_prompt()
|
| 61 |
+
user_prompt = create_user_prompt(code)
|
| 62 |
+
|
| 63 |
+
# Use OpenAI to generate documentation
|
| 64 |
+
response = openai.chat.completions.create(
|
| 65 |
+
model=OPENAI_MODEL,
|
| 66 |
+
messages=[
|
| 67 |
+
{"role": "system", "content": system_prompt},
|
| 68 |
+
{"role": "user", "content": user_prompt},
|
| 69 |
+
],
|
| 70 |
+
temperature=0.7,
|
| 71 |
+
max_tokens=2048,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# Clean up the response
|
| 75 |
+
documented_code = response.choices[0].message.content.replace("```python", "").replace("```", "").replace("python", "")
|
| 76 |
+
return documented_code
|
| 77 |
+
|
| 78 |
+
def document_code(code, api_choice):
|
| 79 |
+
"""Generate documentation using the selected API."""
|
| 80 |
+
if api_choice == "Gemini":
|
| 81 |
+
return document_code_with_gemini(code)
|
| 82 |
+
elif api_choice == "OpenAI":
|
| 83 |
+
return document_code_with_openai(code)
|
| 84 |
+
else:
|
| 85 |
+
return "Invalid API choice."
|
| 86 |
+
|
| 87 |
+
def execute_python(code):
|
| 88 |
+
"""Execute Python code and return the output."""
|
| 89 |
+
try:
|
| 90 |
+
output = io.StringIO()
|
| 91 |
+
sys.stdout = output
|
| 92 |
+
exec(code)
|
| 93 |
+
return output.getvalue()
|
| 94 |
+
except Exception as e:
|
| 95 |
+
return f"Error: {str(e)}"
|
| 96 |
+
finally:
|
| 97 |
+
sys.stdout = sys.__stdout__
|
| 98 |
+
|
| 99 |
+
def create_interface():
|
| 100 |
+
"""Create the Gradio interface for the documentation tool."""
|
| 101 |
+
sample_code = """
|
| 102 |
+
def fibonacci(n):
|
| 103 |
+
fib_series = []
|
| 104 |
+
a, b = 0, 1
|
| 105 |
+
for _ in range(n):
|
| 106 |
+
fib_series.append(a)
|
| 107 |
+
a, b = b, a + b
|
| 108 |
+
return fib_series
|
| 109 |
+
|
| 110 |
+
n = 10
|
| 111 |
+
fib_series = fibonacci(n)
|
| 112 |
+
print("Fibonacci series up to", n, "terms:", fib_series)
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
css = """
|
| 116 |
+
.original {background-color: #2d2d2d; color: #f8f8f2;}
|
| 117 |
+
.documented {background-color: #1e1e1e; color: #f8f8f2;}
|
| 118 |
+
|
| 119 |
+
/* Custom button styles */
|
| 120 |
+
#add-documentation-btn {background-color: #007bff; color: white; font-weight: bold;} /* Blue for Add Documentation */
|
| 121 |
+
#run-original-btn {background-color: #28a745; color: white; font-weight: bold;} /* Green for Run Original Code */
|
| 122 |
+
#run-documented-btn {background-color: #6f42c1; color: white; font-weight: bold;} /* Purple for Run Documented Code */
|
| 123 |
+
|
| 124 |
+
/* Ensure all buttons have white bold text */
|
| 125 |
+
button {color: white; font-weight: bold;}
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
with gr.Blocks(css=css) as ui:
|
| 129 |
+
gr.Markdown("## Automatic Python Documentation Generator")
|
| 130 |
+
|
| 131 |
+
with gr.Row():
|
| 132 |
+
input_code = gr.Textbox(label="Original Python code:", value=sample_code, lines=15, elem_classes=["original"])
|
| 133 |
+
documented_code = gr.Textbox(label="Documented Python code:", lines=15, elem_classes=["documented"])
|
| 134 |
+
|
| 135 |
+
with gr.Row():
|
| 136 |
+
api_choice = gr.Radio(["Gemini", "OpenAI"], label="Select API", value="Gemini")
|
| 137 |
+
document_btn = gr.Button("Add Documentation", elem_id="add-documentation-btn")
|
| 138 |
+
|
| 139 |
+
with gr.Row():
|
| 140 |
+
run_original = gr.Button("Run Original Code", elem_id="run-original-btn")
|
| 141 |
+
run_documented = gr.Button("Run Documented Code", elem_id="run-documented-btn")
|
| 142 |
+
|
| 143 |
+
with gr.Row():
|
| 144 |
+
original_output = gr.TextArea(label="Original code output:")
|
| 145 |
+
documented_output = gr.TextArea(label="Documented code output:")
|
| 146 |
+
|
| 147 |
+
document_btn.click(document_code, inputs=[input_code, api_choice], outputs=[documented_code])
|
| 148 |
+
run_original.click(execute_python, inputs=[input_code], outputs=[original_output])
|
| 149 |
+
run_documented.click(execute_python, inputs=[documented_code], outputs=[documented_output])
|
| 150 |
+
|
| 151 |
+
return ui
|
| 152 |
+
|
| 153 |
+
def main():
|
| 154 |
+
"""Main function to launch the interface."""
|
| 155 |
+
ui = create_interface()
|
| 156 |
+
ui.launch(inbrowser=True)
|
| 157 |
+
|
| 158 |
+
if __name__ == "__main__":
|
| 159 |
+
main()
|