from flask import Flask, request, jsonify
import cv2
import numpy as np
import os
import json

app = Flask(__name__)

# Set YOLO model paths (Make sure these files exist in your cPanel directory)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
cfg_path = os.path.join(BASE_DIR, "yolo", "yolov4.cfg")
weights_path = os.path.join(BASE_DIR, "yolo", "yolov4.weights")
coco_names = os.path.join(BASE_DIR, "yolo", "coco.names")

# Load YOLO model
net = cv2.dnn.readNet(weights_path, cfg_path)

# Load class labels
with open(coco_names, "r") as f:
    classes = [line.strip() for line in f.readlines()]

# Get YOLO output layers
layer_names = net.getLayerNames()
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]

# QR Code Detector
qr_detector = cv2.QRCodeDetector()

# Example products
products = [
    {"id": 1, "name": "cell phone", "description": "A mobile device", "price": "500.00", "stock": 100},
    {"id": 2, "name": "clock", "description": "A wall clock", "price": "30.00", "stock": 50}
]
product_names = [product["name"] for product in products]

@app.route("/", methods=["GET"])
def home():
    return jsonify({"message": "YOLO QR Code & Object Detection API Running"})


@app.route("/detect_qr", methods=["POST"])
def detect_qr():
    try:
        if "image" not in request.files:
            return jsonify({"error": "No image uploaded"}), 400
        
        file = request.files["image"]
        npimg = np.frombuffer(file.read(), np.uint8)
        frame = cv2.imdecode(npimg, cv2.IMREAD_COLOR)

        data, bbox, _ = qr_detector.detectAndDecode(frame)

        if data:
            return jsonify({"status": "success", "qr_data": data})
        else:
            return jsonify({"status": "error", "message": "No QR Code found"})

    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route("/detect_objects", methods=["POST"])
def detect_objects():
    try:
        if "image" not in request.files:
            return jsonify({"error": "No image uploaded"}), 400

        file = request.files["image"]
        npimg = np.frombuffer(file.read(), np.uint8)
        frame = cv2.imdecode(npimg, cv2.IMREAD_COLOR)

        height, width, _ = frame.shape
        blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
        net.setInput(blob)
        outs = net.forward(output_layers)

        detected_labels = []
        for out in outs:
            for detection in out:
                scores = detection[5:]
                class_id = np.argmax(scores)
                confidence = scores[class_id]

                if confidence > 0.5:
                    detected_labels.append(classes[class_id])

        return jsonify({"status": "success", "detected_objects": detected_labels})

    except Exception as e:
        return jsonify({"error": str(e)}), 500


if __name__ == "__main__":
    app.run(debug=True)
