Spaces:
Sleeping
Sleeping
File size: 4,197 Bytes
7716d74 c10636c c4f492c 7716d74 5ca3874 7716d74 c10636c c4f492c c10636c 7716d74 c10636c 7716d74 c4f492c 7716d74 c4f492c 7716d74 c10636c 7716d74 c10636c 7716d74 c10636c c4f492c 7716d74 c10636c 7716d74 c10636c 7716d74 c4f492c c10636c 7716d74 c10636c 7716d74 c10636c 7716d74 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | 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
@app.get("/")
async def root():
return {
"status": "ok",
"message": "Codexe TMA Production Ready",
"file_url_base": "https://satyadev13-codexe-tma.hf.space/files/"
}
@app.get("/libraries")
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}
@app.post("/execute")
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) |