File size: 14,916 Bytes
a1c243a
 
 
462be19
e5bc2ce
1b8d07e
 
 
 
 
 
 
 
 
 
 
 
 
a0a02f2
1b8d07e
a0a02f2
 
 
1b8d07e
a0a02f2
1b8d07e
a1c243a
1b8d07e
a1c243a
1b8d07e
 
 
 
 
 
a0a02f2
1b8d07e
a1c243a
 
1b8d07e
 
 
a0a02f2
1b8d07e
a0a02f2
 
1b8d07e
a0a02f2
 
1b8d07e
a1c243a
1b8d07e
 
a1c243a
1b8d07e
 
a0a02f2
1b8d07e
a1c243a
 
1b8d07e
a1c243a
a0a02f2
1b8d07e
013d287
1b8d07e
a0a02f2
a1c243a
a0a02f2
 
1b8d07e
013d287
1b8d07e
 
a1c243a
a0a02f2
1b8d07e
a1c243a
 
 
 
 
 
 
 
 
 
1b8d07e
 
 
013d287
a1c243a
1b8d07e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63b1816
 
 
 
 
 
 
 
 
 
 
 
 
1b8d07e
63b1816
1b8d07e
 
63b1816
 
 
1b8d07e
 
 
 
 
a0a02f2
1b8d07e
 
 
a1c243a
1b8d07e
 
a0a02f2
1b8d07e
a1c243a
1b8d07e
 
a0a02f2
1b8d07e
 
 
a1c243a
 
 
 
 
 
 
 
 
 
 
 
1b8d07e
 
 
 
 
 
3c3aabc
 
e5bc2ce
 
1b8d07e
e5bc2ce
 
013d287
 
 
 
ecc01e0
 
 
 
 
 
 
 
 
013d287
 
 
c3658fd
 
 
 
 
e5bc2ce
c3658fd
e5bc2ce
013d287
e5bc2ce
 
 
 
 
 
c3658fd
 
e5bc2ce
c3658fd
e5bc2ce
c3658fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b8d07e
 
 
 
 
 
 
 
 
a0a02f2
1b8d07e
a0a02f2
1b8d07e
a1c243a
 
 
 
 
 
 
 
 
1b8d07e
 
 
a1c243a
 
 
 
 
 
 
 
1b8d07e
 
 
 
 
 
 
 
a0a02f2
1b8d07e
 
 
a0a02f2
462be19
 
 
a0a02f2
462be19
a0a02f2
 
462be19
 
 
 
a0a02f2
462be19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0a02f2
462be19
 
a0a02f2
462be19
 
 
a0a02f2
462be19
a0a02f2
 
462be19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0a02f2
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
from typing import Dict, Any, Union
import json
import os
from huggingface_hub import hf_hub_download, HfApi
from huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError

from src.core.state.session_manager import SessionManager
from src.core.builder.code_generator import CodeGenerator
from src.core.deployer.huggingface import HFDeployer
from src.core.builder.proposal_generator import proposal_generator

# Initialisation des singletons
session_manager = SessionManager()
# Note: HFDeployer est instancié à la demande pour avoir le token le plus à jour ou géré par contexte si besoin
# Pour l'instant on l'instancie à chaque déploiement.

def init_project(project_name: str, description: str, type: str = "adhoc") -> Dict[str, Any]:
    """
    Creates a new empty project.
    Args:
        project_name: Technical name (e.g. strawberry-counter, ratp-api).
        description: Tool description, or complete Technical Specification (e.g. content of a Swagger/OpenAPI JSON).
        type: 'adhoc' (pure code), 'api_wrapper' (REST).
    Returns:
        A dictionary containing the 'draft_id' required for next steps.
    """
    print(f"DEBUG [init_project]: project_name={project_name}, type={type}")
    draft = session_manager.create_draft(project_name, description, type)
    result = {
        "draft_id": draft.draft_id,
        "config": {
            "name": draft.name,
            "description": draft.description,
            "files": list(draft.code_files.keys())
        },
        "message": f"Project '{project_name}' initialized. Draft ID: {draft.draft_id}"
    }
    print(f"DEBUG [init_project]: result={result}")
    return result

