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
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
# Add the backend directory to Python path
|
# Add the parent directory to Python path
|
||||||
backend_dir = Path(__file__).parent
|
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:
|
if str(backend_dir) not in sys.path:
|
||||||
sys.path.append(str(backend_dir))
|
sys.path.append(str(backend_dir))
|
||||||
|
|
||||||
|
@ -56,11 +56,14 @@ def create_profile():
|
||||||
@app.route('/api/profiles/<profile_id>', methods=['PUT'])
|
@app.route('/api/profiles/<profile_id>', methods=['PUT'])
|
||||||
def update_profile(profile_id):
|
def update_profile(profile_id):
|
||||||
"""Update existing profile"""
|
"""Update existing profile"""
|
||||||
profile_data = request.json
|
|
||||||
try:
|
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)
|
profile = profile_manager.update_profile(profile_id, profile_data)
|
||||||
|
print(f"Profile updated: {profile}") # Debug
|
||||||
return jsonify(profile)
|
return jsonify(profile)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
print(f"Error updating profile: {e}") # Debug
|
||||||
return jsonify({"error": str(e)}), 400
|
return jsonify({"error": str(e)}), 400
|
||||||
|
|
||||||
@app.route('/api/profiles/<profile_id>', methods=['DELETE'])
|
@app.route('/api/profiles/<profile_id>', methods=['DELETE'])
|
||||||
|
@ -72,11 +75,33 @@ def delete_profile(profile_id):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify({"error": str(e)}), 400
|
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
|
# Directory handling endpoints
|
||||||
@app.route('/api/select-directory', methods=['GET'])
|
@app.route('/api/select-directory', methods=['GET'])
|
||||||
def handle_select_directory():
|
def handle_select_directory():
|
||||||
"""Handle directory selection"""
|
"""Handle directory selection"""
|
||||||
|
print("Handling directory selection request") # Debug
|
||||||
result = select_directory()
|
result = select_directory()
|
||||||
|
print(f"Directory selection result: {result}") # Debug
|
||||||
if "error" in result:
|
if "error" in result:
|
||||||
return jsonify(result), 400
|
return jsonify(result), 400
|
||||||
return jsonify(result)
|
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
|
root.withdraw() # Hide the main window
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
print("Opening directory dialog...") # Debug
|
||||||
directory = filedialog.askdirectory(
|
directory = filedialog.askdirectory(
|
||||||
title="Select Work Directory",
|
title="Select Work Directory",
|
||||||
initialdir=os.path.expanduser("~")
|
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:
|
except Exception as e:
|
||||||
|
print(f"Error in select_directory: {str(e)}") # Debug
|
||||||
return {"error": str(e)}
|
return {"error": str(e)}
|
||||||
finally:
|
finally:
|
||||||
root.destroy()
|
root.destroy()
|
|
@ -58,8 +58,14 @@ class ProfileManager:
|
||||||
"""Save profiles to file"""
|
"""Save profiles to file"""
|
||||||
if profiles is None:
|
if profiles is None:
|
||||||
profiles = self.profiles
|
profiles = self.profiles
|
||||||
with open(self.profiles_file, 'w', encoding='utf-8') as f:
|
try:
|
||||||
json.dump(profiles, f, indent=4)
|
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]]:
|
def get_all_profiles(self) -> List[Dict[str, Any]]:
|
||||||
"""Get all profiles"""
|
"""Get all profiles"""
|
||||||
|
@ -94,19 +100,28 @@ class ProfileManager:
|
||||||
|
|
||||||
def update_profile(self, profile_id: str, profile_data: Dict[str, Any]) -> Dict[str, Any]:
|
def update_profile(self, profile_id: str, profile_data: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
"""Update existing profile"""
|
"""Update existing profile"""
|
||||||
if profile_id not in self.profiles:
|
try:
|
||||||
raise ValueError(f"Profile {profile_id} not found")
|
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:
|
# Update timestamp
|
||||||
raise ValueError("Cannot change id of default profile")
|
profile_data["updated_at"] = datetime.now().isoformat()
|
||||||
|
|
||||||
# Update timestamp
|
# Update profile
|
||||||
profile_data["updated_at"] = datetime.now().isoformat()
|
current_profile = self.profiles[profile_id].copy() # Hacer una copia
|
||||||
|
current_profile.update(profile_data) # Actualizar la copia
|
||||||
# Update profile
|
self.profiles[profile_id] = current_profile # Asignar la copia actualizada
|
||||||
self.profiles[profile_id].update(profile_data)
|
|
||||||
self._save_profiles()
|
print(f"Updated profile: {self.profiles[profile_id]}")
|
||||||
return 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):
|
def delete_profile(self, profile_id: str):
|
||||||
"""Delete profile"""
|
"""Delete profile"""
|
||||||
|
|
|
@ -6,6 +6,34 @@ from typing import Dict, List, Any, Optional
|
||||||
import json
|
import json
|
||||||
|
|
||||||
class ScriptManager:
|
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"""
|
"""Manages script discovery and execution"""
|
||||||
|
|
||||||
def __init__(self, script_groups_dir: Path):
|
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
|
# backend/script_groups/example_group/x1.py
|
||||||
from ..base_script import BaseScript
|
from backend.script_groups.base_script import BaseScript
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
# backend/script_groups/example_group/x2.py
|
# backend/script_groups/example_group/x2.py
|
||||||
from ..base_script import BaseScript
|
from backend.script_groups.base_script import BaseScript
|
||||||
import psutil
|
import psutil
|
||||||
import json
|
import json
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
|
@ -14,13 +14,13 @@
|
||||||
"1": {
|
"1": {
|
||||||
"id": "1",
|
"id": "1",
|
||||||
"name": "Base",
|
"name": "Base",
|
||||||
"work_dir": "D:/Proyectos/AutoCAD",
|
"work_dir": "C:/Estudio",
|
||||||
"llm_settings": {
|
"llm_settings": {
|
||||||
"api_key": "333333333333",
|
"api_key": "333333333333",
|
||||||
"model": "gpt-4",
|
"model": "gpt-4",
|
||||||
"temperature": 0.7
|
"temperature": 0.7
|
||||||
},
|
},
|
||||||
"created_at": "2025-02-07T13:00:43.541932",
|
"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;
|
margin-top: 0.5rem;
|
||||||
white-space: pre-wrap;
|
white-space: pre-wrap;
|
||||||
font-size: 0.9rem;
|
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() {
|
async function selectWorkDir() {
|
||||||
try {
|
try {
|
||||||
|
console.log('Requesting directory selection...'); // Debug
|
||||||
const response = await apiRequest('/select-directory');
|
const response = await apiRequest('/select-directory');
|
||||||
|
console.log('Directory selection response:', response); // Debug
|
||||||
|
|
||||||
if (response.path) {
|
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',
|
method: 'PUT',
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
...currentProfile,
|
...currentProfile,
|
||||||
work_dir: response.path
|
work_dir: response.path
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
console.log('Profile update response:', updateResponse); // Debug
|
||||||
|
|
||||||
await selectProfile(currentProfile.id);
|
await selectProfile(currentProfile.id);
|
||||||
showSuccess('Work directory updated successfully');
|
showSuccess('Work directory updated successfully');
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
console.error('Error in selectWorkDir:', error); // Debug
|
||||||
showError('Failed to update work directory');
|
showError('Failed to update work directory');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,16 +8,60 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||||
await loadScriptGroups();
|
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() {
|
async function loadScriptGroups() {
|
||||||
try {
|
try {
|
||||||
scriptGroups = await apiRequest('/scripts');
|
const groups = await apiRequest('/script-groups');
|
||||||
updateScriptGroupsDisplay();
|
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) {
|
} catch (error) {
|
||||||
showError('Failed to load script groups');
|
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
|
// Update script groups display
|
||||||
function updateScriptGroupsDisplay() {
|
function updateScriptGroupsDisplay() {
|
||||||
const container = document.getElementById('scriptGroups');
|
const container = document.getElementById('scriptGroups');
|
||||||
|
|
|
@ -32,9 +32,16 @@
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="scripts-section">
|
<div class="scripts-section">
|
||||||
<h2>Available Scripts</h2>
|
<h2>Scripts</h2>
|
||||||
<div id="scriptGroups" class="script-groups">
|
<div class="script-group-selector">
|
||||||
<!-- Script groups will be loaded here -->
|
<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>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue