Welcome, {{ user.username }}!
+What would you like to do today?
+diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c5bb855f90719a35283c41ea97cee56ff98a3221 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,36 @@ +# Use Python 3.11 like your local/Render setup +FROM python:3.11-slim + +# System dependencies for numpy / pandas / sklearn / xgboost / shap, etc. +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential \ + gcc \ + g++ \ + git \ + libblas-dev \ + liblapack-dev \ + gfortran \ + libgomp1 \ + && rm -rf /var/lib/apt/lists/* + +# Workdir inside the container +WORKDIR /app + +# Install Python packages +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy the whole project +COPY . . + +# HuggingFace exposes this port +ENV PORT=7860 +ENV PYTHONUNBUFFERED=1 +ENV DJANGO_SETTINGS_MODULE=myproject.settings + +# Collect static files & run migrations +RUN python manage.py collectstatic --noinput || true +RUN python manage.py migrate --noinput || true + +# Start Django via Gunicorn, listening on $PORT +CMD gunicorn myproject.wsgi:application --bind 0.0.0.0:${PORT} --workers 2 diff --git a/manage.py b/manage.py new file mode 100644 index 0000000000000000000000000000000000000000..92bb9a3b2d3b0672cabcfad26835e94407fe1347 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/myproject/__init__.py b/myproject/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/myproject/__pycache__/__init__.cpython-312.pyc b/myproject/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f43e336bfe0b0e0a5f730446e1fa9bfd110c6ee0 Binary files /dev/null and b/myproject/__pycache__/__init__.cpython-312.pyc differ diff --git a/myproject/__pycache__/settings.cpython-312.pyc b/myproject/__pycache__/settings.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b15229af3bd750c471b23e82f8dd9f772bab8abe Binary files /dev/null and b/myproject/__pycache__/settings.cpython-312.pyc differ diff --git a/myproject/__pycache__/urls.cpython-312.pyc b/myproject/__pycache__/urls.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e857d817088057722f72b57ae2e8a476abb0689 Binary files /dev/null and b/myproject/__pycache__/urls.cpython-312.pyc differ diff --git a/myproject/__pycache__/wsgi.cpython-312.pyc b/myproject/__pycache__/wsgi.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d98d55daa369845b624372dac960ebcc0010208 Binary files /dev/null and b/myproject/__pycache__/wsgi.cpython-312.pyc differ diff --git a/myproject/asgi.py b/myproject/asgi.py new file mode 100644 index 0000000000000000000000000000000000000000..18346a369d392cb52c85905f8d28054f7026a411 --- /dev/null +++ b/myproject/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for myproject project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') + +application = get_asgi_application() diff --git a/myproject/settings.py b/myproject/settings.py new file mode 100644 index 0000000000000000000000000000000000000000..4b7061c2a5f755737f392810808688409889c668 --- /dev/null +++ b/myproject/settings.py @@ -0,0 +1,105 @@ +""" +Django settings for myproject project. + +Generated by 'django-admin startproject' using Django 5.2.3. + +For more information on this file, see +https://docs.djangoproject.com/en/5.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/5.2/ref/settings/ +""" + +from pathlib import Path + + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent +LOGIN_URL = '/login/' +LOGIN_REDIRECT_URL = '/landing/' +SESSION_EXPIRE_AT_BROWSER_CLOSE = True + +SECRET_KEY = 'django-insecure-&ew@l$*1zi4$0s^)nrrx#s$j09au5dmty@blo-j1ou+=v(v!(r' +DEBUG = True + +ALLOWED_HOSTS = ["*"] + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'webapp', + 'django_browser_reload', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', # <-- ON + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + # you *can* keep clickjacking protection off if you really need iframes: + # 'django.middleware.clickjacking.XFrameOptionsMiddleware', + 'django_browser_reload.middleware.BrowserReloadMiddleware', +] + +CSRF_TRUSTED_ORIGINS = [ + "https://peaceabolisher-ml-lab.hf.space", + "https://huggingface.co", + "https://*.huggingface.co", +] + +X_FRAME_OPTIONS = "ALLOWALL" + +ROOT_URLCONF = 'myproject.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'myproject.wsgi.application' + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + +MEDIA_ROOT = BASE_DIR / "media" +MEDIA_URL = "/media/" + +AUTH_PASSWORD_VALIDATORS = [ + {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, + {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, + {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, + {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}, +] + +LANGUAGE_CODE = 'en-us' +TIME_ZONE = 'UTC' +USE_I18N = True +USE_TZ = True + +STATIC_URL = 'static/' +STATIC_ROOT = BASE_DIR / "staticfiles" + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/myproject/urls.py b/myproject/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..a14b8b6821cb18589e90705ca040404b15b8d24d --- /dev/null +++ b/myproject/urls.py @@ -0,0 +1,16 @@ +# myproject/urls.py +from django.contrib import admin +from django.urls import path, include +from django.conf import settings +from django.conf.urls.static import static + +urlpatterns = [ + path('admin/', admin.site.urls), + # Include all URL patterns from the 'webapp' app + path('', include('webapp.urls')), + # Include django_browser_reload URLs if you're using it + path("__reload__/", include("django_browser_reload.urls")), +] + +if settings.DEBUG: + urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \ No newline at end of file diff --git a/myproject/wsgi.py b/myproject/wsgi.py new file mode 100644 index 0000000000000000000000000000000000000000..7c6fdd6bb474f73aa47e378499f3009e762530ac --- /dev/null +++ b/myproject/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for myproject project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') + +application = get_wsgi_application() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..5958a06f6d4c61c8f50b505a6b71ddc52bd58ac6 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,24 @@ +Django +django-browser-reload +gunicorn + +numpy +pandas +scikit-learn +xgboost + +matplotlib +seaborn + +shap + +requests +python-dateutil +pytz +tzdata +PyYAML +imbalanced-learn +ctgan +tensorflow +scikeras + diff --git a/staticfiles/.gitkeep b/staticfiles/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/webapp/__init__.py b/webapp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/webapp/__pycache__/__init__.cpython-312.pyc b/webapp/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a328847f7ee939d67bf21f3d08d0b9cc1334f940 Binary files /dev/null and b/webapp/__pycache__/__init__.cpython-312.pyc differ diff --git a/webapp/__pycache__/admin.cpython-312.pyc b/webapp/__pycache__/admin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e9447eb2e504aab58cf5eb9c1ddba41bfbd07bb Binary files /dev/null and b/webapp/__pycache__/admin.cpython-312.pyc differ diff --git a/webapp/__pycache__/apps.cpython-312.pyc b/webapp/__pycache__/apps.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1156c314e0b66afe0a249b61c45694637b81299d Binary files /dev/null and b/webapp/__pycache__/apps.cpython-312.pyc differ diff --git a/webapp/__pycache__/forms.cpython-312.pyc b/webapp/__pycache__/forms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21721571f72add6154eb4b1abbda507ad363d3ec Binary files /dev/null and b/webapp/__pycache__/forms.cpython-312.pyc differ diff --git a/webapp/__pycache__/models.cpython-312.pyc b/webapp/__pycache__/models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d695b843db7c3865fc2f7e34ac2947b99009744 Binary files /dev/null and b/webapp/__pycache__/models.cpython-312.pyc differ diff --git a/webapp/__pycache__/urls.cpython-312.pyc b/webapp/__pycache__/urls.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02298b0af14853afe48a9ddd02afbff4aed9bf25 Binary files /dev/null and b/webapp/__pycache__/urls.cpython-312.pyc differ diff --git a/webapp/__pycache__/views.cpython-312.pyc b/webapp/__pycache__/views.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71d053e973e6e9a814915704c548421b5d7a92b1 Binary files /dev/null and b/webapp/__pycache__/views.cpython-312.pyc differ diff --git a/webapp/admin.py b/webapp/admin.py new file mode 100644 index 0000000000000000000000000000000000000000..41940d664fce78eb337be392cf704a193643d67b --- /dev/null +++ b/webapp/admin.py @@ -0,0 +1,6 @@ +# webapp/admin.py +from django.contrib import admin +from .models import SavedModel, PublicDataset + +admin.site.register(SavedModel) +admin.site.register(PublicDataset) diff --git a/webapp/apps.py b/webapp/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..af0035d4434cfd2ec39643d196a11d133148d017 --- /dev/null +++ b/webapp/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class WebappConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'webapp' diff --git a/webapp/forms.py b/webapp/forms.py new file mode 100644 index 0000000000000000000000000000000000000000..2559d94ba6e959a983e6e7ceb3ed6a4d3dab8e31 --- /dev/null +++ b/webapp/forms.py @@ -0,0 +1,159 @@ +from django import forms +from django.contrib.auth.forms import UserCreationForm +from django.contrib.auth import get_user_model +from .models import UserProfile +from datetime import date + +SCALER_CHOICES = [ + ("standard", "Standard Scaler"), + ("minmax", "MinMax Scaler"), +] + +MODEL_CHOICES = [ + ("rf", "Random Forest"), + ("svm", "Support Vector Machine"), + ("knn", "K-Nearest Neighbors"), + ("lr", "Logistic Regression"), + ("gb", "Gradient Boosting"), + ("xgb", "XGBoost"), + ("mlp", "MLP (Neural Network)"), +] + +META_CHOICES = [ + ("lr", "Logistic Regression"), + ("rf", "Random Forest"), + ("gb", "Gradient Boosting"), +] + +ENSEMBLE_CHOICES = [ + ("none", "No Ensemble"), + ("voting", "Voting Classifier"), + ("stacking","Stacking Classifier"), +] + +VOTING_CHOICES = [ + ("hard", "Hard Voting"), + ("soft", "Soft Voting"), +] + +BALANCING_CHOICES = [ + ("none", "None"), + ("over", "Random Oversampling"), + ("smote", "SMOTE"), + ("gans", "GANS"), +] + +AUGMENT_CHOICES = [ + ("none", "None"), + ("gans", "GANS"), +] + + +class SaveModelForm(forms.Form): + name = forms.CharField(max_length=120) + public = forms.BooleanField(required=False) + description = forms.CharField(required=False,widget=forms.Textarea(attrs={"rows": 3, "maxlength": 2000}) +) + + +class UploadForm(forms.Form): + dataset = forms.FileField( + label="Upload CSV Dataset", + widget=forms.ClearableFileInput(attrs={"class": "form-control"}) + ) + + scaler = forms.ChoiceField( + choices=SCALER_CHOICES, + initial="standard", + widget=forms.Select(attrs={"class": "form-select"}) + ) + + base_models = forms.MultipleChoiceField( + choices=MODEL_CHOICES, + widget=forms.CheckboxSelectMultiple, + label="Base Models", + required=True, + ) + + meta_learner = forms.ChoiceField( + choices=META_CHOICES, + initial="lr", + widget=forms.Select(attrs={"class": "form-select"}) + ) + + ensemble_type = forms.ChoiceField( + choices=ENSEMBLE_CHOICES, + initial="none", + widget=forms.Select(attrs={"class": "form-select"}) + ) + + voting_type = forms.ChoiceField( + choices=VOTING_CHOICES, + required=False, + initial="hard", + widget=forms.Select(attrs={"class": "form-select"}) + ) + + balancing_strategy = forms.ChoiceField( + choices=BALANCING_CHOICES, + initial="none", + widget=forms.Select(attrs={"class": "form-select"}) + ) + + augmentation = forms.ChoiceField( + choices=AUGMENT_CHOICES, + initial="none", + widget=forms.Select(attrs={"class": "form-select"}) + ) + + target_samples = forms.IntegerField( + required=False, + min_value=1, + widget=forms.NumberInput(attrs={"class": "form-control", "placeholder": "e.g. 500"}) + ) + + def clean_base_models(self): + data = self.cleaned_data.get("base_models") or [] + if len(data) == 0: + raise forms.ValidationError("Pick at least one base model.") + return data + + +class RegisterForm(UserCreationForm): + full_name = forms.CharField( + max_length=150, + label="Name", + widget=forms.TextInput(attrs={"class": "form-control"}) + ) + date_of_birth = forms.DateField( + label="Date of birth", + widget=forms.DateInput(attrs={"type": "date", "class": "form-control"}) + ) + + class Meta: + model = get_user_model() + fields = ("username", "full_name", "date_of_birth", "password1", "password2") + + def clean_date_of_birth(self): + dob = self.cleaned_data["date_of_birth"] + if dob >= date.today(): + raise forms.ValidationError("Date of birth must be in the past.") + return dob + + def save(self, commit=True): + user = super().save(commit=False) + + # Best-effort split full_name into first/last for the auth user + name = self.cleaned_data.get("full_name", "").strip() + first, *rest = name.split() + user.first_name = first or "" + user.last_name = " ".join(rest) if rest else "" + + if commit: + user.save() + UserProfile.objects.create( + user=user, + full_name=name, + date_of_birth=self.cleaned_data["date_of_birth"], + ) + return user diff --git a/webapp/migrations/0001_initial.py b/webapp/migrations/0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..026e8dd05f29a229e34462aa62e8b527c0d1d1e0 --- /dev/null +++ b/webapp/migrations/0001_initial.py @@ -0,0 +1,44 @@ +# Generated by Django 5.2.3 on 2025-09-17 17:28 + +import django.db.models.deletion +import webapp.models +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='PublicDataset', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=160)), + ('description', models.TextField(blank=True)), + ('file', models.FileField(upload_to=webapp.models.dataset_upload_path)), + ('rows', models.IntegerField(blank=True, null=True)), + ('cols', models.IntegerField(blank=True, null=True)), + ('is_active', models.BooleanField(default=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ], + ), + migrations.CreateModel( + name='SavedModel', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=120)), + ('file', models.FileField(upload_to=webapp.models.model_upload_path)), + ('public', models.BooleanField(default=False)), + ('test_auc', models.FloatField(blank=True, null=True)), + ('test_f1', models.FloatField(blank=True, null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='saved_models', to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/webapp/migrations/0002_userprofile.py b/webapp/migrations/0002_userprofile.py new file mode 100644 index 0000000000000000000000000000000000000000..79891c52f7cce06a6d30b53bf1d89f70ae299b75 --- /dev/null +++ b/webapp/migrations/0002_userprofile.py @@ -0,0 +1,25 @@ +# Generated by Django 5.2.3 on 2025-09-25 10:28 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('webapp', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='UserProfile', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('full_name', models.CharField(max_length=150)), + ('date_of_birth', models.DateField()), + ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/webapp/migrations/0003_savedmodel_description.py b/webapp/migrations/0003_savedmodel_description.py new file mode 100644 index 0000000000000000000000000000000000000000..2bf6e13f537fa2d36e110b11173a6c497b4e776f --- /dev/null +++ b/webapp/migrations/0003_savedmodel_description.py @@ -0,0 +1,18 @@ +# Generated by Django 5.2.3 on 2025-11-04 10:45 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('webapp', '0002_userprofile'), + ] + + operations = [ + migrations.AddField( + model_name='savedmodel', + name='description', + field=models.TextField(blank=True, max_length=2000), + ), + ] diff --git a/webapp/migrations/0004_savedmodel_trained_on.py b/webapp/migrations/0004_savedmodel_trained_on.py new file mode 100644 index 0000000000000000000000000000000000000000..830a56ea6feebbc1a037084146bd3b245ca9b672 --- /dev/null +++ b/webapp/migrations/0004_savedmodel_trained_on.py @@ -0,0 +1,18 @@ +# Generated by Django 5.2.3 on 2025-11-04 11:21 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('webapp', '0003_savedmodel_description'), + ] + + operations = [ + migrations.AddField( + model_name='savedmodel', + name='trained_on', + field=models.CharField(blank=True, max_length=200), + ), + ] diff --git a/webapp/migrations/0005_add_trained_on_field.py b/webapp/migrations/0005_add_trained_on_field.py new file mode 100644 index 0000000000000000000000000000000000000000..ee1afdfeed89b5d50b489e260ba21358d40056fd --- /dev/null +++ b/webapp/migrations/0005_add_trained_on_field.py @@ -0,0 +1,13 @@ +# Generated by Django 5.2.3 on 2025-11-04 11:33 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('webapp', '0004_savedmodel_trained_on'), + ] + + operations = [ + ] diff --git a/webapp/migrations/__init__.py b/webapp/migrations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/webapp/migrations/__pycache__/0001_initial.cpython-312.pyc b/webapp/migrations/__pycache__/0001_initial.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c677f08b7cca628a86627dbb93a6f418fcbcd2fd Binary files /dev/null and b/webapp/migrations/__pycache__/0001_initial.cpython-312.pyc differ diff --git a/webapp/migrations/__pycache__/0002_userprofile.cpython-312.pyc b/webapp/migrations/__pycache__/0002_userprofile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f3752b3ef1f9e6aeeae36091a70f4d18542c573 Binary files /dev/null and b/webapp/migrations/__pycache__/0002_userprofile.cpython-312.pyc differ diff --git a/webapp/migrations/__pycache__/0003_savedmodel_description.cpython-312.pyc b/webapp/migrations/__pycache__/0003_savedmodel_description.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0415345d8fae1968985a9c151a3b84e685204ab3 Binary files /dev/null and b/webapp/migrations/__pycache__/0003_savedmodel_description.cpython-312.pyc differ diff --git a/webapp/migrations/__pycache__/0004_savedmodel_trained_on.cpython-312.pyc b/webapp/migrations/__pycache__/0004_savedmodel_trained_on.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..132ef7950ef0b454940e8b3889e72bce674b0591 Binary files /dev/null and b/webapp/migrations/__pycache__/0004_savedmodel_trained_on.cpython-312.pyc differ diff --git a/webapp/migrations/__pycache__/0005_add_trained_on_field.cpython-312.pyc b/webapp/migrations/__pycache__/0005_add_trained_on_field.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9a205bec327689a5b990d3a93c528cd117a925a Binary files /dev/null and b/webapp/migrations/__pycache__/0005_add_trained_on_field.cpython-312.pyc differ diff --git a/webapp/migrations/__pycache__/__init__.cpython-312.pyc b/webapp/migrations/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce0d0058bbe8aa33b064039dbd5530dc69b58518 Binary files /dev/null and b/webapp/migrations/__pycache__/__init__.cpython-312.pyc differ diff --git a/webapp/models.py b/webapp/models.py new file mode 100644 index 0000000000000000000000000000000000000000..dad56e6bdd0e66e5095640a6f39495300420301c --- /dev/null +++ b/webapp/models.py @@ -0,0 +1,46 @@ +# webapp/models.py +from django.db import models +from django.contrib.auth import get_user_model + +User = get_user_model() + +def model_upload_path(instance, filename): + return f"saved_models/{instance.owner_id}/{filename}" + +def dataset_upload_path(instance, filename): + return f"public_datasets/{filename}" + +class SavedModel(models.Model): + owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="saved_models") + name = models.CharField(max_length=120) + description = models.TextField(blank=True, max_length=2000) + trained_on = models.CharField(max_length=200, blank=True) + file = models.FileField(upload_to=model_upload_path) + public = models.BooleanField(default=False) + test_auc = models.FloatField(null=True, blank=True) + test_f1 = models.FloatField(null=True, blank=True) + created_at = models.DateTimeField(auto_now_add=True) + + def __str__(self): + return self.name + +class PublicDataset(models.Model): + name = models.CharField(max_length=160) + description = models.TextField(blank=True) + file = models.FileField(upload_to=dataset_upload_path) + rows = models.IntegerField(null=True, blank=True) + cols = models.IntegerField(null=True, blank=True) + is_active = models.BooleanField(default=True) + created_at = models.DateTimeField(auto_now_add=True) + + def __str__(self): + return self.name + + +class UserProfile(models.Model): + user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") + full_name = models.CharField(max_length=150) + date_of_birth = models.DateField() + + def __str__(self): + return f"{self.full_name} ({self.user.username})" diff --git a/webapp/services/__init__.py b/webapp/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/webapp/services/__pycache__/__init__.cpython-312.pyc b/webapp/services/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22d6137b9325e7535a4170c3bc8b7a2548302e9e Binary files /dev/null and b/webapp/services/__pycache__/__init__.cpython-312.pyc differ diff --git a/webapp/services/__pycache__/charts.cpython-312.pyc b/webapp/services/__pycache__/charts.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c7145bc7c101db4a51198a47eec84d5e0a7cf91 Binary files /dev/null and b/webapp/services/__pycache__/charts.cpython-312.pyc differ diff --git a/webapp/services/__pycache__/inference.cpython-312.pyc b/webapp/services/__pycache__/inference.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d687e189a7c0b07143ee58e2bd32e0819094a6f3 Binary files /dev/null and b/webapp/services/__pycache__/inference.cpython-312.pyc differ diff --git a/webapp/services/__pycache__/io_utils.cpython-312.pyc b/webapp/services/__pycache__/io_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abc4ed4d4e35a06c17a71c4830cfd614ac07c019 Binary files /dev/null and b/webapp/services/__pycache__/io_utils.cpython-312.pyc differ diff --git a/webapp/services/__pycache__/ml_utils.cpython-312.pyc b/webapp/services/__pycache__/ml_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..870fde353e263fc2348122bc508980f4111fad3c Binary files /dev/null and b/webapp/services/__pycache__/ml_utils.cpython-312.pyc differ diff --git a/webapp/services/__pycache__/training.cpython-312.pyc b/webapp/services/__pycache__/training.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..652f0185175c567e74944a2d231405c28ea1a5c0 Binary files /dev/null and b/webapp/services/__pycache__/training.cpython-312.pyc differ diff --git a/webapp/services/charts.py b/webapp/services/charts.py new file mode 100644 index 0000000000000000000000000000000000000000..87306f7353730e9832492b879029aabf115fd247 --- /dev/null +++ b/webapp/services/charts.py @@ -0,0 +1,22 @@ +# webapp/services/charts.py +import io, base64 +import matplotlib +matplotlib.use('Agg') +import matplotlib.pyplot as plt +import numpy as np + +def preds_hist_data_url(preds) -> str: + buf = io.BytesIO() + plt.figure(figsize=(6,4)) + try: + plt.hist(preds, bins=3) + except Exception: + vals, counts = np.unique(preds, return_counts=True) + plt.bar([str(v) for v in vals], counts) + plt.title('Predictions') + plt.tight_layout() + plt.savefig(buf, format='png') + plt.close() + buf.seek(0) + b64 = base64.b64encode(buf.read()).decode('utf-8') + return f'data:image/png;base64,{b64}' diff --git a/webapp/services/inference.py b/webapp/services/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..9cc6e382ff2af507646c0598d977b28b6b63de8d --- /dev/null +++ b/webapp/services/inference.py @@ -0,0 +1,326 @@ +from __future__ import annotations + +import io, os, uuid +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Tuple +import re +import joblib +import numpy as np +import pandas as pd +from django.conf import settings +from sklearn.metrics import f1_score, roc_auc_score +from sklearn.inspection import permutation_importance + +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +try: + import shap + _SHAP_OK = True +except Exception: + _SHAP_OK = False + + +@dataclass +class InferenceResult: + error: Optional[str] = None + predictions: Optional[List[Tuple[str, int]]] = None + test_f1: Optional[float] = None + test_auc: Optional[float] = None + val_f1: Optional[float] = None + val_auc: Optional[float] = None + shap_url: Optional[str] = None + explain_type: Optional[str] = None + summary: Optional[Dict[str, Any]] = None + + + +def _pretty_feature_names(names: List[str]) -> List[str]: + out = [] + for n in names: + s = str(n) + # strip ColumnTransformer prefixes + s = re.sub(r'^(num|cat)_{1,2}', '', s) + out.append(s if len(s) <= 40 else s[:37] + '…') + return out + + +def _read_model(upload): + if hasattr(upload, "read"): + data = upload.read() + return joblib.load(io.BytesIO(data)) + return joblib.load(upload) + + +def _coerce_numeric(df: pd.DataFrame) -> pd.DataFrame: + out = df.copy() + for c in out.columns: + if out[c].dtype == object: + coerced = pd.to_numeric(out[c], errors="coerce") + if coerced.notna().sum() > 0: + out[c] = coerced + return out + + +def _media_plot_paths(run_id: str, tag: str) -> Tuple[str, str]: + rel_dir = "inference_runs" + abs_dir = os.path.join(settings.MEDIA_ROOT, rel_dir) + os.makedirs(abs_dir, exist_ok=True) + abs_path = os.path.join(abs_dir, f"{run_id}_{tag}.svg") # ← SVG + url = settings.MEDIA_URL + f"{rel_dir}/{run_id}_{tag}.svg" + return abs_path, url + + +def _try_shap(model, X: pd.DataFrame, feature_names: List[str], run_id: str) -> Tuple[Optional[str], Optional[List[Tuple[str, float]]]]: + if not _SHAP_OK: + return None, None + try: + bg = X.sample(min(50, len(X)), random_state=0) + ev = X.sample(min(200, len(X)), random_state=1) + + try: + exp = shap.Explainer(model, bg) + sv = exp(ev) + shap.summary_plot(sv, features=ev, feature_names=feature_names, plot_type="bar", show=False) + # mean absolute shap per feature + vals = np.abs(sv.values).mean(0) + except Exception: + def _f(A): + df = pd.DataFrame(A, columns=feature_names) + if hasattr(model, "predict_proba"): + return model.predict_proba(df)[:, 1] + return model.predict(df) + kexp = shap.KernelExplainer(_f, bg) + sv = kexp.shap_values(ev, nsamples=100) + shap.summary_plot(sv, ev, feature_names=feature_names, plot_type="bar", show=False) + vals = np.abs(sv).mean(0) # kernel returns ndarray + + plt.tight_layout() + plt.gcf().set_size_inches(8, 5) # ← baseline size + abs_path, url = _media_plot_paths(run_id, "shap") + plt.savefig(abs_path, format="svg", bbox_inches="tight") + plt.close() + + + importances = [(str(f), float(v)) for f, v in zip(feature_names, vals)] + return url, importances + except Exception: + try: plt.close() + except Exception: pass + return None, None + + + +def _try_perm(model, X: pd.DataFrame, y: pd.Series, feature_names: List[str], run_id: str) -> Tuple[Optional[str], Optional[List[Tuple[str, float]]]]: + try: + res = permutation_importance(model, X, y, n_repeats=10, random_state=0, scoring="roc_auc") + imps = pd.Series(res.importances_mean, index=feature_names).fillna(0.0) + top = imps.sort_values().tail(25) + + plt.figure(figsize=(10, 6), dpi=140) + cols = ["tab:red" if v < 0 else "tab:green" for v in top.values] + plt.barh(top.index, top.values, color=cols, alpha=0.9) + plt.axvline(0, linestyle="--", linewidth=1, alpha=0.6) + plt.title("Permutation importance") + plt.xlabel("Δ ROC AUC when permuted") + plt.tight_layout() + + abs_path, url = _media_plot_paths(run_id, "perm") + plt.savefig(abs_path, format="svg", bbox_inches="tight") + plt.close() + + importances = [(str(f), float(s)) for f, s in zip(feature_names, res.importances_mean)] + return url, importances + except Exception: + try: plt.close() + except Exception: pass + return None, None + + +def _normalize_artifact(obj: Any) -> Dict[str, Any]: + """ + Normalize different saved shapes into a common dict: + keys: model, preprocessor|scaler (optional), selector (optional), + pre_features (optional), final_features (optional), + val_auc/val_f1/test_auc/test_f1 (optional) + """ + # A) New/modern artifact (dict with "model") + if isinstance(obj, dict) and "model" in obj: + return { + "model": obj["model"], + "preprocessor": obj.get("preprocessor"), + "scaler": obj.get("scaler"), + "selector": obj.get("selector"), + "pre_features": obj.get("pre_selection_feature_names"), + "final_features": obj.get("final_feature_names"), + "val_auc": obj.get("val_auc"), + "val_f1": obj.get("val_f1"), + "test_auc": obj.get("test_auc"), + "test_f1": obj.get("test_f1"), + } + + # B) Older scripts (dict with model + scaler and possibly selector + feature lists) + if isinstance(obj, dict) and "model" in obj and ("scaler" in obj or "preprocessor" in obj): + return { + "model": obj["model"], + "preprocessor": obj.get("preprocessor"), + "scaler": obj.get("scaler"), + "selector": obj.get("selector"), + "pre_features": obj.get("pre_selection_feature_names"), + "final_features": obj.get("final_feature_names") or obj.get("feature_names"), + "val_auc": obj.get("val_auc"), + "val_f1": obj.get("val_f1"), + "test_auc": obj.get("test_auc"), + "test_f1": obj.get("test_f1"), + } + + # C) Plain sklearn Pipeline or bare estimator + if hasattr(obj, "predict") and hasattr(obj, "fit"): + return { + "model": obj, + "preprocessor": None, + "scaler": None, + "selector": None, + "pre_features": None, + "final_features": list(getattr(obj, "feature_names_in_", [])) or None, + "val_auc": None, "val_f1": None, "test_auc": None, "test_f1": None, + } + + raise ValueError("Unrecognized model file format") + + +def run_inference(model_file, test_file) -> InferenceResult: + # Load model/artifact + try: + obj = _read_model(model_file) + except Exception as e: + return InferenceResult(error=f"Could not load model file: {e}") + + try: + art = _normalize_artifact(obj) + except Exception as e: + return InferenceResult(error=f"Uploaded model file is not a recognized artifact: {e}") + + # Load test CSV + try: + df = pd.read_csv(test_file) if hasattr(test_file, "read") else pd.read_csv(str(test_file)) + except Exception as e: + return InferenceResult(error=f"Could not read test data: {e}") + + y = df["healthy"].astype(int).reset_index(drop=True) if "healthy" in df.columns else None + X = df.drop(columns=["healthy"]) if "healthy" in df.columns else df + X = _coerce_numeric(X) + + model = art["model"] + preprocessor = art.get("preprocessor") + scaler = art.get("scaler") + selector = art.get("selector") + pre_feats = art.get("pre_features") + final_feats = art.get("final_features") + + # ── Preprocess (A: reindex to training columns before transform) ─────────── + try: + if preprocessor is not None: + # Columns the ColumnTransformer saw during fit (raw, before OHE/scale) + raw_cols = list(getattr(preprocessor, "feature_names_in_", [])) + if raw_cols: + # Drop extras like `sample_id`; add any missing cols as NaN for imputers + X_raw = X.reindex(columns=raw_cols, fill_value=np.nan) + else: + X_raw = X # fallback if sklearn version lacks feature_names_in_ + Xp_arr = preprocessor.transform(X_raw) + names = preprocessor.get_feature_names_out().tolist() + Xp = pd.DataFrame(Xp_arr, columns=names).astype(np.float32) + + elif scaler is not None: + # If an older artifact saved a bare scaler, align to its training columns too + raw_cols = list(getattr(scaler, "feature_names_in_", [])) + X_raw = X.reindex(columns=raw_cols, fill_value=np.nan) if raw_cols else X + if not hasattr(scaler, "n_features_in_"): + try: + scaler.fit(X_raw) + except Exception: + pass + Xp = pd.DataFrame(scaler.transform(X_raw), columns=X_raw.columns).astype(np.float32) + + else: + Xp = X.copy() + + # Feature selection / alignment + if selector is not None and pre_feats is not None: + X_aligned = Xp.reindex(columns=pre_feats, fill_value=0.0) + X_final_arr = selector.transform(X_aligned) + Xf = pd.DataFrame(X_final_arr, columns=final_feats) + elif final_feats is not None: + Xf = Xp.reindex(columns=final_feats, fill_value=0.0) + elif hasattr(model, "feature_names_in_"): + needs = list(model.feature_names_in_) + Xf = Xp.reindex(columns=needs, fill_value=0.0) + final_feats = needs + else: + Xf = Xp + final_feats = Xf.columns.tolist() + except Exception as e: + return InferenceResult(error=f"Preprocessing/feature selection failed: {e}") + + # Clean labels for plots/links (drop num__/cat__ prefixes) + pretty_feats = _pretty_feature_names(final_feats) + + + # Predict + try: + y_pred = model.predict(Xf) + except Exception as e: + return InferenceResult(error=f"Model prediction failed: {e}") + + # Metrics (optional) + test_f1 = test_auc = None + if y is not None and len(y) == len(y_pred): + try: + test_f1 = float(f1_score(y, y_pred)) + except Exception: + test_f1 = None + try: + if hasattr(model, "predict_proba"): + test_auc = float(roc_auc_score(y, model.predict_proba(Xf)[:, 1])) + except Exception: + test_auc = None + + # Explainability + run_id = uuid.uuid4().hex + summary = None + + shap_url, shap_importances = _try_shap(model, Xf, pretty_feats, run_id) + explain_type = "shap" if shap_url else None + + if shap_url: + summary = {"explain_type": "shap", "shap_importance": shap_importances} + elif y is not None: + perm_url, perm_importances = _try_perm(model, Xf, y, pretty_feats, run_id) + if perm_url: + shap_url = perm_url + explain_type = "permutation" + summary = {"explain_type": "permutation", "permutation_importance": perm_importances} + + + # Preview (show sample_id if present) + n = min(25, len(df)) + row_ids = ( + df["sample_id"].astype(str).tolist()[:n] + if "sample_id" in df.columns else [str(i) for i in range(n)] + ) + preds_head = list(zip(row_ids, [int(y_pred[i]) for i in range(n)])) + + return InferenceResult( + error=None, + predictions=preds_head, + test_f1=test_f1, + test_auc=test_auc, + val_f1=(None if art.get("val_f1") is None else float(art["val_f1"])), + val_auc=(None if art.get("val_auc") is None else float(art["val_auc"])), + shap_url=shap_url, + explain_type=explain_type, + summary=summary, #make sure the new summary is returned +) + diff --git a/webapp/services/io_utils.py b/webapp/services/io_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..53eae789be827a79472f54f7fd7441ea1931827c --- /dev/null +++ b/webapp/services/io_utils.py @@ -0,0 +1,18 @@ +# webapp/services/io_utils.py +import io +import pandas as pd + +def read_csv_or_txt(uploaded_file) -> pd.DataFrame: + """Reads CSV or TXT. Ignores lines starting with #.""" + if not uploaded_file: + raise ValueError("Missing file.") + raw = uploaded_file.read().decode("utf-8", errors="replace") + lines = raw.splitlines() + data_lines = [ln for ln in lines if not ln.strip().startswith("#")] + if not data_lines: + raise ValueError("No data rows found.") + txt = "\n".join(data_lines) + try: + return pd.read_csv(io.StringIO(txt)) # comma + except Exception: + return pd.read_csv(io.StringIO(txt), sep="\t") # tab diff --git a/webapp/services/ml_utils.py b/webapp/services/ml_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fbdc2c6a0b0e5d92059111e506181276ce508a1c --- /dev/null +++ b/webapp/services/ml_utils.py @@ -0,0 +1,108 @@ +# webapp/services/ml_utils.py +from dataclasses import dataclass +from typing import List, Optional, Tuple +import numpy as np +import pandas as pd + +from sklearn.compose import ColumnTransformer +from sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder +from sklearn.pipeline import Pipeline +from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, VotingClassifier, StackingClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.svm import SVC +from sklearn.neighbors import KNeighborsClassifier + +try: + from xgboost import XGBClassifier + XGB_OK = True +except Exception: + XGB_OK = False + +# Optional balancing +try: + from imblearn.over_sampling import RandomOverSampler, SMOTE + IMB_OK = True +except Exception: + IMB_OK = False + +NON_FEATURE_COLS = {'healthy','label','target','sample_id','id'} + +def get_model_from_choice(choice: str): + if choice == 'rf': + return RandomForestClassifier() + if choice == 'svm': + return SVC(probability=True) + if choice == 'knn': + return KNeighborsClassifier() + if choice == 'lr': + return LogisticRegression(max_iter=1000) + if choice == 'gb': + return GradientBoostingClassifier() + if choice == 'xgb' and XGB_OK: + return XGBClassifier(use_label_encoder=False, eval_metric='logloss') + if choice == 'mlp': + from sklearn.neural_network import MLPClassifier + return MLPClassifier(hidden_layer_sizes=(128,64), max_iter=500) + raise ValueError(f"Unsupported model choice: {choice}") + +def build_preprocessor(scaler_key: str, X: pd.DataFrame) -> ColumnTransformer: + num_cols = X.select_dtypes(include='number').columns.tolist() + cat_cols = X.select_dtypes(exclude='number').columns.tolist() + + scaler = StandardScaler() if scaler_key == 'standard' else MinMaxScaler() + return ColumnTransformer( + transformers=[ + ('num', scaler, num_cols), + ('cat', OneHotEncoder(handle_unknown='ignore', sparse_output=False), cat_cols), + ], + remainder='drop', + verbose_feature_names_out=False, + ) + +def build_estimator(base_models: List[str], meta_learner: str, + ensemble_type: str, voting_type: str): + estimators = [(k, get_model_from_choice(k)) for k in base_models] + if len(estimators) == 0: + raise ValueError("Select at least one base model.") + if len(estimators) >= 2 and ensemble_type == 'none': + ensemble_type = 'stacking' # server-side guard + + if ensemble_type == 'voting': + return VotingClassifier(estimators=estimators, voting=voting_type) + if ensemble_type == 'stacking': + meta = get_model_from_choice(meta_learner) + return StackingClassifier(estimators=estimators, final_estimator=meta) + return estimators[0][1] + +def apply_balancing(X: pd.DataFrame, y: pd.Series, + strategy: str, target_samples: Optional[int]) -> Tuple[pd.DataFrame, pd.Series]: + """Applies optional balancing. SMOTE/oversampling via imblearn; GAN hooks left for you to plug in.""" + if strategy == 'none': + return X, y + if strategy == 'over': + if not IMB_OK: + raise RuntimeError("imblearn not installed for RandomOverSampler.") + ros = RandomOverSampler() + Xr, yr = ros.fit_resample(X, y) + return Xr, yr + if strategy == 'smote': + if not IMB_OK: + raise RuntimeError("imblearn not installed for SMOTE.") + sm = SMOTE() + Xr, yr = sm.fit_resample(X, y) + return Xr, yr + if strategy == 'gans': + # 🔌 hook your GAN generator here; placeholder pass-through: + # from your_module import synthesize_with_gan + # Xr, yr = synthesize_with_gan(X, y, target_samples=target_samples) + return X, y # no-op by default + return X, y + +def apply_augmentation(X_train: pd.DataFrame, y_train: pd.Series, + augmentation: str, target_samples: Optional[int]) -> Tuple[pd.DataFrame, pd.Series]: + if augmentation == 'none': + return X_train, y_train + if augmentation == 'gans': + # 🔌 hook GAN augmentation for the training fold only + return X_train, y_train # no-op by default + return X_train, y_train diff --git a/webapp/services/testing.py b/webapp/services/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..18e0630f440d70b92bc5c7d851d5e614a4b751e6 --- /dev/null +++ b/webapp/services/testing.py @@ -0,0 +1,132 @@ +# webapp/services/testing.py +from __future__ import annotations +import io +from typing import Dict, Any, Tuple, Optional +import numpy as np +import pandas as pd +import joblib +from sklearn.metrics import f1_score, roc_auc_score, accuracy_score, confusion_matrix + +NON_FEATURE_COLS = {"healthy", "label", "target", "sample_id", "id"} + +def _read_txt_like(uploaded_file) -> pd.DataFrame: + raw = uploaded_file.read().decode("utf-8", errors="replace") + lines = [ln for ln in raw.splitlines() if not ln.strip().startswith("#")] + if not lines: + raise ValueError("No data rows found (file only contains comments).") + txt = "\n".join(lines) + try: + df = pd.read_csv(io.StringIO(txt)) + except Exception: + df = pd.read_csv(io.StringIO(txt), sep="\t") + if df.empty: + raise ValueError("Parsed an empty table. Check delimiter and header.") + return df + +def _align_numeric(df: pd.DataFrame) -> pd.DataFrame: + X = df.drop(columns=[c for c in NON_FEATURE_COLS if c in df.columns], errors="ignore").copy() + for c in X.columns: + X[c] = pd.to_numeric(X[c], errors="coerce").fillna(0.0) + return X + +def _load_artifact(model_file) -> Dict[str, Any]: + art = joblib.load(model_file) + for k in ["model","scaler","final_feature_names","pre_selection_feature_names"]: + if k not in art: + raise ValueError(f"Model artifact is missing '{k}'.") + return art + +def _transform_like_training(art: Dict[str, Any], X_raw: pd.DataFrame) -> pd.DataFrame: + # 1) align to pre-selection space + X_pre = X_raw.reindex(columns=art["pre_selection_feature_names"], fill_value=0.0) + # 2) scale with training scaler + X_scaled = art["scaler"].transform(X_pre) + X_scaled = pd.DataFrame(X_scaled, columns=art["pre_selection_feature_names"]).astype(np.float32) + # 3) feature selection + if art.get("selector") is not None: + X_sel_arr = art["selector"].transform(X_scaled) + X_sel = pd.DataFrame(X_sel_arr, columns=art["final_feature_names"]) + else: + X_sel = X_scaled[art["final_feature_names"]] + return X_sel + +def run_inference(model_file, test_file) -> Tuple[np.ndarray, Dict[str, Any]]: + """Unlabeled data → predictions.""" + art = _load_artifact(model_file) + df = _read_txt_like(test_file) + X = _align_numeric(df) + X_sel = _transform_like_training(art, X) + preds = art["model"].predict(X_sel) + meta = { + "scaler_type": art.get("scaler_type"), + "feature_method": art.get("feature_method"), + "k": art.get("k"), + "ensemble_type": art.get("ensemble_type"), + "base_models": art.get("base_models"), + "meta_learner": art.get("meta_learner"), + "voting_type": art.get("voting_type"), + "balancing_method": art.get("balancing_method"), + "augmentation": art.get("augmentation"), + } + return preds, meta + +def evaluate(model_file, labeled_test_file) -> Tuple[Dict[str, Any], np.ndarray, Dict[str, Any]]: + """ + Labeled data with a 'healthy' column → metrics + predictions. + """ + art = _load_artifact(model_file) + df = _read_txt_like(labeled_test_file) + if "healthy" not in df.columns: + raise ValueError("Evaluation requires a 'healthy' column in the uploaded file.") + y_true = df["healthy"].astype(int).values + X = _align_numeric(df) + X_sel = _transform_like_training(art, X) + model = art["model"] + + y_pred = model.predict(X_sel) + + # Probabilities for AUC if available + auc = None + if hasattr(model, "predict_proba"): + try: + y_prob = model.predict_proba(X_sel)[:, 1] + auc = roc_auc_score(y_true, y_prob) + except ValueError: + auc = None + + acc = accuracy_score(y_true, y_pred) + f1 = f1_score(y_true, y_pred) + cm = confusion_matrix(y_true, y_pred).tolist() + + metrics = {"accuracy": acc, "f1": f1, "auc": auc, "confusion_matrix": cm} + meta = { + "scaler_type": art.get("scaler_type"), + "feature_method": art.get("feature_method"), + "k": art.get("k"), + "ensemble_type": art.get("ensemble_type"), + "base_models": art.get("base_models"), + "meta_learner": art.get("meta_learner"), + "voting_type": art.get("voting_type"), + "balancing_method": art.get("balancing_method"), + "augmentation": art.get("augmentation"), + } + return metrics, y_pred, meta + +def auto_test(model_file, test_file) -> Dict[str, Any]: + """ + Convenience: if file has 'healthy', run evaluate(); otherwise run_inference(). + Views can call only this and stay skinny. + """ + # We need to read once to detect label, then rewind for the actual loader. + # Duplicate the file object using bytes to reuse: + raw = test_file.read() + buf1 = io.BytesIO(raw) + buf2 = io.BytesIO(raw) + + df_probe = _read_txt_like(buf1) + if "healthy" in df_probe.columns: + metrics, preds, meta = evaluate(model_file, buf2) + return {"metrics": metrics, "preds": preds, "meta": meta, "labeled": True} + else: + preds, meta = run_inference(model_file, buf2) + return {"metrics": None, "preds": preds, "meta": meta, "labeled": False} diff --git a/webapp/services/training.py b/webapp/services/training.py new file mode 100644 index 0000000000000000000000000000000000000000..4fc9a5f09f105174da36b44988220579d344468a --- /dev/null +++ b/webapp/services/training.py @@ -0,0 +1,940 @@ +# webapp/services/training.py +from __future__ import annotations +import copy +import os +import uuid +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Tuple +import joblib +import matplotlib +import matplotlib.pyplot as plt +import numpy as np +import re +import pandas as pd +from typing import Callable +from django.conf import settings +from sklearn.base import clone +from sklearn.compose import ColumnTransformer +from sklearn.ensemble import ( + GradientBoostingClassifier, + RandomForestClassifier, + StackingClassifier, + VotingClassifier, +) +from sklearn.feature_selection import RFECV, SelectKBest, mutual_info_classif +from sklearn.inspection import permutation_importance +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import f1_score, roc_auc_score +from sklearn.model_selection import GridSearchCV, train_test_split +from sklearn.neighbors import KNeighborsClassifier +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import MinMaxScaler, OneHotEncoder, StandardScaler +from sklearn.svm import SVC + +# ------------------------------------------------------------------------------ +# Optional dependencies (best-effort; gracefully degrade if missing) +# ------------------------------------------------------------------------------ +try: + from xgboost import XGBClassifier + _XGB_OK = True +except Exception: + _XGB_OK = False + +try: + # Try (ctgan >= 0.6) + from ctgan import CTGAN as _CTGANClass + _CTGAN_OK = True +except Exception: + try: + # Fallback for very old ctgan (< 0.6) + from ctgan import CTGANSynthesizer as _CTGANClass + _CTGAN_OK = True + except Exception: + _CTGAN_OK = False + + +try: + import shap + _SHAP_OK = True +except Exception: + _SHAP_OK = False + +try: + from scikeras.wrappers import KerasClassifier + import tensorflow as tf + from tensorflow.keras import Input + from tensorflow.keras.layers import Dense, Dropout + from tensorflow.keras.models import Sequential + from tensorflow.keras.optimizers import Adam + _MLP_OK = True +except Exception: + _MLP_OK = False + +# Matplotlib backend for headless servers +matplotlib.use("Agg") + +# ------------------------------------------------------------------------------ +# Data structures +# ------------------------------------------------------------------------------ +@dataclass +class TrainOptions: + scaler: str # 'standard' | 'minmax' + base_models: List[str] # e.g. ['rf','svm',...] + ensemble_type: str # 'none' | 'voting' | 'stacking' + meta_learner: Optional[str] = None # 'lr' | 'rf' | 'gb' (for stacking) + voting_type: Optional[str] = None # 'hard' | 'soft' (for voting) + balancing: str = "none" # 'none' | 'over' | 'smote' | 'gans' + augmentation: str = "none" # 'none' | 'gans' + target_samples: Optional[int] = None # for augmentation == 'gans' + random_state: int = 42 + test_size: float = 0.2 + val_size: float = 0.25 + + +@dataclass +class TrainResult: + val_auc: Optional[float] + val_f1: float + test_auc: Optional[float] + test_f1: float + summary: Dict[str, Any] + model_path: Optional[str] + artifact: Dict[str, Any] + shap_relpath: Optional[str] = None # (may point to SHAP or permutation plot) + +# ------------------------------------------------------------------------------ +# Model registry & small helpers +# ------------------------------------------------------------------------------ + +# --- JSON-safe helpers (put after imports) --- +# --- JSON-safe helpers --- +def _to_py_scalar(x): + if isinstance(x, (np.integer,)): + return int(x) + if isinstance(x, (np.floating,)): + return float(x) + if isinstance(x, (np.bool_,)): + return bool(x) + if isinstance(x, (np.ndarray,)): + return x.tolist() + if isinstance(x, (pd.Series,)): + return x.astype(object).where(~x.isna(), None).tolist() + if isinstance(x, (pd.DataFrame,)): + return x.to_dict(orient="list") + return x + +def _json_safe(obj): + # recursively convert to JSON-serializable Python types + if isinstance(obj, dict): + return {str(k): _json_safe(v) for k, v in obj.items()} + if isinstance(obj, (list, tuple, set)): + return [_json_safe(v) for v in obj] + return _to_py_scalar(obj) + + +def _balance_training_raw( + X_train_raw: pd.DataFrame, + y_train: pd.Series, + balancing_mode: str, # 'none' | 'over' | 'smote' | 'gans' + augmentation_mode: str, # 'none' | 'gans' + categorical_cols: List[str], + target_samples: Optional[int], + random_state: int, + progress_fn: Optional[Callable[[float, str], None]] = None, +) -> Tuple[pd.DataFrame, pd.Series]: + """ + Modify ONLY THE TRAINING SPLIT, in RAW space (pre-scaling, pre-encoding). + + Steps: + 1. balance (if requested) + 2. then augment (if requested) + + Returns new (X_train_raw_balanced_augmented, y_train_balanced_augmented). + """ + + Xb = X_train_raw.reset_index(drop=True).copy() + yb = y_train.reset_index(drop=True).astype(int) + + # let the UI know we entered balancing + if progress_fn: + progress_fn(15, "Balancing training split...") + + # --- 1. BALANCING ------------------------------------------------- + if balancing_mode == 'none': + if progress_fn: + progress_fn(16, "No class balancing requested.") + + elif balancing_mode == 'over': + if progress_fn: + progress_fn(16, "Applying random oversampling...") + # bootstrap minority class to match majority + train_df = Xb.copy() + train_df['__y__'] = yb.values + counts = train_df['__y__'].value_counts() + if len(counts) >= 2: + maj_class = counts.idxmax() + maj_df = train_df[train_df['__y__'] == maj_class] + min_df = train_df[train_df['__y__'] != maj_class] + + if len(min_df) > 0 and len(maj_df) > 0: + from sklearn.utils import resample + min_up = resample( + min_df, + replace=True, + n_samples=len(maj_df), + random_state=random_state, + ) + up_df = pd.concat([maj_df, min_up]).sample( + frac=1, random_state=random_state + ) + yb = up_df['__y__'].astype(int).reset_index(drop=True) + Xb = up_df.drop(columns=['__y__']).reset_index(drop=True) + + elif balancing_mode == 'smote': + if progress_fn: + progress_fn(16, "Running SMOTE...") + # figure out categorical col indices + cat_idx = [Xb.columns.get_loc(c) for c in categorical_cols if c in Xb.columns] + + if len(cat_idx) == 0: + # all features are numeric -> use regular SMOTE + from imblearn.over_sampling import SMOTE + sm = SMOTE(random_state=random_state) + else: + from imblearn.over_sampling import SMOTENC + sm = SMOTENC( + categorical_features=cat_idx, + random_state=random_state, + ) + + X_res, y_res = sm.fit_resample(Xb, yb) + + Xb = pd.DataFrame(X_res, columns=Xb.columns).reset_index(drop=True) + yb = pd.Series(y_res, name=yb.name).astype(int).reset_index(drop=True) + + elif balancing_mode == 'gans': + if progress_fn: + progress_fn(16, "Training CTGAN to balance minority class...") + # CTGAN upsample minority class to match majority + Xb, yb = _apply_ctgan_on_raw( + X_train_raw=Xb, + y_train=yb, + categorical_cols=categorical_cols, + do_balance=True, # <-- balance minority up to majority + do_augment=False, # <-- NOT doing bulk growth yet + target_samples=None, + random_state=random_state, + ) + + else: + raise ValueError(f"Unknown balancing mode: {balancing_mode}") + + if progress_fn: + progress_fn(17, "Balancing complete.") + + # --- 2. AUGMENTATION ---------------------------------------------- + # still ONLY training data, just making more rows if requested + if augmentation_mode == 'gans': + if progress_fn: + progress_fn(18, "Generating extra synthetic samples (augmentation)...") + + Xb, yb = _apply_ctgan_on_raw( + X_train_raw=Xb, + y_train=yb, + categorical_cols=categorical_cols, + do_balance=False, # don't rebalance again + do_augment=True, # add extra synthetic samples + target_samples=target_samples, + random_state=random_state, + ) + + if progress_fn: + progress_fn(18, "Augmentation complete.") + + elif augmentation_mode == 'none': + if progress_fn: + progress_fn(19.0, "No augmentation requested.") + pass + else: + raise ValueError(f"Unknown augmentation mode: {augmentation_mode}") + + return ( + Xb.reset_index(drop=True), + yb.reset_index(drop=True).astype(int), + ) + + +def _create_mlp(input_dim: int, dropout_rate: float = 0.2, learning_rate: float = 0.001): + model = Sequential() + model.add(Input(shape=(input_dim,))) + model.add(Dense(128, activation='relu')) + model.add(Dropout(dropout_rate)) + model.add(Dense(64, activation='relu')) + model.add(Dropout(dropout_rate)) + model.add(Dense(1, activation='sigmoid')) + model.compile( + optimizer=Adam(learning_rate=learning_rate), + loss='binary_crossentropy', + metrics=[tf.keras.metrics.AUC(name='auc')] + ) + return model + + + +def _pretty_feature_names(names: List[str]) -> List[str]: + out = [] + for n in names: + s = str(n) + # drop ColumnTransformer prefixes like "num__", "num_", "cat__", "cat_" + s = re.sub(r'^(num|cat)_{1,2}', '', s) + # keep it tidy + out.append(s if len(s) <= 40 else s[:37] + '…') + return out + + + +def _stratify_or_none(y: pd.Series): + vc = y.value_counts(dropna=False) + return y if (len(vc) >= 2 and vc.min() >= 2) else None + + +def _get_base_model(key: str, input_dim: Optional[int] = None): + if key == 'rf': + return RandomForestClassifier() + if key == 'svm': + return SVC(probability=True) + if key == 'knn': + return KNeighborsClassifier() + if key == 'lr': + return LogisticRegression(max_iter=10_000) + if key == 'gb': + return GradientBoostingClassifier() + if key == 'xgb' and _XGB_OK: + return XGBClassifier(eval_metric='logloss') + if key == 'mlp' and _MLP_OK and input_dim is not None: + return KerasClassifier(model=_create_mlp, model__input_dim=input_dim, verbose=0) + return None + + +def _ctgan_sample_raw(df_raw: pd.DataFrame, discrete_cols: List[str], n: int, epochs: int = 300, seed: int = 42) -> pd.DataFrame: + if n <= 0: + return pd.DataFrame(columns=df_raw.columns) + if not _CTGAN_OK: + raise RuntimeError("CTGAN requested but the 'ctgan' package is not installed.") + + synth = _CTGANClass(epochs=epochs, verbose=False) + synth.fit(df_raw, discrete_columns=discrete_cols) + out = synth.sample(n) + return out.reset_index(drop=True) + + +def _apply_ctgan_on_raw( + X_train_raw: pd.DataFrame, + y_train: pd.Series, + categorical_cols: List[str], + do_balance: bool, + do_augment: bool, + target_samples: Optional[int], + random_state: int, +) -> Tuple[pd.DataFrame, pd.Series]: + """ + Mirror the script: balance minority to majority on RAW columns (with categoricals), + then optionally augment to target_samples. Returns new (X_raw, y). + """ + train_df = X_train_raw.copy() + train_df['__y__'] = y_train.values.astype(int) + + # Balance + if do_balance: + vc = train_df['__y__'].value_counts() + if len(vc) >= 2: + minority = int(vc.idxmin()) + majority_n = int(vc.max()) + need = majority_n - int((train_df['__y__'] == minority).sum()) + if need > 0: + minority_df = train_df[train_df['__y__'] == minority].reset_index(drop=True) + synth = _ctgan_sample_raw( + minority_df, + discrete_cols=categorical_cols + ['__y__'], + n=need, + epochs=300, + seed=random_state, + ) + train_df = pd.concat([train_df, synth], ignore_index=True) + + # Augment + if do_augment and target_samples is not None and target_samples > len(train_df): + need_total = int(target_samples - len(train_df)) + vc = train_df['__y__'].value_counts() + ratio = vc / vc.sum() + alloc = {int(cls): int(round(need_total * p)) for cls, p in ratio.items()} + diff = need_total - sum(alloc.values()) + if diff: + alloc[int(vc.idxmax())] = alloc.get(int(vc.idxmax()), 0) + diff + + # Fit once on the current (balanced) RAW table and sample in batches + # (simple approach: sample, then filter by class) + parts = [train_df] + for cls, n_add in alloc.items(): + if n_add <= 0: + continue + got = pd.DataFrame() + tries = 0 + while len(got) < n_add and tries < 5: + batch = _ctgan_sample_raw( + train_df, discrete_cols=categorical_cols + ['__y__'], + n=max(n_add * 2, 200), epochs=300, seed=random_state + tries + ) + batch = batch[batch['__y__'] == cls] + got = pd.concat([got, batch], ignore_index=True).head(n_add) + tries += 1 + if len(got) < n_add: + # fallback: unconditional sample (keep whatever class proportion arrives) + got = _ctgan_sample_raw( + train_df, discrete_cols=categorical_cols + ['__y__'], + n=n_add, epochs=300, seed=random_state + 99 + ) + # best-effort: trim/keep to n_add + got = got.head(n_add) + parts.append(got) + train_df = pd.concat(parts, ignore_index=True) + + y_out = train_df['__y__'].astype(int).reset_index(drop=True) + X_out = train_df.drop(columns=['__y__']).reset_index(drop=True) + return X_out, y_out + + +def _param_grid(key: str, input_dim: Optional[int] = None) -> Dict[str, List[Any]]: + grids = { + 'rf': { 'n_estimators': [100, 200, 300], 'max_depth': [None, 10, 20, 30],'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4],'bootstrap': [True, False] }, + 'svm': {'C': [0.1, 1, 10, 100], 'kernel': ['linear', 'rbf', 'poly'], 'gamma': ['scale', 'auto'], 'degree': [3, 4, 5]}, + 'knn': {'n_neighbors': [3, 5, 7, 11], 'weights': ['uniform', 'distance'], 'metric': ['euclidean', 'manhattan'] }, + 'lr': {'C': [0.01, 0.1, 1, 10, 100],'penalty': ['l1', 'l2'],'solver': ['liblinear', 'saga'],'max_iter': [100, 500, 1000]}, + 'gb': {'n_estimators': [100, 200],'learning_rate': [0.01, 0.1, 0.2],'max_depth': [3, 5, 7],'subsample': [0.8, 1.0],'min_samples_split': [2, 5],'min_samples_leaf': [1, 2]}, + 'xgb': {'n_estimators': [100, 200],'learning_rate': [0.01, 0.1, 0.2],'max_depth': [3, 5, 7],'subsample': [0.8, 1.0],'colsample_bytree': [0.6, 0.8, 1.0],'gamma': [0, 0.1, 0.2]}, + 'mlp': {'model__hidden_layers': [[64],[128, 64],[128, 64, 32]],'model__dropout_rate': [0.2, 0.3],'model__learning_rate': [0.001, 0.0005],'epochs': [30, 50],'batch_size': [16, 32]} +} + if key == 'mlp' and _MLP_OK and input_dim is not None: + return { + 'model__input_dim': [input_dim], + 'model__dropout_rate': [0.2, 0.3], + 'model__learning_rate': [0.001, 0.0005], + 'epochs': [25, 40], + 'batch_size': [16, 32], + } + return grids.get(key, {}) + + +def _get_meta_learner(key: str): + if key == 'lr': + return LogisticRegression(max_iter=10_000) + if key == 'rf': + return RandomForestClassifier() + if key == 'gb': + return GradientBoostingClassifier() + return LogisticRegression(max_iter=10_000) + + +def _score_auc_f1(estimator, X: pd.DataFrame, y: pd.Series) -> Tuple[Optional[float], float]: + """Uniform scoring helper that returns plain-Python floats (JSON-safe).""" + y_pred = estimator.predict(X) + f1 = float(f1_score(y, y_pred)) + auc = None + if hasattr(estimator, "predict_proba"): + try: + auc = float(roc_auc_score(y, estimator.predict_proba(X)[:, 1])) + except ValueError: + auc = None + return auc, f1 + +# ------------------------------------------------------------------------------ +# Explainability plots +# ------------------------------------------------------------------------------ +def _make_shap_plot_if_possible( + model, X_bg: pd.DataFrame, X_eval: pd.DataFrame, feature_names: List[str], run_id: str +) -> Optional[str]: + """Return MEDIA-relative path to SHAP bar summary, or None on failure.""" + if not _SHAP_OK: + return None + + bg = X_bg.sample(min(50, len(X_bg)), random_state=0).reset_index(drop=True) + ev = X_eval.sample(min(200, len(X_eval)), random_state=1).reset_index(drop=True) + + try: + explainer = shap.Explainer(model, bg) + sv = explainer(ev) + shap.summary_plot(sv, features=ev, feature_names=feature_names, plot_type="bar", show=False) + except Exception: + try: + def _f(X): + Xdf = pd.DataFrame(X, columns=feature_names) + if hasattr(model, "predict_proba"): + return model.predict_proba(Xdf)[:, 1] + return model.predict(Xdf) + + kexp = shap.KernelExplainer(_f, bg) + sv = kexp.shap_values(ev, nsamples=100) + shap.summary_plot(sv, ev, feature_names=feature_names, plot_type="bar", show=False) + except Exception: + try: + plt.close() + except Exception: + pass + return None + + plt.tight_layout() + rel_dir = os.path.join("train_runs") + abs_dir = os.path.join(settings.MEDIA_ROOT, rel_dir) + os.makedirs(abs_dir, exist_ok=True) + rel_path = os.path.join(rel_dir, f"{run_id}_shap.svg") # needs to be SVG to then be responsive + plt.gcf().set_size_inches(8, 5) + plt.savefig(os.path.join(abs_dir, f"{run_id}_shap.svg"),format="svg", bbox_inches="tight") # ← SVG export + plt.close() + return rel_path + + +def _make_perm_plot_if_possible( + model, X_eval: pd.DataFrame, y_eval: pd.Series, feature_names: List[str], run_id: str +) -> Optional[str]: + """Return MEDIA-relative path to permutation-importance plot, or None on failure.""" + try: + res = permutation_importance(model, X_eval, y_eval, n_repeats=10, random_state=0, scoring="roc_auc") + names = feature_names if feature_names and len(feature_names) == X_eval.shape[1] else list(X_eval.columns) + names = _pretty_feature_names(names) + imps = pd.Series(res.importances_mean, index=names).fillna(0.0) + + top = imps.sort_values().tail(25) + plt.figure(figsize=(12, 6), dpi=140) + colors = ['tab:red' if v < 0 else 'tab:green' for v in top.values] + plt.barh(top.index, top.values, color=colors, alpha=0.9) + plt.axvline(0, linestyle='--', linewidth=1, alpha=0.6) + plt.title("Permutation importance (validation)") + plt.xlabel("Mean change in ROC AUC when permuted") + plt.tight_layout() + + rel_dir = os.path.join("train_runs") + abs_dir = os.path.join(settings.MEDIA_ROOT, rel_dir) + os.makedirs(abs_dir, exist_ok=True) + rel_path = os.path.join(rel_dir, f"{run_id}_perm.svg") + plt.savefig(os.path.join(abs_dir, f"{run_id}_perm.svg"), format="svg", bbox_inches="tight") + plt.close() + return rel_path + except Exception: + try: + plt.close() + except Exception: + pass + return None + +# ------------------------------------------------------------------------------ +# Feature selection helpers +# ------------------------------------------------------------------------------ +def _rfecv_k_per_base(X_train_proc: pd.DataFrame, y_train: pd.Series) -> Tuple[Dict[str, int], Dict[str, RFECV]]: + """Run RFECV with a few base estimators to infer a sensible k (cap at 20).""" + bases = { + 'lr': LogisticRegression(max_iter=10_000), + 'rf': RandomForestClassifier(), + 'svm': SVC(kernel='linear', probability=True), + } + k_map, model_map = {}, {} + for name, est in bases.items(): + rfecv = RFECV(estimator=est, step=1, cv=3, scoring='roc_auc', n_jobs=-1) + rfecv.fit(X_train_proc, y_train) + k = min(20, getattr(rfecv, "n_features_", X_train_proc.shape[1])) + k_map[name] = k + model_map[name] = rfecv + return k_map, model_map + + +def _select_features( + method: str, + X_train_proc: pd.DataFrame, + y_train: pd.Series, + X_val_proc: pd.DataFrame, + k: int, + rfecv_model: Optional[RFECV] = None +) -> Tuple[pd.DataFrame, pd.DataFrame, Optional[SelectKBest], List[str]]: + """ + Returns train/val reduced, optional selector object (only for kbest), and feature names. + """ + selector_obj = None + if method == 'rfe': + ranking = rfecv_model.ranking_ + ranks = pd.Series(ranking, index=X_train_proc.columns).sort_values() + feats = list(ranks.index[:k]) + return X_train_proc[feats], X_val_proc[feats], selector_obj, feats + + selector_obj = SelectKBest(score_func=mutual_info_classif, k=k) + selector_obj.fit(X_train_proc, y_train) + scores = pd.Series(selector_obj.scores_, index=X_train_proc.columns).sort_values(ascending=False) + feats = list(scores.index[:k]) + return X_train_proc[feats], X_val_proc[feats], selector_obj, feats + +# ------------------------------------------------------------------------------ +# Public entry point +# ------------------------------------------------------------------------------ +def train_dataset( + file_obj, + opts: TrainOptions, + save_to: Optional[str] = None, + progress_cb: Optional[Callable[[float, str], None]] = None, # <— NEW +) -> TrainResult: + def _emit(pct: float, msg: str): + if progress_cb: + try: + progress_cb(float(pct), str(msg)) + except Exception: + pass + + # --- sanitize target_samples (form can send '') --- + if isinstance(opts.target_samples, str): + target_samples = int(opts.target_samples) if opts.target_samples.strip() else None + else: + target_samples = opts.target_samples + + + # ---- Load & sanitize + _emit(1, "Reading CSV...") + df = pd.read_csv(file_obj) + if 'healthy' not in df.columns: + raise ValueError("CSV must include a 'healthy' column (0/1).") + + drop_cols = [c for c in ['sample_id', 'id'] if c in df.columns] + if drop_cols: + df = df.drop(columns=drop_cols) + + # coerce object columns that look numeric + for c in df.columns: + if df[c].dtype == object: + coerced = pd.to_numeric(df[c], errors='coerce') + if coerced.notna().sum() > 0: + df[c] = coerced + + + df = df.dropna(axis=0, how='any').reset_index(drop=True) + + raw_feature_cols = [c for c in df.columns if c != 'healthy'] + X = df[raw_feature_cols].copy() + y = df['healthy'].astype(int) + + + # ---- Split (fit preprocessors on TRAIN only) + _emit(8, "Splitting train/val/test...") + X_dev, X_test, y_dev, y_test = train_test_split( + X, y, test_size=opts.test_size, stratify=_stratify_or_none(y), random_state=opts.random_state + ) + X_train_raw, X_val_raw, y_train, y_val = train_test_split( + X_dev, y_dev, test_size=opts.val_size, stratify=_stratify_or_none(y_dev), random_state=opts.random_state + ) + + # ---- Identify numeric vs categorical on TRAIN RAW (before balancing) ---- + numeric_cols = X_train_raw.select_dtypes(include=[np.number, bool]).columns.tolist() + categorical_cols = X_train_raw.columns.difference(numeric_cols).tolist() + + _emit(15, "Balancing / augmentation on training split...") + + X_train_raw, y_train = _balance_training_raw( + X_train_raw=X_train_raw, + y_train=y_train, + balancing_mode=opts.balancing, + augmentation_mode=opts.augmentation, + categorical_cols=categorical_cols, + target_samples=target_samples, + random_state=opts.random_state, + progress_fn=_emit, + ) + + num_pipe = Pipeline(steps=[ + ('scale', StandardScaler() if opts.scaler == 'standard' else MinMaxScaler()), + ]) + + + try: + ohe = OneHotEncoder(handle_unknown='ignore', sparse_output=False) + except TypeError: + ohe = OneHotEncoder(handle_unknown='ignore', sparse=False) + + cat_pipe = Pipeline(steps=[ + ('ohe', ohe), + ]) + + preprocessor = ColumnTransformer( + transformers=[ + ('num', num_pipe, numeric_cols), + ('cat', cat_pipe, categorical_cols), + ], + remainder='drop' + ) + + _emit(25, "Fitting preprocessors...") + preprocessor.fit(X_train_raw) + + def _to_df(arr): + names = preprocessor.get_feature_names_out().tolist() + return pd.DataFrame(arr, columns=names).astype(np.float32) + + X_train_proc = _to_df(preprocessor.transform(X_train_raw)) + X_val_proc = _to_df(preprocessor.transform(X_val_raw)) + X_test_proc = _to_df(preprocessor.transform(X_test)) + + # Ensure labels align with 0..n-1 indices produced by transform() + y_train = y_train.reset_index(drop=True) + y_val = y_val.reset_index(drop=True) + y_test = y_test.reset_index(drop=True) + + # keep tidy indices after any resampling + X_train_proc = X_train_proc.reset_index(drop=True) + y_train = y_train.reset_index(drop=True).astype(int) + + # ---- Feature selection candidates + _emit(35, "Running RFECV...") + k_map, rfecv_map = _rfecv_k_per_base(X_train_proc, y_train) # k cap at 20 per base + selection_methods = ['rfe', 'kbest'] + done_slices = 0 + total_slices = max(1, len(selection_methods) * len(k_map)) + + # if multiple base models but 'none' ensemble, nudge to stacking + ensemble_type = 'stacking' if (len(opts.base_models) >= 2 and opts.ensemble_type == 'none') else opts.ensemble_type + + best_val_key = None + best_val_metrics = (-1.0, -1.0) # (auc, f1) + best_pack: Dict[str, Any] = {} + + for method in selection_methods: + for k_base_name, k in k_map.items(): + done_slices += 1 + _emit(35 + 45 * (done_slices - 1) / total_slices, f"Training {method} / {k_base_name} (k={k})...") + Xtr_sel, Xv_sel, selector_obj, feats = _select_features( + method, X_train_proc, y_train, X_val_proc, k, rfecv_map.get(k_base_name) + ) + + # Instantiate requested base models + chosen_models = [] + for key in opts.base_models: + mdl = _get_base_model(key, input_dim=Xtr_sel.shape[1]) + if mdl is not None: + chosen_models.append((key, mdl)) + + # Hyperparam tune or fit directly + best_estimators: Dict[str, Any] = {} + for key, mdl in chosen_models: + grid_params = copy.deepcopy(_param_grid(key, input_dim=Xtr_sel.shape[1])) + if grid_params: + gs = GridSearchCV(mdl, grid_params, cv=3, scoring='roc_auc', n_jobs=-1) + gs.fit(Xtr_sel, y_train) + best_est = gs.best_estimator_ + else: + mdl.fit(Xtr_sel, y_train) + best_est = mdl + best_estimators[key] = best_est + + if len(best_estimators) == 0: + continue + + # Build final model for this feature slice + if len(best_estimators) == 1 or ensemble_type == 'none': + # choose best single model by (AUC, F1) on VAL + auc_f1_list = [] + for key, est in best_estimators.items(): + auc, f1 = _score_auc_f1(est, Xv_sel, y_val) + auc_f1_list.append((auc if auc is not None else -1, f1, key, est)) + auc_f1_list.sort(reverse=True) + _, _, label, final_model = auc_f1_list[0] + + elif ensemble_type == 'voting': + voting = opts.voting_type or 'hard' + final_model = VotingClassifier(estimators=list(best_estimators.items()), voting=voting) + final_model.fit(Xtr_sel, y_train) + label = f"Voting({voting})" + + else: # 'stacking' + meta = _get_meta_learner(opts.meta_learner or 'lr') + final_model = StackingClassifier( + estimators=list(best_estimators.items()), + final_estimator=clone(meta), + passthrough=True, cv=3, n_jobs=-1 + ) + final_model.fit(Xtr_sel, y_train) + label = f"Stacking({opts.meta_learner or 'lr'})" + + # Validate + val_auc, val_f1 = _score_auc_f1(final_model, Xv_sel, y_val) + key_tuple = (val_auc if val_auc is not None else -1, val_f1) + + if key_tuple > best_val_metrics: + best_val_metrics = key_tuple + best_val_key = (method, k_base_name, k, label) + best_pack = { + "model": final_model, + "selector": selector_obj if method == 'kbest' else None, + "final_features": feats, + "pre_features": list(X_train_proc.columns), + "preprocessor": preprocessor, + "scaler_type": opts.scaler, + "feature_method": method, + "k_from": k_base_name, + "k": k, + "ensemble": ensemble_type, + "base_models": list(best_estimators.keys()), + "meta_learner": (opts.meta_learner if ensemble_type == "stacking" else None), + "voting_type": (opts.voting_type if ensemble_type == "voting" else None), + "balancing": opts.balancing, + "augmentation": opts.augmentation, + } + + if not best_pack: + raise RuntimeError("No valid model configuration could be trained.") + + # ---- Test once on held-out + if best_pack["selector"] is not None: + X_test_aligned = X_test_proc.reindex(columns=best_pack["pre_features"], fill_value=0.0) + Xte_sel_arr = best_pack["selector"].transform(X_test_aligned) + Xte_sel = pd.DataFrame(Xte_sel_arr, columns=best_pack["final_features"]) + else: + Xte_sel = X_test_proc[best_pack["final_features"]] + + _emit(85, "Testing on hold-out...") + test_auc, test_f1 = _score_auc_f1(best_pack["model"], Xte_sel, y_test) + val_auc, val_f1 = best_val_metrics + + # Plain-Python scalars for anything we might serialize/store + val_auc_py = None if (val_auc is None or val_auc < 0) else float(val_auc) + val_f1_py = float(val_f1) + test_auc_py = None if test_auc is None else float(test_auc) + test_f1_py = float(test_f1) + + # best_val_key = (method, k_base_name, k, label) + selection_py = None + if best_val_key is not None: + selection_py = [ + None if best_val_key[0] is None else str(best_val_key[0]), + None if best_val_key[1] is None else str(best_val_key[1]), + None if best_val_key[2] is None else int(best_val_key[2]), + None if best_val_key[3] is None else str(best_val_key[3]), + ] + + + # ---- Explainability (best-effort) + run_id = uuid.uuid4().hex + + if best_pack["selector"] is not None: + X_train_aligned = X_train_proc.reindex(columns=best_pack["pre_features"], fill_value=0.0) + X_val_aligned = X_val_proc.reindex(columns=best_pack["pre_features"], fill_value=0.0) + Xtr_sel_final = pd.DataFrame(best_pack["selector"].transform(X_train_aligned), columns=best_pack["final_features"]) + Xv_sel_final = pd.DataFrame(best_pack["selector"].transform(X_val_aligned), columns=best_pack["final_features"]) + else: + Xtr_sel_final = X_train_proc[best_pack["final_features"]] + Xv_sel_final = X_val_proc[best_pack["final_features"]] + + explain_relpath = None + explain_type = None + feature_importances = None + pretty_names = _pretty_feature_names(best_pack["final_features"]) + + + _emit(90, "Building explainability plot...") + shap_relpath = _make_shap_plot_if_possible( + model=best_pack["model"], X_bg=Xtr_sel_final, X_eval=Xv_sel_final, + feature_names=pretty_names, run_id=run_id, + ) + if shap_relpath: + explain_relpath = shap_relpath + explain_type = "shap" + + # Also compute mean absolute SHAP values (top features) to store in summary + try: + import shap + explainer = shap.Explainer(best_pack["model"], Xtr_sel_final) + sv = explainer(Xv_sel_final) + vals = np.abs(sv.values).mean(0) + feature_importances = [(str(f), float(v)) for f, v in zip(pretty_names, vals)] + + except Exception: + feature_importances = None + + else: + perm_relpath = _make_perm_plot_if_possible( + model=best_pack["model"], X_eval=Xv_sel_final, y_eval=y_val, + feature_names=pretty_names, run_id=run_id, + ) + + if perm_relpath: + explain_relpath = perm_relpath + explain_type = "permutation" + + # Also compute permutation importances numerically for the summary + try: + res_pi = permutation_importance( + best_pack["model"], Xv_sel_final, y_val, + n_repeats=10, random_state=0, scoring="roc_auc" + ) + feature_importances = [(str(f), float(s)) for f, s in zip(pretty_names, res_pi.importances_mean)] + + + except Exception: + feature_importances = None + + + artifact = { + "model": best_pack["model"], + "selector": best_pack["selector"], + "preprocessor": best_pack["preprocessor"], + "pre_selection_feature_names": best_pack["pre_features"], + "final_feature_names": best_pack["final_features"], + "feature_method": best_pack["feature_method"], + "k_from": best_pack["k_from"], + "k": int(best_pack["k"]), # ensure plain int + "shap_relpath": shap_relpath, + "scaler_type": best_pack["scaler_type"], + "ensemble_type": best_pack["ensemble"], + "base_models": best_pack["base_models"], + "meta_learner": best_pack["meta_learner"], + "voting_type": best_pack["voting_type"], + "balancing_method": best_pack["balancing"], + "augmentation": best_pack["augmentation"], + "explain_relpath": explain_relpath, + "explain_type": explain_type, + "target_samples": target_samples, + "val_auc": val_auc_py, + "val_f1": val_f1_py, + "test_auc": test_auc_py, + "test_f1": test_f1_py,} + + summary_raw = { + "selection": selection_py, # list not tuple, already py types + "ensemble": artifact["ensemble_type"], + "base_models": artifact["base_models"], + "meta_learner": artifact["meta_learner"], + "voting_type": artifact["voting_type"], + "balancing": artifact["balancing_method"], + "augmentation": artifact["augmentation"], + "scaler": artifact["scaler_type"], + "explain_type": explain_type, + "target_samples": artifact["target_samples"], + "k": int(best_pack["k"]), + "k_from": best_pack["k_from"], + "feature_method": best_pack["feature_method"], + # NEW: numeric importances so results_view/_extract_top_taxa can build NCBI links + "permutation_importance": feature_importances if explain_type == "permutation" else None, + "shap_importance": feature_importances if explain_type == "shap" else None, + } + + summary_py = _json_safe(summary_raw) + + + saved = None + if save_to: + joblib.dump(artifact, save_to) + saved = save_to + + _emit(100, "Done") + return TrainResult( + val_auc=val_auc_py, + val_f1=val_f1_py, + test_auc=test_auc_py, + test_f1=test_f1_py, + shap_relpath=explain_relpath, + summary=summary_py, + model_path=saved, + artifact=artifact, +) \ No newline at end of file diff --git a/webapp/templates/base.html b/webapp/templates/base.html new file mode 100644 index 0000000000000000000000000000000000000000..f6d6e6f80ccd31c48a968155fd034a053159dd75 --- /dev/null +++ b/webapp/templates/base.html @@ -0,0 +1,43 @@ + +{% load static %} + + +
+ + +What would you like to do today?
++ Don't have an account? Register +
++ Already have an account? Login +
+No chart generated.
+ {% endif %} +