szoya commited on
Commit
f118d14
·
verified ·
1 Parent(s): 5c52a50

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -0
app.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
+ from transformers import pipeline
4
+ from typing import List
5
+ import re
6
+
7
+ app = FastAPI(title="NER + Emotion API")
8
+
9
+ # ---------------------------------------------------------
10
+ # LOAD NER FIRST (PRIORITY LOAD)
11
+ # ---------------------------------------------------------
12
+ print("Loading NER model...")
13
+ ner_pipeline = pipeline(
14
+ "ner",
15
+ model="dslim/bert-base-NER",
16
+ aggregation_strategy="simple"
17
+ )
18
+ print("NER model loaded.")
19
+
20
+ # ---------------------------------------------------------
21
+ # LOAD SENTIMENT SECOND
22
+ # ---------------------------------------------------------
23
+ print("Loading Sentiment model...")
24
+ sentiment_pipeline = pipeline(
25
+ "text-classification",
26
+ model="j-hartmann/emotion-english-distilroberta-base",
27
+ top_k=1
28
+ )
29
+ print("Sentiment model loaded.")
30
+
31
+ # ---------------------------------------------------------
32
+ # REQUEST MODELS
33
+ # ---------------------------------------------------------
34
+ class TextInput(BaseModel):
35
+ text: str
36
+
37
+
38
+ class SentimentInput(BaseModel):
39
+ sentences: List[str]
40
+
41
+
42
+ # ---------------------------------------------------------
43
+ # HEALTH CHECK
44
+ # ---------------------------------------------------------
45
+ @app.get("/")
46
+ def home():
47
+ return {"message": "NER + Emotion API is running"}
48
+
49
+
50
+ # ---------------------------------------------------------
51
+ # NER ENDPOINT (FAST)
52
+ # ---------------------------------------------------------
53
+ @app.post("/analyze/ner")
54
+ def analyze_ner(data: TextInput):
55
+ try:
56
+ results = ner_pipeline(data.text, truncation=True)
57
+
58
+ persons = []
59
+ locations = []
60
+ organizations = []
61
+
62
+ for entity in results:
63
+ label = entity["entity_group"]
64
+ text = entity["word"]
65
+
66
+ if label == "PER":
67
+ persons.append(text)
68
+ elif label == "LOC":
69
+ locations.append(text)
70
+ elif label == "ORG":
71
+ organizations.append(text)
72
+
73
+ return {
74
+ "persons": list(set(persons)),
75
+ "locations": list(set(locations)),
76
+ "organizations": list(set(organizations))
77
+ }
78
+
79
+ except Exception as e:
80
+ raise HTTPException(status_code=500, detail=str(e))
81
+
82
+
83
+ # ---------------------------------------------------------
84
+ # SENTIMENT ENDPOINT
85
+ # ---------------------------------------------------------
86
+ @app.post("/analyze/sentiment")
87
+ def analyze_sentiment(data: SentimentInput):
88
+ try:
89
+ results = sentiment_pipeline(
90
+ data.sentences,
91
+ truncation=True,
92
+ max_length=512
93
+ )
94
+
95
+ processed_results = []
96
+
97
+ for res_list in results:
98
+ top_result = res_list[0]
99
+ label = top_result["label"]
100
+ score = top_result["score"]
101
+
102
+ if label == "joy":
103
+ polarity = score
104
+ elif label in ["anger", "disgust", "fear", "sadness"]:
105
+ polarity = -score
106
+ else:
107
+ polarity = 0.0
108
+
109
+ processed_results.append({
110
+ "label": label,
111
+ "confidence": score,
112
+ "polarity": polarity
113
+ })
114
+
115
+ return {"results": processed_results}
116
+
117
+ except Exception as e:
118
+ raise HTTPException(status_code=500, detail=str(e)}
119
+
120
+
121
+ if __name__ == "__main__":
122
+ import uvicorn
123
+ uvicorn.run(app, host="0.0.0.0", port=7860)