Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from pydantic import BaseModel, validator
|
| 3 |
+
from transformers import pipeline
|
| 4 |
+
|
| 5 |
+
# Initialize the FastAPI app
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
|
| 8 |
+
# Load the sentiment analysis pipeline
|
| 9 |
+
sentiment_model = pipeline("text-classification", model="MarieAngeA13/Sentiment-Analysis-BERT")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Define a Pydantic model for the input data
|
| 13 |
+
class Text(BaseModel):
|
| 14 |
+
text: str
|
| 15 |
+
|
| 16 |
+
@validator('text')
|
| 17 |
+
def must_not_be_blank(cls, value):
|
| 18 |
+
if not value.strip(): # Check if the text is not just whitespace
|
| 19 |
+
raise ValueError('Text must not be empty or just whitespace')
|
| 20 |
+
return value
|
| 21 |
+
|
| 22 |
+
@app.get("/")
|
| 23 |
+
def read_root():
|
| 24 |
+
return {"Hello": "Welcome to our Sentiment Analysis API, type '/docs' after the <URL> to access the Swagger UI"}
|
| 25 |
+
|
| 26 |
+
@app.post("/analyze")
|
| 27 |
+
def analyze(text: Text):
|
| 28 |
+
try:
|
| 29 |
+
# Process the text through the sentiment analysis model
|
| 30 |
+
result = sentiment_model(text.text)
|
| 31 |
+
return {"result": result}
|
| 32 |
+
except ValueError as ve:
|
| 33 |
+
# Handle validation errors, which occur when text is empty or just whitespace
|
| 34 |
+
raise HTTPException(status_code=400, detail=str(ve))
|
| 35 |
+
except Exception as e:
|
| 36 |
+
# Handle all other kinds of unexpected errors
|
| 37 |
+
raise HTTPException(status_code=500, detail="An error occurred during the analysis.")
|