跳到正文
DEV Community· Sanjana Devi·· 2 小時前AI 評分40

Restock-Predictor:以 TabPFN 預測 Etsy、Shopify 獨立賣家的庫存

Restock-Predictor: AI-Powered Inventory Forecasting for Etsy & Shopify Side Hustles with TabPFN

AI 導讀

Restock-Predictor 是為 Etsy、Shopify 獨立賣家打造的 AI 庫存預測工具,採用開放權重模型 TabPFN 進行零樣本上下文表格回歸。用戶上載歷史銷售 CSV 後,系統可在兩秒內估算未來 30 天需求及第 90 百分位安全庫存,並生成可匯出 CSV 的優先採購訂單。項目以 MIT 授權開源,並使用 MongoDB Atlas 記錄批次。

正文

This is a submission for the Hacktoberfest Open-Source AI Challenge Week 2: Side Hustle


What I Built

Independent e-commerce creators—especially Etsy artisans, Shopify boutique owners, and print-on-demand side hustlers—routinely suffer from the "Inventory Trap":

  1. The Cost of Stockouts: Missing sudden weekend demand surges because raw materials ran out, directly leaving revenue on the table and hurting marketplace search rankings.
  2. The Curse of Dead Stock: Over-ordering slow-moving catalog variants, tying up scarce working capital that should be funding marketing or new product launches.

Large enterprises solve this with multimillion-dollar ERP systems like SAP or NetSuite, or expensive $300/month demand forecasting SaaS tools. Solopreneurs and side hustlers, on the other hand, are left guessing in Excel sheets or frantically reordering supplies after they've already sold out.

Restock-Predictor is an AI-powered inventory intelligence micro-SaaS built specifically for these independent sellers.

Store owners simply drag and drop their historical sales export (columns: Date, Item_ID, Quantity_Sold). Within two seconds, the platform:

  • Analyzes multi-item sales velocity, weekly cycles, and seasonal momentum.
  • Runs zero-shot tabular in-context regression via the TabPFN open-weight foundation model.
  • Computes both expected 30-day demand and probabilistic 90th-percentile safety stock buffers to prevent stockouts during peak surges.
  • Generates an actionable, prioritized Purchase Order (PO) table with one-click CSV export for suppliers.
  • Logs every batch to MongoDB Atlas for audit history and usage tracking.

Who Would Pay For It?

Etsy makers and Shopify side hustlers generating \$2,000 to \$25,000/month in revenue. For an artisan maker, avoiding just one single stockout on a high-margin weekend pays for an entire year of a \$15–\$25/month subscription.


Demo

  • Live Deployed Application: https://restock-predictor.onrender.com/
  • Quick-Start Test Baseline: The app includes a built-in "Load Pre-Packaged Sample CSV" button in the sidebar that instantaneously loads 90 continuous days of sales across 3 distinct Etsy inventory archetypes (SKU-SOY-CANDLE, SKU-CERAMIC-MUG, SKU-LINEN-TOTE).

Key UI Features:

  • Obsidian & Electric Indigo Glassmorphism: Sleek, modern SaaS aesthetic with blurred backdrops, crisp typography (Plus Jakarta Sans), and zero default-Streamlit clutter.
  • Interactive Multi-Series Plotly Visualizations: Historical sales actuals seamlessly stitched to 30-day TabPFN forecasts with a shaded translucent amber confidence ribbon representing the 90% safety buffer ceiling.
  • Executive Metric Cards with Colored Deltas: High-level demand growth (+X.X% vs prior 30d), safety stock buffer ratios, and SKU health tracking.
  • Prioritized Procurement Table: Color-gradient styled data table ranking items by restock urgency.

Code

⚡ Restock-Predictor: Premium AI Inventory Intelligence

A High-Aesthetic Minimum Viable Product (MVP) for e-commerce side hustles and independent makers (Etsy/Shopify), submitted for the DEV.to Hacktoberfest Open-Source AI Challenge.

DEV.to Hacktoberfest Deploy to Render TabPFN MongoDB Streamlit Plotly


🌟 Executive Summary & Problem Statement

Independent e-commerce makers frequently face the "Inventory Trap":

  1. Stockouts: Missing out on sudden weekend surges and leaving money on the table.
  2. Dead Stock: Over-purchasing slow-moving catalog items and tying up critical working capital.

