Spaces:
Running
Running
import os | |
import gradio as gr | |
import requests | |
def get_api_key(): | |
"""Retrieve the API key from the environment variable.""" | |
api_key = os.getenv("CODEPAL_API_KEY") | |
if not api_key: | |
raise ValueError("API key not found. Please set the CODEPAL_API_KEY environment variable.") | |
return api_key | |
def handle_api_response(response): | |
"""Handle the API response and return the appropriate message.""" | |
if response.status_code == 201: | |
return response.json().get("result", "No review available.") | |
elif response.status_code == 401: | |
return "Unauthorized: Invalid or missing API key." | |
else: | |
return f"Error {response.status_code}: {response.text}" | |
def review_code(code): | |
""" | |
Sends the provided code to the CodePal Code Reviewer API and returns the review results. | |
Parameters: | |
code (str): The code to be reviewed. | |
Returns: | |
str: The result of the code review, or an error message if the API request fails. | |
""" | |
if not code or not code.strip(): | |
return "Error: The code input is empty. Please provide code for review." | |
api_url = "https://api.codepal.ai/v1/code-reviewer/query" | |
headers = {"Authorization": f"Bearer {get_api_key()}"} | |
# Provide a filename and content type to simulate a file upload | |
files = {"code": ("code.txt", code, "text/plain")} | |
response = requests.post(api_url, headers=headers, files=files) | |
return handle_api_response(response) | |
def create_interface(): | |
"""Create the Gradio interface for the code reviewer.""" | |
with gr.Blocks() as demo: | |
gr.Markdown("# Code Reviewer Interface\nGet a professional code review for any piece of code.") | |
gr.LoginButton() | |
with gr.Row(): | |
with gr.Column(): | |
code_input = gr.Textbox(label="Code to Review", placeholder="Paste your code here...", lines=15) | |
review_button = gr.Button("Review Code") | |
clear_button = gr.Button("Clear") | |
with gr.Column(): | |
review_output = gr.Code(label="Code Review", language="markdown") | |
gr.Examples( | |
examples=[ | |
["def factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)\n\nprint(factorial(5))"] | |
], | |
inputs=code_input | |
) | |
review_button.click(review_code, inputs=code_input, outputs=review_output) | |
clear_button.click(lambda: ("", ""), outputs=[code_input, review_output]) | |
return demo | |
if __name__ == "__main__": | |
demo = create_interface() | |
demo.launch() | |