File size: 1,418 Bytes
475ca58
 
 
 
 
 
 
 
 
71c9a9a
475ca58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#from fastapi import FastAPI, HTTPException, Query
#import pandas as pd
from fastapi import FastAPI
from pydantic import BaseModel
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline

app = FastAPI()

# Load the pre-trained model and tokenizer
model_name = "gyesibiney/Sentiment-review-analysis-roberta-3"
model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)

# Create a sentiment analysis pipeline
sentiment = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)

# Define a request body model
class SentimentRequest(BaseModel):
    text: str

# Define a response model
class SentimentResponse(BaseModel):
    sentiment: str
    score: float

# Create an endpoint for sentiment analysis
@app.post("/sentiment/")
async def analyze_sentiment(request: SentimentRequest):
    input_text = request.text
    result = sentiment(input_text)
    sentiment_label = result[0]["label"]
    sentiment_score = result[0]["score"]

    if sentiment_label == "LABEL_1":
        sentiment_label = "positive"
    elif sentiment_label == "LABEL_0":
        sentiment_label = "neutral"
    else:
        sentiment_label = "negative"

    return SentimentResponse(sentiment=sentiment_label.capitalize(), score=sentiment_score)

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