summaryrefslogtreecommitdiff
path: root/check/app/server/api.py
blob: 66a0dd1df7ef209ef3a9fd2539b2fa33c4f4fe6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import io
import os
import re
import time
import numpy as np
import logging
import urllib.request
from flask import Blueprint, request, jsonify
from PIL import Image

from app.models.sql_factory import search_by_phash, add_phash
from app.utils.im_utils import compute_phash_int
from app.utils.file_utils import sha256_stream

sanitize_re = re.compile('[\W]+')
valid_exts = ['.gif', '.jpg', '.jpeg', '.png']

MATCH_THRESHOLD = 20
MATCH_LIMIT = 10

SIMILAR_THRESHOLD = 20
SIMILAR_LIMIT = 10

api = Blueprint('api', __name__)

@api.route('/')
def index():
  """
  API status test endpoint
  """
  return jsonify({ 'status': 'ok' })

def get_params(default_threshold=MATCH_THRESHOLD, default_limit=MATCH_LIMIT):
  try:
    threshold = int(request.form.get('threshold') or default_threshold)
    limit = int(request.form.get('limit') or default_limit)
  except:
    return jsonify({
      'success': False,
      'match': False,
      'error': 'param_error'
    })

  if 'q' in request.files:
    file = request.files['q']
    fn = file.filename
    if fn.endswith('blob'): # FIX PNG IMAGES?
      logging.debug('received a blob, assuming JPEG')
      fn = 'filename.jpg'

    basename, ext = os.path.splitext(fn)
    if ext.lower() not in valid_exts:
      return jsonify({
        'success': False,
        'match': False,
        'error': 'not_an_image'
      })

    raw = None
    im = Image.open(file.stream).convert('RGB')
  else:
    url = request.form.get('url')
    if not url:
      return jsonify({
        'success': False,
        'match': False,
        'error': 'no_image'
      })
    basename, ext = os.path.splitext(url)
    if ext.lower() not in valid_exts:
      return jsonify({
        'success': False,
        'match': False,
        'error': 'not_an_image'
      })

    remote_request = urllib.request.Request(url)
    remote_response = urllib.request.urlopen(remote_request)
    raw = remote_response.read()
    im = Image.open(io.BytesIO(raw)).convert('RGB')

@api.route('/v1/match', methods=['POST'])
def match():
  """
  Search by uploading an image
  """
  start = time.time()

  threshold, limit, raw, im = get_params()

  phash = compute_phash_int(im)
  ext = ext[1:].lower()

  results = search_by_phash(phash=phash, threshold=threshold, limit=limit)

  if len(results) == 0:
    if url:
      # hash = sha256_stream(file)
      hash = sha256_stream(io.BytesIO(raw))
      add_phash(sha256=hash, phash=phash, ext=ext, url=url)
    match = False
  else:
    match = True

  logging.debug('query took {0:.2g} s.'.format(time.time() - start))

  return jsonify({
    'success': True,
    'match': match,
    'results': results,
    'timing': time.time() - start,
  })

@api.route('/v1/similar', methods=['POST'])
def similar():
  """
  Search by uploading an image
  """
  start = time.time()

  threshold, limit, raw, im = get_params(default_threshold=SIMILARITY_THRESHOLD, default_limit=SIMILARITY_LIMIT)

  phash = compute_phash_int(im)
  ext = ext[1:].lower()

  results = search_by_phash(phash=phash, threshold=threshold, limit=limit)

  if len(results) == 0:
    match = False
  else:
    match = True

  logging.debug('query took {0:.2g} s.'.format(time.time() - start))

  return jsonify({
    'success': True,
    'match': match,
    'results': results,
    'timing': time.time() - start,
  })