Spaces:
Runtime error
Runtime error
Commit
·
25562f7
1
Parent(s):
a34ac54
Create main.py
Browse files
main.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI
|
2 |
+
from sqlalchemy.orm import Session
|
3 |
+
import schemas,models
|
4 |
+
from transformers import pipeline
|
5 |
+
|
6 |
+
app = FastAPI()
|
7 |
+
|
8 |
+
models.database.Base.metadata.create_all(bind=database.engine)
|
9 |
+
|
10 |
+
classifier = pipeline("sentiment-analysis")
|
11 |
+
# Dtabase session Dependency
|
12 |
+
def get_db():
|
13 |
+
db = database.SessionLocal()
|
14 |
+
try:
|
15 |
+
yield db
|
16 |
+
finally:
|
17 |
+
db.close()
|
18 |
+
|
19 |
+
@app.post("/analyze_sentiment", status_code=status.HTTP_201_CREATED)
|
20 |
+
def create_sentiment_result(sentiment_result: schemas.SentimentResultCreate,text_input: str,db: Session = Depends(get_db)):
|
21 |
+
try:
|
22 |
+
# Perform sentiment analysis
|
23 |
+
text_content = text_input
|
24 |
+
sentiment_analysis_result = classifier(text_content)
|
25 |
+
|
26 |
+
# Create a new SentimentResult instance
|
27 |
+
new_sentiment_result = models.SentimentResult(
|
28 |
+
positive_score=sentiment_analysis_result["score"] if sentiment_analysis_result["label"] == "POSITIVE" else 0.0,
|
29 |
+
negative_score=sentiment_analysis_result["score"] if sentiment_analysis_result["label"] == "NEGATIVE" else 0.0,
|
30 |
+
user_id=sentiment_result.user_id,
|
31 |
+
text_id=sentiment_result.text_id
|
32 |
+
)
|
33 |
+
# Add the new SentimentResult to the database
|
34 |
+
db.add(new_sentiment_result)
|
35 |
+
db.commit()
|
36 |
+
db.refresh(new_sentiment_result)
|
37 |
+
|
38 |
+
return new_sentiment_result
|
39 |
+
except Exception as e:
|
40 |
+
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
|
41 |
+
|
42 |
+
@app.delete("/sentiment/{id}", status_code=status.HTTP_204_NO_CONTENT)
|
43 |
+
def delete_sentiment_result(id: int, db: Session = Depends(get_db)):
|
44 |
+
delete_sentiment_result = db.query(models.SentimentResult).filter(models.SentimentResult.id == id).first()
|
45 |
+
if delete_sentiment_result is None:
|
46 |
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"SentimentResult with ID {id} not found")
|
47 |
+
else:
|
48 |
+
db.query(models.SentimentResult).filter_by(id=id).delete()
|
49 |
+
db.commit()
|
50 |
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
51 |
+
|
52 |
+
|
53 |
+
|