import os
import io
import json
from fastapi import FastAPI, File, UploadFile, Form
from fastapi.responses import HTMLResponse
from PIL import Image
import imagehash
app = FastAPI()
DATABASE_DIR = "scam_database"
VOTES_FILE = "votes.json"
# ฟังก์ชันโหลดข้อมูลโหวตจากไฟล์ JSON
def load_votes():
if os.path.exists(VOTES_FILE):
try:
with open(VOTES_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return {}
return {}
# ฟังก์ชันบันทึกข้อมูลโหวตลงไฟล์ JSON
def save_votes(votes_data):
with open(VOTES_FILE, "w", encoding="utf-8") as f:
json.dump(votes_data, f, ensure_ascii=False, indent=2)
# ฟังก์ชันดึง Hash ของรูปทั้งหมดในฐานข้อมูล
def get_database_hashes():
hashes = {}
if not os.path.exists(DATABASE_DIR):
os.makedirs(DATABASE_DIR)
for filename in os.listdir(DATABASE_DIR):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
filepath = os.path.join(DATABASE_DIR, filename)
try:
img = Image.open(filepath)
h = str(imagehash.phash(img))
hashes[filename] = h
except Exception as e:
print(f"Error loading {filename}: {e}")
return hashes
@app.get("/", response_class=HTMLResponse)
def serve_index():
if os.path.exists("index.html"):
with open("index.html", "r", encoding="utf-8") as f:
return f.read()
return "
index.html not found
"
@app.post("/check")
async def check_image(file: UploadFile = File(...)):
try:
contents = await file.read()
uploaded_img = Image.open(io.BytesIO(contents))
uploaded_hash_obj = imagehash.phash(uploaded_img)
uploaded_hash_str = str(uploaded_hash_obj)
db_hashes = get_database_hashes()
votes_data = load_votes()
MATCH_THRESHOLD = 12
matched_hash_key = None
is_in_db = False
# เปรียบเทียบกับภาพในฐานข้อมูล
for filename, db_hash_str in db_hashes.items():
db_hash_obj = imagehash.hex_to_hash(db_hash_str)
distance = uploaded_hash_obj - db_hash_obj
if distance <= MATCH_THRESHOLD:
matched_hash_key = db_hash_str
is_in_db = True
break
# ถ้าไม่เจอในฐานข้อมูล ใช้ Hash ของภาพที่อัปโหลดเป็น Key
if not matched_hash_key:
matched_hash_key = uploaded_hash_str
# ดึงคะแนนโหวต
image_vote = votes_data.get(matched_hash_key, {"likes": 0, "dislikes": 0})
likes = image_vote.get("likes", 0)
dislikes = image_vote.get("dislikes", 0)
# เงื่อนไขตรวจสอบสถานะ
if likes >= 100:
is_scam = False
result_text = "ปลอดภัย"
detail_text = f"รูปภาพนี้ได้รับการยืนยันว่าปลอดภัยจากผู้ใช้งาน (กดไลก์ {likes} คน)"
elif is_in_db:
is_scam = True
result_text = "มิจแน่นอน100%"
detail_text = "พบรูปภาพตรงกับฐานข้อมูลรูปภาพโปรโมทหลอกลวง"
else:
is_scam = False
result_text = "ไม่สามารถตรวจสอบได้"
detail_text = "ยังไม่พบรูปภาพนี้ในฐานข้อมูลมิจฉาชีพ"
return {
"is_scam": is_scam,
"result": result_text,
"detail": detail_text,
"image_hash": matched_hash_key,
"likes": likes,
"dislikes": dislikes
}
except Exception as e:
return {"error": f"เกิดข้อผิดพลาดในการประมวลผล: {str(e)}"}
@app.post("/vote")
async def vote_image(image_hash: str = Form(...), vote_type: str = Form(...)):
try:
votes_data = load_votes()
if image_hash not in votes_data:
votes_data[image_hash] = {"likes": 0, "dislikes": 0}
if vote_type == "like":
votes_data[image_hash]["likes"] += 1
elif vote_type == "dislike":
votes_data[image_hash]["dislikes"] += 1
save_votes(votes_data)
likes = votes_data[image_hash]["likes"]
dislikes = votes_data[image_hash]["dislikes"]
# คำนวณสถานะใหม่หลังกดโหวต
db_hashes = get_database_hashes()
is_in_db = image_hash in db_hashes.values()
if likes >= 100:
is_scam = False
result_text = "ปลอดภัย"
detail_text = f"รูปภาพนี้ได้รับการยืนยันว่าปลอดภัยจากผู้ใช้งาน (กดไลก์ {likes} คน)"
elif is_in_db:
is_scam = True
result_text = "มิจแน่นอน100%"
detail_text = "พบรูปภาพตรงกับฐานข้อมูลรูปภาพโปรโมทหลอกลวง"
else:
is_scam = False
result_text = "ไม่สามารถตรวจสอบได้"
detail_text = "ยังไม่พบรูปภาพนี้ในฐานข้อมูลมิจฉาชีพ"
return {
"success": True,
"likes": likes,
"dislikes": dislikes,
"is_scam": is_scam,
"result": result_text,
"detail": detail_text
}
except Exception as e:
return {"error": f"เกิดข้อผิดพลาดในการโหวต: {str(e)}"}