def propose_implementation(project_name: str, description: str) -> Dict[str, Any]:
    """
    Uses internal AI to propose a complete implementation from a description or Swagger.
    Args:
        project_name: The project name.
        description: The description or Swagger/OpenAPI JSON.
    Returns:
        A dictionary containing the proposed Python code, detected inputs, and requirements.
        The calling agent can then validate or modify this code before calling define_logic.
    """
    print(f"DEBUG [propose_implementation]: project_name={project_name}")
    try:
        proposal = proposal_generator.generate_from_description(project_name, description)
        result = {
            "status": "success",
            "proposal": proposal,
            "message": "Implementation proposed. Please review 'python_code' and 'requirements' before calling define_logic."
        }
        print(f"DEBUG [propose_implementation]: result={result.keys()}")
        return result
    except Exception as e:
        print(f"DEBUG [propose_implementation]: error={str(e)}")
        return {"error": f"Error during generation: {str(e)}"}

def define_logic(draft_id: str, python_code: str, inputs: Union[Dict[str, str], str], output_desc: str, requirements: str = "", output_component: str = "text") -> Dict[str, Any]:
    """
    Defines the internal logic of the tool.
    Args:
        inputs: Dictionary of inputs (e.g. {"word": "text"}). Can be a JSON string.
        output_component: Output Gradio component type (text, image, audio, video, html, json, file).
    """
    print(f"DEBUG [define_logic]: draft_id={draft_id}, output_component={output_component}")
    draft = session_manager.get_draft(draft_id)
    if not draft:
        print(f"DEBUG [define_logic]: Draft not found")
        return {"error": f"Draft {draft_id} not found."}

    # Gestion des inputs (Dict ou JSON String)
    if isinstance(inputs, str):
        try:
            inputs_dict = json.loads(inputs)
        except json.JSONDecodeError:
            print(f"DEBUG [define_logic]: Invalid JSON inputs: {inputs}")
            return {"error": "inputs must be a valid JSON string or dictionary"}
    else:
        inputs_dict = inputs

    # 1. Génération du module de l'outil (ex: tools/strawberry_counter.py)
    # On utilise le nom du projet comme nom de fichier (nettoyé)
    tool_filename = draft.name.replace("-", "_").lower()
    tool_module_code = CodeGenerator.generate_tool_module(python_code, inputs_dict, output_desc, draft.name, output_component)
    
    
    # 2. Génération de l'application maître (app.py)
    master_app_code = CodeGenerator.generate_master_app()
    
    # Sauvegarde dans le draft
    # On place l'outil dans un sous-dossier 'tools'
    session_manager.update_code(draft_id, f"tools/{tool_filename}.py", tool_module_code)
    session_manager.update_code(draft_id, "tools/__init__.py", "") # Package marker
    session_manager.update_code(draft_id, "app.py", master_app_code)
    
    # Mise à jour des requirements
    current_reqs = draft.code_files.get("requirements.txt", "")
    new_reqs = current_reqs
    
    # Ajout de gradio si manquant
    if "gradio" not in new_reqs:
        new_reqs += "\ngradio"
        
    # Ajout des requirements spécifiques demandés par le LLM
    if requirements:
        # requirements peut être une liste ou une chaine (si via UI Textbox)
        if isinstance(requirements, list):
            req_list = requirements
        elif isinstance(requirements, str):
            requirements = requirements.strip()
            # Tentative de parsing JSON (cas où ça vient de gr.Code/JSON)
            try:
                parsed = json.loads(requirements)
                if isinstance(parsed, list):
                    req_list = parsed
                else:
                    # Si c'est un JSON valide mais pas une liste, on considère comme string unique
                    req_list = [str(parsed)]
            except json.JSONDecodeError:
                # Fallback: format CSV classique "req1, req2"
                req_list = [r.strip() for r in requirements.split(",") if r.strip()]
        else:
            req_list = []
            
        for req in req_list:
            req_clean = str(req).strip()
            if req_clean and req_clean not in new_reqs:
                new_reqs += f"\n{req_clean}"
    
    draft.code_files["requirements.txt"] = new_reqs.strip()

    return {
        "status": "success",
        "message": f"Logic generated for '{draft.name}'. Ready to deploy.",
        "preview": tool_module_code[:200] + "..." 
    }


