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 Generator API | |
def generate_code(instructions, language, generation_type): | |
api_url = 'https://api.codepal.ai/v1/code-generator/query' | |
headers = {'Authorization': f'Bearer {api_key}'} | |
data = { | |
'instructions': instructions, | |
'language': language, | |
'generation_type': generation_type | |
} | |
response = requests.post(api_url, headers=headers, data=data) | |
if response.status_code == 201: | |
return response.json().get('result', 'No code generated.') | |
elif response.status_code == 401: | |
return 'Unauthorized: Invalid or missing API key.' | |
else: | |
return f'Error {response.status_code}: {response.text}' | |
# Gradio interface components | |
with gr.Blocks() as demo: | |
gr.Markdown("# Code Generator Interface\nGenerate code snippets using CodePal's Code Generator API.") | |
with gr.Row(): | |
with gr.Column(): | |
instructions_input = gr.Textbox(label='Function Description', placeholder='Describe the function to generate...') | |
language_input = gr.Dropdown(label='Programming Language', choices=['python', 'javascript', 'go', 'java', 'csharp']) | |
generation_type_input = gr.Radio(label='Generation Type', choices=['minimal', 'standard', 'documented'], value='standard') | |
generate_button = gr.Button(value='Generate Code') | |
clear_button = gr.Button(value='Clear') | |
error_output = gr.Textbox(label='Error Message', visible=False) | |
with gr.Column(): | |
output_display = gr.Code(label='Generated Code') | |
# Example inputs | |
examples = [ | |
["Function to add two numbers", "python", "standard"], | |
["Class definition for a linked list", "java", "documented"], | |
["Script to fetch data from an API", "javascript", "minimal"] | |
] | |
gr.Examples(examples=examples, inputs=[instructions_input, language_input, generation_type_input]) | |
# Define button actions | |
generate_button.click(generate_code, inputs=[instructions_input, language_input, generation_type_input], outputs=[output_display, error_output]) | |
clear_button.click(lambda: ("", "python", "standard", "", ""), outputs=[instructions_input, language_input, generation_type_input, output_display, error_output]) | |
# Launch the interface | |
demo.launch() |