manasranjanpani's picture
Upload folder using huggingface_hub
197f994 verified
import streamlit as st
import pandas as pd
import requests
# Set the title of the Streamlit app
st.title("ExtraaLearn Customer Prediction")
# Section for online prediction
st.subheader("Single Customer Prediction")
# Collect user input for customer features
age = st.number_input("Age", min_value=15, max_value=80, step=1, value=25)
current_occupation = st.selectbox("Current Occupation", [
"Student", "Unemployed", "Employed", "Self-Employed", "Professional"
])
first_interaction = st.selectbox("First Interaction", [
"Website", "Mobile App", "Referral", "Advertisement", "Social Media"
])
# Updated: profileCompleted as dropdown with High/Medium/Low
profile_completed = st.selectbox("Profile Completed", ["High", "Medium", "Low"])
website_visits = st.number_input("Website Visits", min_value=0, max_value=100, step=1, value=15)
time_spent_on_website = st.number_input("Time Spent on Website (seconds)", min_value=0, max_value=3600, step=10, value=1200)
page_views_per_visit = st.number_input("Page Views Per Visit", min_value=1, max_value=20, step=1, value=8)
last_activity = st.selectbox("Last Activity", [
"Login", "Course View", "Payment Page", "Profile Update", "Website Activity"
])
print_media_type1 = st.selectbox("Print Media Type 1", ["Yes", "No"])
print_media_type2 = st.selectbox("Print Media Type 2", ["Yes", "No"])
digital_media = st.selectbox("Digital Media", ["Yes", "No"])
educational_channels = st.selectbox("Educational Channels", ["Yes", "No"])
referral = st.selectbox("Referral", ["Yes", "No"])
# Convert user input into a dictionary matching the API requirements
input_data = {
'age': age,
'currentOccupation': current_occupation,
'firstInteraction': first_interaction,
'profileCompleted': profile_completed, # This will now be "High", "Medium", or "Low"
'websiteVisits': website_visits,
'timeSpentOnWebsite': time_spent_on_website,
'pageViewsPerVisit': page_views_per_visit,
'lastActivity': last_activity,
'printMediaType1': print_media_type1,
'printMediaType2': print_media_type2,
'digitalMedia': digital_media,
'educationalChannels': educational_channels,
'referral': referral
}
# Make prediction when the "Predict" button is clicked
if st.button("Predict Customer Conversion"):
try:
response = requests.post(
"https://manasranjanpani-extraalearncustomerpredictionbackend.hf.space/v1/customers",
json=input_data
)
if response.status_code == 200:
result = response.json()
prediction = result['predicted_customer_status']
st.success(f"Predicted Customer Conversion Score: {prediction:.2f}")
# Display additional info if available
if 'input_received' in result:
st.info(f"Processed {len(result['input_received']['fields_processed'])} features successfully")
else:
error_data = response.json()
st.error(f"Error making prediction: {error_data.get('error', 'Unknown error')}")
except requests.exceptions.RequestException as e:
st.error(f"Connection error: {e}")
except Exception as e:
st.error(f"Unexpected error: {e}")
# Section for batch prediction
st.subheader("Batch Prediction")
# Allow users to upload a CSV file for batch prediction
uploaded_file = st.file_uploader("Upload CSV file for batch prediction", type=["csv"])
if uploaded_file is not None:
# Display preview of uploaded data
st.write("Preview of uploaded data:")
batch_data = pd.read_csv(uploaded_file)
st.dataframe(batch_data.head())
# Check if required columns are present
required_columns = list(input_data.keys())
missing_columns = [col for col in required_columns if col not in batch_data.columns]
if missing_columns:
st.warning(f"Missing required columns in CSV: {missing_columns}")
st.info(f"Required columns: {required_columns}")
else:
st.success("All required columns present!")
# Make batch prediction when the "Predict Batch" button is clicked
if uploaded_file is not None and st.button("Predict Batch"):
try:
# Reset file pointer to beginning
uploaded_file.seek(0)
response = requests.post(
"https://manasranjanpani-extraalearncustomerpredictionbackend.hf.space/v1/customersbatch",
files={"file": uploaded_file}
)
if response.status_code == 200:
predictions = response.json()
st.success("Batch predictions completed!")
# Display predictions in a nice format
if 'predictions' in predictions:
st.write("Predictions:")
for i, pred in enumerate(predictions['predictions']):
st.write(f"Customer {i+1}: {pred:.2f}")
else:
# If predictions are keyed by ID
predictions_df = pd.DataFrame(list(predictions.items()), columns=['Customer ID', 'Prediction'])
st.dataframe(predictions_df)
else:
error_data = response.json()
st.error(f"Error making batch prediction: {error_data.get('error', 'Unknown error')}")
except requests.exceptions.RequestException as e:
st.error(f"Connection error: {e}")
except Exception as e:
st.error(f"Unexpected error: {e}")
# Add information section
st.subheader("Check API Status")
if st.button("Check API Status"):
try:
response = requests.get("https://manasranjanpani-extraalearncustomerpredictionbackend.hf.space/ping")
if response.status_code == 200:
st.success("API is running and responsive")
else:
st.error("API is not responding properly")
except:
st.error("Cannot connect to API")