import gradio as gr from groq import Groq import os import json from dotenv import load_dotenv # Load environment variables (for local testing, Hugging Face will handle GROQ_API_KEY as a secret) load_dotenv() def generate_react_component(json_data_str: str, instructions: str, groq_api_key: str) -> str: """ Generates a React functional component based on JSON data and user instructions using the Groq API. Args: json_data_str (str): The input data in JSON string format. instructions (str): Instructions on how to design the React component. groq_api_key (str): Your Groq API key. Returns: str: The generated React component code. """ # Prefer API key from environment variable if available (for Hugging Face Spaces secrets) # The input field will override it if provided api_key_from_env = os.environ.get("GROQ_API_KEY") final_api_key = groq_api_key if groq_api_key else api_key_from_env if not final_api_key: return "Error: Groq API Key is not provided. Please enter your API key or set it as a Hugging Face Space secret named 'GROQ_API_KEY'." try: # Validate JSON data json_data = json.loads(json_data_str) except json.JSONDecodeError: return "Error: Invalid JSON data. Please provide valid JSON." # Initialize Groq client client = Groq(api_key=final_api_key) system_prompt = ( "You are an expert React developer AI. Your task is to generate a React functional " "component (JavaScript/JSX code) based on the provided JSON data and specific " "user instructions. Ensure the component is well-structured, follows best practices, " "and correctly displays the data as requested. Only output the React code, no extra text or explanations." ) user_message = ( f"Here is the JSON data:\n```json\n{json_data_str}\n```\n\n" f"Here are the instructions for designing the React component:\n\"{instructions}\"\n\n" "Please provide ONLY the React functional component code. " "Include necessary imports (e.g., 'React' if using older React versions, though optional for modern JSX transform). " "Focus on presenting the data effectively according to the instructions. " "If the instructions are unclear, make reasonable assumptions to display the data in a user-friendly way." "Make sure the generated code is a complete, runnable React functional component." ) try: chat_completion = client.chat.completions.create( messages=[ { "role": "system", "content": system_prompt, }, { "role": "user", "content": user_message, } ], model="llama3-8b-8192", # Or another suitable Groq model like "llama3-70b-8192" temperature=0.7, # Adjust creativity max_tokens=2048, # Adjust based on expected code length ) react_code = chat_completion.choices[0].message.content return react_code except Exception as e: return f"An error occurred during API call: {e}" # Gradio Interface setup with gr.Blocks(theme=gr.themes.Soft(), title="JSON to React Component Generator") as demo: gr.Markdown( """ # JSON to React Component Generator Provide your data in JSON format and tell me how you want it displayed. I'll generate the React functional component code for you! """ ) with gr.Row(): with gr.Column(scale=1): json_input = gr.Textbox( label="JSON Data", placeholder="Paste your JSON data here...", lines=10, info="Example: {\"products\": [{\"id\": 1, \"name\": \"Laptop\"}, {\"id\": 2, \"name\": \"Mouse\"}]}" ) instructions_input = gr.Textbox( label="Design Instructions", placeholder="e.g., 'Display products in a list with name and id', 'Create cards for each user with their name and email'", lines=3, info="Tell me how you want the React component to display the data." ) groq_api_key_input = gr.Textbox( label="Groq API Key (Optional, set as Space Secret for production)", type="password", placeholder="Enter your Groq API Key here (starts with gsk_...). If set as a Space Secret, you can leave this blank.", info="For Hugging Face Spaces, it's recommended to set this as a secret named 'GROQ_API_KEY'. This field is primarily for local testing or overriding the secret." ) generate_button = gr.Button("Generate React Code") with gr.Column(scale=2): react_code_output = gr.Code( label="Generated React Component Code", language="javascript", # <--- FIX IS HERE: Changed from "jsx" to "javascript" interactive=False, lines=20 ) generate_button.click( fn=generate_react_component, inputs=[json_input, instructions_input, groq_api_key_input], outputs=react_code_output ) gr.Examples( examples=[ [ '{"users": [{"id": 1, "name": "Alice", "email": "alice@example.com"}, {"id": 2, "name": "Bob", "email": "bob@example.com"}]}', 'Display each user in a card with their name as a heading and email below.', '' # Changed placeholder for API key in examples ], [ '{"items": ["Apple", "Banana", "Cherry"]}', 'Create an unordered list of the items.', '' # Changed placeholder for API key in examples ] ], inputs=[json_input, instructions_input, groq_api_key_input], outputs=react_code_output, fn=generate_react_component, cache_examples=False, # Set to False for API key input ) demo.launch()