0% found this document useful (0 votes)
21 views2 pages

Coding 4

This FastAPI application allows users to upload images or use a webcam to detect emotions and receive song recommendations based on those emotions. It supports both file uploads and text input for sentiment analysis, returning results through HTML templates. The application utilizes functions for emotion detection and song recommendations from external modules.

Uploaded by

Cat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views2 pages

Coding 4

This FastAPI application allows users to upload images or use a webcam to detect emotions and receive song recommendations based on those emotions. It supports both file uploads and text input for sentiment analysis, returning results through HTML templates. The application utilizes functions for emotion detection and song recommendations from external modules.

Uploaded by

Cat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

from fastapi import FastAPI, UploadFile, File, Form, Request

from fastapi.responses import HTMLResponse

from fastapi.staticfiles import StaticFiles

from fastapi.templating import Jinja2Templates

import shutil, os

from detectface import predict_emotion_image, predict_emotion_webcam

from TEXT import detect_emotion

from recommendation import recommend_songs_by_emotion

app = FastAPI()

if method == "upload" and file:

# Save uploaded image to static/uploads

file_path = f"static/uploads/{file.filename}"

with open(file_path, "wb") as buffer:

shutil.copyfileobj(file.file, buffer)

emotion = predict_emotion_image(file_path)

image_url = f"/{file_path}" # For displaying in HTML

elif method == "webcam":

emotion = predict_emotion_webcam()

image_url = "/static/uploads/temp.jpg" if os.path.exists("static/uploads/temp.jpg") else None

else:

emotion = "No input detected"

# Get song recommendations based on emotion

if emotion and emotion != "No input detected":

songs = recommend_songs_by_emotion(emotion,n=count)

else:

songs = []
return templates.TemplateResponse(

"emotion.html",

{"request": request, "emotion": emotion, "image_url": image_url, "songs": songs}

@app.post("/predict_sentiment/", response_class=HTMLResponse)

async def predict_sentiment(request: Request, text: str = Form(...), count: int = Form(5)):

sentiment = detect_emotion(text)

songs = recommend_songs_by_emotion(sentiment,n=count)

return templates.TemplateResponse("sentiment.html", {"request": request, "sentiment":


sentiment, "songs": songs})

You might also like