File size: 5,821 Bytes
813ae46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
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)