import gradio as gr import pandas as pd from catboost import CatBoostRegressor import os # 1. Load the model # Make sure 'catboost_skincare_model.cbm' is uploaded to the same Space model = CatBoostRegressor() if os.path.exists("catboost_skincare_model.cbm"): model.load_model("catboost_skincare_model.cbm") else: print("Model file not found!") def predict_rating(brand, product, cat1, cat2, origin, age_range, skin_type, concern, ing1, ing2, ing3): # 2. Feature Engineering: Age Mapping age_map = { '18 and Under': 'Teens', '19 - 24': 'Young Adult', '25 - 29': 'Young Adult', '30 - 34': 'Adult', '35 - 39': 'Adult', '40 - 44': 'Mature', '45 and Above': 'Mature' } age_segment = age_map.get(age_range, 'Young Adult') # 3. Feature Engineering: Ingredient Flags all_ings = f"{ing1} {ing2} {ing3}".lower() def check_ing(term): return "1" if term in all_ings else "0" # 4. Create DataFrame for prediction (Must match training column order) input_df = pd.DataFrame([{ 'brand_name': brand, 'product_name': product, '1st_category': cat1, '2nd_category': cat2, 'brand_country_origin': origin, 'age': age_range, 'skin_type': skin_type, 'skin_concern': concern, 'ingredient_1': ing1, 'ingredient_2': ing2, 'ingredient_3': ing3, # Engineered features the model expects 'age_segment': age_segment, 'has_niacinamide': check_ing('niacinamide'), 'has_retinol': check_ing('retinol'), 'has_salicylic_acid': check_ing('salicylic'), 'has_hyaluronic_acid': check_ing('hyaluronic'), 'has_vitamin_c': check_ing('vitamin c'), 'skin_profile': f"{skin_type}_{concern}", 'product_skin_fit': f"{cat2}_{skin_type}" }]) # 5. Predict prediction = model.predict(input_df) # Return rounded rating return round(float(prediction[0]), 2) # 6. Define the Gradio Interface inputs = [ gr.Textbox(label="Brand Name"), gr.Textbox(label="Product Name"), gr.Textbox(label="1st Category"), gr.Textbox(label="2nd Category"), gr.Textbox(label="Country of Origin"), gr.Dropdown(choices=['18 and Under', '19 - 24', '25 - 29', '30 - 34', '35 - 39', '40 - 44', '45 and Above'], label="Age Range"), gr.Textbox(label="Skin Type"), gr.Textbox(label="Skin Concern"), gr.Textbox(label="Ingredient 1"), gr.Textbox(label="Ingredient 2"), gr.Textbox(label="Ingredient 3") ] demo = gr.Interface( fn=predict_rating, inputs=inputs, outputs=gr.Number(label="Predicted Rating"), title="Skincare Rating Predictor API", api_name="predict_rating" ) if __name__ == "__main__": demo.launch(show_error=True, share=False)