| from fastapi import FastAPI, HTTPException |
| from pydantic import BaseModel |
| from transformers import T5ForConditionalGeneration, T5Tokenizer |
| import torch |
|
|
| |
| app = FastAPI() |
|
|
| |
| tokenizer = T5Tokenizer.from_pretrained("./tokenizer") |
| model = T5ForConditionalGeneration.from_pretrained("./model") |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| model.to(device) |
| model.eval() |
|
|
| |
| class QuestionGenerationRequest(BaseModel): |
| context: str |
| answer: str |
|
|
| |
| @app.post("/generate_question") |
| async def generate_question(request: QuestionGenerationRequest): |
| try: |
| |
| text = f"context: {request.context} answer: {request.answer} </s>" |
|
|
| |
| encoding = tokenizer.encode_plus(text, max_length=512, padding="max_length", return_tensors="pt") |
| input_ids, attention_mask = encoding["input_ids"].to(device), encoding["attention_mask"].to(device) |
|
|
| |
| with torch.no_grad(): |
| beam_outputs = model.generate( |
| input_ids=input_ids, |
| attention_mask=attention_mask, |
| max_length=72, |
| early_stopping=True, |
| num_beams=5, |
| num_return_sequences=3 |
| ) |
|
|
| |
| questions = [ |
| tokenizer.decode(beam_output, skip_special_tokens=True, clean_up_tokenization_spaces=True) |
| for beam_output in beam_outputs |
| ] |
|
|
| |
| return {"questions": questions} |
|
|
| except Exception as e: |
| raise HTTPException(status_code=500, detail=str(e)) |
|
|
| |
| if __name__ == "__main__": |
| import uvicorn |
| uvicorn.run(app, host="0.0.0.0", port=8000) |
|
|