Skip to content

Commit

Permalink
update mr
Browse files Browse the repository at this point in the history
  • Loading branch information
MaertHaekkinen committed Nov 6, 2022
1 parent 2a31d53 commit 4c2d6ab
Show file tree
Hide file tree
Showing 20 changed files with 352 additions and 341 deletions.
14 changes: 6 additions & 8 deletions ajapaik/ajapaik/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import math

from PIL import Image, ImageOps
from django.contrib import admin
from django.contrib.admin import ModelAdmin
Expand Down Expand Up @@ -52,16 +54,12 @@ class DatingConfirmationAdmin(ModelAdmin):
class PhotoAdmin(ModelAdmin):
@staticmethod
def _distance_between_two_points_on_sphere(lon_1, lat_1, lon_2, lat_2):
import math

rad = math.pi / 180.0
equatorial_radius_meters = 6378137
lon_1_rad = lon_1 * rad
lat_1_rad = lat_1 * rad
lon_2_rad = lon_2 * rad
lat_2_rad = lat_2 * rad
cos_angle = math.sin(lat_1_rad) * math.sin(lat_2_rad) + math.cos(lat_1_rad) * math.cos(lat_2_rad) * math.cos(
lon_2_rad - lon_1_rad)

cos_angle = math.sin(lat_1 * rad) * math.sin(lat_2 * rad) + math.cos(lat_1 * rad) * math.cos(
lat_2 * rad) * math.cos(rad * (lon_2 - lon_1))

if cos_angle >= 1:
return 0
Expand All @@ -82,7 +80,7 @@ def save_model(self, request, obj, form, change):
else:
continue

geotag.save(changed_fields=["is_correct"])
geotag.save(update_fields=["is_correct"])
obj.save()

