Saketh12345 commited on
Commit
32f1545
·
1 Parent(s): 024a5bc

Refactor project structure and improve code organization

Browse files

- Reorganized code into a proper Python package structure
- Added comprehensive configuration management
- Improved error handling and logging
- Added type hints and docstrings
- Set up testing infrastructure
- Updated README with better documentation
- Added setup.py for package installation
- Cleaned up unnecessary files

.gitignore ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+
23
+ # Virtual Environment
24
+ venv/
25
+ env/
26
+ ENV/
27
+
28
+ # IDE
29
+ .idea/
30
+ .vscode/
31
+ *.swp
32
+ *.swo
33
+
34
+ # Jupyter Notebook
35
+ .ipynb_checkpoints
36
+
37
+ # Environment variables
38
+ .env
39
+
40
+ # Model files
41
+ models/
42
+ !src/diabetes_prediction/models/.gitkeep
43
+
44
+ # Logs
45
+ logs/
46
+ *.log
47
+
48
+ # Local development
49
+ .DS_Store
50
+
51
+ # Testing
52
+ .coverage
53
+ htmlcov/
54
+ .pytest_cache/
README.md CHANGED
@@ -1,5 +1,8 @@
1
  ---
2
- title: Diabetes Prediction
 
 
 
3
  emoji: 🚀
4
  colorFrom: red
5
  colorTo: red
 
1
  ---
2
+ title: Diabetes Prediction App
3
+
4
+ A Streamlit web application that predicts the likelihood of diabetes based on patient data using a Gradient Boosting Classifier.
5
+
6
  emoji: 🚀
7
  colorFrom: red
8
  colorTo: red
