Spaces:
Sleeping
Sleeping
File size: 1,800 Bytes
1a282d7 | 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 | # mypy: disable - error - code = "no-untyped-def,misc"
import pathlib
from fastapi import FastAPI, Response
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
# Define the FastAPI app
app = FastAPI()
# --- Simple API endpoint ---
class TextIn(BaseModel):
text: str
@app.post("/api/transform")
def transform_text(payload: TextIn):
# Minimal transformation: uppercase with a prefix
modified = f"Hello {payload.text.capitalize()}! How are you!"
return {"result": modified}
def create_frontend_router(build_dir="frontend/dist"):
"""Creates a router to serve the React frontend.
Args:
build_dir: Path to the React build directory relative to this file.
Returns:
A Starlette application serving the frontend.
"""
# Resolve build path from repo root (two levels up from this file: backend/ -> reactfast/)
build_path = pathlib.Path(__file__).resolve().parent.parent / build_dir
if not build_path.is_dir() or not (build_path / "index.html").is_file():
print(
f"WARN: Frontend build directory not found or incomplete at {build_path}. Serving frontend will likely fail."
)
# Return a dummy router if build isn't ready
from starlette.routing import Route
async def dummy_frontend(request):
return Response(
"Frontend not built. Run 'npm run build' in the frontend directory.",
media_type="text/plain",
status_code=503,
)
return Route("/{path:path}", endpoint=dummy_frontend)
return StaticFiles(directory=build_path, html=True)
# Mount the frontend under /app to avoid conflicts and align with Vite base
app.mount(
"/",
create_frontend_router(),
name="frontend",
)
|