TEXTY / app.py
Akash297's picture
Update app.py
4c57879 verified
Raw History Blame Contribute Delete
1.74 kB
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from transformers import pipeline
import logging
# Initialize FastAPI app
app = FastAPI()
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) # Use logger from the logging module
# Initialize Hugging Face sentiment-analysis pipeline
model_name = "distilbert-base-uncased-finetuned-sst-2-english" # You can change this to any model you prefer
nlp = pipeline("sentiment-analysis", model=model_name)
# Define the request body model
class TextRequest(BaseModel):
text: str
@app.post("/detect-depression")
async def detect_depression(request: TextRequest):
try:
text = request.text
if not text.strip():
raise HTTPException(status_code=400, detail="No text provided")
logger.info(f"Processing text: {text[:50]}...") # Log the first 50 characters of the text
# Generate response using Hugging Face model
result = nlp(text)
# Extract relevant information from the result
sentiment = result[0]['label']
# Map the sentiment to depression levels (as an example)
if sentiment == "POSITIVE":
depression_level = "ZERO"
elif sentiment == "NEGATIVE":
depression_level = "SEVERE"
else:
depression_level = "UNKNOWN"
return {"depression_level": depression_level}
except Exception as e:
logger.error(f"Error processing request: {e}") # Log the error
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)