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 %} + + + + + + {% block title %}ML App{% endblock %} + + + + + {% block fullpage %} + {% if user.is_authenticated %} + + {% endif %} + +
+ {% block content %}{% endblock %} +
+ {% endblock %} + + + + + + + + diff --git a/webapp/templates/webapp/landing_page.html b/webapp/templates/webapp/landing_page.html new file mode 100644 index 0000000000000000000000000000000000000000..b5a8d7031610eb81cfcfa3775f3d54b7fcee05ed --- /dev/null +++ b/webapp/templates/webapp/landing_page.html @@ -0,0 +1,397 @@ +{% extends 'base.html' %} + +{% block extra_styles %} + @keyframes float1 { + 0%, 100% { transform: translate(0, 0); } + 50% { transform: translate(100px, 50px); } + } + + @keyframes float2 { + 0%, 100% { transform: translate(0, 0); } + 50% { transform: translate(-80px, -60px); } + } + + @keyframes wave { + 0% { transform: rotate(0deg); } + 10% { transform: rotate(14deg); } + 20% { transform: rotate(-8deg); } + 30% { transform: rotate(14deg); } + 40% { transform: rotate(-4deg); } + 50% { transform: rotate(10deg); } + 60% { transform: rotate(0deg); } + 100% { transform: rotate(0deg); } + } + + @keyframes fadeInUp { + from { + opacity: 0; + transform: translateY(20px); + } + to { + opacity: 1; + transform: translateY(0); + } + } + + @keyframes fadeInScale { + from { + opacity: 0; + transform: scale(0.9); + } + to { + opacity: 1; + transform: scale(1); + } + } + + body { + background: linear-gradient(135deg, #6366f1, #a855f7, #ec4899) !important; + overflow-x: hidden; + min-height: 100vh; + } + + .animated-bg { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + overflow: hidden; + pointer-events: none; + z-index: 0; + } + + .blob { + position: absolute; + border-radius: 50%; + filter: blur(80px); + opacity: 0.3; + } + + .blob-1 { + top: 80px; + left: 80px; + width: 288px; + height: 288px; + background: rgba(255, 255, 255, 0.4); + animation: float1 20s ease-in-out infinite; + } + + .blob-2 { + bottom: 80px; + right: 80px; + width: 384px; + height: 384px; + background: rgba(255, 255, 255, 0.4); + animation: float2 25s ease-in-out infinite; + } + + .header-container { + position: relative; + z-index: 10; + padding: 1rem 2rem; + display: flex; + justify-content: space-between; + align-items: center; + animation: fadeInUp 0.5s ease-out; + } + + .logo-section { + display: flex; + align-items: center; + gap: 0.5rem; + color: white; + } + + .user-section { + display: flex; + align-items: center; + gap: 1rem; + } + + .user-info { + color: rgba(255, 255, 255, 0.9); + font-size: 0.875rem; + } + + .logout-btn { + background: rgba(255, 255, 255, 0.1); + border: 1px solid rgba(255, 255, 255, 0.2); + color: white; + padding: 0.5rem 1rem; + border-radius: 0.375rem; + text-decoration: none; + display: inline-flex; + align-items: center; + gap: 0.5rem; + transition: all 0.3s; + font-size: 0.875rem; + } + + .logout-btn:hover { + background: rgba(255, 255, 255, 0.2); + color: white; + } + + .main-container { + position: relative; + z-index: 10; + display: flex; + align-items: center; + justify-content: center; + min-height: calc(100vh - 80px); + padding: 1rem; + } + + .main-card { + width: 100%; + max-width: 768px; + background: rgba(255, 255, 255, 0.95); + backdrop-filter: blur(10px); + padding: 3rem; + border-radius: 1rem; + box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); + animation: fadeInScale 0.5s ease-out 0.2s both; + } + + .welcome-section { + text-align: center; + margin-bottom: 2rem; + animation: fadeInUp 0.5s ease-out 0.4s both; + } + + .wave-emoji { + font-size: 3rem; + display: inline-block; + animation: wave 2s ease-in-out infinite; + animation-delay: 0.5s; + } + + .welcome-title { + color: #2563eb; + font-size: 2rem; + font-weight: 700; + margin: 1rem 0 0.5rem 0; + } + + .welcome-subtitle { + color: #6b7280; + font-size: 1.25rem; + } + + .action-buttons { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 1rem; + margin: 2rem 0; + animation: fadeInUp 0.5s ease-out 0.6s both; + } + + .action-btn { + position: relative; + overflow: hidden; + padding: 2rem 1.5rem; + border-radius: 0.5rem; + text-decoration: none; + transition: all 0.3s; + display: flex; + flex-direction: column; + align-items: center; + gap: 1rem; + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); + } + + .action-btn:hover { + transform: scale(1.02); + box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.2); + } + + .train-btn { + background: linear-gradient(135deg, #16a34a, #059669); + color: white; + } + + .train-btn::before { + content: ''; + position: absolute; + inset: 0; + background: linear-gradient(135deg, rgba(255,255,255,0), rgba(255,255,255,0.1)); + opacity: 0; + transition: opacity 0.3s; + } + + .train-btn:hover::before { + opacity: 1; + } + + .test-btn { + background: linear-gradient(135deg, #dbeafe, #e0e7ff); + border: 2px solid #2563eb; + color: #1e40af; + } + + .test-btn:hover { + background: linear-gradient(135deg, #bfdbfe, #c7d2fe); + } + + .btn-icon { + width: 48px; + height: 48px; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + font-size: 1.5rem; + } + + .train-btn .btn-icon { + background: rgba(255, 255, 255, 0.2); + } + + .test-btn .btn-icon { + background: #dbeafe; + transition: background 0.3s; + } + + .test-btn:hover .btn-icon { + background: #bfdbfe; + } + + .btn-title { + font-weight: 600; + font-size: 1.125rem; + display: flex; + align-items: center; + gap: 0.5rem; + } + + .btn-subtitle { + font-size: 0.875rem; + opacity: 0.8; + } + + .stats-section { + padding-top: 2rem; + border-top: 1px solid #e5e7eb; + margin-top: 2rem; + animation: fadeInUp 0.5s ease-out 0.8s both; + } + + .stats-grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 1rem; + text-align: center; + } + + .stat-label { + color: #9ca3af; + font-size: 0.875rem; + margin-bottom: 0.25rem; + } + + .stat-value { + color: #111827; + font-size: 1.5rem; + font-weight: 600; + } + + @media (max-width: 768px) { + .action-buttons { + grid-template-columns: 1fr; + } + + .main-card { + padding: 2rem; + } + + .header-container { + flex-direction: column; + gap: 1rem; + } + } +{% endblock %} + +{% block fullpage %} + +
+
+
+
+ + +
+
+ + + + + +

Model Lab

+
+
+ + + + + + + + Logout + +
+
+ + +
+
+ +
+ 👋 +

Welcome, {{ user.username }}!

+

What would you like to do today?

+
+ + + + + +
+
+
+
Active Models
+
{{ active_models_count|default:"0" }}
+
+
+
Total Runs
+
{{ total_runs_count|default:"0" }}
+
+
+
Highest AUC
+
{% if highest_auc %}{{ highest_auc|floatformat:1 }}%{% else %}--{% endif %}
+
+
+
+
+
+{% endblock %} \ No newline at end of file diff --git a/webapp/templates/webapp/login.html b/webapp/templates/webapp/login.html new file mode 100644 index 0000000000000000000000000000000000000000..c4d5afd643ee6c3a782c38827886d68e56fabc65 --- /dev/null +++ b/webapp/templates/webapp/login.html @@ -0,0 +1,296 @@ +{% extends "base.html" %} +{% load static %} + +{% block title %}Login{% endblock %} + +{% block extra_styles %} + @keyframes float1 { + 0%, 100% { transform: translate(0, 0); } + 50% { transform: translate(100px, 50px); } + } + + @keyframes float2 { + 0%, 100% { transform: translate(0, 0); } + 50% { transform: translate(-80px, -60px); } + } + + @keyframes fadeInScale { + from { + opacity: 0; + transform: scale(0.9); + } + to { + opacity: 1; + transform: scale(1); + } + } + + body { + background: linear-gradient(135deg, #667eea, #764ba2) !important; + overflow-x: hidden; + min-height: 100vh; + } + + .animated-bg { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + overflow: hidden; + pointer-events: none; + z-index: 0; + } + + .blob { + position: absolute; + border-radius: 50%; + filter: blur(80px); + opacity: 0.3; + } + + .blob-1 { + top: 80px; + left: 80px; + width: 288px; + height: 288px; + background: rgba(255, 255, 255, 0.4); + animation: float1 20s ease-in-out infinite; + } + + .blob-2 { + bottom: 80px; + right: 80px; + width: 384px; + height: 384px; + background: rgba(255, 255, 255, 0.4); + animation: float2 25s ease-in-out infinite; + } + + .login-container { + position: relative; + z-index: 10; + display: flex; + align-items: center; + justify-content: center; + min-height: 100vh; + padding: 1rem; + } + + .login-card { + width: 100%; + max-width: 420px; + background: rgba(255, 255, 255, 0.98); + backdrop-filter: blur(10px); + padding: 2.5rem; + border-radius: 1rem; + box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); + animation: fadeInScale 0.5s ease-out; + } + + .login-header { + text-align: center; + margin-bottom: 2rem; + } + + .login-emoji { + font-size: 2.5rem; + display: inline-block; + margin-bottom: 0.5rem; + } + + .login-title { + color: #1f2937; + font-size: 1.75rem; + font-weight: 700; + margin: 0; + } + + .form-group { + margin-bottom: 1.25rem; + } + + .form-label { + display: block; + color: #374151; + font-weight: 500; + margin-bottom: 0.5rem; + font-size: 0.875rem; + } + + .form-input { + width: 100%; + padding: 0.75rem 1rem; + border: 2px solid #e5e7eb; + border-radius: 0.5rem; + font-size: 1rem; + transition: all 0.2s; + background: white; + } + + .form-input:focus { + outline: none; + border-color: #667eea; + box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); + } + + .form-input.is-invalid { + border-color: #ef4444; + } + + .form-input.is-invalid:focus { + box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1); + } + + .error-message { + color: #ef4444; + font-size: 0.875rem; + margin-top: 0.5rem; + display: block; + } + + .alert-box { + background: #fee2e2; + border: 1px solid #fca5a5; + color: #991b1b; + padding: 0.75rem 1rem; + border-radius: 0.5rem; + margin-bottom: 1.5rem; + font-size: 0.875rem; + } + + .login-button { + width: 100%; + padding: 0.875rem 1.5rem; + background: linear-gradient(135deg, #667eea, #764ba2); + color: white; + border: none; + border-radius: 0.5rem; + font-size: 1rem; + font-weight: 600; + cursor: pointer; + transition: all 0.3s; + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + margin-top: 0.5rem; + } + + .login-button:hover { + transform: translateY(-2px); + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2); + } + + .login-button:active { + transform: translateY(0); + } + + .register-link-container { + text-align: center; + margin-top: 1.5rem; + padding-top: 1.5rem; + border-top: 1px solid #e5e7eb; + } + + .register-text { + color: #6b7280; + font-size: 0.875rem; + margin: 0; + } + + .register-link { + color: #16a34a; + text-decoration: none; + font-weight: 600; + transition: color 0.2s; + } + + .register-link:hover { + color: #15803d; + text-decoration: underline; + } + + @media (max-width: 768px) { + .login-card { + padding: 2rem; + } + } +{% endblock %} + +{% block fullpage %} + +
+
+
+
+ + +
+
+ + + + + {% if form.is_bound and form.non_field_errors %} +
+ {% for e in form.non_field_errors %} +
{{ e|cut:" Note that both fields may be case-sensitive." }}
+ {% endfor %} +
+ {% endif %} + + +
+ {% csrf_token %} + + +
+ + + {% if form.is_bound %} + {% for e in form.username.errors %} + {{ e }} + {% endfor %} + {% endif %} +
+ + +
+ + + {% if form.is_bound %} + {% for e in form.password.errors %} + {{ e }} + {% endfor %} + {% endif %} +
+ + + +
+ + + +
+
+{% endblock %} diff --git a/webapp/templates/webapp/register.html b/webapp/templates/webapp/register.html new file mode 100644 index 0000000000000000000000000000000000000000..efe1a8996405480e69ef23e0176ea4fab99f9c1e --- /dev/null +++ b/webapp/templates/webapp/register.html @@ -0,0 +1,366 @@ +{% extends "base.html" %} +{% load static %} + +{% block title %}Register{% endblock %} + +{% block extra_styles %} + @keyframes float1 { + 0%, 100% { transform: translate(0, 0); } + 50% { transform: translate(100px, 50px); } + } + + @keyframes float2 { + 0%, 100% { transform: translate(0, 0); } + 50% { transform: translate(-80px, -60px); } + } + + @keyframes fadeInScale { + from { + opacity: 0; + transform: scale(0.9); + } + to { + opacity: 1; + transform: scale(1); + } + } + + body { + background: linear-gradient(135deg, #667eea, #764ba2) !important; + overflow-x: hidden; + min-height: 100vh; + } + + .animated-bg { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + overflow: hidden; + pointer-events: none; + z-index: 0; + } + + .blob { + position: absolute; + border-radius: 50%; + filter: blur(80px); + opacity: 0.3; + } + + .blob-1 { + top: 80px; + left: 80px; + width: 288px; + height: 288px; + background: rgba(255, 255, 255, 0.4); + animation: float1 20s ease-in-out infinite; + } + + .blob-2 { + bottom: 80px; + right: 80px; + width: 384px; + height: 384px; + background: rgba(255, 255, 255, 0.4); + animation: float2 25s ease-in-out infinite; + } + + .register-container { + position: relative; + z-index: 10; + display: flex; + align-items: center; + justify-content: center; + min-height: 100vh; + padding: 2rem 1rem; + } + + .register-card { + width: 100%; + max-width: 440px; + background: rgba(255, 255, 255, 0.98); + backdrop-filter: blur(10px); + padding: 2.5rem; + border-radius: 1rem; + box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); + animation: fadeInScale 0.5s ease-out; + } + + .register-header { + text-align: center; + margin-bottom: 2rem; + } + + .register-emoji { + font-size: 2.5rem; + display: inline-block; + margin-bottom: 0.5rem; + } + + .register-title { + color: #1f2937; + font-size: 1.75rem; + font-weight: 700; + margin: 0; + } + + .form-group { + margin-bottom: 1.25rem; + } + + .form-label { + display: block; + color: #374151; + font-weight: 500; + margin-bottom: 0.5rem; + font-size: 0.875rem; + } + + .form-input { + width: 100%; + padding: 0.75rem 1rem; + border: 2px solid #e5e7eb; + border-radius: 0.5rem; + font-size: 1rem; + transition: all 0.2s; + background: white; + } + + .form-input:focus { + outline: none; + border-color: #667eea; + box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); + } + + .form-input.is-invalid { + border-color: #ef4444; + } + + .form-input.is-invalid:focus { + box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1); + } + + .error-message { + color: #ef4444; + font-size: 0.875rem; + margin-top: 0.5rem; + display: block; + } + + .alert-box { + background: #fee2e2; + border: 1px solid #fca5a5; + color: #991b1b; + padding: 0.75rem 1rem; + border-radius: 0.5rem; + margin-bottom: 1.5rem; + font-size: 0.875rem; + } + + .register-button { + width: 100%; + padding: 0.875rem 1.5rem; + background: linear-gradient(135deg, #16a34a, #059669); + color: white; + border: none; + border-radius: 0.5rem; + font-size: 1rem; + font-weight: 600; + cursor: pointer; + transition: all 0.3s; + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + margin-top: 0.5rem; + } + + .register-button:hover { + transform: translateY(-2px); + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2); + } + + .register-button:active { + transform: translateY(0); + } + + .login-link-container { + text-align: center; + margin-top: 1.5rem; + padding-top: 1.5rem; + border-top: 1px solid #e5e7eb; + } + + .login-text { + color: #6b7280; + font-size: 0.875rem; + margin: 0; + } + + .login-link { + color: #667eea; + text-decoration: none; + font-weight: 600; + transition: color 0.2s; + } + + .login-link:hover { + color: #5568d3; + text-decoration: underline; + } + + /* Date input styling */ + input[type="date"]::-webkit-calendar-picker-indicator { + cursor: pointer; + opacity: 0.6; + transition: opacity 0.2s; + } + + input[type="date"]::-webkit-calendar-picker-indicator:hover { + opacity: 1; + } + + @media (max-width: 768px) { + .register-card { + padding: 2rem; + } + + .register-container { + padding: 1.5rem 1rem; + } + } +{% endblock %} + +{% block fullpage %} + +
+
+
+
+ + +
+
+ +
+
📝
+

Create Account

+
+ + + {% if form.is_bound and form.non_field_errors %} +
+ {% for e in form.non_field_errors %} +
{{ e }}
+ {% endfor %} +
+ {% endif %} + + +
+ {% csrf_token %} + + +
+ + + {% if form.is_bound %} + {% for e in form.username.errors %} + {{ e }} + {% endfor %} + {% endif %} +
+ + +
+ + + {% if form.is_bound %} + {% for e in form.full_name.errors %} + {{ e }} + {% endfor %} + {% endif %} +
+ + +
+ + + {% if form.is_bound %} + {% for e in form.date_of_birth.errors %} + {{ e }} + {% endfor %} + {% endif %} +
+ + +
+ + +
+ + +
+ + + {% if form.is_bound %} + {% for e in form.password1.errors %} + {{ e }} + {% endfor %} + {% for e in form.password2.errors %} + {{ e }} + {% endfor %} + {% endif %} +
+ + + +
+ + + +
+
+{% endblock %} diff --git a/webapp/templates/webapp/results.html b/webapp/templates/webapp/results.html new file mode 100644 index 0000000000000000000000000000000000000000..1f8ef1555256df48300c7a275912ad92b5aafb73 --- /dev/null +++ b/webapp/templates/webapp/results.html @@ -0,0 +1,718 @@ +{% extends 'base.html' %} +{% block title %}Results{% endblock %} + +{% block extra_styles %} + @keyframes float1 { + 0%, 100% { transform: translate(0, 0); } + 50% { transform: translate(100px, 50px); } + } + + @keyframes float2 { + 0%, 100% { transform: translate(0, 0); } + 50% { transform: translate(-80px, -60px); } + } + + @keyframes fadeInScale { + from { + opacity: 0; + transform: scale(0.95); + } + to { + opacity: 1; + transform: scale(1); + } + } + + @keyframes slideInUp { + from { + opacity: 0; + transform: translateY(20px); + } + to { + opacity: 1; + transform: translateY(0); + } + } + + body { + background: linear-gradient(135deg, #667eea, #764ba2) !important; + overflow-x: hidden; + min-height: 100vh; + } + + .animated-bg { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + overflow: hidden; + pointer-events: none; + z-index: 0; + } + + .blob { + position: absolute; + border-radius: 50%; + filter: blur(80px); + opacity: 0.3; + } + + .blob-1 { + top: 80px; + left: 80px; + width: 288px; + height: 288px; + background: rgba(255, 255, 255, 0.4); + animation: float1 20s ease-in-out infinite; + } + + .blob-2 { + bottom: 80px; + right: 80px; + width: 384px; + height: 384px; + background: rgba(255, 255, 255, 0.4); + animation: float2 25s ease-in-out infinite; + } + + .header-container { + position: relative; + z-index: 10; + padding: 1rem 2rem; + display: flex; + justify-content: space-between; + align-items: center; + } + + .logo-section { + display: flex; + align-items: center; + gap: 0.5rem; + color: white; + text-decoration: none; + } + + .logo-section:hover { + color: rgba(255, 255, 255, 0.9); + } + + .user-section { + display: flex; + align-items: center; + gap: 1rem; + } + + .user-info { + color: rgba(255, 255, 255, 0.9); + font-size: 0.875rem; + } + + .logout-btn { + background: rgba(255, 255, 255, 0.1); + border: 1px solid rgba(255, 255, 255, 0.2); + color: white; + padding: 0.5rem 1rem; + border-radius: 0.375rem; + text-decoration: none; + display: inline-flex; + align-items: center; + gap: 0.5rem; + transition: all 0.3s; + font-size: 0.875rem; + } + + .logout-btn:hover { + background: rgba(255, 255, 255, 0.2); + color: white; + } + + .results-container { + position: relative; + z-index: 10; + padding: 2rem 1rem; + max-width: 1100px; + margin: 0 auto; + } + + .results-card { + background: rgba(255, 255, 255, 0.98); + backdrop-filter: blur(10px); + padding: 2.5rem; + border-radius: 1.25rem; + box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); + animation: fadeInScale 0.5s ease-out; + } + + .results-header { + text-align: center; + margin-bottom: 2rem; + } + + .results-title { + color: #2563eb; + font-size: 2rem; + font-weight: 700; + margin: 0; + } + + .metrics-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); + gap: 1rem; + margin-bottom: 2rem; + } + + .metric-card { + background: linear-gradient(135deg, #dbeafe, #bfdbfe); + border: 2px solid #93c5fd; + padding: 1.25rem; + border-radius: 0.75rem; + animation: slideInUp 0.6s ease-out; + } + + .metric-card.success { + background: linear-gradient(135deg, #d1fae5, #a7f3d0); + border-color: #6ee7b7; + } + + .metric-label { + font-weight: 600; + color: #1e40af; + font-size: 0.875rem; + margin-bottom: 0.25rem; + } + + .metric-card.success .metric-label { + color: #065f46; + } + + .metric-value { + font-size: 1.5rem; + font-weight: 700; + color: #1e3a8a; + } + + .metric-card.success .metric-value { + color: #064e3b; + } + + .section-card { + background: #f9fafb; + border: 2px solid #e5e7eb; + padding: 1.5rem; + border-radius: 0.75rem; + margin-bottom: 1.5rem; + animation: slideInUp 0.7s ease-out; + } + + .section-title { + color: #374151; + font-size: 1.25rem; + font-weight: 600; + margin: 0 0 1rem 0; + display: flex; + align-items: center; + gap: 0.5rem; + } + + .config-list { + list-style: none; + padding: 0; + margin: 0; + } + + .config-list li { + padding: 0.5rem 0; + color: #4b5563; + font-size: 0.9375rem; + border-bottom: 1px solid #e5e7eb; + } + + .config-list li:last-child { + border-bottom: none; + } + + .config-list strong { + color: #1f2937; + font-weight: 600; + } + + .viz-wrapper { + width: 100%; + max-width: 100%; + overflow: hidden; + border-radius: 0.5rem; + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + margin: 1rem 0; + } + + .viz-image { + width: 100%; + height: auto; + display: block; + } + + .viz-note { + font-size: 0.875rem; + color: #6b7280; + text-align: center; + margin-top: 0.75rem; + } + + .taxa-card { + background: white; + border: 2px solid #e5e7eb; + border-radius: 0.75rem; + padding: 1.5rem; + margin-bottom: 1.5rem; + animation: slideInUp 0.8s ease-out; + } + + .taxa-header { + display: flex; + justify-content: space-between; + align-items: center; + padding: 0 0.75rem 0.75rem 0.75rem; + border-bottom: 2px solid #e5e7eb; + margin-bottom: 0.75rem; + } + + .taxa-header-label { + font-size: 0.875rem; + font-weight: 600; + color: #6b7280; + } + + .taxa-list { + list-style: none; + padding: 0; + margin: 0; + } + + .taxa-item { + display: flex; + justify-content: space-between; + align-items: center; + padding: 0.875rem 0.75rem; + border-bottom: 1px solid #f3f4f6; + transition: background 0.2s; + } + + .taxa-item:hover { + background: #f9fafb; + } + + .taxa-item:last-child { + border-bottom: none; + } + + .taxa-link { + color: #2563eb; + text-decoration: none; + font-weight: 500; + transition: color 0.2s; + } + + .taxa-link:hover { + color: #1d4ed8; + text-decoration: underline; + } + + .taxa-badge { + background: linear-gradient(135deg, #667eea, #764ba2); + color: white; + padding: 0.375rem 0.75rem; + border-radius: 1rem; + font-size: 0.875rem; + font-weight: 600; + } + + .taxa-note { + font-size: 0.875rem; + color: #6b7280; + margin-top: 0.75rem; + padding: 0 0.75rem; + } + + .action-buttons { + display: flex; + gap: 1rem; + justify-content: center; + margin: 2rem 0; + flex-wrap: wrap; + } + + .btn-primary-gradient { + background: linear-gradient(135deg, #667eea, #764ba2); + color: white; + border: none; + padding: 0.875rem 2rem; + border-radius: 0.5rem; + font-weight: 600; + text-decoration: none; + display: inline-flex; + align-items: center; + gap: 0.5rem; + transition: all 0.3s; + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + font-size: 1rem; + } + + .btn-primary-gradient:hover { + transform: translateY(-2px); + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2); + color: white; + } + + .btn-outline-gradient { + background: white; + color: #667eea; + border: 2px solid #667eea; + padding: 0.875rem 2rem; + border-radius: 0.5rem; + font-weight: 600; + text-decoration: none; + display: inline-flex; + align-items: center; + gap: 0.5rem; + transition: all 0.3s; + font-size: 1rem; + } + + .btn-outline-gradient:hover { + background: linear-gradient(135deg, #667eea, #764ba2); + color: white; + border-color: transparent; + transform: translateY(-2px); + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + } + + .save-form-card { + background: white; + border: 2px solid #e5e7eb; + border-radius: 0.75rem; + padding: 2rem; + margin-top: 1.5rem; + animation: slideInUp 0.9s ease-out; + } + + .form-label { + color: #374151; + font-weight: 600; + margin-bottom: 0.5rem; + font-size: 0.875rem; + display: block; + } + + .form-control { + width: 100%; + padding: 0.75rem 1rem; + border: 2px solid #e5e7eb; + border-radius: 0.5rem; + font-size: 0.9375rem; + transition: all 0.2s; + background: white; + } + + .form-control:focus { + outline: none; + border-color: #667eea; + box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); + } + + textarea.form-control { + resize: vertical; + min-height: 80px; + } + + .form-check { + display: flex; + align-items: center; + gap: 0.5rem; + } + + .form-check-input { + width: 2.5rem; + height: 1.25rem; + cursor: pointer; + accent-color: #667eea; + } + + .form-check-label { + cursor: pointer; + color: #374151; + font-weight: 500; + font-size: 0.9375rem; + } + + .form-row { + display: grid; + grid-template-columns: 1fr; + gap: 1rem; + margin-bottom: 1rem; + } + + @media (min-width: 768px) { + .form-row.cols-2 { + grid-template-columns: 2fr 1fr; + } + } + + .btn-save { + background: linear-gradient(135deg, #667eea, #764ba2); + color: white; + border: none; + padding: 0.75rem 2rem; + border-radius: 0.5rem; + font-weight: 600; + cursor: pointer; + transition: all 0.3s; + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + font-size: 1rem; + } + + .btn-save:hover { + transform: translateY(-2px); + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2); + } + + .text-end { + text-align: right; + } + + @media (max-width: 768px) { + .results-card { + padding: 2rem; + } + + .header-container { + flex-direction: column; + gap: 1rem; + } + + .action-buttons { + flex-direction: column; + } + + .btn-primary-gradient, + .btn-outline-gradient { + width: 100%; + justify-content: center; + } + } +{% endblock %} + +{% block fullpage %} + +
+
+
+
+ + +
+ + + + + + +

Model Lab

+
+
+ + + + + + + + Logout + +
+
+ + +
+
+ +
+

📊 Model Results

+
+ + +
+
+
+
Validation AUC
+
{% if val_auc is not None %}{{ val_auc|floatformat:3 }}{% else %}N/A{% endif %}
+
+
+
Validation F1
+
{{ val_f1|default_if_none:"N/A"|floatformat:3 }}
+
+
+ +
+
+
Test AUC
+
{% if test_auc is not None %}{{ test_auc|floatformat:3 }}{% else %}N/A{% endif %}
+
+
+
Test F1
+
{% if test_f1 is not None %}{{ test_f1|floatformat:3 }}{% else %}N/A{% endif %}
+
+
+
+ + +
+

🔍 Model Configuration

+
    + {% if summary.scaler %}
  • Scaler: {{ summary.scaler }}
  • {% endif %} +
  • Base Models: {% if summary.base_models %}{{ summary.base_models|join:", " }}{% else %}None{% endif %}
  • + + {% if summary.ensemble == 'stacking' %} +
  • Ensemble Type: Stacking
  • + {% if summary.meta_learner %}
  • Meta Learner: {{ summary.meta_learner }}
  • {% endif %} + {% elif summary.ensemble == 'voting' %} +
  • Ensemble Type: Voting
  • + {% if summary.voting_type %}
  • Voting Type: {{ summary.voting_type|title }}
  • {% endif %} + {% else %} + {% if summary.base_models and summary.base_models|length > 1 %} +
  • Ensemble Type: Stacking (Auto)
  • + {% else %} +
  • Ensemble Type: None (Single Model)
  • + {% endif %} + {% endif %} + + {% if summary.balancing %}
  • Balancing: {{ summary.balancing }}
  • {% endif %} + {% if summary.augmentation %}
  • Augmentation: {{ summary.augmentation }}
  • {% endif %} + {% if summary.target_samples %}
  • Target Samples: {{ summary.target_samples }}
  • {% endif %} +
+
+ + +
+

+ {% if explain_type == 'shap' %}🧠 Feature Impact (SHAP) + {% elif explain_type == 'permutation' %}🧪 Feature Impact (Permutation) + {% else %}Feature Impact{% endif %} +

+ + {% if shap_url %} +
+ Feature impact +
+ {% if explain_type == 'permutation' %} +
+ Bars > 0: model performance drops when permuted (feature helps). + Bars < 0: performance improves (feature may hurt). +
+ {% endif %} + {% else %} +

No chart generated.

+ {% endif %} +
+ + + {% if top_taxa_links %} +
+

Top Features → NCBI Taxonomy

+ +
+
NCBI TaxID
+
Importance
+
+ +
    + {% for t in top_taxa_links %} +
  • +
    + {% if t.url %} + + {{ t.id }} + + {% else %} + {{ t.id }} + {% endif %} +
    + {% if t.score is not None %} + + {{ t.score|floatformat:3 }} + + {% endif %} +
  • + {% endfor %} +
+ +
+ Only numeric feature names are treated as TaxIDs. Importance is the feature's contribution score. +
+
+ {% endif %} + + +
+ {% if mode == 'train' %} + + 🔁 Train Another Model + + {% else %} + + 🧪 Test Another Model + + {% endif %} +
+ + + {% if can_save %} +
+

💾 Save Model

+ +
+ {% csrf_token %} + +
+
+ + +
+
+
+ + +
+
+
+ +
+
+ + +
+
+ +
+ +
+
+
+ {% endif %} + +
+
+{% endblock %} diff --git a/webapp/templates/webapp/test_model.html b/webapp/templates/webapp/test_model.html new file mode 100644 index 0000000000000000000000000000000000000000..7ace2b20923e0d7851f48267800300bfd6832378 --- /dev/null +++ b/webapp/templates/webapp/test_model.html @@ -0,0 +1,905 @@ +{% extends 'base.html' %} +{% block title %}Test Model{% endblock %} + +{% block extra_styles %} + @keyframes float1 { + 0%, 100% { transform: translate(0, 0); } + 50% { transform: translate(100px, 50px); } + } + + @keyframes float2 { + 0%, 100% { transform: translate(0, 0); } + 50% { transform: translate(-80px, -60px); } + } + + @keyframes fadeInScale { + from { + opacity: 0; + transform: scale(0.95); + } + to { + opacity: 1; + transform: scale(1); + } + } + + @keyframes slideInLeft { + from { + opacity: 0; + transform: translateX(-20px); + } + to { + opacity: 1; + transform: translateX(0); + } + } + + @keyframes slideInRight { + from { + opacity: 0; + transform: translateX(20px); + } + to { + opacity: 1; + transform: translateX(0); + } + } + + body { + background: linear-gradient(135deg, #667eea, #764ba2) !important; + overflow-x: hidden; + min-height: 100vh; + } + + .animated-bg { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + overflow: hidden; + pointer-events: none; + z-index: 0; + } + + .blob { + position: absolute; + border-radius: 50%; + filter: blur(80px); + opacity: 0.3; + } + + .blob-1 { + top: 80px; + left: 80px; + width: 288px; + height: 288px; + background: rgba(255, 255, 255, 0.4); + animation: float1 20s ease-in-out infinite; + } + + .blob-2 { + bottom: 80px; + right: 80px; + width: 384px; + height: 384px; + background: rgba(255, 255, 255, 0.4); + animation: float2 25s ease-in-out infinite; + } + + .header-container { + position: relative; + z-index: 10; + padding: 1rem 2rem; + display: flex; + justify-content: space-between; + align-items: center; + } + + .logo-section { + display: flex; + align-items: center; + gap: 0.5rem; + color: white; + text-decoration: none; + } + + .logo-section:hover { + color: rgba(255, 255, 255, 0.9); + } + + .user-section { + display: flex; + align-items: center; + gap: 1rem; + } + + .user-info { + color: rgba(255, 255, 255, 0.9); + font-size: 0.875rem; + } + + .logout-btn { + background: rgba(255, 255, 255, 0.1); + border: 1px solid rgba(255, 255, 255, 0.2); + color: white; + padding: 0.5rem 1rem; + border-radius: 0.375rem; + text-decoration: none; + display: inline-flex; + align-items: center; + gap: 0.5rem; + transition: all 0.3s; + font-size: 0.875rem; + } + + .logout-btn:hover { + background: rgba(255, 255, 255, 0.2); + color: white; + } + + .test-container { + position: relative; + z-index: 10; + padding: 2rem 1rem; + max-width: 1400px; + margin: 0 auto; + } + + .alert { + background: rgba(255, 255, 255, 0.95); + border: 2px solid #fca5a5; + color: #991b1b; + padding: 0.875rem 1rem; + border-radius: 0.5rem; + margin-bottom: 1rem; + animation: slideInLeft 0.5s ease-out; + } + + .alert-info { + border-color: #93c5fd; + color: #1e40af; + } + + .alert-success { + border-color: #6ee7b7; + color: #065f46; + } + + .test-grid { + display: grid; + grid-template-columns: 1fr; + gap: 1.5rem; + align-items: start; + } + + @media (min-width: 992px) { + .test-grid { + grid-template-columns: 1.2fr 1fr; + } + } + + .form-card { + background: rgba(255, 255, 255, 0.98); + backdrop-filter: blur(10px); + padding: 2.5rem; + border-radius: 1.25rem; + box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); + animation: slideInLeft 0.5s ease-out; + } + + .sidebar-card { + background: rgba(255, 255, 255, 0.98); + backdrop-filter: blur(10px); + padding: 1.5rem; + border-radius: 1.25rem; + box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); + max-height: 70vh; + overflow-y: auto; + animation: slideInRight 0.5s ease-out; + } + + .sidebar-card::-webkit-scrollbar { + width: 8px; + } + + .sidebar-card::-webkit-scrollbar-track { + background: #f1f5f9; + border-radius: 4px; + } + + .sidebar-card::-webkit-scrollbar-thumb { + background: #cbd5e1; + border-radius: 4px; + } + + .sidebar-card::-webkit-scrollbar-thumb:hover { + background: #94a3b8; + } + + .form-title { + color: #2563eb; + font-size: 1.5rem; + font-weight: 700; + text-align: center; + margin: 0 0 2rem 0; + } + + .form-label { + color: #374151; + font-weight: 600; + margin-bottom: 0.5rem; + font-size: 0.875rem; + display: block; + } + + .form-control { + width: 100%; + padding: 0.75rem 1rem; + border: 2px solid #e5e7eb; + border-radius: 0.5rem; + font-size: 0.9375rem; + transition: all 0.2s; + background: white; + } + + .form-control:focus { + outline: none; + border-color: #667eea; + box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); + } + + input[type="file"].form-control { + padding: 0.625rem 1rem; + cursor: pointer; + } + + input[type="file"]::file-selector-button { + padding: 0.5rem 1rem; + border: none; + background: linear-gradient(135deg, #667eea, #764ba2); + color: white; + border-radius: 0.375rem; + font-weight: 500; + cursor: pointer; + margin-right: 1rem; + transition: all 0.2s; + } + + input[type="file"]::file-selector-button:hover { + transform: translateY(-1px); + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + } + + .form-group { + margin-bottom: 1.5rem; + } + + .selected-model-banner { + background: #e0e7ff; + border: 2px solid #c7d2fe; + padding: 0.875rem 1rem; + border-radius: 0.5rem; + margin-bottom: 1rem; + display: flex; + justify-content: space-between; + align-items: center; + } + + .selected-model-banner strong { + color: #3730a3; + } + + .btn-clear { + background: white; + border: 1px solid #cbd5e1; + color: #475569; + padding: 0.375rem 0.875rem; + border-radius: 0.375rem; + font-size: 0.875rem; + font-weight: 500; + cursor: pointer; + transition: all 0.2s; + } + + .btn-clear:hover { + background: #f1f5f9; + border-color: #94a3b8; + } + + .btn-submit { + width: 100%; + padding: 1rem 1.5rem; + background: linear-gradient(135deg, #16a34a, #059669); + color: white; + border: none; + border-radius: 0.5rem; + font-size: 1.125rem; + font-weight: 600; + cursor: pointer; + transition: all 0.3s; + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + } + + .btn-submit:hover { + transform: translateY(-2px); + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2); + } + + .section-heading { + color: #6b7280; + font-size: 0.875rem; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.05em; + margin: 0 0 1rem 0; + } + + .model-card { + background: white; + border: 2px solid #e5e7eb; + border-radius: 0.75rem; + padding: 1rem; + margin-bottom: 0.75rem; + transition: all 0.2s; + } + + .model-card:hover { + border-color: #cbd5e1; + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + } + + .model-card.pick-active { + border-color: #667eea; + background: #f0f4ff; + box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); + } + + .model-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + margin-bottom: 0.5rem; + } + + .model-name { + font-weight: 600; + color: #1f2937; + font-size: 0.9375rem; + } + + .model-meta { + font-size: 0.8125rem; + color: #6b7280; + line-height: 1.5; + } + + .model-meta strong { + color: #374151; + } + + .model-description { + font-size: 0.8125rem; + color: #6b7280; + margin-top: 0.5rem; + line-height: 1.4; + } + + .model-actions { + display: flex; + gap: 0.5rem; + margin-top: 0.75rem; + } + + .btn-sm { + padding: 0.375rem 0.875rem; + border-radius: 0.375rem; + font-size: 0.8125rem; + font-weight: 500; + cursor: pointer; + transition: all 0.2s; + border: 1px solid; + text-decoration: none; + display: inline-block; + } + + .btn-outline-secondary { + background: white; + border-color: #d1d5db; + color: #4b5563; + } + + .btn-outline-secondary:hover { + background: #f9fafb; + border-color: #9ca3af; + } + + .btn-outline-danger { + background: white; + border-color: #fca5a5; + color: #dc2626; + } + + .btn-outline-danger:hover { + background: #fee2e2; + border-color: #f87171; + } + + .btn-outline-primary { + background: white; + border-color: #93c5fd; + color: #2563eb; + } + + .btn-outline-primary:hover { + background: linear-gradient(135deg, #667eea, #764ba2); + color: white; + border-color: transparent; + } + + .badge { + display: inline-block; + padding: 0.25rem 0.625rem; + border-radius: 0.375rem; + font-size: 0.75rem; + font-weight: 600; + margin-left: 0.375rem; + } + + .badge.bg-success { + background: #059669; + color: white; + } + + .divider { + height: 1px; + background: #e5e7eb; + margin: 1.5rem 0; + } + + .d-none { + display: none !important; + } + + .text-center { + text-align: center; + } + + .alert-danger { + background: #fee2e2; + border-color: #fca5a5; + color: #991b1b; + } + + /* Modal Styles */ + .modal { + display: none; + position: fixed; + z-index: 1000; + left: 0; + top: 0; + width: 100%; + height: 100%; + background: rgba(0, 0, 0, 0.5); + backdrop-filter: blur(4px); + } + + .modal.show { + display: flex; + align-items: center; + justify-content: center; + } + + .modal-dialog { + width: 100%; + max-width: 500px; + margin: 1rem; + } + + .modal-content { + background: white; + border-radius: 0.75rem; + box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5); + overflow: hidden; + } + + .modal-header { + padding: 1.5rem; + border-bottom: 1px solid #e5e7eb; + display: flex; + justify-content: space-between; + align-items: center; + } + + .modal-title { + color: #1f2937; + font-size: 1.25rem; + font-weight: 600; + margin: 0; + } + + .btn-close { + background: transparent; + border: none; + font-size: 1.5rem; + color: #6b7280; + cursor: pointer; + padding: 0; + width: 24px; + height: 24px; + display: flex; + align-items: center; + justify-content: center; + } + + .btn-close:hover { + color: #374151; + } + + .modal-body { + padding: 1.5rem; + } + + .modal-footer { + padding: 1rem 1.5rem; + border-top: 1px solid #e5e7eb; + display: flex; + justify-content: flex-end; + gap: 0.75rem; + } + + .btn { + padding: 0.625rem 1.25rem; + border-radius: 0.375rem; + font-weight: 500; + cursor: pointer; + transition: all 0.2s; + border: none; + font-size: 0.9375rem; + } + + .btn-primary { + background: linear-gradient(135deg, #667eea, #764ba2); + color: white; + } + + .btn-primary:hover { + transform: translateY(-1px); + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + } + + .form-check { + display: flex; + align-items: center; + gap: 0.5rem; + } + + .form-check-input { + width: 2.5rem; + height: 1.25rem; + cursor: pointer; + accent-color: #667eea; + } + + .form-check-label { + cursor: pointer; + color: #374151; + font-weight: 500; + font-size: 0.9375rem; + } + + textarea.form-control { + resize: vertical; + min-height: 100px; + } + + @media (max-width: 768px) { + .form-card, .sidebar-card { + padding: 2rem; + } + + .header-container { + flex-direction: column; + gap: 1rem; + } + + .model-actions { + flex-wrap: wrap; + } + } +{% endblock %} + +{% block fullpage %} + +
+
+
+
+ + +
+ + + + + + +

Model Lab

+
+
+ + + + + + + + Logout + +
+
+ + +
+ + {% if messages %} + {% for m in messages %} +
+ {{ m }} +
+ {% endfor %} + {% endif %} + + +
+ +
+

🧪 Upload Pretrained Model & Test Data

+ +
+ {% csrf_token %} + +
+ + +
+ +
+ + +
+ + + +
+
Selected model:
+ +
+ +
+ +
+
+ + {% if message %} +
+ {{ message }} +
+ {% endif %} +
+ + + +
+
+ + + + + +{% endblock %} \ No newline at end of file diff --git a/webapp/templates/webapp/train_model.html b/webapp/templates/webapp/train_model.html new file mode 100644 index 0000000000000000000000000000000000000000..1186dee64397d242708bb90f04cec1508ed2c3ae --- /dev/null +++ b/webapp/templates/webapp/train_model.html @@ -0,0 +1,627 @@ +{% extends 'base.html' %} +{% block title %}Train Model{% endblock %} + +{% block extra_styles %} + @keyframes float1 { + 0%, 100% { transform: translate(0, 0); } + 50% { transform: translate(100px, 50px); } + } + + @keyframes float2 { + 0%, 100% { transform: translate(0, 0); } + 50% { transform: translate(-80px, -60px); } + } + + @keyframes fadeInScale { + from { + opacity: 0; + transform: scale(0.95); + } + to { + opacity: 1; + transform: scale(1); + } + } + + body { + background: linear-gradient(135deg, #667eea, #764ba2) !important; + overflow-x: hidden; + min-height: 100vh; + } + + .animated-bg { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + overflow: hidden; + pointer-events: none; + z-index: 0; + } + + .blob { + position: absolute; + border-radius: 50%; + filter: blur(80px); + opacity: 0.3; + } + + .blob-1 { + top: 80px; + left: 80px; + width: 288px; + height: 288px; + background: rgba(255, 255, 255, 0.4); + animation: float1 20s ease-in-out infinite; + } + + .blob-2 { + bottom: 80px; + right: 80px; + width: 384px; + height: 384px; + background: rgba(255, 255, 255, 0.4); + animation: float2 25s ease-in-out infinite; + } + + .header-container { + position: relative; + z-index: 10; + padding: 1rem 2rem; + display: flex; + justify-content: space-between; + align-items: center; + } + + .logo-section { + display: flex; + align-items: center; + gap: 0.5rem; + color: white; + text-decoration: none; + } + + .logo-section:hover { + color: rgba(255, 255, 255, 0.9); + } + + .user-section { + display: flex; + align-items: center; + gap: 1rem; + } + + .user-info { + color: rgba(255, 255, 255, 0.9); + font-size: 0.875rem; + } + + .logout-btn { + background: rgba(255, 255, 255, 0.1); + border: 1px solid rgba(255, 255, 255, 0.2); + color: white; + padding: 0.5rem 1rem; + border-radius: 0.375rem; + text-decoration: none; + display: inline-flex; + align-items: center; + gap: 0.5rem; + transition: all 0.3s; + font-size: 0.875rem; + } + + .logout-btn:hover { + background: rgba(255, 255, 255, 0.2); + color: white; + } + + .train-container { + position: relative; + z-index: 10; + display: flex; + align-items: center; + justify-content: center; + min-height: calc(100vh - 80px); + padding: 2rem 1rem; + } + + .train-card { + width: 100%; + max-width: 720px; + background: rgba(255, 255, 255, 0.98); + backdrop-filter: blur(10px); + padding: 2.5rem; + border-radius: 1.25rem; + box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); + animation: fadeInScale 0.5s ease-out; + } + + .train-header { + text-align: center; + margin-bottom: 2rem; + } + + .train-title { + color: #2563eb; + font-size: 1.75rem; + font-weight: 700; + margin: 0; + } + + .form-label { + color: #374151; + font-weight: 600; + margin-bottom: 0.5rem; + font-size: 0.875rem; + display: block; + } + + .form-control, + .form-select { + width: 100%; + padding: 0.75rem 1rem; + border: 2px solid #e5e7eb; + border-radius: 0.5rem; + font-size: 0.9375rem; + transition: all 0.2s; + background: white; + } + + .form-control:focus, + .form-select:focus { + outline: none; + border-color: #667eea; + box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); + } + + .form-select:disabled { + background-color: #f3f4f6; + cursor: not-allowed; + opacity: 0.6; + } + + /* File input styling */ + input[type="file"].form-control { + padding: 0.625rem 1rem; + cursor: pointer; + } + + input[type="file"]::file-selector-button { + padding: 0.5rem 1rem; + border: none; + background: linear-gradient(135deg, #667eea, #764ba2); + color: white; + border-radius: 0.375rem; + font-weight: 500; + cursor: pointer; + margin-right: 1rem; + transition: all 0.2s; + } + + input[type="file"]::file-selector-button:hover { + transform: translateY(-1px); + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + } + + /* Checkbox styling for base models */ + #id_base_models { + display: flex; + flex-wrap: wrap; + gap: 1rem; + padding: 1rem; + background: #f9fafb; + border-radius: 0.5rem; + border: 2px solid #e5e7eb; + } + + #id_base_models label { + display: flex; + align-items: center; + gap: 0.5rem; + cursor: pointer; + font-size: 0.875rem; + color: #374151; + margin: 0; + white-space: nowrap; + } + + #id_base_models input[type="checkbox"] { + width: 1.125rem; + height: 1.125rem; + cursor: pointer; + accent-color: #667eea; + } + + .btn-success { + width: 100%; + padding: 1rem 1.5rem; + background: linear-gradient(135deg, #16a34a, #059669); + color: white; + border: none; + border-radius: 0.5rem; + font-size: 1.125rem; + font-weight: 600; + cursor: pointer; + transition: all 0.3s; + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + } + + .btn-success:hover:not(:disabled) { + transform: translateY(-2px); + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2); + background: linear-gradient(135deg, #16a34a, #059669); + } + + .btn-success:disabled { + opacity: 0.6; + cursor: not-allowed; + transform: none; + } + + .alert-danger { + background: #fee2e2; + border: 1px solid #fca5a5; + color: #991b1b; + padding: 0.875rem 1rem; + border-radius: 0.5rem; + font-size: 0.9375rem; + text-align: center; + } + + /* Row and column spacing */ + .row { + display: flex; + flex-wrap: wrap; + margin: 0 -0.5rem; + } + + .g-3 > * { + padding: 0 0.5rem; + margin-bottom: 1rem; + } + + .col-12 { + width: 100%; + } + + .col-md-6 { + width: 100%; + } + + @media (min-width: 768px) { + .col-md-6 { + width: 50%; + } + } + + /* Training overlay */ + .position-fixed { + position: fixed; + } + + .top-0 { top: 0; } + .start-0 { left: 0; } + .w-100 { width: 100%; } + .h-100 { height: 100%; } + + .d-none { + display: none; + } + + .d-flex { + display: flex; + } + + .justify-content-center { + justify-content: center; + } + + .align-items-center { + align-items: center; + } + + #training-overlay { + background: rgba(0, 0, 0, 0.6); + backdrop-filter: blur(4px); + z-index: 1050; + } + + #training-overlay .card { + background: white; + padding: 2rem; + border-radius: 1rem; + box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5); + min-width: 320px; + } + + .spinner-border { + width: 2.5rem; + height: 2.5rem; + border: 4px solid #e5e7eb; + border-top-color: #667eea; + border-radius: 50%; + animation: spin 0.8s linear infinite; + } + + @keyframes spin { + to { transform: rotate(360deg); } + } + + .me-3 { + margin-right: 1rem; + } + + .mb-1 { + margin-bottom: 0.25rem; + } + + @media (max-width: 768px) { + .train-card { + padding: 2rem; + } + + .header-container { + flex-direction: column; + gap: 1rem; + } + + #id_base_models { + grid-template-columns: 1fr; + } + } +{% endblock %} + +{% block fullpage %} + +
+
+
+
+ + +
+ + + + + + +

Model Lab

+
+
+ + + + + + + + Logout + +
+
+ + +
+
+ +
+

📄 Upload Dataset & Configure ML

+
+ + +
+ {% csrf_token %} + +
+ + {{ form.dataset }} +
+ + +
+ + {% if message %} +
{{ message }}
+ {% endif %} +
+
+ + +
+
+
+
+
+
+
Training in progress…
+ Please keep this tab open. This may take a minute. +
+
+
+
+
+ + + + +{% endblock %} \ No newline at end of file diff --git a/webapp/templates/webapp/training_status.html b/webapp/templates/webapp/training_status.html new file mode 100644 index 0000000000000000000000000000000000000000..82cb85b2818872cb1d91614bef68805d9d9747c5 --- /dev/null +++ b/webapp/templates/webapp/training_status.html @@ -0,0 +1,301 @@ +{# webapp/templates/webapp/training_status.html #} +{% load static %} + + + + + + Training… + + + + +
+
+
+
+ + +
+
+ +
+
🚀
+

Training in progress

+
+ + +
+
+
+ 0% +
+
+
+ + +
+ + Starting… +
+
+
+ + + + diff --git a/webapp/urls.py b/webapp/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..d42410c782b67d3c7bc686d48269cad2dde22fba --- /dev/null +++ b/webapp/urls.py @@ -0,0 +1,47 @@ +# webapp/urls.py +from django.urls import path +from django.contrib.auth import views as auth_views # You might not need this import if you're using custom views +from django.conf import settings +from . import views + +# clear dev startup --> enforces login after each start --->only for dev, not for production +# It's generally better to handle session clearing in a management command or migration, +# but for quick dev iteration, this can be used. However, be cautious. +# If you need this, ensure it's only active during development. +# from django.contrib.sessions.models import Session +# Session.objects.all().delete() # Uncomment with caution! + +urlpatterns = [ + path("debug-csrf/", views.debug_csrf, name="debug_csrf"), + + # User authentication (assuming you have login_view, register_view, logout_view) + path('register/', views.register_view, name='register'), + path('login/', views.login_view, name='login'), + path('logout/', views.logout_view, name='logout'), + + # Application pages + path('', views.landing_page, name='landing_page'), # This is the root URL for your app + path('train_model/', views.train_model, name='train_model'), + path('results/', views.results_view, name='results'), + path('test-model/', views.test_model, name='test_model'), + + # Asynchronous training and API + # This pattern will be matched relative to the root URL because it's included + # in the project's urls.py without a prefix. + path("train/start/", views.start_training, name="start_training"), + path("train//", views.training_status, name="training_status"), + path("train//done/", views.training_done, name="training_done"), + path("api/train//progress/", views.training_progress, name="training_progress"), + + # Add this if you intend to use the landing_page as a named URL elsewhere + # path('landing/', views.landing_page, name='landing_page'), # This might be redundant if '/' maps to landing_page + path('save-model/', views.save_model, name='save_model'), + path('models/delete/', views.delete_saved_model, name='delete_saved_model'), + path('models/edit/', views.edit_saved_model, name='edit_saved_model'), + +] + +# Static files handling is usually in the project's urls.py, but can be here too +if settings.DEBUG: + from django.conf.urls.static import static + urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \ No newline at end of file diff --git a/webapp/views.py b/webapp/views.py new file mode 100644 index 0000000000000000000000000000000000000000..70247cbfcd0cdc5bbce24c240a6a65805cd5888c --- /dev/null +++ b/webapp/views.py @@ -0,0 +1,520 @@ +# webapp/views.py +import threading, uuid, io, joblib, os +from django.shortcuts import render, redirect +from django.contrib.auth.decorators import login_required +from django.contrib.auth import login, logout +from django.contrib.auth.forms import UserCreationForm, AuthenticationForm +from django.conf import settings +from .forms import UploadForm, SaveModelForm, RegisterForm +from .services.training import TrainOptions, train_dataset +from .services.inference import run_inference +from django.views.decorators.http import require_GET, require_POST +from django.core.cache import cache +from django.contrib import messages +from django.http import JsonResponse +from django.core.files.base import File +from django.db.models import Q +from django.utils.text import slugify +from .models import SavedModel, PublicDataset, model_upload_path +import shutil +from django.utils.safestring import mark_safe + +def debug_csrf(request): + return JsonResponse({ + "ALLOWED_HOSTS": settings.ALLOWED_HOSTS, + "CSRF_TRUSTED_ORIGINS": settings.CSRF_TRUSTED_ORIGINS, + }) + + +@require_POST +@login_required +def save_model(request): + form = SaveModelForm(request.POST) + tmp_rel = request.session.get('tmp_model_relpath') + if not tmp_rel: + # nothing to save (probably page refreshed) + return redirect('results') + + if not form.is_valid(): + return redirect('results') + + src_abs = os.path.join(settings.MEDIA_ROOT, tmp_rel) + if not os.path.exists(src_abs): + request.session.pop('tmp_model_relpath', None) + return redirect('results') + + name = form.cleaned_data['name'] + public = form.cleaned_data.get('public', False) + description = (form.cleaned_data.get('description') or '').strip()[:2000] + trained_on = request.session.get('dataset_name', '') + + # build final destination using your upload helper + filename = f"{slugify(name)}-{uuid.uuid4().hex}.joblib" + # model_upload_path expects an instance with owner_id; create a light stub + stub = type('X', (), {'owner_id': request.user.id})() + final_rel = model_upload_path(stub, filename) + final_abs = os.path.join(settings.MEDIA_ROOT, final_rel) + os.makedirs(os.path.dirname(final_abs), exist_ok=True) + shutil.move(src_abs, final_abs) + + SavedModel.objects.create( + owner=request.user, + name=name, + public=public, + description=description, + trained_on=trained_on, + file=final_rel, + test_auc=request.session.get('test_auc'), + test_f1=request.session.get('test_f1'), + ) + + # clear temp so the button disappears + request.session.pop('tmp_model_relpath', None) + request.session.pop('dataset_name', None) + return redirect('test_model') + +@login_required +def train_model(request): + if request.method == 'POST': + form = UploadForm(request.POST, request.FILES) + if form.is_valid(): + try: + uploaded_file = request.FILES['dataset'] + request.session['dataset_name'] = uploaded_file.name + + result = train_dataset( + file_obj=uploaded_file, + opts=TrainOptions( + scaler=form.cleaned_data['scaler'], + base_models=form.cleaned_data['base_models'], + ensemble_type=form.cleaned_data['ensemble_type'], + meta_learner=form.cleaned_data.get('meta_learner'), + voting_type=form.cleaned_data.get('voting_type'), + balancing=form.cleaned_data['balancing_strategy'], + augmentation=form.cleaned_data['augmentation'], + target_samples=(form.cleaned_data.get('target_samples') or None), + ), + save_to=None, + ) + except Exception as e: + return render(request, 'webapp/train_model.html', {'form': form, 'message': str(e)}) + + # ---- store plain Python numbers (avoid numpy int64 in session) ---- + _flt = lambda x: float(x) if x is not None else None + request.session['val_auc'] = _flt(result.val_auc) + request.session['val_f1'] = _flt(result.val_f1) + request.session['test_auc'] = _flt(result.test_auc) + request.session['test_f1'] = _flt(result.test_f1) + request.session['summary'] = result.summary or {} + + # explanation graphic + request.session['shap_url'] = ( + settings.MEDIA_URL + result.shap_relpath + if result.shap_relpath else None + ) + request.session['explain_type'] = result.summary.get('explain_type') + request.session['mode'] = 'train' + + # --- stash artifact to a temp joblib so the "Save Model" button can work --- + tmp_rel = os.path.join("tmp_models", f"{uuid.uuid4().hex}.joblib") + tmp_abs = os.path.join(settings.MEDIA_ROOT, tmp_rel) + os.makedirs(os.path.dirname(tmp_abs), exist_ok=True) + joblib.dump(result.artifact, tmp_abs) + request.session['tmp_model_relpath'] = tmp_rel + + return redirect('results') + + # invalid form -> re-render with errors + return render(request, 'webapp/train_model.html', {'form': form}) + + # GET (or anything else) -> render empty form + form = UploadForm() + return render(request, 'webapp/train_model.html', {'form': form}) + + +@login_required +def results_view(request): + can_save = request.session.get('mode') == 'train' and bool(request.session.get('tmp_model_relpath')) + val_auc = request.session.get('val_auc') + val_f1 = request.session.get('val_f1') + test_auc = request.session.get('test_auc') + test_f1 = request.session.get('test_f1') + summary = request.session.get('summary', {}) + shap_url = request.session.get('shap_url') + explain_type = request.session.get('explain_type') + mode = request.session.get('mode', 'test') + + if val_f1 is None and test_f1 is None: + return redirect('train_model') + + top_taxa_links = _extract_top_taxa(summary, k=5) + + return render(request, 'webapp/results.html', { + 'val_auc': val_auc, + 'val_f1': val_f1, + 'test_auc': test_auc, + 'test_f1': test_f1, + 'summary': summary, + 'shap_url': shap_url, + 'explain_type': explain_type, + 'mode': mode, + 'can_save': can_save, + 'top_taxa_links': top_taxa_links, #ncbi links + }) + + + +@login_required +def landing_page(request): + return render(request, 'webapp/landing_page.html') + +@require_GET +@login_required +def training_progress(request, run_id: str): + data = cache.get(f"train:{run_id}") or {"pct": 0, "msg": "Waiting"} + return JsonResponse(data) + +@login_required +def training_status(request, run_id: str): + # Simple page with a progress bar that polls training_progress + return render(request, "webapp/training_status.html", {"run_id": run_id}) + +@login_required +def training_done(request, run_id: str): + # Pull result from cache, stuff into session, then go to your existing results page + res = cache.get(f"train_result:{run_id}") + if not res: + # Not ready yet — bounce back to the status page + return redirect("training_status", run_id=run_id) + + # Safe to read keys now + ds_name = res.get('dataset_name') + if ds_name: + request.session['dataset_name'] = str(ds_name) + + _flt = lambda x: float(x) if x is not None else None + request.session['val_auc'] = _flt(res.get('val_auc')) + request.session['val_f1'] = _flt(res.get('val_f1')) + request.session['test_auc'] = _flt(res.get('test_auc')) + request.session['test_f1'] = _flt(res.get('test_f1')) + request.session['summary'] = res.get('summary', {}) + shap_relpath = res.get('shap_relpath') + request.session['shap_url'] = (settings.MEDIA_URL + shap_relpath) if shap_relpath else None + request.session['explain_type'] = request.session['summary'].get('explain_type') + request.session['mode'] = 'train' + + tmp_rel = res.get('tmp_model_relpath') + if tmp_rel: + request.session['tmp_model_relpath'] = tmp_rel + + return redirect('results') + + +@login_required +def test_model(request): + if request.user.is_staff or request.user.is_superuser: + # Admins see everything + your_models = SavedModel.objects.all().order_by('-created_at')[:100] + else: + # Regular users see only their models + your_models = SavedModel.objects.filter(owner=request.user).order_by('-created_at')[:50] + + public_models = SavedModel.objects.filter(public=True).order_by('-created_at')[:50] + + + if request.method == 'POST': + model_id = request.POST.get('saved_model_id') # <-- from hidden field + model_file = request.FILES.get('model_file') + test_data = request.FILES.get('test_data') + + # If “Use” was clicked and no upload provided, load the stored file + if model_id and not model_file: + sm = SavedModel.objects.filter( + Q(public=True) | Q(owner=request.user), pk=model_id + ).first() + if sm: + sm.file.open('rb') #open before passing along + model_file = sm.file + + if not model_file or not test_data: + return render( + request, 'webapp/test_model.html', + { + 'message': "Pick a model (file or sidebar) and upload test data.", + 'your_models': your_models, + 'public_models': public_models, + } + ) + + res = run_inference(model_file=model_file, test_file=test_data) + if res.error: + return render( + request, 'webapp/test_model.html', + {'message': res.error, 'your_models': your_models, 'public_models': public_models} + ) + + _flt = lambda x: float(x) if x is not None else None + request.session['val_auc'] = _flt(res.val_auc) + request.session['val_f1'] = _flt(res.val_f1) + request.session['test_auc'] = _flt(res.test_auc) + request.session['test_f1'] = _flt(res.test_f1) + request.session['shap_url'] = res.shap_url + request.session['explain_type']= res.explain_type + request.session['summary'] = res.summary or {} + request.session['mode'] = 'test' + return redirect('results') + + # GET + return render( + request, 'webapp/test_model.html', + {'your_models': your_models, 'public_models': public_models} + ) + +@require_POST +@login_required +def delete_saved_model(request): + model_id = request.POST.get("saved_model_id") + sm = SavedModel.objects.filter(pk=model_id).first() + if not sm: + messages.error(request, "Model not found.") + return redirect('test_model') + + is_owner = sm.owner_id == request.user.id + is_admin = request.user.is_staff or request.user.is_superuser # or just is_superuser + + if not (is_owner or is_admin): + messages.error(request, "You do not have permission to delete this model.") + return redirect('test_model') + + + # Delete file from storage, then DB row + try: + if sm.file: + sm.file.delete(save=False) + sm.delete() + messages.success(request, "Model deleted.") + except Exception as e: + messages.error(request, f"Failed to delete model: {e}") + + return redirect('test_model') + + +@require_POST +@login_required +def edit_saved_model(request): + model_id = request.POST.get("saved_model_id") + new_name = (request.POST.get("new_name") or "").strip() + new_public = request.POST.get("new_public") == "on" + new_description = (request.POST.get("new_description") or "").strip() + + if not model_id: + messages.error(request, "Missing model id.") + return redirect("test_model") + + sm = SavedModel.objects.filter(pk=model_id).first() + if not sm: + messages.error(request, "Model not found.") + return redirect("test_model") + + is_owner = sm.owner_id == request.user.id + is_admin_on_public = request.user.is_staff and sm.public + + if not (is_owner or is_admin_on_public): + messages.error(request, "You do not have permission to edit this model.") + return redirect("test_model") + + if not new_name: + messages.error(request, "Please provide a new name.") + return redirect("test_model") + + if len(new_name) > 120: + messages.error(request, "Name must be at most 120 characters.") + return redirect("test_model") + + try: + sm.name = new_name + sm.description = new_description[:2000] + # owners can change the public flag, admins cannot + if is_owner: + sm.public = new_public + sm.save(update_fields=["name", "description", "public"]) + messages.success(request, "Model updated.") + except Exception as e: + messages.error(request, f"Failed to edit model: {e}") + + return redirect("test_model") + +def _extract_top_taxa(summary: dict, k: int = 5): + """ + Try to find feature importance in the training summary and return the + top-k numeric features as NCBI taxonomy links. + Supports several possible shapes: + - dict: {'feature': score, ...} + - list[tuple]: [(feature, score), ...] + - list[dict]: [{'feature': '123', 'score': 0.12}, ...] + """ + if not isinstance(summary, dict): + return [] + + # Try a few common keys your pipeline might use + candidates = None + for key in ( + "perm_importance", # e.g. dict or list + "permutation_importance", + "feature_importance", + "shap_importance", + "shap_mean_abs", + ): + if key in summary: + candidates = summary[key] + break + if candidates is None: + return [] + + # Normalize to (feature, score) pairs + items = [] + if isinstance(candidates, dict): + items = list(candidates.items()) + elif isinstance(candidates, list): + if candidates and isinstance(candidates[0], dict): + # list of dicts like {'feature': '1305', 'score': 0.11} + for d in candidates: + f = d.get("feature") or d.get("name") + s = d.get("score") or d.get("importance") or d.get("value") + items.append((f, s)) + else: + # list of (feature, score) + items = [(a, b) for a, b in candidates] + else: + return [] + + # Keep only numeric features (likely taxonomy IDs) + # Keep only numeric features (likely taxonomy IDs) + cleaned = [] + for f, s in items: + if f is None: + continue + + fid_raw = str(f).strip() + # normalize names coming from ColumnTransformer / pipelines + fid = ( + fid_raw + .replace("num__", "").replace("cat__", "") + .replace("num_", "").replace("cat_", "") + ) + + # (optional) if you ever get "num__feature_123", keep the tail number: + # if not fid.isdigit() and "_" in fid: + # tail = fid.rsplit("_", 1)[-1] + # if tail.isdigit(): + # fid = tail + if fid.isdigit(): + try: + score = float(s) if s is not None else 0.0 + except Exception: + score = 0.0 + cleaned.append((fid, score)) + + + cleaned.sort(key=lambda x: x[1], reverse=True) + top = cleaned[:k] + + return [ + { + "id": fid, + "score": score, + "url": f"https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id={fid}", + } + for fid, score in top + ] + + + +def register_view(request): + if request.method == 'POST': + form = RegisterForm(request.POST) + if form.is_valid(): + form.save() + return redirect('login') + else: + form = RegisterForm() + return render(request, 'webapp/register.html', {'form': form}) + + +def login_view(request): + if request.method == 'POST': + form = AuthenticationForm(request, data=request.POST) + if form.is_valid(): + login(request, form.get_user()) + return redirect('landing_page') + else: + form = AuthenticationForm() + return render(request, 'webapp/login.html', {'form': form}) + + +def logout_view(request): + logout(request) + return redirect('login') + + +def _progress_cb_factory(run_id: str): + key = f"train:{run_id}" + def cb(pct: float, msg: str): + cache.set(key, {"pct": pct, "msg": msg}, timeout=60*60) + return cb + +# webapp/views.py + +def start_training(request): + if request.method == "POST": + run_id = uuid.uuid4().hex + cache.set(f"train:{run_id}", {"pct": 0, "msg": "Queued"}, 60*60) + + opts = TrainOptions( + scaler=request.POST.get("scaler", "standard"), + base_models=request.POST.getlist("base_models"), + ensemble_type=request.POST.get("ensemble_type", "none"), + meta_learner=request.POST.get("meta_learner") or None, + voting_type=request.POST.get("voting_type") or None, + balancing=request.POST.get("balancing_strategy", "none"), + augmentation=request.POST.get("augmentation", "none"), + target_samples=( + int(request.POST["target_samples"]) + if request.POST.get("target_samples", "").strip() else None + ), + ) + + # accept either 'dataset' (your form) or 'csv' (fallback) + f = request.FILES.get("dataset") or request.FILES.get("csv") + if not f: + return render(request, 'webapp/train_model.html', + {'form': UploadForm(), 'message': "Please upload a CSV file."}) + + request.session['dataset_name'] = f.name + csv_bytes = f.read() + + def worker(): + try: + progress_cb = _progress_cb_factory(run_id) + progress_cb(0, "Starting...") + result = train_dataset(io.BytesIO(csv_bytes), opts, save_to=None, progress_cb=progress_cb) + tmp_rel = os.path.join("tmp_models", f"{uuid.uuid4().hex}.joblib") + tmp_abs = os.path.join(settings.MEDIA_ROOT, tmp_rel) + os.makedirs(os.path.dirname(tmp_abs), exist_ok=True) + joblib.dump(result.artifact, tmp_abs) + cache.set(f"train:{run_id}", {"pct": 100, "msg": "Done", "done": True}, 60*60) + cache.set(f"train_result:{run_id}", { + "summary": result.summary, + "val_auc": result.val_auc, "val_f1": result.val_f1, + "test_auc": result.test_auc, "test_f1": result.test_f1, + "shap_relpath": result.shap_relpath, + "tmp_model_relpath": tmp_rel, + "dataset_name": f.name, + }, 60*60) + except Exception as e: + cache.set(f"train:{run_id}", {"pct": 100, "msg": f"Error: {e}", "error": True}, 60*60) + + threading.Thread(target=worker, daemon=True).start() + return redirect("training_status", run_id=run_id) + + return render(request, "upload_form.html")