app.py DELETED
@@ -1,447 +0,0 @@
1
- import os
2
- import sys
3
- import logging
4
- from pathlib import Path
5
-
6
- import streamlit as st
7
- import pandas as pd
8
- import numpy as np
9
- import matplotlib.pyplot as plt
10
- import seaborn as sns
11
- from sklearn.model_selection import train_test_split, cross_val_score
12
- from sklearn.ensemble import GradientBoostingClassifier
13
- from sklearn.preprocessing import StandardScaler
14
- from sklearn.pipeline import Pipeline
15
- from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, f1_score
16
- import joblib
17
- from dotenv import load_dotenv
18
-
19
- # Configure logging
20
- logging.basicConfig(
21
- level=logging.INFO,
22
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
23
- handlers=[
24
- logging.StreamHandler(sys.stdout)
25
- ]
26
- )
27
- logger = logging.getLogger(__name__)
28
-
29
- # Load environment variables (ignore if .env doesn't exist)
30
- load_dotenv(verbose=False)
31
-
32
- # Constants
33
- MODEL_DIR = Path('models')
34
- MODEL_PATH = MODEL_DIR / 'model.joblib'
35
- DATA_PATH = Path('diabetes.csv')
36
- RANDOM_STATE = 42 # For reproducible results
37
-
38
- def setup_environment():
39
- """Set up the application environment."""
40
- # Ensure models directory exists
41
- MODEL_DIR.mkdir(parents=True, exist_ok=True)
42
- logger.info("Environment setup complete")
43
-
44
- def load_data():
45
- """Load and return the diabetes dataset or use sample data if not found."""
46
- try:
47
- # Try to load the CSV file
48
- csv_paths = [
49
- 'diabetes.csv',
50
- '/app/diabetes.csv',
51
- 'data/diabetes.csv',
52
- '/app/data/diabetes.csv'
53
- ]
54
-
55
- for path in csv_paths:
56
- try:
57
- if os.path.exists(path):
58
- df = pd.read_csv(path)
59
- logger.info(f"Successfully loaded data from {os.path.abspath(path)}")
60
- return df
61
- except Exception as e:
62
- logger.warning(f"Error reading {path}: {e}")
63
- continue
64
-
65
- # If we get here, no file was found - use sample data
66
- logger.warning("Using sample data as fallback")
67
- sample_data = {
68
- 'Pregnancies': [6, 1, 8, 1, 0],
69
- 'Glucose': [148, 85, 183, 89, 137],
70
- 'BloodPressure': [72, 66, 64, 66, 40],
71
- 'SkinThickness': [35, 29, 0, 23, 35],
72
- 'Insulin': [0, 0, 0, 94, 168],
73
- 'BMI': [33.6, 26.6, 23.3, 28.1, 43.1],
74
- 'DiabetesPedigreeFunction': [0.627, 0.351, 0.672, 0.167, 2.288],
75
- 'Age': [50, 31, 32, 21, 33],
76
- 'Outcome': [1, 0, 1, 0, 1]
77
- }
78
- return pd.DataFrame(sample_data)
79
-
80
- except Exception as e:
81
- logger.error(f"Error loading data: {e}")
82
- raise
83
-
84
- def preprocess_data(df):
85
- """Preprocess the input DataFrame."""
86
- try:
87
- # Make a copy to avoid SettingWithCopyWarning
88
- df = df.copy()
89
-
90
- # Check if 'Outcome' column exists (it won't in the sample data)
91
- target_col = 'Outcome' if 'Outcome' in df.columns else None
92
-
93
- # Replace zeros with mean values for numerical columns
94
- numerical_cols = ['Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI']
95
- for col in numerical_cols:
96
- if col in df.columns:
97
- if target_col:
98
- df[col] = replace_zero(df, col, target_col)
99
- else:
100
- # For sample data, just replace zeros with column mean
101
- df[col] = df[col].replace(0, df[col].mean())
102
-
103
- # Log the preprocessed data
104
- logger.info("Data preprocessing completed")
105
- logger.info(f"DataFrame shape: {df.shape}")
106
- logger.info(f"Columns: {df.columns.tolist()}")
107
- logger.info(df.head())
108
-
109
- return df
110
- except Exception as e:
111
- logger.error(f"Error in preprocess_data: {e}")
112
- raise
113
-
114
- def replace_zero(df, field, target):
115
- """Replace zeros with mean values grouped by the target variable."""
116
- try:
117
- # If target column doesn't exist, just replace zeros with column mean
118
- if target not in df.columns:
119
- return df[field].replace(0, df[df[field] != 0][field].mean())
120
-
121
- # Calculate mean by target class for non-zero values
122
- non_zero = df[df[field] != 0]
123
- if len(non_zero) == 0: # If all values are zero
124
- return df[field]
125
-
126
- mean_by_target = non_zero.groupby(target)[field].mean()
127
-
128
- # Create a copy to avoid SettingWithCopyWarning
129
- result = df[field].copy()
130
-
131
- # Replace zeros with the mean of the corresponding target class
132
- for target_value in df[target].unique():
133
- if target_value in mean_by_target: # Check if we have a mean for this target
134
- mask = (df[field] == 0) & (df[target] == target_value)
135
- if mask.any():
136
- result.loc[mask] = mean_by_target[target_value]
137
-
138
- return result
139
- except Exception as e:
140
- logger.error(f"Error replacing zeros in {field}: {e}")
141
- # Fall back to simple mean if there's an error
142
- return df[field].replace(0, df[df[field] != 0][field].mean() if len(df[df[field] != 0]) > 0 else 0)
143
-
144
- def train_model(X, y):
145
- """Train and return the Gradient Boosting model."""
146
- try:
147
- # Gradient Boosting with optimized parameters
148
- gb_params = {
149
- 'n_estimators': 290,
150
- 'max_depth': 9,
151
- 'subsample': 0.5,
152
- 'learning_rate': 0.01,
153
- 'min_samples_leaf': 1,
154
- 'random_state': RANDOM_STATE
155
- }
156
-
157
- # Create pipeline with preprocessing and model
158
- pipeline = Pipeline([
159
- ('scaler', StandardScaler()),
160
- ('classifier', GradientBoostingClassifier(**gb_params))
161
- ])
162
-
163
- # Train the model
164
- pipeline.fit(X, y)
165
- logger.info("Model training completed successfully")
166
- return pipeline
167
- except Exception as e:
168
- logger.error(f"Error during model training: {e}")
169
- raise
170
-
171
- def save_model(model):
172
- """Save the trained model to disk."""
173
- try:
174
- joblib.dump(model, MODEL_PATH)
175
- logger.info(f"Model saved to {MODEL_PATH}")
176
- except Exception as e:
177
- logger.error(f"Error saving model: {e}")
178
- raise
179
-
180
- def load_saved_model():
181
- """Load a previously saved model from disk or return None to train a new one."""
182
- # Always return None to force training a new model
183
- # This is because we can't guarantee the model file exists in the deployment
184
- return None
185
-
186
- def get_user_input():
187
- """Get input features from the user via the sidebar."""
188
- st.sidebar.header('Patient Information')
189
-
190
- # Group related features
191
- with st.sidebar.expander("Personal Information"):
192
- pregnancies = st.slider('Pregnancies', 0, 17, 3)
193
- age = st.slider('Age', 21, 81, 29)
194
-
195
- with st.sidebar.expander("Medical Measurements"):
196
- col1, col2 = st.columns(2)
197
- with col1:
198
- glucose = st.slider('Glucose (mg/dL)', 0, 200, 120)
199
- bp = st.slider('Blood Pressure (mmHg)', 0, 122, 70)
200
- skin_thickness = st.slider('Skin Thickness (mm)', 0, 100, 20)
201
- with col2:
202
- insulin = st.slider('Insulin (μU/mL)', 0, 846, 79)
203
- bmi = st.slider('BMI', 0.0, 67.1, 32.0)
204
- dpf = st.slider('Diabetes Pedigree', 0.0, 2.42, 0.3725, 0.01)
205
-
206
- # Create feature dictionary
207
- user_data = {
208
- 'Pregnancies': pregnancies,
209
- 'Glucose': glucose,
210
- 'BloodPressure': bp,
211
- 'SkinThickness': skin_thickness,
212
- 'Insulin': insulin,
213
- 'BMI': bmi,
214
- 'DiabetesPedigreeFunction': dpf,
215
- 'Age': age
216
- }
217
-
218
- return pd.DataFrame(user_data, index=[0])
219
-
220
- def main():
221
- """Main application function."""
222
- try:
223
- # Set page config
224
- st.set_page_config(
225
- page_title="Diabetes Prediction App",
226
- page_icon="🩺",
227
- layout="wide",
228
- initial_sidebar_state="expanded"
229
- )
230
-
231
- # Setup environment - create models directory if it doesn't exist
232
- try:
233
- os.makedirs('models', exist_ok=True)
234
- except Exception as e:
235
- st.warning(f"Could not create models directory: {e}")
236
-
237
- # Show loading message
238
- with st.spinner('Loading and preprocessing data...'):
239
- try:
240
- df = load_data()
241
- df = preprocess_data(df)
242
- X = df.drop(['Outcome'], axis=1)
243
- y = df['Outcome']
244
-
245
- # Split the data
246
- X_train, X_test, y_train, y_test = train_test_split(
247
- X, y, test_size=0.2, random_state=RANDOM_STATE
248
- )
249
- except Exception as e:
250
- st.error(f"Error loading data: {str(e)}")
251
- st.stop()
252
-
253
- # Always train a new model (since we can't upload model files)
254
- with st.spinner('Training model (this may take a minute)...'):
255
- try:
256
- model = train_model(X_train, y_train)
257
- # Don't save the model to avoid permission issues
258
- st.success("Model training completed successfully!")
259
- except Exception as e:
260
- st.error(f"Error training model: {str(e)}")
261
- st.stop()
262
-
263
- # Main app layout
264
- st.title('Diabetes Risk Assessment')
265
- st.markdown("""
266
- This application uses machine learning to predict the likelihood of diabetes
267
- based on patient health metrics. Enter the patient's information in the sidebar
268
- and click 'Predict' to see the results.
269
- """)
270
-
271
- # Get user input and display it
272
- try:
273
- user_data = get_user_input()
274
-
275
- # Display user input in main area
276
- with st.expander("View Patient Data"):
277
- st.dataframe(user_data.style.format({
278
- 'Pregnancies': '{:.0f}',
279
- 'Glucose': '{:.0f} mg/dL',
280
- 'BloodPressure': '{:.0f} mm Hg',
281
- 'SkinThickness': '{:.0f} mm',
282
- 'Insulin': '{:.0f} mu U/ml',
283
- 'BMI': '{:.1f} kg/m²',
284
- 'DiabetesPedigreeFunction': '{:.3f}',
285
- 'Age': '{:.0f} years'
286
- }))
287
-
288
- # Make prediction when user clicks the button
289
- if st.button('Predict Diabetes Risk'):
290
- with st.spinner('Analyzing...'):
291
- prediction = model.predict(user_data)
292
- prediction_proba = model.predict_proba(user_data)
293
-
294
- # Display results
295
- st.subheader('Prediction Results')
296
- col1, col2 = st.columns(2)
297
- with col1:
298
- st.metric(
299
- "Risk of Diabetes",
300
- "High Risk" if prediction[0] == 1 else "Low Risk",
301
- f"{prediction_proba[0][1] * 100:.2f}%"
302
- )
303
- with col2:
304
- st.metric(
305
- "Confidence",
306
- f"{np.max(prediction_proba) * 100:.1f}%",
307
- "in prediction"
308
- )
309
-
310
- # Display feature importance
311
- st.subheader('Feature Importance')
312
- if hasattr(model, 'feature_importances_'):
313
- feature_importance = pd.DataFrame({
314
- 'Feature': X_train.columns,
315
- 'Importance': model.feature_importances_
316
- }).sort_values('Importance', ascending=False)
317
-
318
- fig, ax = plt.subplots(figsize=(10, 6))
319
- sns.barplot(
320
- x='Importance',
321
- y='Feature',
322
- data=feature_importance,
323
- palette='viridis'
324
- )
325
- plt.title('Feature Importance')
326
- plt.tight_layout()
327
- st.pyplot(fig)
328
-
329
- except Exception as e:
330
- st.error(f"An error occurred: {str(e)}")
331
- logger.error(f"Error in main app: {str(e)}", exc_info=True)
332
- # Make prediction
333
- if st.sidebar.button('Predict', type='primary'):
334
- with st.spinner('Analyzing...'):
335
- # Make prediction
336
- prediction = model.predict(user_data)
337
- proba = model.predict_proba(user_data)[0]
338
-
339
- # Display prediction with emoji and styling
340
- st.markdown("## Prediction Result")
341
- if prediction[0] == 1:
342
- st.error('⚠️ **High Risk of Diabetes**')
343
- st.warning("""
344
- Based on the provided information, this patient shows indicators associated
345
- with a higher risk of diabetes. We recommend consulting with a healthcare
346
- professional for further evaluation.
347
- """)
348
- else:
349
- st.success('✅ **Low Risk of Diabetes**')
350
- st.info("""
351
- Based on the provided information, this patient shows indicators associated
352
- with a lower risk of diabetes. However, regular check-ups are recommended
353
- for maintaining good health.
354
- """)
355
-
356
- # Show probability with a progress bar
357
- risk_percent = proba[1] * 100
358
- st.metric("Risk Score", f"{risk_percent:.1f}%")
359
- st.progress(risk_percent / 100)
360
-
361
- # Model performance
362
- st.markdown("## Model Performance")
363
-
364
- # Cross-validated metrics
365
- with st.expander("Performance Metrics"):
366
- col1, col2 = st.columns(2)
367
-
368
- # Cross-validated F1
369
- with col1:
370
- cv_scores = cross_val_score(model, X, y, cv=5, scoring='f1')
371
- st.metric(
372
- "Cross-validated F1-score",
373
- f"{cv_scores.mean():.3f}",
374
- f"±{cv_scores.std():.3f}"
375
- )
376
-
377
- # Test set metrics
378
- with col2:
379
- y_pred = model.predict(X_test)
380
- test_accuracy = accuracy_score(y_test, y_pred)
381
- st.metric(
382
- "Test Set Accuracy",
383
- f"{test_accuracy*100:.1f}%"
384
- )
385
-
386
- # Feature importance
387
- st.markdown("## Feature Importance")
388
- importances = model.named_steps['classifier'].feature_importances_
389
- feature_importance = pd.DataFrame({
390
- 'Feature': X.columns,
391
- 'Importance': importances
392
- }).sort_values('Importance', ascending=True)
393
-
394
- # Horizontal bar chart for feature importance
395
- fig, ax = plt.subplots(figsize=(10, 6))
396
- ax.barh(feature_importance['Feature'], feature_importance['Importance'])
397
- ax.set_xlabel('Importance Score')
398
- ax.set_title('Relative Importance of Features in Prediction')
399
- st.pyplot(fig)
400
-
401
- # Confusion matrix
402
- st.markdown("## Confusion Matrix")
403
- cm = confusion_matrix(y_test, y_pred)
404
- fig, ax = plt.subplots()
405
- sns.heatmap(
406
- cm,
407
- annot=True,
408
- fmt='d',
409
- cmap='Blues',
410
- ax=ax,
411
- xticklabels=['No Diabetes', 'Diabetes'],
412
- yticklabels=['No Diabetes', 'Diabetes']
413
- )
414
- ax.set_xlabel('Predicted')
415
- ax.set_ylabel('Actual')
416
- ax.set_title('Model Performance on Test Data')
417
- st.pyplot(fig)
418
-
419
- # Add footer
420
- st.markdown("---")
421
- st.caption("""
422
- **Note**: This tool is for informational purposes only and is not intended
423
- to replace professional medical advice, diagnosis, or treatment. Always seek
424
- the advice of your physician or other qualified health provider with any
425
- questions you may have regarding a medical condition.
426
- """)
427
-
428
- except FileNotFoundError:
429
- st.error("""
430
- ### Error: Data File Not Found
431
- The diabetes dataset could not be found. Please ensure that `diabetes.csv`
432
- is in the project directory.
433
- """)
434
- logger.error("diabetes.csv file not found")
435
- except Exception as e:
436
- st.error(f"""
437
- ### An Unexpected Error Occurred
438
- We apologize for the inconvenience. The application encountered an error:
439
-
440
- `{str(e)}`
441
-
442
- Please try refreshing the page or contact support if the issue persists.
443
- """)
444
- logger.exception("Unexpected error in main application")
445
-
446
- if __name__ == "__main__":
447
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,3 +1,4 @@
 
