#!/usr/bin/python3
from fastapi import FastAPI, File, UploadFile, Form, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse
import subprocess
import os
import magic
app = FastAPI()
# HTML form for file upload
html_form = """
File Upload and Processing
File Upload and Processing
"""
@app.get("/")
async def read_root():
return HTMLResponse(content=html_form, status_code=200)
def get_mime_type(file: UploadFile):
mime = magic.Magic()
mime_type = mime.from_buffer(file.file.read(1024))
return mime_type
@app.post("/upload")
async def create_upload_file(file: UploadFile = File(...), convert_to: str = Form(...)):
# Validate file size
max_file_size = 100 * 1024 * 1024 # 100MB
if file.file.__sizeof__() > max_file_size:
raise HTTPException(status_code=400, detail="File size exceeds the limit of 100MB")
# Check the file type
mime_type = get_mime_type(file)
print(f"Detected MIME type: {mime_type}")
# Save the uploaded file to a temporary location
with open(file.filename, "wb") as f:
f.write(file.file.read())
# Continue with the processing logic
# Run the post-treatment Bash script
logs = subprocess.run(["bash", "addfile.sh", file.filename, mime_type, convert_to], capture_output=True, text=True).stdout
# Optionally, you can remove the temporary file
os.remove(file.filename)
return JSONResponse(content={"filename": file.filename, "mime_type": mime_type, "convert_to": convert_to, "message": "File processed successfully.", "logs": logs})
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=10101)