Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
-
from fastapi import FastAPI
|
|
|
|
| 2 |
from pydantic import BaseModel
|
| 3 |
import sys
|
| 4 |
import io
|
|
@@ -8,95 +9,114 @@ import os
|
|
| 8 |
import glob
|
| 9 |
import tempfile
|
| 10 |
import shutil
|
| 11 |
-
import
|
| 12 |
-
import
|
| 13 |
-
from typing import Optional, List, Dict
|
| 14 |
|
| 15 |
app = FastAPI(title="Codexe TMA - AI Code Executor")
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
| 21 |
|
| 22 |
class ExecutionResult(BaseModel):
|
| 23 |
status: str
|
| 24 |
output: str
|
| 25 |
error: Optional[str] = None
|
| 26 |
-
files: dict = {}
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
@app.get("/")
|
| 30 |
async def root():
|
| 31 |
return {
|
| 32 |
"status": "ok",
|
| 33 |
-
"message": "Codexe TMA Ready",
|
| 34 |
-
"
|
| 35 |
}
|
| 36 |
|
| 37 |
-
# ================== NEW ENDPOINT ==================
|
| 38 |
@app.get("/libraries")
|
| 39 |
async def list_libraries():
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
"package": pkg.project_name,
|
| 46 |
-
"version": pkg.version
|
| 47 |
-
})
|
| 48 |
-
|
| 49 |
-
# Sort by name
|
| 50 |
-
libraries.sort(key=lambda x: x["package"].lower())
|
| 51 |
-
|
| 52 |
-
return {
|
| 53 |
-
"status": "success",
|
| 54 |
-
"total": len(libraries),
|
| 55 |
-
"libraries": libraries
|
| 56 |
-
}
|
| 57 |
-
except Exception as e:
|
| 58 |
-
return {"status": "error", "message": str(e)}
|
| 59 |
-
|
| 60 |
-
@app.get("/health")
|
| 61 |
-
async def health():
|
| 62 |
-
return {"status": "healthy"}
|
| 63 |
|
| 64 |
@app.post("/execute")
|
| 65 |
-
async def execute_code(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
old_stdout = sys.stdout
|
| 67 |
redirected_output = sys.stdout = io.StringIO()
|
| 68 |
-
temp_dir = tempfile.mkdtemp(dir="/tmp")
|
| 69 |
-
shell_output = None
|
| 70 |
|
| 71 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
local_vars = {
|
| 73 |
"__builtins__": __builtins__,
|
| 74 |
"temp_dir": temp_dir,
|
| 75 |
-
"
|
| 76 |
-
"
|
| 77 |
}
|
| 78 |
|
| 79 |
-
|
|
|
|
| 80 |
|
| 81 |
output = redirected_output.getvalue()
|
| 82 |
|
| 83 |
-
#
|
| 84 |
-
|
|
|
|
|
|
|
| 85 |
for filepath in glob.glob(f"{temp_dir}/**/*.*", recursive=True):
|
| 86 |
if os.path.isfile(filepath):
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
return ExecutionResult(
|
| 96 |
status="success",
|
| 97 |
output=output,
|
| 98 |
-
files=
|
| 99 |
-
shell_output=shell_output
|
| 100 |
)
|
| 101 |
|
| 102 |
except Exception as e:
|
|
@@ -107,7 +127,4 @@ async def execute_code(request: CodeRequest):
|
|
| 107 |
)
|
| 108 |
finally:
|
| 109 |
sys.stdout = old_stdout
|
| 110 |
-
|
| 111 |
-
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 112 |
-
except:
|
| 113 |
-
pass
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File, Form
|
| 2 |
+
from fastapi.staticfiles import StaticFiles
|
| 3 |
from pydantic import BaseModel
|
| 4 |
import sys
|
| 5 |
import io
|
|
|
|
| 9 |
import glob
|
| 10 |
import tempfile
|
| 11 |
import shutil
|
| 12 |
+
import time
|
| 13 |
+
from typing import Optional, List
|
|
|
|
| 14 |
|
| 15 |
app = FastAPI(title="Codexe TMA - AI Code Executor")
|
| 16 |
|
| 17 |
+
# ====================== CONFIG ======================
|
| 18 |
+
FILES_DIR = "/app/files"
|
| 19 |
+
os.makedirs(FILES_DIR, exist_ok=True)
|
| 20 |
+
|
| 21 |
+
# Mount folder files agar bisa diakses publik
|
| 22 |
+
app.mount("/files", StaticFiles(directory=FILES_DIR), name="files")
|
| 23 |
|
| 24 |
class ExecutionResult(BaseModel):
|
| 25 |
status: str
|
| 26 |
output: str
|
| 27 |
error: Optional[str] = None
|
| 28 |
+
files: List[dict] = [] # [{"filename": , "url": , "size": }]
|
| 29 |
+
|
| 30 |
+
def cleanup_old_files(max_age=300): # 5 menit
|
| 31 |
+
now = time.time()
|
| 32 |
+
for f in os.listdir(FILES_DIR):
|
| 33 |
+
filepath = os.path.join(FILES_DIR, f)
|
| 34 |
+
if os.path.isfile(filepath) and (now - os.path.getmtime(filepath) > max_age):
|
| 35 |
+
try:
|
| 36 |
+
os.remove(filepath)
|
| 37 |
+
except:
|
| 38 |
+
pass
|
| 39 |
|
| 40 |
@app.get("/")
|
| 41 |
async def root():
|
| 42 |
return {
|
| 43 |
"status": "ok",
|
| 44 |
+
"message": "Codexe TMA Production Ready",
|
| 45 |
+
"file_url_base": "https://satyadev13-codexe-tma.hf.space/files/"
|
| 46 |
}
|
| 47 |
|
|
|
|
| 48 |
@app.get("/libraries")
|
| 49 |
async def list_libraries():
|
| 50 |
+
import pkg_resources
|
| 51 |
+
libs = sorted([{"package": pkg.project_name, "version": pkg.version}
|
| 52 |
+
for pkg in pkg_resources.working_set],
|
| 53 |
+
key=lambda x: x["package"].lower())
|
| 54 |
+
return {"total": len(libs), "libraries": libs}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
@app.post("/execute")
|
| 57 |
+
async def execute_code(
|
| 58 |
+
code: str = Form(...),
|
| 59 |
+
timeout: int = Form(30),
|
| 60 |
+
file: UploadFile = File(None)
|
| 61 |
+
):
|
| 62 |
+
await asyncio.to_thread(cleanup_old_files)
|
| 63 |
+
temp_dir = tempfile.mkdtemp(dir="/tmp")
|
| 64 |
old_stdout = sys.stdout
|
| 65 |
redirected_output = sys.stdout = io.StringIO()
|
|
|
|
|
|
|
| 66 |
|
| 67 |
try:
|
| 68 |
+
# Simpan uploaded file
|
| 69 |
+
uploaded_path = None
|
| 70 |
+
if file:
|
| 71 |
+
uploaded_path = os.path.join(temp_dir, file.filename)
|
| 72 |
+
with open(uploaded_path, "wb") as f:
|
| 73 |
+
f.write(await file.read())
|
| 74 |
+
|
| 75 |
local_vars = {
|
| 76 |
"__builtins__": __builtins__,
|
| 77 |
"temp_dir": temp_dir,
|
| 78 |
+
"files_dir": FILES_DIR,
|
| 79 |
+
"uploaded_file": uploaded_path
|
| 80 |
}
|
| 81 |
|
| 82 |
+
# Jalankan kode user
|
| 83 |
+
exec(code, local_vars, local_vars)
|
| 84 |
|
| 85 |
output = redirected_output.getvalue()
|
| 86 |
|
| 87 |
+
# Auto detect semua file di temp_dir dan files_dir
|
| 88 |
+
generated_files = []
|
| 89 |
+
|
| 90 |
+
# Scan di temp_dir (hasil kode)
|
| 91 |
for filepath in glob.glob(f"{temp_dir}/**/*.*", recursive=True):
|
| 92 |
if os.path.isfile(filepath):
|
| 93 |
+
filename = os.path.basename(filepath)
|
| 94 |
+
dest_path = os.path.join(FILES_DIR, filename)
|
| 95 |
+
shutil.copy2(filepath, dest_path)
|
| 96 |
+
|
| 97 |
+
public_url = f"https://satyadev13-codexe-tma.hf.space/files/{filename}"
|
| 98 |
+
generated_files.append({
|
| 99 |
+
"filename": filename,
|
| 100 |
+
"url": public_url,
|
| 101 |
+
"size": os.path.getsize(dest_path)
|
| 102 |
+
})
|
| 103 |
+
|
| 104 |
+
# Scan juga di FILES_DIR (jika user simpan langsung ke files_dir)
|
| 105 |
+
for filepath in glob.glob(f"{FILES_DIR}/*.*"):
|
| 106 |
+
if os.path.isfile(filepath):
|
| 107 |
+
filename = os.path.basename(filepath)
|
| 108 |
+
if not any(f["filename"] == filename for f in generated_files):
|
| 109 |
+
public_url = f"https://satyadev13-codexe-tma.hf.space/files/{filename}"
|
| 110 |
+
generated_files.append({
|
| 111 |
+
"filename": filename,
|
| 112 |
+
"url": public_url,
|
| 113 |
+
"size": os.path.getsize(filepath)
|
| 114 |
+
})
|
| 115 |
|
| 116 |
return ExecutionResult(
|
| 117 |
status="success",
|
| 118 |
output=output,
|
| 119 |
+
files=generated_files
|
|
|
|
| 120 |
)
|
| 121 |
|
| 122 |
except Exception as e:
|
|
|
|
| 127 |
)
|
| 128 |
finally:
|
| 129 |
sys.stdout = old_stdout
|
| 130 |
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
|
|
|
|
|
|
|
|