Traditional time-series forecasting requires extensive statistical tuning (ARIMA stationarity, Prophet holidays, or iterative GBDTs like XGBoost). Meanwhile, attempting to use standard LLMs (like GPT-4) fails due to token arithmetic hallucinations, linear drift failures, and extreme prompt token costs.

Restock-Predictor solves this with a TabPFN (Prior-Data Fitted Network) foundation model — performing zero-shot in-context regression in sub-second inference. Combined with MongoDB Atlas for audit logging and Streamlit + Plotly styled in an obsidian glassmorphism SaaS theme, store owners can upload…

Modular Project Architecture:

  • .streamlit/config.toml: Custom dark-mode SaaS palette definitions and server configs.
  • app.py: Streamlit frontend featuring custom glassmorphism CSS, Plotly multi-series charts, tabs, and delta metrics.
  • predictor.py: TabPFN API client (tabpfn-client), time-series tabular feature extraction, and quantile probabilistic forecasting.
  • db.py: MongoDB Atlas connection manager with latency timeouts, ping verification, and resilient session auditing.
  • render.yaml: Infrastructure as Code (IaC) blueprint for one-click deployment on Render.
  • sample_data.csv: 270-row baseline dataset modeled with weekend lifts and realistic trends.

How I Built It

1. The Core AI Model: TabPFN (Prior-Data Fitted Network)

Instead of forcing a language model to do math, Restock-Predictor is built around TabPFN (tabpfn-client), an open-weight foundation model designed purely for tabular data.

TabPFN was pre-trained on millions of synthetic tabular datasets to approximate Bayesian inference in a single transformer forward pass. It requires:

  • No iterative gradient boosting (unlike XGBoost or LightGBM).
  • No hyperparameter tuning or cross-validation loops.
  • No stationarity transformations or ARIMA parameter searching.

Tabular Feature Engineering Pipeline (predictor.py)

To feed TabPFN the cleanest tabular signal, we extract structural temporal features from the raw sales timestamps:

# Extract tabular representations for TabPFN's in-context attention mechanism
df["day_index"] = (df["Date"] - min_date).dt.days        # Continuous linear drift
df["day_of_week"] = df["Date"].dt.dayofweek              # Weekly seasonality (0=Mon, 6=Sun)
df["is_weekend"] = df["day_of_week"].apply(lambda w: 1 if w >= 5 else 0) # Weekend Etsy spikes
df["day_of_month"] = df["Date"].dt.day                   # Payday purchasing patterns
df["rolling_7d_mean"] = df["Quantity_Sold"].rolling(7, min_periods=1).mean() # Current demand baseline
df["lag_7"] = df["Quantity_Sold"].shift(7).fillna(...)   # Same-day previous week anchor

Probabilistic Quantile Forecasting

Inventory forecasting isn't just about the average—it's about the risk tail. We query TabPFN for both median expectations and 90th-percentile quantiles:

# Predict both expected demand (median) and 90% risk ceiling for safety stock
quantiles = model.predict(X_future, output_type="quantiles", quantiles=[0.5, 0.9])
expected_demand = quantiles[:, 0]
safety_stock_ceiling = quantiles[:, 1]

2. Frontend & Visual Polish (Streamlit + Plotly)

We established a bespoke aesthetic by pairing .streamlit/config.toml with custom CSS injected via st.markdown:

  • Transparent dark glassmorphic cards with subtle 1px solid rgba(255, 255, 255, 0.08) borders.
  • Interactive Plotly figures with custom tooltips, unified crosshairs, and shaded confidence ribbons (fill="tonexty").
  • Tabbed layout organizing views into Forecasts, Purchase Orders, SKU Trends, and MongoDB Audit Telemetry.

3. Cloud Audit Trails (MongoDB Atlas)

Every upload triggers a non-blocking insert into MongoDB Atlas via pymongo:

log_doc = {
    "timestamp": datetime.now(timezone.utc).isoformat(),
    "filename": filename,
    "row_count": total_rows,
    "item_count": item_count,
    "items": unique_items,
    "metadata": metadata_payload
}
collection.insert_one(log_doc)

If network restrictions or unconfigured credentials arise during demo testing, a resilient session fallback catches the exception so the UI never crashes.

4. Continuous Deployment on Render

Configured via render.yaml with automated pip package resolution and Streamlit port binding to Render's dynamic $PORT.


Why Does Open Innovation Matter?

Why build with an open-weight tabular foundation model like TabPFN instead of calling a closed-source general LLM like GPT-4 or Claude?

1. Continuous Numerical Precision vs. Token Hallucinations

