File size: 4,004 Bytes
67d07c0
aa0cce8
67d07c0
 
 
 
 
 
1dc3500
 
 
 
 
 
 
 
 
67d07c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa0cce8
67d07c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import spaces
import gradio as gr
from github import Github, GithubException
from smolagents import CodeAgent, OpenAIServerModel, tool

@tool
def create_or_update_file(file_path: str, content: str, commit_message: str, repo_name: str) -> str:
    """
    Crea o aggiorna un file direttamente nel repository GitHub specificato.

    Args:
        file_path: Il percorso e nome del file da creare o aggiornare (es. 'index.html', 'style.css').
        content: Il codice o contenuto testuale completo da scrivere nel file.
        commit_message: Il messaggio descrittivo per il commit su GitHub.
        repo_name: Il nome del repository GitHub target nel formato 'username/repository'.
    """
    github_token = os.getenv("GITHUB_TOKEN")

    if not github_token:
        return "Errore: GITHUB_TOKEN non configurato nei Secret dello Space."

    try:
        g = Github(github_token)
        repo = g.get_repo(repo_name)
        
        try:
            existing_file = repo.get_contents(file_path)
            repo.update_file(
                path=file_path,
                message=commit_message,
                content=content,
                sha=existing_file.sha
            )
            return f"File '{file_path}' aggiornato con successo nel repository '{repo_name}'."
        except GithubException as e:
            if e.status == 404:
                repo.create_file(
                    path=file_path,
                    message=commit_message,
                    content=content
                )
                return f"File '{file_path}' creato con successo nel repository '{repo_name}'."
            else:
                raise e
    except Exception as e:
        return f"Errore nell'operazione su GitHub: {str(e)}"

@spaces.GPU
def generate_website(prompt: str, repo_name: str) -> str:
    nvidia_key = os.getenv("NVIDIA_API_KEY")
    if not nvidia_key:
        return "Errore: NVIDIA_API_KEY non configurata nei Secret dello Space."
    
    if not repo_name or "/" not in repo_name:
        return "Inserisci un repository valido nel formato 'username/repository'."

    nvidia_model = OpenAIServerModel(
        model_id="meta/llama-3.3-70b-instruct",
        api_base="https://integrate.api.nvidia.com/v1",
        api_key=nvidia_key,
    )

    agent = CodeAgent(
        tools=[create_or_update_file],
        model=nvidia_model,
        additional_authorized_imports=["os", "json"]
    )

    formatted_prompt = (
        f"{prompt}\n\n"
        f"Devi salvare tutti i file generati (es. index.html, style.css, script.js) "
        f"utilizzando il tool 'create_or_update_file' fornendo come repo_name esattamente '{repo_name}'."
    )

    try:
        result = agent.run(formatted_prompt)
        return str(result)
    except Exception as e:
        return f"Errore durante l'esecuzione dell'agente: {str(e)}"

with gr.Blocks(title="AI Web Builder Agent") as demo:
    gr.Markdown("# 🚀 AI Web Builder Agent")
    gr.Markdown("Genera siti web automatici e invia direttamente i commit al tuo repository GitHub tramite **NVIDIA NIM** e **smolagents**.")
    
    with gr.Row():
        with gr.Column():
            repo_input = gr.Textbox(
                label="Repository GitHub Target",
                placeholder="es. tuo-utente/tuo-repo",
                lines=1
            )
            prompt_input = gr.Textbox(
                label="Descrizione del Sito Web",
                placeholder="es. Crea un sito web moderno per una landing page con HTML5, CSS custom in un file style.css e script.js...",
                lines=5
            )
            btn = gr.Button("Genera e Commit su GitHub", variant="primary")
        
        with gr.Column():
            output_box = gr.Textbox(
                label="Log di Esecuzione Agente",
                lines=12
            )

    btn.click(
        fn=generate_website,
        inputs=[prompt_input, repo_input],
        outputs=output_box
    )

if __name__ == "__main__":
    demo.launch()