def deploy_to_space(draft_id: str, visibility: str = "public", space_target: str = "new", target_space_name: str = "") -> Dict[str, Any]:
    """
    Deploys the project to Hugging Face Spaces.
    """
    print(f"DEBUG [deploy_to_space]: draft_id={draft_id}, target={space_target}, name={target_space_name}")
    draft = session_manager.get_draft(draft_id)
    if not draft:
        return {"error": f"Draft {draft_id} not found."}

    deployer = HFDeployer()
    
    # Logique de détermination de la cible (Toolbox Centralisée vs Nouveau Space)
    
    default_space_env = os.environ.get("DEFAULT_SPACE")
    
    if target_space_name:
        final_space_name = target_space_name
    elif default_space_env:
        final_space_name = default_space_env
        print(f"DEBUG: Using DEFAULT_SPACE env var: {final_space_name}")
        space_target = "existing" 
    else:
        final_space_name = draft.name
        
    # Filtrage des fichiers à déployer
    files_to_deploy = draft.code_files.copy()
    
    # Si on ajoute à un space existant, on n'écrase pas le loader principal (app.py)
    if space_target == "existing":
        #if "app.py" in files_to_deploy:
        #    del files_to_deploy["app.py"]
            
        # Fusion intelligente des requirements
        if "requirements.txt" in files_to_deploy:
            new_reqs = set(files_to_deploy["requirements.txt"].splitlines())
            
            # Reconstruction du repo_id complet si nécessaire
            repo_id_to_fetch = final_space_name
            if "/" not in repo_id_to_fetch:
                 hf_user = os.environ.get("HF_USER")
                 if not hf_user:
                     # Tentative de récupération du user via l'API si non configuré
                     try:
                         user_info = deployer.api.whoami()
                         if user_info and "name" in user_info:
                             hf_user = user_info["name"]
                     except:
                         pass

                 if hf_user:
                     repo_id_to_fetch = f"{hf_user}/{final_space_name}"
            
            import requests
            existing_reqs = set()
            fetch_success = False

            # Méthode 1: Via API HuggingFace (hf_hub_download)
            try:
                print(f"DEBUG: Tentative de récupération des requirements via API sur {repo_id_to_fetch}...")
                cached_path = hf_hub_download(
                    repo_id=repo_id_to_fetch,
                    filename="requirements.txt",
                    repo_type="space",
                    token=deployer.token
                )
                with open(cached_path, 'r') as f:
                    existing_reqs = set(f.read().splitlines())
                fetch_success = True
                print(f"DEBUG: Requirements récupérés via API ({len(existing_reqs)} items).")
            except (EntryNotFoundError, RepositoryNotFoundError):
                print("DEBUG: Pas de requirements.txt via API (404/Not Found).")
            except Exception as e:
                print(f"DEBUG: Erreur API lors de la récupération requirements: {e}")

            # Méthode 2: Via URL directe (Fallback "Raw")
            # Utile si l'API échoue ou si le cache local est incohérent
            if not fetch_success and "/" in repo_id_to_fetch:
                try:
                    raw_url = f"https://huggingface.co/spaces/{repo_id_to_fetch}/resolve/main/requirements.txt"
                    print(f"DEBUG: Tentative de récupération via URL Raw: {raw_url}")
                    headers = {}
                    if deployer.token:
                        headers["Authorization"] = f"Bearer {deployer.token}"
                    
                    resp = requests.get(raw_url, headers=headers)
                    if resp.status_code == 200:
                        existing_reqs = set(resp.text.splitlines())
                        fetch_success = True
                        print(f"DEBUG: Requirements récupérés via URL Raw ({len(existing_reqs)} items).")
                    elif resp.status_code == 404:
                         print("DEBUG: requirements.txt non trouvé via URL Raw (404).")
                    else:
                         print(f"DEBUG: Erreur HTTP {resp.status_code} lors de la récupération via URL Raw.")
                except Exception as e:
                    print(f"DEBUG: Exception lors de la récupération via URL Raw: {e}")

            # Fusion finale
            if fetch_success or existing_reqs:
                merged_reqs = existing_reqs.union(new_reqs)
                # Nettoyage
                cleaned_reqs = sorted([r.strip() for r in merged_reqs if r.strip()])
                files_to_deploy["requirements.txt"] = "\n".join(cleaned_reqs)
                print(f"DEBUG: Fusion terminée. Total requirements: {len(cleaned_reqs)}")
            else:
                print("DEBUG: Aucun requirements existant trouvé, déploiement des nouveaux uniquement.")
            
    try:
        url = deployer.deploy_space(
            space_name=final_space_name,
            files=files_to_deploy,
            sdk="gradio",
            private=(visibility == "private")
        )
        
        mode_msg = "added to toolbox" if space_target == "existing" else "deployed (new space)"
        
        # Standard MCP URL for Gradio
        mcp_endpoint = url.rstrip("/") + "/gradio_api/mcp/"
        
        # Nom du serveur pour la config Claude (nom du Space sans le username)
        # Ex: alihmaou/mymcpserver -> mymcpserver
        if "/" in final_space_name:
             server_name = final_space_name.split("/")[-1]
        else:
             server_name = final_space_name

        # Configuration pour Claude Desktop utilisant mcp-remote (via npx)
        claude_config = f"""
        {{
          "mcpServers": {{
            "{server_name}": {{
              "command": "npx",
              "args": [
                "mcp-remote",
                "{mcp_endpoint}",
                "--transport",
                "streamable-http"
              ]
            }}
          }}
        }}
        """
        
        return {
            "status": "success",
            "url": url,
            "instructions": f"Tool '{draft.name}' {mode_msg} !",
            "claude_config": claude_config
        }
    except Exception as e:
        return {"error": f"Deployment error: {str(e)}"}

