File size: 3,764 Bytes
f118d14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4aa41c7
f118d14
8cd5417
 
 
f118d14
 
 
8cd5417
 
 
f118d14
 
 
 
 
 
8cd5417
 
 
f118d14
4aa41c7
f118d14
4aa41c7
f118d14
4aa41c7
f118d14
 
 
 
 
 
 
8cd5417
 
f118d14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4aa41c7
f118d14
 
 
 
 
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
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from transformers import pipeline
from typing import List

app = FastAPI(title="NER + Emotion API")

# ---------------------------------------------------------
# LOAD NER FIRST (PRIORITY LOAD)
# ---------------------------------------------------------
print("Loading NER model...")
ner_pipeline = pipeline(
    "ner",
    model="dslim/bert-base-NER",
    aggregation_strategy="simple"
)
print("NER model loaded.")

# ---------------------------------------------------------
# LOAD SENTIMENT SECOND
# ---------------------------------------------------------
print("Loading Sentiment model...")
sentiment_pipeline = pipeline(
    "text-classification",
    model="j-hartmann/emotion-english-distilroberta-base",
    top_k=1
)
print("Sentiment model loaded.")

# ---------------------------------------------------------
# REQUEST MODELS
# ---------------------------------------------------------
class TextInput(BaseModel):
    text: str


class SentimentInput(BaseModel):
    sentences: List[str]


# ---------------------------------------------------------
# HEALTH CHECK
# ---------------------------------------------------------
@app.get("/")
def home():
    return {"message": "NER + Emotion API is running"}


# ---------------------------------------------------------
# NER ENDPOINT
# ---------------------------------------------------------
# ---------------------------------------------------------
# NER ENDPOINT (UPDATED)
# ---------------------------------------------------------
@app.post("/analyze/ner")
def analyze_ner(data: TextInput):
    try:
        # REMOVED truncation=True to fix the 500 error
        results = ner_pipeline(data.text, aggregation_strategy="simple")
        
        persons = []
        locations = []
        organizations = []

        for entity in results:
            label = entity["entity_group"]
            word = entity["word"].strip()
            
            # dslim/bert-base-NER uses these labels:
            if label == "PER":
                persons.append(word)
            elif label == "LOC":
                locations.append(word)
            elif label == "ORG":
                organizations.append(word)

        return {
            "persons": list(set(persons)),
            "locations": list(set(locations)),
            "organizations": list(set(organizations))
        }
    except Exception as e:
        # This will help you see the exact error in HF logs
        print(f"Internal Error: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


# ---------------------------------------------------------
# SENTIMENT ENDPOINT
# ---------------------------------------------------------
@app.post("/analyze/sentiment")
def analyze_sentiment(data: SentimentInput):
    try:
        results = sentiment_pipeline(
            data.sentences,
            truncation=True,
            max_length=512
        )

        processed_results = []

        for res_list in results:
            top_result = res_list[0]
            label = top_result["label"]
            score = top_result["score"]

            if label == "joy":
                polarity = score
            elif label in ["anger", "disgust", "fear", "sadness"]:
                polarity = -score
            else:
                polarity = 0.0

            processed_results.append({
                "label": label,
                "confidence": score,
                "polarity": polarity
            })

        return {"results": processed_results}

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)