maFern's picture
Update main.py
23725f6 verified
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from transformers import pipeline
from pythainlp.util import normalize
# โหลดสมอง AI (ภาษาไทย)
print("Downloading Model...")
classifier = pipeline("text-classification", model="SandboxBhh/sentiment-thai-text-model", tokenizer="SandboxBhh/sentiment-thai-text-model")
app = FastAPI()
# เปิดอนุญาตให้เว็บข้างนอกเข้ามาใช้ได้
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class Item(BaseModel):
text: str
# ฟังก์ชันแปลผล (Positive/Negative)
label_map = {
"pos": "Positive (บวก)",
"neg": "Negative (ลบ)",
"neu": "Neutral (ทั่วไป)",
"q": "Question (สอบถาม)"
}
@app.get("/")
def home():
return {"status": "AI Ready"}
@app.post("/analyze-sentiment")
def analyze(item: Item):
text = normalize(item.text)
prediction = classifier(text)[0]
return {
"label": label_map.get(prediction['label'], "Unknown"),
"score": round(prediction['score'] * 100, 2)
}