Spaces:
Runtime error
Runtime error
from fastapi import Depends, FastAPI, HTTPException, status | |
from sqlalchemy.orm import Session | |
from fastapi.responses import JSONResponse | |
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() | |
def create_sentiment_result(sentiment_result: schemas.SentimentResultCreate,db: Session = Depends(get_db))->JSONResponse: | |
try: | |
# Perform input validation | |
if not isinstance(sentiment_result.text_input, str) or not sentiment_result.text_input.strip(): | |
raise HTTPException( | |
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, | |
detail="Invalid text input" | |
) | |
text_content = sentiment_result.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) | |
# Convert datetime objects to strings | |
created_at_str = new_sentiment_result.created_at.strftime("%Y-%m-%dT%H:%M:%SZ") | |
textinput_dict = { | |
"id": new_sentiment_result.id, | |
"text_input": new_sentiment_result.text_input, | |
"score": new_sentiment_result.score, | |
"label": new_sentiment_result.label, | |
"created_at": created_at_str, | |
} | |
return JSONResponse(content=textinput_dict, status_code=status.HTTP_201_CREATED) | |
except Exception as e: | |
raise HTTPException( | |
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
detail=f"An error occurred: {str(e)}" | |
) | |
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() | |