import gradio as gr import os import json import uuid from datetime import datetime from pathlib import Path import requests from functools import lru_cache # Minimal HF Space implementation DATA_DIR = Path("./data") PROJECTS_FILE = DATA_DIR / "projects.json" DATA_DIR.mkdir(exist_ok=True) if not PROJECTS_FILE.exists(): with open(PROJECTS_FILE, 'w') as f: json.dump({}, f) def load_projects(): try: with open(PROJECTS_FILE, 'r') as f: return json.load(f) except: return {} def save_projects(projects): with open(PROJECTS_FILE, 'w') as f: json.dump(projects, f, indent=2) @lru_cache(maxsize=32) def call_hf_api(prompt: str): """Call Hugging Face Inference API with caching.""" try: hf_token = os.getenv('HF_TOKEN') if not hf_token: return None headers = {"Authorization": f"Bearer {hf_token}"} response = requests.post( "https://api-inference.huggingface.co/models/microsoft/DialoGPT-medium", headers=headers, json={"inputs": prompt, "parameters": {"max_length": 300}}, timeout=10 ) if response.status_code == 200: result = response.json() if isinstance(result, list) and len(result) > 0: return result[0].get('generated_text', '').replace(prompt, '').strip() except Exception as e: print(f"HF API error: {e}") return None def generate_static_analysis(project_name: str, description: str, features: str): """Fallback static analysis template.""" return f"""# Technical Analysis for {project_name} ## Project Overview {description} ## Recommended Technology Stack - **Backend**: Python with FastAPI - **Frontend**: React with TypeScript - **Database**: PostgreSQL - **Testing**: Jest, Pytest - **Deployment**: Hugging Face Spaces ## Key Features Implementation {features} *Analysis powered by AgentAI on Hugging Face Spaces* """ def analyze_requirements(project_name: str, description: str, features: str): if not project_name or not description: return "Please provide project name and description.", "", "" # Try LLM analysis first prompt = f"Analyze this software project: {project_name}. Description: {description}. Features: {features}. Provide technical recommendations:" llm_analysis = call_hf_api(prompt) if llm_analysis and len(llm_analysis) > 50: analysis = f"""# AI-Generated Technical Analysis for {project_name} ## Project Overview {description} ## AI Analysis {llm_analysis} ## Key Features {features} *Analysis generated using Hugging Face LLM* """ status_msg = f"✅ Project '{project_name}' analyzed with AI!" else: # Fallback to static template analysis = generate_static_analysis(project_name, description, features) status_msg = f"✅ Project '{project_name}' created (static template)!" project_id = str(uuid.uuid4()) projects = load_projects() projects[project_id] = { "name": project_name, "description": description, "features": features, "analysis": analysis, "created_at": datetime.now().isoformat(), "ai_generated": llm_analysis is not None } save_projects(projects) return analysis, status_msg, project_id def generate_code(project_id: str): projects = load_projects() if not project_id or project_id not in projects: return "Please create a project first." project = projects[project_id] # Try LLM code generation prompt = f"Generate Python FastAPI code for {project['name']}: {project['description']}. Include basic endpoints:" llm_code = call_hf_api(prompt) if llm_code and "def " in llm_code: code = f"""# {project["name"]} - AI Generated Code {llm_code} # Generated by AgentAI with Hugging Face LLM """ else: # Fallback to static template code = f"""# {project["name"]} - Generated by AgentAI from fastapi import FastAPI from pydantic import BaseModel app = FastAPI(title="{project["name"]}") @app.get("/") async def root(): return {{"message": "Welcome to {project["name"]} API"}} @app.get("/health") async def health(): return {{"status": "healthy"}} # Generated by AgentAI - Hugging Face Spaces """ return code with gr.Blocks(title="AgentAI - HF Space", theme=gr.themes.Soft()) as demo: gr.Markdown("# 🤖 AgentAI - Hugging Face Space") with gr.Tab("🚀 Create Project"): with gr.Row(): with gr.Column(): project_name = gr.Textbox(label="Project Name") description = gr.Textbox(label="Description", lines=3) features = gr.Textbox(label="Features", lines=3) create_btn = gr.Button("Analyze", variant="primary") with gr.Column(): analysis_output = gr.Markdown() status_output = gr.Textbox(label="Status") project_id_output = gr.Textbox(label="Project ID") with gr.Tab("💻 Generate Code"): with gr.Row(): with gr.Column(): input_project_id = gr.Textbox(label="Project ID") generate_btn = gr.Button("Generate Code", variant="primary") with gr.Column(): code_output = gr.Code(language="python") create_btn.click( fn=analyze_requirements, inputs=[project_name, description, features], outputs=[analysis_output, status_output, project_id_output] ) generate_btn.click( fn=generate_code, inputs=[input_project_id], outputs=[code_output] ) if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860)