Skip to content

Commit a31bcda

Browse files
committed
2 parents 9c8a59a + 91f47f6 commit a31bcda

6 files changed

Lines changed: 166 additions & 98 deletions

File tree

src/backend/audio/audioprocessing.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ def preprocess_database(dataset_path):
121121
# Use os.path.join(root, file) directly
122122
midi_files.append(os.path.join(root, file))
123123

124-
midi_files = midi_files[:100]
124+
midi_files = midi_files
125125
all_vect_hist = {}
126126
# Loop melalui semua file MIDI
127127
for midi_file in midi_files:
@@ -145,6 +145,8 @@ def preprocess_database(dataset_path):
145145
def process_query(query_path, database):
146146
try:
147147
query_data = PrettyMIDI(query_path)
148+
progress = 10
149+
yield progress
148150
# Process MIDI data
149151
query_windows = group_beat_by_window(query_data)
150152

@@ -157,19 +159,21 @@ def process_query(query_path, database):
157159
hist_rtb = calculate_rtb(window)
158160
hist_ftb = calculate_ftb(window)
159161
database[query_path].append([hist_atb,hist_rtb,hist_ftb])
162+
progress += 20/len(query_windows)
163+
yield progress
160164

161165
# compare query to database
162-
print(len(database.keys()))
163166
for midi_file in database.keys():
164167
if(midi_file == query_path):
165168
continue
166169
similarity_result = sliding_similarity(database[midi_file], database[query_path])
167170
if(similarity_result >= 0.7000000):
168171
final_res.append({
169-
# "score": similarity_result,
170172
"score": similarity_result,
171173
"filename": midi_file
172174
})
175+
progress += 70/len(database.keys())
176+
yield progress
173177
final_res.sort(key=lambda x: x["score"], reverse=True)
174178
return final_res
175179

