46 lines
1.2 KiB
PHP
46 lines
1.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services\Recommendations;
|
|
|
|
use App\Models\Artwork;
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
final class SimilarArtworksService
|
|
{
|
|
/**
|
|
* @return Collection<int, Artwork>
|
|
*/
|
|
public function forArtwork(int $artworkId, int $limit = 12, ?string $algoVersion = null): Collection
|
|
{
|
|
$effectiveAlgo = $algoVersion ?: (string) config('recommendations.embedding.algo_version', 'clip-cosine-v1');
|
|
|
|
$ids = DB::table('artwork_similarities')
|
|
->where('artwork_id', $artworkId)
|
|
->where('algo_version', $effectiveAlgo)
|
|
->orderBy('rank')
|
|
->limit(max(1, min($limit, 50)))
|
|
->pluck('similar_artwork_id')
|
|
->map(static fn ($id) => (int) $id)
|
|
->all();
|
|
|
|
if ($ids === []) {
|
|
return collect();
|
|
}
|
|
|
|
$artworks = Artwork::query()
|
|
->whereIn('id', $ids)
|
|
->public()
|
|
->published()
|
|
->get();
|
|
|
|
$byId = $artworks->keyBy('id');
|
|
|
|
return collect($ids)
|
|
->map(static fn (int $id) => $byId->get($id))
|
|
->filter();
|
|
}
|
|
}
|