Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
+
from transformers import pipeline
|
| 4 |
+
from fastapi.requests import Request
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
|
| 8 |
+
# Initialize the text generation pipeline
|
| 9 |
+
pipe = pipeline("text2text-generation", model="google/flan-t5-small")
|
| 10 |
+
|
| 11 |
+
@app.middleware("http")
|
| 12 |
+
async def log_requests(request: Request, call_next):
|
| 13 |
+
print(f"Incoming request: {request.method} {request.url}")
|
| 14 |
+
response = await call_next(request)
|
| 15 |
+
return response
|
| 16 |
+
|
| 17 |
+
@app.get("/")
|
| 18 |
+
def read_root():
|
| 19 |
+
return {
|
| 20 |
+
"message": "Welcome to the FastAPI text generation API! Use the /generate endpoint with a 'text' query parameter."
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
@app.get("/generate")
|
| 24 |
+
def generate(text: str):
|
| 25 |
+
try:
|
| 26 |
+
output = pipe(text)
|
| 27 |
+
return {"output": output[0]["generated_text"]}
|
| 28 |
+
except Exception as e:
|
| 29 |
+
return JSONResponse(
|
| 30 |
+
status_code=500,
|
| 31 |
+
content={"error": f"An error occurred: {str(e)}"}
|
| 32 |
+
)
|