Spaces:
Sleeping
Sleeping
Update app.py
Browse files8 unmodified lines910111213141516171819202122232425262714 unmodified lines42434445464748495051525354552 unmodified lines58596061626364183 unmodified lines24824925025125225330 unmodified lines28428528628728828929020 unmodified lines3113123133143153163178 unmodified linespreprocessor_path = 'modelExports/preprocessor.pkl'preprocessor = joblib.load(preprocessor_path)def process_uploaded_file(uploaded_file, required_columns):try:file_extension = uploaded_file.name.split('.')[-1].lower()if file_extension == 'csv':df = pd.read_csv(uploaded_file)elif file_extension in ['xlsx', 'xls']:df = pd.read_excel(uploaded_file, engine='openpyxl')else:st.error("Unsupported file format. Please upload a CSV or Excel file.")return None# Standardize column names to uppercase and strip spacesdf.columns = df.columns.str.upper().str.strip()st.write("DataFrame columns:", df.columns.tolist())14 unmodified linesst.error(f"Error reading the file: {e}")return Nonedef predict_with_model(model, data, includes_preprocessor):if includes_preprocessor:return model.predict(data)else:return model.predict(preprocessor.transform(data))def create_model_output(df, predictions, model_name):output_df = df[['PID']].copy() # Keep PID from original dataframeoutput_df['Prediction'] = predictions2 unmodified lineslambda x: 'Yes' if x == 1 else 'No')return output_df# Load models and record whether they include the preprocessormodel_folder = 'modelExports'models = {}183 unmodified linesif df is None:st.stop()# Convert numerical columns to numeric data typesnumerical_columns = ['BILLING_ZIP', 'ACTIVE_SUBSCRIBERS', 'NOT_ACTIVE_SUBSCRIBERS',30 unmodified linestry:# Prepare data for predictiondata_for_prediction = df[required_columns[1:]] # Exclude 'PID'if not includes_preprocessor:data_for_prediction = preprocessor.transform(data_for_prediction)20 unmodified lineselse:st.info('Awaiting CSV or Excel file to be uploaded.')# Sidebar informationst.sidebar.write("### Model Information")st.sidebar.write(f"Total models available: {len(models)}")8 unmodified lines9101112131415161718192021222324252627282930313233343536373839404142434445464748495014 unmodified lines6566676869707172737475762 unmodified lines798081828384183 unmodified lines26826927027127227327427527630 unmodified lines30730830931031131231320 unmodified lines3343353363373383398 unmodified linespreprocessor_path = 'modelExports/preprocessor.pkl'preprocessor = joblib.load(preprocessor_path)def find_header_row(df, required_columns, max_rows_to_check=10):required_columns_upper = [col.upper().strip() for col in required_columns]for i in range(min(max_rows_to_check, len(df))):row_values = [str(val).upper().strip() for val in df.iloc[i].values]if all(col in row_values for col in required_columns_upper):return i # Header row found at row ireturn -1 # Header row not founddef process_uploaded_file(uploaded_file, required_columns):try:file_extension = uploaded_file.name.split('.')[-1].lower()if file_extension == 'csv':# Read the first few rows to check for headersdf = pd.read_csv(uploaded_file, nrows=10, header=None)elif file_extension in ['xlsx', 'xls']:df = pd.read_excel(uploaded_file, nrows=10, header=None, engine='openpyxl')else:st.error("Unsupported file format. Please upload a CSV or Excel file.")return Noneheader_row = find_header_row(df, required_columns)if header_row == -1:st.error(f"Required columns not found in the first {len(df)} rows.")st.write("Expected columns:", required_columns)st.write("Found data rows:", df.head().values.tolist())return None# Re-read the file with the correct header rowuploaded_file.seek(0) # Reset file pointerif file_extension == 'csv':df = pd.read_csv(uploaded_file, header=header_row)else:df = pd.read_excel(uploaded_file, header=header_row, engine='openpyxl')# Standardize column names to uppercase and strip spacesdf.columns = df.columns.str.upper().str.strip()st.write("DataFrame columns:", df.columns.tolist())14 unmodified linesst.error(f"Error reading the file: {e}")return Nonedef predict_with_model(model, data, includes_preprocessor):if includes_preprocessor:return model.predict(data)else:return model.predict(preprocessor.transform(data))def create_model_output(df, predictions, model_name):output_df = df[['PID']].copy() # Keep PID from original dataframeoutput_df['Prediction'] = predictions2 unmodified lineslambda x: 'Yes' if x == 1 else 'No')return output_df# Load models and record whether they include the preprocessormodel_folder = 'modelExports'models = {}183 unmodified linesif df is None:st.stop()# Standardize required columns to uppercase and strip spacesrequired_columns_upper = [col.upper().strip() for col in required_columns]# Convert numerical columns to numeric data typesnumerical_columns = ['BILLING_ZIP', 'ACTIVE_SUBSCRIBERS', 'NOT_ACTIVE_SUBSCRIBERS',30 unmodified linestry:# Prepare data for predictiondata_for_prediction = df[required_columns_upper[1:]] # Exclude 'PID'if not includes_preprocessor:data_for_prediction = preprocessor.transform(data_for_prediction)20 unmodified lineselse:st.info('Awaiting CSV or Excel file to be uploaded.')# Sidebar informationst.sidebar.write("### Model Information")st.sidebar.write(f"Total models available: {len(models)}")
app.py+29-7