File size: 2,335 Bytes
062c36e
25562f7
c23e33b
062c36e
25562f7
062c36e
25562f7
 
c23e33b
 
 
ce7cb88
c23e33b
 
 
 
25562f7
ad38258
062c36e
25562f7
 
 
 
 
 
 
 
062c36e
 
 
 
 
25562f7
 
ad38258
25562f7
 
 
c19a330
 
e8e558d
25562f7
062c36e
25562f7
 
 
 
 
 
 
062c36e
25562f7
 
 
062c36e
 
 
 
25562f7
062c36e
 
 
 
 
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from fastapi import Depends, FastAPI, HTTPException, status
from sqlalchemy.orm import Session
from fastapi.middleware.cors import CORSMiddleware
import schemas, models
from transformers import pipeline
import database

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

models.database.Base.metadata.create_all(bind=database.engine)
pipe = pipeline("text-classification", model="lxyuan/distilbert-base-multilingual-cased-sentiments-student")
# Database 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)):
    # Perform input validation
    if not isinstance(text_input, str) or not text_input.strip():
        raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Invalid text input")

    try:
        text_content = text_input
        sentiment_analysis_result = pipe(text_content)

        # Create a new SentimentResult instance
        new_sentiment_result = models.SentimentResult(
            score=sentiment_analysis_result[0]['score'],
            label = sentiment_analysis_result[0]['label'],
            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=f"An error occurred: {str(e)}")

@app.delete("/sentiment/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_sentiment_result(id: int, db: Session = Depends(get_db)):
    # Retrieve the sentiment result and check for existence
    sentiment_result_to_delete = db.query(models.SentimentResult).filter(models.SentimentResult.id == id).first()

    if sentiment_result_to_delete is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"SentimentResult with ID {id} not found")

    # Delete the sentiment result
    db.delete(sentiment_result_to_delete)
    db.commit()