Spaces:
Sleeping
Sleeping
from fastapi import FastAPI, Request | |
from fastapi.staticfiles import StaticFiles | |
from fastapi.responses import HTMLResponse | |
from itables import to_html_datatable | |
from pathlib import Path | |
import pandas as pd | |
ROOT = Path(".") | |
app = FastAPI() | |
app.mount(path="/", app=StaticFiles(directory=ROOT), name="HOME") | |
async def file_system(request: Request, call_next): | |
url = request.url | |
if url.path.endswith("/"): | |
return HTMLResponse(content=files_in_folder(url.path.lstrip("/"))) | |
response = await call_next(request) | |
return response | |
def files_in_folder(path: str): | |
"""List files to render as file index.""" | |
folder = ROOT / path | |
print(folder) | |
path_glob = folder.glob("*") | |
res = pd.DataFrame( | |
[ | |
( | |
f.name, | |
f.stat().st_size, | |
pd.Timestamp(int(f.stat().st_mtime), unit="s"), | |
f.stat().st_nlink > 1, | |
) | |
for f in path_glob | |
], | |
columns=["path", "size", "mtime", "folder"], | |
).sort_values(["folder"], ascending=False) | |
res["path"] = res.apply( | |
lambda x: f"<a href=/{path}{x.path}{'/' if x.folder else ''}>{x.path}</a>", | |
axis=1, | |
) | |
return f"<h1>{folder}</h1><br>" + to_html_datatable( | |
df=res.drop(columns="folder"), | |
classes="display compact", | |
showIndex=False, | |
) | |