backend / main.py
Mudiji's picture
Upload 14 files
d15459a verified
Raw History Blame Contribute Delete
3.81 kB
import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import torch
from transformers import T5Tokenizer, T5ForConditionalGeneration
# --- 1. Define the "shape" of your input and output data using Pydantic
class SimplificationRequest(BaseModel):
sentence: str
class SimplificationResponse(BaseModel):
simplified_text: str
# --- 2. Load your trained model ONCE, when the server starts
print("Loading fine-tuned model (V3)...")
model_path = "./"
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 quantization for faster inference and smaller memory footprint
if device == "cuda":
model = model.half() # Convert to FP16 on GPU
print(f"Model loaded with FP16 quantization on {device}")
else:
print(f"Model loaded on {device} (FP16 only works on GPU)")
print(f"Model size reduced by ~50% with minimal quality loss")
# --- 3. Create a function that uses your loaded model to simplify text
def simplify_with_model(input_text: str) -> str:
"""
Uses the fine-tuned T5 model to simplify the input text.
"""
print(f"Received for simplification: {input_text}")
if not input_text.strip():
return "Please enter some text to simplify."
# Prepare the input for T5 (add "simplify: " prefix)
input_text_formatted = "simplify: " + input_text
inputs = tokenizer(
input_text_formatted,
return_tensors="pt",
max_length=256,
truncation=True
).to(device)
# Generate the simplified output
outputs = model.generate(
inputs['input_ids'],
max_length=128,
num_beams=4, # Use beam search for better quality
early_stopping=True
)
# Decode the output
simplified_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(f"Returning simplified text: {simplified_text}")
return simplified_text
# --- FastAPI Server Setup ---
app = FastAPI()
# Add CORS middleware to allow your frontend to talk to this backend
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins (e.g., your 'index.html' file)
allow_credentials=True,
allow_methods=["*"], # Allows all methods (POST, GET, etc.)
allow_headers=["*"], # Allows all headers
)
@app.post("/simplify", response_model=SimplificationResponse)
async def create_simplification(request_data: SimplificationRequest):
"""
This is the API endpoint.
It receives data matching the 'SimplificationRequest' model,
calls the model function, and returns data matching
the 'SimplificationResponse' model.
"""
try:
sentence = request_data.sentence
# Call your model function
simplified_sentence = simplify_with_model(sentence)
# Return the result
return SimplificationResponse(simplified_text=simplified_sentence)
except Exception as e:
# If anything goes wrong, return a 500 internal server error
print(f"An error occurred: {e}")
raise HTTPException(status_code=500, detail="An internal server error occurred.")
# This block allows you to run the server by just running 'python main.py'
if __name__ == '__main__':
# --- [IMPORTANT] ---
# Make sure your model is loaded *before* uvicorn.run()
# (The code at the top of the file already handles this)
# ---
print("Starting Uvicorn server... Go to http://127.0.0.1:5000")
uvicorn.run("main:app", host="127.0.0.1", port=5000, reload=True)