Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os, uuid, shutil
|
2 |
+
from flask import Flask, request, jsonify
|
3 |
+
from PIL import Image
|
4 |
+
import face_recognition
|
5 |
+
import requests
|
6 |
+
from io import BytesIO
|
7 |
+
from bs4 import BeautifulSoup
|
8 |
+
|
9 |
+
TMP_DIR = "temp"
|
10 |
+
os.makedirs(TMP_DIR, exist_ok=True)
|
11 |
+
|
12 |
+
app = Flask(__name__)
|
13 |
+
|
14 |
+
def scrape_yandex_reverse(image_bytes):
|
15 |
+
session = requests.Session()
|
16 |
+
headers = {"User-Agent": "Mozilla/5.0"}
|
17 |
+
|
18 |
+
temp_path = os.path.join(TMP_DIR, f"{uuid.uuid4().hex}.jpg")
|
19 |
+
with open(temp_path, "wb") as f:
|
20 |
+
f.write(image_bytes)
|
21 |
+
|
22 |
+
files = {"upfile": open(temp_path, "rb")}
|
23 |
+
upload_url = "https://yandex.com/images/search"
|
24 |
+
r = session.post(upload_url, files=files, headers=headers, allow_redirects=True)
|
25 |
+
search_url = r.url
|
26 |
+
|
27 |
+
r2 = session.get(search_url, headers=headers)
|
28 |
+
soup = BeautifulSoup(r2.text, "html.parser")
|
29 |
+
image_elements = soup.select("img.serp-item__thumb")
|
30 |
+
image_links = [img.get("src") for img in image_elements if img.get("src")]
|
31 |
+
|
32 |
+
return image_links[:10]
|
33 |
+
|
34 |
+
@app.route('/upload', methods=['POST'])
|
35 |
+
def upload():
|
36 |
+
if 'image' not in request.files:
|
37 |
+
return jsonify({"error": "No image uploaded"}), 400
|
38 |
+
|
39 |
+
uploaded = request.files['image']
|
40 |
+
image = face_recognition.load_image_file(uploaded)
|
41 |
+
try:
|
42 |
+
original_enc = face_recognition.face_encodings(image)[0]
|
43 |
+
except:
|
44 |
+
return jsonify({"error": "No face found"}), 400
|
45 |
+
|
46 |
+
matches = []
|
47 |
+
image_bytes = uploaded.read()
|
48 |
+
results = scrape_yandex_reverse(image_bytes)
|
49 |
+
|
50 |
+
for link in results:
|
51 |
+
try:
|
52 |
+
response = requests.get(link, timeout=6)
|
53 |
+
img = Image.open(BytesIO(response.content)).convert("RGB")
|
54 |
+
path = os.path.join(TMP_DIR, f"{uuid.uuid4().hex}.jpg")
|
55 |
+
img.save(path)
|
56 |
+
|
57 |
+
comp = face_recognition.load_image_file(path)
|
58 |
+
encs = face_recognition.face_encodings(comp)
|
59 |
+
for enc in encs:
|
60 |
+
if face_recognition.compare_faces([original_enc], enc, tolerance=0.5)[0]:
|
61 |
+
matches.append({"image_url": link, "source_url": link})
|
62 |
+
break
|
63 |
+
except:
|
64 |
+
continue
|
65 |
+
|
66 |
+
shutil.rmtree(TMP_DIR)
|
67 |
+
os.makedirs(TMP_DIR, exist_ok=True)
|
68 |
+
return jsonify({"matches": matches})
|
69 |
+
|
70 |
+
if __name__ == '__main__':
|
71 |
+
app.run(host="0.0.0.0", port=7860)
|