Skip to content

Commit

Permalink
Added Cache for images
Browse files Browse the repository at this point in the history
  • Loading branch information
snorrealv committed Apr 24, 2023
1 parent 3bd21ef commit b10eaf9
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from django.core.management.base import BaseCommand, CommandError
from handler.models import Recommendations, MoviesRanked
import os
import requests
import random
class Command(BaseCommand):
help = 'Caches image links for movies that has a rank or has been recommended to a user'



def add_arguments(self, parser):
parser.add_argument('--single-user',
type=str,
action='store',
help='If you only want to get one user',
default='',
dest='single_user'
)

parser.add_argument('--overwrite',
type=bool,
action='store',
help='If you want to overwrite previously cached images',
default=False,
dest='overwrite'
)

parser.add_argument('--clear-cache',
type=bool,
action='store',
help='To clear all cached images',
default=False,
dest='clear-cache'
)

def handle(self, *args, **options):
if options['clear-cache']:
ranked_movies = MoviesRanked.objects.all().delete()
else:
TMDB_KEY = os.environ.get('TMDB_KEY')
try:
ranked_movies = MoviesRanked.objects.all()
n = len(ranked_movies)
i = 0
for ranked_movie in ranked_movies:
if ranked_movie.cached_img_url != "not_cached" or options['overwrite']:
self.stdout.write(f'{i}/{n} || Movie {ranked_movie.movie.title} already cached.')
else:
api_url = f'https://api.themoviedb.org/3/movie/{ranked_movie.tmdbId}?api_key={TMDB_KEY}'
response = requests.get(api_url)
ranked_movie.cached_img_url = response.json()["poster_path"]
ranked_movie.save()
self.stdout.write(f'{i}/{n} || Movie {ranked_movie.movie.title}, https://image.tmdb.org/t/p/w200/{response.json()["backdrop_path"]}')

i += 1
except Exception as e:
self.stdout.write('Something went wrong: \n' + e)
7 changes: 4 additions & 3 deletions backend/web/handler/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ class MoviesRanked(models.Model):
movie = models.ForeignKey("handler.Movies", on_delete=models.CASCADE)
tmdbId = models.IntegerField()
rank = models.IntegerField()

cached_img_url = models.CharField(default='not_cached', max_length=400)
cached_background_img_url = models.CharField(default='not_cached', max_length=400)

class Movies(models.Model):
movieId = models.IntegerField(primary_key=True)
title = models.CharField(max_length=200)
Expand Down Expand Up @@ -77,8 +79,7 @@ class Recommendations(models.Model):

def movies_default():
return {"movies":["a","b","c"]}

#movies = models.JSONField('Recommendation', default=movies_default)

movies = models.ManyToManyField(MoviesRanked)

user_description_short = models.CharField(default='', max_length=500)
Expand Down
2 changes: 2 additions & 0 deletions backend/web/handler/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ class MovieSerializer(serializers.Serializer):
class MovieRankedSerializer(serializers.Serializer):
tmdbId = serializers.IntegerField()
rank = serializers.IntegerField()
cached_img_url = serializers.CharField()
cached_background_img_url = serializers.CharField()
movie = MovieSerializer()


Expand Down
26 changes: 23 additions & 3 deletions frontend/src/components/Dashboard.astro
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const {url=settings.API_SERVER_URL} = Astro.props;
<div class="profile">
<img src="/assets/mainstream.png" alt="">
</div>
<p>Judging by the rating history, this person seems to prefer very popular mainstream movies. Clasically, such users are treated better by standard recommendation algorithms, maintaining the same popularity level of suggested movies to watch. Not much change in reranking is expected here - the recommendation list is supposedly already rather fitting.</p>
<p id="user-explanation-one" class="user-text-long">Judging by the rating history, this person seems to prefer very popular mainstream movies. Clasically, such users are treated better by standard recommendation algorithms, maintaining the same popularity level of suggested movies to watch. Not much change in reranking is expected here - the recommendation list is supposedly already rather fitting.</p>
</div>
</section>
<h3 class='session_header'>What our mainstream user likes</h3>
Expand Down Expand Up @@ -81,7 +81,7 @@ const {url=settings.API_SERVER_URL} = Astro.props;
<div class="profile">
<img src="/assets/niche.png" alt="">
</div>
<p>This person is less fond of mainstream movies and potentially would not be satisfied with a standard recommendation with higher popularity. The reranking effect is expected to be more visible in such case, lowering the popularity level of recommended movies.</p>
<p id="user-explanation-two" class="user-text-long" >This person is less fond of mainstream movies and potentially would not be satisfied with a standard recommendation with higher popularity. The reranking effect is expected to be more visible in such case, lowering the popularity level of recommended movies.</p>
</div>
</section>

Expand Down Expand Up @@ -137,6 +137,9 @@ const {url=settings.API_SERVER_URL} = Astro.props;
<div class='footer_main'>
<img src="/assets/MF-LOGO-WHITE-2x.png" alt="">
<h3>Demo brought to you by SFI MediaFutures</h3>
<p>
This product uses the TMDB API but is not endorsed or certified by TMDB
</p>
</div>
</section>

Expand Down Expand Up @@ -214,6 +217,11 @@ const {url=settings.API_SERVER_URL} = Astro.props;

}

.user-text-long {
overflow: scroll;
min-height: 15rem;
max-height: 15rem;
}

.expl_one_right > a > svg {
scale: 1.5;
Expand Down Expand Up @@ -473,6 +481,12 @@ const {url=settings.API_SERVER_URL} = Astro.props;
#third {

}

@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
</style>

<script type="module" is:inline defer define:vars={{url}}>
Expand All @@ -493,8 +507,12 @@ const {url=settings.API_SERVER_URL} = Astro.props;
await Promise.all(data.movies.map(async (element, index) => {
const top20 = document.getElementById(section)
const item = top20.querySelector(`#image_item_${index}`)
if (element.cached_img_url == "not_cached") {
const item_detail = await getImageFromSource(element.tmdbId)
item.src = `https://image.tmdb.org/t/p/w200/${item_detail.poster_path}`
item.src = `https://image.tmdb.org/t/p/w200/${item_detail.poster_path}`
} else {
item.src = `https://image.tmdb.org/t/p/w200${element.cached_img_url}`
}
item.dataset.id = element.tmdbId
}))

Expand All @@ -505,11 +523,13 @@ const {url=settings.API_SERVER_URL} = Astro.props;

async function loadContent() {
// User1
const user_one_expl = document.getElementById('user-explanation-one')
getPosters(user1, 'first', 'original')
getPosters(user1, 'second', 'SVD')
getPosters(user1, 'third', 'SVD-Reranked')

// User2
const user_two_expl = document.getElementById('user-explanation-one')
getPosters(user2, 'fourth', 'original')
getPosters(user2, 'fifth', 'SVD')
getPosters(user2, 'sixth', 'SVD-Reranked')
Expand Down

0 comments on commit b10eaf9

Please sign in to comment.