Spaces:
Runtime error
Runtime error
File size: 1,801 Bytes
d5c7889 | 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 62 63 64 | import logging
from fastapi import FastAPI, Request, HTTPException
from transformers import GPT2LMHeadModel, GPT2Tokenizer
import torch
from pathlib import Path
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
# Create cache directory
cache_dir = Path("/cache")
cache_dir.mkdir(exist_ok=True, parents=True)
# Load model with explicit cache
try:
logger.info("Loading model...")
tokenizer = GPT2Tokenizer.from_pretrained('gpt2', cache_dir=cache_dir)
model = GPT2LMHeadModel.from_pretrained('gpt2', cache_dir=cache_dir)
logger.info("Model loaded successfully!")
except Exception as e:
logger.error(f"Model loading failed: {e}")
raise RuntimeError("Model initialization failed")
@app.get("/")
async def root():
return {"status": "ready", "model": "gpt2"}
@app.post("/generate")
async def generate(request: Request):
try:
data = await request.json()
user_input = data.get("message", "").strip()
if not user_input:
raise HTTPException(400, "Empty input")
inputs = tokenizer.encode(user_input, return_tensors="pt")
outputs = model.generate(
inputs,
max_length=100,
num_return_sequences=1,
pad_token_id=tokenizer.eos_token_id,
temperature=0.7
)
return {
"response": tokenizer.decode(outputs[0], skip_special_tokens=True),
"status": "success"
}
except torch.cuda.OutOfMemoryError:
raise HTTPException(429, "Prompt too long")
except Exception as e:
logger.error(f"Error: {str(e)}")
raise HTTPException(500, "Generation failed")
@app.get("/health")
async def health_check():
return {"status": "healthy"} |