Spaces:
Sleeping
Sleeping
File size: 1,817 Bytes
d97202c | 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 | from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import JSONResponse
import pandas as pd
import json
import io
app = FastAPI()
@app.get("/")
def root():
return {"status": "ok", "message": "Server is running"}
# --- Endpoint 1: Upload CSV → trả về thống kê ---
@app.post("/process/csv")
async def process_csv(file: UploadFile = File(...)):
if not file.filename.endswith(".csv"):
raise HTTPException(status_code=400, detail="Chỉ chấp nhận file CSV")
content = await file.read()
df = pd.read_csv(io.BytesIO(content))
result = {
"filename": file.filename,
"rows": len(df),
"columns": list(df.columns),
"summary": json.loads(df.describe().to_json())
}
return JSONResponse(result)
# --- Endpoint 2: Upload JSON → lọc/xử lý dữ liệu ---
@app.post("/process/json")
async def process_json(file: UploadFile = File(...)):
content = await file.read()
data = json.loads(content)
# Ví dụ: đếm keys, trả về cấu trúc
result = {
"filename": file.filename,
"type": type(data).__name__,
"length": len(data) if isinstance(data, list) else len(data.keys()),
"preview": data[:3] if isinstance(data, list) else dict(list(data.items())[:3])
}
return JSONResponse(result)
# --- Endpoint 3: Xử lý text thuần ---
@app.post("/process/text")
async def process_text(file: UploadFile = File(...)):
content = await file.read()
text = content.decode("utf-8")
lines = text.splitlines()
result = {
"filename": file.filename,
"lines": len(lines),
"words": sum(len(l.split()) for l in lines),
"chars": len(text),
"preview": lines[:5]
}
return JSONResponse(result) |