File size: 5,365 Bytes
9b12ec1
 
 
 
 
 
 
 
 
 
 
 
fea32b2
8dacc67
 
9b12ec1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7708e97
 
 
 
 
 
 
 
 
b2bed46
7708e97
 
 
 
 
 
 
 
 
 
 
 
58bb5fd
fea32b2
58bb5fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f04a007
 
 
 
58bb5fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b12ec1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58bb5fd
 
9b12ec1
58bb5fd
 
 
 
9b12ec1
 
 
 
58bb5fd
 
 
 
 
 
 
9b12ec1
 
 
 
58bb5fd
9b12ec1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8c1af1
 
 
 
 
58bb5fd
 
fea32b2
58bb5fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7708e97
 
8923d39
7708e97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58bb5fd
d8c1af1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263

import os
import time
import numpy as np

from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Header
from fastapi.concurrency import run_in_threadpool

from app.models import models
from app.schemas import (
    AnalysisRequest,
    EmbeddingRequest,
    SarcasmRequest,
    AbsaRequest
)


API_KEY = os.getenv("API_KEY", "")


def verify_api_key(key: str | None):
    if API_KEY and key != API_KEY:
        raise HTTPException(
            status_code=401,
            detail="Invalid API key"
        )


def classify(pipe, text):
    result = pipe(text)[0]

    return {
        "label": result["label"],
        "confidence": round(float(result["score"]), 6)
    }


def detect_absa(request: AbsaRequest):
    absa_model = models.absa()

    start = time.perf_counter()
    
    # Format input untuk ABSA: [sentence] [SEP] [aspect]
    text_input = f"{request.text} [SEP] {request.aspect}"
    
    # Prediksi sentimen
    pred = absa_model(text_input)

    return {
        "absa":pred,
        "metadata": {
            "pipeline": ["absa"],
            "inference_time_ms": round(
                (time.perf_counter() - start) * 1000,
                2
            )
        },
    }


def detect_sarcasm_text(request: SarcasmRequest):
    # # PHASE 3: Sarcasm Detection
    sarcasm_model = models.sarcasm()

    text = request.text
    start = time.perf_counter()

    sarcasm = classify(
        sarcasm_model,
        text
    )

    return {
        # "entities": entities,
        # "sentiment": sentiment,
        "sarcasm": {
            **sarcasm,
            # "is_sarcastic": (
            #     "sarcas" in sarcasm["label"].lower()
            #     or sarcasm["label"] == "LABEL_1" or sarcasm["label"] == "1"
            # )
        },
        "metadata": {
            "pipeline": [
                # "dynamic_ner",
                # "sentiment",
                "sarcasm"
            ],
            "inference_time_ms": round(
                (time.perf_counter() - start) * 1000,
                2
            )
        }
    }


def analyze_text(request: AnalysisRequest):

    text = request.text
    start = time.perf_counter()

    # PHASE 1: Dynamic NER
    ner_model = models.ner()

    entities = ner_model.predict_entities(
        text,
        request.entity_labels,
        threshold=request.entity_threshold
    )

    # PHASE 2: Sentiment Analysis
    sentiment_model = models.sentiment()

    sentiment = classify(
        sentiment_model,
        text
    )

    # # PHASE 3: Sarcasm Detection
    # sarcasm_model = models.sarcasm()

    # sarcasm = classify(
    #     sarcasm_model,
    #     text
    # )

    return {
        "entities": entities,
        "sentiment": sentiment,
        # "sarcasm": {
        #     **sarcasm,
        #     "is_sarcastic": (
        #         "sarcas" in sarcasm["label"].lower()
        #         or sarcasm["label"] == "LABEL_1"
        #     )
        # },
        "metadata": {
            "pipeline": [
                "dynamic_ner",
                "sentiment",
                # "sarcasm"
            ],
            "inference_time_ms": round(
                (time.perf_counter() - start) * 1000,
                2
            )
        }
    }


@asynccontextmanager
async def lifespan(app: FastAPI):
    yield


app = FastAPI(
    title="NLP Inference Service",
    version="1.0.0",
    lifespan=lifespan
)


@app.get("/health")
async def health():
    return {
        "status": "healthy",
        "loaded_models": list(models._models.keys())
    }


@app.post("/v1/analyze")
async def analyze(
    request: AnalysisRequest,
    x_api_key: str | None = Header(default=None)
):
    verify_api_key(x_api_key)

    try:
        return await run_in_threadpool(
            analyze_text,
            request
        )
    except HTTPException:
        raise
    except Exception as exc:
        raise HTTPException(
            status_code=500,
            detail=str(exc)
        )





@app.post("/v1/detect_sarcasm")
async def detect_sarcasm(
    request: SarcasmRequest,
    x_api_key: str | None = Header(default=None)
):
    verify_api_key(x_api_key)

    try:
        return await run_in_threadpool(
            detect_sarcasm_text,
            request
        )
    except HTTPException:
        raise
    except Exception as exc:
        raise HTTPException(
            status_code=500,
            detail=str(exc)
        )



@app.post("/v1/absa")
async def absa(
    request: AbsaRequest,
    x_api_key: str | None = Header(default=None)
):
    verify_api_key(x_api_key)

    try:
        return await run_in_threadpool(
            detect_absa,
            request
        )
    except HTTPException:
        raise
    except Exception as exc:
        raise HTTPException(
            status_code=500,
            detail=str(exc)
        )



from app.embedding import generate_embeddings


@app.post("/v1/embeddings")
async def embeddings(
    request: EmbeddingRequest,
    x_api_key: str | None = Header(default=None)
):
    verify_api_key(x_api_key)

    try:
        return await run_in_threadpool(
            generate_embeddings,
            request
        )
    except HTTPException:
        raise
    except Exception as exc:
        raise HTTPException(
            status_code=500,
            detail=str(exc)
        )