Spaces:
Sleeping
Sleeping
Ruzzel Mendoza commited on
Commit ·
887791e
0
Parent(s):
Clean Deployment for Hugging Face
Browse files- .gitignore +54 -0
- api/art_classification.py +16 -0
- api/plagiarism.py +135 -0
- api/test.py +20 -0
- lib/cloudinary_service.py +43 -0
- lib/hugging_face.py +36 -0
- lib/phash.py +305 -0
- lib/serp_service.py +23 -0
- main.py +22 -0
- requirements.txt +0 -0
- router.py +14 -0
- test_main.http +11 -0
.gitignore
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Byte-compiled / optimized / DLL files
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
|
| 6 |
+
# Environments
|
| 7 |
+
.venv/
|
| 8 |
+
venv/
|
| 9 |
+
ENV/
|
| 10 |
+
env/
|
| 11 |
+
bin/
|
| 12 |
+
include/
|
| 13 |
+
|
| 14 |
+
# Secrets and Config
|
| 15 |
+
.env
|
| 16 |
+
.flaskenv
|
| 17 |
+
*.secrets
|
| 18 |
+
secrets.py
|
| 19 |
+
|
| 20 |
+
# Databases (SQLite)
|
| 21 |
+
*.sqlite3
|
| 22 |
+
*.db
|
| 23 |
+
|
| 24 |
+
# Distribution / packaging
|
| 25 |
+
dist/
|
| 26 |
+
build/
|
| 27 |
+
*.egg-info/
|
| 28 |
+
|
| 29 |
+
# Unit test / coverage reports
|
| 30 |
+
htmlcov/
|
| 31 |
+
.tox/
|
| 32 |
+
.nox/
|
| 33 |
+
.coverage
|
| 34 |
+
.cache
|
| 35 |
+
nosetests.xml
|
| 36 |
+
coverage.xml
|
| 37 |
+
*.cover
|
| 38 |
+
.hypothesis/
|
| 39 |
+
.pytest_cache/
|
| 40 |
+
|
| 41 |
+
# IDE specific files
|
| 42 |
+
.vscode/
|
| 43 |
+
.idea/
|
| 44 |
+
*.swp
|
| 45 |
+
*.swo
|
| 46 |
+
|
| 47 |
+
# OS generated files
|
| 48 |
+
.DS_Store
|
| 49 |
+
Thumbs.db
|
| 50 |
+
|
| 51 |
+
*.jpg
|
| 52 |
+
*.jpeg
|
| 53 |
+
*.png
|
| 54 |
+
*.webp
|
api/art_classification.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, UploadFile, File, HTTPException, status
|
| 2 |
+
from lib.hugging_face import classify_art
|
| 3 |
+
|
| 4 |
+
router = APIRouter()
|
| 5 |
+
|
| 6 |
+
@router.post("/")
|
| 7 |
+
async def classify(file: UploadFile = File(...)):
|
| 8 |
+
allowed_types = ["image/jpeg", "image/png"]
|
| 9 |
+
|
| 10 |
+
if file.content_type not in allowed_types:
|
| 11 |
+
raise HTTPException(
|
| 12 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 13 |
+
detail="Invalid file type. Only JPEG and PNG are allowed."
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
return await classify_art(file)
|
api/plagiarism.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
|
| 3 |
+
from fastapi import APIRouter, UploadFile, File, HTTPException
|
| 4 |
+
from numpy.f2py.auxfuncs import throw_error
|
| 5 |
+
from starlette.websockets import WebSocket
|
| 6 |
+
|
| 7 |
+
from lib.phash import generate_hashes, generate_hash_from_serp, check_distance_between_serp, \
|
| 8 |
+
compare_two_hashes
|
| 9 |
+
from lib.cloudinary_service import cloudinary_uploader, delete_image
|
| 10 |
+
from lib.serp_service import serp_image_search
|
| 11 |
+
|
| 12 |
+
router = APIRouter()
|
| 13 |
+
|
| 14 |
+
@router.get("/", tags=["Plagiarism"])
|
| 15 |
+
async def root():
|
| 16 |
+
return {"message": "Hello World"}
|
| 17 |
+
|
| 18 |
+
@router.websocket("/check/web")
|
| 19 |
+
async def plagiarism_web_check(websocket: WebSocket):
|
| 20 |
+
|
| 21 |
+
await websocket.accept()
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
Pipeline for this route:
|
| 25 |
+
1. Hash the uploaded image
|
| 26 |
+
2. Upload the image to cloudinary
|
| 27 |
+
3. Scan the uploaded image to SerpAPI for reverse image scan
|
| 28 |
+
4. Generate hashes for all the scanned images by SerpAPI
|
| 29 |
+
5. Compare the hashes against the uploaded image
|
| 30 |
+
6. Return a similarity percentage/index score
|
| 31 |
+
:param file:
|
| 32 |
+
:return: similarity percentage/index score
|
| 33 |
+
"""
|
| 34 |
+
try:
|
| 35 |
+
data = await websocket.receive_json()
|
| 36 |
+
filename = data["filename"]
|
| 37 |
+
file_bytes = base64.b64decode(data["file"])
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
from io import BytesIO
|
| 41 |
+
file = BytesIO(file_bytes)
|
| 42 |
+
|
| 43 |
+
await websocket.send_json({"progress": 5, "stage": "validating file"})
|
| 44 |
+
|
| 45 |
+
hashes = generate_hashes(file)
|
| 46 |
+
|
| 47 |
+
if hashes is None:
|
| 48 |
+
await websocket.send_json({"error": "Failed to generate hashes"})
|
| 49 |
+
return
|
| 50 |
+
|
| 51 |
+
await websocket.send_json({"progress": 20, "stage": "uploading image"})
|
| 52 |
+
|
| 53 |
+
upload_file = UploadFile(
|
| 54 |
+
filename=data["filename"],
|
| 55 |
+
file=file,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
upload_response = cloudinary_uploader(upload_file)
|
| 59 |
+
|
| 60 |
+
await websocket.send_json({"progress": 40, "stage": "reverse image search"})
|
| 61 |
+
|
| 62 |
+
searched_images = serp_image_search(upload_response["secure_url"])
|
| 63 |
+
|
| 64 |
+
await websocket.send_json({"progress": 60, "stage": "generating hashes from serp results"})
|
| 65 |
+
|
| 66 |
+
generated_hashes = generate_hash_from_serp(searched_images)
|
| 67 |
+
|
| 68 |
+
await websocket.send_json({"progress": 80, "stage": "comparing hashes"})
|
| 69 |
+
|
| 70 |
+
distances = check_distance_between_serp(hashes, generated_hashes)
|
| 71 |
+
|
| 72 |
+
success = delete_image(upload_response["public_id"])
|
| 73 |
+
|
| 74 |
+
await websocket.send_json( {
|
| 75 |
+
"progress": 100,
|
| 76 |
+
"stage": "completed",
|
| 77 |
+
"result": {
|
| 78 |
+
"filename": filename,
|
| 79 |
+
"hashes": hashes,
|
| 80 |
+
"distances": distances,
|
| 81 |
+
"success": success,
|
| 82 |
+
}
|
| 83 |
+
})
|
| 84 |
+
|
| 85 |
+
await websocket.close()
|
| 86 |
+
|
| 87 |
+
except Exception as e:
|
| 88 |
+
await websocket.send_json({"error": str(e)})
|
| 89 |
+
await websocket.close()
|
| 90 |
+
|
| 91 |
+
@router.websocket("/check")
|
| 92 |
+
async def plagiarism_check(websocket: WebSocket):
|
| 93 |
+
|
| 94 |
+
await websocket.accept()
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
data = await websocket.receive_json()
|
| 98 |
+
|
| 99 |
+
import base64
|
| 100 |
+
from io import BytesIO
|
| 101 |
+
|
| 102 |
+
file1 = BytesIO(base64.b64decode(data["file1"]))
|
| 103 |
+
file2 = BytesIO(base64.b64decode(data["file2"]))
|
| 104 |
+
filename1 = data["filename1"]
|
| 105 |
+
filename2 = data["filename2"]
|
| 106 |
+
|
| 107 |
+
await websocket.send_json({"progress": 25, "stage": "generating hash 1"})
|
| 108 |
+
hash1 = generate_hashes(file1)
|
| 109 |
+
|
| 110 |
+
await websocket.send_json({"progress": 50, "stage": "generating hash 2"})
|
| 111 |
+
hash2 = generate_hashes(file2)
|
| 112 |
+
|
| 113 |
+
if hash1 is None or hash2 is None:
|
| 114 |
+
await websocket.send_json({"error": "Failed to generate hashes"})
|
| 115 |
+
return
|
| 116 |
+
|
| 117 |
+
await websocket.send_json({"progress": 80, "stage": "comparing hashes"})
|
| 118 |
+
|
| 119 |
+
distance = compare_two_hashes(hash1, hash2)
|
| 120 |
+
|
| 121 |
+
await websocket.send_json({
|
| 122 |
+
"progress": 100,
|
| 123 |
+
"stage": "completed",
|
| 124 |
+
"result": {
|
| 125 |
+
"filename1": filename1,
|
| 126 |
+
"filename2": filename2,
|
| 127 |
+
"distance": distance,
|
| 128 |
+
"hash1": hash1,
|
| 129 |
+
"hash2": hash2
|
| 130 |
+
}
|
| 131 |
+
})
|
| 132 |
+
|
| 133 |
+
except Exception as e:
|
| 134 |
+
await websocket.send_json({"error": str(e)})
|
| 135 |
+
await websocket.close()
|
api/test.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
|
| 3 |
+
from fastapi import APIRouter
|
| 4 |
+
router = APIRouter()
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@router.get("/")
|
| 8 |
+
async def root():
|
| 9 |
+
return {"message": "Hello World"}
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@router.get("/hello/{name}")
|
| 13 |
+
async def say_hello(name: str):
|
| 14 |
+
return {"message": f"Hello {name}"}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# with open("C:\\Users\\mendo\\Downloads\\643662567_1310948180867431_7223931227735271979_n.jpg", "rb") as f:
|
| 18 |
+
# encoded = base64.b64encode(f.read()).decode()
|
| 19 |
+
#
|
| 20 |
+
# print(encoded)
|
lib/cloudinary_service.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cloudinary
|
| 2 |
+
import cloudinary.uploader
|
| 3 |
+
import os
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
from fastapi import HTTPException, UploadFile, File
|
| 6 |
+
|
| 7 |
+
load_dotenv()
|
| 8 |
+
|
| 9 |
+
cloudinary.config(
|
| 10 |
+
cloud_name=os.getenv("CLOUDINARY_NAME"),
|
| 11 |
+
api_key=os.getenv("CLOUDINARY_KEY"),
|
| 12 |
+
api_secret=os.getenv("CLOUDINARY_SECRET"),
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
def cloudinary_uploader(image_file: UploadFile = File(...)):
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
|
| 19 |
+
image_file.file.seek(0)
|
| 20 |
+
|
| 21 |
+
response = cloudinary.uploader.upload(
|
| 22 |
+
image_file.file,
|
| 23 |
+
resource_type="image",
|
| 24 |
+
folder="temp_plag_scans",
|
| 25 |
+
)
|
| 26 |
+
return response
|
| 27 |
+
except Exception as e:
|
| 28 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def delete_image(public_id):
|
| 32 |
+
try:
|
| 33 |
+
result = cloudinary.uploader.destroy(
|
| 34 |
+
public_id,
|
| 35 |
+
invalidate=True,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
if result.get("result") == "ok":
|
| 39 |
+
return True
|
| 40 |
+
else:
|
| 41 |
+
return False
|
| 42 |
+
except Exception as e:
|
| 43 |
+
raise HTTPException(status_code=400, detail=str(e))
|
lib/hugging_face.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from fastapi import UploadFile, File
|
| 5 |
+
from transformers import pipeline
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# Load Google's SigLIP model for zero-shot classification
|
| 9 |
+
print("Loading SigLIP Zero-Shot Model...")
|
| 10 |
+
classifier = pipeline(
|
| 11 |
+
"zero-shot-image-classification",
|
| 12 |
+
model="google/siglip-base-patch16-224"
|
| 13 |
+
)
|
| 14 |
+
print("Model loaded successfully!")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
DIGITAL_ART_GENRES = [
|
| 18 |
+
"Anime", "Manga", "Cartoon", "Semi-Realism", "Realism",
|
| 19 |
+
"Hyperrealism", "Abstract", "Minimalist", "Impressionism",
|
| 20 |
+
"Surrealism", "Pop Art", "Pixel Art", "Low Poly",
|
| 21 |
+
"Vector Art", "Line Art", "Sketch Art", "Flat Design",
|
| 22 |
+
"3D Render", "Isometric"
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
async def classify_art(file: UploadFile = File(...)):
|
| 27 |
+
try:
|
| 28 |
+
image_bytes = await file.read()
|
| 29 |
+
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 30 |
+
|
| 31 |
+
results = classifier(image, candidate_labels=DIGITAL_ART_GENRES)
|
| 32 |
+
|
| 33 |
+
return {"success": True, "results": results}
|
| 34 |
+
|
| 35 |
+
except Exception as e:
|
| 36 |
+
return {"success": False, "error": str(e)}
|
lib/phash.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from io import BytesIO
|
| 2 |
+
from typing import Dict, Any
|
| 3 |
+
|
| 4 |
+
import requests
|
| 5 |
+
from PIL import Image, ImageOps, ImageFilter
|
| 6 |
+
import imagehash
|
| 7 |
+
|
| 8 |
+
def preprocess_image(img):
|
| 9 |
+
"""
|
| 10 |
+
Standardizes image before hashing:
|
| 11 |
+
- Removes alpha channel
|
| 12 |
+
- Converts to RGB
|
| 13 |
+
- Converts to grayscale
|
| 14 |
+
- Applies slight Gaussian blur (compression robustness)
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
# Remove alpha channel if present
|
| 18 |
+
if img.mode in ("RGBA", "LA"):
|
| 19 |
+
background = Image.new("RGB", img.size, (255, 255, 255))
|
| 20 |
+
background.paste(img, mask=img.split()[-1])
|
| 21 |
+
img = background
|
| 22 |
+
else:
|
| 23 |
+
img = img.convert("RGB")
|
| 24 |
+
|
| 25 |
+
# Convert to grayscale
|
| 26 |
+
img = img.convert("L")
|
| 27 |
+
|
| 28 |
+
# Reduce compression artifacts
|
| 29 |
+
img = img.filter(ImageFilter.GaussianBlur(radius=1))
|
| 30 |
+
|
| 31 |
+
return img
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def generate_hashes(image_file, hash_size=8):
|
| 35 |
+
"""
|
| 36 |
+
Generates multiple perceptual hashes (pHash, dHash, wHash)
|
| 37 |
+
for rotated and flipped variants of an image.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
img = Image.open(image_file)
|
| 42 |
+
img = preprocess_image(img)
|
| 43 |
+
|
| 44 |
+
images = {
|
| 45 |
+
"0": img,
|
| 46 |
+
"90": img.rotate(90, expand=True),
|
| 47 |
+
"180": img.rotate(180, expand=True),
|
| 48 |
+
"270": img.rotate(270, expand=True),
|
| 49 |
+
"mirror": ImageOps.mirror(img),
|
| 50 |
+
"flip": ImageOps.flip(img),
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
hashed_images = {}
|
| 54 |
+
|
| 55 |
+
for key, value in images.items():
|
| 56 |
+
hashed_images[key] = {
|
| 57 |
+
"phash": str(imagehash.phash(value, hash_size=hash_size)),
|
| 58 |
+
"dhash": str(imagehash.dhash(value, hash_size=hash_size)),
|
| 59 |
+
"whash": str(imagehash.whash(value, hash_size=hash_size)),
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
return hashed_images
|
| 63 |
+
|
| 64 |
+
except Exception as e:
|
| 65 |
+
print(f"Error generating hashes: {e}")
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
def generate_phash_from_img_url(image_url):
|
| 69 |
+
"""
|
| 70 |
+
Downloads an image from a URL and passes it to generate_phash.
|
| 71 |
+
"""
|
| 72 |
+
try:
|
| 73 |
+
# 1. Fetch the image from the URL
|
| 74 |
+
# Adding a User-Agent header helps bypass basic bot blocks on some image hosts
|
| 75 |
+
headers = {'User-Agent': 'Mozilla/5.0'}
|
| 76 |
+
response = requests.get(image_url, headers=headers, stream=True, timeout=10)
|
| 77 |
+
|
| 78 |
+
# Raise an exception if the download failed (e.g., 404 or 403)
|
| 79 |
+
response.raise_for_status()
|
| 80 |
+
|
| 81 |
+
# 2. Convert the raw bytes into a file-like object
|
| 82 |
+
image_file = BytesIO(response.content)
|
| 83 |
+
|
| 84 |
+
# 3. Pass it to your original function
|
| 85 |
+
return generate_hashes(image_file)
|
| 86 |
+
|
| 87 |
+
except requests.exceptions.RequestException as e:
|
| 88 |
+
print(f"Network error fetching {image_url}: {e}")
|
| 89 |
+
return None
|
| 90 |
+
except Exception as e:
|
| 91 |
+
print(f"Error processing {image_url}: {e}")
|
| 92 |
+
return None
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def check_distance(hash1: str, hash2: str):
|
| 96 |
+
return imagehash.hex_to_hash(hash1) - imagehash.hex_to_hash(hash2)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def compute_weighted_distance(hash_set1, hash_set2, weights=None):
|
| 100 |
+
"""
|
| 101 |
+
Computes weighted Hamming distance across multiple hashing algorithms.
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
if weights is None:
|
| 105 |
+
weights = {
|
| 106 |
+
"phash": 0.8,
|
| 107 |
+
"dhash": 0.1,
|
| 108 |
+
"whash": 0.1
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
total_distance = 0
|
| 112 |
+
total_weight = 0
|
| 113 |
+
|
| 114 |
+
for algo, weight in weights.items():
|
| 115 |
+
d = check_distance(hash_set1[algo], hash_set2[algo])
|
| 116 |
+
total_distance += d * weight
|
| 117 |
+
total_weight += weight
|
| 118 |
+
|
| 119 |
+
return total_distance / total_weight
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def compare_two_hashes(hashes1, hashes2):
|
| 123 |
+
"""
|
| 124 |
+
Compares two uploaded images using:
|
| 125 |
+
- Multi-algorithm hashing (pHash, dHash, wHash)
|
| 126 |
+
- Full cross-transform comparison
|
| 127 |
+
- Weighted similarity scoring
|
| 128 |
+
|
| 129 |
+
Returns similarity metrics.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
if not hashes1 or not hashes2:
|
| 133 |
+
return None
|
| 134 |
+
|
| 135 |
+
# Weight configuration
|
| 136 |
+
weights = {
|
| 137 |
+
"phash": 0.8,
|
| 138 |
+
"dhash": 0.1,
|
| 139 |
+
"whash": 0.1
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
min_distance = float("inf")
|
| 143 |
+
best_pair = None
|
| 144 |
+
all_distances = []
|
| 145 |
+
|
| 146 |
+
# Full cross-transform comparison
|
| 147 |
+
for transform1, hash_set1 in hashes1.items():
|
| 148 |
+
for transform2, hash_set2 in hashes2.items():
|
| 149 |
+
|
| 150 |
+
distance = compute_weighted_distance(
|
| 151 |
+
hash_set1,
|
| 152 |
+
hash_set2,
|
| 153 |
+
weights
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
all_distances.append(distance)
|
| 157 |
+
|
| 158 |
+
if distance < min_distance:
|
| 159 |
+
min_distance = distance
|
| 160 |
+
best_pair = f"{transform1}->{transform2}"
|
| 161 |
+
|
| 162 |
+
# Maximum possible distance = hash_size^2 (e.g., 8x8 = 64)
|
| 163 |
+
max_possible_distance = 64
|
| 164 |
+
average_combined_distance = sum(all_distances) / len(all_distances)
|
| 165 |
+
|
| 166 |
+
similarity_percentage = (
|
| 167 |
+
(1 - (min_distance / max_possible_distance)) * 100
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
return {
|
| 171 |
+
"min_weighted_distance": min_distance,
|
| 172 |
+
"average_weighted_distance": average_combined_distance,
|
| 173 |
+
"max_weighted_distance": max(all_distances),
|
| 174 |
+
"best_match_pair": best_pair,
|
| 175 |
+
"similarity_percentage": round(similarity_percentage, 2)
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# def compute_combined_distance(hash_set1: Dict[str, str],
|
| 180 |
+
# hash_set2: Dict[str, str]) -> float:
|
| 181 |
+
# """
|
| 182 |
+
# Computes average Hamming distance across
|
| 183 |
+
# phash, dhash, and whash.
|
| 184 |
+
# """
|
| 185 |
+
#
|
| 186 |
+
# distances = []
|
| 187 |
+
#
|
| 188 |
+
# for algo in ["phash", "dhash", "whash"]:
|
| 189 |
+
# d = check_distance(hash_set1[algo], hash_set2[algo])
|
| 190 |
+
# distances.append(d)
|
| 191 |
+
#
|
| 192 |
+
# return sum(distances) / len(distances)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def check_distance_between_serp(
|
| 196 |
+
uploaded_image: Dict[str, Dict[str, str]],
|
| 197 |
+
searched_images: Dict[str, Dict[str, Any]]
|
| 198 |
+
):
|
| 199 |
+
"""
|
| 200 |
+
Full cross-comparison between transforms AND algorithms.
|
| 201 |
+
Returns ONLY the single image with the lowest minimum distance.
|
| 202 |
+
"""
|
| 203 |
+
|
| 204 |
+
# Trackers for the absolute best match across all URLs
|
| 205 |
+
overall_best_url = None
|
| 206 |
+
overall_min_distance = float("inf")
|
| 207 |
+
overall_best_data = {}
|
| 208 |
+
|
| 209 |
+
for url, image_data in searched_images.items():
|
| 210 |
+
|
| 211 |
+
serp_hashes = image_data["hashes"]
|
| 212 |
+
|
| 213 |
+
all_distances = []
|
| 214 |
+
min_distance = float("inf")
|
| 215 |
+
best_pair = None
|
| 216 |
+
|
| 217 |
+
for up_transform, up_hashes in uploaded_image.items():
|
| 218 |
+
for serp_transform, serp_hashes_set in serp_hashes.items():
|
| 219 |
+
|
| 220 |
+
combined_distance = compute_weighted_distance(
|
| 221 |
+
up_hashes,
|
| 222 |
+
serp_hashes_set
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
all_distances.append(combined_distance)
|
| 226 |
+
|
| 227 |
+
if combined_distance < min_distance:
|
| 228 |
+
min_distance = combined_distance
|
| 229 |
+
best_pair = f"{up_transform}->{serp_transform}"
|
| 230 |
+
|
| 231 |
+
# If this image is the best match we've seen so far, update the champion
|
| 232 |
+
if all_distances and min_distance < overall_min_distance:
|
| 233 |
+
overall_min_distance = min_distance
|
| 234 |
+
overall_best_url = url
|
| 235 |
+
|
| 236 |
+
# Calculate final metrics only for the new champion to save processing
|
| 237 |
+
max_possible_distance = 64
|
| 238 |
+
average_combined_distance = sum(all_distances) / len(all_distances)
|
| 239 |
+
similarity_percentage = (
|
| 240 |
+
(1 - (min_distance / max_possible_distance)) * 100
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
overall_best_data = {
|
| 244 |
+
"source": image_data["source"],
|
| 245 |
+
"link": image_data["link"],
|
| 246 |
+
"url": image_data["imageUrl"],
|
| 247 |
+
"min_combined_distance": min_distance,
|
| 248 |
+
"average_combined_distance": average_combined_distance,
|
| 249 |
+
"max_combined_distance": max(all_distances),
|
| 250 |
+
"best_match_pair": best_pair,
|
| 251 |
+
"similarity_percentage": round(similarity_percentage, 2)
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
# Return the single best result (or an empty dict if no matches were found)
|
| 255 |
+
if overall_best_url:
|
| 256 |
+
return {overall_best_url: overall_best_data}
|
| 257 |
+
else:
|
| 258 |
+
return {}
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def generate_hash_from_serp(payload):
|
| 263 |
+
hashed_payload = {}
|
| 264 |
+
|
| 265 |
+
i = 0
|
| 266 |
+
for item in payload["organic"]:
|
| 267 |
+
generated_hash = generate_phash_from_img_url(item["imageUrl"])
|
| 268 |
+
|
| 269 |
+
if generated_hash is None:
|
| 270 |
+
continue
|
| 271 |
+
else:
|
| 272 |
+
hashed_payload[f"{i}"] = {
|
| 273 |
+
"hashes": generated_hash,
|
| 274 |
+
"source": item["source"],
|
| 275 |
+
"link": item["link"],
|
| 276 |
+
"imageUrl": item["imageUrl"]
|
| 277 |
+
}
|
| 278 |
+
i += 1
|
| 279 |
+
|
| 280 |
+
return hashed_payload
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
# image_path = 'D:\\dev\\thesis-intelligent-module\\test_image.jpg'
|
| 285 |
+
# img_hash = generate_phash(image_path)
|
| 286 |
+
#
|
| 287 |
+
# copy_image_path = 'D:\\dev\\thesis-intelligent-module\\copy.jpg'
|
| 288 |
+
# copy_img_hash = generate_phash(copy_image_path)
|
| 289 |
+
#
|
| 290 |
+
# print(f"Image: {image_path}")
|
| 291 |
+
# print(f"Perceptual Hashes: {img_hash}")
|
| 292 |
+
#
|
| 293 |
+
# print("\n-------------------------------------\n")
|
| 294 |
+
#
|
| 295 |
+
# print(f"Image: {copy_image_path}")
|
| 296 |
+
# print(f"Perceptual Hash: {copy_img_hash}")
|
| 297 |
+
#
|
| 298 |
+
# print("\n-------------------------------------\n")
|
| 299 |
+
#
|
| 300 |
+
# distance = imagehash.hex_to_hash(img_hash["0"]) - imagehash.hex_to_hash(copy_img_hash["0"])
|
| 301 |
+
#
|
| 302 |
+
# print(f"Distance: {distance}")
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
|
lib/serp_service.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import requests
|
| 4 |
+
from fastapi import HTTPException
|
| 5 |
+
|
| 6 |
+
url = os.getenv('SERPER_URL')
|
| 7 |
+
|
| 8 |
+
def serp_image_search(image_url):
|
| 9 |
+
try:
|
| 10 |
+
payload = {
|
| 11 |
+
"url": image_url,
|
| 12 |
+
}
|
| 13 |
+
headers = {
|
| 14 |
+
'X-API-KEY': os.getenv('SERPER_KEY'),
|
| 15 |
+
'Content-Type': 'application/json'
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
response = requests.request("POST", url, headers=headers, json=payload)
|
| 19 |
+
return response.json()
|
| 20 |
+
except:
|
| 21 |
+
raise HTTPException(status_code=400, detail="Serper service error")
|
| 22 |
+
|
| 23 |
+
|
main.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from starlette.middleware.cors import CORSMiddleware
|
| 3 |
+
|
| 4 |
+
from router import router
|
| 5 |
+
|
| 6 |
+
app = FastAPI(
|
| 7 |
+
title="Thesis Intelligent System Module",
|
| 8 |
+
version="1.0.0",
|
| 9 |
+
description="Image Plagiarism Checker and Image Classification API for the Intellectual Property Rights Management System using Perceptual Hashing Algorithms",
|
| 10 |
+
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# configure CORS middleware
|
| 15 |
+
app.add_middleware(
|
| 16 |
+
CORSMiddleware,
|
| 17 |
+
allow_credentials=True,
|
| 18 |
+
allow_methods=["*"],
|
| 19 |
+
allow_headers=["*"],
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
app.include_router(router)
|
requirements.txt
ADDED
|
Binary file (1.41 kB). View file
|
|
|
router.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter
|
| 2 |
+
from api import plagiarism
|
| 3 |
+
from api import test
|
| 4 |
+
from api import art_classification
|
| 5 |
+
|
| 6 |
+
router = APIRouter()
|
| 7 |
+
|
| 8 |
+
router.include_router(plagiarism.router, prefix="/plagiarism", tags=["Plagiarism"])
|
| 9 |
+
router.include_router(art_classification.router, prefix="/classify", tags=["Art-Classification"])
|
| 10 |
+
router.include_router(test.router, prefix="/test", tags=["Test"])
|
| 11 |
+
|
| 12 |
+
@router.get("/", tags=["Plagiarism"])
|
| 13 |
+
async def root():
|
| 14 |
+
return {"message": "Hello World"}
|
test_main.http
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Test your FastAPI endpoints
|
| 2 |
+
|
| 3 |
+
GET http://127.0.0.1:8000/
|
| 4 |
+
Accept: application/json
|
| 5 |
+
|
| 6 |
+
###
|
| 7 |
+
|
| 8 |
+
GET http://127.0.0.1:8000/hello/User
|
| 9 |
+
Accept: application/json
|
| 10 |
+
|
| 11 |
+
###
|