Spaces:
Runtime error
Runtime error
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() | |
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)) | |
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) | |