Upload 5 files
Browse filesFiles changed (5)
- DockerfileAdded+36
- app/main.pyAdded+490
- app/static/app.jsAdded+559
- app/static/index.htmlAdded+172
- app/static/style.cssAdded+892
123456789101112131415161718192021222324252627282930313233343536FROM python:3.10-slim
# Set environment variablesENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ PORT=7860
# Create a non-root user with UID 1000 to comply with Hugging Face Spaces requirementsRUN useradd -m -u 1000 user
# Set up working directoryWORKDIR /home/user/app
# Install basic system dependenciesRUN apt-get update && apt-get install -y --no-install-recommends \ curl \ git \ && rm -rf /var/lib/apt/lists/*
# Install python dependencies directlyRUN pip install --no-cache-dir fastapi uvicorn requests huggingface_hub python-multipart
# Copy the rest of the application files and set ownership to 'user'COPY --chown=user:user . .
# Create local data directory and set permissionsRUN mkdir -p /home/user/app/data && chown -R user:user /home/user/app/data
# Switch to the non-root userUSER user
# Expose port 7860 (Hugging Face Spaces default)EXPOSE 7860
# Command to run the application using uvicornCMD ["python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490import osimport sysimport jsonimport uuidimport shutilimport subprocessimport threadingfrom typing import Dict, List, Optionalfrom datetime import datetime
from fastapi import FastAPI, HTTPException, BackgroundTasksfrom fastapi.responses import FileResponse, JSONResponsefrom fastapi.staticfiles import StaticFilesfrom pydantic import BaseModel
# ----------------------------------------------------# 1. Environment & Folder Configurations# ----------------------------------------------------# Check if /data is writable (Hugging Face Spaces persistent storage)if os.path.exists("/data") and os.access("/data", os.W_OK): DATA_DIR = "/data"else: # Use data folder in local workspace root current_dir = os.path.dirname(os.path.abspath(__file__)) workspace_root = os.path.dirname(current_dir) DATA_DIR = os.path.join(workspace_root, "data")
os.makedirs(DATA_DIR, exist_ok=True)
# ----------------------------------------------------# 2. Thread-Safe Task Manager Definition# ----------------------------------------------------class TaskManager: def __init__(self, data_root: str): self.data_root = data_root self.tasks_file = os.path.join(data_root, "tasks.json") self.logs_dir = os.path.join(data_root, "logs") self.temp_dir = os.path.join(data_root, "temp_scripts") # Ensure directories exist os.makedirs(self.data_root, exist_ok=True) os.makedirs(self.logs_dir, exist_ok=True) os.makedirs(self.temp_dir, exist_ok=True) self.lock = threading.Lock() self.tasks: Dict[str, dict] = {} self.active_processes: Dict[str, subprocess.Popen] = {} self._load_tasks() self._reset_stale_tasks()
def _load_tasks(self): with self.lock: if os.path.exists(self.tasks_file): try: with open(self.tasks_file, 'r', encoding='utf-8') as f: self.tasks = json.load(f) except Exception as e: print(f"Error loading tasks: {e}", file=sys.stderr) self.tasks = {} else: self.tasks = {}
def _save_tasks(self): with self.lock: try: with open(self.tasks_file, 'w', encoding='utf-8') as f: json.dump(self.tasks, f, indent=2, ensure_ascii=False) except Exception as e: print(f"Error saving tasks: {e}", file=sys.stderr)
def _reset_stale_tasks(self): updated = False for task_id, task in self.tasks.items(): if task.get("status") in ["running", "pending"]: task["status"] = "failed" task["error_message"] = "Server restarted or task interrupted." task["updated_at"] = datetime.now().isoformat() updated = True if updated: self._save_tasks()
def get_all_tasks(self) -> List[dict]: with self.lock: task_list = list(self.tasks.values()) # Return newer tasks first task_list.sort(key=lambda x: x.get("created_at", ""), reverse=True) return task_list
def get_task(self, task_id: str) -> Optional[dict]: with self.lock: return self.tasks.get(task_id)
def get_task_logs(self, task_id: str) -> str: log_path = os.path.join(self.logs_dir, f"{task_id}.log") if os.path.exists(log_path): try: with open(log_path, 'r', encoding='utf-8', errors='replace') as f: return f.read() except Exception as e: return f"Error reading log: {str(e)}" return "Log file not found."
def cancel_task(self, task_id: str) -> bool: process = None with self.lock: if task_id in self.active_processes: process = self.active_processes[task_id] task = self.tasks.get(task_id) if task and task["status"] in ["running", "pending"]: task["status"] = "cancelled" task["updated_at"] = datetime.now().isoformat() if process: try: process.terminate() try: process.wait(timeout=2) except subprocess.TimeoutExpired: process.kill() return True except Exception as e: print(f"Error terminating process for {task_id}: {e}", file=sys.stderr) return False if task and task["status"] == "cancelled": self._save_tasks() return True return False
def delete_task(self, task_id: str, delete_files: bool = False) -> bool: # Cancel first if running self.cancel_task(task_id) with self.lock: task = self.tasks.pop(task_id, None) if not task: return False self._save_tasks() # Clean up files if requested if delete_files and task: folder_name = task.get("folder_name") if folder_name: folder_path = os.path.join(self.data_root, folder_name) # Prevent path traversal outside data root real_folder_path = os.path.abspath(folder_path) real_data_root = os.path.abspath(self.data_root) if real_folder_path.startswith(real_data_root) and os.path.exists(real_folder_path): try: shutil.rmtree(real_folder_path) except Exception as e: print(f"Error deleting folder {real_folder_path}: {e}", file=sys.stderr) # Delete log log_path = os.path.join(self.logs_dir, f"{task_id}.log") if os.path.exists(log_path): try: os.remove(log_path) except Exception as e: print(f"Error deleting log {log_path}: {e}", file=sys.stderr) return True
def create_task(self, folder_name: str, code: str) -> dict: task_id = str(uuid.uuid4()) # Clean up folder name safe_folder = "".join(c for c in folder_name if c.isalnum() or c in ('-', '_')).strip() if not safe_folder: safe_folder = "downloaded_files" task = { "id": task_id, "folder_name": safe_folder, "code": code, "status": "pending", "progress": 0, "error_message": None, "created_at": datetime.now().isoformat(), "updated_at": datetime.now().isoformat() } with self.lock: self.tasks[task_id] = task self._save_tasks() # Start executing script in a background thread threading.Thread(target=self._run_task, args=(task_id,), daemon=True).start() return task
def _run_task(self, task_id: str): with self.lock: task = self.tasks.get(task_id) if not task or task["status"] == "cancelled": return task["status"] = "running" task["updated_at"] = datetime.now().isoformat() self._save_tasks() folder_name = task["folder_name"] save_dir = os.path.join(self.data_root, folder_name) os.makedirs(save_dir, exist_ok=True) script_path = os.path.join(self.temp_dir, f"{task_id}.py") log_path = os.path.join(self.logs_dir, f"{task_id}.log") # Inject standard helper code at the top of the user's script full_code = f"""# -*- coding: utf-8 -*-import osimport sysimport requestsfrom huggingface_hub import hf_hub_download
SAVE_DIR = {repr(save_dir)}os.makedirs(SAVE_DIR, exist_ok=True)
def report_progress(percent): print(f"__PROGRESS__:{{percent}}", flush=True)
def download_file(url, filename=None): if not filename: filename = url.split("/")[-1].split("?")[0] if not filename: filename = "file" filepath = os.path.join(SAVE_DIR, filename) print(f"Downloading {{url}} to {{filepath}}...", flush=True) response = requests.get(url, stream=True) response.raise_for_status() total_size = int(response.headers.get('content-length', 0)) block_size = 1024 * 1024 # 1MB chunks downloaded = 0 with open(filepath, 'wb') as f: for block in response.iter_content(block_size): if block: f.write(block) downloaded += len(block) if total_size > 0: percent = int((downloaded / total_size) * 100) report_progress(percent) print(f"Download complete: {{filepath}}", flush=True) report_progress(100) return filepath
# --- User Code Starts Here ---{task["code"]}# --- User Code Ends Here ---""" # Write user code to temporary file try: with open(script_path, 'w', encoding='utf-8') as f: f.write(full_code) except Exception as e: with self.lock: task = self.tasks.get(task_id) if task: task["status"] = "failed" task["error_message"] = f"Failed to initialize script file: {str(e)}" task["updated_at"] = datetime.now().isoformat() self._save_tasks() return
# Open log file log_file = None try: log_file = open(log_path, 'w', encoding='utf-8') log_file.write(f"=== Task {task_id} Started at {datetime.now().isoformat()} ===\n") log_file.write(f"Saving to: {save_dir}\n\n") log_file.flush() except Exception as e: print(f"Could not open log file: {e}", file=sys.stderr) try: env = os.environ.copy() env["SAVE_DIR"] = save_dir env["PYTHONUNBUFFERED"] = "1" # Start process process = subprocess.Popen( [sys.executable, script_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, env=env ) with self.lock: if self.tasks.get(task_id, {}).get("status") == "cancelled": process.terminate() if log_file: log_file.write("Task cancelled immediately.\n") return self.active_processes[task_id] = process # Read process logs and extract progress while True: line = process.stdout.readline() if not line: break if line.startswith("__PROGRESS__:"): try: percent = int(line.split(":", 1)[1].strip()) with self.lock: if task_id in self.tasks and self.tasks[task_id]["status"] == "running": self.tasks[task_id]["progress"] = percent self.tasks[task_id]["updated_at"] = datetime.now().isoformat() self._save_tasks() except ValueError: pass else: if log_file: log_file.write(line) log_file.flush() # Wait for exit code return_code = process.wait() with self.lock: self.active_processes.pop(task_id, None) task = self.tasks.get(task_id) if task and task["status"] == "running": if return_code == 0: task["status"] = "completed" task["progress"] = 100 else: task["status"] = "failed" task["error_message"] = f"Script exited with error code {return_code}" task["updated_at"] = datetime.now().isoformat() if log_file: log_file.write(f"\n=== Task Finished with code {return_code} ===\n") except Exception as e: with self.lock: self.active_processes.pop(task_id, None) task = self.tasks.get(task_id) if task and task["status"] in ["running", "pending"]: task["status"] = "failed" task["error_message"] = str(e) task["updated_at"] = datetime.now().isoformat() if log_file: log_file.write(f"\n=== Execution Failed: {str(e)} ===\n") finally: if log_file: log_file.close() self._save_tasks() # Clean up temporary file if os.path.exists(script_path): try: os.remove(script_path) except Exception: pass
# Initialize TaskManager instancemanager = TaskManager(DATA_DIR)
# ----------------------------------------------------# 3. FastAPI Web Application Configuration# ----------------------------------------------------app = FastAPI(title="Hugging Face Spaces Downloader Portal")
# API Modelsclass TaskCreateRequest(BaseModel): folder_name: str code: str
# API Routes@app.get("/api/tasks")def list_tasks(): return manager.get_all_tasks()
@app.post("/api/tasks")def create_task(req: TaskCreateRequest): if not req.folder_name.strip(): raise HTTPException(status_code=400, detail="Folder name is required") if not req.code.strip(): raise HTTPException(status_code=400, detail="Python script content is required") task = manager.create_task(req.folder_name, req.code) return task
@app.get("/api/tasks/{task_id}/logs")def get_task_logs(task_id: str): task = manager.get_task(task_id) if not task: raise HTTPException(status_code=404, detail="Task not found") logs = manager.get_task_logs(task_id) return {"logs": logs}
@app.post("/api/tasks/{task_id}/cancel")def cancel_task(task_id: str): success = manager.cancel_task(task_id) if not success: raise HTTPException(status_code=400, detail="Failed to cancel task, or it was not running") return {"status": "cancelled"}
@app.delete("/api/tasks/{task_id}")def delete_task(task_id: str, delete_files: bool = False): success = manager.delete_task(task_id, delete_files) if not success: raise HTTPException(status_code=404, detail="Task not found") return {"status": "deleted"}
@app.get("/api/files")def list_files(): # Walk the directory tree to list all files, skipping system metadata files_tree = [] real_data_root = os.path.abspath(DATA_DIR) for root, dirs, files in os.walk(DATA_DIR): rel_root = os.path.relpath(root, DATA_DIR) if rel_root == ".": rel_root = "" parts = rel_root.split(os.sep) if "logs" in parts or "temp_scripts" in parts or (len(parts) > 0 and parts[0] in ["logs", "temp_scripts"]): continue for file in files: if rel_root == "" and file == "tasks.json": continue file_path = os.path.join(root, file) rel_path = os.path.join(rel_root, file).replace("\\", "/") stat = os.stat(file_path) files_tree.append({ "name": file, "path": rel_path, "size": stat.st_size, "modified": datetime.fromtimestamp(stat.st_mtime).isoformat(), "is_dir": False }) return files_tree
@app.get("/api/files/download/{file_path:path}")def download_file(file_path: str): # Prevent directory traversal attacks target_path = os.path.abspath(os.path.join(DATA_DIR, file_path)) real_data_root = os.path.abspath(DATA_DIR) if not target_path.startswith(real_data_root): raise HTTPException(status_code=400, detail="Access denied") if not os.path.exists(target_path) or os.path.isdir(target_path): raise HTTPException(status_code=404, detail="File not found") return FileResponse(target_path, filename=os.path.basename(target_path))
@app.delete("/api/files/{file_path:path}")def delete_file(file_path: str): target_path = os.path.abspath(os.path.join(DATA_DIR, file_path)) real_data_root = os.path.abspath(DATA_DIR) if not target_path.startswith(real_data_root): raise HTTPException(status_code=400, detail="Access denied") # Prevent deleting critical directories parts = file_path.split("/") if parts[0] in ["logs", "temp_scripts", "tasks.json"] or not file_path: raise HTTPException(status_code=400, detail="Cannot delete system folders or metadata") if not os.path.exists(target_path): raise HTTPException(status_code=404, detail="File or folder not found") try: if os.path.isdir(target_path): shutil.rmtree(target_path) else: os.remove(target_path) return {"status": "success"} except Exception as e: raise HTTPException(status_code=500, detail=str(e))
# Mount Frontend static filesstatic_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")if os.path.exists(static_dir): app.mount("/", StaticFiles(directory=static_dir, html=True), name="static")else: # Dynamic fallback in case it starts before folders are written @app.get("/") def index_fallback(): return JSONResponse({"status": "running", "msg": "Static files directory is being configured. Please refresh in a moment."})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559// Global state variableslet tasks = [];let files = [];let activeLogTaskId = null;let logPollInterval = null;let generalPollInterval = null;
// Code Templates Definitionconst templates = { url: `# 单文件 URL 下载模板# 内置了 download_file(url, filename=None) 辅助函数# 它会自动以流式块方式下载文件并上报进度条进度
url = "https://raw.githubusercontent.com/huggingface/hub-docs/main/assets/hf-logo.png"download_file(url, "huggingface-logo.png")`, hf: `# Hugging Face Hub 模型/文件下载模板# 可以使用 huggingface_hub 库直接下载 Hugging Face Spaces/Models 中的文件# 我们的环境变量已经定义了 SAVE_DIR 指向任务文件夹
from huggingface_hub import hf_hub_download
repo_id = "gpt2"filename = "config.json"
print(f"正在从 Hugging Face 仓库 {repo_id} 下载 {filename} ...")
# 必须指定 local_dir=SAVE_DIRfilepath = hf_hub_download( repo_id=repo_id, filename=filename, local_dir=SAVE_DIR, local_dir_use_symlinks=False)
print(f"文件已下载并保存到: {filepath}")# 完成后可以上报 100% 进度report_progress(100)`, 'multi-url': `# 多 URL 批量并发或循环下载模板import time
urls = [ "https://raw.githubusercontent.com/huggingface/hub-docs/main/assets/hf-logo.png", "https://raw.githubusercontent.com/huggingface/transformers/main/docs/source/en/imgs/transformers_logo.png"]
total = len(urls)for index, url in enumerate(urls): filename = f"logo_{index + 1}.png" print(f"正在下载第 {index + 1}/{total} 个文件...") # 执行下载 download_file(url, filename) # 估算总进度并上报 progress = int(((index + 1) / total) * 100) report_progress(progress) time.sleep(0.5) # 稍微等待`, 'custom-script': `# 自定义脚本逻辑模板 (例如自定义请求或解压文件)import osimport timeimport requests
print("开始执行自定义数据采集流程...")report_progress(10)
# 使用 requests 获取特定内容print("正在请求测试 API 数据...")response = requests.get("https://httpbin.org/json")if response.status_code == 200: data = response.json() print("获取数据成功,正在保存...") # 存储到 SAVE_DIR target_path = os.path.join(SAVE_DIR, "test_api_response.json") with open(target_path, "w", encoding="utf-8") as f: import json json.dump(data, f, indent=4, ensure_ascii=False) print(f"结果已成功写入: {target_path}")else: print(f"API 请求失败: {response.status_code}")
report_progress(60)time.sleep(1)
# 生成一个大的日志print("数据校验中...")report_progress(100)`};
// Initialize Applicationdocument.addEventListener('DOMContentLoaded', () => { // Set default template document.getElementById('code-editor').value = templates.url;
// Event Listeners Setup initEventListeners(); // Initial fetch fetchTasks(); fetchFiles(); fetchSystemStatus();
// Start background poll every 3 seconds for dashboard updates generalPollInterval = setInterval(() => { fetchTasks(); fetchFiles(); }, 3000);});
// Event Listeners Initializationfunction initEventListeners() { // Template dropdown logic const templateBtn = document.getElementById('template-btn'); const templatesDropdown = document.getElementById('templates-dropdown'); templateBtn.addEventListener('click', (e) => { e.stopPropagation(); document.getElementById('templates-list').parentElement.classList.toggle('active'); });
document.addEventListener('click', () => { document.getElementById('templates-list').parentElement.classList.remove('active'); });
document.querySelectorAll('#templates-list a').forEach(item => { item.addEventListener('click', (e) => { e.preventDefault(); const templateKey = item.getAttribute('data-template'); if (templates[templateKey]) { document.getElementById('code-editor').value = templates[templateKey]; } }); });
// Code Editor tab key handling (standard tab indent in textarea) const textarea = document.getElementById('code-editor'); textarea.addEventListener('keydown', function(e) { if (e.key === 'Tab') { e.preventDefault(); const start = this.selectionStart; const end = this.selectionEnd; this.value = this.value.substring(0, start) + " " + this.value.substring(end); this.selectionStart = this.selectionEnd = start + 4; } });
// Submit Task document.getElementById('submit-task-btn').addEventListener('click', submitTask);
// Refresh Buttons document.getElementById('refresh-tasks-btn').addEventListener('click', fetchTasks); document.getElementById('refresh-files-btn').addEventListener('click', fetchFiles);
// Logs modal close document.querySelectorAll('#close-modal-btn, #close-modal-btn-footer').forEach(btn => { btn.addEventListener('click', closeLogsModal); });
// Copy logs document.getElementById('copy-logs-btn').addEventListener('click', copyLogsToClipboard);}
// Fetch Tasks APIasync function fetchTasks() { try { const response = await fetch('/api/tasks'); if (!response.ok) throw new Error("获取任务列表失败"); tasks = await response.json(); renderTasks(); updateActiveTasksBadge(); } catch (error) { console.error("Error fetching tasks:", error); }}
// Fetch Files APIasync function fetchFiles() { try { const response = await fetch('/api/files'); if (!response.ok) throw new Error("获取文件列表失败"); files = await response.json(); renderFiles(); } catch (error) { console.error("Error fetching files:", error); }}
// Fetch System Storage Statusasync function fetchSystemStatus() { const storageBadge = document.getElementById('storage-status'); try { const response = await fetch('/api/files'); if (response.ok) { // Check if we are running in persistent environment // (Just a visual simulation or custom check from location) const isHF = window.location.hostname.includes('hf.space'); storageBadge.querySelector('.badge-text').textContent = isHF ? "Hugging Face Spaces 持久存储 (数据持久)" : "本地开发存储 (data/)"; storageBadge.querySelector('.dot').className = "dot green"; } } catch (error) { storageBadge.querySelector('.badge-text').textContent = "存储连接错误"; storageBadge.querySelector('.dot').className = "dot amber"; }}
// Render Tasks Listfunction renderTasks() { const container = document.getElementById('tasks-list-container'); if (tasks.length === 0) { container.innerHTML = ` <div class="empty-state"> <i class="fa-solid fa-circle-info"></i> <p>暂无下载任务,在左侧创建新任务以开始</p> </div> `; return; }
container.innerHTML = tasks.map(task => { const date = new Date(task.created_at).toLocaleString(); // Progress display const isRunning = task.status === 'running'; const progressVal = task.progress || 0; let actionButtons = ''; if (isRunning || task.status === 'pending') { actionButtons = ` <button class="btn btn-sm btn-danger" onclick="cancelTask('${task.id}')"> <i class="fa-solid fa-ban"></i> 取消任务 </button> `; } else { actionButtons = ` <button class="btn btn-sm btn-secondary" onclick="confirmDeleteTask('${task.id}')"> <i class="fa-solid fa-trash-can"></i> 删除历史 </button> `; }
const errorDiv = task.error_message ? `<div class="task-error"><strong>错误原因:</strong> ${task.error_message}</div>` : '';
return ` <div class="task-item ${task.status}" id="task-${task.id}"> <div class="task-meta"> <div class="task-info-left"> <div class="task-folder"> <i class="fa-regular fa-folder-open"></i> ${task.folder_name} </div> <div class="task-id">ID: ${task.id} | 创建时间: ${date}</div> </div> <span class="status-pill ${task.status}">${translateStatus(task.status)}</span> </div> <div class="task-progress-box"> <div class="progress-info"> <span>进度</span> <span>${progressVal}%</span> </div> <div class="progress-bar-bg"> <div class="progress-bar-fill" style="width: ${progressVal}%"></div> </div> </div>
${errorDiv}
<div class="task-actions"> <button class="btn btn-sm btn-outline" onclick="openLogsModal('${task.id}')"> <i class="fa-solid fa-terminal"></i> 运行日志 </button> ${actionButtons} </div> </div> `; }).join('');}
// Render Files List Tablefunction renderFiles() { const tbody = document.getElementById('files-list-tbody'); if (files.length === 0) { tbody.innerHTML = ` <tr> <td colspan="4" class="table-empty"> <i class="fa-solid fa-folder-open"></i> 暂无已下载的文件 </td> </tr> `; return; }
tbody.innerHTML = files.map(file => { const sizeReadable = formatBytes(file.size); const date = new Date(file.modified).toLocaleString(); return ` <tr> <td> <div class="file-name-cell"> <i class="fa-regular fa-file"></i> <div> <div>${file.name}</div> <span class="file-path">${file.path}</span> </div> </div> </td> <td>${sizeReadable}</td> <td>${date}</td> <td style="text-align: center;"> <div style="display: flex; gap: 8px; justify-content: center;"> <a href="/api/files/download/${encodeURIComponent(file.path)}" class="btn btn-sm btn-outline" style="text-decoration:none;" download> <i class="fa-solid fa-download"></i> </a> <button class="btn btn-sm btn-outline btn-danger" style="padding: 6px 10px;" onclick="deleteFile('${file.path}')" title="删除文件"> <i class="fa-solid fa-trash"></i> </button> </div> </td> </tr> `; }).join('');}
// Helper: Translate backend status stringsfunction translateStatus(status) { switch (status) { case 'pending': return '排队中'; case 'running': return '下载中'; case 'completed': return '已完成'; case 'failed': return '执行失败'; case 'cancelled': return '已取消'; default: return status; }}
// Helper: Format Bytes to human readablefunction formatBytes(bytes, decimals = 2) { if (bytes === 0) return '0 Bytes'; const k = 1024; const dm = decimals < 0 ? 0 : decimals; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];}
// Helper: Update Active Tasks counter in headerfunction updateActiveTasksBadge() { const activeTasks = tasks.filter(t => t.status === 'running' || t.status === 'pending'); document.getElementById('active-tasks-count').querySelector('.badge-number').textContent = activeTasks.length;}
// Submit New Taskasync function submitTask() { const folderInput = document.getElementById('folder-name-input'); const editor = document.getElementById('code-editor'); const folderName = folderInput.value.trim(); const code = editor.value.trim(); if (!folderName) { alert("请输入存储文件夹名称!"); folderInput.focus(); return; } if (!code) { alert("请输入 Python 下载代码!"); editor.focus(); return; } const submitBtn = document.getElementById('submit-task-btn'); submitBtn.disabled = true; submitBtn.innerHTML = `<i class="fa-solid fa-circle-notch fa-spin"></i> 提交任务中...`; try { const response = await fetch('/api/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ folder_name: folderName, code: code }) }); if (!response.ok) { const err = await response.json(); throw new Error(err.detail || "提交下载任务失败"); } // Reset folder inputs and refresh folderInput.value = ''; await fetchTasks(); } catch (error) { alert(error.message); } finally { submitBtn.disabled = false; submitBtn.innerHTML = `<i class="fa-solid fa-play"></i> 开始下载任务`; }}
// Cancel Running Taskasync function cancelTask(taskId) { if (!confirm("确定要取消此下载任务吗?")) return; try { const response = await fetch(`/api/tasks/${taskId}/cancel`, { method: 'POST' }); if (!response.ok) throw new Error("取消任务失败"); fetchTasks(); } catch (error) { alert(error.message); }}
// Delete History Task Entryfunction confirmDeleteTask(taskId) { const container = document.createElement('div'); container.style.cssText = ` position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.6); display: flex; align-items: center; justify-content: center; z-index: 1000; backdrop-filter: blur(5px); `; const dialog = document.createElement('div'); dialog.className = 'card panel'; dialog.style.cssText = ` max-width: 420px; width: 100%; padding: 24px; display: flex; flex-direction: column; gap: 16px; background: #0f1322; border: 1px solid rgba(255,255,255,0.1); `; dialog.innerHTML = ` <h3 style="font-size:1.15rem; font-weight:600;"><i class="fa-solid fa-circle-question" style="color:var(--primary);"></i> 删除确认</h3> <p style="font-size:0.9rem; color:var(--text-secondary);">您想要如何删除此任务历史?</p> <div style="display:flex; flex-direction:column; gap:10px; margin-top: 10px;"> <button class="btn btn-outline" id="del-history-only">仅删除任务历史 (保留下载文件)</button> <button class="btn btn-danger" id="del-all">彻底删除任务及下载的文件</button> <button class="btn btn-secondary" id="del-cancel" style="margin-top: 5px;">取消</button> </div> `; container.appendChild(dialog); document.body.appendChild(container); document.getElementById('del-history-only').addEventListener('click', () => { deleteTask(taskId, false); document.body.removeChild(container); }); document.getElementById('del-all').addEventListener('click', () => { if (confirm("警告: 这将永久删除该文件夹下已下载的所有文件,无法恢复!确认继续?")) { deleteTask(taskId, true); } document.body.removeChild(container); }); document.getElementById('del-cancel').addEventListener('click', () => { document.body.removeChild(container); });}
async function deleteTask(taskId, deleteFiles) { try { const response = await fetch(`/api/tasks/${taskId}?delete_files=${deleteFiles}`, { method: 'DELETE' }); if (!response.ok) throw new Error("删除任务失败"); fetchTasks(); fetchFiles(); } catch (error) { alert(error.message); }}
// Delete File directly from Explorerasync function deleteFile(filePath) { if (!confirm(`确定要彻底删除该文件吗?\n${filePath}`)) return; try { const response = await fetch(`/api/files/${encodeURIComponent(filePath)}`, { method: 'DELETE' }); if (!response.ok) throw new Error("删除文件失败"); fetchFiles(); } catch (error) { alert(error.message); }}
// Open Logs Modalfunction openLogsModal(taskId) { activeLogTaskId = taskId; const modal = document.getElementById('logs-modal'); document.getElementById('modal-task-id').textContent = taskId.substring(0, 8) + '...'; document.getElementById('logs-content').textContent = '正在连接日志流...'; modal.classList.add('active'); // Immediate fetch logs fetchLogs(); // Poll logs every 1 second logPollInterval = setInterval(fetchLogs, 1000);}
// Close Logs Modalfunction closeLogsModal() { const modal = document.getElementById('logs-modal'); modal.classList.remove('active'); if (logPollInterval) { clearInterval(logPollInterval); logPollInterval = null; } activeLogTaskId = null;}
// Fetch Logs APIasync function fetchLogs() { if (!activeLogTaskId) return; try { const response = await fetch(`/api/tasks/${activeLogTaskId}/logs`); if (!response.ok) throw new Error("获取日志失败"); const data = await response.json(); const logsBox = document.getElementById('logs-content'); logsBox.textContent = data.logs || '控制台暂无输出。'; // Handle Auto Scroll const autoScroll = document.getElementById('auto-scroll-logs').checked; if (autoScroll) { const modalBody = document.querySelector('.modal-body'); modalBody.scrollTop = modalBody.scrollHeight; } } catch (error) { console.error("Error fetching logs:", error); }}
// Copy Console Logs to Clipboardfunction copyLogsToClipboard() { const text = document.getElementById('logs-content').textContent; navigator.clipboard.writeText(text).then(() => { alert("日志已成功复制到剪贴板!"); }).catch(err => { console.error("Could not copy logs: ", err); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>HF Space Downloader & Task Manager</title> <!-- Google Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500&family=Outfit:wght@300;400;500;600;700&display=swap" rel="stylesheet"> <!-- FontAwesome for icons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> <!-- Custom Style --> <link rel="stylesheet" href="style.css"></head><body> <div class="background-decor"> <div class="blur-circle circle-1"></div> <div class="blur-circle circle-2"></div> </div>
<div class="app-container"> <!-- Header --> <header class="app-header"> <div class="brand"> <i class="fa-solid fa-cloud-arrow-down brand-icon animate-pulse"></i> <div class="brand-text"> <h1>HF Downloader</h1> <p>Docker Task & Download Manager</p> </div> </div> <div class="system-status"> <div class="status-badge" id="storage-status"> <span class="dot green"></span> <span class="badge-text">初始化中...</span> </div> <div class="status-badge" id="active-tasks-count"> <span class="badge-number">0</span> <span class="badge-text">个运行中的任务</span> </div> </div> </header>
<!-- Main Content Layout --> <main class="app-main-layout"> <!-- Left Panel: Create Task --> <section class="panel card form-panel"> <div class="panel-header"> <h2><i class="fa-solid fa-code"></i> 新建下载任务</h2> <span class="panel-subtitle">编写 Python 代码执行下载逻辑</span> </div> <div class="form-group"> <label for="folder-name-input"> <i class="fa-regular fa-folder-open"></i> 存储文件夹名称 </label> <input type="text" id="folder-name-input" placeholder="例如: my_dataset_v1" autocomplete="off" /> <span class="input-helper">文件将保存在 <code>data/[文件夹名称]/</code> 下</span> </div>
<div class="form-group"> <div class="editor-header"> <label for="code-editor"> <i class="fa-brands fa-python"></i> Python 脚本代码 </label> <div class="templates-dropdown"> <button class="btn btn-sm btn-outline" id="template-btn"> <i class="fa-solid fa-wand-magic-sparkles"></i> 快速模板 <i class="fa-solid fa-chevron-down"></i> </button> <div class="dropdown-content" id="templates-list"> <a href="#" data-template="url"><i class="fa-solid fa-link"></i> 单文件 URL 下载</a> <a href="#" data-template="hf"><i class="fa-solid fa-face-smile"></i> Hugging Face 模型下载</a> <a href="#" data-template="multi-url"><i class="fa-solid fa-list-check"></i> 多 URL 批量下载</a> <a href="#" data-template="custom-script"><i class="fa-solid fa-code"></i> 自定义脚本逻辑</a> </div> </div> </div> <div class="editor-container"> <textarea id="code-editor" spellcheck="false" placeholder="写入您的下载Python代码..."></textarea> </div> <span class="input-helper">支持标准 Python 代码。内置辅助函数 <code>download_file(url, filename=None)</code>,调用会自动报告进度。</span> </div>
<button class="btn btn-primary btn-block" id="submit-task-btn"> <i class="fa-solid fa-play"></i> 开始下载任务 </button> </section>
<!-- Right Panel: Tasks Status --> <section class="panel card tasks-panel"> <div class="panel-header"> <h2><i class="fa-solid fa-list-check"></i> 任务监控大盘</h2> <button class="btn btn-sm btn-icon-only" id="refresh-tasks-btn" title="刷新任务列表"> <i class="fa-solid fa-rotate"></i> </button> </div> <div class="tasks-container" id="tasks-list-container"> <!-- Task items will be dynamically rendered here --> <div class="empty-state"> <i class="fa-solid fa-circle-info"></i> <p>暂无下载任务,在左侧创建新任务以开始</p> </div> </div> </section> </main>
<!-- Lower Section: File Manager --> <section class="panel card files-panel"> <div class="panel-header"> <h2><i class="fa-solid fa-folder-tree"></i> 数据文件管理器 (data/)</h2> <div class="files-actions"> <button class="btn btn-sm btn-outline" id="refresh-files-btn"> <i class="fa-solid fa-arrows-rotate"></i> 刷新文件列表 </button> </div> </div> <div class="files-table-container"> <table class="files-table"> <thead> <tr> <th>文件名 / 相对路径</th> <th>大小</th> <th>修改时间</th> <th style="width: 120px; text-align: center;">操作</th> </tr> </thead> <tbody id="files-list-tbody"> <tr> <td colspan="4" class="table-empty"> <i class="fa-solid fa-folder-open"></i> 暂无已下载的文件 </td> </tr> </tbody> </table> </div> </section> </div>
<!-- Live Console Drawer Modal --> <div class="modal-overlay" id="logs-modal"> <div class="modal-card"> <div class="modal-header"> <div class="modal-title"> <i class="fa-solid fa-terminal"></i> <h3>任务控制台日志 (<span id="modal-task-id"></span>)</h3> </div> <button class="modal-close" id="close-modal-btn">×</button> </div> <div class="modal-body"> <pre class="console-logs" id="logs-content">加载日志中...</pre> </div> <div class="modal-footer"> <div class="log-controls"> <label class="checkbox-container"> <input type="checkbox" id="auto-scroll-logs" checked> <span class="checkmark"></span> 自动滚动 </label> <button class="btn btn-sm btn-outline" id="copy-logs-btn"> <i class="fa-regular fa-copy"></i> 复制日志 </button> </div> <button class="btn btn-sm btn-secondary" id="close-modal-btn-footer">关闭</button> </div> </div> </div>
<!-- Custom Script JS --> <script src="app.js"></script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892/* Design Tokens & CSS Variables */:root { --bg-main: #090d16; --bg-gradient: linear-gradient(135deg, #090d16 0%, #111322 50%, #1a152e 100%); --card-bg: rgba(22, 28, 45, 0.6); --card-border: rgba(255, 255, 255, 0.06); --card-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37); --text-primary: #f8fafc; --text-secondary: #94a3b8; --text-muted: #64748b; --primary: #6366f1; --primary-glow: rgba(99, 102, 241, 0.45); --primary-gradient: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); --success: #10b981; --success-bg: rgba(16, 185, 129, 0.15); --warning: #f59e0b; --warning-bg: rgba(245, 158, 11, 0.15); --danger: #ef4444; --danger-bg: rgba(239, 68, 68, 0.15); --info: #0ea5e9; --info-bg: rgba(14, 165, 233, 0.15); --code-bg: #0b0f19; --border-radius-lg: 16px; --border-radius-md: 10px; --border-radius-sm: 6px; --transition-fast: 0.2s ease; --transition-smooth: 0.3s cubic-bezier(0.4, 0, 0.2, 1);}
/* Base Styles */* { box-sizing: border-box; margin: 0; padding: 0;}
body { font-family: 'Outfit', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background-color: var(--bg-main); background-image: var(--bg-gradient); color: var(--text-primary); min-height: 100vh; position: relative; overflow-x: hidden; line-height: 1.5;}
/* Background Decor */.background-decor { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: -1; overflow: hidden; pointer-events: none;}
.blur-circle { position: absolute; border-radius: 50%; filter: blur(120px); opacity: 0.2;}
.circle-1 { top: -10%; right: 10%; width: 45vw; height: 45vw; background: radial-gradient(circle, var(--primary) 0%, transparent 70%); animation: float-slow 20s infinite alternate;}
.circle-2 { bottom: -10%; left: 5%; width: 40vw; height: 40vw; background: radial-gradient(circle, #8b5cf6 0%, transparent 70%); animation: float-slow 25s infinite alternate-reverse;}
@keyframes float-slow { 0% { transform: translate(0, 0) scale(1); } 100% { transform: translate(3%, 5%) scale(1.1); }}
/* Layout Wrapper */.app-container { max-width: 1300px; margin: 0 auto; padding: 24px 16px; display: flex; flex-direction: column; gap: 24px;}
/* Header */.app-header { display: flex; justify-content: space-between; align-items: center; padding: 16px 24px; background: var(--card-bg); border: 1px solid var(--card-border); border-radius: var(--border-radius-lg); box-shadow: var(--card-shadow); backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);}
.brand { display: flex; align-items: center; gap: 16px;}
.brand-icon { font-size: 2.2rem; background: var(--primary-gradient); -webkit-background-clip: text; -webkit-text-fill-color: transparent; filter: drop-shadow(0 0 10px rgba(99, 102, 241, 0.4));}
.brand-text h1 { font-size: 1.6rem; font-weight: 700; letter-spacing: -0.5px; background: linear-gradient(120deg, #ffffff 40%, #e2e8f0 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent;}
.brand-text p { font-size: 0.85rem; color: var(--text-secondary);}
.system-status { display: flex; gap: 12px;}
.status-badge { display: flex; align-items: center; gap: 8px; background: rgba(15, 23, 42, 0.6); border: 1px solid rgba(255, 255, 255, 0.05); padding: 8px 14px; border-radius: var(--border-radius-md); font-size: 0.85rem; font-weight: 500;}
.status-badge .dot { width: 8px; height: 8px; border-radius: 50%;}
.status-badge .dot.green { background-color: var(--success); box-shadow: 0 0 8px var(--success); animation: pulse 1.8s infinite;}
.status-badge .dot.amber { background-color: var(--warning); box-shadow: 0 0 8px var(--warning); animation: pulse 1.8s infinite;}
.status-badge .badge-number { background: var(--primary-gradient); color: white; width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; border-radius: 50%; font-size: 0.75rem; font-weight: 700;}
/* Animations */@keyframes pulse { 0% { transform: scale(0.95); opacity: 0.8; } 50% { transform: scale(1.1); opacity: 1; box-shadow: 0 0 12px currentColor; } 100% { transform: scale(0.95); opacity: 0.8; }}
.animate-pulse { animation: pulse 3s infinite;}
/* Cards & Panels */.card { background: var(--card-bg); border: 1px solid var(--card-border); border-radius: var(--border-radius-lg); box-shadow: var(--card-shadow); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); transition: var(--transition-smooth);}
.panel { display: flex; flex-direction: column; padding: 24px;}
.panel-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; border-bottom: 1px solid rgba(255, 255, 255, 0.05); padding-bottom: 14px;}
.panel-header h2 { font-size: 1.25rem; font-weight: 600; display: flex; align-items: center; gap: 10px;}
.panel-header h2 i { color: var(--primary);}
.panel-subtitle { font-size: 0.8rem; color: var(--text-muted);}
/* Main Grid Layout */.app-main-layout { display: grid; grid-template-columns: 1.2fr 1fr; gap: 24px;}
@media (max-width: 992px) { .app-main-layout { grid-template-columns: 1fr; }}
/* Forms & Inputs */.form-group { display: flex; flex-direction: column; gap: 8px; margin-bottom: 20px;}
.form-group label { font-size: 0.9rem; font-weight: 500; color: var(--text-secondary); display: flex; align-items: center; gap: 8px;}
.form-group label i { color: var(--primary);}
input[type="text"] { background: rgba(15, 23, 42, 0.8); border: 1px solid rgba(255, 255, 255, 0.1); color: var(--text-primary); padding: 12px 16px; border-radius: var(--border-radius-md); font-family: inherit; font-size: 0.95rem; outline: none; transition: var(--transition-fast);}
input[type="text"]:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.25);}
.input-helper { font-size: 0.8rem; color: var(--text-muted);}
.input-helper code { background: rgba(255, 255, 255, 0.05); padding: 2px 5px; border-radius: var(--border-radius-sm); color: #f43f5e;}
/* Editor Style */.editor-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 2px;}
.editor-container { position: relative; border: 1px solid rgba(255, 255, 255, 0.1); border-radius: var(--border-radius-md); overflow: hidden;}
#code-editor { width: 100%; height: 320px; background: var(--code-bg); color: #e2e8f0; font-family: 'Fira Code', monospace; font-size: 0.85rem; padding: 16px; border: none; resize: vertical; outline: none; line-height: 1.6; tab-size: 4;}
#code-editor:focus { box-shadow: inset 0 0 0 1px var(--primary);}
/* Dropdown styling */.templates-dropdown { position: relative; display: inline-block;}
.dropdown-content { display: none; position: absolute; right: 0; top: calc(100% + 4px); background: #111625; min-width: 220px; box-shadow: 0px 8px 24px rgba(0, 0, 0, 0.5); border: 1px solid rgba(255, 255, 255, 0.08); border-radius: var(--border-radius-md); z-index: 10; overflow: hidden;}
.dropdown-content a { color: var(--text-secondary); padding: 10px 16px; text-decoration: none; display: flex; align-items: center; gap: 10px; font-size: 0.85rem; transition: var(--transition-fast);}
.dropdown-content a:hover { background-color: rgba(99, 102, 241, 0.15); color: white;}
.dropdown-content a i { width: 16px; text-align: center; color: var(--primary);}
.templates-dropdown.active .dropdown-content { display: block; animation: fadeIn 0.15s ease-out;}
@keyframes fadeIn { from { opacity: 0; transform: translateY(-5px); } to { opacity: 1; transform: translateY(0); }}
/* Buttons */.btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; padding: 10px 20px; border-radius: var(--border-radius-md); font-family: inherit; font-size: 0.95rem; font-weight: 500; cursor: pointer; border: none; transition: var(--transition-smooth);}
.btn:active { transform: scale(0.98);}
.btn-primary { background: var(--primary-gradient); color: white; box-shadow: 0 4px 14px 0 var(--primary-glow);}
.btn-primary:hover { box-shadow: 0 6px 20px 0 var(--primary-glow); filter: brightness(1.1);}
.btn-outline { background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.08); color: var(--text-primary);}
.btn-outline:hover { background: rgba(255, 255, 255, 0.08); border-color: rgba(255, 255, 255, 0.2);}
.btn-secondary { background: rgba(148, 163, 184, 0.1); color: var(--text-secondary);}
.btn-secondary:hover { background: rgba(148, 163, 184, 0.2); color: var(--text-primary);}
.btn-danger { background: var(--danger-bg); border: 1px solid rgba(239, 68, 68, 0.2); color: var(--danger);}
.btn-danger:hover { background: var(--danger); color: white; box-shadow: 0 4px 12px rgba(239, 68, 68, 0.2);}
.btn-sm { padding: 6px 12px; font-size: 0.8rem; border-radius: var(--border-radius-sm);}
.btn-block { width: 100%;}
.btn-icon-only { width: 32px; height: 32px; padding: 0; border-radius: 50%; background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.05); color: var(--text-secondary);}
.btn-icon-only:hover { background: rgba(255, 255, 255, 0.08); color: var(--text-primary);}
/* Tasks list styling */.tasks-container { display: flex; flex-direction: column; gap: 16px; overflow-y: auto; max-height: 520px; padding-right: 4px;}
.tasks-container::-webkit-scrollbar { width: 6px;}.tasks-container::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.1); border-radius: 4px;}
.empty-state { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 48px 16px; text-align: center; color: var(--text-muted); gap: 12px;}
.empty-state i { font-size: 2.5rem;}
/* Task Card */.task-item { background: rgba(15, 23, 42, 0.4); border: 1px solid rgba(255, 255, 255, 0.04); border-radius: var(--border-radius-md); padding: 16px; display: flex; flex-direction: column; gap: 12px; transition: var(--transition-smooth);}
.task-item:hover { background: rgba(15, 23, 42, 0.6); border-color: rgba(99, 102, 241, 0.25);}
.task-meta { display: flex; justify-content: space-between; align-items: flex-start;}
.task-info-left { display: flex; flex-direction: column; gap: 4px;}
.task-folder { font-weight: 600; font-size: 0.95rem; color: var(--text-primary); display: flex; align-items: center; gap: 6px;}
.task-id { font-family: monospace; font-size: 0.75rem; color: var(--text-muted);}
/* Status Badges */.status-pill { padding: 4px 10px; border-radius: 12px; font-size: 0.75rem; font-weight: 600; text-transform: uppercase;}
.status-pill.pending { background: rgba(148, 163, 184, 0.15); color: var(--text-secondary); }.status-pill.running { background: rgba(99, 102, 241, 0.15); color: var(--primary); animation: breathing 2s infinite; }.status-pill.completed { background: var(--success-bg); color: var(--success); }.status-pill.failed { background: var(--danger-bg); color: var(--danger); }.status-pill.cancelled { background: rgba(245, 158, 11, 0.15); color: var(--warning); }
@keyframes breathing { 0% { box-shadow: 0 0 0 0 rgba(99, 102, 241, 0.3); } 70% { box-shadow: 0 0 0 6px rgba(99, 102, 241, 0); } 100% { box-shadow: 0 0 0 0 rgba(99, 102, 241, 0); }}
/* Progress Section */.task-progress-box { display: flex; flex-direction: column; gap: 6px;}
.progress-info { display: flex; justify-content: space-between; font-size: 0.8rem; color: var(--text-secondary);}
.progress-bar-bg { height: 6px; background: rgba(255, 255, 255, 0.05); border-radius: 3px; overflow: hidden;}
.progress-bar-fill { height: 100%; background: var(--primary-gradient); width: 0%; border-radius: 3px; transition: width 0.4s cubic-bezier(0.4, 0, 0.2, 1);}
.task-item.running .progress-bar-fill { position: relative;}
.task-item.running .progress-bar-fill::after { content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: linear-gradient( 90deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.25) 50%, rgba(255, 255, 255, 0) 100-percent ); animation: shimmer 1.5s infinite;}
@keyframes shimmer { 0% { transform: translateX(-100%); } 100% { transform: translateX(100%); }}
.task-error { font-size: 0.8rem; color: var(--danger); background: rgba(239, 68, 68, 0.08); padding: 6px 10px; border-radius: var(--border-radius-sm); border-left: 3px solid var(--danger); word-break: break-all;}
/* Actions */.task-actions { display: flex; justify-content: flex-end; gap: 8px; border-top: 1px solid rgba(255, 255, 255, 0.03); padding-top: 10px;}
/* File explorer */.files-panel { margin-top: 8px;}
.files-actions { display: flex; gap: 12px;}
.files-table-container { overflow-x: auto; max-height: 400px;}
.files-table { width: 100%; border-collapse: collapse; text-align: left; font-size: 0.9rem;}
.files-table th { background: rgba(15, 23, 42, 0.4); padding: 12px 16px; font-weight: 600; color: var(--text-secondary); border-bottom: 1px solid rgba(255, 255, 255, 0.08);}
.files-table td { padding: 12px 16px; border-bottom: 1px solid rgba(255, 255, 255, 0.03); color: var(--text-primary); vertical-align: middle;}
.files-table tr:hover td { background: rgba(255, 255, 255, 0.02);}
.file-name-cell { display: flex; align-items: center; gap: 10px; font-weight: 500;}
.file-name-cell i { color: var(--info); font-size: 1.1rem;}
.file-path { font-size: 0.8rem; color: var(--text-muted); font-family: monospace;}
.table-empty { text-align: center; color: var(--text-muted); padding: 40px 16px !important;}
.table-empty i { font-size: 2rem; display: block; margin-bottom: 10px;}
/* Modal Drawer Styling */.modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.7); backdrop-filter: blur(8px); z-index: 100; display: none; align-items: center; justify-content: center; padding: 16px; opacity: 0; transition: opacity var(--transition-fast) ease;}
.modal-overlay.active { display: flex; opacity: 1;}
.modal-card { background: #0f1322; border: 1px solid rgba(255, 255, 255, 0.1); border-radius: var(--border-radius-lg); width: 100%; max-width: 800px; box-shadow: 0 20px 50px rgba(0,0,0,0.6); display: flex; flex-direction: column; max-height: 85vh; transform: scale(0.95); transition: transform var(--transition-fast) cubic-bezier(0.34, 1.56, 0.64, 1);}
.modal-overlay.active .modal-card { transform: scale(1);}
.modal-header { display: flex; justify-content: space-between; align-items: center; padding: 16px 24px; border-bottom: 1px solid rgba(255, 255, 255, 0.05);}
.modal-title { display: flex; align-items: center; gap: 12px;}
.modal-title i { color: var(--primary); font-size: 1.3rem;}
.modal-title h3 { font-size: 1.15rem; font-weight: 600;}
.modal-title span { font-family: monospace; font-size: 0.8rem; color: var(--text-muted);}
.modal-close { background: transparent; border: none; color: var(--text-secondary); font-size: 1.8rem; cursor: pointer; line-height: 1;}
.modal-close:hover { color: white;}
.modal-body { padding: 20px 24px; overflow-y: auto; flex: 1; background: #07090e;}
.console-logs { font-family: 'Fira Code', monospace; font-size: 0.8rem; line-height: 1.6; color: #38bdf8; white-space: pre-wrap; word-break: break-all;}
.modal-footer { display: flex; justify-content: space-between; align-items: center; padding: 16px 24px; border-top: 1px solid rgba(255, 255, 255, 0.05);}
.log-controls { display: flex; align-items: center; gap: 20px;}
/* Custom Checkbox */.checkbox-container { display: flex; align-items: center; position: relative; padding-left: 26px; cursor: pointer; font-size: 0.85rem; user-select: none; color: var(--text-secondary);}
.checkbox-container input { position: absolute; opacity: 0; cursor: pointer; height: 0; width: 0;}
.checkmark { position: absolute; top: 50%; transform: translateY(-50%); left: 0; height: 16px; width: 16px; background-color: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 4px; transition: var(--transition-fast);}
.checkbox-container:hover input ~ .checkmark { background-color: rgba(255,255,255,0.1);}
.checkbox-container input:checked ~ .checkmark { background-color: var(--primary); border-color: var(--primary);}
.checkmark:after { content: ""; position: absolute; display: none;}
.checkbox-container input:checked ~ .checkmark:after { display: block;}
.checkbox-container .checkmark:after { left: 5px; top: 2px; width: 4px; height: 8px; border: solid white; border-width: 0 2px 2px 0; transform: rotate(45deg);}DockerfileAdded+36
app/main.pyAdded+490
app/static/app.jsAdded+559
app/static/index.htmlAdded+172
app/static/style.cssAdded+892