Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recommendation Algorithm for Songs #104

Merged
merged 2 commits into from
Feb 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions backend/app/api/songs/recommendations/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { verifySession } from '@/lib/session';
import { ErrorResponse } from '@/lib/types';
import { Song } from '@prisma/client';
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import { getRandomSegment } from '@/lib/misc';

type GetResponse = {
songs: Song[];
};

export const GET = async (
req: NextRequest
): Promise<NextResponse<GetResponse | ErrorResponse>> => {
const session = await verifySession();

const searchParams = new URL(req.url).searchParams;
const size = searchParams.get('size');

if (!size) {
return NextResponse.json({ error: 'Size is required' }, { status: 400 });
}

if (!session.isAuth) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

const user = await prisma.user.findUnique({
where: {
id: session.uid,
},
include: {
preferences: true,
},
});

if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}

const songs = await prisma.song.findMany({
where: {
seenBy: {
none: {
id: session.uid,
},
},
genre: {
value: {
in: user.preferences.map((preference) => preference.value),
},
},
},
include: {
genre: true,
seenBy: true,
},
});

console.log('Songs found:', songs.length);

return NextResponse.json({
songs: getRandomSegment(songs, parseInt(size)),
});
};
11 changes: 11 additions & 0 deletions backend/lib/misc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const getRandomSegment = <T>(arr: T[], n: number): T[] => {
const result: T[] = [];
const indices: Set<number> = new Set();

while (indices.size < n && indices.size < arr.length) {
indices.add(Math.floor(Math.random() * arr.length));
}

indices.forEach((i) => result.push(arr[i]));
return result;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
-- CreateTable
CREATE TABLE "_SongSeenBy" (
"A" INTEGER NOT NULL,
"B" INTEGER NOT NULL,

CONSTRAINT "_SongSeenBy_AB_pkey" PRIMARY KEY ("A","B")
);

-- CreateIndex
CREATE INDEX "_SongSeenBy_B_index" ON "_SongSeenBy"("B");

-- AddForeignKey
ALTER TABLE "_SongSeenBy" ADD CONSTRAINT "_SongSeenBy_A_fkey" FOREIGN KEY ("A") REFERENCES "Song"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "_SongSeenBy" ADD CONSTRAINT "_SongSeenBy_B_fkey" FOREIGN KEY ("B") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
2 changes: 2 additions & 0 deletions backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ model User {
updatedAt DateTime @updatedAt
preferences Genre[]
likedSongs Song[]
seenSongs Song[] @relation("SongSeenBy")
}

model Song {
Expand All @@ -32,6 +33,7 @@ model Song {
likedBy User[]
genreId Int?
genre Genre? @relation(fields: [genreId], references: [id])
seenBy User[] @relation("SongSeenBy")
}