File size: 1,049 Bytes
86609a2 aefcfc0 86609a2 aefcfc0 a4f85f3 aefcfc0 86609a2 aefcfc0 86609a2 42a9bcd aefcfc0 a4f85f3 aefcfc0 a4f85f3 aefcfc0 386d394 f540470 | 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 | from fastapi import FastAPI
from fastapi.responses import JSONResponse
from transformers import pipeline
from fastapi.requests import Request
from pydantic import BaseModel
app = FastAPI()
# Initialize the text generation pipeline
pipe = pipeline("text2text-generation", model="google/flan-t5-small")
@app.middleware("http")
async def log_requests(request: Request, call_next):
print(f"Incoming request: {request.method} {request.url}")
response = await call_next(request)
return response
@app.get("/")
def read_root():
return {
"message": "Welcome to the FastAPI text generation API! Use the /generate endpoint with a 'text' query parameter."
}
class GenerateRequest(BaseModel):
text: str
@app.post("/generate")
def generate(request: GenerateRequest):
try:
output = pipe(request.text)
return {"output": output[0]["generated_text"]}
except Exception as e:
return JSONResponse(
status_code=500,
content={"error": f"An error occurred: {str(e)}"}
)
|