def delete_tool(space_name: str, tool_name: str) -> Dict[str, Any]:
    """
    Deletes a tool from an existing Space.
    Args:
        space_name: Full Space name (e.g. user/space) or short name (if HF_USER configured).
        tool_name: Tool name (e.g. strawberry_counter).
    """
    deployer = HFDeployer()
    api = HfApi(token=deployer.token)
    
    # Repo name resolution
    repo_id = space_name
    if "/" not in repo_id:
        hf_user = os.environ.get("HF_USER")
        if hf_user:
            repo_id = f"{hf_user}/{space_name}"
            
    file_path = f"tools/{tool_name}.py"
    
    try:
        print(f"DEBUG [delete_tool]: Deleting {file_path} from {repo_id}")
        api.delete_file(
            path_in_repo=file_path,
            repo_id=repo_id,
            repo_type="space",
            commit_message=f"Delete tool {tool_name} via Meta-MCP"
        )
        return {"status": "success", "message": f"Tool '{tool_name}' deleted from '{repo_id}'."}
    except Exception as e:
        print(f"DEBUG [delete_tool]: Error: {e}")
        return {"error": f"Error during deletion: {str(e)}"}

def get_tool_code(space_name: str, tool_name: str) -> Dict[str, Any]:
    """
    Retrieves the source code of an existing tool.
    Args:
        space_name: Full Space name (e.g. user/space).
        tool_name: Tool name.
    """
    deployer = HFDeployer()
    
    repo_id = space_name
    if "/" not in repo_id:
        hf_user = os.environ.get("HF_USER")
        if hf_user:
            repo_id = f"{hf_user}/{space_name}"
            
    filename = f"tools/{tool_name}.py"
    
    try:
        print(f"DEBUG [get_tool_code]: Fetching {filename} from {repo_id}")
        path = hf_hub_download(
            repo_id=repo_id,
            filename=filename,
            repo_type="space",
            token=deployer.token
        )
        with open(path, "r") as f:
            code = f.read()
            
        return {"status": "success", "code": code}
    except Exception as e:
        print(f"DEBUG [get_tool_code]: Error: {e}")
        return {"error": f"Error reading code: {str(e)}"}