saidhanush4422 / Helium-3

0 stars 1 forks source link

Module 5: Successful Implementation #18

Closed saidhanush4422 closed 1 year ago

saidhanush4422 commented 1 year ago

Import necessary libraries

from textblob import TextBlob import ipywidgets as widgets from tkinter import * from tkinter import filedialog import numpy as np import pandas as pd import random import csv from flask import Flask, render_template, request

Define function to analyze emotion

def analyze_emotion(text): blob = TextBlob(text) sentiment_score = blob.sentiment.polarity if sentiment_score > 0.2: return 'Happy' elif sentiment_score >= 0 and sentiment_score <= 0.2: return 'Neutral' elif sentiment_score < 0 and sentiment_score >= -0.2: return 'Depressed' elif sentiment_score < -0.2 and sentiment_score >= -0.5: return 'Sad' else: return 'Angry'

flask

app = Flask(name)

@app.route("/") def index(): return render_template("index.html", )

User input if condition, Two models

user_input = input("Enter '1' to type input, '2' to upload a text file: ")

if user_input == '1':

Prompt user to type input in the command prompt

print("Enter the text and type in quit to exit the prompt")
output_list = []
#user_text = input("Enter text: ")
while True:
    user_text = input("Enter text: \n")
    emotion = analyze_emotion(user_text)
    print(emotion)
    output_list.append(emotion)
    #print(user_text)
    if user_text.lower()=="quit":
        print("You have exited the prompt")
        break
print(output_list)

#to find out the repeated emotion using simple linear search

count_dict = {}
for element in output_list:
    if element in count_dict:
        count_dict[element] += 1
    else:
        count_dict[element] = 1

max_count = max(count_dict.values())

for element, count in count_dict.items():
    if count == max_count:
        print(f"{element} occurs {count} times (the maximum number of times)")
        final_emotion=element
        print(final_emotion)

#final_emotion = max()
#print(final_emotion)

elif user_input == '2':

Prompt user to upload a text file

ele= int(input("Enter the no.of elements"))

# Function to process each line of data
def process_line(line, n):
    # Delete the first n elements from the line
    modified_line = line.split()[n:]
    # Convert the modified line back to a string and return it
    return ' '.join(modified_line)

def delete_n_elements(n):
    filename = filedialog.askopenfilename(initialdir="/", title="Select a File", filetypes=(("Text files", "*.txt"), ("All Files", "*.*")))
    with open(filename, "r", encoding='utf-8') as f:
        modified_lines = [process_line(line.strip(), n) for line in f]
    return modified_lines

# Example usage:
#def process_emotion(emotion):
# Process the line here
# return processed_emotion

output_list = []

modified_data = delete_n_elements(ele)
for line in modified_data:
    print(line)
    emotion = analyze_emotion(line)
    print(emotion)
    output_list.append(emotion)

to print the list of all the outputs

#print(output_list)

#to find out the repeated emotion
count_dict = {}
for element in output_list:
    if element in count_dict:
        count_dict[element] += 1
    else:
        count_dict[element] = 1

max_count = max(count_dict.values())

for element, count in count_dict.items():
    if count == max_count:
        print(f"{element} occurs {count} times (the maximum number of times)")
        final_emotion=element
        print(final_emotion)

final_emotion = max(output_list)

print(final_emotion)

#file_path = input("Enter file path: ")
#with open(file_path, 'r') as file:
#    user_text = file.read()

else: print("Invalid input. Please enter '1' or '2'.")

Do something with the user_text variable

Take final_emotion as input and use that as the recommendation parameter

print("Menu: \n 1.Music \n 2.Movies \n 3.Books \n 4.Art ") rec_input = input("Enter the prefered input for the user:") if rec_input.lower() == "music":

Executed sucessfully

#a=input("Enter the artist_name: ")
a = final_emotion
if a == 'Neutral':
    a=0.4
elif a == 'Depressed':
    a= 0.3
