RASHMIKA2006's picture
Update app.py
2ee7d8b verified
Raw History Blame Contribute Delete
1.33 kB
from fastapi import FastAPI
from pydantic import BaseModel
from transformers import pipeline
import os
# -----------------------------
# Configure HuggingFace cache
# -----------------------------
CACHE_DIR = "/tmp/huggingface_cache"
os.makedirs(CACHE_DIR, exist_ok=True)
os.environ["HF_HOME"] = CACHE_DIR
os.environ["TRANSFORMERS_CACHE"] = CACHE_DIR
# -----------------------------
# Initialize FastAPI
# -----------------------------
app = FastAPI(title="Free AI Text Generator")
# -----------------------------
# Load lightweight free model
# -----------------------------
chatbot = pipeline(
"text2text-generation",
model="google/flan-t5-small",
device_map=-1 # CPU only
)
# -----------------------------
# Request schema
# -----------------------------
class Question(BaseModel):
text: str
# -----------------------------
# Health check
# -----------------------------
@app.get("/")
async def root():
return {"message": "AI model is ready! POST /ask with JSON {text: 'your question'}"}
# -----------------------------
# Ask AI
# -----------------------------
@app.post("/ask")
async def ask_ai(question: Question):
try:
response = chatbot(question.text, max_length=200)
return {"answer": response[0]["generated_text"]}
except Exception as e:
return {"error": str(e)}