File size: 2,039 Bytes
9ed519c
25562f7
 
 
c0aa75e
25562f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8e558d
 
25562f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import Depends, FastAPI, HTTPException,status
from sqlalchemy.orm import Session
import schemas,models
from transformers import pipeline
import database 

app = FastAPI()

models.database.Base.metadata.create_all(bind=database.engine)

classifier = pipeline("sentiment-analysis")
# Dtabase session Dependency
def get_db():
    db = database.SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.post("/analyze_sentiment", status_code=status.HTTP_201_CREATED)
def create_sentiment_result(sentiment_result: schemas.SentimentResultCreate,text_input: str,db: Session = Depends(get_db)):
    try:
        # Perform sentiment analysis
        text_content = text_input
        sentiment_analysis_result = classifier(text_content)

        # Create a new SentimentResult instance
        new_sentiment_result = models.SentimentResult(
            positive_score=sentiment_analysis_result["score"] if sentiment_analysis_result["label"] == "POSITIVE" else 0.0,
            negative_score=sentiment_analysis_result["score"] if sentiment_analysis_result["label"] == "NEGATIVE" else 0.0,
            text_input=text_content
        )
        # Add the new SentimentResult to the database
        db.add(new_sentiment_result)
        db.commit()
        db.refresh(new_sentiment_result)

        return new_sentiment_result
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

@app.delete("/sentiment/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_sentiment_result(id: int, db: Session = Depends(get_db)):
    delete_sentiment_result = db.query(models.SentimentResult).filter(models.SentimentResult.id == id).first()
    if delete_sentiment_result is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"SentimentResult with ID {id} not found")
    else:
        db.query(models.SentimentResult).filter_by(id=id).delete()
        db.commit()
    return Response(status_code=status.HTTP_204_NO_CONTENT)