Spaces:
Paused
Paused
Download app.py from SatyaDev13/dockerf: direct link, hf CLI and curl.
- Browser
- Download file 4.2 kB
-
https://huggingface.co/spaces/SatyaDev13/dockerf/resolve/main/app.py
- Command line
-
hf download hf://spaces/SatyaDev13/dockerf/app.py
-
curl -L -o app.py https://huggingface.co/spaces/SatyaDev13/dockerf/resolve/main/app.py
4.2 kB
| from fastapi import FastAPI, UploadFile, File, Form | |
| from fastapi.staticfiles import StaticFiles | |
| from pydantic import BaseModel | |
| import sys | |
| import io | |
| import traceback | |
| import base64 | |
| import os | |
| import glob | |
| import tempfile | |
| import shutil | |
| import time | |
| import asyncio | |
| from typing import Optional, List | |
| app = FastAPI(title="Codexe TMA - AI Code Executor") | |
| # ====================== CONFIG ====================== | |
| FILES_DIR = "/app/files" | |
| os.makedirs(FILES_DIR, exist_ok=True) | |
| # Mount folder files agar bisa diakses publik | |
| app.mount("/files", StaticFiles(directory=FILES_DIR), name="files") | |
| class ExecutionResult(BaseModel): | |
| status: str | |
| output: str | |
| error: Optional[str] = None | |
| files: List[dict] = [] # [{"filename": , "url": , "size": }] | |
| def cleanup_old_files(max_age=300): # 5 menit | |
| now = time.time() | |
| for f in os.listdir(FILES_DIR): | |
| filepath = os.path.join(FILES_DIR, f) | |
| if os.path.isfile(filepath) and (now - os.path.getmtime(filepath) > max_age): | |
| try: | |
| os.remove(filepath) | |
| except: | |
| pass | |
| async def root(): | |
| return { | |
| "status": "ok", | |
| "message": "Codexe TMA Production Ready", | |
| "file_url_base": "https://satyadev13-codexe-tma.hf.space/files/" | |
| } | |
| async def list_libraries(): | |
| import pkg_resources | |
| libs = sorted([{"package": pkg.project_name, "version": pkg.version} | |
| for pkg in pkg_resources.working_set], | |
| key=lambda x: x["package"].lower()) | |
| return {"total": len(libs), "libraries": libs} | |
| async def execute_code( | |
| code: str = Form(...), | |
| timeout: int = Form(30), | |
| file: UploadFile = File(None) | |
| ): | |
| await asyncio.to_thread(cleanup_old_files) | |
| temp_dir = tempfile.mkdtemp(dir="/tmp") | |
| old_stdout = sys.stdout | |
| redirected_output = sys.stdout = io.StringIO() | |
| try: | |
| # Simpan uploaded file | |
| uploaded_path = None | |
| if file: | |
| uploaded_path = os.path.join(temp_dir, file.filename) | |
| with open(uploaded_path, "wb") as f: | |
| f.write(await file.read()) | |
| local_vars = { | |
| "__builtins__": __builtins__, | |
| "temp_dir": temp_dir, | |
| "files_dir": FILES_DIR, | |
| "uploaded_file": uploaded_path | |
| } | |
| # Jalankan kode user | |
| exec(code, local_vars, local_vars) | |
| output = redirected_output.getvalue() | |
| # Auto detect semua file di temp_dir dan files_dir | |
| generated_files = [] | |
| # Scan di temp_dir (hasil kode) | |
| for filepath in glob.glob(f"{temp_dir}/**/*.*", recursive=True): | |
| if os.path.isfile(filepath): | |
| filename = os.path.basename(filepath) | |
| dest_path = os.path.join(FILES_DIR, filename) | |
| shutil.copy2(filepath, dest_path) | |
| public_url = f"https://satyadev13-codexe-tma.hf.space/files/{filename}" | |
| generated_files.append({ | |
| "filename": filename, | |
| "url": public_url, | |
| "size": os.path.getsize(dest_path) | |
| }) | |
| # Scan juga di FILES_DIR (jika user simpan langsung ke files_dir) | |
| for filepath in glob.glob(f"{FILES_DIR}/*.*"): | |
| if os.path.isfile(filepath): | |
| filename = os.path.basename(filepath) | |
| if not any(f["filename"] == filename for f in generated_files): | |
| public_url = f"https://satyadev13-codexe-tma.hf.space/files/{filename}" | |
| generated_files.append({ | |
| "filename": filename, | |
| "url": public_url, | |
| "size": os.path.getsize(filepath) | |
| }) | |
| return ExecutionResult( | |
| status="success", | |
| output=output, | |
| files=generated_files | |
| ) | |
| except Exception as e: | |
| return ExecutionResult( | |
| status="error", | |
| output=redirected_output.getvalue(), | |
| error=traceback.format_exc() | |
| ) | |
| finally: | |
| sys.stdout = old_stdout | |
| shutil.rmtree(temp_dir, ignore_errors=True) |