Spaces:
Runtime error
Runtime error
Update app.py
Browse files112344567891017 unmodified lines2829303031323333343536373839406 unmodified lines474849465051525 unmodified lines585960586162637 unmodified lines7172737274757625 unmodified lines1021031041041051061073 unmodified lines1111121131141151141151164 unmodified lines121122123126127128129124125126127128129130133134135136137138139140141142143144131146147148149150132import sqlite3import osfrom pathlib import Pathimport sqlite3from fastapi import FastAPI, HTTPException, statusimport gradio as grimport joblibimport pandas as pdimport uvicorn
BASE_DIR = Path(__file__).resolve().parent
17 unmodified lines)
# API Endpoints@app.get("/", status_code=status.HTTP_200_OK)@app.get("/health", status_code=status.HTTP_200_OK)def health_check(): return {"ok": True, "message": "healthy"} return { "status": "healthy", "message": "Superstore Recommendation API is live!", }
@app.get("/customers", status_code=status.HTTP_200_OK)6 unmodified lines
@app.get("/recommended/{customer_id}", status_code=status.HTTP_200_OK)def get_recommended_product(customer_id: str, n: int = 3): # Verify customer exists in database customer = pd.read_sql_query( "SELECT customer_id FROM dim_customers WHERE customer_id = ?", conn,5 unmodified lines detail=f"Customer '{customer_id}' not found", )
# Look up customer's precomputed cluster user_segment = pd.read_sql_query( "SELECT cluster FROM customer_segments WHERE customer_id = ?", conn,7 unmodified lines
cluster_id = int(user_segment["cluster"].iloc[0])
# Retrieve candidate products bought by peers in the same cluster candidate_query = """ SELECT oi.discount,25 unmodified lines detail="No candidate items found for this cluster", )
# Predict profitability using the classification pipeline feature_cols = [ "discount", "shipping_cost",3 unmodified lines "sub_category", ] predictions = clf_model.predict(candidates[feature_cols])
# Filter for profitable items only (1 = Profitable, 0 = Loss) profitable = candidates[predictions == 1]
recommendations = []4 unmodified lines })
return { "customer_id": customer_id, "cluster": cluster_id, "total_profitable_found": len(recommendations), "recommendations": recommendations[:n], "customer_id": customer_id, "cluster": cluster_id, "total_profitable_found": len(recommendations), "recommendations": recommendations[:n], }
with gr.Blocks(title="Product Recommender API") as demo: gr.Markdown( "# Product Recommender API\n" "Backend is **online and healthy**.\n\n" "- **Health Check**: `/health`\n" "- **Recommendations**: `/recommended/{customer_id}?n=3`\n" "- **Customer List**: `/customers`" )
app = gr.mount_gradio_app(app, demo, path="/")
if __name__ == "__main__": import os import uvicorn
port = int(os.environ.get("PORT", 7860)) uvicorn.run(app, host="0.0.0.0", port=port) uvicorn.run(app, host="0.0.0.0", port=7860)app.py+13-31