Spaces:
Runtime error
Runtime error
Download main.py from Mudiji/backend-text: direct link, hf CLI and curl.
- Browser
- Download file 4.91 kB
-
https://huggingface.co/spaces/Mudiji/backend-text/resolve/main/main.py
- Command line
-
hf download hf://spaces/Mudiji/backend-text/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Mudiji/backend-text/resolve/main/main.py
4.91 kB
| # main.py — safer, production-friendly version | |
| import os | |
| import asyncio | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| # NOTE: heavy libs (torch, transformers) are imported only during startup in a thread. | |
| # This avoids blocking the event loop and prevents duplicate loads during worker spawn. | |
| class SimplificationRequest(BaseModel): | |
| sentence: str | |
| class SimplificationResponse(BaseModel): | |
| simplified_text: str | |
| app = FastAPI() | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Global model handle (populated at startup) | |
| MODEL = {"model": None, "tokenizer": None, "device": None} | |
| MODEL_LOCK = asyncio.Lock() | |
| # Blocking model load function (runs in thread via asyncio.to_thread) | |
| def _blocking_load_model(model_path: str = "./"): | |
| # Delay heavy imports until now | |
| import torch | |
| from transformers import T5Tokenizer, T5ForConditionalGeneration | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| tokenizer = T5Tokenizer.from_pretrained(model_path) | |
| model = T5ForConditionalGeneration.from_pretrained(model_path).to(device) | |
| # Apply FP16 if GPU | |
| if device == "cuda": | |
| model = model.half() | |
| return {"model": model, "tokenizer": tokenizer, "device": device} | |
| # Blocking inference function (runs in thread) | |
| def _blocking_simplify(input_text: str, tokenizer, model, device) -> str: | |
| if not input_text.strip(): | |
| return "Please enter some text to simplify." | |
| input_text_formatted = "simplify: " + input_text | |
| inputs = tokenizer( | |
| input_text_formatted, | |
| return_tensors="pt", | |
| max_length=256, | |
| truncation=True, | |
| ) | |
| # Move tensors to device | |
| import torch as _torch | |
| inputs = {k: v.to(device) for k, v in inputs.items()} | |
| outputs = model.generate( | |
| inputs["input_ids"], | |
| max_length=128, | |
| num_beams=4, | |
| early_stopping=True, | |
| ) | |
| simplified_text = tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| return simplified_text | |
| async def startup_event(): | |
| """ | |
| Load model at startup but run the blocking work in a thread so the event-loop | |
| isn't blocked and uvicorn/healthchecks can proceed. Use a lock to avoid races. | |
| """ | |
| global MODEL | |
| model_path = os.environ.get("MODEL_PATH", "./") | |
| async with MODEL_LOCK: | |
| if MODEL["model"] is not None: | |
| return # already loaded | |
| print("Starting model load (in background thread)...") | |
| try: | |
| # run blocking load in a separate thread with a timeout | |
| load_coro = asyncio.to_thread(_blocking_load_model, model_path) | |
| loaded = await asyncio.wait_for(load_coro, timeout=600) # adjust timeout if needed | |
| MODEL.update(loaded) | |
| print(f"Model loaded on {MODEL['device']} (FP16 on GPU if available).") | |
| except asyncio.TimeoutError: | |
| print("Model loading timed out during startup.") | |
| MODEL = {"model": None, "tokenizer": None, "device": None} | |
| except asyncio.CancelledError: | |
| print("Startup was cancelled while model was loading.") | |
| MODEL = {"model": None, "tokenizer": None, "device": None} | |
| raise | |
| except Exception as e: | |
| print("Model load failed during startup:", e) | |
| MODEL = {"model": None, "tokenizer": None, "device": None} | |
| async def shutdown_event(): | |
| # If needed, free model resources (GPU memory) here | |
| MODEL["model"] = None | |
| MODEL["tokenizer"] = None | |
| MODEL["device"] = None | |
| print("Shutdown: cleared model references") | |
| async def health(): | |
| return {"status": "ok", "model_loaded": MODEL["model"] is not None} | |
| async def create_simplification(request_data: SimplificationRequest): | |
| if MODEL["model"] is None or MODEL["tokenizer"] is None: | |
| raise HTTPException(status_code=503, detail="Model not loaded yet") | |
| # Run the blocking inference in a thread so we don't block the event loop | |
| try: | |
| simplified = await asyncio.to_thread( | |
| _blocking_simplify, request_data.sentence, MODEL["tokenizer"], MODEL["model"], MODEL["device"] | |
| ) | |
| return SimplificationResponse(simplified_text=simplified) | |
| except Exception as e: | |
| print("Inference error:", e) | |
| raise HTTPException(status_code=500, detail="Internal inference error") | |
| # Local dev convenience. In containers, prefer CMD ["uvicorn","main:app", ...] | |
| # if __name__ == "__main__": | |
| # import uvicorn | |
| # port = int(os.environ.get("PORT", 8000)) | |
| # print(f"Starting Uvicorn server... Go to http://0.0.0.0:{port}") | |
| # uvicorn.run("main:app", host="0.0.0.0", port=port, reload=False) | |