# app/main.py from fastapi import FastAPI from pydantic import BaseModel from typing import Union from fastapi.responses import RedirectResponse from .predictor import Predictor description_md = """ ### Microservice Phát hiện Tin đăng Lừa đảo 🛡️ API này sử dụng mô hình **PhoBERT** đã được fine-tune để thực hiện các chức năng sau: 1. **Tiền xử lý văn bản tiếng Việt** bằng VnCoreNLP để tách từ. 2. **Dự đoán khả năng lừa đảo** của tin đăng dựa trên tiêu đề và nội dung. 3. **Trả về điểm số lừa đảo (scam_score)** và kết quả phân loại. _API được xây dựng với FastAPI và triển khai trên Hugging Face Spaces._ """ app = FastAPI( title="Scam Detector API", description=description_md, version="1.0.0" ) # --- 1. Định nghĩa cấu trúc dữ liệu Input và Output --- # Dữ liệu mà API sẽ nhận vào class ListingRequest(BaseModel): listing_id: Union[str, int, None] = None title: str content: str # Dữ liệu mà API sẽ trả về class PredictionResponse(BaseModel): scam_score: float is_scam: bool version: str # --- 2. Khởi tạo ứng dụng FastAPI và tải model --- app = FastAPI( title="Scam Detection API", description="API để phát hiện tin đăng lừa đảo sử dụng PhoBERT", version="1.0.0" ) # Tải model MỘT LẦN khi ứng dụng khởi động # Điều này giúp tránh việc tải lại model cho mỗi request, tiết kiệm thời gian và bộ nhớ. predictor = Predictor() # --- 3. Định nghĩa Endpoint --- @app.get("/", include_in_schema=False) async def root(): """ Tự động chuyển hướng từ trang gốc đến trang tài liệu API. """ return RedirectResponse(url="/docs") @app.post("/predict/", response_model=PredictionResponse) def predict_scam(request: ListingRequest): """ Nhận dữ liệu tin đăng và trả về dự đoán lừa đảo. """ # Gọi hàm predict từ class Predictor đã được tải prediction_result = predictor.predict(title=request.title, content=request.content) return prediction_result