src/backend/image/image_processing.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,20 +170,25 @@ def queryImage(query_paths: list, cache_path: str, target_size=100, batch_size=4
170170

171171
print("Starting image processing...")
172172
startTime = time.time()
173+
yield 10
173174
#query to matrix---------------------------------------------------------------------------------------------------------------------
174175
queryPicture = process_images_in_batches(query_paths, target_size, batch_size)
175176
t1 = time.time()
176177
print(f"imgQuery to matrix: {t1-startTime}")
178+
yield 20
177179
#centering dataPicture---------------------------------------------------------------------------------------------------------------------
178180
queryPicture_centered = center_data_with_mean(queryPicture, dataMean)
179181
t2 = time.time()
180182
print(f"data centering: {t2-t1}")
183+
yield 30
181184
# Project queryPicture---------------------------------------------------------------------------------------------------------------------
182185
projected_query = project_data(queryPicture_centered, eigenvectors)
183186
t3 = time.time()
184187
print(f"query projection: {t3-t2}")
188+
yield 40
185189

186190
sorted_imgPaths = compute_similarity(projected_data, projected_query)
191+
yield 60
187192

188193
t4 = time.time()
189194
print(f"compute similarity: {t4-t3}")
@@ -192,11 +197,13 @@ def queryImage(query_paths: list, cache_path: str, target_size=100, batch_size=4
192197
)
193198
t5 = time.time()
194199
print(f"sortZip: {t5-t4}")
200+
yield 80
195201
sorted_by_percentage_images = []
196202
for similarity, img_path in sorted_similarities[:12]:
197203
print(f"Image: {img_path}, Similarity: {similarity:.2f}%")
198204
if similarity > 75:
199205
sorted_by_percentage_images.append({"filename": img_path, "score": similarity})
206+
yield 100
200207
return sorted_by_percentage_images
201208

202209

src/backend/main.py

Lines changed: 61 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -66,41 +66,47 @@ async def processing_with_progress():
6666
return
6767

6868

69-
yield "data: 10\n\n"
69+
yield "data: 0\n\n"
7070

7171
now = time.time()
7272
result = None
7373

7474
if is_image:
7575
# Start image processing and stream progress
76-
result = queryImage([str(extracted_file_path)], DATASET_DIR)
77-
# generator = imageProcessing(DATASET_DIR, [str(extracted_file_path)])
78-
# while True:
79-
# try:
80-
# progress = next(generator) # Get the next progress value
81-
# yield f"data: {progress}\n\n"
82-
# except StopIteration as stop_result:
83-
# # Capture the final result from the generator
84-
# result = stop_result.value
85-
# break
76+
# result = queryImage([str(extracted_file_path)], DATASET_DIR)
77+
generator = queryImage([str(extracted_file_path)], DATASET_DIR)
78+
while True:
79+
try:
80+
progress = next(generator) # Get the next progress value
81+
82+
yield f"data: {progress}\n\n"
83+
except StopIteration as stop_result:
84+
# Capture the final result from the generator
85+
result = stop_result.value
86+
break
8687

8788
else:
8889
# Load the preprocessed database if it exists, otherwise preprocess and save it
8990
database_path = DATASET_DIR / "preprocessed_database.pkl"
9091
if database_path.exists():
9192
database = joblib.load(database_path)
93+
generator = process_query(str(extracted_file_path), database)
9294

93-
print(len(database))
94-
result = process_query(str(extracted_file_path), database)
95-
print(result[:limit])
96-
# print(result)
95+
while True:
96+
try:
97+
progress = next(generator) # Get the next progress value
9798

99+
yield f"data: {progress}\n\n"
100+
except StopIteration as stop_result:
101+
# Capture the final result from the generator
102+
result = stop_result.value
103+
break
98104
time_taken = time.time() - now
99105
query_file_path = QUERY_RESULT_DIR / "result.txt"
100106

101107
with open(query_file_path, "w", encoding="utf-8") as query_file:
102108
for res in result[:limit]:
103-
query_file.write(f"{res["filename"]} {res["score"]}\n")
109+
query_file.write(f"{res['filename']} {res['score']}\n")
104110
query_file.write(str(time_taken) + "\n")
105111

106112
yield "data: 100\n\n"
@@ -197,44 +203,48 @@ async def create_upload_dataset(file_upload: UploadFile, is_image: str = Form(..
197203

198204
try:
199205
zip_data = await file_upload.read()
206+
progress = 10
207+
async def processing_with_progress():
208+
nonlocal progress
209+
yield "data: 10\n\n"
210+
# extract zip file
211+
with zipfile.ZipFile(io.BytesIO(zip_data)) as zip_ref:
212+
increment = 70 / len(zip_ref.infolist())
213+
for file_info in zip_ref.infolist():
214+
# Skip directories
215+
if file_info.is_dir():
216+
continue
200217

201-
# extract zip file
202-
with zipfile.ZipFile(io.BytesIO(zip_data)) as zip_ref:
203-
for file_info in zip_ref.infolist():
204-
# Skip directories
205-
if file_info.is_dir():
206-
continue
207-
208-
file_name = file_info.filename
209-
# check jika file adalah file gambar atau file audio
210-
if (is_image_file(file_name) and is_image) or (is_midi_file(file_name) and not is_image):
211-
extracted_file_path = DATASET_DIR / Path(file_name).name
212-
try:
213-
with open(extracted_file_path, "wb") as extracted_file:
214-
extracted_file.write(zip_ref.read(file_name))
215-
except:
216-
print(f"Failed to write file: {file_name}")
218+
file_name = file_info.filename
219+
# check jika file adalah file gambar atau file audio
220+
if (is_image_file(file_name) and is_image) or (is_midi_file(file_name) and not is_image):
221+
extracted_file_path = DATASET_DIR / Path(file_name).name
222+
try:
223+
with open(extracted_file_path, "wb") as extracted_file:
224+
extracted_file.write(zip_ref.read(file_name))
225+
except:
226+
print(f"Failed to write file: {file_name}")
227+
continue
228+
229+
# file bukan file gambar atau file audio
230+
else:
217231
continue
218-
219-
# file bukan file gambar atau file audio
220-
else:
221-
continue
232+
progress += increment
233+
yield f"data: {progress}\n\n"
222234

223-
if (is_image):
224-
image_paths, projected_data, eigenvectors, dataMean = preProcessingDataSet(DATASET_DIR)
225-
# Save the processed data using joblib
226-
path = DATASET_DIR / "processed_data.pkl"
227-
joblib.dump((image_paths, projected_data, eigenvectors, dataMean), path)
228-
else:
229-
database = preprocess_database(DATASET_DIR)
230-
path = DATASET_DIR / "preprocessed_database.pkl"
231-
joblib.dump(database, path)
232-
233-
data_urls = [
234-
f"http://localhost:8000/uploads/dataset/{file_name}"
235-
for file_name in os.listdir(DATASET_DIR)
236-
]
237-
return {"uploaded_images": data_urls}
235+
if (is_image):
236+
image_paths, projected_data, eigenvectors, dataMean = preProcessingDataSet(DATASET_DIR)
237+
# Save the processed data using joblib
238+
path = DATASET_DIR / "processed_data.pkl"
239+
joblib.dump((image_paths, projected_data, eigenvectors, dataMean), path)
240+
else:
241+
database = preprocess_database(DATASET_DIR)
242+
path = DATASET_DIR / "preprocessed_database.pkl"
243+
joblib.dump(database, path)
244+
245+
yield f"data: 100\n\n"
246+
247+
return StreamingResponse(processing_with_progress(), media_type="text/event-stream")
238248

239249
except zipfile.BadZipFile:
240250
raise HTTPException(status_code=400, detail="Invalid zip file")
Lines changed: 16 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,23 @@
1-
"use client"
2-
import React, { useState } from "react";
1+
"use client";
2+
import React from "react";
33
import Image from "next/image";
4-
import { FaPlay, FaPause } from "react-icons/fa";
54
import { useRouter } from "next/navigation";
65

76
interface SongCardProps {
87
imgSrc: string;
98
title: string;
10-
duration: string;
119
number: number;
10+
score?: number;
1211
}
1312

14-
export const SongCard = ({
15-
imgSrc,
16-
title,
17-
duration,
18-
number,
19-
}: SongCardProps) => {
20-
const [isPlaying, setIsPlaying] = useState(false);
21-
const handlePlayPause = () => {
22-
setIsPlaying(!isPlaying);
23-
};
13+
export const SongCard = ({ imgSrc, title, number, score }: SongCardProps) => {
2414
const router = useRouter();
2515

26-
2716
return (
28-
<div className="w-full grid grid-cols-12 py-3 px-6 text-biru-teks bg-white shadow-xl shadow-gray-200/50 hover:scale-105 hover:bg-cyan-tua/10 transition-all duration-300 hover:cursor-pointer"
29-
onClick={() => router.push(`/song/${title}.mid`)}>
17+
<div
18+
className="w-full grid grid-cols-12 py-3 px-6 text-biru-teks bg-white shadow-xl shadow-gray-200/50 hover:scale-105 hover:bg-cyan-tua/10 transition-all duration-300 hover:cursor-pointer"
19+
onClick={() => router.push(`/song/${title}.mid`)}
20+
>
3021
<div className="col-span-1 flex items-center">
3122
<p className="font-extrabold text-xl">{number}</p>
3223
</div>
@@ -39,21 +30,16 @@ export const SongCard = ({
3930
className="size-10 object-cover rounded-sm"
4031
/>
4132
</div>
42-
<div className="col-span-8 flex items-center">
33+
<div
34+
className={`${score ? "col-span-8" : "col-span-10"} flex items-center`}
35+
>
4336
<h3 className="text-md font-bold">{title}</h3>
4437
</div>
45-
<div className="col-span-1 flex items-center justify-end">
46-
<p className="text-center text-gray-500">{duration}</p>
47-
</div>
48-
<div className="col-span-1 flex items-center justify-end">
49-
<button onClick={handlePlayPause}>
50-
{isPlaying ? (
51-
<FaPause className="text-2xl" />
52-
) : (
53-
<FaPlay className="text-2xl" />
54-
)}
55-
</button>
56-
</div>
38+
{score && (
39+
<div className="col-span-2 flex items-center justify-end">
40+
<p className="text-center text-gray-500">Similarity: {(score*100).toFixed(2)}%</p>
41+
</div>
42+
)}
5743
</div>
5844
);
5945
};

src/frontend/src/components/search/AudioResult.tsx

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,13 @@ import { Song } from "../home/PopularSongs";
55
import { SongSkeleton } from "../home/SongSkeleton";
66
import { SongCard } from "../SongCard";
77

8+
type extendedSong = Song & {
9+
score: string;
10+
}
11+
812
export const AudioResult = () => {
913
const { toast } = useToast();
10-
const [resultAudios, setResultAudios] = useState<Song[]>([]);
14+
const [resultAudios, setResultAudios] = useState<extendedSong[]>([]);
1115
const [timeTaken, setTimeTaken] = useState(0);
1216
const [isLoading, setIsLoading] = useState(true);
1317

@@ -74,7 +78,7 @@ export const AudioResult = () => {
7478
key={index}
7579
imgSrc={song.imgSrc}
7680
title={song.title}
77-
duration={"3:00"}
81+
score={Number(song.score)}
7882
number={index + 1}
7983
/>
8084
))

0 commit comments

Comments
 (0)