from flask import Flask, jsonify, request import json import os import random from collections import OrderedDict app = Flask(__name__) JSON_PATH = r"C:\Users\ASUS\Desktop\Computer_vision_binder\output_cleaning_imagesCarrefourksa_fields.json" def load_products(): if os.path.exists(JSON_PATH): with open(JSON_PATH, 'r', encoding='utf-8') as file: return json.load(file) return [] def save_products(products_list): cleaned = [] for p in products_list: ordered = OrderedDict() # Desired field order field_order = [ "product_id", "image_id", "sor_cat", "sor_subcat", "sor_subsubcat", "sor_prdocut_name", "sor_product_url", "sor_image_url" ] for key in field_order: if key in p: ordered[key] = p[key] # SKU always last ordered["binder_cv_sku"] = p.get("binder_cv_sku", None) cleaned.append(ordered) with open(JSON_PATH, 'w', encoding='utf-8') as file: json.dump(cleaned, file, indent=2, ensure_ascii=False) def generate_unique_sku(existing_skus): while True: sku = f"{random.randint(0, 999999999):09d}" if sku not in existing_skus: return sku @app.route('/all-products', methods=['GET']) def get_all_products(): products = load_products() sku_map = {} existing_skus = set() updated = False for p in products: pid = p.get("product_id") sku = p.get("binder_cv_sku") if sku: sku_map[pid] = sku existing_skus.add(sku) for p in products: pid = p.get("product_id") if not p.get("binder_cv_sku"): if pid in sku_map: p["binder_cv_sku"] = sku_map[pid] else: new_sku = generate_unique_sku(existing_skus) sku_map[pid] = new_sku p["binder_cv_sku"] = new_sku existing_skus.add(new_sku) updated = True if updated: save_products(products) return jsonify(products) @app.route('/add-product', methods=['POST']) def add_product(): new_product = request.get_json() if not new_product or "product_id" not in new_product or "image_id" not in new_product: return jsonify({"error": "Missing product_id or image_id"}), 400 products = load_products() # Check if image_id already exists — avoid duplicates existing_image_ids = {p['image_id'] for p in products} if new_product["image_id"] in existing_image_ids: return jsonify({"message": "Image already exists. Skipped."}), 200 # Map product_id to existing SKUs existing_skus = {p['binder_cv_sku'] for p in products if "binder_cv_sku" in p} sku_map = {p['product_id']: p['binder_cv_sku'] for p in products if "binder_cv_sku" in p} pid = new_product["product_id"] # Assign SKU: reuse if product_id exists, else generate new SKU if pid in sku_map: new_product["binder_cv_sku"] = sku_map[pid] else: new_sku = generate_unique_sku(existing_skus) new_product["binder_cv_sku"] = new_sku sku_map[pid] = new_sku # Append and save products.append(new_product) save_products(products) return jsonify({"message": "Product added successfully", "binder_cv_sku": new_product["binder_cv_sku"]}) if __name__ == '__main__': app.run(debug=True)