Spaces:
Running
Running
Download main.py from veltrixcode/FinderX: direct link, hf CLI and curl.
- Browser
- Download file 38.5 kB
-
https://huggingface.co/spaces/veltrixcode/FinderX/resolve/78d39068bc3a37df8ddbc7160661da20930313ef/main.py
- Command line
-
hf download hf://spaces/veltrixcode/FinderX@78d39068bc3a37df8ddbc7160661da20930313ef/main.py
-
curl -L -o main.py https://huggingface.co/spaces/veltrixcode/FinderX/resolve/78d39068bc3a37df8ddbc7160661da20930313ef/main.py
38.5 kB
| """ | |
| FinderX File Manager API | |
| ======================== | |
| A comprehensive file management API backed by HuggingFace Buckets. | |
| Bucket: FinderX File Upload (configure BUCKET_ID in .env) | |
| """ | |
| import os | |
| import io | |
| import json | |
| import math | |
| import time | |
| import uuid | |
| import shutil | |
| import hashlib | |
| import asyncio | |
| import mimetypes | |
| import tempfile | |
| from pathlib import Path | |
| from datetime import datetime, timezone | |
| from typing import Optional, List, Dict, Any | |
| import aiofiles | |
| from fastapi import ( | |
| FastAPI, HTTPException, UploadFile, File, Form, | |
| Query, BackgroundTasks, Request, Depends | |
| ) | |
| from fastapi.responses import StreamingResponse, JSONResponse, Response | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel, Field | |
| from huggingface_hub import HfApi, list_bucket_tree, batch_bucket_files, download_bucket_files, get_bucket_paths_info, bucket_info | |
| # ββββββββββββββββββββββββββββ Config ββββββββββββββββββββββββββββ | |
| BUCKET_ID = os.getenv("BUCKET_ID", "veltrixcode/FinderX") | |
| HF_TOKEN = os.getenv("HF_TOKEN", "") # hf_xxxx token | |
| CHUNK_DIR = Path(tempfile.gettempdir()) / "finderx_chunks" | |
| CACHE_DIR = Path(tempfile.gettempdir()) / "finderx_cache" | |
| MAX_UPLOAD_MB = int(os.getenv("MAX_UPLOAD_MB", "5120")) # 5 GB default | |
| API_VERSION = "1.0.0" | |
| CHUNK_DIR.mkdir(parents=True, exist_ok=True) | |
| CACHE_DIR.mkdir(parents=True, exist_ok=True) | |
| # ββββββββββββββββββββββββββββ HF Client βββββββββββββββββββββββββ | |
| api = HfApi(token=HF_TOKEN or None) | |
| # ββββββββββββββββββββββββββββ In-Memory Stores ββββββββββββββββββ | |
| # (In production swap these with a Redis / SQLite store) | |
| _recent_files: List[Dict] = [] # last 50 accessed paths | |
| _favorites: Dict[str, bool] = {} # path -> True | |
| _trash: Dict[str, Dict] = {} # path -> {original, deleted_at, data} | |
| _activity_log: List[Dict] = [] # append-only log | |
| _versions: Dict[str, List] = {} # path -> [{version_id, uploaded_at, size}] | |
| _chunk_sessions: Dict[str, Dict] = {} # session_id -> {filename, total, received, parts[]} | |
| # ββββββββββββββββββββββββββββ Helpers βββββββββββββββββββββββββββ | |
| def _now() -> str: | |
| return datetime.now(timezone.utc).isoformat() | |
| def _log(action: str, path: str, extra: Dict = None): | |
| entry = {"action": action, "path": path, "timestamp": _now(), **(extra or {})} | |
| _activity_log.append(entry) | |
| if len(_activity_log) > 1000: | |
| _activity_log.pop(0) | |
| def _add_recent(path: str): | |
| global _recent_files | |
| _recent_files = [r for r in _recent_files if r["path"] != path] | |
| _recent_files.insert(0, {"path": path, "accessed_at": _now()}) | |
| _recent_files = _recent_files[:50] | |
| def _detect_mime(filename: str) -> str: | |
| mime, _ = mimetypes.guess_type(filename) | |
| return mime or "application/octet-stream" | |
| def _hf_path(virtual_path: str) -> str: | |
| """Clean and normalise a virtual path for bucket storage.""" | |
| p = virtual_path.strip("/") | |
| return p | |
| def _list_tree(prefix: str = "", recursive: bool = True) -> List[Dict]: | |
| items = [] | |
| for item in list_bucket_tree(BUCKET_ID, prefix=prefix or None, recursive=recursive): | |
| items.append({ | |
| "path": item.path, | |
| "type": item.type, # "file" | "directory" | |
| "size": getattr(item, "size", None), | |
| "last_modified": getattr(item, "last_modified", None), | |
| "mime_type": _detect_mime(item.path) if item.type == "file" else None, | |
| }) | |
| return items | |
| def _upload_bytes(data: bytes, remote_path: str): | |
| batch_bucket_files(BUCKET_ID, add=[(data, remote_path)], token=HF_TOKEN or None) | |
| def _download_bytes(remote_path: str) -> bytes: | |
| with tempfile.NamedTemporaryFile(delete=False) as tmp: | |
| tmp_path = tmp.name | |
| try: | |
| download_bucket_files( | |
| BUCKET_ID, | |
| files=[(remote_path, tmp_path)], | |
| token=HF_TOKEN or None, | |
| ) | |
| with open(tmp_path, "rb") as f: | |
| return f.read() | |
| finally: | |
| if os.path.exists(tmp_path): | |
| os.remove(tmp_path) | |
| def _file_exists(remote_path: str) -> bool: | |
| try: | |
| results = list(get_bucket_paths_info(BUCKET_ID, [remote_path], token=HF_TOKEN or None)) | |
| return len(results) > 0 | |
| except Exception: | |
| return False | |
| def _get_file_meta(remote_path: str) -> Optional[Dict]: | |
| try: | |
| results = list(get_bucket_paths_info(BUCKET_ID, [remote_path], token=HF_TOKEN or None)) | |
| if not results: | |
| return None | |
| r = results[0] | |
| return { | |
| "path": r.path, | |
| "size": getattr(r, "size", None), | |
| "xet_hash": getattr(r, "xet_hash", None), | |
| "mime_type": _detect_mime(r.path), | |
| "last_modified": getattr(r, "last_modified", _now()), | |
| } | |
| except Exception: | |
| return None | |
| # ββββββββββββββββββββββββββββ App βββββββββββββββββββββββββββββββ | |
| app = FastAPI( | |
| title="FinderX File Manager API", | |
| description="Full-featured file management API backed by HuggingFace Buckets", | |
| version=API_VERSION, | |
| docs_url="/docs", | |
| redoc_url="/redoc", | |
| ) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # HEALTH | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def root(): | |
| return {"service": "FinderX API", "version": API_VERSION, "status": "ok"} | |
| def health(): | |
| try: | |
| info = bucket_info(BUCKET_ID, token=HF_TOKEN or None) | |
| return {"status": "ok", "bucket": BUCKET_ID, "size": info.size, "files": info.total_files} | |
| except Exception as e: | |
| raise HTTPException(500, f"Bucket unreachable: {e}") | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # FILE LISTING & SEARCH | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def list_files( | |
| path: str = Query("", description="Folder prefix to list"), | |
| recursive: bool = Query(False, description="Recurse into sub-folders"), | |
| sort_by: str = Query("name", description="Sort by: name | size | date"), | |
| order: str = Query("asc", description="asc | desc"), | |
| page: int = Query(1, ge=1), | |
| per_page: int = Query(50, ge=1, le=500), | |
| ): | |
| """List files and folders. Supports pagination, sorting.""" | |
| items = _list_tree(prefix=path, recursive=recursive) | |
| # sort | |
| reverse = order.lower() == "desc" | |
| if sort_by == "size": | |
| items.sort(key=lambda x: x["size"] or 0, reverse=reverse) | |
| elif sort_by == "date": | |
| items.sort(key=lambda x: str(x["last_modified"] or ""), reverse=reverse) | |
| else: | |
| items.sort(key=lambda x: x["path"], reverse=reverse) | |
| # paginate | |
| total = len(items) | |
| start = (page - 1) * per_page | |
| end = start + per_page | |
| return { | |
| "path": path, | |
| "total": total, | |
| "page": page, | |
| "per_page": per_page, | |
| "pages": math.ceil(total / per_page), | |
| "items": items[start:end], | |
| } | |
| def search_files( | |
| q: str = Query(..., description="Search term (matches path/filename)"), | |
| path: str = Query("", description="Scope search to a folder prefix"), | |
| sort_by: str = Query("name"), | |
| order: str = Query("asc"), | |
| page: int = Query(1, ge=1), | |
| per_page: int = Query(50, ge=1, le=500), | |
| ): | |
| """Full-text search across all file paths.""" | |
| all_items = _list_tree(prefix=path, recursive=True) | |
| term = q.lower() | |
| matched = [i for i in all_items if term in i["path"].lower()] | |
| reverse = order.lower() == "desc" | |
| if sort_by == "size": | |
| matched.sort(key=lambda x: x["size"] or 0, reverse=reverse) | |
| elif sort_by == "date": | |
| matched.sort(key=lambda x: str(x["last_modified"] or ""), reverse=reverse) | |
| else: | |
| matched.sort(key=lambda x: x["path"], reverse=reverse) | |
| total = len(matched) | |
| start = (page - 1) * per_page | |
| return { | |
| "query": q, "total": total, "page": page, | |
| "per_page": per_page, "pages": math.ceil(total / per_page) if total else 0, | |
| "items": matched[start: start + per_page], | |
| } | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # FILE METADATA | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def file_metadata(path: str = Query(..., description="Remote file path")): | |
| """Get metadata: size, MIME type, hash, modified date.""" | |
| meta = _get_file_meta(_hf_path(path)) | |
| if not meta: | |
| raise HTTPException(404, f"File not found: {path}") | |
| meta["favorites"] = _favorites.get(path, False) | |
| meta["in_trash"] = path in _trash | |
| meta["versions"] = _versions.get(path, []) | |
| return meta | |
| def hash_file(path: str = Query(..., description="Remote file path")): | |
| """Compute SHA-256 hash of a file (duplicate / corruption detection).""" | |
| data = _download_bytes(_hf_path(path)) | |
| sha256 = hashlib.sha256(data).hexdigest() | |
| md5 = hashlib.md5(data).hexdigest() | |
| _log("hash", path) | |
| return {"path": path, "sha256": sha256, "md5": md5, "size": len(data)} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # UPLOAD | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def upload_file( | |
| file: UploadFile = File(...), | |
| destination_path: str = Form("", description="Remote folder path (e.g. photos/2024)"), | |
| overwrite: bool = Form(True), | |
| ): | |
| """ | |
| Upload a single file. The remote path is: `destination_path/filename`. | |
| Saves a version snapshot if the file already exists. | |
| """ | |
| if file.size and file.size > MAX_UPLOAD_MB * 1024 * 1024: | |
| raise HTTPException(413, f"File exceeds {MAX_UPLOAD_MB} MB limit") | |
| remote_dir = destination_path.strip("/") | |
| remote_path = f"{remote_dir}/{file.filename}".strip("/") | |
| # version snapshot | |
| if _file_exists(remote_path): | |
| if not overwrite: | |
| raise HTTPException(409, f"File already exists: {remote_path}") | |
| _versions.setdefault(remote_path, []) | |
| _versions[remote_path].append({ | |
| "version_id": str(uuid.uuid4()), | |
| "uploaded_at": _now(), | |
| "size": (_get_file_meta(remote_path) or {}).get("size"), | |
| }) | |
| data = await file.read() | |
| _upload_bytes(data, remote_path) | |
| _log("upload", remote_path, {"size": len(data)}) | |
| _add_recent(remote_path) | |
| return { | |
| "status": "uploaded", | |
| "path": remote_path, | |
| "size": len(data), | |
| "mime_type": _detect_mime(file.filename), | |
| "uploaded_at": _now(), | |
| } | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # CHUNKED / RESUMABLE UPLOAD | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class ChunkInitRequest(BaseModel): | |
| filename: str | |
| total_size: int | |
| total_chunks: int | |
| destination_path: str = "" | |
| def init_chunked_upload(req: ChunkInitRequest): | |
| """Initialise a chunked upload session. Returns a session_id.""" | |
| session_id = str(uuid.uuid4()) | |
| session_dir = CHUNK_DIR / session_id | |
| session_dir.mkdir(parents=True, exist_ok=True) | |
| _chunk_sessions[session_id] = { | |
| "filename": req.filename, | |
| "total_size": req.total_size, | |
| "total_chunks": req.total_chunks, | |
| "destination_path": req.destination_path, | |
| "received": [], | |
| "created_at": _now(), | |
| } | |
| return {"session_id": session_id, "total_chunks": req.total_chunks} | |
| async def upload_chunk(session_id: str, chunk_index: int, file: UploadFile = File(...)): | |
| """Upload a single chunk. chunk_index is 0-based.""" | |
| if session_id not in _chunk_sessions: | |
| raise HTTPException(404, "Session not found. Call /upload/chunked/init first.") | |
| session = _chunk_sessions[session_id] | |
| chunk_data = await file.read() | |
| chunk_path = CHUNK_DIR / session_id / f"chunk_{chunk_index:06d}" | |
| async with aiofiles.open(chunk_path, "wb") as f: | |
| await f.write(chunk_data) | |
| if chunk_index not in session["received"]: | |
| session["received"].append(chunk_index) | |
| progress = len(session["received"]) / session["total_chunks"] * 100 | |
| return { | |
| "session_id": session_id, | |
| "chunk_index": chunk_index, | |
| "received": len(session["received"]), | |
| "total_chunks": session["total_chunks"], | |
| "progress": round(progress, 2), | |
| } | |
| def complete_chunked_upload(session_id: str): | |
| """Assemble all chunks and push the completed file to the bucket.""" | |
| if session_id not in _chunk_sessions: | |
| raise HTTPException(404, "Session not found.") | |
| session = _chunk_sessions[session_id] | |
| total_chunks = session["total_chunks"] | |
| received = sorted(session["received"]) | |
| if len(received) != total_chunks or received != list(range(total_chunks)): | |
| missing = [i for i in range(total_chunks) if i not in received] | |
| raise HTTPException(400, f"Missing chunks: {missing}") | |
| session_dir = CHUNK_DIR / session_id | |
| assembled = b"" | |
| for i in range(total_chunks): | |
| chunk_path = session_dir / f"chunk_{i:06d}" | |
| with open(chunk_path, "rb") as f: | |
| assembled += f.read() | |
| remote_dir = session["destination_path"].strip("/") | |
| remote_path = f"{remote_dir}/{session['filename']}".strip("/") | |
| _upload_bytes(assembled, remote_path) | |
| shutil.rmtree(session_dir, ignore_errors=True) | |
| del _chunk_sessions[session_id] | |
| _log("chunked_upload", remote_path, {"size": len(assembled)}) | |
| _add_recent(remote_path) | |
| return { | |
| "status": "assembled", | |
| "path": remote_path, | |
| "size": len(assembled), | |
| "uploaded_at": _now(), | |
| } | |
| def chunked_upload_status(session_id: str): | |
| """Check status / progress of a chunked upload session.""" | |
| if session_id not in _chunk_sessions: | |
| raise HTTPException(404, "Session not found.") | |
| session = _chunk_sessions[session_id] | |
| received = len(session["received"]) | |
| total = session["total_chunks"] | |
| return { | |
| "session_id": session_id, | |
| "filename": session["filename"], | |
| "received": received, | |
| "total_chunks": total, | |
| "progress": round(received / total * 100, 2), | |
| "missing": [i for i in range(total) if i not in session["received"]], | |
| } | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # DOWNLOAD & STREAM | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def download_file(path: str = Query(..., description="Remote file path")): | |
| """Download a file as an attachment (triggers browser save dialog).""" | |
| remote_path = _hf_path(path) | |
| data = _download_bytes(remote_path) | |
| _add_recent(path) | |
| _log("download", path) | |
| filename = Path(remote_path).name | |
| mime = _detect_mime(filename) | |
| return Response( | |
| content=data, | |
| media_type=mime, | |
| headers={"Content-Disposition": f'attachment; filename="{filename}"'}, | |
| ) | |
| def stream_file(path: str = Query(..., description="Remote file path")): | |
| """ | |
| Stream a file inline (for direct open in browser/player). | |
| Supports partial Range requests for video seeking. | |
| """ | |
| remote_path = _hf_path(path) | |
| data = _download_bytes(remote_path) | |
| filename = Path(remote_path).name | |
| mime = _detect_mime(filename) | |
| _add_recent(path) | |
| _log("stream", path) | |
| def _gen(): | |
| chunk = 65536 | |
| for i in range(0, len(data), chunk): | |
| yield data[i: i + chunk] | |
| return StreamingResponse( | |
| _gen(), | |
| media_type=mime, | |
| headers={ | |
| "Content-Disposition": f'inline; filename="{filename}"', | |
| "Content-Length": str(len(data)), | |
| "Accept-Ranges": "bytes", | |
| "Cache-Control": "public, max-age=3600", | |
| }, | |
| ) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # FILE OPERATIONS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class RenameRequest(BaseModel): | |
| path: str = Field(..., description="Current path") | |
| new_name: str = Field(..., description="New filename (not full path)") | |
| def rename_file(req: RenameRequest): | |
| """Rename a file (keeps it in the same folder).""" | |
| old_path = _hf_path(req.path) | |
| parent = str(Path(old_path).parent).rstrip(".") | |
| new_path = f"{parent}/{req.new_name}".strip("/") | |
| data = _download_bytes(old_path) | |
| _upload_bytes(data, new_path) | |
| batch_bucket_files(BUCKET_ID, delete=[old_path], token=HF_TOKEN or None) | |
| _log("rename", old_path, {"new_path": new_path}) | |
| return {"status": "renamed", "old_path": old_path, "new_path": new_path} | |
| class MoveRequest(BaseModel): | |
| path: str = Field(..., description="Source path") | |
| destination_dir: str = Field(..., description="Target folder path") | |
| def move_file(req: MoveRequest): | |
| """Move a file to a different folder.""" | |
| old_path = _hf_path(req.path) | |
| filename = Path(old_path).name | |
| new_path = f"{req.destination_dir.strip('/')}/{filename}" | |
| data = _download_bytes(old_path) | |
| _upload_bytes(data, new_path) | |
| batch_bucket_files(BUCKET_ID, delete=[old_path], token=HF_TOKEN or None) | |
| _log("move", old_path, {"new_path": new_path}) | |
| return {"status": "moved", "old_path": old_path, "new_path": new_path} | |
| class CopyRequest(BaseModel): | |
| path: str = Field(..., description="Source path") | |
| destination_dir: str = Field(..., description="Target folder path") | |
| new_name: Optional[str] = Field(None, description="Override filename") | |
| def copy_file(req: CopyRequest): | |
| """Copy a file to another folder (optionally rename).""" | |
| src_path = _hf_path(req.path) | |
| filename = req.new_name or Path(src_path).name | |
| dest_path = f"{req.destination_dir.strip('/')}/{filename}" | |
| data = _download_bytes(src_path) | |
| _upload_bytes(data, dest_path) | |
| _log("copy", src_path, {"dest_path": dest_path}) | |
| return {"status": "copied", "source": src_path, "destination": dest_path} | |
| def delete_file( | |
| path: str = Query(..., description="File path to delete"), | |
| permanent: bool = Query(False, description="Skip trash and permanently delete"), | |
| ): | |
| """ | |
| Move a file to trash (recoverable) or permanently delete it. | |
| """ | |
| remote_path = _hf_path(path) | |
| if permanent: | |
| batch_bucket_files(BUCKET_ID, delete=[remote_path], token=HF_TOKEN or None) | |
| _log("permanent_delete", path) | |
| return {"status": "permanently_deleted", "path": path} | |
| else: | |
| # soft delete β store data in trash | |
| data = _download_bytes(remote_path) | |
| _trash[path] = { | |
| "original_path": path, | |
| "deleted_at": _now(), | |
| "data": data, | |
| "size": len(data), | |
| "mime_type": _detect_mime(Path(path).name), | |
| } | |
| batch_bucket_files(BUCKET_ID, delete=[remote_path], token=HF_TOKEN or None) | |
| _log("trash", path) | |
| return {"status": "moved_to_trash", "path": path} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # BATCH OPERATIONS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class BatchDeleteRequest(BaseModel): | |
| paths: List[str] | |
| permanent: bool = False | |
| def batch_delete(req: BatchDeleteRequest): | |
| """Delete multiple files at once.""" | |
| results = [] | |
| for path in req.paths: | |
| remote_path = _hf_path(path) | |
| try: | |
| if req.permanent: | |
| batch_bucket_files(BUCKET_ID, delete=[remote_path], token=HF_TOKEN or None) | |
| results.append({"path": path, "status": "permanently_deleted"}) | |
| else: | |
| data = _download_bytes(remote_path) | |
| _trash[path] = { | |
| "original_path": path, | |
| "deleted_at": _now(), | |
| "data": data, | |
| "size": len(data), | |
| "mime_type": _detect_mime(Path(path).name), | |
| } | |
| batch_bucket_files(BUCKET_ID, delete=[remote_path], token=HF_TOKEN or None) | |
| results.append({"path": path, "status": "trashed"}) | |
| _log("batch_delete", path) | |
| except Exception as e: | |
| results.append({"path": path, "status": "error", "error": str(e)}) | |
| return {"results": results} | |
| class BatchMoveRequest(BaseModel): | |
| paths: List[str] | |
| destination_dir: str | |
| def batch_move(req: BatchMoveRequest): | |
| """Move multiple files to the same destination folder.""" | |
| results = [] | |
| for path in req.paths: | |
| try: | |
| old_path = _hf_path(path) | |
| filename = Path(old_path).name | |
| new_path = f"{req.destination_dir.strip('/')}/{filename}" | |
| data = _download_bytes(old_path) | |
| _upload_bytes(data, new_path) | |
| batch_bucket_files(BUCKET_ID, delete=[old_path], token=HF_TOKEN or None) | |
| results.append({"path": path, "new_path": new_path, "status": "moved"}) | |
| _log("batch_move", path, {"new_path": new_path}) | |
| except Exception as e: | |
| results.append({"path": path, "status": "error", "error": str(e)}) | |
| return {"results": results} | |
| class BatchCopyRequest(BaseModel): | |
| paths: List[str] | |
| destination_dir: str | |
| def batch_copy(req: BatchCopyRequest): | |
| """Copy multiple files to the same destination folder.""" | |
| results = [] | |
| for path in req.paths: | |
| try: | |
| src = _hf_path(path) | |
| dest = f"{req.destination_dir.strip('/')}/{Path(src).name}" | |
| data = _download_bytes(src) | |
| _upload_bytes(data, dest) | |
| results.append({"path": path, "dest": dest, "status": "copied"}) | |
| _log("batch_copy", path, {"dest": dest}) | |
| except Exception as e: | |
| results.append({"path": path, "status": "error", "error": str(e)}) | |
| return {"results": results} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # FOLDER OPERATIONS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class FolderCreateRequest(BaseModel): | |
| path: str = Field(..., description="Full path for the new folder (e.g. docs/work)") | |
| def create_folder(req: FolderCreateRequest): | |
| """ | |
| Create a folder by uploading a hidden placeholder file. | |
| HF Buckets use virtual folders (path prefixes) β this ensures | |
| the folder appears in listings. | |
| """ | |
| folder_path = req.path.strip("/") | |
| placeholder = f"{folder_path}/.finderx_folder" | |
| _upload_bytes(b"", placeholder) | |
| _log("create_folder", folder_path) | |
| return {"status": "created", "path": folder_path} | |
| class FolderRenameRequest(BaseModel): | |
| path: str = Field(..., description="Current folder path") | |
| new_name: str = Field(..., description="New folder name (last segment)") | |
| def rename_folder(req: FolderRenameRequest): | |
| """Rename a folder by moving all its contents to the new path.""" | |
| old_prefix = req.path.strip("/") | |
| parent = str(Path(old_prefix).parent).rstrip(".") | |
| new_prefix = f"{parent}/{req.new_name}".strip("/") | |
| items = [i for i in _list_tree(prefix=old_prefix, recursive=True) if i["type"] == "file"] | |
| moved = [] | |
| for item in items: | |
| old_p = item["path"] | |
| suffix = old_p[len(old_prefix):] | |
| new_p = new_prefix + suffix | |
| data = _download_bytes(old_p) | |
| _upload_bytes(data, new_p) | |
| batch_bucket_files(BUCKET_ID, delete=[old_p], token=HF_TOKEN or None) | |
| moved.append({"old": old_p, "new": new_p}) | |
| _log("rename_folder", old_prefix, {"new_prefix": new_prefix}) | |
| return {"status": "renamed", "old_path": old_prefix, "new_path": new_prefix, "files_moved": len(moved)} | |
| def delete_folder( | |
| path: str = Query(..., description="Folder path to delete"), | |
| permanent: bool = Query(False), | |
| ): | |
| """Delete a folder and all its contents (recursive).""" | |
| folder_path = path.strip("/") | |
| items = [i for i in _list_tree(prefix=folder_path, recursive=True) if i["type"] == "file"] | |
| paths = [i["path"] for i in items] | |
| if permanent: | |
| if paths: | |
| batch_bucket_files(BUCKET_ID, delete=paths, token=HF_TOKEN or None) | |
| _log("permanent_delete_folder", folder_path, {"count": len(paths)}) | |
| else: | |
| for p in paths: | |
| data = _download_bytes(p) | |
| _trash[p] = { | |
| "original_path": p, "deleted_at": _now(), | |
| "data": data, "size": len(data), | |
| "mime_type": _detect_mime(Path(p).name), | |
| } | |
| if paths: | |
| batch_bucket_files(BUCKET_ID, delete=paths, token=HF_TOKEN or None) | |
| _log("trash_folder", folder_path, {"count": len(paths)}) | |
| return {"status": "deleted" if permanent else "trashed", "path": folder_path, "files_affected": len(paths)} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # TRASH BIN | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def list_trash(): | |
| """List all files in the trash bin.""" | |
| items = [ | |
| {"path": p, "original_path": v["original_path"], | |
| "deleted_at": v["deleted_at"], "size": v["size"], "mime_type": v["mime_type"]} | |
| for p, v in _trash.items() | |
| ] | |
| return {"total": len(items), "items": items} | |
| def restore_from_trash(path: str = Query(..., description="Path to restore")): | |
| """Restore a file from trash to its original location.""" | |
| if path not in _trash: | |
| raise HTTPException(404, f"Not found in trash: {path}") | |
| item = _trash.pop(path) | |
| original = item["original_path"] | |
| _upload_bytes(item["data"], _hf_path(original)) | |
| _log("restore", original) | |
| return {"status": "restored", "path": original} | |
| def empty_trash(): | |
| """Permanently delete everything in the trash bin.""" | |
| count = len(_trash) | |
| _trash.clear() | |
| _log("empty_trash", "*", {"count": count}) | |
| return {"status": "emptied", "files_removed": count} | |
| def permanent_delete_from_trash(path: str = Query(...)): | |
| """Permanently delete a single item from trash.""" | |
| if path not in _trash: | |
| raise HTTPException(404, f"Not found in trash: {path}") | |
| del _trash[path] | |
| _log("permanent_delete", path) | |
| return {"status": "permanently_deleted", "path": path} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # FAVORITES | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def list_favorites(): | |
| return {"total": len(_favorites), "items": list(_favorites.keys())} | |
| def add_favorite(path: str = Query(...)): | |
| _favorites[path] = True | |
| _log("favorite_add", path) | |
| return {"status": "added", "path": path} | |
| def remove_favorite(path: str = Query(...)): | |
| _favorites.pop(path, None) | |
| return {"status": "removed", "path": path} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # RECENT FILES | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def recent_files(limit: int = Query(20, ge=1, le=50)): | |
| return {"items": _recent_files[:limit]} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # VERSIONING | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def list_versions(path: str = Query(...)): | |
| return {"path": path, "versions": _versions.get(path, [])} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # THUMBNAILS & PREVIEW | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def preview_file(path: str = Query(..., description="Remote image or PDF path")): | |
| """ | |
| Return raw bytes for inline preview (images and PDFs). | |
| Images: returned as-is. PDFs: returned as application/pdf. | |
| """ | |
| remote_path = _hf_path(path) | |
| mime = _detect_mime(Path(remote_path).name) | |
| allowed = ("image/", "application/pdf") | |
| if not any(mime.startswith(p) for p in allowed): | |
| raise HTTPException(415, f"Preview not supported for MIME type: {mime}") | |
| data = _download_bytes(remote_path) | |
| _add_recent(path) | |
| return Response(content=data, media_type=mime) | |
| def thumbnail( | |
| path: str = Query(...), | |
| width: int = Query(256, ge=32, le=1024), | |
| height: int = Query(256, ge=32, le=1024), | |
| ): | |
| """ | |
| Generate a thumbnail for image files. | |
| Requires Pillow (`pip install Pillow`). | |
| Falls back to the original image if Pillow is unavailable. | |
| """ | |
| remote_path = _hf_path(path) | |
| mime = _detect_mime(Path(remote_path).name) | |
| if not mime.startswith("image/"): | |
| raise HTTPException(415, "Thumbnails are only supported for images") | |
| data = _download_bytes(remote_path) | |
| try: | |
| from PIL import Image | |
| img = Image.open(io.BytesIO(data)) | |
| img.thumbnail((width, height), Image.LANCZOS) | |
| buf = io.BytesIO() | |
| fmt = img.format or "JPEG" | |
| img.save(buf, format=fmt) | |
| return Response(content=buf.getvalue(), media_type=mime) | |
| except ImportError: | |
| # Pillow not installed β return original | |
| return Response(content=data, media_type=mime) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # STORAGE USAGE | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def storage_usage(): | |
| """Total bucket usage: size in bytes and file count.""" | |
| info = bucket_info(BUCKET_ID, token=HF_TOKEN or None) | |
| return { | |
| "bucket_id": BUCKET_ID, | |
| "total_bytes": info.size, | |
| "total_files": info.total_files, | |
| "total_mb": round(info.size / 1024 / 1024, 2), | |
| "total_gb": round(info.size / 1024 / 1024 / 1024, 4), | |
| } | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # ACTIVITY LOGS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def activity_log( | |
| limit: int = Query(50, ge=1, le=500), | |
| action: Optional[str] = Query(None, description="Filter by action type"), | |
| ): | |
| """Return recent activity log entries.""" | |
| entries = list(reversed(_activity_log)) | |
| if action: | |
| entries = [e for e in entries if e["action"] == action] | |
| return {"total": len(entries), "items": entries[:limit]} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # CACHE MANAGEMENT | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def clear_cache(): | |
| """Clear all locally cached temporary files.""" | |
| removed = 0 | |
| for f in CACHE_DIR.iterdir(): | |
| try: | |
| f.unlink() if f.is_file() else shutil.rmtree(f) | |
| removed += 1 | |
| except Exception: | |
| pass | |
| return {"status": "cleared", "files_removed": removed} | |
| def cache_stats(): | |
| files = list(CACHE_DIR.iterdir()) | |
| size = sum(f.stat().st_size for f in files if f.is_file()) | |
| return {"files": len(files), "size_bytes": size, "size_mb": round(size / 1024 / 1024, 2)} | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # PATH UTILITIES | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def path_info(path: str = Query(...)): | |
| """Return structured path components.""" | |
| p = Path(path) | |
| return { | |
| "full": str(p), | |
| "parent": str(p.parent), | |
| "name": p.name, | |
| "stem": p.stem, | |
| "suffix": p.suffix, | |
| "parts": list(p.parts), | |
| "mime_type": _detect_mime(p.name), | |
| } |