Spaces:
Runtime error
Runtime error
Commit Β·
ebbb600
1
Parent(s): c3c3195
Update Streamlit app to support deployed backend with fallback to localhost
Browse files53 unmodified lines545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011 unmodified line1031041051061071081091101111121131141151161171181 unmodified line12012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636753 unmodified lines</style>""", unsafe_allow_html=True)# API base URLAPI_BASE = "http://localhost:8000"def check_backend_health():"""Check if backend is running"""try:response = requests.get(f"{API_BASE}/health", timeout=5)return response.status_code == 200except:return Falsedef upload_dataset(uploaded_file):"""Upload dataset to backend"""try:files = {'file': uploaded_file}response = requests.post(f"{API_BASE}/api/upload-dataset", files=files, timeout=30)if response.status_code == 200:return response.json()else:return Noneexcept Exception as e:st.error(f"Upload error: {str(e)}")return Nonedef process_pipeline(uploaded_file, prompt):"""Process dataset with ML pipeline"""try:files = {'file': uploaded_file}data = {'prompt': prompt}response = requests.post(f"{API_BASE}/process-pipeline", files=files, data=data, timeout=120)if response.status_code == 200:return response.json()else:st.error(f"Processing error: {response.text}")return Noneexcept Exception as e:st.error(f"Processing error: {str(e)}")return Nonedef download_file(filename):"""Generate download link for file"""return f"{API_BASE}/api/download/{filename}"def main():# Main header1 unmodified linest.markdown('<p style="text-align: center; color: #6b7280; font-size: 1.1rem;">Convert natural language prompts into ML-ready datasets</p>', unsafe_allow_html=True)# Check backend healthif not check_backend_health():st.error("β Backend is not running! Please start the backend first:")st.code("""cd promptprepml/backendvenv\\Scripts\\activatepython app/main.py""")returnst.success("β Backend is connected and ready!")# Sidebar for navigationst.sidebar.title("π Processing Steps")1 unmodified line# Initialize session stateif 'step' not in st.session_state:st.session_state.step = 'upload'if 'dataset_info' not in st.session_state:st.session_state.dataset_info = Noneif 'processing_results' not in st.session_state:st.session_state.processing_results = Noneif 'uploaded_file' not in st.session_state:st.session_state.uploaded_file = None# Step indicatorssteps = ['π€ Upload Dataset', 'π¬ Enter Prompt', 'β‘ Processing', 'π Results']step_mapping = {'upload': 0,'prompt': 1,'processing': 2,'results': 3}current_step_idx = step_mapping.get(st.session_state.step, 0)for i, step in enumerate(steps):if i <= current_step_idx:st.sidebar.markdown(f"β {step}")else:st.sidebar.markdown(f"β³ {step}")# Main content based on current stepif st.session_state.step == 'upload':st.markdown('<h2 class="step-header">π€ Upload Your Dataset</h2>', unsafe_allow_html=True)# File uploaduploaded_file = st.file_uploader("Choose a CSV file",type=['csv'],help="Upload your dataset in CSV format. Maximum file size: 200MB")if uploaded_file is not None:# Display file infost.markdown('<div class="info-box">', unsafe_allow_html=True)st.write(f"**Filename:** {uploaded_file.name}")st.write(f"**Size:** {uploaded_file.size / 1024 / 1024:.2f} MB")st.markdown('</div>', unsafe_allow_html=True)# Preview datatry:df = pd.read_csv(uploaded_file)st.write("**Data Preview:**")st.dataframe(df.head(), use_container_width=True)st.write(f"**Shape:** {df.shape[0]} rows Γ {df.shape[1]} columns")# Upload buttonif st.button("π Upload Dataset", type="primary"):with st.spinner("Uploading dataset..."):# Reset file pointeruploaded_file.seek(0)result = upload_dataset(uploaded_file)if result:st.session_state.dataset_info = resultst.session_state.uploaded_file = uploaded_file # Store the filest.session_state.step = 'prompt'st.rerun()else:st.error("Upload failed. Please try again.")except Exception as e:st.error(f"Error reading CSV file: {str(e)}")elif st.session_state.step == 'prompt':st.markdown('<h2 class="step-header">π¬ Describe Your Preprocessing Needs</h2>', unsafe_allow_html=True)# Show dataset infoif st.session_state.dataset_info:info = st.session_state.dataset_info['dataset_info']st.markdown('<div class="info-box">', unsafe_allow_html=True)col1, col2, col3, col4 = st.columns(4)with col1:st.metric("Rows", info['shape'][0])with col2:st.metric("Columns", info['shape'][1])with col3:st.metric("Missing Values", sum(info['missing_values'].values()))with col4:st.metric("Duplicates", info['duplicates'])st.markdown('</div>', unsafe_allow_html=True)# Show file infoif st.session_state.uploaded_file:st.info(f"π File loaded: {st.session_state.uploaded_file.name} ({st.session_state.uploaded_file.size / 1024 / 1024:.2f} MB)")# Prompt inputst.write("**Enter your preprocessing instructions in natural language:**")# Example promptsexample_prompts = ["Prepare this dataset for fraud classification, handle missing values, encode categorical variables, remove outliers, and scale numeric features.","Clean this dataset for customer churn prediction, fill missing values with median, one-hot encode categories, and apply standard scaling.","Preprocess data for regression analysis, handle null values, remove duplicates, and normalize numerical features.","Get this dataset ready for machine learning, handle missing data, encode categorical variables, and scale features.","Analyze this customer dataset and prepare it for machine learning. Remove duplicate rows and unnecessary identifier columns. Handle missing values appropriately. Encode categorical variables such as country, city, and company. Extract useful features from the subscription date. Scale any numerical features if present. Remove low-variance features and prepare the dataset for clustering or classification."]# Prompt text areaprompt = st.text_area("Your prompt:",height=120,placeholder="e.g., Handle missing values, encode categorical variables, remove outliers, and scale numeric features",help="Describe how you want to preprocess your dataset in plain English")# Example prompts sectionwith st.expander("π‘ Example Prompts"):for i, example in enumerate(example_prompts, 1):if st.button(f"Use Example {i}", key=f"example_{i}"):prompt = examplest.rerun()st.write(f"{i}. {example}")# Supported operations infowith st.expander("π§ Supported Operations"):st.write("""**Missing Values:**- Mean/median/mode imputation- Constant value filling- Row deletion**Categorical Encoding:**- One-hot encoding- Label encoding**Feature Scaling:**- Standard scaling (Z-score)- Min-max scaling- Robust scaling**Outlier Detection:**- Isolation Forest- IQR method- Z-score method**Feature Engineering:**- Variance threshold selection- Correlation filtering- Interaction features""")# Process buttonif prompt and st.button("π Process Dataset", type="primary"):if st.session_state.uploaded_file:with st.spinner("Processing dataset... This may take a few minutes."):# Reset file pointerst.session_state.uploaded_file.seek(0)result = process_pipeline(st.session_state.uploaded_file, prompt)if result:st.session_state.processing_results = resultst.session_state.step = 'results'st.rerun()else:st.warning("No file found. Please upload your dataset again.")elif st.session_state.step == 'results':st.markdown('<h2 class="step-header">π Processing Complete!</h2>', unsafe_allow_html=True)if st.session_state.processing_results:results = st.session_state.processing_results# Success messagest.markdown('<div class="success-box">', unsafe_allow_html=True)st.success("β Your dataset has been successfully preprocessed and is ready for machine learning!")st.markdown('</div>', unsafe_allow_html=True)# Dataset informationst.write("### π Dataset Information")info = results['dataset_info']['basic_info']col1, col2, col3, col4 = st.columns(4)with col1:st.metric("Original Shape", f"{info['shape'][0]} Γ {info['shape'][1]}")with col2:st.metric("Numeric Columns", len(info['numeric_columns']))with col3:st.metric("Categorical Columns", len(info['categorical_columns']))with col4:missing_total = sum(results['dataset_info']['missing_values']['counts'].values())st.metric("Missing Values", missing_total)# Applied preprocessing stepsst.write("### π§ Applied Preprocessing Steps")for i, step in enumerate(results['preprocessing_steps'], 1):st.markdown(f"""<div style="padding: 1rem; margin: 0.5rem 0; background-color: #f8fafc; border-left: 4px solid #3b82f6; border-radius: 0.25rem;"><strong>Step {i}:</strong> {step['description']}<br><small>Method: {step.get('method', 'N/A')}</small></div>""", unsafe_allow_html=True)# Download filesst.write("### π Download Files")files_to_download = [("processed_dataset.csv", "π Processed Dataset", "Fully preprocessed dataset ready for ML"),("train.csv", "π Training Set", "80% of data for model training"),("test.csv", "π§ͺ Test Set", "20% of data for model testing"),("pipeline.pkl", "βοΈ Pipeline", "Scikit-learn pipeline for reuse"),("eda_report.html", "π EDA Report", "Exploratory Data Analysis report")]col1, col2 = st.columns(2)for i, (filename, title, description) in enumerate(files_to_download):with col1 if i % 2 == 0 else col2:st.markdown(f"""<div style="padding: 1rem; margin: 0.5rem 0; border: 1px solid #e5e7eb; border-radius: 0.5rem;"><h4>{title}</h4><p><small>{description}</small></p><a href="{download_file(filename)}" download="{filename}" style="text-decoration: none;"><button style="background-color: #3b82f6; color: white; padding: 0.5rem 1rem; border: none; border-radius: 0.25rem; cursor: pointer;">π₯ Download {filename}</button></a></div>""", unsafe_allow_html=True)# Quick actionsst.write("### β‘ Quick Actions")col1, col2, col3 = st.columns(3)with col1:if st.button("π View EDA Report", type="secondary"):st.info(f"EDA Report will be available at: {download_file('eda_report.html')}")with col2:if st.button("βοΈ Download Pipeline", type="secondary"):st.info(f"Pipeline file: {download_file('pipeline.pkl')}")with col3:if st.button("π Process Another Dataset", type="primary"):# Reset session statefor key in st.session_state.keys():del st.session_state[key]st.session_state.step = 'upload'st.rerun()else:st.error("No processing results available. Please start over.")# Footerst.markdown("---")53 unmodified lines545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201 unmodified line1221231241251261271281291301311321331341351361371381391401411421 unmodified line14414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132253 unmodified lines</style>""", unsafe_allow_html=True)# API base URLs - try deployed backend first, fallback to localhostDEPLOYED_BACKEND = "https://promptprepml-backend.railway.app"LOCAL_BACKEND = "http://localhost:8000"def check_backend_health():"""Check if backend is running (try deployed first, then local)"""backends = [DEPLOYED_BACKEND, LOCAL_BACKEND]for backend_url in backends:try:response = requests.get(f"{backend_url}/health", timeout=5)if response.status_code == 200:st.session_state.backend_url = backend_urlreturn True, backend_urlexcept:continuereturn False, Nonedef upload_dataset(uploaded_file):"""Upload dataset to backend"""if 'backend_url' not in st.session_state:return None, "Backend not connected"try:files = {'file': uploaded_file}response = requests.post(f"{st.session_state.backend_url}/api/upload", files=files)if response.status_code == 200:return response.json(), Noneelse:return None, f"Upload failed: {response.text}"except Exception as e:return None, f"Upload error: {str(e)}"def process_pipeline(file_path, prompt):"""Process dataset through ML pipeline"""if 'backend_url' not in st.session_state:return None, "Backend not connected"try:data = {'file_path': file_path, 'prompt': prompt}response = requests.post(f"{st.session_state.backend_url}/process-pipeline", json=data)if response.status_code == 200:return response.json(), Noneelse:return None, f"Processing failed: {response.text}"except Exception as e:return None, f"Processing error: {str(e)}"def download_file(filename):"""Download processed file"""if 'backend_url' not in st.session_state:return None, "Backend not connected"try:response = requests.get(f"{st.session_state.backend_url}/api/download/{filename}")if response.status_code == 200:return response.content, Noneelse:return None, f"Download failed: {response.text}"except Exception as e:return None, f"Download error: {str(e)}"def main():# Main header1 unmodified linest.markdown('<p style="text-align: center; color: #6b7280; font-size: 1.1rem;">Convert natural language prompts into ML-ready datasets</p>', unsafe_allow_html=True)# Check backend healthbackend_healthy, backend_url = check_backend_health()if not backend_healthy:st.error("β Backend is not running! Please start the backend:")st.code("""cd promptprepml/backendvenv\\Scripts\\activatepython app/main.py# OR wait for deployed backend to be ready""")st.info("π **Deploying backend to cloud...** This will make the app work standalone!")returnst.success(f"β Backend connected at: {backend_url}")# Sidebar for navigationst.sidebar.title("π Processing Steps")1 unmodified line# Initialize session stateif 'step' not in st.session_state:st.session_state.step = 'upload'if 'upload_result' not in st.session_state:st.session_state.upload_result = Noneif 'processing_result' not in st.session_state:st.session_state.processing_result = None# Step indicatorssteps = ['π€ Upload', 'βοΈ Configure', 'π Process', 'π Results']current_step_index = 0if st.session_state.step == 'upload':current_step_index = 0elif st.session_state.step == 'configure':current_step_index = 1elif st.session_state.step == 'process':current_step_index = 2elif st.session_state.step == 'results':current_step_index = 3# Display step indicatorsfor i, step in enumerate(steps):if i < current_step_index:st.sidebar.success(f"β {step}")elif i == current_step_index:st.sidebar.info(f"π {step}")else:st.sidebar.write(f"β³ {step}")# Step 1: Upload Datasetif st.session_state.step == 'upload':st.markdown('<h2 class="step-header">π€ Step 1: Upload Dataset</h2>', unsafe_allow_html=True)uploaded_file = st.file_uploader("Choose a CSV file",type=['csv'],help="Upload your dataset for preprocessing")if uploaded_file is not None:st.info(f"π File uploaded: `{uploaded_file.name}`")# Show file previewtry:df = pd.read_csv(uploaded_file)st.markdown('<div class="info-box">', unsafe_allow_html=True)st.markdown(f"**Dataset Shape:** {df.shape}")st.markdown(f"**Columns:** {', '.join(df.columns)}")st.dataframe(df.head())st.markdown('</div>', unsafe_allow_html=True)if st.button("π Continue to Configuration", type="primary"):# Upload to backendwith st.spinner("Uploading dataset..."):result, error = upload_dataset(uploaded_file)if error:st.error(f"β Upload failed: {error}")else:st.session_state.upload_result = resultst.session_state.step = 'configure'st.rerun()except Exception as e:st.error(f"β Error reading file: {str(e)}")# Step 2: Configure Processingelif st.session_state.step == 'configure':st.markdown('<h2 class="step-header">βοΈ Step 2: Configure Processing</h2>', unsafe_allow_html=True)if st.session_state.upload_result:file_info = st.session_state.upload_resultst.markdown('<div class="info-box">', unsafe_allow_html=True)st.markdown(f"**File:** {file_info.get('filename', 'Unknown')}")st.markdown(f"**Size:** {file_info.get('size', 'Unknown')} bytes")st.markdown('</div>', unsafe_allow_html=True)# Processing optionsprompt = st.text_area("Describe your preprocessing needs:",value="Prepare this dataset for machine learning. Handle missing values, remove identifier columns, extract date features, encode categorical variables, and scale numeric features.",height=100,help="Describe what you want to do with your dataset in natural language")col1, col2 = st.columns([1, 1])with col1:if st.button("β¬ οΈ Back", type="secondary"):st.session_state.step = 'upload'st.rerun()with col2:if st.button("π Start Processing", type="primary"):if st.session_state.upload_result:file_path = st.session_state.upload_result.get('file_path')with st.spinner("Processing dataset... This may take a few minutes."):result, error = process_pipeline(file_path, prompt)if error:st.error(f"β Processing failed: {error}")else:st.session_state.processing_result = resultst.session_state.step = 'results'st.rerun()# Step 3: Resultselif st.session_state.step == 'results':st.markdown('<h2 class="step-header">π Step 3: Results</h2>', unsafe_allow_html=True)if st.session_state.processing_result:result = st.session_state.processing_result# Success messagest.markdown('<div class="success-box">', unsafe_allow_html=True)st.success("β Dataset processed successfully!")st.markdown('</div>', unsafe_allow_html=True)# Results summarycol1, col2 = st.columns([2, 1])with col1:st.markdown("### π Processing Summary")dataset_info = result.get('dataset_info', {})if dataset_info:basic_info = dataset_info.get('basic_info', {})st.markdown(f"- **Original Shape:** {basic_info.get('shape', 'Unknown')}")st.markdown(f"- **Columns:** {basic_info.get('columns', 'Unknown')}")preprocessing_info = result.get('preprocessing_info', {})if preprocessing_info:st.markdown(f"- **Processed Shape:** {preprocessing_info.get('processed_shape', 'Unknown')}")# Dataset previewst.markdown("### π Dataset Preview")preview_data = result.get('preview_data', [])if preview_data:df_preview = pd.DataFrame(preview_data)st.dataframe(df_preview)with col2:st.markdown("### π₯ Download Files")download_links = [("Processed Dataset", "processed_dataset.csv"),("Training Set", "train.csv"),("Test Set", "test.csv"),("Pipeline", "pipeline.pkl"),("EDA Report", "eda_report.html")]for name, filename in download_links:if st.button(f"π₯ {name}", key=f"download_{filename}"):with st.spinner(f"Downloading {filename}..."):file_content, error = download_file(filename)if error:st.error(f"β Download failed: {error}")else:st.download_button(label=f"πΎ Save {filename}",data=file_content,file_name=filename,mime="application/octet-stream")# Action buttonscol1, col2 = st.columns([1, 1])with col1:if st.button("π Process New Dataset", type="secondary"):# Reset session statefor key in list(st.session_state.keys()):del st.session_state[key]st.session_state.step = 'upload'st.rerun()with col2:if st.button("π View EDA Report", type="primary"):st.info("π EDA Report feature coming soon!")# Footerst.markdown("---")
app.py+182-227