""" 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 # ════════════════════════════════════════════════════════════════ @app.get("/", tags=["Health"]) def root(): return {"service": "FinderX API", "version": API_VERSION, "status": "ok"} @app.get("/health", tags=["Health"]) 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 # ════════════════════════════════════════════════════════════════ @app.get("/files", tags=["Browse"]) 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], } @app.get("/search", tags=["Browse"]) 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 # ════════════════════════════════════════════════════════════════ @app.get("/files/meta", tags=["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 @app.post("/files/hash", tags=["Metadata"]) 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 # ════════════════════════════════════════════════════════════════ @app.post("/upload", tags=["Upload"], status_code=201) 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 = "" @app.post("/upload/chunked/init", tags=["Upload"]) 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} @app.post("/upload/chunked/{session_id}/{chunk_index}", tags=["Upload"]) 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), } @app.post("/upload/chunked/{session_id}/complete", tags=["Upload"]) 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(), } @app.get("/upload/chunked/{session_id}/status", tags=["Upload"]) 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 # ════════════════════════════════════════════════════════════════ @app.get("/download", tags=["Download"]) 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}"'}, ) @app.get("/stream", tags=["Download"]) 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)") @app.post("/files/rename", tags=["File Operations"]) 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") @app.post("/files/move", tags=["File Operations"]) 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") @app.post("/files/copy", tags=["File Operations"]) 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} @app.delete("/files", tags=["File Operations"]) 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 @app.post("/batch/delete", tags=["Batch"]) 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 @app.post("/batch/move", tags=["Batch"]) 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 @app.post("/batch/copy", tags=["Batch"]) 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)") @app.post("/folders", tags=["Folders"], status_code=201) 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)") @app.post("/folders/rename", tags=["Folders"]) 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)} @app.delete("/folders", tags=["Folders"]) 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 # ════════════════════════════════════════════════════════════════ @app.get("/trash", tags=["Trash"]) 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} @app.post("/trash/restore", tags=["Trash"]) 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} @app.delete("/trash", tags=["Trash"]) 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} @app.delete("/trash/item", tags=["Trash"]) 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 # ════════════════════════════════════════════════════════════════ @app.get("/favorites", tags=["Favorites"]) def list_favorites(): return {"total": len(_favorites), "items": list(_favorites.keys())} @app.post("/favorites", tags=["Favorites"]) def add_favorite(path: str = Query(...)): _favorites[path] = True _log("favorite_add", path) return {"status": "added", "path": path} @app.delete("/favorites", tags=["Favorites"]) def remove_favorite(path: str = Query(...)): _favorites.pop(path, None) return {"status": "removed", "path": path} # ════════════════════════════════════════════════════════════════ # RECENT FILES # ════════════════════════════════════════════════════════════════ @app.get("/recent", tags=["Recent"]) def recent_files(limit: int = Query(20, ge=1, le=50)): return {"items": _recent_files[:limit]} # ════════════════════════════════════════════════════════════════ # VERSIONING # ════════════════════════════════════════════════════════════════ @app.get("/versions", tags=["Versions"]) def list_versions(path: str = Query(...)): return {"path": path, "versions": _versions.get(path, [])} # ════════════════════════════════════════════════════════════════ # THUMBNAILS & PREVIEW # ════════════════════════════════════════════════════════════════ @app.get("/preview", tags=["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) @app.get("/thumbnail", tags=["Preview"]) 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 # ════════════════════════════════════════════════════════════════ @app.get("/storage/usage", tags=["Storage"]) 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 # ════════════════════════════════════════════════════════════════ @app.get("/activity", tags=["Activity"]) 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 # ════════════════════════════════════════════════════════════════ @app.delete("/cache", tags=["Cache"]) 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} @app.get("/cache/stats", tags=["Cache"]) 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 # ════════════════════════════════════════════════════════════════ @app.get("/path/info", tags=["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), }