import gradio as gr import requests import json import os # Retrieve the API key from environment variables API_KEY = os.getenv('API_KEY') if not API_KEY: raise ValueError("API_KEY environment variable not set") API_URL = "https://api-inference.huggingface.co/models/Salesforce/codegen-350M-mono" headers = {"Authorization": f"Bearer {API_KEY}"} def generate_response(prompt, max_length=200, temperature=0.5): data = { "inputs": prompt, "parameters": { "max_length": max_length, "temperature": temperature, } } response = requests.post(API_URL, headers=headers, json=data) if response.status_code == 200: result = response.json() return result[0]['generated_text'] if result else "No response received" else: return f"Error: {response.status_code}\n{response.text}" def main(prompt, max_length=200, temperature=0.5): response = generate_response(prompt, max_length, temperature) return response # Adding real-time feedback def real_time_feedback(prompt): # Validate prompt and provide feedback if len(prompt) < 10: return "Please enter a longer prompt..." else: return "Ready to generate code!" # Adding rich text formatting def format_code(code): # Add syntax highlighting to the generated code using HTML tags formatted_code = "
" + code + "
"
return formatted_code
# Adding interactive elements
def interactive_elements(prompt, max_length=200, temperature=0.5):
# Provide interactive feedback and formatting
feedback = real_time_feedback(prompt)
code = main(prompt, max_length, temperature)
formatted_code = format_code(code)
return feedback, formatted_code
# Enhanced Gradio Interface with interactive elements
interactive_iface = gr.Interface(
fn=interactive_elements,
inputs=[
gr.Textbox(label="Enter your prompt", placeholder="Enter your prompt here...", lines=5),
gr.Slider(label="Max Length", minimum=50, maximum=500, value=200, step=10),
gr.Slider(label="Temperature", minimum=0.1, maximum=1.0, value=0.5, step=0.1)
],
outputs=[
gr.Textbox(label="Real-Time Feedback", placeholder="Real-time feedback will appear here...", lines=1),
gr.HTML(label="Generated Code")
],
title="Enhanced Code Assistant",
description="Enter your prompt and get responses from the code generation model. Adjust the max length and temperature to customize the output."
)
# Launch the Gradio Interface
if __name__ == "__main__":
interactive_iface.launch()