Spaces:
Runtime error
Runtime error
Update app.py
Browse files12345678917 unmodified lines272829303132333435366 unmodified lines434445464748495 unmodified lines555657585960617 unmodified lines6970717273747525 unmodified lines1011021031041051061073 unmodified lines1111121131141151161171184 unmodified lines123124125126127128129130131132133134135136137138139140141142143144145146147148149150import sqlite3from pathlib import Pathfrom fastapi import FastAPI, HTTPException, statusimport gradio as grimport joblibimport pandas as pdBASE_DIR = Path(__file__).resolve().parent17 unmodified lines)# API Endpoints@app.get("/health", status_code=status.HTTP_200_OK)def health_check():return {"ok": True, "message": "healthy"}@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 databasecustomer = pd.read_sql_query("SELECT customer_id FROM dim_customers WHERE customer_id = ?",conn,5 unmodified linesdetail=f"Customer '{customer_id}' not found",)# Look up customer's precomputed clusteruser_segment = pd.read_sql_query("SELECT cluster FROM customer_segments WHERE customer_id = ?",conn,7 unmodified linescluster_id = int(user_segment["cluster"].iloc[0])# Retrieve candidate products bought by peers in the same clustercandidate_query = """SELECToi.discount,25 unmodified linesdetail="No candidate items found for this cluster",)# Predict profitability using the classification pipelinefeature_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],}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 osimport uvicornport = int(os.environ.get("PORT", 7860))uvicorn.run(app, host="0.0.0.0", port=port)1234567891017 unmodified lines282930313233343536373839406 unmodified lines4748495051525 unmodified lines5859606162637 unmodified lines71727374757625 unmodified lines1021031041051061073 unmodified lines1111121131141151164 unmodified lines121122123124125126127128129130131132import osfrom pathlib import Pathimport sqlite3from fastapi import FastAPI, HTTPException, statusimport joblibimport pandas as pdimport uvicornBASE_DIR = Path(__file__).resolve().parent17 unmodified lines)@app.get("/", status_code=status.HTTP_200_OK)@app.get("/health", status_code=status.HTTP_200_OK)def health_check():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):customer = pd.read_sql_query("SELECT customer_id FROM dim_customers WHERE customer_id = ?",conn,5 unmodified linesdetail=f"Customer '{customer_id}' not found",)user_segment = pd.read_sql_query("SELECT cluster FROM customer_segments WHERE customer_id = ?",conn,7 unmodified linescluster_id = int(user_segment["cluster"].iloc[0])candidate_query = """SELECToi.discount,25 unmodified linesdetail="No candidate items found for this cluster",)feature_cols = ["discount","shipping_cost",3 unmodified lines"sub_category",]predictions = clf_model.predict(candidates[feature_cols])profitable = candidates[predictions == 1]recommendations = []4 unmodified lines})return {"customer_id": customer_id,"cluster": cluster_id,"total_profitable_found": len(recommendations),"recommendations": recommendations[:n],}if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)
app.py+13-31