extra_buttons = [
Expand Down
53 changes: 27 additions & 26 deletions ajapaik/ajapaik/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,7 @@ def _handle_request(self, data, user, request):
photos = Photo.objects.filter(rephoto_of__isnull=True, ).annotate(
distance=GeometryDistance("geography", ref_location)).order_by("distance")[start:end]
photo_ids = photos.values_list('id', flat=True)
photos = Photo.objects.filter(id__in=photo_ids).order_by(GeometryDistance("geography", ref_location));
photos = Photo.objects.filter(id__in=photo_ids).order_by(GeometryDistance("geography", ref_location))

photos = PhotoSerializer.annotate_photos(
photos,
Expand Down Expand Up @@ -730,11 +730,11 @@ class AlbumPhotoInformation(AjapaikAPIView):
API endpoint to retrieve album details.
'''

def get(self, album_id: int, photo_id: int):
def get(self, album_id: int, photo: int):
album = get_object_or_404(Album, id=album_id)
album_photo = AlbumPhoto.objects.filter(
album_id=album_id,
photo_id=photo_id,
photo_id=photo,
profile__isnull=False
).order_by('-created').first()

Expand Down Expand Up @@ -1646,6 +1646,13 @@ def post(self, request, format=None):
user = get_object_or_404(Profile, pk=request.user.profile.id)
count = Transcription.objects.filter(photo=photo, text=request.POST['text']).count()
text = request.POST['text']
transcriptions_with_same_text = Transcription.objects.filter(photo=photo, text=text)

for transcriptions_with_same_text in transcriptions_with_same_text:
TranscriptionFeedback(
user=user,
transcription=transcriptions_with_same_text
).save()

if count < 1:
previous_transcription_by_current_user = Transcription.objects.filter(photo=photo, user=user).first()
Expand All @@ -1667,23 +1674,16 @@ def post(self, request, format=None):
photo.transcription_count += 1
photo.light_save()

transcriptions_with_same_text = Transcription.objects.filter(photo=photo, text=text)
for transcription in transcriptions_with_same_text:
TranscriptionFeedback(
user=user,
transcription=transcription
).save()
if previous_transcription_by_current_user:
return JsonResponse({'message': TRANSCRIPTION_UPDATED})
else:
return JsonResponse({'message': TRANSCRIPTION_ADDED})

if count > 0:
else:
if transcriptions_with_same_text.exists():
return JsonResponse({'message': TRANSCRIPTION_ALREADY_EXISTS})
else:
return JsonResponse({'message': TRANSCRIPTION_ALREADY_SUBMITTED})
else:
if previous_transcription_by_current_user:
return JsonResponse({'message': TRANSCRIPTION_UPDATED})
else:
return JsonResponse({'message': TRANSCRIPTION_ADDED})
except: # noqa
return JsonResponse({'error': _('Something went wrong')}, status=500)

Expand Down Expand Up @@ -1895,7 +1895,7 @@ def post(self, request, collection_id):
return JsonResponse({'message': 'Done'})

def delete(self, request, collection_id):
collection = MuisCollection.filter(id=collection_id)
collection = MuisCollection.objects.filter(id=collection_id)
collection.blacklisted = True
collection.save()
return JsonResponse({'message': 'Done'})
Expand Down Expand Up @@ -1952,14 +1952,18 @@ def get(self, request, photo_id, format=None):
return JsonResponse({'error': _('Something went wrong')}, status=500)

def post(self, request, format=None):
profile = request.user.profile
data = json.loads(request.body.decode('utf-8'))
photo_ids = data['photoIds']

if not photo_ids:
return JsonResponse({'error': MISSING_PARAMETER_PHOTO_IDS}, status=400)

flip = data['flip']
invert = data['invert']
rotated = data['rotated']
photo_ids = data['photoIds']
was_rotate_successful = False
response = ''

if flip is None and invert is None and rotated is None:
return JsonResponse({'error': MISSING_PARAMETER_FLIP_INVERT_ROTATE}, status=400)

if flip == 'undefined':
flip = None
Expand All @@ -1970,12 +1974,9 @@ def post(self, request, format=None):
if rotated == 'undefined':
rotated = None

if photo_ids is None:
return JsonResponse({'error': MISSING_PARAMETER_PHOTO_IDS}, status=400)

if flip is None and invert is None and rotated is None:
return JsonResponse({'error': MISSING_PARAMETER_FLIP_INVERT_ROTATE}, status=400)

profile = request.user.profile
was_rotate_successful = False
response = ''
photo_flip_suggestions = []
photo_rotated_suggestions = []
photo_invert_suggestions = []
Expand Down
2 changes: 1 addition & 1 deletion ajapaik/ajapaik/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class SignupForm(AllauthSignupForm):
def signup(self, _, user):
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save(changed_fields=['first_name', 'last_name'])
user.save(update_fields=['first_name', 'last_name'])
return user


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ def handle(self, *args, **options):
similarity_type=0).exists() or \
ImageSimilarity.objects.filter(to_photo_id=photo.id).exclude(similarity_type=0).exists()
photo.has_similar = has_similar
photo.save(changed_fields=["has_similar"])
photo.save(update_fields=["has_similar"])
except IndexError:
pass
2 changes: 1 addition & 1 deletion ajapaik/ajapaik/management/commands/get_fb_comments.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def handle(self, *args, **options):
for comment in v['data']:
if existing_comment := PhotoComment.objects.filter(fb_comment_id=comment['id']).first():
existing_comment.text = comment['message']
existing_comment.save(changed_fields=['message'])
existing_comment.save(update_fields=['message'])
else:
object_id = comment['id'].split('_')[0]
new_photo_comment = PhotoComment(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def handle(self, *args, **options):
if albums_linking_to_other_instances is not None:
for link in albums_linking_to_other_instances:
link.subalbum_of = first_instance
link.save(changed_fields=["subalbum_of"])
link.save(update_fields=["subalbum_of"])
link.save()

for other_instance in other_instances:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ def handle(self, *args, **options):
elif each.user.first_name and each.user.last_name:
each.first_name = each.user.first_name
each.last_name = each.user.last_name
each.save(changed_fields=['first_name', 'last_name'])
each.save(update_fields=['first_name', 'last_name'])
2 changes: 1 addition & 1 deletion ajapaik/ajapaik/mediawiki/mediawiki.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def get_wikimedia_api_client(user):
if 'access_token' in token:
social_token.token = token["access_token"]
social_token.token_secret = token["refresh_token"]
social_token.save(changed_fields=['toke', 'token_secret'])
social_token.save(update_fields=['toke', 'token_secret'])
print("Refreshing token OK")
else:
print("Refreshing token failed")
Expand Down
10 changes: 5 additions & 5 deletions ajapaik/ajapaik/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,13 +163,13 @@ def _make_fullscreen(photo):
}


def _get_pseudo_slug_for_photo(description: str, source_key: str, id: int):
def _get_pseudo_slug_for_photo(description: str | None, source_key: str | None, photo_id: int):
if description:
slug = '-'.join(slugify(description).split('-')[:6])[:60]
elif source_key:
slug = slugify(source_key)
else:
slug = slugify(id)
slug = slugify(photo_id)

return slug

Expand Down Expand Up @@ -993,7 +993,7 @@ def do_rotate(self, degrees):
object_recognition_rectangle.x2 = self.width - top
object_recognition_rectangle.y2 = right
object_recognition_rectangle.x1 = self.width - bottom
object_recognition_rectangle.save(changed_fields=['x1', 'x2', 'y1', 'y2'])
object_recognition_rectangle.save(update_fields=['x1', 'x2', 'y1', 'y2'])

self.light_save()

Expand Down Expand Up @@ -1389,8 +1389,8 @@ def __update__(self, qs):
from_photo_id=from_photo.id).exclude(similarity_type=0).first() is not None
from_photo.has_similar = ImageSimilarity.objects.filter(
from_photo_id=to_photo.id).exclude(similarity_type=0).first() is not None
image_similarity.from_photo.save(changed_fields=['has_similar'])
image_similarity.to_photo.save(changed_fields=['has_similar'])
image_similarity.from_photo.save(update_fields=['has_similar'])
image_similarity.to_photo.save(update_fields=['has_similar'])

if suggestions.filter(proposer=self.user_last_modified).count() < 1:
return 10, suggestion
Expand Down
12 changes: 6 additions & 6 deletions ajapaik/ajapaik/phash.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import (absolute_import, division, print_function)

import numpy
import scipy.fftpack
from PIL import Image


Expand All @@ -11,23 +12,22 @@ def __init__(self, binary_array):
self.hash = binary_array


def binaryhash_to_signed_integer(hash: list[bool]) -> int:
def binary_hash_to_signed_integer(binary_hash: list[bool]) -> int:
result = ""
for i in hash:
for i in binary_hash:
if i:
result += '1'
else:
result += '0'
if (result[0] == '1'):
if result[0] == '1':
temp = result[1:].replace('1', '2').replace('0', '1').replace('2', '0')
return (-1 * int(temp, base=2) - 1)
return -1 * int(temp, base=2) - 1
return int(result, base=2)


def phash(image: Image, hash_size: int = 8, highfreq_factor: int = 4) -> int:
if hash_size < 2:
raise ValueError('Hash size must be greater than or equal to 2')
import scipy.fftpack
img_size = hash_size * highfreq_factor
image = image.convert('L').resize((img_size, img_size), Image.ANTIALIAS)
pixels = numpy.asarray(image)
Expand All @@ -37,4 +37,4 @@ def phash(image: Image, hash_size: int = 8, highfreq_factor: int = 4) -> int:
diff = dctlowfreq > med
result = ImageHash(diff)

return binaryhash_to_signed_integer(result.hash.flatten())
return binary_hash_to_signed_integer(result.hash.flatten())
26 changes: 13 additions & 13 deletions ajapaik/ajapaik/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,10 @@ class CuratorAlbumInfoSerializer(serializers.ModelSerializer):
parent_album_id = serializers.SerializerMethodField()
parent_album_name = serializers.SerializerMethodField()

def get_parent_album_id(self, obj):
def get_parent_album_id(self, obj: Album):
return obj.subalbum_of.id if obj.subalbum_of else None

def get_parent_album_name(self, obj):
def get_parent_album_name(self, obj: Album):
return obj.subalbum_of.name if obj.subalbum_of else None

class Meta:
Expand Down Expand Up @@ -210,21 +210,21 @@ def annotate_photos(cls, photos_queryset, user_profile):
.annotate(favorited=Case(When(Q(likes__profile=user_profile) & Q(likes__profile__isnull=False),
then=Value(True)), default=Value(False), output_field=BooleanField()))

def get_display_text(self, instance):
def get_display_text(self, instance: Photo):
return instance.get_display_text

def get_full_image(self, instance):
def get_full_image(self, instance: Photo):
request = self.context['request']
image_name=str(instance.image)
prefix='uploads/'
image_name = str(instance.image)
prefix = 'uploads/'

if image_name.startswith(prefix):
image_name=image_name[len(prefix):]
image_name = image_name[len(prefix):]

iiif_jpeg=request.build_absolute_uri(f'/iiif/work/iiif/ajapaik/{image_name}.tif/full/max/0/default.jpg')
iiif_jpeg = request.build_absolute_uri(f'/iiif/work/iiif/ajapaik/{image_name}.tif/full/max/0/default.jpg')
return iiif_jpeg

def get_image(self, instance):
def get_image(self, instance: Photo):
request = self.context['request']
relative_url = reverse('image_thumb', args=(instance.id,))

Expand All @@ -236,7 +236,7 @@ def get_date(self, instance):
else:
return instance.date_text

def get_source(self, instance):
def get_source(self, instance: Photo):
if instance.source:
source_key = instance.source_key or ''
return {
Expand All @@ -248,7 +248,7 @@ def get_source(self, instance):
'url': instance.source_url,
}

def get_rephotos(self, instance):
def get_rephotos(self, instance: Photo):
return RephotoSerializer(
instance=instance.rephotos.all(),
many=True,
Expand Down Expand Up @@ -298,13 +298,13 @@ def get_image(self, instance):
relative_url = reverse('image_thumb', args=(instance.id,))
return '{}[DIM]/'.format(request.build_absolute_uri(relative_url))

def get_date(self, instance):
def get_date(self, instance: Photo):
if instance.date:
return instance.date.strftime('%d-%m-%Y')
else:
return instance.date_text

def get_source(self, instance):
def get_source(self, instance: Photo):
if instance.source:
source_key = instance.source_key or ''
return {
Expand Down
34 changes: 17 additions & 17 deletions ajapaik/ajapaik/tests/test_phash.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
from PIL import Image, ImageDraw

from ajapaik.ajapaik.phash import binaryhash_to_signed_integer, phash
from ajapaik.ajapaik.phash import binary_hash_to_signed_integer, phash


def test_binaryhash_to_signed_integer():
assert(binaryhash_to_signed_integer([True, False, False, True, False,
False, False, False, True, False,
True, True, True, True, False,
True, True, True, False, True,
True, True, True, False, True,
False, True, False, False, False,
False, False, False, True, True,
True, True, False, False, False,
True, False, False, False, True,
False, True, False, False, True,
False, False, True, True, True,
False, True, True, False, False,
True, False, True, True])) == -8017006980851151157
assert binaryhash_to_signed_integer([True]*64) == -1
assert binaryhash_to_signed_integer([False]*64) == 0
def test_binary_hash_to_signed_integer():
assert (binary_hash_to_signed_integer([True, False, False, True, False,
False, False, False, True, False,
True, True, True, True, False,
True, True, True, False, True,
True, True, True, False, True,
False, True, False, False, False,
False, False, False, True, True,
True, True, False, False, False,
True, False, False, False, True,
False, True, False, False, True,
False, False, True, True, True,
False, True, True, False, False,
True, False, True, True])) == -8017006980851151157
assert binary_hash_to_signed_integer([True] * 64) == -1
assert binary_hash_to_signed_integer([False] * 64) == 0


def test_phash():
Expand Down
Loading

0 comments on commit 4c2d6ab

Please sign in to comment.