Funcionando la lectura de los grupos de scripts
This commit is contained in:
parent
dbf4d9d685
commit
372e5c087e
Binary file not shown.
|
@ -3,8 +3,8 @@ import os
|
|||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Add the backend directory to Python path
|
||||
backend_dir = Path(__file__).parent
|
||||
# Add the parent directory to Python path
|
||||
backend_dir = Path(__file__).parent.parent # Sube un nivel más para incluir la carpeta raíz
|
||||
if str(backend_dir) not in sys.path:
|
||||
sys.path.append(str(backend_dir))
|
||||
|
||||
|
@ -56,11 +56,14 @@ def create_profile():
|
|||
@app.route('/api/profiles/<profile_id>', methods=['PUT'])
|
||||
def update_profile(profile_id):
|
||||
"""Update existing profile"""
|
||||
profile_data = request.json
|
||||
try:
|
||||
profile_data = request.json
|
||||
print(f"Received update request for profile {profile_id}: {profile_data}") # Debug
|
||||
profile = profile_manager.update_profile(profile_id, profile_data)
|
||||
print(f"Profile updated: {profile}") # Debug
|
||||
return jsonify(profile)
|
||||
except Exception as e:
|
||||
print(f"Error updating profile: {e}") # Debug
|
||||
return jsonify({"error": str(e)}), 400
|
||||
|
||||
@app.route('/api/profiles/<profile_id>', methods=['DELETE'])
|
||||
|
@ -72,11 +75,33 @@ def delete_profile(profile_id):
|
|||
except Exception as e:
|
||||
return jsonify({"error": str(e)}), 400
|
||||
|
||||
@app.route('/api/script-groups', methods=['GET'])
|
||||
def get_script_groups():
|
||||
"""Get all available script groups"""
|
||||
try:
|
||||
groups = script_manager.get_available_groups()
|
||||
return jsonify(groups)
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
@app.route('/api/script-groups/<group_id>/scripts', methods=['GET'])
|
||||
def get_group_scripts(group_id):
|
||||
"""Get scripts for a specific group"""
|
||||
try:
|
||||
scripts = script_manager.get_group_scripts(group_id)
|
||||
return jsonify(scripts)
|
||||
except ValueError as e:
|
||||
return jsonify({"error": str(e)}), 404
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
# Directory handling endpoints
|
||||
@app.route('/api/select-directory', methods=['GET'])
|
||||
def handle_select_directory():
|
||||
"""Handle directory selection"""
|
||||
print("Handling directory selection request") # Debug
|
||||
result = select_directory()
|
||||
print(f"Directory selection result: {result}") # Debug
|
||||
if "error" in result:
|
||||
return jsonify(result), 400
|
||||
return jsonify(result)
|
||||
|
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -13,12 +13,17 @@ def select_directory():
|
|||
root.withdraw() # Hide the main window
|
||||
|
||||
try:
|
||||
print("Opening directory dialog...") # Debug
|
||||
directory = filedialog.askdirectory(
|
||||
title="Select Work Directory",
|
||||
initialdir=os.path.expanduser("~")
|
||||
)
|
||||
return {"path": directory} if directory else {"error": "No directory selected"}
|
||||
print(f"Selected directory: {directory}") # Debug
|
||||
result = {"path": directory} if directory else {"error": "No directory selected"}
|
||||
print(f"Returning result: {result}") # Debug
|
||||
return result
|
||||
except Exception as e:
|
||||
print(f"Error in select_directory: {str(e)}") # Debug
|
||||
return {"error": str(e)}
|
||||
finally:
|
||||
root.destroy()
|
|
@ -58,8 +58,14 @@ class ProfileManager:
|
|||
"""Save profiles to file"""
|
||||
if profiles is None:
|
||||
profiles = self.profiles
|
||||
with open(self.profiles_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(profiles, f, indent=4)
|
||||
try:
|
||||
print(f"Saving profiles to: {self.profiles_file}") # Agregar debug
|
||||
with open(self.profiles_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(profiles, f, indent=4)
|
||||
print("Profiles saved successfully") # Agregar debug
|
||||
except Exception as e:
|
||||
print(f"Error saving profiles: {e}") # Agregar debug
|
||||
raise # Re-lanzar la excepción para que se maneje arriba
|
||||
|
||||
def get_all_profiles(self) -> List[Dict[str, Any]]:
|
||||
"""Get all profiles"""
|
||||
|
@ -94,19 +100,28 @@ class ProfileManager:
|
|||
|
||||
def update_profile(self, profile_id: str, profile_data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Update existing profile"""
|
||||
if profile_id not in self.profiles:
|
||||
raise ValueError(f"Profile {profile_id} not found")
|
||||
try:
|
||||
print(f"Updating profile {profile_id} with data: {profile_data}")
|
||||
if profile_id not in self.profiles:
|
||||
raise ValueError(f"Profile {profile_id} not found")
|
||||
|
||||
if profile_id == "default" and "id" in profile_data:
|
||||
raise ValueError("Cannot change id of default profile")
|
||||
|
||||
if profile_id == "default" and "id" in profile_data:
|
||||
raise ValueError("Cannot change id of default profile")
|
||||
|
||||
# Update timestamp
|
||||
profile_data["updated_at"] = datetime.now().isoformat()
|
||||
|
||||
# Update profile
|
||||
self.profiles[profile_id].update(profile_data)
|
||||
self._save_profiles()
|
||||
return self.profiles[profile_id]
|
||||
# Update timestamp
|
||||
profile_data["updated_at"] = datetime.now().isoformat()
|
||||
|
||||
# Update profile
|
||||
current_profile = self.profiles[profile_id].copy() # Hacer una copia
|
||||
current_profile.update(profile_data) # Actualizar la copia
|
||||
self.profiles[profile_id] = current_profile # Asignar la copia actualizada
|
||||
|
||||
print(f"Updated profile: {self.profiles[profile_id]}")
|
||||
self._save_profiles()
|
||||
return self.profiles[profile_id]
|
||||
except Exception as e:
|
||||
print(f"Error in update_profile: {e}") # Agregar debug
|
||||
raise
|
||||
|
||||
def delete_profile(self, profile_id: str):
|
||||
"""Delete profile"""
|
||||
|
|
|
@ -6,6 +6,34 @@ from typing import Dict, List, Any, Optional
|
|||
import json
|
||||
|
||||
class ScriptManager:
|
||||
def get_available_groups(self) -> List[Dict[str, Any]]:
|
||||
"""Get list of available script groups"""
|
||||
groups = []
|
||||
|
||||
for group_dir in self.script_groups_dir.iterdir():
|
||||
if group_dir.is_dir() and not group_dir.name.startswith('_'):
|
||||
groups.append({
|
||||
"id": group_dir.name,
|
||||
"name": group_dir.name.replace('_', ' ').title(),
|
||||
"path": str(group_dir)
|
||||
})
|
||||
|
||||
return groups
|
||||
|
||||
def get_group_scripts(self, group_id: str) -> List[Dict[str, Any]]:
|
||||
"""Get scripts for a specific group"""
|
||||
group_dir = self.script_groups_dir / group_id
|
||||
|
||||
if not group_dir.exists() or not group_dir.is_dir():
|
||||
raise ValueError(f"Script group '{group_id}' not found")
|
||||
|
||||
scripts = []
|
||||
for script_file in group_dir.glob('x[0-9].py'):
|
||||
script_info = self._analyze_script(script_file)
|
||||
if script_info:
|
||||
scripts.append(script_info)
|
||||
|
||||
return sorted(scripts, key=lambda x: x['id'])
|
||||
"""Manages script discovery and execution"""
|
||||
|
||||
def __init__(self, script_groups_dir: Path):
|
||||
|
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -1,5 +1,5 @@
|
|||
# backend/script_groups/example_group/x1.py
|
||||
from ..base_script import BaseScript
|
||||
from backend.script_groups.base_script import BaseScript
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
# backend/script_groups/example_group/x2.py
|
||||
from ..base_script import BaseScript
|
||||
from backend.script_groups.base_script import BaseScript
|
||||
import psutil
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
|
|
@ -14,13 +14,13 @@
|
|||
"1": {
|
||||
"id": "1",
|
||||
"name": "Base",
|
||||
"work_dir": "D:/Proyectos/AutoCAD",
|
||||
"work_dir": "C:/Estudio",
|
||||
"llm_settings": {
|
||||
"api_key": "333333333333",
|
||||
"model": "gpt-4",
|
||||
"temperature": 0.7
|
||||
},
|
||||
"created_at": "2025-02-07T13:00:43.541932",
|
||||
"updated_at": "2025-02-07T13:01:40.473406"
|
||||
"updated_at": "2025-02-07T23:34:43.039269"
|
||||
}
|
||||
}
|
|
@ -160,4 +160,33 @@
|
|||
margin-top: 0.5rem;
|
||||
white-space: pre-wrap;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
/* frontend/static/css/style.css */
|
||||
|
||||
.script-group-selector {
|
||||
margin-bottom: 20px;
|
||||
padding: 1rem;
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
.script-group-selector label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.script-group-selector select {
|
||||
width: 100%;
|
||||
padding: 0.5rem;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 4px;
|
||||
background: white;
|
||||
}
|
||||
|
||||
#scriptList {
|
||||
display: none;
|
||||
margin-top: 1rem;
|
||||
}
|
|
@ -93,19 +93,26 @@ function updateWorkDirDisplay() {
|
|||
|
||||
async function selectWorkDir() {
|
||||
try {
|
||||
console.log('Requesting directory selection...'); // Debug
|
||||
const response = await apiRequest('/select-directory');
|
||||
console.log('Directory selection response:', response); // Debug
|
||||
|
||||
if (response.path) {
|
||||
await apiRequest(`/profiles/${currentProfile.id}`, {
|
||||
console.log('Updating profile with new work_dir:', response.path); // Debug
|
||||
const updateResponse = await apiRequest(`/profiles/${currentProfile.id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
...currentProfile,
|
||||
work_dir: response.path
|
||||
})
|
||||
});
|
||||
console.log('Profile update response:', updateResponse); // Debug
|
||||
|
||||
await selectProfile(currentProfile.id);
|
||||
showSuccess('Work directory updated successfully');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error in selectWorkDir:', error); // Debug
|
||||
showError('Failed to update work directory');
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,16 +8,60 @@ document.addEventListener('DOMContentLoaded', async () => {
|
|||
await loadScriptGroups();
|
||||
});
|
||||
|
||||
// Load script groups from API
|
||||
// Load script groups when page loads
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
await loadScriptGroups();
|
||||
});
|
||||
|
||||
// Load available script groups
|
||||
async function loadScriptGroups() {
|
||||
try {
|
||||
scriptGroups = await apiRequest('/scripts');
|
||||
updateScriptGroupsDisplay();
|
||||
const groups = await apiRequest('/script-groups');
|
||||
const select = document.getElementById('groupSelect');
|
||||
|
||||
select.innerHTML = `
|
||||
<option value="">Select a group...</option>
|
||||
${groups.map(group => `
|
||||
<option value="${group.id}">${group.name}</option>
|
||||
`).join('')}
|
||||
`;
|
||||
} catch (error) {
|
||||
showError('Failed to load script groups');
|
||||
}
|
||||
}
|
||||
|
||||
// Load scripts for selected group
|
||||
async function loadGroupScripts(groupId) {
|
||||
const scriptList = document.getElementById('scriptList');
|
||||
|
||||
if (!groupId) {
|
||||
scriptList.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const scripts = await apiRequest(`/script-groups/${groupId}/scripts`);
|
||||
|
||||
scriptList.innerHTML = scripts.map(script => `
|
||||
<div class="script-item">
|
||||
<div class="script-info">
|
||||
<h4>${script.name}</h4>
|
||||
<p>${script.description || 'No description available'}</p>
|
||||
</div>
|
||||
<div class="script-actions">
|
||||
<button onclick="runScript('${groupId}', '${script.id}')" class="run-btn">
|
||||
Run
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
scriptList.style.display = 'block';
|
||||
} catch (error) {
|
||||
showError('Failed to load scripts for group');
|
||||
}
|
||||
}
|
||||
|
||||
// Update script groups display
|
||||
function updateScriptGroupsDisplay() {
|
||||
const container = document.getElementById('scriptGroups');
|
||||
|
|
|
@ -32,9 +32,16 @@
|
|||
</div>
|
||||
|
||||
<div class="scripts-section">
|
||||
<h2>Available Scripts</h2>
|
||||
<div id="scriptGroups" class="script-groups">
|
||||
<!-- Script groups will be loaded here -->
|
||||
<h2>Scripts</h2>
|
||||
<div class="script-group-selector">
|
||||
<label for="groupSelect">Select Script Group:</label>
|
||||
<select id="groupSelect" onchange="loadGroupScripts(this.value)">
|
||||
<option value="">Select a group...</option>
|
||||
<!-- Groups will be loaded here -->
|
||||
</select>
|
||||
</div>
|
||||
<div id="scriptList" class="script-list" style="display: none;">
|
||||
<!-- Scripts will be loaded here after group selection -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
Loading…
Reference in New Issue