Spaces:
Running
Running
import os | |
import gradio as gr | |
import requests | |
# 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.") | |
# Function to call CodePal's Code Reviewer API | |
def review_code(code): | |
api_url = "https://api.codepal.ai/v1/code-reviewer/query" | |
headers = {"Authorization": f"Bearer {api_key}"} | |
data = {"code": code} | |
response = requests.post(api_url, headers=headers, data=data) | |
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}" | |
# Build the Gradio interface using Blocks for better layout control | |
with gr.Blocks() as demo: | |
gr.Markdown("# Code Reviewer Interface\nGet a professional code review for any piece of code.") | |
# Hugging Face Login Button (requires `hf_oauth: true` in your README metadata) | |
login_button = 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") | |
# Examples to guide users | |
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 | |
) | |
# Define the actions for the buttons | |
review_button.click(review_code, inputs=code_input, outputs=review_output) | |
clear_button.click(lambda: ("", ""), outputs=[code_input, review_output]) | |
# Launch the interface | |
demo.launch() |