elif a == 'Sad':
    a= 0.2
elif a == 'Angry':
    a= 0.1
elif a == 'Happy':
    a= 0.5
else:
    print("Mood not found")
# Load the data
print(a)
data = pd.read_csv("music_data1.csv")

# Define a function to recommend songs based on similar artists
def recommend_songs(Mood_Value):
  # Get all the songs by the artist
  songs_by_artist = data[data["artist_name"] == Mood_Value]["tempo"]

  # Get all the songs by similar artists
  similar_artists = data[data["artist_name"] != Mood_Value]["artist_name"].unique()
  songs_by_similar_artists = data[data["artist_name"].isin(similar_artists)]["artist_name"]

  # Recommend the top 10 most popular songs by similar artist
  recommendations = songs_by_similar_artists.value_counts().head(10)

  # Remove any songs by the original artist from the recommendations
  recommendations = recommendations[~recommendations.isin(songs_by_artist)]

  return recommendations

# Test the recommendation function
print(recommend_songs(a))

elif rec_input.lower() == "books":

Executed sucessfully

#a=input("Enter the artist_name: ")
#a = final_emotion

Define the input condition

input_mood = final_emotion

# Open the CSV file and read the rows
with open("database_books_analyzed.csv", newline="", encoding='utf-8') as csvfile:
    reader = csv.DictReader(csvfile)
    rows = [row for row in reader if row["Mood_Value"] == input_mood]

Randomly select a row based on the input condition

if len(rows) > 0:
    selected_row = random.choice(rows)
    book_title = selected_row["Book_Title"]
    print(f"The book title for mood '{input_mood}' is '{book_title}'")

elif rec_input.lower() == "movies":

Executed sucessfully

 input_mood = final_emotion

 # Open the CSV file and read the rows
 if(final_emotion == "Sad"):
    print('http://www.imdb.com/search/title?genres=drama&title_type=feature&sort=moviemeter, asc')

# IMDb Url for Musical genre of
# movie against emotion Disgust
 elif(final_emotion == "Depressed"):
    print('http://www.imdb.com/search/title?genres=musical&title_type=feature&sort=moviemeter, asc')

# IMDb Url for Family genre of
# movie against emotion Anger
 elif(emotion == "Angry"):
    print('http://www.imdb.com/search/title?genres=family&title_type=feature&sort=moviemeter, asc')

# IMDb Url for Sport genre of
# movie against emotion Fear
 elif(emotion == "Happy"):
    print('http://www.imdb.com/search/title?genres=sport&title_type=feature&sort=moviemeter, asc')

# IMDb Url for Thriller genre of
# movie against emotion Enjoyment

 elif(emotion == "Neutral"):
    print('http://www.imdb.com/search/title?genres=western&title_type=feature&sort=moviemeter, asc')

# with open("database_movies_analyzed.csv", newline="", encoding='utf-8') as csvfile:
#     reader = csv.DictReader(csvfile)
#     rows = [row for row in reader if row["Mood_Value"] == input_mood]

Randomly select a row based on the input condition

 #if len(rows) > 0:
#     selected_row = random.choice(rows)
#     Movie_title = selected_row["Movie_Title"]
#     print(f"The Movie URL for mood '{input_mood}' is '{Movie_title}'")

elif rec_input.lower() == "art":

Executed sucessfully

 input_mood = final_emotion

 # Open the CSV file and read the rows
 with open("WikiArt-annotations.csv", newline="", encoding='latin-1') as csvfile:
     reader = csv.DictReader(csvfile)
     rows = [row for row in reader if row["Mood_Value"] == input_mood]

Randomly select a row based on the input condition

 if len(rows) > 0:
     selected_row = random.choice(rows)
     Art_title = selected_row["Title"]
     print(f"The art title for mood '{input_mood}' is '{Art_title}'")
 else:
    print(f"No books found for mood '{input_mood}'")

else: print("Not available")