Generative LLMs represent numbers as discrete Byte-Pair Encoding (BPE) tokens. They have no innate understanding of continuous mathematics, often hallucinating sums, failing to extrapolate gradual linear declines, or inventing phantom sales spikes. TabPFN is a specialized transformer trained on synthetic prior mathematical functions, treating numerical values with mathematical continuity.

2. Sub-Second Bayesian Inference (< 500ms)

Generating 30 days of multi-item forecasts through an autoregressive text LLM requires generating hundreds of output tokens sequentially, taking 8 to 15 seconds. TabPFN processes the entire feature matrix in a single forward pass in less than 500 milliseconds.

3. Native Probabilistic Uncertainty

Inventory planners cannot rely on deterministic point estimates alone; they need to know the volatility spread to calculate safety stock. Closed LLMs can only provide hand-wavy descriptions ("sales might surge on weekends"). TabPFN outputs true mathematical predictive distributions and quantiles.

4. Data Privacy & Zero Token Inflation

Feeding 90 days of multi-item sales logs into a commercial chat API consumes tens of thousands of tokens per run and exposes confidential boutique business metrics to third-party commercial training pools. TabPFN accepts compact numerical arrays locally or via lightweight API endpoints without token bloat.


My Agent Session

This entire project was engineered collaboratively with Antigravity, an agentic pair programmer.

What We Tackled:

  1. Infrastructure as Code: Architecting render.yaml to overcome common Streamlit PaaS deployment traps (binding to 0.0.0.0, dynamic $PORT handling, and disabling CORS/XSRF for Render).
  2. Tabular Feature Engineering: Designing the rolling window and lag feature transformer in predictor.py to maximize TabPFN's in-context attention.
  3. Resilient Architecture: Writing db.py with tight socket timeouts and graceful session fallbacks so the app works flawlessly out of the box even before external credentials are plugged in.
  4. UI/UX Elevation: Transforming a default Streamlit layout into a glassmorphic dark SaaS interface complete with interactive Plotly confidence bands and styled gradient dataframes.

My First User

To test Restock-Predictor with a real-world side hustle, I shared the live Render deployment with Priya, an independent maker running a hand-poured candle and artisan ceramics shop on Etsy.

The Problem:

Priya had been ordering candle wax and ceramic clay in arbitrary batches every two weeks. Last month, a sudden weekend feature on an Etsy curation feed caused her best-selling soy candle to sell out in 36 hours. She missed out on an estimated \$340 in lost sales while waiting 5 days for a new shipment of soy wax flakes.

The Test Run:

Priya exported her last 90 days of sales as a CSV and uploaded it to Restock-Predictor on Render.

Her Feedback:

"Seeing the amber 'Safety Buffer' band on the chart made it immediately obvious why I keep running out of stock on weekends. My base sales look manageable, but the weekend surge pushes demand way past my typical reorder point. Having an exact restock number with safety buffer included—and being able to download it as a spreadsheet—saved me hours of manual math."

Next Feature Request:

Priya asked if future versions could let her input lead times for her suppliers (e.g., "supplier takes 6 days to deliver") so the app can alert her on the exact calendar day she needs to submit her order.


Prize Categories

🌟 Best Use of Render ($200 Featured Category)

Restock-Predictor is deployed natively on Render using an Infrastructure as Code blueprint (render.yaml).

  • Zero-Downtime Web Service: Configured with Python 3.11, automatic dependency caching, and clean port forwarding via streamlit run app.py --server.port $PORT --server.address 0.0.0.0.
  • Production Health Checks: Health check polling wired directly to Streamlit's native endpoint /_stcore/health.
  • Secure Secret Decoupling: Database credentials (MONGO_URI) and model tokens (TABPFN_API_KEY) are managed through Render's environment dashboard (sync: false), keeping the public repository fully secure.

⚡ Best Use of TabPFN ($200 Featured Category)

TabPFN (tabpfn-client) is the algorithmic core of the platform. We utilize TabPFN's zero-shot in-context learning to perform tabular regression across engineered time-series features without hyperparameter tuning, and extract probabilistic 90th-percentile quantiles to calculate inventory safety stocks.

🍃 Best Use of MongoDB Atlas ($100 Partner Category)

All upload batches, row counts, unique catalog SKUs, and processing metadata are immutably logged to a MongoDB Atlas cluster (pymongo). A dedicated audit tab in the dashboard provides store owners with transparent traceability over past inventory analysis runs.

來源:DEV Community · dev.to