File size: 5,497 Bytes
c2110ef
 
 
4791673
 
c2110ef
 
 
 
 
 
 
 
 
 
 
59190fa
c2110ef
4791673
59190fa
4791673
 
59190fa
c2110ef
59190fa
 
4791673
 
c2110ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59190fa
4791673
c2110ef
 
 
 
59190fa
 
 
 
4791673
c2110ef
59190fa
 
 
 
 
c2110ef
59190fa
 
 
4791673
59190fa
c2110ef
59190fa
c2110ef
 
4791673
c2110ef
 
 
 
 
4791673
 
c2110ef
4791673
59190fa
4791673
 
c2110ef
 
 
 
 
 
 
 
4791673
 
 
 
 
c2110ef
4791673
59190fa
 
 
 
 
 
 
 
 
 
 
 
 
 
4791673
59190fa
4791673
c2110ef
 
 
 
 
4791673
 
c2110ef
 
4791673
c2110ef
59190fa
c2110ef
 
 
 
 
 
 
 
 
 
59190fa
c2110ef
 
 
 
59190fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2110ef
 
59190fa
c2110ef
59190fa
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import torch
import warnings
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from peft import PeftModel
from transformers import (
    MBartForConditionalGeneration, MBart50Tokenizer,
    MT5ForConditionalGeneration, T5Tokenizer
)

warnings.filterwarnings("ignore")

app = FastAPI(
    title="Khmer Summarization API",
    description="mBART-LoRA + mT5 in ONE API",
    version="1.1.0"
)

# ================= CORS =================
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# ================= Device =================
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# ================= Models Config =================
MODELS = {
    "model1": {
        "name": "Khmer mBART + LoRA",
        "type": "mbart",
        "repo": "sedtha/mBart-50-large_LoRa_kh_sumerize",
        "model": None,
        "tokenizer": None
    },
    "model2": {
        "name": "Khmer mT5",
        "type": "mt5",
        "repo": "angkor96/khmer-mT5-news-summarization",
        "model": None,
        "tokenizer": None
    }
}

# ================= Load Model =================
def load_model(key: str):
    info = MODELS[key]

    if info["model"] is None:
        print(f"πŸ”Ή Loading {info['name']}...")

        if info["type"] == "mbart":
            tokenizer = MBart50Tokenizer.from_pretrained(
                info["repo"],
                src_lang="km_KH",
                tgt_lang="km_KH",
                cache_dir="./cache"
            )

            base_model = MBartForConditionalGeneration.from_pretrained(
                "facebook/mbart-large-50",
                cache_dir="./cache"
            )

            model = PeftModel.from_pretrained(
                base_model,
                info["repo"],
                cache_dir="./cache"
            )

            # βœ… IMPORTANT: Merge LoRA weights
            model = model.merge_and_unload()

        elif info["type"] == "mt5":
            tokenizer = T5Tokenizer.from_pretrained(
                info["repo"],
                cache_dir="./cache"
            )

            model = MT5ForConditionalGeneration.from_pretrained(
                info["repo"],
                cache_dir="./cache"
            )

        model = model.to(device)
        model.eval()

        info["model"] = model
        info["tokenizer"] = tokenizer

        print(f"βœ… Loaded {info['name']}")

    return info["model"], info["tokenizer"]

# ================= Request Schema =================
class SummarizeRequest(BaseModel):
    text: str
    model: str = "model2"

# ================= Summarization =================
@app.post("/summarize")
def summarize(req: SummarizeRequest):
    if not req.text.strip():
        raise HTTPException(status_code=400, detail="Text is empty")

    if req.model not in MODELS:
        raise HTTPException(status_code=400, detail="Invalid model")

    model, tokenizer = load_model(req.model)

    inputs = tokenizer(
        req.text,
        return_tensors="pt",
        truncation=True,
        max_length=1024
    ).to(device)

    gen_kwargs = {
        "max_new_tokens": 150,
        "do_sample": True,
        "temperature": 1.0,
        "top_p": 0.95,
        "top_k": 100,
        "repetition_penalty": 1.2,
        "no_repeat_ngram_size": 3
    }

    # βœ… Fix for mBART language output
    if MODELS[req.model]["type"] == "mbart":
        gen_kwargs["forced_bos_token_id"] = tokenizer.lang_code_to_id["km_KH"]

    with torch.no_grad():
        summary_ids = model.generate(**inputs, **gen_kwargs)

    summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)

    # Khmer sentence cleanup
    if "αŸ”" in summary:
        summary = summary[:summary.rfind("αŸ”") + 1]

    return {
        "model": MODELS[req.model]["name"],
        "summary": summary.strip()
    }

# ================= Health =================
@app.get("/")
def root():
    return {"status": "Khmer Summarization API is running πŸš€"}

@app.get("/health")
def health_check():
    return {
        "status": "healthy",
        "device": str(device),
        "models_loaded": {
            key: info["model"] is not None
            for key, info in MODELS.items()
        }
    }

# ================= Optional Compare Endpoint =================
@app.post("/compare")
def compare(req: SummarizeRequest):
    if not req.text.strip():
        raise HTTPException(status_code=400, detail="Text is empty")

    results = {}

    for key in MODELS:
        model, tokenizer = load_model(key)

        inputs = tokenizer(
            req.text,
            return_tensors="pt",
            truncation=True,
            max_length=1024
        ).to(device)

        gen_kwargs = {
            "max_new_tokens": 120
        }

        if MODELS[key]["type"] == "mbart":
            gen_kwargs["forced_bos_token_id"] = tokenizer.lang_code_to_id["km_KH"]

        with torch.no_grad():
            ids = model.generate(**inputs, **gen_kwargs)

        results[MODELS[key]["name"]] = tokenizer.decode(
            ids[0],
            skip_special_tokens=True
        )

    return results

# ================= Startup =================
@app.on_event("startup")
async def startup_event():
    print("πŸš€ Starting Khmer Summarization API...")
    print(f"Using device: {device}")
    print("Models will load on first request (memory efficient)")