hisham-cmd commited on
Commit
60470bc
·
1 Parent(s): b2be963

Optimized Sync: Differential Upload & Performance Tweak

Browse files
.dockerignore ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ venv/
2
+ .venv/
3
+ __pycache__/
4
+ *.pyc
5
+ *.pyo
6
+ .env
7
+ .git/
8
+ *.db
9
+ .pytest_cache/
10
+ kaggle/
11
+ scripts/
12
+ tests/
13
+ .ipynb_checkpoints/
14
+ *.zip
15
+ *.tar.gz
.hfignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .git/
2
+ .venv/
3
+ venv/
4
+ __pycache__/
5
+ *.pyc
6
+ *.pyo
7
+ .env
8
+ vortex.db
9
+ kaggle/
10
+ scripts/
11
+ tests/
12
+ .ipynb_checkpoints/
13
+ *.zip
14
+ *.tar.gz
Dockerfile CHANGED
@@ -1,8 +1,13 @@
1
- # Forced Rebuild 2026-03-27T17:15
2
-
3
  # Use an official Python runtime as a parent image
4
  FROM python:3.11-slim
5
 
 
 
 
 
 
 
 
6
  # Set the working directory in the container
7
  WORKDIR /app
8
 
@@ -12,28 +17,21 @@ RUN apt-get update && apt-get install -y \
12
  fonts-dejavu-core \
