hisham-cmd commited on
Commit
ec990b4
·
verified ·
1 Parent(s): e7d67fc

Upload seed_products.py

Browse files
Files changed (1) hide show
  1. seed_products.py +142 -0
seed_products.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import random
3
+ from sqlalchemy.orm import Session
4
+ from app.db.base import SessionLocal
5
+ from app.models.product import Product, Category, ProductImage
6
+
7
+ # Mapping distinct categories from Excel to a hierarchical structure
8
+ CATEGORY_MAP = {
9
+ # Parents (Keys) : Subcategories (Values)
10
+ "الأزياء": ["الملابس الرجالية", "الملابس النسائية"],
11
+ "الأحذية": ["الأحذية"],
12
+ "الأطفال والألعاب": ["الأطفال"],
13
+ "المنزل والمطبخ": ["المنزل والمطبخ"],
14
+ "العطور والتجميل": ["العطور", "التجميل والعناية"],
15
+ "الأجهزة الإلكترونية": ["الهواتف والإلكترونيات"],
16
+ }
17
+
18
+ # Image placeholders by Parent Category for realistic-ish dummy images
19
+ IMAGE_KEYWORDS = {
20
+ "الأزياء": "clothing,fashion,apparel",
21
+ "الأحذية": "shoes,sneakers",
22
+ "الأطفال والألعاب": "kids,toys,baby",
23
+ "المنزل والمطبخ": "kitchen,home,appliance",
24
+ "العطور والتجميل": "perfume,beauty,skincare",
25
+ "الأجهزة الإلكترونية": "electronics,smartphone,gadget",
26
+ }
27
+
28
+ def get_image_url(parent_category: str, image_index: int):
29
+ # Use Unsplash Source or Picsum
30
+ # To ensure varied images, we use random seeds
31
+ seed = random.randint(1000, 9999) + image_index
32
+ return f"https://picsum.photos/seed/{seed}/800/800"
33
+
34
+ def seed_database():
35
+ db: Session = SessionLocal()
36
+ try:
37
+ print("Loading JSON data...")
38
+ with open("products_dump.json", "r", encoding="utf-8") as f:
39
+ products_data = json.load(f)
40
+
41
+ print(f"Loaded {len(products_data)} products from JSON.")
42
+
43
+ # Optional: Clean existing data (or we can just append, but appending might cause duplicates)
44
+ # Uncomment if starting fresh is preferred:
45
+ # print("Clearing existing products and categories...")
46
+ # db.query(ProductImage).delete()
47
+ # db.query(Product).delete()
48
+ # db.query(Category).delete()
49
+ # db.commit()
50
+
51
+ # 1. Create Parent Categories
52
+ parent_cats = {}
53
+ for parent_name, sub_names in CATEGORY_MAP.items():
54
+ parent_cat = db.query(Category).filter(Category.name_ar == parent_name).first()
55
+ if not parent_cat:
56
+ parent_cat = Category(
57
+ name_ar=parent_name,
58
+ name_en=parent_name, # Fallback to Arabic if English is unavailable
59
+ icon="grid", # generic icon
60
+ )
61
+ db.add(parent_cat)
62
+ db.commit()
63
+ db.refresh(parent_cat)
64
+ parent_cats[parent_name] = parent_cat
65
+
66
+ # 2. Create Subcategories
67
+ sub_cats = {}
68
+ for parent_name, sub_names in CATEGORY_MAP.items():
69
+ for sub_name in sub_names:
70
+ sub_cat = db.query(Category).filter(Category.name_ar == sub_name).first()
71
+ if not sub_cat:
72
+ sub_cat = Category(
73
+ name_ar=sub_name,
74
+ name_en=sub_name,
75
+ icon="list",
76
+ parent_id=parent_cats[parent_name].id
77
+ )
78
+ db.add(sub_cat)
79
+ db.commit()
80
+ db.refresh(sub_cat)
81
+ sub_cats[sub_name] = {"model": sub_cat, "parent_name": parent_name}
82
+
83
+ # 3. Create Products
84
+ print("Inserting products...")
85
+ inserted_count = 0
86
+ for item in products_data:
87
+ cat_name = item.get("الفئة")
88
+ if not cat_name or cat_name not in sub_cats:
89
+ print(f"Skipping row with missing/unknown category: {cat_name}")
90
+ continue
91
+
92
+ sub_cat_info = sub_cats[cat_name]
93
+
94
+ # Create product
95
+ price = float(item.get("سعر البيع (ريال)", 0))
96
+ compare_price = price * 1.2 # dummy compare price 20% higher
97
+
98
+ prod = Product(
99
+ name_ar=item.get("اسم المنتج", ""),
100
+ name_en=item.get("اسم المنتج", ""), # Fallback
101
+ description_ar=item.get("الوصف التسويقي", ""),
102
+ description_en=item.get("الوصف التسويقي", ""),
103
+ price=price,
104
+ compare_price=round(compare_price, 2),
105
+ stock=random.randint(10, 100),
106
+ category_id=sub_cat_info["model"].id,
107
+ rating=round(random.uniform(3.5, 5.0), 1),
108
+ rating_count=random.randint(0, 50),
109
+ is_featured=random.choice([True, False]),
110
+ is_active=True
111
+ )
112
+ db.add(prod)
113
+ db.flush() # get prod.id
114
+
115
+ # 4. Create multiple images for the product
116
+ # Request was "توفير صور للمنتجات مناسبة متعددة" -> multiple images
117
+ num_images = random.randint(2, 4)
118
+ for i in range(num_images):
119
+ img_url = get_image_url(sub_cat_info["parent_name"], i)
120
+ prod_img = ProductImage(
121
+ product_id=prod.id,
122
+ image_url=img_url,
123
+ alt_text=prod.name_ar,
124
+ sort_order=i
125
+ )
126
+ db.add(prod_img)
127
+
128
+ inserted_count += 1
129
+ if inserted_count % 50 == 0:
130
+ print(f"Inserted {inserted_count} / {len(products_data)} products...")
131
+
132
+ db.commit()
133
+ print(f"Successfully seeded {inserted_count} products with multiple images and subcategories!")
134
+
135
+ except Exception as e:
136
+ db.rollback()
137
+ print(f"Error seeding database: {e}")
138
+ finally:
139
+ db.close()
140
+
141
+ if __name__ == "__main__":
142
+ seed_database()