Spaces:
Sleeping
Sleeping
File size: 2,943 Bytes
62f27f1 5549d22 dcda433 5549d22 dcda433 62f27f1 4f1cd2e 7b19954 dcda433 7b19954 1bb8933 dcda433 7b19954 dcda433 7b19954 dcda433 d9965e1 7b19954 dcda433 7b19954 4f1cd2e 7b19954 4f1cd2e 7b19954 f254a63 7b19954 4f1cd2e 7b19954 4f1cd2e 7b19954 4f1cd2e 7b19954 f5c5c4b 7b19954 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | import os
import gradio as gr
from huggingface_hub import InferenceClient
def get_hf_token():
"""Get the HF token from environment variables or Gradio secrets"""
try:
# Try Gradio secrets first (works on Spaces)
return gr.secrets["HF_TOKEN"]
except (AttributeError, KeyError):
# Fall back to environment variable (works locally)
return os.getenv("HF_TOKEN")
def generate_code(prompt):
try:
token = get_hf_token()
if not token:
return "Error: Missing Hugging Face token."
client = InferenceClient(
model="codellama/CodeLlama-34b-Instruct-hf", # Smaller alternative
token=token
)
system_prompt = """You are an expert Next.js 15 or higher with modern App Router, TypeScript and TailwindCSS developer.
Generate clean, efficient code following these rules:
1. Use Next.js App Router
2. Strict TypeScript typing
3. Modern TailwindCSS classes
4. Include proper error boundaries
5. Add JSDoc comments"""
response = client.chat_completion(
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
max_tokens=1500,
temperature=0.3
)
return response.choices[0].message.content
except Exception as e:
return f"Error generating code: {str(e)}"
# Gradio interface with improved layout
with gr.Blocks(
title="Next.js Code Generator",
theme=gr.themes.Soft(),
css=".gradio-container {max-width: 900px !important}"
) as demo:
gr.Markdown("## 🚀 Next.js + TypeScript + TailwindCSS Code Generator")
with gr.Row():
with gr.Column(scale=3):
input_prompt = gr.Textbox(
label="Describe your component",
placeholder="Create a responsive navbar with dark mode toggle...",
lines=5,
max_lines=10
)
with gr.Row():
submit_btn = gr.Button("Generate Code", variant="primary")
clear_btn = gr.Button("Clear")
with gr.Column(scale=7):
output_code = gr.Code(
label="Generated Component",
language="typescript",
interactive=False,
lines=25
)
# Form submission handling
submit_btn.click(
fn=generate_code,
inputs=input_prompt,
outputs=output_code
)
clear_btn.click(
fn=lambda: ("", ""),
inputs=None,
outputs=[input_prompt, output_code]
)
# Launch with sharing enabled
if __name__ == "__main__":
demo.launch(
auth=None, # Disable authentication for local development
share=False # Disable sharing when running locally
) |