13
  && rm -rf /var/lib/apt/lists/*
14
 
15
- # Copy the requirements file into the container
16
  COPY requirements.txt .
17
 
18
- # Install any needed packages specified in requirements.txt
19
  RUN pip install --no-cache-dir -r requirements.txt
20
 
21
- # Copy the rest of the application code into the container
22
  COPY . .
23
 
24
  # Hugging Face Spaces runs as user with UID 1000
25
- # Grant ownership of /app so SQLite DB can be created and written
26
  RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app
27
  USER appuser
28
 
29
  # Expose port 7860 as required by Hugging Face Spaces
30
  EXPOSE 7860
31
 
32
- # Define environment variables
33
- ENV PYTHONUNBUFFERED=1
34
- ENV HOST=0.0.0.0
35
- ENV PORT=7860
36
- ENV DATABASE_URL=sqlite:///./vortex.db
37
-
38
  # Command to run the application
39
  CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860", "--proxy-headers", "--forwarded-allow-ips='*'"]
 
 
 
1
  # Use an official Python runtime as a parent image
2
  FROM python:3.11-slim
3
 
4
+ # Set environment variables for performance
5
+ ENV PYTHONUNBUFFERED=1 \
6
+ PYTHONOPTIMIZE=1 \
7
+ HOST=0.0.0.0 \
8
+ PORT=7860 \
9
+ DATABASE_URL=sqlite:///./vortex.db
10
+
11
  # Set the working directory in the container
12
  WORKDIR /app
13
 
 
17
  fonts-dejavu-core \
18
  && rm -rf /var/lib/apt/lists/*
19
 
20
+ # Copy only requirements first to leverage Docker layer caching
21
  COPY requirements.txt .
22
 
23
+ # Install dependencies
24
  RUN pip install --no-cache-dir -r requirements.txt
25
 
26
+ # Copy the rest of the application code
27
  COPY . .
28
 
29
  # Hugging Face Spaces runs as user with UID 1000
 
30
  RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app
31
  USER appuser
32
 
33
  # Expose port 7860 as required by Hugging Face Spaces
34
  EXPOSE 7860
35
 
 
 
 
 
 
 
36
  # Command to run the application
37
  CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860", "--proxy-headers", "--forwarded-allow-ips='*'"]
__test_cleanup__ ADDED
File without changes
app/main.py CHANGED
@@ -28,102 +28,13 @@ import app.models.home # noqa: F401
28
  import app.models.analytics # noqa: F401
29
 
30
 
 
31
  from contextlib import asynccontextmanager
32
 
33
  @asynccontextmanager
34
  async def lifespan(app: FastAPI):
35
- # Startup logic
36
- import asyncio
37
- from app.db.base import SessionLocal, Base, engine
38
-
39
- # 1. Ensure tables exist (fast)
40
- print(">>> [DB] Ensuring tables exist...")
41
- Base.metadata.create_all(bind=engine)
42
-
43
- # 1.5 Auto-migrate missing columns for orders table
44
- print(">>> [DB] Auto-migrating orders table...")
45
- try:
46
- from sqlalchemy import inspect, text
47
- inspector = inspect(engine)
48
- if inspector.has_table("orders"):
49
- columns_exist = [col['name'] for col in inspector.get_columns('orders')]
50
-
51
- columns_to_add = [
52
- ("ip_address", "VARCHAR(50)"),
53
- ("user_agent", "TEXT"),
54
- ("browser", "VARCHAR(100)"),
55
- ("os", "VARCHAR(100)"),
56
- ("device_type", "VARCHAR(50)"),
57
- ("location_data", "TEXT"),
58
- ("client_metadata", "TEXT")
59
- ]
60
-
61
- with engine.begin() as conn:
62
- for col_name, col_type in columns_to_add:
63
- if col_name not in columns_exist:
64
- conn.execute(text(f"ALTER TABLE orders ADD COLUMN {col_name} {col_type}"))
65
- print(f">>> [DB] Added column {col_name} to orders table.")
66
- except Exception as e:
67
- print(f">>> [DB] Auto-migration error (orders): {e}")
68
-
69
- # 1.6 Auto-migrate missing columns for order_items table
70
- print(">>> [DB] Auto-migrating order_items table...")
71
- try:
72
- from sqlalchemy import inspect, text
73
- inspector = inspect(engine)
74
- if inspector.has_table("order_items"):
75
- columns_exist = [col['name'] for col in inspector.get_columns('order_items')]
76
-
77
- with engine.begin() as conn:
78
- if "variant_id" not in columns_exist:
79
- conn.execute(text("ALTER TABLE order_items ADD COLUMN variant_id VARCHAR(50)"))
80
- print(">>> [DB] Added column variant_id to order_items table.")
81
- if "variant_label" not in columns_exist:
82
- conn.execute(text("ALTER TABLE order_items ADD COLUMN variant_label VARCHAR(255)"))
83
- print(">>> [DB] Added column variant_label to order_items table.")
84
- except Exception as e:
85
- print(f">>> [DB] Auto-migration error (order_items): {e}")
86
-
87
- # 1.7 Ensure Analytics tables exist
88
- print(">>> [DB] Ensuring analytics tables exist...")
89
- try:
90
- from app.models.analytics import VisitorLog, AnalyticsEvent
91
- Base.metadata.create_all(bind=engine, tables=[VisitorLog.__table__, AnalyticsEvent.__table__])
92
- except Exception as e:
93
- print(f">>> [DB] Analytics table creation error: {e}")
94
-
95
- # 2. Run Seeding in the Background to avoid HF Startup Timeout
96
- async def run_background_seed():
97
- from app.models.product import Product
98
- from app.api.seed import seed_database
99
- import asyncio
100
-
101
- # Use a new session for the background thread
102
- db = SessionLocal()
103
- try:
104
- # Check if we have any products
105
- print(">>> [BOOTSTRAP] Checking database status...")
106
- count = db.query(Product).count()
107
- if count == 0:
108
- print(">>> [BOOTSTRAP] Database is empty. Starting BACKGROUND Auto-seeding...")
109
- # Run the sync seed function in a separate thread
110
- result = await asyncio.to_thread(seed_database, db=db)
111
- if result.isSuccess:
112
- print(f">>> [BOOTSTRAP] Seeding SUCCESS: {result.value.get('message', 'Complete')}")
113
- else:
114
- print(f">>> [BOOTSTRAP] Seeding FAILED: {result.error} | {result.value.get('message')}")
115
- print(f">>> [BOOTSTRAP] Paths checked: {result.value.get('checked')}")
116
- else:
117
- print(f">>> [BOOTSTRAP] Database already has {count} products. Skipping seed.")
118
- except Exception as e:
119
- print(f">>> [BOOTSTRAP] Background Seeding error: {e}")
120
- finally:
121
- db.close()
122
-
123
- # Create the task but don't await it here
124
- asyncio.create_task(run_background_seed())
125
-
126
- print(">>> [MAIN] Startup sequence finished. Yielding to health checks...")
127
  yield
128
  # Shutdown logic (optional)
129
  # Shutdown logic (optional)
@@ -147,6 +58,9 @@ def create_app() -> FastAPI:
147
  allow_headers=["*"],
148
  )
149
 
 
 
 
150
  # Routers
151
  app.include_router(auth_router, prefix="/api")
152
  app.include_router(products_router, prefix="/api")
 
28
  import app.models.analytics # noqa: F401
29
 
30
 
31
+ from fastapi.middleware.gzip import GZipMiddleware
32
  from contextlib import asynccontextmanager
33
 
34
  @asynccontextmanager
35
  async def lifespan(app: FastAPI):
36
+ # Startup logic - Minimal and fast
37
+ print(">>> [MAIN] Application starting (DB maintenance disabled).")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  yield
39
  # Shutdown logic (optional)
40
  # Shutdown logic (optional)
 
58
  allow_headers=["*"],
59
  )
60
 
61
+ # Response Compression
62
+ app.add_middleware(GZipMiddleware, minimum_size=1000)
63
+
64
  # Routers
65
  app.include_router(auth_router, prefix="/api")
66
  app.include_router(products_router, prefix="/api")
compare_jsons.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+
4
+ files = [
5
+ r'c:\react_projects\VortexCommerce\kaggle\extra_products_vortex.json',
6
+ r'c:\react_projects\VortexCommerce\backend\kaggle\extra_products_vortex.json'
7
+ ]
8
+
9
+ for f_path in files:
10
+ if os.path.exists(f_path):
11
+ with open(f_path, "r", encoding="utf-8") as f:
12
+ data = json.load(f)
13
+ count = len(data["products"]) if isinstance(data, dict) and "products" in data else len(data)
14
+ print(f"{f_path}: {count} products")
15
+ else:
16
+ print(f"{f_path}: NOT FOUND")
counts.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ sys.path.append(os.getcwd())
4
+ from sqlalchemy import create_engine
5
+ from app.db.base import settings
6
+ from app.models.product import Product, Category
7
+
8
+ # Use port 6543 for transaction mode (more reliable on Supabase)
9
+ db_url = settings.DATABASE_URL.replace(":5432/", ":6543/")
10
+ engine = create_engine(db_url)
11
+ from sqlalchemy.orm import sessionmaker
12
+ SessionLocal = sessionmaker(bind=engine)
13
+
14
+ db = SessionLocal()
15
+ try:
16
+ p_count = db.query(Product).count()
17
+ c_count = db.query(Category).count()
18
+ print(f"Product count: {p_count}")
19
+ print(f"Category count: {c_count}")
20
+ finally:
21
+ db.close()
fix_bom.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ with open('README.md', 'r', encoding='utf-8-sig') as f:
4
+ content = f.read()
5
+
6
+ with open('README.md', 'w', encoding='utf-8', newline='\n') as f:
7
+ f.write(content)
8
+
9
+ print("README.md rewritten without BOM")
fix_slugs.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import time
4
+ from app.db.base import SessionLocal
5
+ from app.models.product import Product
6
+
7
+ def fix_slugs():
8
+ db = SessionLocal()
9
+ products = db.query(Product).filter(Product.slug == None).all()
10
+
11
+ # Load JSON to map existing products to their legacy ref
12
+ json_path = "app/data/extra_products_vortex.json"
13
+ legacy_map = {}
14
+
15
+ if os.path.exists(json_path):
16
+ with open(json_path, 'r', encoding='utf-8') as f:
17
+ data = json.load(f)
18
+ for item in data:
19
+ # the product_name_ar logic in seed.py
20
+ title_ar = item.get("title_ar") or item.get("title_en", "")
21
+ if title_ar:
22
+ legacy_map[title_ar] = item.get("legacy_ref") or item.get("sku_base")
23
+
24
+ count = 0
25
+ for p in products:
26
+ slug = legacy_map.get(p.name_ar)
27
+ if not slug:
28
+ slug = legacy_map.get(p.name_en)
29
+
30
+ if not slug:
31
+ slug = f"vortex-product-{p.id}"
32
+
33
+ p.slug = slug
34
+ count += 1
35
+
36
+ db.commit()
37
+ print(f"Fixed {count} product slugs.")
38
+
39
+ if __name__ == "__main__":
40
+ fix_slugs()
kaggle/Extra_Scraper_Kaggle.py CHANGED
@@ -684,9 +684,12 @@ class ExtraScraper:
684
  detail = await page.evaluate(DETAIL_AR_JS)
685
  return detail
686
 
687
- async def scrape(self, category_key, url_template, max_products=None):
688
  """السكرابر الكامل: قائمة → تفاصيل EN → تفاصيل AR"""
689
  results = []
 
 
 
690
  async with async_playwright() as pw:
691
  browser = await pw.chromium.launch(headless=True)
692
  context = await browser.new_context(
@@ -700,17 +703,21 @@ class ExtraScraper:
700
  listing = await self.scrape_listing(page, category_key, url_template, max_products, current_total=len(results))
701
  logger.info(f"📋 [{category_key}] Total listings found: {len(listing)}")
702
 
703
- if max_products:
704
- listing = listing[:max_products]
705
-
706
  # === خطوة 2 + 3: زيارة كل منتج ===
707
  for i, item in enumerate(listing):
708
- if max_products and i >= max_products:
709
- break
710
-
711
  pid = item['pid']
712
  url = item['product_url']
713
- logger.info(f" 🔎 [{category_key}] Product {i+1}/{len(listing)}: PID={pid}")
 
 
 
 
 
 
 
 
 
 
714
 
715
  # --- تفاصيل إنجليزية ---
716
  en_detail = await self.scrape_detail_en(page, url)
@@ -741,10 +748,13 @@ class ExtraScraper:
741
  'rating_count': en_detail.get('rating_count', 0),
742
  'raw_categories': en_detail.get('categories', []),
743
  }
 
744
  results.append(product)
 
 
745
  logger.info(f" ✅ {product['title_en'][:50]}... | {len(product['images'])} imgs | {len(product['specs_en'])} specs")
746
 
747
- await asyncio.sleep(random.uniform(0.2, 0.8))
748
 
749
  await browser.close()
750
  return results
@@ -994,29 +1004,22 @@ async def main():
994
  print(f"📂 Processing Category: {cat_key} (Target: {TARGET_PRODUCTS_PER_CATEGORY})")
995
  print(f"{'─'*50}")
996
 
997
- # Step 1: Get enough listings to reach the target after filtering
998
- # We fetch extra to account for skips/duplicates
999
- prods = await scraper.scrape(cat_key, url_tpl, max_products=TARGET_PRODUCTS_PER_CATEGORY)
1000
-
1001
- # Filter duplicates across categories
1002
- unique_prods = []
1003
- for p in prods:
1004
- if p['pid'] not in seen_pids:
1005
- seen_pids.add(p['pid'])
1006
- unique_prods.append(p)
1007
 
1008
- if unique_prods:
1009
- saved = db.save_products(unique_prods)
1010
- all_raw.extend(unique_prods)
1011
 
1012
- img_counts = [len(p.get('images', [])) for p in unique_prods]
1013
  avg_imgs = sum(img_counts) / len(img_counts) if img_counts else 0
1014
- ar_count = sum(1 for p in unique_prods if p.get('title_ar'))
1015
 
1016
- print(f" ✅ {len(unique_prods)} unique products saved for this category")
1017
- print(f" 🖼️ Avg images: {avg_imgs:.1f} | 🌐 Arabic: {ar_count}/{len(unique_prods)}")
1018
  else:
1019
- print(f" ⚠️ No new unique products found in this category")
1020
 
1021
  print(f"\n{'═'*60}")
1022
  print(f"📦 FINAL SCRAPE COMPLETE: Total {len(all_raw)} products across all categories")
 
684
  detail = await page.evaluate(DETAIL_AR_JS)
685
  return detail
686
 
687
+ async def scrape(self, category_key, url_template, max_products=None, global_seen_pids=None):
688
  """السكرابر الكامل: قائمة → تفاصيل EN → تفاصيل AR"""
689
  results = []
690
+ if global_seen_pids is None:
691
+ global_seen_pids = set()
692
+
693
  async with async_playwright() as pw:
694
  browser = await pw.chromium.launch(headless=True)
695
  context = await browser.new_context(
 
703
  listing = await self.scrape_listing(page, category_key, url_template, max_products, current_total=len(results))
704
  logger.info(f"📋 [{category_key}] Total listings found: {len(listing)}")
705
 
 
 
 
706
  # === خطوة 2 + 3: زيارة كل منتج ===
707
  for i, item in enumerate(listing):
 
 
 
708
  pid = item['pid']
709
  url = item['product_url']
710
+
711
+ # --- الفلترة المسبقة الفورية (Early Deduplication) ---
712
+ if pid in global_seen_pids:
713
+ logger.info(f" ⏩ Skipping PID={pid} (Already processed previously)")
714
+ continue
715
+
716
+ if max_products and len(results) >= max_products:
717
+ logger.info(f" 🎯 Reached quota for category: {category_key}")
718
+ break
719
+
720
+ logger.info(f" 🔎 [{category_key}] Product {len(results)+1}/{max_products or '?'}: PID={pid}")
721
 
722
  # --- تفاصيل إنجليزية ---
723
  en_detail = await self.scrape_detail_en(page, url)
 
748
  'rating_count': en_detail.get('rating_count', 0),
749
  'raw_categories': en_detail.get('categories', []),
750
  }
751
+
752
  results.append(product)
753
+ global_seen_pids.add(pid) # إضافة المنتج لقائمة المعالجين
754
+
755
  logger.info(f" ✅ {product['title_en'][:50]}... | {len(product['images'])} imgs | {len(product['specs_en'])} specs")
756
 
757
+ await asyncio.sleep(random.uniform(0.1, 0.4))
758
 
759
  await browser.close()
760
  return results
 
1004
  print(f"📂 Processing Category: {cat_key} (Target: {TARGET_PRODUCTS_PER_CATEGORY})")
1005
  print(f"{'─'*50}")
1006
 
1007
+ # Step 1: Get enough listings and scrape details with early deduplication
1008
+ # We pass global_seen_pids to skip already visited products across categories
1009
+ prods = await scraper.scrape(cat_key, url_tpl, max_products=TARGET_PRODUCTS_PER_CATEGORY, global_seen_pids=seen_pids)
 
 
 
 
 
 
 
1010
 
1011
+ if prods:
1012
+ saved = db.save_products(prods)
1013
+ all_raw.extend(prods)
1014
 
1015
+ img_counts = [len(p.get('images', [])) for p in prods]
1016
  avg_imgs = sum(img_counts) / len(img_counts) if img_counts else 0
1017
+ ar_count = sum(1 for p in prods if p.get('title_ar'))
1018
 
1019
+ print(f" ✅ {len(prods)} products saved and processed for this category")
1020
+ print(f" 🖼️ Avg images: {avg_imgs:.1f} | 🌐 Arabic: {ar_count}/{len(prods)}")
1021
  else:
1022
+ print(f" ⚠️ No new products found in this category")
1023
 
1024
  print(f"\n{'═'*60}")
1025
  print(f"📦 FINAL SCRAPE COMPLETE: Total {len(all_raw)} products across all categories")
run_local.bat ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ echo ==========================================
3
+ echo Starting VortexCommerce Local Backend...
4
+ echo ==========================================
5
+ if not exist venv (
6
+ echo [!] venv not found. Creating it...
7
+ python -m venv venv
8
+ )
9
+ call venv\Scripts\activate
10
+ echo [*] Installing dependencies...
11
+ pip install -r requirements.txt
12
+ echo [OK] Dependencies ready.
13
+
14
+ echo [*] Starting Uvicorn on http://localhost:8000
15
+ set PYTHONPATH=.
16
+ uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
17
+ pause
run_seed.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+
4
+ # Add the current directory to sys.path to allow importing 'app'
5
+ sys.path.append(os.getcwd())
6
+
7
+ from sqlalchemy import create_engine
8
+ from sqlalchemy.pool import NullPool
9
+ from app.db.base import Base, settings
10
+ from app.api.seed import seed_database
11
+ from sqlalchemy.orm import sessionmaker
12
+ import json
13
+
14
+ def run():
15
+ print(">>> Starting Product Import from extra_products_vortex.json...")
16
+
17
+ # 1. Create a fresh engine with NullPool and use port 6543 (Transaction Mode)
18
+ # to avoid "MaxClientsInSessionMode" errors on port 5432.
19
+ db_url = settings.DATABASE_URL.replace(":5432/", ":6543/")
20
+ temp_engine = create_engine(db_url, poolclass=NullPool)
21
+ TempSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=temp_engine)
22
+
23
+ # 2. Ensure tables exist
24
+ Base.metadata.create_all(bind=temp_engine)
25
+
26
+ # 3. Setup DB Session
27
+ db = TempSessionLocal()
28
+ try:
29
+ # Step 1: Initialize Categories and wipe data
30
+ print(">>> Wiping data and creating categories...")
31
+ result = seed_database(clear=True, db=db)
32
+ if not result.isSuccess:
33
+ print(f"FAILED: {result.error}")
34
+ return
35
+
36
+ print(f"SUCCESS: {result.value.get('message')}")
37
+ print(f"Stats: Inserted {result.value.get('inserted_new')} products.")
38
+
39
+ except Exception as e:
40
+ print(f"CRITICAL ERROR: {str(e)}")
41
+ db.rollback()
42
+ finally:
43
+ db.close()
44
+
45
+ if __name__ == "__main__":
46
+ run()
run_seed_v2.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ # Add the current directory to sys.path so we can import 'app'
5
+ sys.path.insert(0, os.path.join(os.getcwd(), "app"))
6
+ sys.path.insert(0, os.getcwd())
7
+
8
+ from app.db.base import SessionLocal
9
+ from app.api.seed import seed_database
10
+
11
+ def run():
12
+ print(">>> [LAUNCHER] Starting Hierarchical Seeding...")
13
+ db = SessionLocal()
14
+ try:
15
+ # Clear=True ensures a professional "From Scratch" reset
16
+ response = seed_database(clear=True, db=db)
17
+ print(">>> [LAUNCHER] Seeding Complete!")
18
+ print(f">>> Result: {response.value}")
19
+ except Exception as e:
20
+ print(f">>> [LAUNCHER] ERROR during seeding: {e}")
21
+ import traceback
22
+ traceback.print_exc()
23
+ finally:
24
+ db.close()
25
+
26
+ if __name__ == "__main__":
27
+ run()
seed_home_sections.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ sys.path.append(os.getcwd())
4
+
5
+ from app.db.base import engine as base_engine
6
+ from sqlalchemy.orm import sessionmaker
7
+ from sqlalchemy.pool import NullPool
8
+ from app.models.home import HomeSection
9
+ from app.models.product import Category
10
+
11
+ # For Supabase Pooler (6543), use NullPool to avoid session overhead
12
+ base_engine.pool = NullPool()
13
+ SessionLocal = sessionmaker(bind=base_engine)
14
+ db = SessionLocal()
15
+
16
+ def seed_home_sections():
17
+ print("Seeding Home Sections...")
18
+
19
+ # 1. Clear existing sections to avoid duplicates
20
+ db.query(HomeSection).delete()
21
+ db.commit()
22
+
23
+ # Get some category IDs for dynamic rules
24
+ categories = db.query(Category).all()
25
+ cat_map = {c.name_en: c.id for c in categories}
26
+
27
+ sections_data = [
28
+ {
29
+ "title_ar": "وصل حديثاً",
30
+ "title_en": "New Arrivals",
31
+ "subtitle_ar": "اكتشف أحدث المنتجات في متجرنا",
32
+ "subtitle_en": "Discover the latest additions to our store",
33
+ "section_type": "AUTOMATIC",
34
+ "rule": {"sort_by": "created_at", "sort_order": "desc", "limit": 8},
35
+ "display_order": 1,
36
+ "color_theme": "emerald",
37
+ "icon": "✨"
38
+ },
39
+ {
40
+ "title_ar": "الأكثر مبيعاً",
41
+ "title_en": "Best Sellers",
42
+ "subtitle_ar": "المنتجات الأكثر طلباً هذا الأسبوع",
43
+ "subtitle_en": "Most popular items this week",
44
+ "section_type": "AUTOMATIC",
45
+ "rule": {"is_featured": True, "limit": 8},
46
+ "display_order": 2,
47
+ "color_theme": "blue",
48
+ "icon": "🔥"
49
+ },
50
+ {
51
+ "title_ar": "عروض الأجهزة الإلكترونية",
52
+ "title_en": "Electronics Deals",
53
+ "subtitle_ar": "أفضل الأسعار على الجوالات والملحقات",
54
+ "subtitle_en": "Best prices on phones and accessories",
55
+ "section_type": "AUTOMATIC",
56
+ "rule": {
57
+ "category_id": cat_map.get("Electronics", 1),
58
+ "limit": 4,
59
+ "sort_by": "discount"
60
+ },
61
+ "display_order": 3,
62
+ "color_theme": "amber",
63
+ "icon": "📱"
64
+ },
65
+ {
66
+ "title_ar": "عالم الألعاب",
67
+ "title_en": "Gaming World",
68
+ "subtitle_ar": "اكتشف تشكيلة واسعة من مستلزمات الألعاب",
69
+ "subtitle_en": "Explore our wide range of gaming gear",
70
+ "section_type": "AUTOMATIC",
71
+ "rule": {
72
+ "category_id": cat_map.get("Gaming", 3),
73
+ "limit": 8
74
+ },
75
+ "display_order": 4,
76
+ "color_theme": "indigo",
77
+ "icon": "🎮"
78
+ }
79
+ ]
80
+
81
+ for data in sections_data:
82
+ section = HomeSection(**data)
83
+ db.add(section)
84
+
85
+ db.commit()
86
+ print(f"Successfully seeded {len(sections_data)} home sections.")
87
+
88
+ if __name__ == "__main__":
89
+ try:
90
+ seed_home_sections()
91
+ except Exception as e:
92
+ print(f"Error seeding: {e}")
93
+ finally:
94
+ db.close()
seed_log.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ C:\Users\hisha\.pyenv\pyenv-win\versions\3.12.0\Lib\site-packages\requests\__init__.py:113: RequestsDependencyWarning: urllib3 (2.6.2) or chardet (7.0.1)/charset_normalizer (3.4.4) doesn't match a supported version!
2
+ warnings.warn(
3
+ >>> [LAUNCHER] Starting Hierarchical Seeding...
4
+ >>> [SEED] Clearing existing data...
5
+ - Cleared product_images
6
+ - Cleared cart_items
7
+ - Cleared reviews
8
+ - Cleared payment_details
9
+ - Cleared payments
10
+ - Cleared order_items
11
+ - Cleared orders
12
+ - Cleared addresses
13
+ - Cleared products
14
+ - Cleared categories
15
+ - Cleared coupons
16
+ - Cleared store_settings
17
+ - Cleared notifications
18
+ >>> [SEED] Creating default store settings...
19
+ >>> [SEED] Progress: 20 products committed...
20
+ >>> [SEED] Progress: 40 products committed...
21
+ >>> [SEED] Progress: 60 products committed...
22
+ >>> [SEED] Progress: 80 products committed...
23
+ >>> [SEED] Progress: 100 products committed...
24
+ >>> [SEED] Progress: 120 products committed...
25
+ >>> [SEED] Progress: 140 products committed...
26
+ >>> [SEED] Progress: 160 products committed...
27
+ >>> [LAUNCHER] Seeding Complete!
28
+ >>> Result: {'message': '(psycopg2.errors.ForeignKeyViolation) insert or update on table "products" violates foreign key constraint "products_category_id_fkey"\nDETAIL: Key (category_id)=(79) is not present in table "categories".\n\n[SQL: INSERT INTO products (name_ar, name_en, description_ar, description_en, price, compare_price, stock, category_id, rating, rating_count, is_featured, is_active, specs, created_at, deleted_at, deleted_by, deletion_reason, quality_score) VALUES (%(name_ar)s, %(name_en)s, %(description_ar)s, %(description_en)s, %(price)s, %(compare_price)s, %(stock)s, %(category_id)s, %(rating)s, %(rating_count)s, %(is_featured)s, %(is_active)s, %(specs)s, %(created_at)s, %(deleted_at)s, %(deleted_by)s, %(deletion_reason)s, %(quality_score)s) RETURNING products.id]\n[parameters: {\'name_ar\': \'������� ������� ��� 36� 5 ��� 256 ���ǡ ����\', \'name_en\': \'SAMSUNG Galaxy A36, 5G, 256 GB, Awesome White\', \'description_ar\': \'����� ������� ������� ��� 36� 5 ��� 256 ���ǡ ���� �� ������ �����! .\', \'description_en\': \'Buy SAMSUNG Galaxy A36, 5G, 256 GB, Awesome White from eXtra today!\', \'price\': 1099.0, \'compare_price\': 1399.0, \'stock\': 53, \'category_id\': 79, \'rating\': 4.5, \'rating_count\': 20, \'is_featured\': False, \'is_active\': True, \'specs\': \'{"origin": "Saudi Arabia", "condition": "New Genuine", "rating": 3.73, "warranty": "1 Year Official KSA Warranty", "sku_base": "EXT-SKU-162", "source ... (4914 characters truncated) ... , "name_ar": "\\\\u0662\\\\u0665\\\\u0666 \\\\u062c\\\\u064a\\\\u062c\\\\u0627\\\\u0628\\\\u0627\\\\u064a\\\\u062a", "price_modifier": 0.0, "stock": 13, "image_url": ""}]}\', \'created_at\': datetime.datetime(2026, 3, 20, 21, 10, 27, 701730, tzinfo=datetime.timezone.utc), \'deleted_at\': None, \'deleted_by\': None, \'deletion_reason\': None, \'quality_score\': 100}]\n(Background on this error at: https://sqlalche.me/e/20/gkpj)'}
tmp/check_import.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from sqlalchemy import create_engine, text
4
+ from dotenv import load_dotenv
5
+
6
+ # Load env from backend
7
+ load_dotenv("backend/.env")
8
+ db_url = os.getenv("DATABASE_URL")
9
+
10
+ if not db_url:
11
+ print("[ERROR] DATABASE_URL not found in backend/.env")
12
+ exit(1)
13
+
14
+ # Handle potential psql prefix
15
+ if db_url.startswith("postgres://"):
16
+ db_url = db_url.replace("postgres://", "postgresql://", 1)
17
+
18
+ engine = create_engine(db_url)
19
+
20
+ def check_db():
21
+ with engine.connect() as conn:
22
+ # Check Products
23
+ p_res = conn.execute(text("SELECT count(*) FROM products"))
24
+ p_count = p_res.scalar()
25
+
26
+ # Check Categories
27
+ c_res = conn.execute(text("SELECT count(*) FROM categories"))
28
+ c_count = c_res.scalar()
29
+
30
+ # Check Images
31
+ i_res = conn.execute(text("SELECT count(*) FROM product_images"))
32
+ i_count = i_res.scalar()
33
+
34
+ # Check Sample Product
35
+ sample_res = conn.execute(text("SELECT name_en, price FROM products LIMIT 5"))
36
+ samples = sample_res.fetchall()
37
+
38
+ print(f"--- Database Report ---")
39
+ print(f"Products: {p_count}")
40
+ print(f"Categories: {c_count}")
41
+ print(f"Product Images: {i_count}")
42
+ print(f"Sample Products:")
43
+ for s in samples:
44
+ print(f" - {s[0]} ({s[1]} SAR)")
45
+
46
+ if __name__ == "__main__":
47
+ check_db()
trigger_seed.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+
4
+ url = "http://localhost:8000/api/seed?clear=true"
5
+ try:
6
+ print(f"Triggering seed at {url}...")
7
+ response = requests.post(url)
8
+ print(f"Status Code: {response.status_code}")
9
+ print("Response:")
10
+ print(json.dumps(response.json(), indent=2, ensure_ascii=False))
11
+ except Exception as e:
12
+ print(f"Error: {e}")
upload_to_hf.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ from huggingface_hub import HfApi
4
+ from dotenv import load_dotenv
5
+
6
+ load_dotenv()
7
+
8
+ REPO_ID = "hisham-cmd/VortexCommerceBackend"
9
+ HF_TOKEN = os.environ.get("HF_TOKEN")
10
+
11
+ api = HfApi(token=HF_TOKEN)
12
+
13
+ def prepare_assets():
14
+ """Prepare any assets like fonts before uploading."""
15
+ print(">>> [PREPARE] Preparing assets...")
16
+ font_src = os.path.join("..", "frontend", "public", "ArbFONTS-cocon-next-arabic.ttf")
17
+ font_dest_dir = "fonts"
18
+ font_dest = os.path.join(font_dest_dir, "ArbFONTS-cocon-next-arabic.ttf")
19
+
20
+ if os.path.exists(font_src):
21
+ os.makedirs(font_dest_dir, exist_ok=True)
22
+ shutil.copy(font_src, font_dest)
23
+ print(f"[*] Copied font: {font_dest}")
24
+ else:
25
+ print(f"[!] Warning: Font source not found at {font_src}")
26
+
27
+ def upload():
28
+ # 1. Prepare assets
29
+ prepare_assets()
30
+
31
+ print(f"\n>>> [SYNC] Uploading to Hugging Face: https://huggingface.co/spaces/{REPO_ID}")
32
+ print("[*] Using DIFFERENTIAL SYNC (fastest) - only changed files will be uploaded.")
33
+
34
+ try:
35
+ # Ensure repo exists
36
+ api.create_repo(repo_id=REPO_ID, repo_type="space", space_sdk="docker", private=False, exist_ok=True)
37
+
38
+ # Upload folder using both .hfignore and explicit ignore patterns for speed
39
+ api.upload_folder(
40
+ repo_id=REPO_ID,
41
+ folder_path=".",
42
+ repo_type="space",
43
+ commit_message="Optimized Sync: Differential Upload & Performance Tweak",
44
+ ignore_patterns=[
45
+ ".git/*", ".venv/*", "venv/*", "__pycache__/*",
46
+ "*.db", "*.sqlite*", ".env*", "*.env",
47
+ "scripts/*", "tests/*", "node_modules/*", ".pytest_cache/*",
48
+ "*.pyc", "*.pyo"
49
+ ],
50
+ delete_patterns=["*.pyc", "__pycache__/*"], # Extra cleanup
51
+ )
52
+
53
+ print("\n" + "="*50)
54
+ print(f"[OK] SUCCESS!")
55
+ print(f"[SYS] Differential sync complete.")
56
+ print(f"[LINK] https://huggingface.co/spaces/{REPO_ID}")
57
+ print("="*50)
58
+
59
+ except Exception as e:
60
+ print(f"\n[ERROR] {e}")
61
+
62
+ if __name__ == "__main__":
63
+ upload()