-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
166 lines (135 loc) · 5.7 KB
/
Copy pathapp.py
File metadata and controls
166 lines (135 loc) · 5.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, jsonify, flash
import os
from werkzeug.utils import secure_filename
import subprocess
from utils.file_utils import allowed_file, load_and_preprocess_audio, get_album_art_for_song
from utils.model_utils import predict_genre
from extract_features import extract_audio_features
from recommend import recommend_songs
UPLOAD_FOLDER = "uploads"
app = Flask(__name__)
app.secret_key = 'supersecretkey' # Needed for flashing messages
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
# Welcome page
@app.route("/", methods=["GET"])
def welcome():
return render_template("welcome.html")
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/contact", methods=["GET", "POST"])
def contact():
if request.method == "POST":
name = request.form.get("name")
email = request.form.get("email")
message = request.form.get("message")
from datetime import datetime
import json
contact_data = {
"name": name,
"email": email,
"message": message,
"timestamp": datetime.now().isoformat()
}
contacts_file = os.path.join(os.path.dirname(__file__), 'contacts.json')
if os.path.exists(contacts_file):
with open(contacts_file, 'r', encoding='utf-8') as f:
try:
contacts = json.load(f)
except json.JSONDecodeError:
contacts = []
else:
contacts = []
contacts.append(contact_data)
with open(contacts_file, 'w', encoding='utf-8') as f:
json.dump(contacts, f, indent=2, ensure_ascii=False)
flash("Thank you for reaching out! We'll get back to you soon.", "success")
return redirect(url_for("contact"))
return render_template("contact.html")
# Home page – handles analyze requests
@app.route("/index", methods=["GET", "POST"])
def index():
# Get all allowed audio files from the upload folder
song_list = os.listdir(app.config["UPLOAD_FOLDER"])
song_files = [f for f in song_list if allowed_file(f)]
# Get file info with modification times
song_info = []
for song in song_files:
file_path = os.path.join(app.config["UPLOAD_FOLDER"], song)
mod_time = os.path.getmtime(file_path)
# Add album art URL for each song
album_art = get_album_art_for_song(song)
song_info.append({
"name": song,
"modified": mod_time,
"album_art": album_art
})
# Sort by modification time (newest first)
song_info.sort(key=lambda x: x["modified"], reverse=True)
# Extract just the filenames for the template
sorted_song_files = song_info
if request.method == "POST":
filename = request.form.get("filename") #
if filename and allowed_file(filename):
path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
# Extract features & predict
audio_features = extract_audio_features(path)
audio_input = load_and_preprocess_audio(path)
predicted_genre, prediction = predict_genre(audio_input)
recommendations = recommend_songs(predicted_genre, audio_features)
# Load genre facts and pick a random one for the predicted genre
genre_facts_path = os.path.join(os.path.dirname(__file__), 'genre_facts.json')
genre_fact = None
try:
with open(genre_facts_path, 'r', encoding='utf-8') as f:
all_facts = json.load(f)
facts_list = all_facts.get(predicted_genre, [])
if facts_list:
import random
genre_fact = random.choice(facts_list)
except Exception as e:
genre_fact = None
return render_template("result.html",
genre=predicted_genre,
confidence=prediction,
features=audio_features,
recommendations=recommendations,
genre_fact=genre_fact)
return render_template("index.html", song_files=sorted_song_files)
import json
def escapejs_filter(value):
# Use json.dumps to escape characters and then strip the surrounding quotes
return json.dumps(value)[1:-1]
app.jinja_env.filters['escapejs'] = escapejs_filter
# Serve uploaded audio files
from urllib.parse import unquote
@app.route('/uploads/<path:filename>')
def uploaded_file(filename):
decoded_filename = unquote(filename)
return send_from_directory(app.config["UPLOAD_FOLDER"], decoded_filename)
# Handle music download from YouTube
@app.route("/download", methods=["POST"])
def download_song():
data = request.get_json()
query = data.get("query")
output_path = app.config["UPLOAD_FOLDER"]
if not query:
return jsonify({"message": "❌ No search query provided."}), 400
if not os.path.exists(output_path):
os.makedirs(output_path)
# Build yt-dlp command
command = [
"yt-dlp",
"-x", "--audio-format", "mp3",
f"ytsearch1:{query}",
"-o", os.path.join(output_path, "%(title)s.%(ext)s")
]
try:
result = subprocess.run(command, capture_output=True, text=True, check=True)
print("✅ Download success:", result.stdout)
return jsonify({"message": "✅ Song downloaded successfully!"})
except subprocess.CalledProcessError as e:
print("❌ Download failed:", e.stderr)
return jsonify({"message": "❌ Download failed"}), 500
if __name__ == "__main__":
app.run(debug=True)