1
  streamlit>=1.32.0
2
  pandas>=2.1.4
3
  numpy>=1.26.3
@@ -6,7 +7,17 @@ matplotlib>=3.8.2
6
  seaborn>=0.13.2
7
  joblib>=1.3.2
8
  python-dotenv>=1.0.0
9
- Pillow>=10.4.0
10
- pydeck>=0.9.1
11
- protobuf>=4.25.8
12
- typing-extensions>=4.10.0
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core Dependencies
2
  streamlit>=1.32.0
3
  pandas>=2.1.4
4
  numpy>=1.26.3
 
7
  seaborn>=0.13.2
8
  joblib>=1.3.2
9
  python-dotenv>=1.0.0
10
+
11
+ # Testing
12
+ pytest>=7.4.0
13
+ pytest-cov>=4.1.0
14
+
15
+ # Code Quality
16
+ black>=23.7.0
17
+ isort>=5.12.0
18
+ flake8>=6.1.0
19
+ mypy>=1.4.1
20
+
21
+ # Documentation
22
+ mkdocs>=1.5.2
23
+ mkdocs-material>=9.1.21
setup.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from setuptools import setup, find_packages
2
+
3
+ with open("README.md", "r", encoding="utf-8") as fh:
4
+ long_description = fh.read()
5
+
6
+ with open("requirements.txt", "r", encoding="utf-8") as fh:
7
+ requirements = [line.strip() for line in fh if line.strip() and not line.startswith('#')]
8
+
9
+ setup(
10
+ name="diabetes-prediction",
11
+ version="0.1.0",
12
+ author="Your Name",
13
+ author_email="your.email@example.com",
14
+ description="A Streamlit web application for diabetes prediction",
15
+ long_description=long_description,
16
+ long_description_content_type="text/markdown",
17
+ url="https://github.com/yourusername/diabetes-prediction",
18
+ packages=find_packages(where="src"),
19
+ package_dir={"": "src"},
20
+ install_requires=requirements,
21
+ python_requires=">=3.8",
22
+ classifiers=[
23
+ "Programming Language :: Python :: 3",
24
+ "License :: OSI Approved :: MIT License",
25
+ "Operating System :: OS Independent",
26
+ ],
27
+ entry_points={
28
+ "console_scripts": [
29
+ "diabetes-prediction=diabetes_prediction.app:main",
30
+ ],
31
+ },
32
+ )
src/diabetes_prediction/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """Diabetes Prediction Application.
2
+
3
+ This package provides functionality for predicting diabetes risk based on patient data.
4
+ """
5
+
6
+ __version__ = '0.1.0'
src/diabetes_prediction/app.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Streamlit application for diabetes prediction."""
2
+
3
+ import logging
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+ import pandas as pd
10
+ import seaborn as sns
11
+ import streamlit as st
12
+
13
+ # Add the project root to the Python path
14
+ project_root = Path(__file__).parent.parent.parent
15
+ sys.path.append(str(project_root))
16
+
17
+ from diabetes_prediction.config import (
18
+ DATA_PATH,
19
+ FEATURES,
20
+ LOGGING_CONFIG,
21
+ MODEL_PATH,
22
+ PREDICTION_THRESHOLD,
23
+ ZERO_FEATURES,
24
+ )
25
+ from diabetes_prediction.data import load_data, preprocess_data
26
+ from diabetes_prediction.model import DiabetesPredictor
27
+ from diabetes_prediction.utils.helpers import ensure_directory_exists, setup_logging
28
+
29
+ # Configure logging
30
+ setup_logging(LOGGING_CONFIG)
31
+ logger = logging.getLogger(__name__)
32
+
33
+ def setup_page():
34
+ """Set up the Streamlit page configuration."""
35
+ st.set_page_config(
36
+ page_title="Diabetes Prediction App",
37
+ page_icon="🩺",
38
+ layout="wide",
39
+ initial_sidebar_state="expanded"
40
+ )
41
+
42
+ # Custom CSS for better styling
43
+ st.markdown("""
44
+ <style>
45
+ .main {
46
+ max-width: 1000px;
47
+ padding: 2rem;
48
+ }
49
+ .stButton>button {
50
+ background-color: #4CAF50;
51
+ color: white;
52
+ font-weight: bold;
53
+ }
54
+ .stButton>button:hover {
55
+ background-color: #45a049;
56
+ }
57
+ .stAlert {
58
+ padding: 1rem;
59
+ border-radius: 0.5rem;
60
+ }
61
+ </style>
62
+ """, unsafe_allow_html=True)
63
+
64
+ def display_header():
65
+ """Display the application header."""
66
+ st.title("Diabetes Prediction App")
67
+ st.markdown("""
68
+ This application uses machine learning to predict the likelihood of diabetes based on patient data.
69
+ Enter the patient's information in the sidebar and click 'Predict' to see the results.
70
+ """)
71
+
72
+ def get_user_input():
73
+ """Get input features from the user via the sidebar.
74
+
75
+ Returns:
76
+ dict: Dictionary of user inputs
77
+ """
78
+ st.sidebar.header('Patient Information')
79
+
80
+ # Input fields with validation
81
+ pregnancies = st.sidebar.slider('Pregnancies', 0, 17, 3)
82
+ glucose = st.sidebar.number_input('Glucose (mg/dL)', 0, 200, 120, 1)
83
+ blood_pressure = st.sidebar.number_input('Blood Pressure (mm Hg)', 0, 122, 72, 1)
84
+ skin_thickness = st.sidebar.number_input('Skin Thickness (mm)', 0, 99, 23, 1)
85
+ insulin = st.sidebar.number_input('Insulin (μU/ml)', 0, 846, 30, 1)
86
+ bmi = st.sidebar.number_input('BMI', 0.0, 67.1, 32.0, 0.1)
87
+ diabetes_pedigree = st.sidebar.number_input('Diabetes Pedigree Function', 0.0, 2.42, 0.37, 0.01)
88
+ age = st.sidebar.slider('Age (years)', 21, 81, 29)
89
+
90
+ return {
91
+ 'Pregnancies': pregnancies,
92
+ 'Glucose': glucose,
93
+ 'BloodPressure': blood_pressure,
94
+ 'SkinThickness': skin_thickness,
95
+ 'Insulin': insulin,
96
+ 'BMI': bmi,
97
+ 'DiabetesPedigreeFunction': diabetes_pedigree,
98
+ 'Age': age
99
+ }
100
+
101
+ def display_prediction(prediction_prob, threshold=0.5):
102
+ """Display the prediction result.
103
+
104
+ Args:
105
+ prediction_prob (float): Probability of diabetes (0-1)
106
+ threshold (float): Decision threshold for classification
107
+ """
108
+ st.subheader("Prediction Result")
109
+
110
+ # Display probability with a progress bar
111
+ prob_percent = prediction_prob * 100
112
+ st.metric("Diabetes Risk", f"{prob_percent:.1f}%")
113
+ st.progress(float(prediction_prob))
114
+
115
+ # Display interpretation
116
+ if prediction_prob >= threshold:
117
+ st.error("High risk of diabetes. Please consult a healthcare professional.")
118
+ else:
119
+ st.success("Low risk of diabetes. Maintain a healthy lifestyle!")
120
+
121
+ # Show threshold info
122
+ st.caption(f"*Threshold for high risk: {threshold*100:.0f}%")
123
+
124
+ def display_data_insights(df):
125
+ """Display data visualizations and insights."""
126
+ st.subheader("Data Insights")
127
+
128
+ # Show data summary
129
+ with st.expander("View Data Summary"):
130
+ st.write(df.describe())
131
+
132
+ # Show correlation heatmap
133
+ st.write("### Feature Correlation")
134
+ fig, ax = plt.subplots(figsize=(10, 8))
135
+ sns.heatmap(df.corr(), annot=True, cmap='coolwarm', center=0, ax=ax)
136
+ st.pyplot(fig)
137
+
138
+ def main():
139
+ """Main application function."""
140
+ # Set up the page
141
+ setup_page()
142
+ display_header()
143
+
144
+ # Initialize the model
145
+ model = DiabetesPredictor(MODEL_PATH)
146
+
147
+ # Load and preprocess data
148
+ try:
149
+ df = load_data(DATA_PATH)
150
+ X, y = preprocess_data(df)
151
+
152
+ # Display data insights in a tab
153
+ with st.expander("View Data Insights", expanded=False):
154
+ display_data_insights(df)
155
+
156
+ # Get user input
157
+ user_data = get_user_input()
158
+
159
+ # Convert user input to DataFrame
160
+ input_df = pd.DataFrame([user_data])
161
+
162
+ # Make prediction when button is clicked
163
+ if st.sidebar.button('Predict', type='primary'):
164
+ with st.spinner('Making prediction...'):
165
+ # Train or load model
166
+ if not model.load_model():
167
+ st.info("Training a new model...")
168
+ X_train, X_test, y_train, y_test = split_data(X, y)
169
+ model.train(X_train, y_train)
170
+ model.save_model()
171
+
172
+ # Show model performance
173
+ st.success("Model trained successfully!")
174
+ eval_metrics = model.evaluate(X_test, y_test)
175
+ st.metric("Model Accuracy", f"{eval_metrics['accuracy']*100:.1f}%")
176
+
177
+ # Make prediction
178
+ prediction_prob = model.predict(input_df)[0]
179
+
180
+ # Display results
181
+ st.balloons()
182
+ display_prediction(prediction_prob)
183
+
184
+ except Exception as e:
185
+ st.error(f"An error occurred: {str(e)}")
186
+ logger.exception("Error in main application")
187
+
188
+ if __name__ == "__main__":
189
+ main()
src/diabetes_prediction/config.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration settings for the diabetes prediction application."""
2
+
3
+ from pathlib import Path
4
+
5
+ # Base directory
6
+ BASE_DIR = Path(__file__).parent.parent.parent
7
+
8
+ # Data paths
9
+ DATA_DIR = BASE_DIR / 'data'
10
+ DATA_FILE = 'diabetes.csv'
11
+ DATA_PATH = DATA_DIR / DATA_FILE
12
+
13
+ # Model paths
14
+ MODEL_DIR = BASE_DIR / 'models'
15
+ MODEL_FILE = 'diabetes_model.joblib'
16
+ MODEL_PATH = MODEL_DIR / MODEL_FILE
17
+
18
+ # Model parameters
19
+ MODEL_PARAMS = {
20
+ 'n_estimators': 100,
21
+ 'learning_rate': 0.1,
22
+ 'max_depth': 3,
23
+ 'random_state': 42
24
+ }
25
+
26
+ # Feature names
27
+ FEATURES = [
28
+ 'Pregnancies',
29
+ 'Glucose',
30
+ 'BloodPressure',
31
+ 'SkinThickness',
32
+ 'Insulin',
33
+ 'BMI',
34
+ 'DiabetesPedigreeFunction',
35
+ 'Age'
36
+ ]
37
+
38
+ # Target column
39
+ TARGET = 'Outcome'
40
+
41
+ # Data preprocessing
42
+ ZERO_FEATURES = [
43
+ 'Glucose',
44
+ 'BloodPressure',
45
+ 'SkinThickness',
46
+ 'Insulin',
47
+ 'BMI'
48
+ ]
49
+
50
+ # Prediction threshold
51
+ PREDICTION_THRESHOLD = 0.5
52
+
53
+ # Logging configuration
54
+ LOGGING_CONFIG = {
55
+ 'version': 1,
56
+ 'disable_existing_loggers': False,
57
+ 'formatters': {
58
+ 'standard': {
59
+ 'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
60
+ },
61
+ },
62
+ 'handlers': {
63
+ 'default': {
64
+ 'level': 'INFO',
65
+ 'formatter': 'standard',
66
+ 'class': 'logging.StreamHandler',
67
+ 'stream': 'ext://sys.stdout',
68
+ },
69
+ },
70
+ 'loggers': {
71
+ '': { # root logger
72
+ 'handlers': ['default'],
73
+ 'level': 'INFO',
74
+ 'propagate': False
75
+ },
76
+ 'diabetes_prediction': {
77
+ 'handlers': ['default'],
78
+ 'level': 'DEBUG',
79
+ 'propagate': False
80
+ },
81
+ }
82
+ }
src/diabetes_prediction/data.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Data loading and preprocessing utilities for the diabetes prediction model."""
2
+
3
+ import logging
4
+ from pathlib import Path
5
+ import pandas as pd
6
+ import numpy as np
7
+ from sklearn.model_selection import train_test_split
8
+ from sklearn.preprocessing import StandardScaler
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ def load_data(filepath='diabetes.csv'):
13
+ """Load and return the diabetes dataset.
14
+
15
+ Args:
16
+ filepath (str): Path to the diabetes CSV file.
17
+
18
+ Returns:
19
+ pd.DataFrame: Loaded diabetes dataset.
20
+ """
21
+ try:
22
+ # Try to load the CSV file
23
+ df = pd.read_csv(filepath)
24
+ logger.info(f"Successfully loaded data from {filepath}")
25
+ return df
26
+ except FileNotFoundError:
27
+ logger.error(f"Data file not found at {filepath}")
28
+ raise
29
+
30
+ def preprocess_data(df):
31
+ """Preprocess the input DataFrame.
32
+
33
+ Args:
34
+ df (pd.DataFrame): Input DataFrame with diabetes data.
35
+
36
+ Returns:
37
+ tuple: (X, y) - Features and target variable
38
+ """
39
+ # Replace zeros with mean values for specific columns
40
+ df = df.copy()
41
+
42
+ # Columns where zero values should be replaced with mean
43
+ zero_columns = ['Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI']
44
+
45
+ for col in zero_columns:
46
+ df[col] = df[col].replace(0, np.nan)
47
+ mean_value = df[col].mean()
48
+ df[col] = df[col].fillna(mean_value)
49
+
50
+ # Separate features and target
51
+ X = df.drop('Outcome', axis=1)
52
+ y = df['Outcome']
53
+
54
+ return X, y
55
+
56
+ def split_data(X, y, test_size=0.2, random_state=42):
57
+ """Split data into training and testing sets.
58
+
59
+ Args:
60
+ X (pd.DataFrame): Features
61
+ y (pd.Series): Target variable
62
+ test_size (float): Proportion of the dataset to include in the test split
63
+ random_state (int): Random seed for reproducibility
64
+
65
+ Returns:
66
+ tuple: X_train, X_test, y_train, y_test
67
+ """
68
+ return train_test_split(X, y, test_size=test_size, random_state=random_state, stratify=y)
69
+
70
+ def get_scaler(X_train):
71
+ """Fit and return a StandardScaler on the training data.
72
+
73
+ Args:
74
+ X_train (pd.DataFrame): Training features
75
+
76
+ Returns:
77
+ StandardScaler: Fitted scaler
78
+ """
79
+ scaler = StandardScaler()
80
+ scaler.fit(X_train)
81
+ return scaler
src/diabetes_prediction/model.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model training and evaluation for diabetes prediction."""
2
+
3
+ import logging
4
+ import joblib
5
+ from pathlib import Path
6
+ from sklearn.ensemble import GradientBoostingClassifier
7
+ from sklearn.pipeline import Pipeline
8
+ from sklearn.metrics import (
9
+ accuracy_score,
10
+ classification_report,
11
+ confusion_matrix,
12
+ f1_score
13
+ )
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ class DiabetesPredictor:
18
+ """A class to handle diabetes prediction model training and evaluation."""
19
+
20
+ def __init__(self, model_path='models/model.joblib'):
21
+ """Initialize the DiabetesPredictor.
22
+
23
+ Args:
24
+ model_path (str): Path to save/load the model
25
+ """
26
+ self.model_path = Path(model_path)
27
+ self.model = None
28
+ self.scaler = None
29
+
30
+ def create_model(self, random_state=42):
31
+ """Create a new Gradient Boosting model.
32
+
33
+ Args:
34
+ random_state (int): Random seed for reproducibility
35
+
36
+ Returns:
37
+ Pipeline: A scikit-learn pipeline with preprocessing and model
38
+ """
39
+ return GradientBoostingClassifier(
40
+ n_estimators=100,
41
+ learning_rate=0.1,
42
+ max_depth=3,
43
+ random_state=random_state
44
+ )
45
+
46
+ def train(self, X_train, y_train):
47
+ """Train the model on the given data.
48
+
49
+ Args:
50
+ X_train (pd.DataFrame): Training features
51
+ y_train (pd.Series): Training target
52
+
53
+ Returns:
54
+ Pipeline: Trained model pipeline
55
+ """
56
+ self.model = self.create_model()
57
+ self.model.fit(X_train, y_train)
58
+ return self.model
59
+
60
+ def evaluate(self, X_test, y_test):
61
+ """Evaluate the model on test data.
62
+
63
+ Args:
64
+ X_test (pd.DataFrame): Test features
65
+ y_test (pd.Series): True labels
66
+
67
+ Returns:
68
+ dict: Dictionary of evaluation metrics
69
+ """
70
+ if self.model is None:
71
+ raise ValueError("Model has not been trained yet.")
72
+
73
+ y_pred = self.model.predict(X_test)
74
+
75
+ return {
76
+ 'accuracy': accuracy_score(y_test, y_pred),
77
+ 'f1': f1_score(y_test, y_pred, average='weighted'),
78
+ 'classification_report': classification_report(y_test, y_pred, output_dict=True),
79
+ 'confusion_matrix': confusion_matrix(y_test, y_pred).tolist()
80
+ }
81
+
82
+ def predict(self, X):
83
+ """Make predictions on new data.
84
+
85
+ Args:
86
+ X (pd.DataFrame): Input features
87
+
88
+ Returns:
89
+ np.array: Predicted probabilities for class 1 (diabetes)
90
+ """
91
+ if self.model is None:
92
+ raise ValueError("Model has not been trained or loaded.")
93
+
94
+ return self.model.predict_proba(X)[:, 1]
95
+
96
+ def save_model(self):
97
+ """Save the model to disk."""
98
+ if self.model is None:
99
+ raise ValueError("No model to save.")
100
+
101
+ # Create parent directories if they don't exist
102
+ self.model_path.parent.mkdir(parents=True, exist_ok=True)
103
+
104
+ joblib.dump(self.model, self.model_path)
105
+ logger.info(f"Model saved to {self.model_path}")
106
+
107
+ def load_model(self):
108
+ """Load a previously saved model from disk.
109
+
110
+ Returns:
111
+ bool: True if model was loaded successfully, False otherwise
112
+ """
113
+ if not self.model_path.exists():
114
+ logger.warning(f"No saved model found at {self.model_path}")
115
+ return False
116
+
117
+ try:
118
+ self.model = joblib.load(self.model_path)
119
+ logger.info(f"Model loaded from {self.model_path}")
120
+ return True
121
+ except Exception as e:
122
+ logger.error(f"Error loading model: {e}")
123
+ return False
src/diabetes_prediction/tests/test_data.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for data processing functions."""
2
+
3
+ import pytest
4
+ import pandas as pd
5
+ import numpy as np
6
+ from pathlib import Path
7
+
8
+ # Add the project root to the Python path
9
+ import sys
10
+ sys.path.append(str(Path(__file__).parent.parent))
11
+
12
+ from src.diabetes_prediction.data import load_data, preprocess_data, split_data
13
+
14
+
15
+ def test_load_data(tmp_path):
16
+ """Test loading data from a CSV file."""
17
+ # Create a temporary CSV file
18
+ data = {
19
+ 'Pregnancies': [6, 1, 8],
20
+ 'Glucose': [148, 85, 183],
21
+ 'BloodPressure': [72, 66, 64],
22
+ 'SkinThickness': [35, 29, 0],
23
+ 'Insulin': [0, 0, 0],
24
+ 'BMI': [33.6, 26.6, 23.3],
25
+ 'DiabetesPedigreeFunction': [0.627, 0.351, 0.672],
26
+ 'Age': [50, 31, 32],
27
+ 'Outcome': [1, 0, 1]
28
+ }
29
+ test_file = tmp_path / "test_data.csv"
30
+ df = pd.DataFrame(data)
31
+ df.to_csv(test_file, index=False)
32
+
33
+ # Test loading the data
34
+ loaded_df = load_data(test_file)
35
+ assert isinstance(loaded_df, pd.DataFrame)
36
+ assert loaded_df.shape == (3, 9)
37
+
38
+
39
+ def test_preprocess_data():
40
+ """Test data preprocessing function."""
41
+ # Create test data with zeros that should be replaced
42
+ data = {
43
+ 'Glucose': [0, 85, 0],
44
+ 'BloodPressure': [72, 0, 64],
45
+ 'SkinThickness': [35, 29, 0],
46
+ 'Insulin': [0, 0, 0],
47
+ 'BMI': [33.6, 26.6, 23.3],
48
+ 'Outcome': [1, 0, 1]
49
+ }
50
+ df = pd.DataFrame(data)
51
+
52
+ # Test preprocessing
53
+ X, y = preprocess_data(df)
54
+
55
+ # Check that zeros were replaced with means
56
+ assert (X['Glucose'] != 0).all()
57
+ assert (X['BloodPressure'] != 0).all()
58
+ assert (X['SkinThickness'] != 0).all()
59
+
60
+ # Check shapes
61
+ assert X.shape == (3, 5) # 5 features
62
+ assert y.shape == (3,) # 1 target
63
+
64
+
65
+ def test_split_data():
66
+ """Test train-test splitting function."""
67
+ # Create test data
68
+ X = pd.DataFrame({'feature1': range(100), 'feature2': range(100, 200)})
69
+ y = pd.Series([0] * 50 + [1] * 50) # Balanced classes
70
+
71
+ # Test splitting
72
+ X_train, X_test, y_train, y_test = split_data(X, y, test_size=0.2, random_state=42)
73
+
74
+ # Check shapes
75
+ assert len(X_train) == 80
76
+ assert len(X_test) == 20
77
+ assert len(y_train) == 80
78
+ assert len(y_test) == 20
79
+
80
+ # Check stratification (approximately equal class distribution)
81
+ assert 0.4 <= y_train.mean() <= 0.6
82
+ assert 0.4 <= y_test.mean() <= 0.6
src/diabetes_prediction/utils/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """Utility functions for the diabetes prediction application."""
2
+
3
+ # This file makes the utils directory a Python package
src/diabetes_prediction/utils/helpers.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helper functions for the diabetes prediction application."""
2
+
3
+ import logging
4
+ import logging.config
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Any, Dict, Optional, Union
9
+
10
+
11
+ def setup_logging(config: Optional[Dict[str, Any]] = None) -> None:
12
+ """Set up logging configuration.
13
+
14
+ Args:
15
+ config: Optional logging configuration dictionary. If not provided,
16
+ uses a basic console configuration.
17
+ """
18
+ if config:
19
+ logging.config.dictConfig(config)
20
+ else:
21
+ logging.basicConfig(
22
+ level=logging.INFO,
23
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
24
+ handlers=[logging.StreamHandler(sys.stdout)]
25
+ )
26
+ logger = logging.getLogger(__name__)
27
+ logger.debug("Logging configuration complete")
28
+
29
+
30
+ def ensure_directory_exists(directory: Union[str, Path]) -> Path:
31
+ """Ensure that a directory exists, create it if it doesn't.
32
+
33
+ Args:
34
+ directory: Directory path to check/create
35
+
36
+ Returns:
37
+ Path object of the directory
38
+
39
+ Raises:
40
+ OSError: If directory creation fails
41
+ """
42
+ path = Path(directory).resolve()
43
+ try:
44
+ path.mkdir(parents=True, exist_ok=True)
45
+ return path
46
+ except OSError as e:
47
+ logger = logging.getLogger(__name__)
48
+ logger.error(f"Failed to create directory {path}: {e}")
49
+ raise
50
+
51
+
52
+ def get_absolute_path(relative_path: Union[str, Path]) -> Path:
53
+ """Convert a relative path to an absolute path based on the project root.
54
+
55
+ Args:
56
+ relative_path: Path relative to the project root
57
+
58
+ Returns:
59
+ Absolute path
60
+ """
61
+ project_root = Path(__file__).parent.parent.parent
62
+ return (project_root / relative_path).resolve()
63
+
64
+
65
+ def load_environment_vars(env_file: Union[str, Path] = '.env') -> None:
66
+ """Load environment variables from a .env file.
67
+
68
+ Args:
69
+ env_file: Path to the .env file
70
+ """
71
+ from dotenv import load_dotenv
72
+
73
+ env_path = get_absolute_path(env_file)
74
+ if env_path.exists():
75
+ load_dotenv(dotenv_path=env_path, override=True)
76
+ logger = logging.getLogger(__name__)
77
+ logger.debug(f"Loaded environment variables from {env_path}")
78
+ else:
79
+ logger = logging.getLogger(__name__)
80
+ logger.warning(f"No .env file found at {env_path}")
81
+
82
+
83
+ def validate_environment() -> bool:
84
+ """Validate that all required environment variables are set.
85
+
86
+ Returns:
87
+ bool: True if all required environment variables are set, False otherwise
88
+ """
89
+ required_vars = [
90
+ # Add any required environment variables here
91
+ ]
92
+
93
+ missing_vars = [var for var in required_vars if not os.getenv(var)]
94
+
95
+ if missing_vars:
96
+ logger = logging.getLogger(__name__)
97
+ logger.error(f"Missing required environment variables: {', '.join(missing_vars)}")
98
+ return False
99
+
100
+ return True
src/streamlit_app.py DELETED
@@ -1,40 +0,0 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
- import streamlit as st
5
-
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))